Repository: apple/swift-syntax (swift)

Issue:
TryExpr with questionOrExclamationMark does not build correct syntax.
### Description

In case of TryExpr with `questionOrExclamationMark`,  `SwiftSyntaxBuilder` should build syntax:  `try! a.b()` instead of `try !a.b()`

### Steps to Reproduce

Add  `questionOrExclamationMark` DoStmtTests:
```swift
let buildable = DoStmt(
      body: CodeBlock(statementsBuilder: {
          CodeBlockItem(item: TryExpr(questionOrExclamationMark: .exclamationMark, expression: FunctionCallExpr(MemberAccessExpr(base: "a", name: "b"))))
      }),
      catchClauses: [
        CatchClause(CatchItemList {
          CatchItem(pattern: "Error1")
          CatchItem(pattern: "Error2")
        }) {
          FunctionCallExpr("print") {
            TupleExprElement(expression: StringLiteralExpr("Known error"))
          }
        },
        CatchClause(CatchItemList {
          CatchItem(
            pattern: "Error3", whereClause: WhereClause(guardResult: MemberAccessExpr(base: "error", name: "isError4")))
        }) {
          ThrowStmt(expression: MemberAccessExpr(base: "Error4", name: "error3"))
        },
        CatchClause {
          FunctionCallExpr("print") {
            TupleExprElement(expression: "error")
          }
        }
      ])
```

Pull request:
This fixes so we don't get `var newLayout: ContiguousArray < RawSyntax ? > ?`when doing `VariableDecl("var newLayout: ContiguousArray<RawSyntax?>?")`.

If you can think of other test cases that I nee to add, to ensure we have expected behaviour different places feel free to comment then.

this PR also fixes #853

Patch:
diff --git a/CodeGeneration/Sources/SyntaxSupport/gyb_generated/TokenSpec.swift b/CodeGeneration/Sources/SyntaxSupport/gyb_generated/TokenSpec.swift
index 5346a700e83..e4c16e53f93 100644
--- a/CodeGeneration/Sources/SyntaxSupport/gyb_generated/TokenSpec.swift
+++ b/CodeGeneration/Sources/SyntaxSupport/gyb_generated/TokenSpec.swift
@@ -261,8 +261,8 @@ public let SYNTAX_TOKENS: [TokenSpec] = [
   PunctuatorSpec(name: "RightBrace", kind: "r_brace", text: "}"),
   PunctuatorSpec(name: "LeftSquareBracket", kind: "l_square", text: "["),
   PunctuatorSpec(name: "RightSquareBracket", kind: "r_square", text: "]"),
-  PunctuatorSpec(name: "LeftAngle", kind: "l_angle", text: "<", requiresLeadingSpace: true, requiresTrailingSpace: true),
-  PunctuatorSpec(name: "RightAngle", kind: "r_angle", text: ">", requiresLeadingSpace: true, requiresTrailingSpace: true),
+  PunctuatorSpec(name: "LeftAngle", kind: "l_angle", text: "<"),
+  PunctuatorSpec(name: "RightAngle", kind: "r_angle", text: ">"),
   PunctuatorSpec(name: "Period", kind: "period", text: "."),
   PunctuatorSpec(name: "Comma", kind: "comma", text: ",", requiresTrailingSpace: true),
   PunctuatorSpec(name: "Ellipsis", kind: "ellipsis", text: "..."),
@@ -275,8 +275,8 @@ public let SYNTAX_TOKENS: [TokenSpec] = [
   PunctuatorSpec(name: "Arrow", kind: "arrow", text: "->", requiresLeadingSpace: true, requiresTrailingSpace: true),
   PunctuatorSpec(name: "Backtick", kind: "backtick", text: "`"),
   PunctuatorSpec(name: "Backslash", kind: "backslash", text: "\\"),
-  PunctuatorSpec(name: "ExclamationMark", kind: "exclaim_postfix", text: "!"),
-  PunctuatorSpec(name: "PostfixQuestionMark", kind: "question_postfix", text: "?"),
+  PunctuatorSpec(name: "ExclamationMark", kind: "exclaim_postfix", text: "!", requiresTrailingSpace: true),
+  PunctuatorSpec(name: "PostfixQuestionMark", kind: "question_postfix", text: "?", requiresTrailingSpace: true),
   PunctuatorSpec(name: "InfixQuestionMark", kind: "question_infix", text: "?"),
   PunctuatorSpec(name: "StringQuote", kind: "string_quote", text: "\"", classification: "StringLiteral"),
   PunctuatorSpec(name: "SingleQuote", kind: "single_quote", text: "\'", classification: "StringLiteral"),
diff --git a/CodeGeneration/Sources/generate-swiftsyntax/templates/basicformat/BasicFormatFile.swift b/CodeGeneration/Sources/generate-swiftsyntax/templates/basicformat/BasicFormatFile.swift
index a024fa99bf6..54462cdb35b 100644
--- a/CodeGeneration/Sources/generate-swiftsyntax/templates/basicformat/BasicFormatFile.swift
+++ b/CodeGeneration/Sources/generate-swiftsyntax/templates/basicformat/BasicFormatFile.swift
@@ -122,6 +122,15 @@ let basicFormatFile = SourceFile {
     }
 
     FunctionDecl("open func requiresLeadingSpace(_ token: TokenSyntax) -> Bool") {
+      SwitchStmt("""
+        switch (token.previousToken(viewMode: .sourceAccurate)?.tokenKind, token.tokenKind) {
+        case (.leftParen, .spacedBinaryOperator):
+          return false
+        default:
+          break
+        }
+        """)
+      
       SwitchStmt(expression: Expr("token.tokenKind")) {
         for token in SYNTAX_TOKENS {
           if token.requiresLeadingSpace {
@@ -146,12 +155,19 @@ let basicFormatFile = SourceFile {
 
       SwitchStmt("""
         switch (token.tokenKind, token.nextToken(viewMode: .sourceAccurate)?.tokenKind) {
-        case (.asKeyword, .exclamationMark),
-             (.asKeyword, .postfixQuestionMark),
-             (.initKeyword, .leftParen),
-             (.initKeyword, .postfixQuestionMark),
-             (.tryKeyword, .exclamationMark),
-             (.tryKeyword, .postfixQuestionMark):
+        case (.asKeyword, .exclamationMark), // Ensures there is not space in `as!`
+             (.asKeyword, .postfixQuestionMark), // Ensures there is not space in `as?`
+             (.exclamationMark, .leftParen), // Ensures there is not space in `myOptionalClosure!()`
+             (.exclamationMark, .period), // Ensures there is not space in `myOptionalBar!.foo()`
+             (.initKeyword, .leftParen), // Ensures there is not space in `init()`
+             (.initKeyword, .postfixQuestionMark), // Ensures there is not space in `init?`
+             (.postfixQuestionMark, .leftParen), // Ensures there is not space in `init?()`
+             (.postfixQuestionMark, .rightAngle), // Ensures there is not space in `ContiguousArray<RawSyntax?>`
+             (.postfixQuestionMark, .rightParen), // Ensures there is not space in `myOptionalClosure?()`
+             (.tryKeyword, .exclamationMark), // Ensures there is not space in `try!`
+             (.tryKeyword, .postfixQuestionMark): // Ensures there is not space in `try?`
+          return false
+        case (.spacedBinaryOperator, .comma):
           return false
         default:
           break
diff --git a/Sources/SwiftBasicFormat/generated/BasicFormat.swift b/Sources/SwiftBasicFormat/generated/BasicFormat.swift
index 7f48a6457b3..41b5df7a897 100644
--- a/Sources/SwiftBasicFormat/generated/BasicFormat.swift
+++ b/Sources/SwiftBasicFormat/generated/BasicFormat.swift
@@ -130,6 +130,12 @@ open class BasicFormat: SyntaxRewriter {
   }
   
   open func requiresLeadingSpace(_ token: TokenSyntax) -> Bool {
+    switch (token.previousToken(viewMode: .sourceAccurate)?.tokenKind, token.tokenKind) {
+    case (.leftParen, .spacedBinaryOperator): 
+      return false
+    default: 
+      break 
+    }
     switch token.tokenKind {
     case .inKeyword: 
       return true
@@ -139,10 +145,6 @@ open class BasicFormat: SyntaxRewriter {
       return true
     case .leftBrace: 
       return true
-    case .leftAngle: 
-      return true
-    case .rightAngle: 
-      return true
     case .equal: 
       return true
     case .arrow: 
@@ -160,12 +162,19 @@ open class BasicFormat: SyntaxRewriter {
       return false
     }
     switch (token.tokenKind, token.nextToken(viewMode: .sourceAccurate)?.tokenKind) {
-    case (.asKeyword, .exclamationMark), 
-     (.asKeyword, .postfixQuestionMark), 
-     (.initKeyword, .leftParen), 
-     (.initKeyword, .postfixQuestionMark), 
-     (.tryKeyword, .exclamationMark), 
-     (.tryKeyword, .postfixQuestionMark): 
+    case (.asKeyword, .exclamationMark), // Ensures there is not space in `as!`
+     (.asKeyword, .postfixQuestionMark), // Ensures there is not space in `as?`
+     (.exclamationMark, .leftParen), // Ensures there is not space in `myOptionalClosure!()`
+     (.exclamationMark, .period), // Ensures there is not space in `myOptionalBar!.foo()`
+     (.initKeyword, .leftParen), // Ensures there is not space in `init()`
+     (.initKeyword, .postfixQuestionMark), // Ensures there is not space in `init?`
+     (.postfixQuestionMark, .leftParen), // Ensures there is not space in `init?()`
+     (.postfixQuestionMark, .rightAngle), // Ensures there is not space in `ContiguousArray<RawSyntax?>`
+     (.postfixQuestionMark, .rightParen), // Ensures there is not space in `myOptionalClosure?()`
+     (.tryKeyword, .exclamationMark), // Ensures there is not space in `try!`
+     (.tryKeyword, .postfixQuestionMark): // Ensures there is not space in `try?`
+      return false
+    case (.spacedBinaryOperator, .comma): 
       return false
     default: 
       break 
@@ -261,10 +270,6 @@ open class BasicFormat: SyntaxRewriter {
       return true
     case .wildcardKeyword: 
       return true
-    case .leftAngle: 
-      return true
-    case .rightAngle: 
-      return true
     case .comma: 
       return true
     case .colon: 
@@ -273,6 +278,10 @@ open class BasicFormat: SyntaxRewriter {
       return true
     case .arrow: 
       return true
+    case .exclamationMark: 
+      return true
+    case .postfixQuestionMark: 
+      return true
     case .poundKeyPathKeyword: 
       return true
     case .poundLineKeyword: 
diff --git a/Sources/SwiftSyntax/gyb_generated/SyntaxFactory.swift b/Sources/SwiftSyntax/gyb_generated/SyntaxFactory.swift
index e7562e94348..56578767bce 100644
--- a/Sources/SwiftSyntax/gyb_generated/SyntaxFactory.swift
+++ b/Sources/SwiftSyntax/gyb_generated/SyntaxFactory.swift
@@ -9039,8 +9039,8 @@ public enum SyntaxFactory {
   }
   @available(*, deprecated, message: "Use TokenSyntax.leftAngleToken instead")
   public static func makeLeftAngleToken(
-    leadingTrivia: Trivia = .space,
-    trailingTrivia: Trivia = .space
+    leadingTrivia: Trivia = [],
+    trailingTrivia: Trivia = []
   ) -> TokenSyntax {
     return makeToken(.leftAngle, presence: .present,
                      leadingTrivia: leadingTrivia,
@@ -9048,8 +9048,8 @@ public enum SyntaxFactory {
   }
   @available(*, deprecated, message: "Use TokenSyntax.rightAngleToken instead")
   public static func makeRightAngleToken(
-    leadingTrivia: Trivia = .space,
-    trailingTrivia: Trivia = .space
+    leadingTrivia: Trivia = [],
+    trailingTrivia: Trivia = []
   ) -> TokenSyntax {
     return makeToken(.rightAngle, presence: .present,
                      leadingTrivia: leadingTrivia,
@@ -9166,7 +9166,7 @@ public enum SyntaxFactory {
   @available(*, deprecated, message: "Use TokenSyntax.exclamationMarkToken instead")
   public static func makeExclamationMarkToken(
     leadingTrivia: Trivia = [],
-    trailingTrivia: Trivia = []
+    trailingTrivia: Trivia = .space
   ) -> TokenSyntax {
     return makeToken(.exclamationMark, presence: .present,
                      leadingTrivia: leadingTrivia,
@@ -9175,7 +9175,7 @@ public enum SyntaxFactory {
   @available(*, deprecated, message: "Use TokenSyntax.postfixQuestionMarkToken instead")
   public static func makePostfixQuestionMarkToken(
     leadingTrivia: Trivia = [],
-    trailingTrivia: Trivia = []
+    trailingTrivia: Trivia = .space
   ) -> TokenSyntax {
     return makeToken(.postfixQuestionMark, presence: .present,
                      leadingTrivia: leadingTrivia,
diff --git a/gyb_syntax_support/Token.py b/gyb_syntax_support/Token.py
index 03d6909ba07..41c326c249d 100644
--- a/gyb_syntax_support/Token.py
+++ b/gyb_syntax_support/Token.py
@@ -254,10 +254,8 @@ def macro_name(self):
     Punctuator('RightBrace', 'r_brace', text='}'),
     Punctuator('LeftSquareBracket', 'l_square', text='['),
     Punctuator('RightSquareBracket', 'r_square', text=']'),
-    Punctuator('LeftAngle', 'l_angle', text='<', requires_leading_space=True,
-               requires_trailing_space=True),
-    Punctuator('RightAngle', 'r_angle', text='>', requires_leading_space=True,
-               requires_trailing_space=True),
+    Punctuator('LeftAngle', 'l_angle', text='<'),
+    Punctuator('RightAngle', 'r_angle', text='>'),
 
     Punctuator('Period', 'period', text='.'),
     Punctuator('Comma', 'comma', text=',', requires_trailing_space=True),
@@ -277,9 +275,11 @@ def macro_name(self):
 
     Punctuator('Backslash', 'backslash', text='\\\\'),
 
-    Punctuator('ExclamationMark', 'exclaim_postfix', text='!'),
+    Punctuator('ExclamationMark', 'exclaim_postfix', text='!',
+               requires_trailing_space=True),
 
-    Punctuator('PostfixQuestionMark', 'question_postfix', text='?'),
+    Punctuator('PostfixQuestionMark', 'question_postfix', text='?',
+               requires_trailing_space=True),
     Punctuator('InfixQuestionMark', 'question_infix', text='?'),
 
     Punctuator('StringQuote', 'string_quote', text='\\\"',


Test patch:
diff --git a/Tests/SwiftSyntaxBuilderTest/DoStmtTests.swift b/Tests/SwiftSyntaxBuilderTest/DoStmtTests.swift
index e0372a0e9b0..688a5fa23ec 100644
--- a/Tests/SwiftSyntaxBuilderTest/DoStmtTests.swift
+++ b/Tests/SwiftSyntaxBuilderTest/DoStmtTests.swift
@@ -64,4 +64,104 @@ final class DoStmtTests: XCTestCase {
       """
     )
   }
+
+  func testDoStmtWithExclamationMark() {
+    let buildable = DoStmt(
+      body: CodeBlock(statementsBuilder: {
+        TryExpr(questionOrExclamationMark: .exclamationMark, expression: FunctionCallExpr(callee: ExprSyntax("a.b")))
+      }),
+      catchClauses: [
+        CatchClause(
+          CatchItemList {
+            CatchItem(pattern: PatternSyntax("Error1"))
+            CatchItem(pattern: PatternSyntax("Error2"))
+          }
+        ) {
+          FunctionCallExpr(callee: ExprSyntax("print")) {
+            TupleExprElement(expression: StringLiteralExpr(content: "Known error"))
+          }
+        },
+        CatchClause(
+          CatchItemList {
+            CatchItem(
+              pattern: PatternSyntax("Error3"),
+              whereClause: WhereClause(guardResult: MemberAccessExpr(base: "error", name: "isError4"))
+            )
+          }
+        ) {
+          ThrowStmt(expression: MemberAccessExpr(base: "Error4", name: "error3"))
+        },
+        CatchClause {
+          FunctionCallExprSyntax(callee: ExprSyntax("print")) {
+            TupleExprElementSyntax(expression: Expr("error"))
+          }
+        },
+      ]
+    )
+
+    AssertBuildResult(
+      buildable,
+      """
+      do {
+          try! a.b()
+      } catch Error1, Error2 {
+          print("Known error")
+      } catch Error3 where error.isError4 {
+          throw Error4.error3
+      } catch {
+          print(error)
+      }
+      """
+    )
+  }
+
+  func testDoStmtWithPostfixQuestionMark() {
+    let buildable = DoStmt(
+      body: CodeBlock(statementsBuilder: {
+        TryExpr(questionOrExclamationMark: .postfixQuestionMark, expression: FunctionCallExpr(callee: ExprSyntax("a.b")))
+      }),
+      catchClauses: [
+        CatchClause(
+          CatchItemList {
+            CatchItem(pattern: PatternSyntax("Error1"))
+            CatchItem(pattern: PatternSyntax("Error2"))
+          }
+        ) {
+          FunctionCallExpr(callee: ExprSyntax("print")) {
+            TupleExprElement(expression: StringLiteralExpr(content: "Known error"))
+          }
+        },
+        CatchClause(
+          CatchItemList {
+            CatchItem(
+              pattern: PatternSyntax("Error3"),
+              whereClause: WhereClause(guardResult: MemberAccessExpr(base: "error", name: "isError4"))
+            )
+          }
+        ) {
+          ThrowStmt(expression: MemberAccessExpr(base: "Error4", name: "error3"))
+        },
+        CatchClause {
+          FunctionCallExprSyntax(callee: ExprSyntax("print")) {
+            TupleExprElementSyntax(expression: Expr("error"))
+          }
+        },
+      ]
+    )
+
+    AssertBuildResult(
+      buildable,
+      """
+      do {
+          try? a.b()
+      } catch Error1, Error2 {
+          print("Known error")
+      } catch Error3 where error.isError4 {
+          throw Error4.error3
+      } catch {
+          print(error)
+      }
+      """
+    )
+  }
 }
diff --git a/Tests/SwiftSyntaxBuilderTest/FunctionTests.swift b/Tests/SwiftSyntaxBuilderTest/FunctionTests.swift
index ccc5728e5ac..7386217c485 100644
--- a/Tests/SwiftSyntaxBuilderTest/FunctionTests.swift
+++ b/Tests/SwiftSyntaxBuilderTest/FunctionTests.swift
@@ -37,6 +37,196 @@ final class FunctionTests: XCTestCase {
     )
   }
 
+  func testFunctionDeclEnsurePropperSpacing() {
+    let testCases: [UInt: (FunctionDecl, String)] = [
+      #line: (
+        FunctionDecl(
+          """
+          @available(*, deprecated, message: "Use function on Baz")
+          private func visitChildren<SyntaxType: SyntaxProtocol>(_ node: SyntaxType) {
+          }
+          """
+        ),
+        """
+        @available(*, deprecated, message: "Use function on Baz")
+        private func visitChildren<SyntaxType: SyntaxProtocol>(_ node: SyntaxType) {
+        }
+        """
+      ),
+      #line: (
+        FunctionDecl(
+          """
+          public static func == (lhs: String, rhs: String) -> Bool {
+            return lhs < rhs
+          }
+          """
+        ),
+        """
+        public static func == (lhs: String, rhs: String) -> Bool {
+            return lhs < rhs
+        }
+        """
+      ),
+      #line: (
+        FunctionDecl(
+          """
+          public static func == (lhs: String, rhs: String) -> Bool {
+            return lhs > rhs
+          }
+          """
+        ),
+        """
+        public static func == (lhs: String, rhs: String) -> Bool {
+            return lhs > rhs
+        }
+        """
+      ),
+      #line: (
+        FunctionDecl(
+          """
+          public static func == (lhs1: String, lhs2: String, rhs1: String, rhs2: String) -> Bool {
+            return (lhs1, lhs2) > (rhs1, rhs2)
+          }
+          """
+        ),
+        """
+        public static func == (lhs1: String, lhs2: String, rhs1: String, rhs2: String) -> Bool {
+            return (lhs1, lhs2) > (rhs1, rhs2)
+        }
+        """
+      ),
+      #line: (
+        FunctionDecl(
+          """
+          public func foo<Generic>(input: Bas) -> Foo<Generic> {
+            return input as Foo<Generic>!
+          }
+          """
+        ),
+        """
+        public func foo<Generic>(input: Bas) -> Foo<Generic> {
+            return input as Foo<Generic>!
+        }
+        """
+      ),
+      #line: (
+        FunctionDecl(
+          """
+          public func foo<Generic>(input: Bas) -> Foo<Generic?> {
+            return input as Foo<Generic?>!
+          }
+          """
+        ),
+        """
+        public func foo<Generic>(input: Bas) -> Foo<Generic?> {
+            return input as Foo<Generic?>!
+        }
+        """
+      ),
+      #line: (
+        FunctionDecl(
+          """
+          public func foo<Generic>(input: [Bar]) -> Foo<[Bar]> {
+            return input
+          }
+          """
+        ),
+        """
+        public func foo<Generic>(input: [Bar]) -> Foo<[Bar]> {
+            return input
+        }
+        """
+      ),
+      #line: (
+        FunctionDecl(
+          """
+          public func foo(myOptionalClosure: MyClosure?)  {
+            myOptionalClosure!()
+          }
+          """
+        ),
+        """
+        public func foo(myOptionalClosure: MyClosure?)  {
+            myOptionalClosure!()
+        }
+        """
+      ),
+      #line: (
+        FunctionDeclSyntax(
+          modifiers: [DeclModifier(name: .public), DeclModifier(name: .static)],
+          identifier: Token.identifier("=="),
+          signature: FunctionSignatureSyntax(
+            input: ParameterClauseSyntax(
+              parameterList: FunctionParameterListSyntax {
+                FunctionParameterSyntax(firstName: TokenSyntax.identifier("lhs"), colon: .colon, type: SimpleTypeIdentifier("String"))
+                FunctionParameterSyntax(firstName: TokenSyntax.identifier("rhs"), colon: .colon, type: SimpleTypeIdentifier("String"))
+              }
+            ),
+            output: ReturnClauseSyntax(
+              returnType: SimpleTypeIdentifier(name: TokenSyntax.identifier("Bool"))
+            )
+          ),
+          bodyBuilder: {
+            ReturnStmt(
+              expression: SequenceExpr(
+                elements: ExprListSyntax {
+                  IdentifierExprSyntax(identifier: .identifier("lhs"))
+                  BinaryOperatorExprSyntax(operatorToken: .spacedBinaryOperator("<"))
+                  IdentifierExprSyntax(identifier: .identifier("rhs"))
+                }
+              )
+            )
+          }
+        ),
+        """
+        public static func ==(lhs: String, rhs: String) -> Bool {
+            return lhs < rhs
+        }
+        """
+      ),
+      #line: (
+        FunctionDeclSyntax(
+          modifiers: [DeclModifierSyntax(name: .public), DeclModifierSyntax(name: .static)],
+          identifier: Token.identifier("=="),
+          signature: FunctionSignatureSyntax(
+            input: ParameterClauseSyntax(
+              parameterList: FunctionParameterListSyntax {
+                FunctionParameterSyntax(firstName: TokenSyntax.identifier("lhs1"), colon: .colon, type: SimpleTypeIdentifierSyntax("String"))
+                FunctionParameterSyntax(firstName: TokenSyntax.identifier("lhs2"), colon: .colon, type: SimpleTypeIdentifierSyntax("String"))
+                FunctionParameterSyntax(firstName: TokenSyntax.identifier("rhs1"), colon: .colon, type: SimpleTypeIdentifierSyntax("String"))
+                FunctionParameterSyntax(firstName: TokenSyntax.identifier("rhs2"), colon: .colon, type: SimpleTypeIdentifierSyntax("String"))
+              }
+            ),
+            output: ReturnClauseSyntax(
+              returnType: SimpleTypeIdentifierSyntax(name: TokenSyntax.identifier("Bool"))
+            )
+          ),
+          bodyBuilder: {
+            ReturnStmt(
+              expression: SequenceExprSyntax(
+                elements: ExprListSyntax {
+                  ExprSyntax("(lhs1, lhs2)")
+                  BinaryOperatorExprSyntax(operatorToken: .spacedBinaryOperator("<"))
+                  ExprSyntax("(rhs1, rhs2)")
+                }
+              )
+            )
+          }
+        ),
+        """
+        public static func ==(lhs1: String, lhs2: String, rhs1: String, rhs2: String) -> Bool {
+            return (lhs1, lhs2) < (rhs1, rhs2)
+        }
+        """
+      ),
+    ]
+
+    for (line, testCase) in testCases {
+      let (builder, expected) = testCase
+      AssertBuildResult(builder, expected, line: line)
+    }
+  }
+
   func testArguments() {
     let buildable = FunctionCallExpr(callee: ExprSyntax("test")) {
       for param in (1...5) {
diff --git a/Tests/SwiftSyntaxBuilderTest/IfStmtTests.swift b/Tests/SwiftSyntaxBuilderTest/IfStmtTests.swift
index 1a5ea5601c0..d6eed3085dc 100644
--- a/Tests/SwiftSyntaxBuilderTest/IfStmtTests.swift
+++ b/Tests/SwiftSyntaxBuilderTest/IfStmtTests.swift
@@ -85,6 +85,35 @@ final class IfStmtTests: XCTestCase {
     }
   }
 
+  func testIfStmtSpacing() {
+    let testCases: [UInt: (IfStmt, String)] = [
+      #line: (
+        IfStmt(conditions: ConditionElementList { Expr("!(true)") }) {},
+        """
+        if !(true) {
+        }
+        """
+      ),
+      #line: (
+        IfStmt(
+          """
+          if !(false) {
+          }
+          """
+        ),
+        """
+        if !(false) {
+        }
+        """
+      ),
+    ]
+
+    for (line, testCase) in testCases {
+      let (builder, expected) = testCase
+      AssertBuildResult(builder, expected, line: line)
+    }
+  }
+
   func testIfElseStmt() {
     // Use the convenience initializer from IfStmtConvenienceInitializers
     // with an else branch expressed by a second trailing closure.
diff --git a/Tests/SwiftSyntaxBuilderTest/StructTests.swift b/Tests/SwiftSyntaxBuilderTest/StructTests.swift
index e7e8014e7ef..d779e004cbb 100644
--- a/Tests/SwiftSyntaxBuilderTest/StructTests.swift
+++ b/Tests/SwiftSyntaxBuilderTest/StructTests.swift
@@ -69,7 +69,7 @@ final class StructTests: XCTestCase {
       public struct TestStruct {
           /// A nested struct
           /// with multi line comment
-          struct NestedStruct < A, B: C, D > where A: X, A.P == D {
+          struct NestedStruct<A, B: C, D> where A: X, A.P == D {
           }
           /// A nested struct\r\
           /// with multi line comment where the newline is a CR\r\
diff --git a/Tests/SwiftSyntaxBuilderTest/VariableTests.swift b/Tests/SwiftSyntaxBuilderTest/VariableTests.swift
index 767b694c55c..04be416490b 100644
--- a/Tests/SwiftSyntaxBuilderTest/VariableTests.swift
+++ b/Tests/SwiftSyntaxBuilderTest/VariableTests.swift
@@ -25,7 +25,7 @@ final class VariableTests: XCTestCase {
     AssertBuildResult(buildable, "␣let a: [Int]")
   }
 
-  func testVariableDeclWithTry() {
+  func testVariableDeclWithStringParsing() {
     let testCases: [UInt: (VariableDecl, String)] = [
       #line: (
         VariableDecl("let content = try? String(contentsOf: url)"),
@@ -35,6 +35,18 @@ final class VariableTests: XCTestCase {
         VariableDecl("let content = try! String(contentsOf: url)"),
         "let content = try! String(contentsOf: url)"
       ),
+      #line: (
+        VariableDecl("var newLayout: ContiguousArray<RawSyntax?>?"),
+        "var newLayout: ContiguousArray<RawSyntax?>?"
+      ),
+      #line: (
+        VariableDecl("var foo: String { myOptional!.someProperty }"),
+        """
+        var foo: String {
+            myOptional!.someProperty
+        }
+        """
+      ),
     ]
 
     for (line, testCase) in testCases {