Skip to content

Commit 93eb479

Browse files
authored
Merge pull request #1264 from kimdv/kimdv/add-node-with-body-to-variable-decl
2 parents 0283ae6 + fb05e95 commit 93eb479

File tree

2 files changed

+44
-15
lines changed

2 files changed

+44
-15
lines changed

Sources/SwiftSyntaxBuilder/SyntaxNodeWithBody.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,3 +123,17 @@ public extension SwitchStmtSyntax {
123123
self.cases = casesBuilder()
124124
}
125125
}
126+
127+
// MARK: - VariableDeclSyntax
128+
// VariableDeclSyntax is a special scenario as it don't have body or members
129+
// So we cannot conform to `HasTrailingCodeBlock` or `HasTrailingMemberDeclBlock`
130+
131+
public extension VariableDeclSyntax {
132+
init(_ signature: PartialSyntaxNodeString, @CodeBlockItemListBuilder accessor: () -> CodeBlockItemListSyntax) {
133+
self = "\(signature) {}"
134+
assert(self.bindings.count == 1)
135+
var binding: PatternBindingSyntax? = self.bindings.last
136+
binding?.accessor = .getter(CodeBlockSyntax(statements: accessor()))
137+
bindings = PatternBindingListSyntax([binding].compactMap { $0 })
138+
}
139+
}

Tests/SwiftSyntaxBuilderTest/VariableTests.swift

Lines changed: 30 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -175,22 +175,37 @@ final class VariableTests: XCTestCase {
175175
}
176176

177177
func testComputedProperty() {
178-
let buildable = VariableDeclSyntax(name: "test", type: TypeAnnotationSyntax(type: TypeSyntax("Int"))) {
179-
SequenceExprSyntax {
180-
IntegerLiteralExprSyntax(4)
181-
BinaryOperatorExprSyntax(text: "+")
182-
IntegerLiteralExprSyntax(5)
183-
}
184-
}
178+
let testCases: [UInt: (VariableDeclSyntax, String)] = [
179+
#line: (
180+
VariableDeclSyntax(name: "test", type: TypeAnnotationSyntax(type: TypeSyntax("Int"))) {
181+
SequenceExprSyntax {
182+
IntegerLiteralExprSyntax(4)
183+
BinaryOperatorExprSyntax(text: "+")
184+
IntegerLiteralExprSyntax(5)
185+
}
186+
},
187+
"""
188+
var test: Int {
189+
4 + 5
190+
}
191+
"""
192+
),
193+
#line: (
194+
VariableDeclSyntax("var foo: String") {
195+
ReturnStmtSyntax(#"return "hello world""#)
196+
},
197+
"""
198+
var foo: String {
199+
return "hello world"
200+
}
201+
"""
202+
),
203+
]
185204

186-
AssertBuildResult(
187-
buildable,
188-
"""
189-
var test: Int {
190-
4 + 5
191-
}
192-
"""
193-
)
205+
for (line, testCase) in testCases {
206+
let (builder, expected) = testCase
207+
AssertBuildResult(builder, expected, line: line)
208+
}
194209
}
195210

196211
func testAccessorList() {

0 commit comments

Comments
 (0)