[DSL] Allow function builders to opt in to "if" statements.

If a function builder contains a buildIf function, then "if" statements
will be supported by passing an optional of the "then" branch.
"if" statements with an "else" statement are unsupported at present.
This commit is contained in:
Doug Gregor
2019-04-16 23:34:59 -07:00
committed by John McCall
parent ffd160162f
commit c98f01705c
4 changed files with 66 additions and 5 deletions

View File

@@ -24,15 +24,16 @@ struct TupleBuilder {
}
static func buildDo<T>(_ value: T) -> T { return value }
static func buildIf<T>(_ value: T?) -> T? { return value }
}
func tuplify<T>(@TupleBuilder body: () -> T) {
print(body())
func tuplify<T>(_ cond: Bool, @TupleBuilder body: (Bool) -> T) {
print(body(cond))
}
// CHECK: (17, 3.14159, "Hello, DSL", (["nested", "do"], 6))
// CHECK: (17, 3.14159, "Hello, DSL", (["nested", "do"], 6), Optional((2.71828, ["if", "stmt"])))
let name = "dsl"
tuplify {
tuplify(true) {
17
3.14159
"Hello, \(name.map { $0.uppercased() }.joined())"
@@ -40,4 +41,17 @@ tuplify {
["nested", "do"]
1 + 2 + 3
}
if $0 {
2.71828
["if", "stmt"]
}
}
// CHECK: ("Empty optional", nil)
tuplify(false) {
"Empty optional"
if $0 {
2.71828
["if", "stmt"]
}
}