diff --git a/Sources/SwiftBasicFormat/BasicFormat.swift b/Sources/SwiftBasicFormat/BasicFormat.swift index aed7bda76a2..bf732490310 100644 --- a/Sources/SwiftBasicFormat/BasicFormat.swift +++ b/Sources/SwiftBasicFormat/BasicFormat.swift @@ -293,6 +293,7 @@ open class BasicFormat: SyntaxRewriter { defer { self.previousToken = token } + let isInitialToken = self.previousToken == nil let previousToken = self.previousToken ?? token.previousToken(viewMode: viewMode) let nextToken = token.nextToken(viewMode: viewMode) @@ -393,7 +394,7 @@ open class BasicFormat: SyntaxRewriter { } } - if leadingTrivia.indentation(isOnNewline: previousTokenWillEndWithNewline) == [] { + if leadingTrivia.indentation(isOnNewline: isInitialToken || previousTokenWillEndWithNewline) == [] { // If the token starts on a new line and does not have indentation, this // is the last non-indented token. Store its indentation level anchorPoints[token] = currentIndentationLevel diff --git a/Tests/SwiftBasicFormatTest/BasicFormatTests.swift b/Tests/SwiftBasicFormatTest/BasicFormatTests.swift index c815d9b960e..6128eae4a20 100644 --- a/Tests/SwiftBasicFormatTest/BasicFormatTests.swift +++ b/Tests/SwiftBasicFormatTest/BasicFormatTests.swift @@ -341,4 +341,43 @@ final class BasicFormatTest: XCTestCase { """ ) } + + func testSubTreeNode() { + let decl: DeclSyntax = """ + func test() { + print(1) + } + """ + let body = decl.cast(FunctionDeclSyntax.self).body! + + assertFormatted( + source: body.formatted().description, + expected: """ + { + print(1) + } + """ + ) + } + + func testSubTreeNodeWithIndentedParentNode() { + let decl: DeclSyntax = """ + struct X { + func test() { + print(1) + } + } + """ + + let body = decl.cast(StructDeclSyntax.self).memberBlock.members.first!.decl.cast(FunctionDeclSyntax.self).body! + + assertFormatted( + source: body.formatted().description, + expected: """ + { + print(1) + } + """ + ) + } }