Peer macros on a protocol

arbitrary indeed seems bad at global scope. However, I was looking if it is possible to make prefixed and suffixed name at the same time instead of previously arbitrary. For example:

@MyMacro
struct MyStruct {
...
}

which generates:

struct MyStruct {
...
    enum _Enum {}
    enum _Value {}
}

public typalias MyLibMyStructEnum = MyStruct._Enum
public typalias MyLibMyStructValue = MyStruct._Value
...

Currently, the following macro description doesn't allow that:

@attached(peer, names: prefixed(MyLib), suffixed(Value), suffixed(Enum))
public macro MyMacro() = #externalMacro(...)

with error:

error: declaration name 'MyLibMyStructValue' is not covered by macro 'MyMacro'
public typealias MyLibMyStructValue = MyStruct._Value

I can imagine that it is possible by making some ugly hacks like using two macros:

@attached(peer, names: suffixed(Value), suffixed(Enum))
public macro MyMacro() = #externalMacro(...)

which generates dummy structures:

@PrefixAndPublic
typalias MyStructEnum = MyStruct._Enum
@PrefixAndPublic
typalias MyStructValue = MyStruct._Value

and the second:

@attached(peer, names: prefixed(MyLib))
public macro PrefixAndPublic() = #externalMacro(...)

that adds public and prefixed declarations:

public typalias MyLibMyStructEnum = MyStruct._Enum
public typalias MyLibMyStructValue = MyStruct._Value

However, I was looking for some solutions that would be correct and pretty at the same time like:

@attached(peer, names: prefixed(MyLib) & suffixed(Value), prefixed(MyLib) & suffixed(Enum))
public macro MyMacro() = #externalMacro(...)

Maybe I miss something and someone could guide me to the right direction, please?

UPD: also put and issue related to sequential peer macro unfolding: Sequential peer macro (PeerMacro) is not taken in attention for compilation but conflicts with re-declarations (swift 5.9) · Issue #67506 · apple/swift · GitHub

1 Like