Bryan
Bryan

Reputation: 5700

Get Raw String Literal of Type Annotation in Swift Member Macro

Context

Consider this class, decorated with a macro:

@Blah
final class Foo
{
   var title: String = ""
   var count: Int = 0
}

In the implementation of the @Blah Macro, I want to inspect the TypeSyntax for each member property and compare it. Like this:

static func expansion(of node: AttributeSyntax, providingMembersOf declaration: some DeclGroupSyntax, in context: some MacroExpansionContext) throws -> [DeclSyntax]
{
    for member in declaration.memberBlock.members
    {
        guard let type: TypeSyntax = member.decl.as(VariableDeclSyntax.self)?.bindings.first?.typeAnnotation?.type else {
           continue
        }

        // Pseudo code:
        if type.literalStringTokenValue == "String"
        {
          ...
        }
        else if type.literalStringTokenValue == "Int"
        { 
           ...
        }
    }
}

I understand that the Macro can't handle property declarations with an implied type, but in this case the type annotation is there and I just need its literal string value so I can decide how to proceed.

I've tried casting with .as(), but get a bunch of deprecation warnings. What's the correct way to do this?

Upvotes: 3

Views: 85

Answers (1)

Bryan
Bryan

Reputation: 5700

It's this:

if type.as(IdentifierTypeSyntax.self)?.name.text == "String"
{

}

I just grabbed the wrong syntax type in my original attempts. This website is tremendously useful for writing Swift Macros and helped me spot the error: https://swift-ast-explorer.com

Upvotes: 0

Related Questions