Skip to content

Commit 8aae9cd

Browse files
committed
[Macros] Drop attributes from peer declaration macros after expansion
This makes sure we eliminate the macro uses from the resulting source file.
1 parent 719bdfa commit 8aae9cd

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

Sources/_SwiftSyntaxMacros/MacroSystem.swift

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,38 @@ class MacroApplication: SyntaxRewriter {
182182

183183
return .init(newItems)
184184
}
185+
186+
override func visit(_ node: FunctionDeclSyntax) -> DeclSyntax {
187+
let visitedNode = super.visit(node)
188+
189+
// FIXME: Generalize this to DeclSyntax, once we have attributes.
190+
// Visit the node first.
191+
192+
guard let visitedFunc = visitedNode.as(FunctionDeclSyntax.self),
193+
let attributes = visitedFunc.attributes else {
194+
return visitedNode
195+
}
196+
197+
// Remove any attached attributes.
198+
let newAttributes = attributes.filter {
199+
guard case let .customAttribute(customAttr) = $0 else {
200+
return true
201+
}
202+
203+
guard let attributeName = customAttr.attributeName.as(SimpleTypeIdentifierSyntax.self)?.name.text,
204+
let macro = macroSystem.macros[attributeName] else {
205+
return true
206+
}
207+
208+
return !(macro is PeerDeclarationMacro.Type)
209+
}
210+
211+
if newAttributes.isEmpty {
212+
return DeclSyntax(visitedFunc.withAttributes(nil))
213+
}
214+
215+
return DeclSyntax(visitedFunc.withAttributes(AttributeListSyntax(newAttributes)))
216+
}
185217
}
186218

187219
extension MacroApplication {

Tests/SwiftSyntaxMacrosTest/MacroSystemTests.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -507,7 +507,7 @@ final class MacroSystemTests: XCTestCase {
507507
func f(a: Int, for b: String, _ value: Double) async -> String { }
508508
""",
509509
"""
510-
@addCompletionHandler
510+
511511
func f(a: Int, for b: String, _ value: Double) async -> String { }
512512
513513
func f(a: Int, for b: String, _ value: Double, completionHandler: (String) -> Void) {

0 commit comments

Comments
 (0)