I'm trying to create a macro that generates some boilerplate code like this:
protocol Foo {
associatedtype Bar
}
extension Foo where Self: View, Bar: View {
func doDefaultThing() {
// implementation here
}
}
The freestanding macro that generates this code results in an error on the generated extensions that says Macro expansion cannot introduce extension
. Having read through these forums, it seems like there is a recent update in the form of extension macros that would allow this if I create an additional extension macro and generate the boilerplate code like this:
@AddDefaultThingExtension
protocol Foo {
associatedtype Bar
}
In theory, this would allow the extension macro to generate the second part:
extension Foo where Self: View, Bar: View {
func doDefaultThing() {
// implementation here
}
}
Having read the proposal and review thread and played around with implementing this in Xcode, I'm still coming up short on understanding how to implement the extension macro. The necessary type signature is:
public struct AddDefaultThingExtensionMacro: ExtensionMacro {
public static func expansion(of node: AttributeSyntax, attachedTo declaration: some DeclGroupSyntax, providingExtensionsOf type: some TypeSyntaxProtocol, conformingTo protocols: [TypeSyntax], in context: some MacroExpansionContext) throws -> [ExtensionDeclSyntax] {
// Missing good examples of how to create ExtensionDeclSyntax
}
}
In working on other macros, I've found Doug Gregor's Swift Macro Examples repo to be invaluable. But as this is a new update, I don't see any examples of it in this repo or anywhere else yet!
Does anyone know of good examples of Extension Macros or is anyone able to provide me with some advice for how to go about implementing this:
public static func expansion(of node: AttributeSyntax, attachedTo declaration: some DeclGroupSyntax, providingExtensionsOf type: some TypeSyntaxProtocol, conformingTo protocols: [TypeSyntax], in context: some MacroExpansionContext) throws -> [ExtensionDeclSyntax] { }
so as to generate the output:
extension Foo where Self: View, Bar: View {
func doDefaultThing() {
// implementation here
}
}
Thanks!