I have a macro that generates constant declarations, but those declarations seem not to be available in the code following the macro.
The following code demonstrates the issue:
@freestanding(declaration, names: arbitrary)
public macro constantInt(name: String) = #externalMacro(module: "AgentMacroMacros", type: "ConstantIntMacro")
// just checking if arbitrary identifiers has anything to do with it
@freestanding(declaration, names: named(intValue))
public macro constantIntValue() = #externalMacro(module: "AgentMacroMacros", type: "ConstantIntValueMacro")
The definitions:
public enum ConstantIntMacro : DeclarationMacro {
public static func expansion(
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext) throws -> [DeclSyntax]
{
let str = node.argumentList.first!.expression.as(StringLiteralExprSyntax.self)!
// assume no interpolations for simplicity
guard case .stringSegment(let strSyntax) = str.segments.first else { fatalError() }
return ["let \(raw: strSyntax.content.text) = 0"]
}
}
public enum ConstantIntValueMacro : DeclarationMacro {
public static func expansion(of node: some FreestandingMacroExpansionSyntax, in context: some MacroExpansionContext) throws -> [DeclSyntax] {
["let intValue = 0"]
}
}
Client code:
func demo() {
#constantIntValue
#constantInt(name: "someInt")
intValue // error
someInt // error
}
Expanding the macros gives me this:
I'm wondering if constant declarations cannot be used in this manner, or if this is a bug.