Repository: swiftlang/swift-syntax (swift)

Issue:
Extraneous indentation if the formatted node has parents
The following new test case fails

```swift
let decl: DeclSyntax = """
  func test() {
    print(1)
  }
"""

let body = decl.cast(FunctionDeclSyntax.self).body!

let expectedFormatted = """
  {
      print(1)
    }
  """

assertStringsEqualWithDiff(body.formatted().description, expectedFormatted) // fails: `print` is indented by 8 spaces
assertStringsEqualWithDiff(body.detach().formatted().description, expectedFormatted) // passes
```

For some reason we are adding 8 spaces in front of `print` if `body` is not detached.

Pull request description:
Resolves #1744

Patch:
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


Test patch:
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)
+            }
+        """
+    )
+  }
 }