When I was developing a macro, I ran into this issue. When I use a macro as a default value, there aren't any lexical contexts.
The macro for testing:
struct LexCountMacro: ExpressionMacro {
static func expansion(
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) -> ExprSyntax {
return #""\#(raw: context.lexicalContext.count)""#
}
}
When I use it directly, it works as I expected it to.
func main() {
print(#lexCount) // 1
}
But when I use it as a default value, there isn't any lexical context. I expected it to be "1" since it's called inside the function main.
func test(count: String = #lexCount) -> String { count }
func main() {
print(test()) // 0
}
I also tested to make sure the macro isn't expanding in the declaration:
struct Type {
static func test(count: String = #lexCount) -> String { count }
}
func main() {
print(Test.test()) // 0
}
Is this intended behavior?
Thanks in advance.