Skip to content

MemberAttributeMacro arguments have parents with SyntaxProtocol.expand() but not via compiler plugin #1779

Open
@tgoyne

Description

@tgoyne

Description

// Macro definition
public struct WrapPropertiesWithParents: MemberAttributeMacro {
    public static func expansion(
        of node: AttributeSyntax,
        attachedTo declaration: some DeclGroupSyntax,
        providingAttributesFor member: some DeclSyntaxProtocol,
        in context: some MacroExpansionContext
    ) throws -> [AttributeSyntax] {
        guard member.is(VariableDeclSyntax.self) && member.hasParent else {
            return []
        }
        return [
            AttributeSyntax(attributeName: SimpleTypeIdentifierSyntax(name: .identifier("Wrapper")))
        ]
    }
}

@main
struct reproPlugin: CompilerPlugin {
    let providingMacros: [Macro.Type] = [
        WrapPropertiesWithParents.self,
    ]
}

// Test case
final class reproTests: XCTestCase {
    func testMacro() {
        assertMacroExpansion(
            """
            @WrapPropertiesWithParents
            class Foo {
                var bar: Int = 0
            }
            """,
            expandedSource: """

            class Foo {
                @Wrapper
                    var bar: Int = 0
            }
            """,
            macros:  [
                "WrapPropertiesWithParents": WrapPropertiesWithParents.self,
            ]
        )
    }
}

// Non-test usage
@WrapPropertiesWithParents
class Foo {
    var bar: Int = 0
}

This macro attaches the @Wrapper attribute to member variables if the decl passed to the macro has a parent. assertMacroExpansion does set the parent on the decl, so the test passes. The actual macro expansion when invoked by the compiler does not, so the attribute is not added and compilation succeeds (the @Wrapper attribute doesn't exist, so compilation would fail if it was added).

I don't know which of these behaviors is the intended one, but presumably they should be the same?

Steps to Reproduce

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    MacrosIssues in the SwiftSyntaxMacro… modulesbugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions