Skip to content

Commit a32bdbf

Browse files
authored
Merge pull request #2829 from mateusrodriguesxyz/code-block-builder-add-build-final-result
Add `buildFinalResult` to `CodeBlockItemListBuilder` to ensure newline between expressions
2 parents 51eb17a + 95f5aa6 commit a32bdbf

File tree

3 files changed

+50
-1
lines changed

3 files changed

+50
-1
lines changed

Sources/SwiftSyntaxBuilder/ResultBuilderExtensions.swift

+12
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,18 @@ extension CodeBlockItemListBuilder {
4040
public static func buildExpression(_ expression: some Sequence<DeclSyntaxProtocol>) -> Component {
4141
buildExpression(expression.map { CodeBlockItemSyntax(item: .decl(DeclSyntax($0))) })
4242
}
43+
44+
public static func buildFinalResult(_ component: Component) -> CodeBlockItemListSyntax {
45+
.init(
46+
component.enumerated().map { (index, expression) in
47+
if index > component.startIndex, !expression.leadingTrivia.contains(where: \.isNewline) {
48+
return expression.with(\.leadingTrivia, .newline.merging(expression.leadingTrivia))
49+
} else {
50+
return expression
51+
}
52+
}
53+
)
54+
}
4355
}
4456

4557
extension ConditionElementListBuilder {

Sources/SwiftSyntaxMacroExpansion/MacroExpansion.swift

+11-1
Original file line numberDiff line numberDiff line change
@@ -528,5 +528,15 @@ public func collapse<Node: SyntaxProtocol>(
528528
break
529529
}
530530

531-
return expansions.joined(separator: separator)
531+
// Join the expansions ensuring `separator` between them.
532+
var collapsed = ""
533+
for expansion in expansions {
534+
if collapsed.isEmpty || expansion.hasPrefix(separator) {
535+
collapsed.append(expansion)
536+
} else {
537+
collapsed.append(separator + expansion)
538+
}
539+
}
540+
541+
return collapsed
532542
}

Tests/SwiftSyntaxBuilderTest/CollectionNodeFlatteningTests.swift

+27
Original file line numberDiff line numberDiff line change
@@ -75,4 +75,31 @@ final class CollectionNodeFlatteningTests: XCTestCase {
7575
"""
7676
)
7777
}
78+
79+
func test_FlattenCodeBlockItemListWithCodeBlockInterpolated() {
80+
let block = CodeBlockItemListSyntax {
81+
"let a = 1"
82+
"let b = 2"
83+
"let c = 3"
84+
}
85+
86+
let buildable = CodeBlockItemListSyntax {
87+
"let one = object.methodOne()"
88+
"let two = object.methodTwo()"
89+
"let three = {\(block)}()"
90+
}
91+
92+
assertBuildResult(
93+
buildable,
94+
"""
95+
let one = object.methodOne()
96+
let two = object.methodTwo()
97+
let three = {
98+
let a = 1
99+
let b = 2
100+
let c = 3
101+
}()
102+
"""
103+
)
104+
}
78105
}

0 commit comments

Comments
 (0)