11.1 C
London
Tuesday, December 12, 2023

ios – Swift ExtensionMacro – Stack Overflow


I’m making an attempt to create a macro to assist in testing on a manufacturing app and have been making an attempt a good few various things. Extra element:

Desired Consequence:

Within the undertaking we now have numerous protocols, so given the beneath:

protocol Foo {
    var bar: Bool { get }
    func fooBar() -> Bool
}

We need to create a @Testable that will we’d use like so:

@Testable
remaining class FooSpy: Foo { }

This class could be outlined within the Testing bundle and we might anticipate the macro to broaden into:

remaining class FooSpy: Foo {

    var bar: Bool


    var fooBarExpectation = XCTestExpectation()
    var fooBarToReturn: Bool = false
    func fooBar() -> Bool {
        fooBarExpectation.fullFill()
        return fooBarToReturn
    }

}

Strategy

I’ve managed to create a PeerMacro that does the above by setting the protocol as @Testable. The difficulty is that the macro expands in place the place the protocol is and as such numerous testing associated code would not compile resulting from lack of imports and many others.

I then went on to attempt to make an ExtensionMacro in order that I might mark the Take a look at class as @Testable which is contained in the take a look at goal and thus has the required imports. The difficulty is, that with this method I do not appear to get entry to the Protocols conformance necessities. Code beneath

public struct Testable: ExtensionMacro {
    personal static let extractor = Extractor()

    public static func enlargement(of node: SwiftSyntax.AttributeSyntax, 
                                 attachedTo declaration: some SwiftSyntax.DeclGroupSyntax,
                                 providingExtensionsOf kind: some SwiftSyntax.TypeSyntaxProtocol,
                                 conformingTo protocols: [SwiftSyntax.TypeSyntax],
                                 in context: some SwiftSyntaxMacros.MacroExpansionContext) throws -> [SwiftSyntax.ExtensionDeclSyntax] {
        
// Right here I am making an attempt to get the protocol particulars (extractor beneath):
let protocolDeclaration = attempt extractor.extractProtocolDeclaration(from: declaration)

Extractor:

struct Extractor {
  func extractClassDeclaration(
    from declaration: DeclGroupSyntax
  ) throws -> ProtocolDeclSyntax {

    guard let protocolDeclaration = declaration.as(ProtocolDeclSyntax) else {
        throw TestableMacroError.invalidProtocol
    }

    return protocolDeclaration
  }
}

The apparent concern is that with the ExtensionMacro, the declaration is not the identical as when it is a PeerMacro so this code would not work.

How can I (if i even can) get the protocol particulars from a DeclGroupSyntax?

Latest news
Related news

LEAVE A REPLY

Please enter your comment!
Please enter your name here