-
Notifications
You must be signed in to change notification settings - Fork 426
/
Copy pathMacroSystem.swift
1505 lines (1347 loc) · 51.9 KB
/
MacroSystem.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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if swift(>=6)
internal import SwiftDiagnostics
internal import SwiftOperators
@_spi(MacroExpansion) internal import SwiftParser
public import SwiftSyntax
internal import SwiftSyntaxBuilder
@_spi(MacroExpansion) @_spi(ExperimentalLanguageFeature) public import SwiftSyntaxMacros
#else
import SwiftDiagnostics
import SwiftOperators
@_spi(MacroExpansion) import SwiftParser
import SwiftSyntax
import SwiftSyntaxBuilder
@_spi(MacroExpansion) @_spi(ExperimentalLanguageFeature) import SwiftSyntaxMacros
#endif
// MARK: - Public entry function
extension SyntaxProtocol {
/// Expand all uses of the given set of macros within this syntax node.
@available(*, deprecated, message: "Use contextGenerator form to produce a specific context for each expansion node")
public func expand(
macros: [String: Macro.Type],
in context: some MacroExpansionContext,
indentationWidth: Trivia? = nil
) -> Syntax {
return expand(
macros: macros,
contextGenerator: { _ in context },
indentationWidth: indentationWidth
)
}
/// Expand all uses of the given set of macros within this syntax node.
/// - SeeAlso: ``expand(macroSpecs:contextGenerator:indentationWidth:)``
/// to also specify the list of conformances passed to the macro expansion.
public func expand<Context: MacroExpansionContext>(
macros: [String: Macro.Type],
contextGenerator: @escaping (Syntax) -> Context,
indentationWidth: Trivia? = nil
) -> Syntax {
return expand(
macroSpecs: macros.mapValues { MacroSpec(type: $0) },
contextGenerator: contextGenerator,
indentationWidth: indentationWidth
)
}
/// Expand all uses of the given set of macros with specifications within this syntax node.
public func expand<Context: MacroExpansionContext>(
macroSpecs: [String: MacroSpec],
contextGenerator: @escaping (Syntax) -> Context,
indentationWidth: Trivia? = nil
) -> Syntax {
// Build the macro system.
var system = MacroSystem()
for (macroName, macroSpec) in macroSpecs {
try! system.add(macroSpec, name: macroName)
}
let applier = MacroApplication(
macroSystem: system,
contextGenerator: contextGenerator,
indentationWidth: indentationWidth
)
return applier.rewrite(self)
}
}
// MARK: - Expand macros
/// Expand the given freestanding macro and parse the resulting text into a
/// syntax tree.
private func expandFreestandingMemberDeclList(
definition: Macro.Type,
node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext,
indentationWidth: Trivia
) throws -> MemberBlockItemListSyntax? {
guard
let expanded = try expandFreestandingMacro(
definition: definition,
macroRole: inferFreestandingMacroRole(definition: definition),
node: node.detach(in: context, foldingWith: .standardOperators),
in: context,
indentationWidth: indentationWidth
)
else {
return nil
}
let indentedSource = adjustIndentationOfFreestandingMacro(expandedCode: expanded, node: node)
return "\(raw: indentedSource)"
}
private func expandFreestandingCodeItemList(
definition: Macro.Type,
node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext,
indentationWidth: Trivia
) throws -> CodeBlockItemListSyntax? {
guard
let expanded = try expandFreestandingMacro(
definition: definition,
macroRole: inferFreestandingMacroRole(definition: definition),
node: node.detach(in: context, foldingWith: .standardOperators),
in: context,
indentationWidth: indentationWidth
)
else {
return nil
}
let indentedSource = adjustIndentationOfFreestandingMacro(expandedCode: expanded, node: node)
return "\(raw: indentedSource)"
}
private func expandFreestandingExpr(
definition: Macro.Type,
node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext,
indentationWidth: Trivia
) throws -> ExprSyntax? {
guard
let expanded = expandFreestandingMacro(
definition: definition,
macroRole: .expression,
node: node.detach(in: context, foldingWith: .standardOperators),
in: context,
indentationWidth: indentationWidth
)
else {
return nil
}
let indentedSource = adjustIndentationOfFreestandingMacro(expandedCode: expanded, node: node)
return "\(raw: indentedSource)"
}
/// Adds the appropriate indentation on expanded code even if it's multi line.
/// Makes sure original macro expression's trivia is maintained by adding it to expanded code.
private func adjustIndentationOfFreestandingMacro(
expandedCode: String,
node: some FreestandingMacroExpansionSyntax
) -> String {
if expandedCode.isEmpty {
return expandedCode.wrappingInTrivia(from: node)
}
let indentationOfFirstLine = node.indentationOfFirstLine
let indentLength = indentationOfFirstLine.sourceLength.utf8Length
// we are doing 3 step adjustment here
// step 1: add indentation to each line of expanded code
// step 2: remove indentation from first line of expaned code
// step 3: wrap the expanded code into macro expression's trivia. This trivia will contain appropriate existing
// indentation. Note that if macro expression occurs in middle of the line then there will be no indentation or extra space.
// Hence we are doing step 2
var indentedSource = expandedCode.indented(by: indentationOfFirstLine)
indentedSource.removeFirst(indentLength)
indentedSource = indentedSource.wrappingInTrivia(from: node)
return indentedSource
}
private func expandMemberMacro(
definition: MemberMacro.Type,
attributeNode: AttributeSyntax,
attachedTo: DeclSyntax,
conformanceList: InheritedTypeListSyntax,
in context: some MacroExpansionContext,
indentationWidth: Trivia
) throws -> MemberBlockItemListSyntax? {
guard
let expanded = expandAttachedMacro(
definition: definition,
macroRole: .member,
attributeNode: attributeNode.detach(in: context, foldingWith: .standardOperators),
declarationNode: attachedTo.detach(in: context),
parentDeclNode: nil,
extendedType: nil,
conformanceList: conformanceList,
in: context,
indentationWidth: indentationWidth
)
else {
return nil
}
// Separate new members from exisiting members by two newlines
let indentedSource = "\n\n" + expanded.indented(by: attachedTo.indentationOfFirstLine + indentationWidth)
return "\(raw: indentedSource)"
}
private func expandMemberAttributeMacro(
definition: MemberAttributeMacro.Type,
attributeNode: AttributeSyntax,
attachedTo declaration: DeclSyntax,
providingAttributeFor member: DeclSyntax,
in context: some MacroExpansionContext,
indentationWidth: Trivia
) throws -> AttributeListSyntax? {
guard
let expanded = expandAttachedMacro(
definition: definition,
macroRole: .memberAttribute,
attributeNode: attributeNode.detach(in: context, foldingWith: .standardOperators),
declarationNode: member.detach(in: context),
parentDeclNode: declaration.detach(in: context),
extendedType: nil,
conformanceList: nil,
in: context,
indentationWidth: indentationWidth
)
else {
return nil
}
// The added attributes should be on their own line, so prepend them with a newline.
let indentedSource = "\n" + expanded.indented(by: member.indentationOfFirstLine)
return "\(raw: indentedSource)"
}
private func expandPeerMacroMember(
definition: PeerMacro.Type,
attributeNode: AttributeSyntax,
attachedTo: DeclSyntax,
in context: some MacroExpansionContext,
indentationWidth: Trivia
) throws -> MemberBlockItemListSyntax? {
if let variable = attachedTo.as(VariableDeclSyntax.self), variable.bindings.count > 1 {
throw MacroApplicationError.peerMacroOnVariableWithMultipleBindings
}
guard
let expanded = expandAttachedMacro(
definition: definition,
macroRole: .peer,
attributeNode: attributeNode.detach(in: context, foldingWith: .standardOperators),
declarationNode: attachedTo.detach(in: context),
parentDeclNode: nil,
extendedType: nil,
conformanceList: nil,
in: context,
indentationWidth: indentationWidth
)
else {
return nil
}
// Separate the peers and the declaration by two newlines.
let indentedSource = "\n\n" + expanded.indented(by: attachedTo.indentationOfFirstLine)
return "\(raw: indentedSource)"
}
private func expandPeerMacroCodeItem(
definition: PeerMacro.Type,
attributeNode: AttributeSyntax,
attachedTo: DeclSyntax,
in context: some MacroExpansionContext,
indentationWidth: Trivia
) throws -> CodeBlockItemListSyntax? {
if let variable = attachedTo.as(VariableDeclSyntax.self), variable.bindings.count > 1 {
throw MacroApplicationError.peerMacroOnVariableWithMultipleBindings
}
guard
let expanded = expandAttachedMacro(
definition: definition,
macroRole: .peer,
attributeNode: attributeNode.detach(in: context, foldingWith: .standardOperators),
declarationNode: attachedTo.detach(in: context),
parentDeclNode: nil,
extendedType: nil,
conformanceList: nil,
in: context,
indentationWidth: indentationWidth
)
else {
return nil
}
// Separate the peers and the declaration by two newlines.
let indentedSource = "\n\n" + expanded.indented(by: attachedTo.indentationOfFirstLine)
return "\(raw: indentedSource)"
}
/// Expand an accessor macro of a declaration that does not have existing
/// accessors.
///
/// See comment in `expandAccessors` for an explanation why we need this.
private func expandAccessorMacroWithoutExistingAccessors(
definition: AccessorMacro.Type,
attributeNode: AttributeSyntax,
attachedTo: DeclSyntax,
in context: some MacroExpansionContext,
indentationWidth: Trivia
) throws -> AccessorBlockSyntax? {
guard
let expanded = expandAttachedMacro(
definition: definition,
macroRole: .accessor,
attributeNode: attributeNode.detach(in: context, foldingWith: .standardOperators),
declarationNode: attachedTo.detach(in: context),
parentDeclNode: nil,
extendedType: nil,
conformanceList: nil,
in: context,
indentationWidth: indentationWidth
),
!expanded.isEmpty
else {
return nil
}
// `expandAttachedMacro` adds the `{` and `}` to wrap the accessor block and
// then indents it.
// Remove any indentation from the first line using `drop(while:)` and then
// prepend a space to separate it from the variable declaration
let indentedSource = " " + expanded.indented(by: attachedTo.indentationOfFirstLine).drop(while: { $0.isWhitespace })
return "\(raw: indentedSource)"
}
/// Expand an accessor macro of a declaration that already has an accessor.
///
/// See comment in `expandAccessors` for an explanation why we need this.
private func expandAccessorMacroWithExistingAccessors(
definition: AccessorMacro.Type,
attributeNode: AttributeSyntax,
attachedTo: DeclSyntax,
in context: some MacroExpansionContext,
indentationWidth: Trivia
) throws -> AccessorDeclListSyntax? {
guard
let expanded = expandAttachedMacro(
definition: definition,
macroRole: .accessor,
attributeNode: attributeNode.detach(in: context, foldingWith: .standardOperators),
declarationNode: attachedTo.detach(in: context),
parentDeclNode: nil,
extendedType: nil,
conformanceList: nil,
in: context,
indentationWidth: indentationWidth
)
else {
return nil
}
// Separate the accessor from any existing accessors by an empty line
let indentedSource = "\n" + expanded.indented(by: attachedTo.indentationOfFirstLine + indentationWidth)
return "\(raw: indentedSource)"
}
private func expandExtensionMacro(
definition: ExtensionMacro.Type,
attributeNode: AttributeSyntax,
attachedTo: DeclSyntax,
conformanceList: InheritedTypeListSyntax,
in context: some MacroExpansionContext,
indentationWidth: Trivia
) throws -> CodeBlockItemListSyntax? {
guard attachedTo.isProtocol(DeclGroupSyntax.self) else {
return nil
}
guard let extendedType = attachedTo.syntacticQualifiedTypeContext else {
return nil
}
guard
let expanded = expandAttachedMacro(
definition: definition,
macroRole: .extension,
attributeNode: attributeNode.detach(in: context, foldingWith: .standardOperators),
declarationNode: attachedTo.detach(in: context),
parentDeclNode: nil,
extendedType: extendedType.detach(in: context),
conformanceList: conformanceList,
in: context,
indentationWidth: indentationWidth
)
else {
return nil
}
// Separate the extension from other declarations in the source file by two newlines.
let indentedSource = "\n\n" + expanded
return "\(raw: indentedSource)"
}
/// Expand a preamble macro into a list of code items.
private func expandPreambleMacro(
definition: PreambleMacro.Type,
attributeNode: AttributeSyntax,
attachedTo decl: some DeclSyntaxProtocol & WithOptionalCodeBlockSyntax,
in context: some MacroExpansionContext,
indentationWidth: Trivia
) -> CodeBlockItemListSyntax? {
guard
let expanded = expandAttachedMacro(
definition: definition,
macroRole: .preamble,
attributeNode: attributeNode.detach(
in: context,
foldingWith: .standardOperators
),
declarationNode: DeclSyntax(decl.detach(in: context)),
parentDeclNode: nil,
extendedType: nil,
conformanceList: nil,
in: context,
indentationWidth: indentationWidth
)
else {
return []
}
// Match the indentation of the statements if we can, and put newlines around
// the preamble to separate it from the rest of the body.
let indentation = decl.body?.statements.indentationOfFirstLine ?? (decl.indentationOfFirstLine + indentationWidth)
let indentedSource = "\n" + expanded.indented(by: indentation) + "\n"
return "\(raw: indentedSource)"
}
private func expandBodyMacro(
definition: BodyMacro.Type,
attributeNode: AttributeSyntax,
attachedTo decl: some DeclSyntaxProtocol & WithOptionalCodeBlockSyntax,
in context: some MacroExpansionContext,
indentationWidth: Trivia
) -> CodeBlockSyntax? {
guard
let expanded = expandAttachedMacro(
definition: definition,
macroRole: .body,
attributeNode: attributeNode.detach(
in: context,
foldingWith: .standardOperators
),
declarationNode: DeclSyntax(decl.detach(in: context)),
parentDeclNode: nil,
extendedType: nil,
conformanceList: nil,
in: context,
indentationWidth: indentationWidth
),
!expanded.isEmpty
else {
return nil
}
// `expandAttachedMacro` adds the `{` and `}` to wrap the body and then
// indents it.
// Remove any indentation from the first line using `drop(while:)` and then
// prepend a space when it's being introduced on a declaration that has no
// body yet.
let leadingWhitespace = decl.body == nil ? " " : ""
let indentedSource =
leadingWhitespace + expanded.indented(by: decl.indentationOfFirstLine).drop(while: { $0.isWhitespace })
return "\(raw: indentedSource)"
}
// MARK: - MacroSystem
/// Describes the kinds of errors that can occur within a macro system.
enum MacroSystemError: Error {
/// Indicates that a macro with the given name has already been defined.
case alreadyDefined(new: Macro.Type, existing: Macro.Type)
}
/// A system of known macros that can be expanded syntactically
struct MacroSystem {
var macros: [String: MacroSpec] = [:]
/// Create an empty macro system.
init() {}
/// Add a macro specification to the system.
///
/// Throws an error if there is already a macro with this name.
mutating func add(_ macroSpec: MacroSpec, name: String) throws {
if let knownMacroSpec = macros[name] {
throw MacroSystemError.alreadyDefined(new: macroSpec.type, existing: knownMacroSpec.type)
}
macros[name] = macroSpec
}
/// Look for a macro specification with the given name.
func lookup(_ macroName: String) -> MacroSpec? {
return macros[macroName]
}
}
// MARK: - MacroApplication
/// Removes attributes from a syntax tree while maintaining their surrounding trivia.
@_spi(Testing)
public class AttributeRemover: SyntaxRewriter {
let predicate: (AttributeSyntax) -> Bool
var triviaToAttachToNextToken: Trivia = Trivia()
/// Initializes an attribute remover with a given predicate to determine which attributes to remove.
///
/// - Parameter predicate: A closure that determines whether a given `AttributeSyntax` should be removed.
/// If this closure returns `true` for an attribute, that attribute will be removed.
public init(removingWhere predicate: @escaping (AttributeSyntax) -> Bool) {
self.predicate = predicate
}
public override func visit(_ node: AttributeListSyntax) -> AttributeListSyntax {
var filteredAttributes: [AttributeListSyntax.Element] = []
for case .attribute(let attribute) in node {
if self.predicate(attribute) {
var leadingTrivia = attribute.leadingTrivia
// Don't leave behind an empty line when the attribute being removed is on its own line,
// based on the following conditions:
// - Leading trivia ends with a newline followed by arbitrary number of spaces or tabs
// - All leading trivia pieces after the last newline are just whitespace, ensuring
// there are no comments or other non-whitespace characters on the same line
// preceding the attribute.
// - There is no trailing trivia and the next token has leading trivia.
if let lastNewline = leadingTrivia.pieces.lastIndex(where: \.isNewline),
leadingTrivia.pieces[lastNewline...].allSatisfy(\.isWhitespace),
attribute.trailingTrivia.isEmpty,
let nextToken = attribute.nextToken(viewMode: .sourceAccurate),
!nextToken.leadingTrivia.isEmpty
{
leadingTrivia = Trivia(pieces: leadingTrivia.pieces[..<lastNewline])
}
// Drop any spaces or tabs from the trailing trivia because there’s no
// more attribute they need to separate.
let trailingTrivia = attribute.trailingTrivia.trimmingPrefix(while: \.isSpaceOrTab)
triviaToAttachToNextToken += leadingTrivia + trailingTrivia
// If the attribute is not separated from the previous attribute by trivia, as in
// `@First@Second var x: Int` (yes, that's valid Swift), removing the `@Second`
// attribute and dropping all its trivia would cause `@First` and `var` to join
// without any trivia in between, which is invalid. In such cases, the trailing trivia
// of the attribute is significant and must be retained.
if triviaToAttachToNextToken.isEmpty,
let previousToken = attribute.previousToken(viewMode: .sourceAccurate),
previousToken.trailingTrivia.isEmpty
{
triviaToAttachToNextToken = attribute.trailingTrivia
}
} else {
filteredAttributes.append(.attribute(prependAndClearAccumulatedTrivia(to: attribute)))
}
}
// Ensure that any horizontal whitespace trailing the attributes list is trimmed if the next
// token starts a new line.
if let nextToken = node.nextToken(viewMode: .sourceAccurate),
nextToken.leadingTrivia.startsWithNewline
{
if !triviaToAttachToNextToken.isEmpty {
triviaToAttachToNextToken = triviaToAttachToNextToken.trimmingSuffix(while: \.isSpaceOrTab)
} else if let lastAttribute = filteredAttributes.last {
filteredAttributes[filteredAttributes.count - 1].trailingTrivia = lastAttribute
.trailingTrivia
.trimmingSuffix(while: \.isSpaceOrTab)
}
}
return AttributeListSyntax(filteredAttributes)
}
public override func visit(_ token: TokenSyntax) -> TokenSyntax {
return prependAndClearAccumulatedTrivia(to: token)
}
/// Prepends the accumulated trivia to the given node's leading trivia.
///
/// To preserve correct formatting after attribute removal, this function reassigns
/// significant trivia accumulated from removed attributes to the provided subsequent node.
/// Once attached, the accumulated trivia is cleared.
///
/// - Parameter node: The syntax node receiving the accumulated trivia.
/// - Returns: The modified syntax node with the prepended trivia.
private func prependAndClearAccumulatedTrivia<T: SyntaxProtocol>(to syntaxNode: T) -> T {
defer { triviaToAttachToNextToken = Trivia() }
return syntaxNode.with(\.leadingTrivia, triviaToAttachToNextToken + syntaxNode.leadingTrivia)
}
}
private extension Trivia {
func trimmingPrefix(
while predicate: (TriviaPiece) -> Bool
) -> Trivia {
Trivia(pieces: self.drop(while: predicate))
}
func trimmingSuffix(
while predicate: (TriviaPiece) -> Bool
) -> Trivia {
Trivia(
pieces: self[...]
.reversed()
.drop(while: predicate)
.reversed()
)
}
var startsWithNewline: Bool {
self.first?.isNewline ?? false
}
}
let diagnosticDomain: String = "SwiftSyntaxMacroExpansion"
private enum MacroApplicationError: DiagnosticMessage, Error {
case accessorMacroOnVariableWithMultipleBindings
case peerMacroOnVariableWithMultipleBindings
case malformedAccessor
var diagnosticID: MessageID {
return MessageID(domain: diagnosticDomain, id: "\(self)")
}
var severity: DiagnosticSeverity { return .error }
var message: String {
switch self {
case .accessorMacroOnVariableWithMultipleBindings:
return "accessor macro can only be applied to a single variable"
case .peerMacroOnVariableWithMultipleBindings:
return "peer macro can only be applied to a single variable"
case .malformedAccessor:
return """
macro returned a malformed accessor. Accessors should start with an introducer like 'get' or 'set'.
"""
}
}
}
/// Syntax rewriter that evaluates any macros encountered along the way.
private class MacroApplication<Context: MacroExpansionContext>: SyntaxRewriter {
let macroSystem: MacroSystem
var contextGenerator: (Syntax) -> Context
var indentationWidth: Trivia
/// Nodes that we are currently handling in `visitAny` and that should be
/// visited using the node-specific handling function.
var skipVisitAnyHandling: Set<Syntax> = []
/// Store expanded extension while visiting member decls. This should be
/// added to top-level 'CodeBlockItemList'.
var extensions: [CodeBlockItemSyntax] = []
/// Stores the types of the freestanding macros that are currently expanding.
///
/// As macros are expanded by DFS, `expandingFreestandingMacros` always represent the expansion path starting from
/// the root macro node to the last macro node currently expanding.
var expandingFreestandingMacros: [any Macro.Type] = []
init(
macroSystem: MacroSystem,
contextGenerator: @escaping (Syntax) -> Context,
indentationWidth: Trivia?
) {
self.macroSystem = macroSystem
self.contextGenerator = contextGenerator
// Default to 4 spaces if no indentation was passed.
// In the future, we could consider inferring the indentation width from the
// source file in which we expand the macros.
self.indentationWidth = indentationWidth ?? .spaces(4)
super.init(viewMode: .sourceAccurate)
}
override func visitAny(_ node: Syntax) -> Syntax? {
guard !skipVisitAnyHandling.contains(node) else {
return nil
}
// Expand 'MacroExpansionExpr'.
// Note that 'MacroExpansionExpr'/'MacroExpansionExprDecl' at code item
// position are handled by 'visit(_:CodeBlockItemListSyntax)'.
// Only expression expansions inside other syntax nodes is handled here.
switch expandExpr(node: node) {
case .success(let expansion):
return expansion.withExpandedNode { expandedNode in
Syntax(visit(expandedNode))
}
case .failure:
return Syntax(node)
case .notAMacro:
break
}
if var declSyntax = node.as(DeclSyntax.self),
let attributedNode = node.asProtocol(WithAttributesSyntax.self),
!attributedNode.attributes.isEmpty
{
// Apply body and preamble macros.
if let nodeWithBody = node.asProtocol(WithOptionalCodeBlockSyntax.self),
let declNodeWithBody = nodeWithBody as? any DeclSyntaxProtocol & WithOptionalCodeBlockSyntax
{
declSyntax = DeclSyntax(visitBodyAndPreambleMacros(declNodeWithBody))
}
// Visit the node, disabling the `visitAny` handling.
skipVisitAnyHandling.insert(Syntax(declSyntax))
let visitedNode = self.visit(declSyntax)
skipVisitAnyHandling.remove(Syntax(declSyntax))
let attributesToRemove = self.macroAttributes(attachedTo: visitedNode).map(\.attributeNode)
return AttributeRemover(removingWhere: { attributesToRemove.contains($0) }).rewrite(visitedNode)
}
return nil
}
/// Visit for both the body and preamble macros.
func visitBodyAndPreambleMacros<Node: DeclSyntaxProtocol & WithOptionalCodeBlockSyntax>(
_ node: Node
) -> Node {
// Expand preamble macros into a set of code items.
let preamble = expandMacros(
attachedTo: DeclSyntax(node),
ofType: PreambleMacro.Type.self
) { attributeNode, definition, _ in
expandPreambleMacro(
definition: definition,
attributeNode: attributeNode,
attachedTo: node,
in: contextGenerator(Syntax(node)),
indentationWidth: indentationWidth
)
}
// Expand body macro.
let expandedBodies = expandMacros(
attachedTo: DeclSyntax(node),
ofType: BodyMacro.Type.self
) { attributeNode, definition, _ in
expandBodyMacro(
definition: definition,
attributeNode: attributeNode,
attachedTo: node,
in: contextGenerator(Syntax(node)),
indentationWidth: indentationWidth
).map { [$0] }
}
// Dig out the body.
let body: CodeBlockSyntax
switch expandedBodies.count {
case 0 where preamble.isEmpty:
// Nothing changes
return node
case 0:
guard let existingBody = node.body else {
// Any leftover preamble statements have nowhere to go, complain and
// exit.
contextGenerator(Syntax(node)).addDiagnostics(from: MacroExpansionError.preambleWithoutBody, node: node)
return node
}
body = existingBody
case 1:
body = expandedBodies[0]
default:
contextGenerator(Syntax(node)).addDiagnostics(from: MacroExpansionError.moreThanOneBodyMacro, node: node)
body = expandedBodies[0]
}
// If there's no preamble, swap in the new body.
if preamble.isEmpty {
return node.with(\.body, body)
}
return node.with(\.body, body.with(\.statements, preamble + body.statements))
}
override func visit(_ node: CodeBlockItemListSyntax) -> CodeBlockItemListSyntax {
var newItems: [CodeBlockItemSyntax] = []
func addResult(_ node: CodeBlockItemSyntax) {
// Expand freestanding macro.
switch expandCodeBlockItem(node: node) {
case .success(let expansion):
expansion.withExpandedNode { expandedNode in
for item in expandedNode {
addResult(item)
}
}
return
case .failure:
// Expanding the macro threw an error. We don't have an expanded source.
// Retain the macro node as-is.
newItems.append(node)
case .notAMacro:
// Recurse on the child node
newItems.append(visit(node))
}
// Expand any peer macro on this item.
if case .decl(let decl) = node.item {
for peer in expandCodeBlockPeers(of: decl) {
addResult(peer)
}
extensions += expandExtensions(of: decl)
}
}
for item in node {
addResult(item)
}
// If this is the top-level code block item list, add the expanded extensions
// at its end.
if node.parent?.is(SourceFileSyntax.self) ?? false {
newItems += extensions
}
return CodeBlockItemListSyntax(newItems)
}
override func visit(_ node: MemberBlockSyntax) -> MemberBlockSyntax {
let parentDeclGroup = node
.parent?
.as(DeclSyntax.self)
var newItems: [MemberBlockItemSyntax] = []
func addResult(_ node: MemberBlockItemSyntax) {
// Expand freestanding macro.
switch expandMemberDecl(node: node) {
case .success(let expansion):
expansion.withExpandedNode { expandedNode in
for item in expandedNode {
addResult(item)
}
}
return
case .failure:
newItems.append(node)
case .notAMacro:
// Recurse on the child node.
newItems.append(visit(node))
}
// Expand any peer macro on this member.
for peer in expandMemberDeclPeers(of: node.decl) {
addResult(peer)
}
extensions += expandExtensions(of: node.decl)
}
for var item in node.members {
// Expand member attribute members attached to the declaration context.
// Note that MemberAttribute macros are _not_ applied to generated members
if let parentDeclGroup, let decl = item.decl.asProtocol(WithAttributesSyntax.self) {
var newAttributes = AttributeListSyntax(
expandAttributesFromMemberAttributeMacros(
of: item.decl,
parentDecl: parentDeclGroup
)
.map { visit($0) }
)
if !newAttributes.isEmpty {
// Transfer the trailing trivia from the old attributes to the new attributes.
// This way, we essentially insert the new attributes right after the last attribute in source
// but before its trailing trivia, keeping the trivia that separates the attribute block
// from the variable itself.
newAttributes.trailingTrivia = newAttributes.trailingTrivia + decl.attributes.trailingTrivia
newAttributes.insert(contentsOf: decl.attributes.with(\.trailingTrivia, []), at: newAttributes.startIndex)
item.decl = decl.with(\.attributes, newAttributes).cast(DeclSyntax.self)
}
}
// Recurse on the child node.
addResult(item)
}
// Expand any member macros of parent.
if let parentDeclGroup {
for member in expandMembers(of: parentDeclGroup) {
addResult(member)
}
}
/// Returns an leading trivia for the member blocks closing brace.
/// It will add a leading newline, if there is none.
var leadingTriviaForClosingBrace: Trivia {
if newItems.isEmpty {
return node.rightBrace.leadingTrivia
}
if node.rightBrace.leadingTrivia.contains(where: { $0.isNewline }) {
return node.rightBrace.leadingTrivia
}
if newItems.last?.trailingTrivia.pieces.last?.isNewline ?? false {
return node.rightBrace.leadingTrivia
} else {
return .newline + node.rightBrace.leadingTrivia
}
}
return MemberBlockSyntax(
leftBrace: node.leftBrace,
members: MemberBlockItemListSyntax(newItems),
rightBrace: node.rightBrace.with(\.leadingTrivia, leadingTriviaForClosingBrace)
)
}
override func visit(_ node: VariableDeclSyntax) -> DeclSyntax {
var node = super.visit(node).cast(VariableDeclSyntax.self)
guard !macroAttributes(attachedTo: DeclSyntax(node), ofType: AccessorMacro.Type.self).isEmpty else {
return DeclSyntax(node)
}
guard node.bindings.count == 1,
var binding = node.bindings.first
else {
contextGenerator(Syntax(node)).addDiagnostics(
from: MacroApplicationError.accessorMacroOnVariableWithMultipleBindings,
node: node
)
return DeclSyntax(node)
}
var expansion = expandAccessors(of: node, existingAccessors: binding.accessorBlock)
if expansion.accessors != binding.accessorBlock {
if binding.accessorBlock == nil {
// remove the trailing trivia of the variable declaration and move it
// to the trailing trivia of the left brace of the newly created accessor block
expansion.accessors?.leftBrace.trailingTrivia = binding.trailingTrivia
binding.trailingTrivia = []
}
if binding.initializer != nil, expansion.expandsGetSet {
// The accessor block will have a leading space, but there will already be a
// space between the variable and the to-be-removed initializer. Remove the
// leading trivia on the accessor block so we don't double up.
binding.accessorBlock = expansion.accessors?.with(\.leadingTrivia, [])
binding.initializer = nil
} else {
binding.accessorBlock = expansion.accessors
}
node.bindings = [binding]
}
return DeclSyntax(node)
}
override func visit(_ node: SubscriptDeclSyntax) -> DeclSyntax {
var node = super.visit(node).cast(SubscriptDeclSyntax.self)
node.accessorBlock = expandAccessors(of: node, existingAccessors: node.accessorBlock).accessors
return DeclSyntax(node)
}
}
// MARK: Attached macro expansions.
extension MacroApplication {
/// Get pairs of a macro attribute and the macro specification attached to `decl`.
///
/// The macros must be registered in `macroSystem`.
private func macroAttributes(
attachedTo decl: DeclSyntax
) -> [(attributeNode: AttributeSyntax, spec: MacroSpec)] {
guard let attributedNode = decl.asProtocol(WithAttributesSyntax.self) else {
return []
}
return attributedNode.attributes.compactMap {
guard case let .attribute(attribute) = $0,
let attributeName = attribute.attributeName.as(IdentifierTypeSyntax.self)?.name.text,
let macroSpec = macroSystem.lookup(attributeName)
else {
return nil