Check if type conforms to a protocol

Is there a way in SwiftSyntax to check if the type of a member conforms to a protocol P? I would like to implement a macro that adds AccessorDeclSyntax only to properties which type implements a protocol defined by me.

1 Like

According to my understanding, this is not possible and never will.

Macros run on the syntax, and not on a program that has been fully compiled.

Consider the type that you'd like to test whether it conforms to a protocol or not. It's not really a fully-fledged type. More likely, it is a SimpleTypeIdentifierSyntax or a OptionalTypeSyntax (or another animal that conforms to TypeSyntaxProtocol).

It's only a syntactic reference to a type, because the "real" type, the one that can conform to protocols, either does not exist yet, either exists in an incomplete form (whichever is true does not matter: macros don't have access to such information).

I can illustrate a bit. Maybe the type is declared in an imported module that wasn't compiled yet? Or in another file that wasn't compiled yet? Or maybe the type requires other compilation stages until it is complete? Maybe the conformance will be added, retroactively, in another module that is still unknown at the moment your macro runs?

And I did not mention identifier resolution yet: is this thing called Int the genuine Swift.Int, or MyModule.Int? That's another question that may not have its answer at the time the macro runs.

As frustrating as it may sound for some of our wildest ideas, macros can only operate with what the programmer has provided to the macro: its arguments, and the syntax of the attached element.

3 Likes

Thanks for the answer, that's make sense! I've realized that it's not that much of a problem for my user case because if I add a code in my macro that depends on protocol P but the type doesn't implement it will just fail during compilation.

1 Like