I'm trying out declaration macros with the following minimal example:
// in module "ExampleMacro":
import SwiftCompilerPlugin
import SwiftSyntax
import SwiftSyntaxBuilder
import SwiftSyntaxMacros
public struct DefineEmptyStructMacro: DeclarationMacro {
public static func expansion(
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
return ["struct Empty {}"]
}
}
@main
struct MacroTestPlugin: CompilerPlugin {
let providingMacros: [Macro.Type] = [
DefineEmptyStructMacro.self,
]
}
// in a different module that depends on "MacroExample":
@freestanding(declaration, names: named(Empty))
macro empty() = #externalMacro(module: "ExampleMacro", type: "DefineEmptyStructMacro")
#empty()
extension Empty: Equatable {} // error: cannot find type 'Empty' in scope
It puzzles me why Empty
isn't in scope. By my understanding, #empty
is expanded when parsed, so at the point of the extension declaration, Empty
should already be declared in the same scope. Am I using the macro wrong, or is this a bug?