Skip to content

Commit 97e13ca

Browse files
committed
Insert the PatternBindingSyntax into the lexical context
1 parent 8438c91 commit 97e13ca

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

Sources/SwiftSyntaxMacroExpansion/MacroExpansion.swift

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,14 @@
1212

1313
#if compiler(>=6)
1414
import SwiftBasicFormat
15+
import SwiftDiagnostics
16+
import SwiftIfConfig
1517
public import SwiftSyntax
1618
@_spi(MacroExpansion) @_spi(ExperimentalLanguageFeatures) public import SwiftSyntaxMacros
1719
#else
1820
import SwiftBasicFormat
21+
import SwiftDiagnostics
22+
import SwiftIfConfig
1923
import SwiftSyntax
2024
@_spi(MacroExpansion) @_spi(ExperimentalLanguageFeatures) import SwiftSyntaxMacros
2125
#endif
@@ -410,6 +414,16 @@ public func expandAttachedMacroWithoutCollapsing<Context: MacroExpansionContext>
410414
rightBrace: accessorBlock.rightBrace
411415
)
412416
)
417+
418+
// Insert the accessor's parent `PatternBindingSyntax` into the lexical context
419+
var context: MacroExpansionContext = context
420+
if let bindingLexicalContext = binding.asMacroLexicalContext() {
421+
context = PrependLexicalContextWrapperContext(
422+
prependLexicalContext: [bindingLexicalContext],
423+
wrapping: context
424+
)
425+
}
426+
413427
body = try attachedMacro.expansion(
414428
of: attributeNode,
415429
providingBodyFor: getterDecl,
@@ -656,3 +670,39 @@ public func collapse<Node: SyntaxProtocol>(
656670

657671
return collapsed
658672
}
673+
674+
/// Wrapper context that prepends additional `lexicalContext`
675+
/// to an existing `MacroExpansionContext`
676+
final class PrependLexicalContextWrapperContext: MacroExpansionContext {
677+
init(prependLexicalContext: [Syntax], wrapping wrappedContext: MacroExpansionContext) {
678+
self.prependLexicalContext = prependLexicalContext
679+
self.wrappedContext = wrappedContext
680+
}
681+
682+
let prependLexicalContext: [Syntax]
683+
let wrappedContext: MacroExpansionContext
684+
685+
var lexicalContext: [Syntax] {
686+
prependLexicalContext + wrappedContext.lexicalContext
687+
}
688+
689+
func makeUniqueName(_ name: String) -> TokenSyntax {
690+
wrappedContext.makeUniqueName(name)
691+
}
692+
693+
func diagnose(_ diagnostic: Diagnostic) {
694+
wrappedContext.diagnose(diagnostic)
695+
}
696+
697+
func location(
698+
of node: some SyntaxProtocol,
699+
at position: PositionInSyntaxNode,
700+
filePathMode: SourceLocationFilePathMode
701+
) -> AbstractSourceLocation? {
702+
wrappedContext.location(of: node, at: position, filePathMode: filePathMode)
703+
}
704+
705+
var buildConfiguration: (any BuildConfiguration)? {
706+
wrappedContext.buildConfiguration
707+
}
708+
}

0 commit comments

Comments
 (0)