Skip to content

Commit 1a2dbea

Browse files
authored
Merge pull request #1261 from kimdv/kimdv/add-node-with-body-to-switch
Add init with `PartialSyntaxNodeString` on `SwitchStmtSyntax`
2 parents 917f3b9 + af652c9 commit 1a2dbea

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

Sources/SwiftSyntaxBuilder/SyntaxNodeWithBody.swift

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ extension ExtensionDeclSyntax: HasTrailingMemberDeclBlock {}
9393
extension ProtocolDeclSyntax: HasTrailingMemberDeclBlock {}
9494
extension StructDeclSyntax: HasTrailingMemberDeclBlock {}
9595

96-
// MARK: - IfStmt
96+
// MARK: - IfStmtSyntax
9797
// IfStmtSyntax is a special scenario as we also have the `else` body or an if-else
9898
// So we cannot conform to `HasTrailingCodeBlock`
9999

@@ -105,10 +105,21 @@ public extension IfStmtSyntax {
105105
self.elseKeyword = elseBody != nil ? .keyword(.else) : nil
106106
}
107107

108-
init(_ signature: String, @CodeBlockItemListBuilder bodyBuilder: () -> CodeBlockItemListSyntax, elseIf: IfStmtSyntax) {
108+
init(_ signature: PartialSyntaxNodeString, @CodeBlockItemListBuilder bodyBuilder: () -> CodeBlockItemListSyntax, elseIf: IfStmtSyntax) {
109109
self = "\(signature) {}"
110110
self.body = CodeBlockSyntax(statements: bodyBuilder())
111111
self.elseBody = .ifStmt(elseIf)
112112
self.elseKeyword = elseBody != nil ? .keyword(.else) : nil
113113
}
114114
}
115+
116+
// MARK: - SwitchStmtSyntax
117+
// SwitchStmtSyntax is a special scenario as it don't have body or members
118+
// So we cannot conform to `HasTrailingCodeBlock` or `HasTrailingMemberDeclBlock`
119+
120+
public extension SwitchStmtSyntax {
121+
init(_ signature: PartialSyntaxNodeString, @SwitchCaseListBuilder casesBuilder: () -> SwitchCaseListSyntax = { SwitchCaseListSyntax([]) }) {
122+
self = "\(signature) {}"
123+
self.cases = casesBuilder()
124+
}
125+
}

Tests/SwiftSyntaxBuilderTest/SwitchTests.swift

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,31 @@ final class SwitchTests: XCTestCase {
4141
"""
4242
)
4343
}
44+
45+
func testSwitchStmtSyntaxWithStringParsing() {
46+
let syntax = SwitchStmtSyntax("switch count") {
47+
for num in 1..<3 {
48+
SwitchCaseSyntax("case \(literal: num):") {
49+
ExprSyntax("print(count)")
50+
}
51+
}
52+
SwitchCaseSyntax("default:") {
53+
BreakStmtSyntax("break")
54+
}
55+
}
56+
57+
AssertBuildResult(
58+
syntax,
59+
"""
60+
switch count {
61+
case 1:
62+
print(count)
63+
case 2:
64+
print(count)
65+
default:
66+
break
67+
}
68+
"""
69+
)
70+
}
4471
}

0 commit comments

Comments
 (0)