Swift: Declaration name is not covered by macro

Hello!

I'm trying to generate a protocol dependent for another one using Swift macros. The implementation looks like the following:

@attached (peer, names: suffixed (Dependent),prefixed (svc))
public macro dependableService() = #externalMacro (module: "Macros", type: "DependableServiceMacro")
public struct DependableServiceMacro: PeerMacro
{
    public static func expansion (of node: AttributeSyntax,
             providingPeersOf declaration: some DeclSyntaxProtocol,
                               in context: some MacroExpansionContext)
        throws -> [DeclSyntax]
    {
        guard let baseProto = declaration.as (ExtensionDeclSyntax.self)
        else {
            return []
        }

        let nm = baseProto.extendedType.trimmedDescription
        let protoNm = nm + "Dependent"
        let varNm = "svc" + nm

        let protoDecl: DeclSyntax =
            """
            protocol \(raw: protoNm) : ServiceDependent {
                var \(raw: varNm) : \(raw: nm) { get set }
            }
            """
        return [protoDecl]
    }
}

When I try using it in my code like this

@dependableService extension MyService {}

the macro correctly expands to the following text:

protocol MyServiceDependent : ServiceDependent {
    var svcMyService : MyService {
        get
        set
    }
}

However, the compiler gives me the error:

error: declaration name 'MyServiceDependent' is not covered by macro 'dependableService'
protocol MyServiceDependent : ServiceDependent {
         ^

Do I understand correctly, that for some reason the compiler cannot deduce the name of the generated protocol based on the name of the extensible protocol, despite the presence of the names: suffixed(Dependent) attribute in the macro declaration?

Could anybody please tell me what I'm doing wrong here?

Thanks in advance

Answered by MobileTen in 788658022
  1. Is ServiceDependent implemented?
  2. Apply the macro directly to the struct or class and not the extension. What happens when this is done?
Accepted Answer
  1. Is ServiceDependent implemented?
  2. Apply the macro directly to the struct or class and not the extension. What happens when this is done?
Swift: Declaration name is not covered by macro
 
 
Q