Skip to content

Conversation

@rickhohler
Copy link

Fix(MacroSystem): Validate MemberMacro application on non-group declarations (Issue #2206)

Description

This PR fixes an issue where MemberMacro attributes applied to invalid declarations (such as var properties or functions) were silently ignored by the MacroApplication walker.

Before this change, the following code would compile successfully with 0 diagnostics, even though @Test is a MemberMacro:

@Test
var x: Int

After this change, it correctly produces the expected diagnostic:
error: macro 'Test' can only be applied to a struct, enum, class, extension, or actor

Fixes: #2206

Motivation

The visit(_ : MemberBlockSyntax) method handles member macros correctly for container types. However, when a MemberMacro is applied to a standalone declaration (like a VariableDecl), the walker visits it via visitAny or specific node visitors which previously lacked logic to check for member macro attributes. This resulted in silent failures where the user would expect either an expansion or an error.

Detailed Design

  • Added a new error case MacroApplicationError.memberMacroOnInvalidDecl(macroName: String).
  • Updated MacroApplication.visitAny(_:) to inspect DeclSyntax nodes.
  • If a node has attributes matching a registered MemberMacro but does not conform to DeclGroupSyntax (and is not an ExtensionDeclSyntax), a diagnostic is now added to the context.

Verification

  • Added Tests/SwiftSyntaxMacroExpansionTest/Issue2206Tests.swift.
  • Verified that the test case fails before the fix and passes after the fix.
  • Ran full test suite for SwiftSyntaxMacroExpansion.

Checklist

  • I have read the Contributing Guide.
  • I have processed the feedback of the Swift Syntax team (if applicable).
  • I have added a test case that demonstrates the issue and verified the fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

assertMacroExpansion should emit an error if member macro is applied to declaration that can’t have members

1 participant