forked from swiftlang/swift
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmacro_expand.swift
751 lines (604 loc) · 31.3 KB
/
macro_expand.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
// REQUIRES: swift_swift_parser, executable_test
// RUN: %empty-directory(%t)
// RUN: %host-build-swift -swift-version 5 -emit-library -o %t/%target-library-name(MacroDefinition) -module-name=MacroDefinition %S/Inputs/syntax_macro_definitions.swift
// Diagnostics testing
// RUN: %target-typecheck-verify-swift -swift-version 5 -load-plugin-library %t/%target-library-name(MacroDefinition) -module-name MacroUser -DTEST_DIAGNOSTICS
// Diagnostics testing by importing macros from a module
// RUN: %target-swift-frontend -swift-version 5 -emit-module -o %t/freestanding_macro_library.swiftmodule %S/Inputs/freestanding_macro_library.swift -module-name freestanding_macro_library -load-plugin-library %t/%target-library-name(MacroDefinition)
// RUN: %target-swift-frontend -swift-version 5 -emit-module -o %t/freestanding_macro_library_2.swiftmodule %S/Inputs/freestanding_macro_library_2.swift -module-name freestanding_macro_library_2 -load-plugin-library %t/%target-library-name(MacroDefinition) -I %t
// RUN: %target-typecheck-verify-swift -swift-version 5 -load-plugin-library %t/%target-library-name(MacroDefinition) -module-name MacroUser -DTEST_DIAGNOSTICS -I %t -DIMPORT_MACRO_LIBRARY
// RUN: not %target-swift-frontend -swift-version 5 -typecheck -load-plugin-library %t/%target-library-name(MacroDefinition) -module-name MacroUser -DTEST_DIAGNOSTICS -serialize-diagnostics-path %t/macro_expand.dia %s -emit-macro-expansion-files no-diagnostics -Rmacro-loading > %t/macro-printing.txt
// RUN: c-index-test -read-diagnostics %t/macro_expand.dia 2>&1 | %FileCheck -check-prefix CHECK-DIAGS -dump-input=always %s
// RUN: %FileCheck %s --check-prefix CHECK-MACRO-PRINTED < %t/macro-printing.txt
// RUN: not %target-swift-frontend -swift-version 5 -typecheck -diagnostic-style=swift -load-plugin-library %t/%target-library-name(MacroDefinition) -module-name MacroUser -DTEST_DIAGNOSTICS %s > %t/pretty-macro-diagnostics.txt 2>&1
// RUN: %FileCheck %s --check-prefix PRETTY-DIAGS < %t/pretty-macro-diagnostics.txt
// Debug info SIL testing
// RUN: %target-swift-frontend -swift-version 5 -emit-sil -load-plugin-library %t/%target-library-name(MacroDefinition) %s -module-name MacroUser -o - -g | %FileCheck --check-prefix CHECK-SIL %s
// Debug info IR testing
// RUN: %target-swift-frontend -swift-version 5 -dwarf-version=4 -emit-ir -load-plugin-library %t/%target-library-name(MacroDefinition) %s -module-name MacroUser -o - -g | %FileCheck --check-prefix CHECK-IR-DWARF4 %s
// RUN: %target-swift-frontend -swift-version 5 -dwarf-version=5 -emit-ir -load-plugin-library %t/%target-library-name(MacroDefinition) %s -module-name MacroUser -o - -g | %FileCheck --check-prefix CHECK-IR %s
// Execution testing
// RUN: %target-build-swift -swift-version 5 -g -load-plugin-library %t/%target-library-name(MacroDefinition) %s -o %t/main -module-name MacroUser -Xfrontend -emit-dependencies-path -Xfrontend %t/main.d -Xfrontend -emit-reference-dependencies-path -Xfrontend %t/main.swiftdeps
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// Plugin search path and loaded module trace testing
// RUN: %target-swift-frontend -swift-version 5 -emit-sil -plugin-path %t %s -module-name MacroUser -emit-loaded-module-trace -o %t/loaded_module_trace
// RUN: %FileCheck -check-prefix=CHECK-MODULE-TRACE %s < %t/loaded_module_trace.trace.json
// CHECK-MODULE-TRACE: {{libMacroDefinition.dylib|libMacroDefinition.so|MacroDefinition.dll}}
// CHECK-DIAGS: loaded macro implementation module 'MacroDefinition' from shared library
#if IMPORT_MACRO_LIBRARY
import freestanding_macro_library
import freestanding_macro_library_2
#else
@freestanding(declaration, names:named(StructWithUnqualifiedLookup))
macro structWithUnqualifiedLookup()= #externalMacro(module:"MacroDefinition", type:"DefineStructWithUnqualifiedLookupMacro")
@freestanding(declaration)
macro anonymousTypes(_:()->String)= #externalMacro(module:"MacroDefinition", type:"DefineAnonymousTypesMacro")
@freestanding(declaration)
macro freestandingWithClosure<T>(_ value:T, body:(T)->T)= #externalMacro(module:"MacroDefinition", type:"EmptyDeclarationMacro")
@freestanding(declaration, names: arbitrary) macro bitwidthNumberedStructs(_ baseName:String)= #externalMacro(module:"MacroDefinition", type:"DefineBitwidthNumberedStructsMacro")
@freestanding(expression) macro stringify<T>(_ value:T)->(T,String)= #externalMacro(module:"MacroDefinition", type:"StringifyMacro")
@freestanding(declaration, names: arbitrary) macro bitwidthNumberedStructs(_ baseName:String, blah:Bool)= #externalMacro(module:"MacroDefinition", type:"DefineBitwidthNumberedStructsMacro")
@freestanding(declaration, names:named(value)) macro varValue()= #externalMacro(module:"MacroDefinition", type:"VarValueMacro")
#endif
@freestanding(declaration, names:named(storedProperty))
public macro AddStoredProperty<T>(_ x:T)= #externalMacro(module:"MacroDefinition", type:"StoredPropertyMacro")
#if TEST_DIAGNOSTICS
@freestanding(declaration)
macro NotCovered()= #externalMacro(module:"MacroDefinition", type:"InvalidMacro")
struct MemberNotCovered {
#NotCovered
// expected-note@-1 {{in expansion of macro 'NotCovered' here}}
// CHECK-DIAGS: error: declaration name 'value' is not covered by macro 'NotCovered'
// CHECK-DIAGS: CONTENTS OF FILE @__swiftmacro_9MacroUser0023macro_expandswift_elFCffMX[[@LINE-5]]_2_33_4361AD9339943F52AE6186DD51E04E91Ll10NotCoveredfMf_.swift
// CHECK-DIAGS: var value: Int
// CHECK-DIAGS: END CONTENTS OF FILE
}
@attached(peer)
macro Invalid()= #externalMacro(module:"MacroDefinition", type:"InvalidMacro")
@Invalid
structBad{}
// expected-note@-2 18 {{in expansion of macro 'Invalid' on struct 'Bad' here}}
// CHECK-DIAGS: error: macro expansion cannot introduce import
// CHECK-DIAGS: error: macro expansion cannot introduce precedence group
// CHECK-DIAGS: error: macro expansion cannot introduce macro
// CHECK-DIAGS: error: macro expansion cannot introduce extension
// CHECK-DIAGS: error: macro expansion cannot introduce '@main' type
// CHECK-DIAGS: error: declaration name 'MyMain' is not covered by macro 'Invalid'
// CHECK-DIAGS: error: declaration name 'Array' is not covered by macro 'Invalid'
// CHECK-DIAGS: error: declaration name 'Dictionary' is not covered by macro 'Invalid'
// CHECK-DIAGS: error: macro expansion cannot introduce default literal type 'BooleanLiteralType'
// CHECK-DIAGS: error: macro expansion cannot introduce default literal type 'ExtendedGraphemeClusterType'
// CHECK-DIAGS: error: macro expansion cannot introduce default literal type 'FloatLiteralType'
// CHECK-DIAGS: error: macro expansion cannot introduce default literal type 'IntegerLiteralType'
// CHECK-DIAGS: error: macro expansion cannot introduce default literal type 'StringLiteralType'
// CHECK-DIAGS: error: macro expansion cannot introduce default literal type 'UnicodeScalarType'
// CHECK-DIAGS: error: macro expansion cannot introduce default literal type '_ColorLiteralType'
// CHECK-DIAGS: error: macro expansion cannot introduce default literal type '_ImageLiteralType'
// CHECK-DIAGS: error: macro expansion cannot introduce default literal type '_FileReferenceLiteralType'
// CHECK-DIAGS: CONTENTS OF FILE @__swiftmacro_9MacroUser3Bad7InvalidfMp_.swift
// CHECK-DIAGS: import Swift
// CHECK-DIAGS: precedencegroup MyPrecedence {
// CHECK-DIAGS: }
// CHECK-DIAGS: @attached(member) macro myMacro()
// CHECK-DIAGS: extension Int {
// CHECK-DIAGS: }
// CHECK-DIAGS: @main
// CHECK-DIAGS: struct MyMain {
// CHECK-DIAGS: static func main() {
// CHECK-DIAGS: }
// CHECK-DIAGS: }
// CHECK-DIAGS: typealias Array = Void
// CHECK-DIAGS: typealias Dictionary = Void
// CHECK-DIAGS: typealias BooleanLiteralType = Void
// CHECK-DIAGS: typealias ExtendedGraphemeClusterType = Void
// CHECK-DIAGS: typealias FloatLiteralType = Void
// CHECK-DIAGS: typealias IntegerLiteralType = Void
// CHECK-DIAGS: typealias StringLiteralType = Void
// CHECK-DIAGS: typealias UnicodeScalarType = Void
// CHECK-DIAGS: typealias _ColorLiteralType = Void
// CHECK-DIAGS: typealias _ImageLiteralType = Void
// CHECK-DIAGS: typealias _FileReferenceLiteralType = Void
// CHECK-DIAGS: END CONTENTS OF FILE
class HasStoredPropertyClassInvalid {
#AddStoredProperty((Self.self,0).1) // expected-note {{in expansion of macro 'AddStoredProperty' here}}
// CHECK-DIAGS: @__swiftmacro_9MacroUser0023macro_expandswift_elFCffMX[[@LINE-2]]_2_33_{{.*}}AddStoredPropertyfMf_.swift:1:22: error: covariant 'Self' type cannot be referenced from a stored property initializer
}
// Redeclaration checking should behave as though expansions are part of the
// source file.
structRedeclChecking{
#varValue
// expected-error@+1 {{invalid redeclaration of 'value'}}
varvalue:Int{0}
}
// CHECK-DIAGS: macro_expand.swift:[[@LINE-3]]:7: error: invalid redeclaration of 'value'
// CHECK-DIAGS: @__swiftmacro_9MacroUser0023macro_expandswift_elFCffMX[[@LINE-8]]_2_33_4361AD9339943F52AE6186DD51E04E91Ll8varValuefMf_.swift:1:5: note: 'value' previously declared here
// CHECK-DIAGS: CONTENTS OF FILE @__swiftmacro_9MacroUser0023macro_expandswift_elFCffMX[[@LINE-9]]_2_33_4361AD9339943F52AE6186DD51E04E91Ll8varValuefMf_.swift:
// CHECK-DIAGS: var value: Int {
// CHECK-DIAGS: 1
// CHECK-DIAGS: }
// CHECK-DIAGS: END CONTENTS OF FILE
@attached(body)
public macro ThrowCancellation()= #externalMacro(module:"MacroDefinition", type:"ThrowCancellationMacro")
// https://github.com/swiftlang/swift/issues/79039 - Make sure we diagnose the
// error mismatch.
@ThrowCancellation // expected-note {{in expansion of macro 'ThrowCancellation' on global function 'issue79039()' here}}
func issue79039()throws(DecodingError)
// CHECK-DIAGS: @__swiftmacro_9MacroUser10issue7903917ThrowCancellationfMb_.swift:2:11: error: thrown expression type 'CancellationError' cannot be converted to error type 'DecodingError'
@ThrowCancellation // expected-note {{in expansion of macro 'ThrowCancellation' on global function 'issue79039_2()' here}}
func issue79039_2()throws(DecodingError){}
// CHECK-DIAGS: @__swiftmacro_9MacroUser12issue79039_217ThrowCancellationfMb_.swift:2:11: error: thrown expression type 'CancellationError' cannot be converted to error type 'DecodingError'
#endif
@freestanding(declaration)
macro accidentalCodeItem()= #externalMacro(module:"MacroDefinition", type:"FakeCodeItemMacro")
@attached(peer)
macro AccidentalCodeItem()= #externalMacro(module:"MacroDefinition", type:"FakeCodeItemMacro")
#if TEST_DIAGNOSTICS
func invalidDeclarationMacro(){
#accidentalCodeItem
// expected-note@-1 {{in expansion of macro 'accidentalCodeItem' here}}
// CHECK-DIAGS: @__swiftmacro_9MacroUser0023macro_expandswift_elFCffMX[[@LINE-3]]_2_18accidentalCodeItemfMf_.swift:1:1: error: expected macro expansion to produce a declaration
@AccidentalCodeItemstructS{}
// expected-note@-1 {{in expansion of macro 'AccidentalCodeItem' on struct 'S' here}}
// CHECK-DIAGS: @__swiftmacro_9MacroUser018invalidDeclarationA0yyF5S_$l018AccidentalCodeItemfMp_.swift:1:1: error: expected macro expansion to produce a declaration
do{
@AccidentalCodeItemstructS{}
// expected-note@-1 {{in expansion of macro 'AccidentalCodeItem' on struct 'S' here}}
// CHECK-DIAGS: @__swiftmacro_9MacroUser018invalidDeclarationA0yyF5S_$l118AccidentalCodeItemfMp_.swift:1:1: error: expected macro expansion to produce a declaration
}
}
#endif
@freestanding(expression) macro customFileID()->String= #externalMacro(module:"MacroDefinition", type:"FileIDMacro")
@freestanding(expression) macro fileID<T:ExpressibleByStringLiteral>()->T= #externalMacro(module:"MacroDefinition", type:"FileIDMacro")
@freestanding(expression) macro recurse(_:Bool)= #externalMacro(module:"MacroDefinition", type:"RecursiveMacro")
@freestanding(expression) macro assert(_:Bool)= #externalMacro(module:"MacroDefinition", type:"AssertMacro")
func testFileID(a:Int, b:Int){
// CHECK: MacroUser/macro_expand.swift
print("Result is \(#customFileID)")
// CHECK-SIL: sil_scope [[SRC_SCOPE:[0-9]+]] { loc "{{.*}}macro_expand.swift":[[@LINE-3]]:6 parent {{.*}}testFileID
// CHECK-SIL: sil_scope [[EXPANSION_SCOPE:[0-9]+]] { loc "{{.*}}macro_expand.swift":[[@LINE-2]]:22 parent [[SRC_SCOPE]]
// CHECK-SIL: sil_scope [[MACRO_SCOPE:[0-9]+]] { loc "@__swiftmacro{{.*}}":1:1 parent @$s9MacroUser0023macro_expandswift_elFCffMX{{.*}}_12customFileIDfMf_ {{.*}} inlined_at [[EXPANSION_SCOPE]] }
// CHECK-SIL: string_literal utf8 "MacroUser/macro_expand.swift", loc "@__swiftmacro_9MacroUser0023macro_expandswift_elFCffMX{{.*}}_12customFileIDfMf_.swift":1:1, scope [[MACRO_SCOPE]]
// CHECK-IR-DAG: !DISubprogram(name: "customFileID", linkageName:"$s9MacroUser0023macro_expandswift_elFCffMX{{.*}}_12customFileIDfMf_"
// CHECK: Builtin result is MacroUser/macro_expand.swift
// CHECK-AST: macro_expansion_expr type='String'{{.*}}name=line
print("Builtin result is \(#fileID)")
print(
// CHECK-IR-DAG: ![[L1:[0-9]+]] = distinct !DILocation(line: [[@LINE+4]], column: 5
// CHECK-IR-DAG: ![[L2:[0-9]+]] = distinct !DILocation({{.*}}inlinedAt: ![[L1]])
// CHECK-IR-DAG: !DIFile(filename: "{{.*}}@__swiftmacro_9MacroUser0023macro_expandswift_elFCffMX{{.*}}_12customFileIDfMf_.swift", {{.*}}source: "{{.*}}MacroUser/macro_expand.swift{{.*}}// original-source-range: {{.*}}")
// CHECK-IR-DWARF4: {{(target triple = .*-unknown-windows-msvc)|(!DIFile\(filename: ".*generated-.*@__swiftmacro_9MacroUser0023macro_expandswift_elFCffMX.*_12customFileIDfMf_.swift", directory: "[^"]*"\))}}
#addBlocker(
#stringify(a - b)
)
)
}
testFileID(a:1, b:2)
@freestanding(expression)macro stringifyAndTry<T>(_ value: T)->(T, String)=
#externalMacro(module:"MacroDefinition", type:"StringifyAndTryMacro")
enum Angle {
case degrees(Double)
case radians(Double)
}
func testStringify(a: Int, b: Int){
lets= #stringify(a + b)
print(s)
// CHECK-AST: macro_expansion_expr type='(Int, String)'{{.*}}name=stringify
// CHECK-AST-NEXT: argument_list
// CHECK-AST: tuple_expr type='(Int, String)' location=Macro expansion of #stringify
let(b, s2)= #stringify({()->Boolinreturntrue})
// CHECK-AST: macro_expansion_expr type='(() -> Bool, String)'{{.*}}name=stringify
// CHECK-AST-NEXT: argument_list
// CHECK-AST: tuple_expr type='(() -> Bool, String)' location=Macro expansion of #stringify
let(b2, s3)= #stringify<Double>(1+2)
// CHECK-AST: macro_expansion_expr type='(Double, String)'{{.*}}name=stringify
// CHECK-AST-NEXT: argument_list
// CHECK-AST: tuple_expr type='(Double, String)' location=Macro expansion of #stringify
_ =(b, b2, s2, s3)
letangle=Angle.degrees(17)
switch angle {
case.degrees(let value):
_ = #stringify(value)
case.radians(let value):
_ = #stringify(value)
}
}
func testAssert(a: Int, b: Int){
#assert(a == b)
}
public struct Outer {
varvalue:Int=0
public func test(){
let(a, b)= #stringify(1+ value)
let(c, d)= #stringify({ x in
x +1
})
_ = a
_ = b
_ = c
_ = d
}
}
// CHECK: (2, "a + b")
testStringify(a:1, b:1)
protocol P {}
extension Int: P {}
// Stringify with closures that have local types.
@available(SwiftStdlib 5.1,*)
func testStringifyWithLocalTypes(){
_ = #stringify({
structLocalType:P{
staticvarname:String="Taylor"
varsomething:someP{self}
}
func f()->someP{returnLocalType().something }
})
}
// Stringify in closures that have anonymous parameters.
func testStringifyWithAnonymousParameters(){
{
_ = #stringify($0 + $1)
}(1,2)
}
func maybeThrowing() throws -> Int { 5 }
#if TEST_DIAGNOSTICS
@freestanding(expression) @discardableResult
macro discardableStringify<T>(_ value: T) -> (T, String) = #externalMacro(module: "MacroDefinition", type:"StringifyMacro")
func testDiscardableStringify(x:Int){
#stringify(x +1) // expected-warning{{expression of type '(Int, String)' is unused}}
#discardableStringify(x +1)
}
#endif
#if TEST_DIAGNOSTICS
// This causes an error when non-'Bool' value is passed.
@freestanding(expression) macro assertAny<T>(_ value: T)= #externalMacro(module:"MacroDefinition", type:"AssertMacro")
func testNested(){
structNested{}
_ = #stringify(#assertAny(Nested()))
// expected-note@-1 {{in expansion of macro 'stringify' here}}
// CHECK-DIAGS-NOT: error: cannot convert value of type 'Nested' to expected argument type 'Bool'
// CHECK-DIAGS: @__swiftmacro_9MacroUser0023macro_expandswift_elFCffMX{{.*}}_9stringifyfMf_9assertAnyfMf_.swift:1:8: error: cannot convert value of type 'Nested' to expected argument type 'Bool'
// CHECK-DIAGS-NOT: error: cannot convert value of type 'Nested' to expected argument type 'Bool'
// PRETTY-DIAGS: 1:8: error: cannot convert value of type 'Nested' to expected argument type 'Bool'
// PRETTY-DIAGS: macro_expand.swift:{{.*}}:39: note: expanded code originates here
// PRETTY-DIAGS: --- macro expansion #stringify
// PRETTY-DIAGS: --- macro expansion #assertAny
// PRETTY-DIAGS-NEXT: 1 | assert(Nested())
// PRETTY-DIAGS-NEXT: | `- error: cannot convert value
}
#endif
func testStringifyWithThrows()throws{
// Okay, we can put the try inside or outside
_ =try #stringify(maybeThrowing())
_ = #stringify(trymaybeThrowing())
#if TEST_DIAGNOSTICS
// FIXME: Lots of duplicate notes here
_ = #stringify(maybeThrowing()) // expected-note 4{{in expansion of macro 'stringify' here}}
// CHECK-DIAGS: @__swiftmacro_9MacroUser0023macro_expandswift_elFCffMX{{.*}}_9stringifyfMf1_.swift:1:2: error: call can throw but is not marked with 'try'
#endif
// The macro adds the 'try' for us.
_ = #stringifyAndTry(maybeThrowing())
}
@available(SwiftStdlib 5.1,*)
func throwingFunc()asyncthrows->Int{5}
@freestanding(expression) macro callThrowingFunc<T>(_ body:()-> T)-> T = #externalMacro(module:"MacroDefinition", type:"TryCallThrowingFuncMacro")
@available(SwiftStdlib 5.1,*)
func testThrowingCall()asyncthrows->Int{
#callThrowingFunc {
[1,2,3,4,5].map{ $0 +1}.first!
}
}
func testStringifyWithLocalType()throws{
_ = #stringify({
structQuailError:Error{}
throwQuailError()
})
}
@freestanding(expression) macro addBlocker<T>(_ value: T)-> T = #externalMacro(module:"MacroDefinition", type:"AddBlocker")
structOnlyAdds{
staticfunc+(lhs:OnlyAdds, rhs:OnlyAdds)->OnlyAdds{ lhs }
}
func testAddBlocker(a:Int, b:Int, c:Int, oa:OnlyAdds){
_ = #addBlocker(a * b * c)
#if TEST_DIAGNOSTICS
_ = #addBlocker(a + b * c) // expected-error{{blocked an add; did you mean to subtract? (from macro 'addBlocker')}}
// expected-note@-1{{use '-'}}{{21-22=-}}
_ = #addBlocker(oa + oa) // expected-error{{blocked an add; did you mean to subtract? (from macro 'addBlocker')}}
// expected-note@-1{{in expansion of macro 'addBlocker' here}}
// expected-note@-2{{use '-'}}{{22-23=-}}
// CHECK-DIAGS: @__swiftmacro_9MacroUser0023macro_expandswift_elFCffMX{{.*}}_10addBlockerfMf1_.swift:1:4: error: binary operator '-' cannot be applied to two 'OnlyAdds' operands [] []
// CHECK-DIAGS: CONTENTS OF FILE @__swiftmacro_9MacroUser0023macro_expandswift_elFCffMX{{.*}}_10addBlockerfMf1_.swift:
// CHECK-DIAGS-NEXT: Original source range: {{.*}}macro_expand.swift:[[@LINE-6]]:7 - {{.*}}macro_expand.swift:[[@LINE-6]]:27
// CHECK-DIAGS-NEXT: oa - oa
// CHECK-DIAGS-NEXT: END CONTENTS OF FILE
_ = #addBlocker({ // expected-note{{in expansion of macro 'addBlocker' here}}
print("hello")
print(oa + oa) // expected-error{{blocked an add; did you mean to subtract? (from macro 'addBlocker')}}
// expected-note@-1{{use '-'}}
print(oa + oa) // expected-error{{blocked an add; did you mean to subtract? (from macro 'addBlocker')}}
// expected-note@-1{{use '-'}}
}())
// Check recursion.
#recurse(false) // okay
#recurse(true) // expected-note{{in expansion of macro 'recurse' here}}
#endif
}
@freestanding(expression) macro leftHandOperandFinder<T>(_ value: T)-> T = #externalMacro(module:"MacroDefinition", type:"LeftHandOperandFinderMacro")
// Test source location information.
func testSourceLocations(x:Int, yolo:Int, zulu:Int){
// CHECK-MACRO-PRINTED: Source range for LHS is "MacroUser/macro_expand.swift": [[@LINE+3]]:5-[[@LINE+3]]:13
// CHECK-MACRO-PRINTED: Source range for LHS is "MacroUser/macro_expand.swift": [[@LINE+2]]:5-[[@LINE+2]]:6
_ = #leftHandOperandFinder(
x + yolo + zulu
)
}
// Make sure we don't crash with declarations produced by expansions.
@freestanding(expression) macro nestedDeclInExpr()->()-> Void = #externalMacro(module:"MacroDefinition", type:"NestedDeclInExprMacro")
func testNestedDeclInExpr(){
let _:()->Void= #nestedDeclInExpr
}
// Test non-arbitrary names
@freestanding(declaration, names:named(A),named(B),named(foo),named(addOne))
macro defineDeclsWithKnownNames()= #externalMacro(module:"MacroDefinition", type:"DefineDeclsWithKnownNamesMacro")
// Freestanding macros are not in inlined scopes.
// CHECK-SIL: sil_scope {{.*}} { loc "@__swiftmacro_9MacroUser0023macro_expandswift_elFCffMX{{.*}}_25defineDeclsWithKnownNamesfMf_.swift"{{.*}} -> Int }
// FIXME: Macros producing arbitrary names are not supported yet
#if false
#bitwidthNumberedStructs("MyIntGlobal")
#bitwidthNumberedStructs("MyIntGlobalTwo", blah:false)
letblah=false
#bitwidthNumberedStructs("MyIntGlobalThree", blah: blah)
#endif
// Test unqualified lookup from within a macro expansion
letworld=3 // to be used by the macro expansion below
#structWithUnqualifiedLookup()
_ =StructWithUnqualifiedLookup().foo()
#anonymousTypes {"hello"}
func testFreestandingMacroExpansion(){
// Explicit structs to force macros to be parsed as decl.
structFoo{
staticletsingleton=Foo()
staticlets2=Foo.singleton
#bitwidthNumberedStructs("MyIntOne")
}
// CHECK: MyIntOne8
print(Foo.MyIntOne8.self)
// CHECK: MyIntOne16
print(Foo.MyIntOne16.self)
// CHECK: MyIntOne32
print(Foo.MyIntOne32.self)
// CHECK: MyIntOne64
print(Foo.MyIntOne64.self)
struct Foo2 {
#bitwidthNumberedStructs("MyIntTwo", blah:false)
#defineDeclsWithKnownNames()
}
// CHECK: MyIntTwo8
print(Foo2.MyIntTwo8.self)
// CHECK: MyIntTwo16
print(Foo2.MyIntTwo16.self)
// CHECK: MyIntTwo32
print(Foo2.MyIntTwo32.self)
// CHECK: MyIntTwo64
print(Foo2.MyIntTwo64.self)
// CHECK: A
print(Foo2.A.self)
// CHECK: B
print(Foo2.B.self)
// CHECK: 1
print(Foo2().foo)
// CHECK: 2
print(Foo2().addOne(1))
#if TEST_DIAGNOSTICS
struct Foo3 {
#bitwidthNumberedStructs("BUG", blah:false)
// expected-note@-1 4{{in expansion of macro 'bitwidthNumberedStructs' here}}
// CHECK-DIAGS: CONTENTS OF FILE @__swiftmacro_9MacroUser0023macro_expandswift_elFCffMX{{.*}}_23bitwidthNumberedStructsfMf_.swift
// CHECK-DIAGS: struct BUG {
// CHECK-DIAGS: func $s9MacroUser0023macro_expandswift_elFCffMX{{.*}}_23bitwidthNumberedStructsfMf_6methodfMu_()
// CHECK-DIAGS: func $s9MacroUser0023macro_expandswift_elFCffMX{{.*}}_23bitwidthNumberedStructsfMf_6methodfMu0{{_?}}()
}
#endif
// FIXME: Arbitrary name lookup is not yet supported.
// HECK: MyIntGlobal8
// print(MyIntGlobal8.self)
// HECK: MyIntGlobal16
// print(MyIntGlobal16.self)
// HECK: MyIntGlobal32
// print(MyIntGlobal32.self)
// HECK: MyIntGlobal64
// print(MyIntGlobal64.self)
#anonymousTypes {"hello"}
}
testFreestandingMacroExpansion()
// Explicit structs to force macros to be parsed as decl.
varglobalBool=true
struct ContainerOfNumberedStructs {
#bitwidthNumberedStructs("MyIntOne")
#bitwidthNumberedStructs("MyIntTwo", blah: globalBool)
}
// Avoid re-type-checking declaration macro arguments.
func testFreestandingWithClosure(i:Int){
#freestandingWithClosure(i){ x in x }
#freestandingWithClosure(i){
letx= $0
return x
}
}
// Nested macros with closures
@freestanding(expression) macro coerceToInt<T>(_ value:T)->Int= #externalMacro(module:"MacroDefinition", type:"CoerceToIntMacro")
func testFreestandingClosureNesting(){
_ = #stringify({()->Intin
#coerceToInt(2)
})
}
// Freestanding declaration macros that produce local variables
func testLocalVarsFromDeclarationMacros(){
#varValue
}
// Variadic macro
@freestanding(declaration, names: arbitrary) macro emptyDecl(_:String...)= #externalMacro(module:"MacroDefinition", type:"EmptyDeclarationMacro")
struct TakesVariadic {
#emptyDecl("foo","bar")
}
// Funkiness with static functions introduced via macro expansions.
@freestanding(declaration, names:named(foo()))public macro staticFooFunc()= #externalMacro(module:"MacroDefinition", type:"StaticFooFuncMacro")
@freestanding(declaration, names: arbitrary)public macro staticFooFuncArbitrary()= #externalMacro(module:"MacroDefinition", type:"StaticFooFuncMacro")
classHasAnExpandedStatic{
#staticFooFunc()
}
classHasAnExpandedStatic2{
#staticFooFuncArbitrary()
}
func testHasAnExpandedStatic(){
#if TEST_DIAGNOSTICS
foo() // expected-error{{cannot find 'foo' in scope}}
#endif
}
@freestanding(declaration, names:named(==))public macro addSelfEqualsOperator()= #externalMacro(module:"MacroDefinition", type:"SelfAlwaysEqualOperator")
@freestanding(declaration, names: arbitrary)public macro addSelfEqualsOperatorArbitrary()= #externalMacro(module:"MacroDefinition", type:"SelfAlwaysEqualOperator")
@attached(member, names:named(==))public macro AddSelfEqualsMemberOperator()= #externalMacro(module:"MacroDefinition", type:"SelfAlwaysEqualOperator")
@attached(member, names: arbitrary)public macro AddSelfEqualsMemberOperatorArbitrary()= #externalMacro(module:"MacroDefinition", type:"SelfAlwaysEqualOperator")
structHasEqualsSelf{
#addSelfEqualsOperator
}
structHasEqualsSelf2{
#addSelfEqualsOperatorArbitrary
}
@AddSelfEqualsMemberOperator
structHasEqualsSelf3{
}
@AddSelfEqualsMemberOperatorArbitrary
structHasEqualsSelf4{
}
protocolSelfEqualsBoolProto{ // expected-note 4{{where 'Self' =}}
staticfunc==(lhs:Self, rhs:Bool)->Bool
}
structHasEqualsSelfP:SelfEqualsBoolProto{
#addSelfEqualsOperator
}
structHasEqualsSelf2P:SelfEqualsBoolProto{
#addSelfEqualsOperatorArbitrary
}
@AddSelfEqualsMemberOperator
structHasEqualsSelf3P:SelfEqualsBoolProto{
}
@AddSelfEqualsMemberOperatorArbitrary
structHasEqualsSelf4P:SelfEqualsBoolProto{
}
func testHasEqualsSelf(
x:HasEqualsSelf, y:HasEqualsSelf2, z:HasEqualsSelf3, w:HasEqualsSelf4,
xP:HasEqualsSelfP, yP:HasEqualsSelf2P, zP:HasEqualsSelf3P,
wP:HasEqualsSelf4P
){
#if TEST_DIAGNOSTICS
// Global operator lookup doesn't find member operators introduced by macros.
_ =(x ==true) // expected-error{{referencing operator function '=='}}
_ =(y ==true) // expected-error{{referencing operator function '=='}}
_ =(z ==true) // expected-error{{referencing operator function '=='}}
_ =(w ==true) // expected-error{{referencing operator function '=='}}
#endif
// These should be found through the protocol.
_ =(xP ==true)
_ =(yP ==true)
_ =(zP ==true)
_ =(wP ==true)
}
// Macro whose implementation is both an expression and declaration macro.
@freestanding(declaration)
macro AsDeclMacro<T>(_ value:T)= #externalMacro(module:"MacroDefinition", type:"ExprAndDeclMacro")
@freestanding(expression)
macro AsExprMacro<T>(_ value:T)->(T,String)= #externalMacro(module:"MacroDefinition", type:"ExprAndDeclMacro")
func testExpressionAndDeclarationMacro(){
#AsExprMacro(1+1) // expected-warning{{expression of type '(Int, String)' is unused}}
struct Inner {
#AsDeclMacro(1+1)
}
#AsDeclMacro(1+1)
}
// Expression macro implementation with declaration macro role
@freestanding(declaration) macro stringifyAsDeclMacro<T>(_ value:T)= #externalMacro(module:"MacroDefinition", type:"StringifyMacro")
func testExpressionAsDeclarationMacro(){
#if TEST_DIAGNOSTICS
#stringifyAsDeclMacro(1+1)
// expected-error@-1{{macro implementation type 'StringifyMacro' doesn't conform to required protocol 'DeclarationMacro' (from macro 'stringifyAsDeclMacro')}}
#endif
}
// Deprecated macro
@available(*, deprecated, message:"This macro is deprecated.")
@freestanding(expression) macro deprecatedStringify<T>(_ value:T)->(T,String)= #externalMacro(module:"MacroDefinition", type:"StringifyMacro")
@available(*, deprecated, message:"This macro is deprecated.")
@freestanding(declaration) macro deprecatedStringifyAsDeclMacro<T>(_ value:T)= #externalMacro(module:"MacroDefinition", type:"StringifyMacro")
func testDeprecated(){
// expected-warning@+1{{'deprecatedStringify' is deprecated: This macro is deprecated.}}
_ = #deprecatedStringify(1+1)
}
#if TEST_DIAGNOSTICS
struct DeprecatedStructWrapper {
// expected-error@+2{{macro implementation type 'StringifyMacro' doesn't conform to required protocol 'DeclarationMacro' (from macro 'deprecatedStringifyAsDeclMacro')}}
// expected-warning@+1{{'deprecatedStringifyAsDeclMacro' is deprecated: This macro is deprecated.}}
#deprecatedStringifyAsDeclMacro(1+1)
}
#endif
@freestanding(declaration, names:named(ComparableType))
macro DefineComparableType()= #externalMacro(module:"MacroDefinition", type:"DefineComparableTypeMacro")
structHasNestedType{
#DefineComparableType
}
@attached(accessor)
macro AddGetter()= #externalMacro(module:"MacroDefinition", type:"AddGetterMacro")
// Make sure the mangling for the accessor macro doesn't kick local
// discriminator assignment, which would miss the autoclosure.
func testLocalAccessorMacroWithAutoclosure(){
@AddGetter
varx:Int=2
func takesAutoclosure(_ x:@autoclosure()->Int){}
takesAutoclosure(1)
}
@propertyWrapper
structSomePropertyWrapper<T>{
varwrappedValue:T
init(wrappedValue:T){
self.wrappedValue = wrappedValue
}
init(projectedValue:Self){
self= projectedValue
}
varprojectedValue:Self{self}
}
// Property wrappers on macros probably aren't all that useful, but make sure
// we don't crash.
@freestanding(expression)
macro hasPropertyWrapperParam(@SomePropertyWrapper x:Int)= #externalMacro(module:"MacroDefinition", type:"GenericToVoidMacro")
func testPropertyWrapperMacro(){
#hasPropertyWrapperParam(x:0)
#hasPropertyWrapperParam($x:.init(wrappedValue:0))
}
#if TEST_DIAGNOSTICS
@freestanding(expression)
macro missingMacro()= #externalMacro(module:"MacroDefinition", type:"BluhBlah")
// FIXME: xpected-warning@-1 {{external macro implementation type 'MacroDefinition.BluhBlah' could not be found for macro 'missingMacro()'; 'MacroDefinition.BluhBlah' could not be found in library plugin '}}
@freestanding(expression)
macro notMacro()= #externalMacro(module:"MacroDefinition", type:"NotMacroStruct")
// FIXME: xpected-warning@-1 {{macro implementation type 'MacroDefinition.NotMacroStruct' could not be found for macro 'notMacro()'; 'MacroDefinition.NotMacroStruct' is not a valid macro implementation type in library plugin '}}
// Because this is a method in a local decl, it ends up getting delayed, so
// we need to check it at the end of the file.
// FIXME: We either need to switch to using CHECK-DAG, or ideally teach
// the diagnostic verifier about macro expansion buffers.
func invalidDeclarationMacro2(){
structLocalThing1{
func f(){
#accidentalCodeItem
// expected-note@-1 {{in expansion of macro 'accidentalCodeItem' here}}
// CHECK-DIAGS: @__swiftmacro_9MacroUser0023macro_expandswift_elFCffMX[[@LINE-3]]_6_18accidentalCodeItemfMf_.swift:1:1: error: expected macro expansion to produce a declaration
}
}
}
#endif
// Make sure we compute captures for the introduced stored property here.
structHasStoredProperty{
#AddStoredProperty(0)
}
classHasStoredPropertyClass{
#AddStoredProperty(0)
}