I'm trying out the new function body macros. I'm attempting to attach the macro to a computed variable, which I believe was part of the proposal:
When using the shorthand syntax for get-only properties, a function body macro can be applied to the property itself
However, when I do I get the error 'body' macro cannot be attached to property. Is attaching a body macro to a get only property still a supported use case?
Complete code:
// plugin
import SwiftSyntax
import SwiftCompilerPlugin
@_spi(ExperimentalLanguageFeature) import SwiftSyntaxMacros
@main
struct Plugin: CompilerPlugin {
let providingMacros: [Macro.Type] = [
HelloMacro.self,
]
}
struct HelloMacro: BodyMacro {
static func expansion(
of node: AttributeSyntax,
providingBodyFor declaration: some DeclSyntaxProtocol & WithOptionalCodeBlockSyntax,
in context: some MacroExpansionContext
) throws -> [CodeBlockItemSyntax] {
[
"""
"hello," + \(declaration.body!)
"""
]
}
}
// package
@attached(body)
public macro Hello() = #externalMacro(module: "Plugin", type: "HelloMacro")
struct Test {
@Hello
var helloFoo: String {
"Foo"
}
}
The return doesn't affect things - with or without it always returns "Foo" but does not call print("hello!")
Also - that example was using the accessor macro; I thought this would be a great use case for BodyMacro but when I try to use one, I get the error I mentioned above 'body' macro cannot be attached to property.
I'm assuming this is a bug in the compiler warning? Since I was under the impression we could attach BodyMacros to computed variables / variable getters.