Skip to content

Commit 88bd3ba

Browse files
authored
Merge branch 'main' into TriviaPiece.isComment
2 parents d99236f + 89dd2bd commit 88bd3ba

File tree

22 files changed

+699
-117
lines changed

22 files changed

+699
-117
lines changed

CodeGeneration/Sources/SyntaxSupport/Utils.swift

Lines changed: 6 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -42,35 +42,19 @@ public func lowercaseFirstWord(name: String) -> String {
4242
extension SwiftSyntax.Trivia {
4343
/// Make a new trivia from a (possibly multi-line) string, prepending `///`
4444
/// to each line and creating a `.docLineComment` trivia piece for each line.
45-
public static func docCommentTrivia(from string: String?) -> SwiftSyntax.Trivia {
46-
guard let string else {
47-
return []
48-
}
49-
50-
let lines = string.split(separator: "\n", omittingEmptySubsequences: false)
51-
let pieces = lines.enumerated().map { (index, line) in
52-
var line = line
53-
if index != lines.count - 1 {
54-
line = "\(line)\n"
55-
}
56-
return SwiftSyntax.TriviaPiece.docLineComment("/// \(line)")
57-
}
58-
return SwiftSyntax.Trivia(pieces: pieces)
45+
public static func docCommentTrivia(from string: String?) -> Self {
46+
guard let string else { return [] }
47+
let lines = string.split(separator: "\n", omittingEmptySubsequences: false).map { "/// \($0)" }
48+
return .init(pieces: lines.flatMap { [.docLineComment($0), .newlines(1)] })
5949
}
6050

6151
/// Make a new trivia by joining together ``SwiftSyntax/TriviaPiece``s from `joining`,
6252
/// and gluing them together with pieces from `separator`.
6353
public init(
6454
joining items: [SwiftSyntax.Trivia],
65-
separator: SwiftSyntax.Trivia = SwiftSyntax.Trivia(pieces: [TriviaPiece.newlines(1), TriviaPiece.docLineComment("///"), TriviaPiece.newlines(1)])
55+
separator: SwiftSyntax.Trivia = .init(pieces: [.docLineComment("///"), .newlines(1)])
6656
) {
67-
68-
self.init(
69-
pieces:
70-
items
71-
.filter { !$0.isEmpty }
72-
.joined(separator: separator)
73-
)
57+
self.init(pieces: items.filter { !$0.isEmpty }.joined(separator: separator))
7458
}
7559
}
7660

CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxBaseNodesFile.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ let syntaxBaseNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
173173

174174
try! StructDeclSyntax(
175175
"""
176-
\(documentation)
176+
\(documentation)\
177177
\(node.apiAttributes())\
178178
public struct \(node.kind.syntaxType): \(node.kind.protocolType), SyntaxHashable
179179
"""

CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxCollectionsFile.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ let syntaxCollectionsFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
2626

2727
try! StructDeclSyntax(
2828
"""
29-
\(documentation)
29+
\(documentation)\
3030
\(node.node.apiAttributes())\
3131
public struct \(node.kind.syntaxType): SyntaxCollection, SyntaxHashable
3232
"""

CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxNodesFile.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ func syntaxNode(nodesStartingWith: [Character]) -> SourceFileSyntax {
2727
"""
2828
// MARK: - \(node.kind.syntaxType)
2929
30-
\(SwiftSyntax.Trivia(joining: [node.documentation, node.experimentalDocNote, node.grammar, node.containedIn]))
30+
\(SwiftSyntax.Trivia(joining: [node.documentation, node.experimentalDocNote, node.grammar, node.containedIn]))\
3131
\(node.node.apiAttributes())\
3232
public struct \(node.kind.syntaxType): \(node.baseType.syntaxBaseName)Protocol, SyntaxHashable, \(node.base.leafProtocolType)
3333
"""
@@ -55,7 +55,7 @@ func syntaxNode(nodesStartingWith: [Character]) -> SourceFileSyntax {
5555

5656
try! InitializerDeclSyntax(
5757
"""
58-
\(node.generateInitializerDocComment())
58+
\(node.generateInitializerDocComment())\
5959
\(node.generateInitializerDeclHeader())
6060
"""
6161
) {
@@ -137,7 +137,7 @@ func syntaxNode(nodesStartingWith: [Character]) -> SourceFileSyntax {
137137

138138
try! VariableDeclSyntax(
139139
"""
140-
\(child.documentation)
140+
\(child.documentation)\
141141
\(child.apiAttributes)public var \(child.varOrCaseName.backtickedIfNeeded): \(type)
142142
"""
143143
) {

CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxTraitsFile.swift

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,9 @@ let syntaxTraitsFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
2121
"""
2222
// MARK: - \(trait.protocolName)
2323
24-
\(trait.documentation)
24+
\(trait.documentation)\
2525
public protocol \(trait.protocolName): SyntaxProtocol\(raw:
26-
trait.baseKind != nil
27-
? ", \(trait.baseKind!.protocolType)"
28-
: ""
26+
trait.baseKind == nil ? "" : ", \(trait.baseKind!.protocolType)"
2927
)
3028
"""
3129
) {
@@ -34,7 +32,7 @@ let syntaxTraitsFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
3432

3533
DeclSyntax(
3634
"""
37-
\(child.documentation)
35+
\(child.documentation)\
3836
\(child.apiAttributes)var \(child.varOrCaseName): \(child.syntaxNodeKind.syntaxType)\(raw: questionMark) { get set }
3937
"""
4038
)

CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntaxbuilder/ResultBuildersFile.swift

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ let resultBuildersFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
2323

2424
try! StructDeclSyntax(
2525
"""
26-
2726
// MARK: - \(type.resultBuilderType)
2827
2928
@resultBuilder

Release Notes/511.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@
3636
- Description: `SwiftParser` adds an extension on `String` to check if it can be used as an identifier in a given context.
3737
- Pull Request: https://github.com/apple/swift-syntax/pull/2434
3838

39+
- `SyntaxProtocol.asMacroLexicalContext()` and `allMacroLexicalContexts(enclosingSyntax:)`
40+
- Description: Produce the lexical context for a given syntax node (if it has one), or the entire stack of lexical contexts enclosing a syntax node, for use in macro expansion.
41+
- Pull request: https://github.com/apple/swift-syntax/pull/1554
42+
3943
- `TriviaPiece.isComment`
4044
- Description: `TriviaPiece` now has a computed property `isComment` that returns `true` if the trivia piece is a comment.
4145
- Pull Request: https://github.com/apple/swift-syntax/pull/2469
@@ -97,6 +101,11 @@
97101
- The new cases cover the newly introduced `ThrowsClauseSyntax`
98102
- Pull request: https://github.com/apple/swift-syntax/pull/2379
99103
- Migration steps: In exhaustive switches over `SyntaxEnum` and `SyntaxKind`, cover the new case.
104+
105+
- `MacroExpansionContext` now requires a property `lexicalContext`:
106+
- Description: The new property provides the lexical context in which the macro is expanded, and has several paired API changes. Types that conform to `MacroExpansionContext` will need to implement this property. Additionally, the `HostToPluginMessage` cases `expandFreestandingMacro` and `expandAttachedMacro` now include an optional `lexicalContext`. Finally, the `SyntaxProtocol.expand(macros:in:indentationWidth:)` syntactic expansion operation has been deprecated in favor of a new version `expand(macros:contextGenerator:indentationWidth:)` that takes a function produces a new macro expansion context for each expansion.
107+
- Pull request: https://github.com/apple/swift-syntax/pull/1554
108+
- Migration steps: Add the new property `lexicalContext` to any `MacroExpansionContext`-conforming types. If implementing the host-to-plugin message protocol, add support for `lexicalContext`. For macro expansion operations going through `SyntaxProtocol.expand`, provide a context generator that creates a fresh context including the lexical context.
100109

101110

102111
## Template

Sources/SwiftCompilerPluginMessageHandling/CompilerPluginMessageHandler.swift

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -114,12 +114,19 @@ extension CompilerPluginMessageHandler {
114114
)
115115
try self.sendMessage(.getCapabilityResult(capability: capability))
116116

117-
case .expandFreestandingMacro(let macro, let macroRole, let discriminator, let expandingSyntax):
117+
case .expandFreestandingMacro(
118+
let macro,
119+
let macroRole,
120+
let discriminator,
121+
let expandingSyntax,
122+
let lexicalContext
123+
):
118124
try expandFreestandingMacro(
119125
macro: macro,
120126
macroRole: macroRole,
121127
discriminator: discriminator,
122-
expandingSyntax: expandingSyntax
128+
expandingSyntax: expandingSyntax,
129+
lexicalContext: lexicalContext
123130
)
124131

125132
case .expandAttachedMacro(
@@ -130,7 +137,8 @@ extension CompilerPluginMessageHandler {
130137
let declSyntax,
131138
let parentDeclSyntax,
132139
let extendedTypeSyntax,
133-
let conformanceListSyntax
140+
let conformanceListSyntax,
141+
let lexicalContext
134142
):
135143
try expandAttachedMacro(
136144
macro: macro,
@@ -140,7 +148,8 @@ extension CompilerPluginMessageHandler {
140148
declSyntax: declSyntax,
141149
parentDeclSyntax: parentDeclSyntax,
142150
extendedTypeSyntax: extendedTypeSyntax,
143-
conformanceListSyntax: conformanceListSyntax
151+
conformanceListSyntax: conformanceListSyntax,
152+
lexicalContext: lexicalContext
144153
)
145154

146155
case .loadPluginLibrary(let libraryPath, let moduleName):

Sources/SwiftCompilerPluginMessageHandling/Macros.swift

Lines changed: 37 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,18 +23,41 @@ extension CompilerPluginMessageHandler {
2323
try provider.resolveMacro(moduleName: ref.moduleName, typeName: ref.typeName)
2424
}
2525

26+
/// Resolve the lexical context
27+
private static func resolveLexicalContext(
28+
_ lexicalContext: [PluginMessage.Syntax]?,
29+
sourceManager: SourceManager,
30+
operatorTable: OperatorTable,
31+
fallbackSyntax: some SyntaxProtocol
32+
) -> [Syntax] {
33+
// If we weren't provided with a lexical context, retrieve it from the
34+
// syntax node we were given. This is for dealing with older compilers.
35+
guard let lexicalContext else {
36+
return fallbackSyntax.allMacroLexicalContexts()
37+
}
38+
39+
return lexicalContext.map { sourceManager.add($0, foldingWith: operatorTable) }
40+
}
41+
2642
/// Expand `@freestainding(XXX)` macros.
2743
func expandFreestandingMacro(
2844
macro: PluginMessage.MacroReference,
2945
macroRole pluginMacroRole: PluginMessage.MacroRole?,
3046
discriminator: String,
31-
expandingSyntax: PluginMessage.Syntax
47+
expandingSyntax: PluginMessage.Syntax,
48+
lexicalContext: [PluginMessage.Syntax]?
3249
) throws {
3350
let sourceManager = SourceManager()
3451
let syntax = sourceManager.add(expandingSyntax, foldingWith: .standardOperators)
3552

3653
let context = PluginMacroExpansionContext(
3754
sourceManager: sourceManager,
55+
lexicalContext: Self.resolveLexicalContext(
56+
lexicalContext,
57+
sourceManager: sourceManager,
58+
operatorTable: .standardOperators,
59+
fallbackSyntax: syntax
60+
),
3861
expansionDiscriminator: discriminator
3962
)
4063

@@ -85,14 +108,10 @@ extension CompilerPluginMessageHandler {
85108
declSyntax: PluginMessage.Syntax,
86109
parentDeclSyntax: PluginMessage.Syntax?,
87110
extendedTypeSyntax: PluginMessage.Syntax?,
88-
conformanceListSyntax: PluginMessage.Syntax?
111+
conformanceListSyntax: PluginMessage.Syntax?,
112+
lexicalContext: [PluginMessage.Syntax]?
89113
) throws {
90114
let sourceManager = SourceManager()
91-
let context = PluginMacroExpansionContext(
92-
sourceManager: sourceManager,
93-
expansionDiscriminator: discriminator
94-
)
95-
96115
let attributeNode = sourceManager.add(
97116
attributeSyntax,
98117
foldingWith: .standardOperators
@@ -107,6 +126,17 @@ extension CompilerPluginMessageHandler {
107126
return placeholderStruct.inheritanceClause!.inheritedTypes
108127
}
109128

129+
let context = PluginMacroExpansionContext(
130+
sourceManager: sourceManager,
131+
lexicalContext: Self.resolveLexicalContext(
132+
lexicalContext,
133+
sourceManager: sourceManager,
134+
operatorTable: .standardOperators,
135+
fallbackSyntax: declarationNode
136+
),
137+
expansionDiscriminator: discriminator
138+
)
139+
110140
// TODO: Make this a 'String?' and remove non-'hasExpandMacroResult' branches.
111141
let expandedSources: [String]?
112142
do {

Sources/SwiftCompilerPluginMessageHandling/PluginMacroExpansionContext.swift

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,9 @@ fileprivate extension Syntax {
192192
class PluginMacroExpansionContext {
193193
private var sourceManger: SourceManager
194194

195+
/// The lexical context of the macro expansion described by this context.
196+
let lexicalContext: [Syntax]
197+
195198
/// The macro expansion discriminator, which is used to form unique names
196199
/// when requested.
197200
///
@@ -208,8 +211,9 @@ class PluginMacroExpansionContext {
208211
/// macro.
209212
internal private(set) var diagnostics: [Diagnostic] = []
210213

211-
init(sourceManager: SourceManager, expansionDiscriminator: String = "") {
214+
init(sourceManager: SourceManager, lexicalContext: [Syntax], expansionDiscriminator: String = "") {
212215
self.sourceManger = sourceManager
216+
self.lexicalContext = lexicalContext
213217
self.expansionDiscriminator = expansionDiscriminator
214218
}
215219
}

Sources/SwiftCompilerPluginMessageHandling/PluginMessages.swift

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ public enum HostToPluginMessage: Codable {
2323
macro: PluginMessage.MacroReference,
2424
macroRole: PluginMessage.MacroRole? = nil,
2525
discriminator: String,
26-
syntax: PluginMessage.Syntax
26+
syntax: PluginMessage.Syntax,
27+
lexicalContext: [PluginMessage.Syntax]? = nil
2728
)
2829

2930
/// Expand an '@attached' macro.
@@ -35,7 +36,8 @@ public enum HostToPluginMessage: Codable {
3536
declSyntax: PluginMessage.Syntax,
3637
parentDeclSyntax: PluginMessage.Syntax?,
3738
extendedTypeSyntax: PluginMessage.Syntax?,
38-
conformanceListSyntax: PluginMessage.Syntax?
39+
conformanceListSyntax: PluginMessage.Syntax?,
40+
lexicalContext: [PluginMessage.Syntax]? = nil
3941
)
4042

4143
/// Optionally implemented message to load a dynamic link library.

Sources/SwiftSyntax/generated/SyntaxTraits.swift

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414

1515
// MARK: - BracedSyntax
1616

17-
1817
public protocol BracedSyntax: SyntaxProtocol {
1918
/// ### Tokens
2019
///
@@ -62,7 +61,6 @@ public extension SyntaxProtocol {
6261

6362
// MARK: - DeclGroupSyntax
6463

65-
6664
public protocol DeclGroupSyntax: SyntaxProtocol, DeclSyntaxProtocol {
6765
var attributes: AttributeListSyntax {
6866
get
@@ -120,7 +118,6 @@ public extension SyntaxProtocol {
120118

121119
// MARK: - EffectSpecifiersSyntax
122120

123-
124121
public protocol EffectSpecifiersSyntax: SyntaxProtocol {
125122
var unexpectedBeforeAsyncSpecifier: UnexpectedNodesSyntax? {
126123
get
@@ -182,7 +179,6 @@ public extension SyntaxProtocol {
182179

183180
// MARK: - FreestandingMacroExpansionSyntax
184181

185-
186182
public protocol FreestandingMacroExpansionSyntax: SyntaxProtocol {
187183
/// ### Tokens
188184
///
@@ -266,7 +262,6 @@ public extension SyntaxProtocol {
266262

267263
// MARK: - NamedDeclSyntax
268264

269-
270265
public protocol NamedDeclSyntax: SyntaxProtocol {
271266
/// ### Tokens
272267
///
@@ -350,7 +345,6 @@ public extension SyntaxProtocol {
350345

351346
// MARK: - ParenthesizedSyntax
352347

353-
354348
public protocol ParenthesizedSyntax: SyntaxProtocol {
355349
/// ### Tokens
356350
///
@@ -398,7 +392,6 @@ public extension SyntaxProtocol {
398392

399393
// MARK: - WithAttributesSyntax
400394

401-
402395
public protocol WithAttributesSyntax: SyntaxProtocol {
403396
var attributes: AttributeListSyntax {
404397
get
@@ -435,7 +428,6 @@ public extension SyntaxProtocol {
435428

436429
// MARK: - WithCodeBlockSyntax
437430

438-
439431
public protocol WithCodeBlockSyntax: SyntaxProtocol {
440432
var body: CodeBlockSyntax {
441433
get
@@ -518,7 +510,6 @@ public extension SyntaxProtocol {
518510

519511
// MARK: - WithModifiersSyntax
520512

521-
522513
public protocol WithModifiersSyntax: SyntaxProtocol {
523514
var modifiers: DeclModifierListSyntax {
524515
get
@@ -555,7 +546,6 @@ public extension SyntaxProtocol {
555546

556547
// MARK: - WithOptionalCodeBlockSyntax
557548

558-
559549
public protocol WithOptionalCodeBlockSyntax: SyntaxProtocol {
560550
var body: CodeBlockSyntax? {
561551
get
@@ -592,7 +582,6 @@ public extension SyntaxProtocol {
592582

593583
// MARK: - WithStatementsSyntax
594584

595-
596585
public protocol WithStatementsSyntax: SyntaxProtocol {
597586
var statements: CodeBlockItemListSyntax {
598587
get
@@ -629,7 +618,6 @@ public extension SyntaxProtocol {
629618

630619
// MARK: - WithTrailingCommaSyntax
631620

632-
633621
public protocol WithTrailingCommaSyntax: SyntaxProtocol {
634622
/// ### Tokens
635623
///

0 commit comments

Comments
 (0)