Skip to content

Commit 7e7296c

Browse files
committed
Use VariableDeclSyntax in lexicalContext
1 parent 97e13ca commit 7e7296c

3 files changed

Lines changed: 18 additions & 5 deletions

File tree

Sources/SwiftSyntaxMacroExpansion/MacroExpansion.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -415,11 +415,11 @@ public func expandAttachedMacroWithoutCollapsing<Context: MacroExpansionContext>
415415
)
416416
)
417417

418-
// Insert the accessor's parent `PatternBindingSyntax` into the lexical context
418+
// Insert the enclosing `VariableDeclSyntax` into the lexical context
419419
var context: MacroExpansionContext = context
420-
if let bindingLexicalContext = binding.asMacroLexicalContext() {
420+
if let varDeclLexicalContext = varDecl.asMacroLexicalContext() {
421421
context = PrependLexicalContextWrapperContext(
422-
prependLexicalContext: [bindingLexicalContext],
422+
prependLexicalContext: [varDeclLexicalContext],
423423
wrapping: context
424424
)
425425
}

Sources/SwiftSyntaxMacros/Syntax+LexicalContext.swift

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,19 @@ extension SyntaxProtocol {
6262
patternBinding.initializer = nil
6363
return Syntax(patternBinding)
6464

65+
// Variable declarations have their accessor blocks removed from bindings.
66+
case var varDecl as VariableDeclSyntax:
67+
varDecl = varDecl.detached
68+
varDecl.bindings = PatternBindingListSyntax(
69+
varDecl.bindings.map {
70+
var binding = $0
71+
binding.accessorBlock = nil
72+
binding.initializer = nil
73+
return binding
74+
}
75+
)
76+
return Syntax(varDecl)
77+
6578
// Freestanding macros are fine as-is because if any arguments change
6679
// the whole macro would have to be re-evaluated.
6780
case let freestandingMacro as FreestandingMacroExpansionSyntax:

Tests/SwiftSyntaxMacroExpansionTest/BodyMacroTests.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,9 +78,9 @@ struct StartTaskMacro: BodyMacro {
7878
taskName = funcDecl.name.text
7979
} else if declaration.is(AccessorDeclSyntax.self) {
8080
taskName = context.lexicalContext
81-
.compactMap { $0.as(PatternBindingSyntax.self) }
81+
.compactMap { $0.as(VariableDeclSyntax.self) }
8282
.first
83-
.flatMap { $0.pattern.as(IdentifierPatternSyntax.self)?.identifier.text }
83+
.flatMap { $0.bindings.first?.pattern.as(IdentifierPatternSyntax.self)?.identifier.text }
8484
} else {
8585
taskName = nil
8686
}

0 commit comments

Comments
 (0)