swiftswift-macroswift-syntax

Attaching Swift Macro to Closure


I have been able to create a Swift Macro that attaches to function declarations like

@DoThing
func foo() {
}

converting to

func foo() {
    thing()
}

This is a simplified version of my macro but it does basically this.

I would like to do something like @MainActor can achieve in closures. Something like this.

Task { @DoThing [capture] in
}
Task { [capture] in
    thing()
}

I would like to be able to support all closure types, even ones that have parameters. Is there any existing Macro type that allows you to see an entire closure declaration?


Solution

  • After looking at the swift-syntax repo it seems like very recently they have added the ability to add to function closures in BodyMacro
    https://github.com/swiftlang/swift-syntax/blob/main/Sources/SwiftSyntaxMacros/MacroProtocols/BodyMacro.swift

    Doesn't seem to be in a release yet.