Skip to content

Commit 05fc5ed

Browse files
committed
Generate expr node in generateAssertStmtTextChoices
1 parent eb39f3e commit 05fc5ed

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

Sources/SwiftSyntaxBuilderGeneration/SyntaxBuildableChild.swift

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ extension Child {
7171
/// If this node is a token that can't contain arbitrary text, generate a Swift
7272
/// `assert` statement that verifies the variable with name var_name and of type
7373
/// `TokenSyntax` contains one of the supported text options. Otherwise return `nil`.
74-
func generateAssertStmtTextChoices(varName: String) -> String? {
74+
func generateAssertStmtTextChoices(varName: String) -> ExpressibleAsExprBuildable? {
7575
guard type.isToken else {
7676
return nil
7777
}
@@ -91,14 +91,24 @@ extension Child {
9191
return nil
9292
}
9393

94-
var assertChoices: [String] = []
94+
var assertChoices: [ExpressibleAsExprBuildable] = []
9595
if type.isOptional {
96-
assertChoices.append("\(varName) == nil")
96+
assertChoices.append(SequenceExpr {
97+
varName
98+
BinaryOperatorExpr("==")
99+
NilLiteralExpr()
100+
})
97101
}
98-
let unwrap = type.isOptional ? "!" : ""
99102
for textChoice in choices {
100-
assertChoices.append("\(varName)\(unwrap) == \"\(textChoice)\"")
103+
assertChoices.append(SequenceExpr {
104+
MemberAccessExpr(base: type.forceUnwrappedIfNeeded(expr: varName), name: "text")
105+
BinaryOperatorExpr("==")
106+
StringLiteralExpr(raw: textChoice)
107+
})
108+
}
109+
let disjunction = ExprList(assertChoices.flatMap { [$0, BinaryOperatorExpr("||")] }.dropLast())
110+
return FunctionCallExpr("assert") {
111+
SequenceExpr(elements: disjunction)
101112
}
102-
return "assert(\(assertChoices.joined(separator: " || ")))"
103113
}
104114
}

Sources/SwiftSyntaxBuilderGeneration/SyntaxBuildableType.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,15 @@ struct SyntaxBuildableType: Hashable {
256256
}
257257
}
258258

259+
/// Wraps a type in a force unwrap expression depending on whether `isOptional` is true.
260+
func forceUnwrappedIfNeeded(expr: ExpressibleAsExprBuildable) -> ExpressibleAsExprBuildable {
261+
if isOptional {
262+
return ForcedValueExpr(expression: expr)
263+
} else {
264+
return expr
265+
}
266+
}
267+
259268
/// Generate an expression that converts a variable named `varName`
260269
/// which is of `expressibleAs` type to an object of type `buildable`.
261270
func generateExprConvertParamTypeToStorageType(varName: String) -> ExpressibleAsExprBuildable {

0 commit comments

Comments
 (0)