I'm trying to create a Swift-Macro. Intention of the Macro is:

  1. take a protocol type as input
  2. generate a class declaration which conforms to this protocol type
  3. implement protocol defined funcs

I've managed to get the class with its conformance being created. I'm now stuck at getting the funcs which are defined by the protocol. Anyone has an idea how to obtain this information? How do I get the info about the function (fooBar) defined in my sample?

Current Macro output

protocol MyProtocol {
    func fooBar() -> String
}

#myMacro(MyProtocol.self)
//expands to =>
//class MyGeneratedClass: MyProtocol { }

Current Macro implementation:

public struct MyMacro: DeclarationMacro {
    public static func expansion(of node: some SwiftSyntax.FreestandingMacroExpansionSyntax, in context: some SwiftSyntaxMacros.MacroExpansionContext) throws -> [SwiftSyntax.DeclSyntax] {

        let protocolType = try node.extractArgument()
        let inheritanceType = SimpleTypeIdentifierSyntax(name: protocolType.identifier)
        let inheritance = TypeInheritanceClauseSyntax {
            InheritedTypeListSyntax {
                InheritedTypeSyntax(typeName: inheritanceType)
            }
        }
        let mockDecl = ClassDeclSyntax(identifier: "MyGeneratedClass", inheritanceClause: inheritance) {

        }
        return [DeclSyntax(mockDecl)]
    }

}

private extension FreestandingMacroExpansionSyntax {

    func extractArgument() throws -> IdentifierExprSyntax {
        guard
            self.argumentList.count == 1,
            let memberAccessExpr = self.argumentList.first?.expression.as(MemberAccessExprSyntax.self),
            let identifierSyntax = memberAccessExpr.base?.as(IdentifierExprSyntax.self)
        else {
          throw MyError.missingArgument
        }

        return identifierSyntax
    }
}

1

There are 1 best solutions below

0
On

I tried to do the same and seems like it isn't possible unfortunately.

There was a discussion on the swift forum with a similar question:
https://forums.swift.org/t/macros-accessing-the-parent-context-of-a-syntax-node-passed-to-a-macro/64443/19