-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathfunction_builder.swift
769 lines (660 loc) · 17.4 KB
/
function_builder.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
// RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
enum Either<T,U> {
case first(T)
case second(U)
}
@_functionBuilder
struct TupleBuilder {
static func buildBlock<T1>(_ t1: T1) -> (T1) {
return (t1)
}
static func buildBlock<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) {
return (t1, t2)
}
static func buildBlock<T1, T2, T3>(_ t1: T1, _ t2: T2, _ t3: T3)
-> (T1, T2, T3) {
return (t1, t2, t3)
}
static func buildBlock<T1, T2, T3, T4>(_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4)
-> (T1, T2, T3, T4) {
return (t1, t2, t3, t4)
}
static func buildBlock<T1, T2, T3, T4, T5>(
_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5
) -> (T1, T2, T3, T4, T5) {
return (t1, t2, t3, t4, t5)
}
static func buildIf<T>(_ value: T?) -> T? { return value }
static func buildEither<T,U>(first value: T) -> Either<T,U> {
return .first(value)
}
static func buildEither<T,U>(second value: U) -> Either<T,U> {
return .second(value)
}
static func buildArray<T>(_ array: [T]) -> [T] { return array }
}
func tuplify<T>(_ cond: Bool, @TupleBuilder body: (Bool) throws -> T) rethrows {
print(try body(cond))
}
// CHECK: (17, 3.14159, "Hello, DSL", (["nested", "do"], 6), Optional((2.71828, ["if", "stmt"])))
let name = "dsl"
tuplify(true) {
17
3.14159
"Hello, \(name.map { $0.uppercased() }.joined())"
do {
["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"]
}
}
// CHECK: ("chain0", main.Either<(Swift.String, Swift.Double), (Swift.Double, Swift.String)>.second(2.8, "capable"))
tuplify(false) {
"chain0"
if $0 {
"marginal"
2.9
} else {
2.8
"capable"
}
}
// CHECK: ("chain1", nil)
tuplify(false) {
"chain1"
if $0 {
"marginal"
2.9
} else if $0 {
2.8
"capable"
}
}
// CHECK: ("chain2", Optional(main.Either<(Swift.String, Swift.Double), (Swift.Double, Swift.String)>.first("marginal", 2.9)))
tuplify(true) {
"chain2"
if $0 {
"marginal"
2.9
} else if $0 {
2.8
"capable"
}
}
// CHECK: ("chain3", main.Either<main.Either<(Swift.String, Swift.Double), (Swift.Double, Swift.String)>, main.Either<(Swift.Double, Swift.Double), (Swift.String, Swift.String)>>.first(main.Either<(Swift.String, Swift.Double), (Swift.Double, Swift.String)>.first("marginal", 2.9)))
tuplify(true) {
"chain3"
if $0 {
"marginal"
2.9
} else if $0 {
2.8
"capable"
} else if $0 {
2.8
1.0
} else {
"wild"
"broken"
}
}
// CHECK: ("chain4", main.Either<main.Either<main.Either<(Swift.String, Swift.Int), (Swift.String, Swift.Int)>, main.Either<(Swift.String, Swift.Int), (Swift.String, Swift.Int)>>, main.Either<main.Either<(Swift.String, Swift.Int), (Swift.String, Swift.Int)>, (Swift.String, Swift.Int)>>.first
tuplify(true) {
"chain4"
if $0 {
"0"
0
} else if $0 {
"1"
1
} else if $0 {
"2"
2
} else if $0 {
"3"
3
} else if $0 {
"4"
4
} else if $0 {
"5"
5
} else {
"6"
6
}
}
// rdar://50710698
// CHECK: ("chain5", 8, 9)
tuplify(true) {
"chain5"
#if false
6
$0
#else
8
9
#endif
}
// CHECK: ("getterBuilder", 0, 4, 12)
@TupleBuilder
var globalBuilder: (String, Int, Int, Int) {
"getterBuilder"
0
4
12
}
print(globalBuilder)
// CHECK: ("funcBuilder", 13, 45.0)
@TupleBuilder
func funcBuilder(d: Double) -> (String, Int, Double) {
"funcBuilder"
13
d
}
print(funcBuilder(d: 45))
struct MemberBuilders {
@TupleBuilder
func methodBuilder(_ i: Int) -> (String, Int) {
"methodBuilder"
i
}
@TupleBuilder
static func staticMethodBuilder(_ i: Int) -> (String, Int) {
"staticMethodBuilder"
i + 14
}
@TupleBuilder
var propertyBuilder: (String, Int) {
"propertyBuilder"
12
}
}
// CHECK: ("staticMethodBuilder", 27)
print(MemberBuilders.staticMethodBuilder(13))
let mbuilders = MemberBuilders()
// CHECK: ("methodBuilder", 13)
print(mbuilders.methodBuilder(13))
// CHECK: ("propertyBuilder", 12)
print(mbuilders.propertyBuilder)
// SR-11439: Operator builders
infix operator ^^^
func ^^^ (lhs: Int, @TupleBuilder rhs: (Int) -> (String, Int)) -> (String, Int) {
return rhs(lhs)
}
// CHECK: ("hello", 6)
print(5 ^^^ {
"hello"
$0 + 1
})
struct Tagged<Tag, Entity> {
let tag: Tag
let entity: Entity
}
protocol Taggable {
}
extension Taggable {
func tag<Tag>(_ tag: Tag) -> Tagged<Tag, Self> {
return Tagged(tag: tag, entity: self)
}
}
extension Int: Taggable { }
extension String: Taggable { }
extension Double: Taggable { }
@_functionBuilder
struct TaggedBuilder<Tag> {
static func buildBlock() -> () { }
static func buildBlock<T1>(_ t1: Tagged<Tag, T1>) -> Tagged<Tag, T1> {
return t1
}
static func buildBlock<T1, T2>(_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>) -> (Tagged<Tag, T1>, Tagged<Tag, T2>) {
return (t1, t2)
}
static func buildBlock<T1, T2, T3>(_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>, _ t3: Tagged<Tag, T3>)
-> (Tagged<Tag, T1>, Tagged<Tag, T2>, Tagged<Tag, T3>) {
return (t1, t2, t3)
}
static func buildBlock<T1, T2, T3, T4>(_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>, _ t3: Tagged<Tag, T3>, _ t4: Tagged<Tag, T4>)
-> (Tagged<Tag, T1>, Tagged<Tag, T2>, Tagged<Tag, T3>, Tagged<Tag, T4>) {
return (t1, t2, t3, t4)
}
static func buildBlock<T1, T2, T3, T4, T5>(
_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>, _ t3: Tagged<Tag, T3>, _ t4: Tagged<Tag, T4>, _ t5: Tagged<Tag, T5>
) -> (Tagged<Tag, T1>, Tagged<Tag, T2>, Tagged<Tag, T3>, Tagged<Tag, T4>, Tagged<Tag, T5>) {
return (t1, t2, t3, t4, t5)
}
static func buildIf<T>(_ value: Tagged<Tag, T>?) -> Tagged<Tag, T>? { return value }
}
enum Color {
case red, green, blue
}
func acceptColorTagged<Result>(@TaggedBuilder<Color> body: () -> Result) {
print(body())
}
struct TagAccepter<Tag> {
static func acceptTagged<Result>(@TaggedBuilder<Tag> body: () -> Result) {
print(body())
}
}
func testAcceptColorTagged(b: Bool, i: Int, s: String, d: Double) {
// FIXME: When we support buildExpression, drop the "Color" prefix
// CHECK: Tagged<
acceptColorTagged {
i.tag(Color.red)
s.tag(Color.green)
d.tag(Color.blue)
}
// FIXME: When we support buildExpression, drop the "Color" prefix
// CHECK: Tagged<
TagAccepter<Color>.acceptTagged {
i.tag(Color.red)
s.tag(Color.green)
d.tag(Color.blue)
}
// CHECK: Tagged<
TagAccepter<Color>.acceptTagged { () -> Tagged<Color, Int> in
if b {
return i.tag(Color.green)
} else {
return i.tag(Color.blue)
}
}
}
testAcceptColorTagged(b: true, i: 17, s: "Hello", d: 3.14159)
// Use buildExpression() when it's available.
enum Component {
case string(StaticString)
case floating(Double)
case color(Color)
indirect case array([Component])
indirect case optional(Component?)
}
@_functionBuilder
struct ComponentBuilder {
static func buildExpression(_ string: StaticString) -> Component {
return .string(string)
}
static func buildExpression(_ float: Double) -> Component {
return .floating(float)
}
static func buildExpression(_ color: Color) -> Component {
return .color(color)
}
static func buildBlock(_ components: Component...) -> Component {
return .array(components)
}
static func buildIf(_ value: Component?) -> Component {
return .optional(value)
}
}
func acceptComponentBuilder(@ComponentBuilder _ body: () -> Component) {
print(body())
}
func colorWithAutoClosure(_ color: @autoclosure () -> Color) -> Color {
return color()
}
var trueValue = true
acceptComponentBuilder {
"hello"
if trueValue {
3.14159
colorWithAutoClosure(.red)
}
.red
}
// CHECK: array([main.Component.string("hello"), main.Component.optional(Optional(main.Component.array([main.Component.floating(3.14159), main.Component.color(main.Color.red)]))), main.Component.color(main.Color.red)])
// rdar://53325810
// Test that we don't have problems with expression pre-checking when
// type-checking an overloaded function-builder call. In particular,
// we need to make sure that expressions in the closure are pre-checked
// before we build constraints for them. Note that top-level expressions
// that need to be rewritten by expression prechecking (such as the operator
// sequences in the boolean conditions and statements below) won't be
// rewritten in the original closure body if we just precheck the
// expressions produced by the function-builder transformation.
struct ForEach1<Data : RandomAccessCollection, Content> {
var data: Data
var content: (Data.Element) -> Content
func show() {
print(content(data.first!))
print(content(data.last!))
}
}
extension ForEach1 where Data.Element: StringProtocol {
// Checking this overload shouldn't trigger inappropriate caching that
// affects checking the next overload.
init(_ data: Data,
@TupleBuilder content: @escaping (Data.Element) -> Content) {
self.init(data: data, content: content)
}
}
extension ForEach1 where Data == Range<Int> {
// This is the overload we actually want.
init(_ data: Data,
@TupleBuilder content: @escaping (Int) -> Content) {
self.init(data: data, content: content)
}
}
let testForEach1 = ForEach1(-10 ..< 10) { i in
"testForEach1"
if i < 0 {
"begin"
i < -5
} else {
i > 5
"end"
}
}
testForEach1.show()
// CHECK: ("testForEach1", main.Either<(Swift.String, Swift.Bool), (Swift.Bool, Swift.String)>.first("begin", true))
// CHECK: ("testForEach1", main.Either<(Swift.String, Swift.Bool), (Swift.Bool, Swift.String)>.second(true, "end"))
func test_single_stmt_closure_support() {
@_functionBuilder
struct MyBuilder {
static func buildBlock(_ numbers: Int...) -> Int {
return 42
}
}
func test(@MyBuilder builder: () -> Int) -> Int {
builder()
}
let _ = test { 0 } // ok
}
// Check a case involving nested closures that refer to parameters of their
// enclosing closures.
struct X<C: Collection, T> {
init(_ c: C, @TupleBuilder body: (C.Element) -> T) { }
}
struct Y<T> {
init(@TupleBuilder body: () -> T) { }
}
struct Z<T> {
init(@TupleBuilder body: () -> T) { }
}
func testNestedClosuresWithDependencies(cond: Bool) {
tuplify(cond) { _ in
X([1, 2, 3]) { x in
Y {
Z {
x
1
}
}
}
}
}
// Check that we can handle multiple conditions in an 'if' statement.
func testIfConditions(cond: Bool, c1: Bool, i1: Int, i2: Int) {
tuplify(cond) { x in
"testIfConditions"
if i1 == i2, c1, x {
1
"hello"
}
3.14159
}
}
testIfConditions(cond: true, c1: true, i1: 1, i2: 1)
// CHECK: testIfConditions
// CHECK-SAME: hello
// Use a "let" declaration within a function builder.
tuplify(true) { c in
"testLetDeclarations"
let (a, b) = (c, c && true)
if a == b {
"hello"
b
}
a
}
// CHECK: testLetDeclarations"
// CHECK-SAME: hello
// CHECK-SAME: true
// Use if let / if case with various forms of decomposition.
func getOptionalInt(_: Bool) -> Int? { return 25 }
enum E {
case a
case b(Int, String?)
}
func getE(_ i: Int) -> E {
switch i {
case 0:
return .a
case 1:
return .b(17, "hello")
case 2:
return .b(42, nil)
default:
fatalError("Unhandled case")
}
}
tuplify(true) { c in
"testIfLetMatching"
if let theValue = getOptionalInt(c) {
theValue + 17
}
if case let .a = getE(0) {
"matched without payload"
}
if case let .b(i, s?) = getE(1) {
"matched with payload"
s + "!"
i + 17
}
if case let .b(i, s?) = getE(2) {
fatalError("cannot match this")
} else {
"intentional mismatch"
}
}
// CHECK: testIfLetMatching
// CHECK-SAME: Optional(42)
// CHECK-SAME: Optional("matched without payload")
// CHECK-SAME: "matched with payload", "hello!", 34
// CHECK-SAME: "intentional mismatch"
class Super { }
class Sub : Super {
func subMethod() -> String {
return "subMethod"
}
}
func getSuper(wantSubclass: Bool) -> Super {
return wantSubclass ? Sub() : Super()
}
tuplify(true) { c in
"testIfLetAsMatching"
if case let sub as Sub = getSuper(wantSubclass: true) {
sub.subMethod()
}
if case let sub as Sub = getSuper(wantSubclass: false) {
fatalError("cannot match this")
} else {
"Superclass instance"
}
}
// CHECK: testIfLetAsMatching
// CHECK-SAME: "subMethod"
// CHECK-SAME: "Superclass instance"
// switch statements
func testSwitch(_ e: E) {
tuplify(true) { c in
"testSwitch"
switch e {
case .a:
"a"
case .b(let i, let s?):
i * 2
s + "!"
case .b(let i, nil):
"just \(i)"
}
}
}
// CHECK: testSwitch
// CHECK-SAME: first(main.Either<Swift.String, (Swift.Int, Swift.String)>.first("a"))
testSwitch(getE(0))
// CHECK: testSwitch
// CHECK-SAME: first(main.Either<Swift.String, (Swift.Int, Swift.String)>.second(34, "hello!"))
testSwitch(getE(1))
// CHECK: testSwitch
// CHECK-SAME: second("just 42")
testSwitch(getE(2))
func testSwitchCombined(_ eIn: E) {
var e = eIn
tuplify(true) { c in
"testSwitchCombined"
switch e {
case .a:
"a"
case .b(let i, _?), .b(let i, nil):
"just \(i)"
}
}
}
// CHECK: testSwitchCombined
// CHECK-SAME: main.Either<Swift.String, Swift.String>.first("a")
testSwitchCombined(getE(0))
// CHECK: testSwitchCombined
// CHECK-SAME: second("just 17")
testSwitchCombined(getE(1))
// CHECK: testSwitchCombined
// CHECK-SAME: second("just 42")
testSwitchCombined(getE(2))
// Test buildOptional(_:) as an alternative to buildIf(_:).
@_functionBuilder
struct TupleBuilderWithOpt {
static func buildBlock<T1>(_ t1: T1) -> (T1) {
return (t1)
}
static func buildBlock<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) {
return (t1, t2)
}
static func buildBlock<T1, T2, T3>(_ t1: T1, _ t2: T2, _ t3: T3)
-> (T1, T2, T3) {
return (t1, t2, t3)
}
static func buildBlock<T1, T2, T3, T4>(_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4)
-> (T1, T2, T3, T4) {
return (t1, t2, t3, t4)
}
static func buildBlock<T1, T2, T3, T4, T5>(
_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5
) -> (T1, T2, T3, T4, T5) {
return (t1, t2, t3, t4, t5)
}
static func buildOptional<T>(_ value: T?) -> T? { return value }
static func buildEither<T,U>(first value: T) -> Either<T,U> {
return .first(value)
}
static func buildEither<T,U>(second value: U) -> Either<T,U> {
return .second(value)
}
}
func tuplifyWithOpt<T>(_ cond: Bool, @TupleBuilderWithOpt body: (Bool) -> T) {
print(body(cond))
}
tuplifyWithOpt(true) { c in
"1"
3.14159
}
// Test for-each loops with buildArray.
// CHECK: testForEach
// CHECK-SAME: (1, "separator")
// CHECK-SAME: (2, "separator")
// CHECK-SAME: (3, "separator")
// CHECK-SAME: (4, "separator")
// CHECK-SAME: (5, "separator")
// CHECK-SAME: (6, "separator")
// CHECK-SAME: (7, "separator")
// CHECK-SAME: (8, "separator")
// CHECK-SAME: (9, "separator")
// CHECK-SAME: (10, "separator")
tuplify(true) { c in
"testForEach"
for i in 0 ..< (c ? 10 : 5) {
i + 1
"separator"
}
}
// Test the use of function builders partly implemented through a protocol.
indirect enum FunctionBuilder<Expression> {
case expression(Expression)
case block([FunctionBuilder])
case either(Either<FunctionBuilder, FunctionBuilder>)
case optional(FunctionBuilder?)
}
protocol FunctionBuilderProtocol {
associatedtype Expression
typealias Component = FunctionBuilder<Expression>
associatedtype Return
static func buildExpression(_ expression: Expression) -> Component
static func buildBlock(_ components: Component...) -> Component
static func buildOptional(_ optional: Component?) -> Component
static func buildArray(_ components: [Component]) -> Component
static func buildLimitedAvailability(_ component: Component) -> Component
static func buildFinalResult(_ components: Component) -> Return
}
extension FunctionBuilderProtocol {
static func buildExpression(_ expression: Expression) -> Component { .expression(expression) }
static func buildBlock(_ components: Component...) -> Component { .block(components) }
static func buildOptional(_ optional: Component?) -> Component { .optional(optional) }
static func buildArray(_ components: [Component]) -> Component { .block(components) }
static func buildLimitedAvailability(_ component: Component) -> Component { component }
}
@_functionBuilder
enum ArrayBuilder<E>: FunctionBuilderProtocol {
typealias Expression = E
typealias Component = FunctionBuilder<E>
typealias Return = [E]
static func buildFinalResult(_ components: Component) -> Return {
switch components {
case .expression(let e): return [e]
case .block(let children): return children.flatMap(buildFinalResult)
case .either(.first(let child)): return buildFinalResult(child)
case .either(.second(let child)): return buildFinalResult(child)
case .optional(let child?): return buildFinalResult(child)
case .optional(nil): return []
}
}
}
func buildArray(@ArrayBuilder<String> build: () -> [String]) -> [String] {
return build()
}
let a = buildArray {
"1"
"2"
if Bool.random() {
"maybe 3"
}
}
// CHECK: ["1", "2"
print(a)
// Throwing in function builders.
enum MyError: Error {
case boom
}
// CHECK: testThrow
do {
print("testThrow")
try tuplify(true) { c in
"ready to throw"
throw MyError.boom
}
} catch MyError.boom {
// CHECK: caught it!
print("caught it!")
} catch {
fatalError("Threw something else?")
}