Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP][Macro] Emit error if AccessorMacro is applied to node that is not a variable #2624

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
11 changes: 11 additions & 0 deletions Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,7 @@ private enum MacroApplicationError: DiagnosticMessage, Error {
case accessorMacroOnVariableWithMultipleBindings
case peerMacroOnVariableWithMultipleBindings
case malformedAccessor
case accessorMacroNotOnVariableOrSubscript

var diagnosticID: MessageID {
return MessageID(domain: diagnosticDomain, id: "\(self)")
Expand All @@ -650,6 +651,8 @@ private enum MacroApplicationError: DiagnosticMessage, Error {
return """
macro returned a malformed accessor. Accessors should start with an introducer like 'get' or 'set'.
"""
case .accessorMacroNotOnVariableOrSubscript:
return "accessor macro can only be applied to a variable or subscript"
}
}
}
Expand Down Expand Up @@ -703,6 +706,14 @@ private class MacroApplication<Context: MacroExpansionContext>: SyntaxRewriter {
let attributedNode = node.asProtocol(WithAttributesSyntax.self),
!attributedNode.attributes.isEmpty
{
if (!macroAttributes(attachedTo: declSyntax, ofType: AccessorMacro.Type.self).isEmpty
&& !declSyntax.is(VariableDeclSyntax.self) && !declSyntax.is(SubscriptDeclSyntax.self))
{
contextGenerator(node).addDiagnostics(
from: MacroApplicationError.accessorMacroNotOnVariableOrSubscript,
node: declSyntax
)
}
// Apply body and preamble macros.
if let nodeWithBody = node.asProtocol(WithOptionalCodeBlockSyntax.self),
let declNodeWithBody = nodeWithBody as? any DeclSyntaxProtocol & WithOptionalCodeBlockSyntax
Expand Down
21 changes: 21 additions & 0 deletions Tests/SwiftSyntaxMacroExpansionTest/AccessorMacroTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -411,4 +411,25 @@ final class AccessorMacroTests: XCTestCase {
indentationWidth: indentationWidth
)
}

func testAccessorOnStruct() {
struct TestMacro: AccessorMacro {
static func expansion(
of node: AttributeSyntax,
providingAccessorsOf declaration: some DeclSyntaxProtocol,
in context: some MacroExpansionContext
) throws -> [AccessorDeclSyntax] {
return []
}
}

assertMacroExpansion(
"@Test struct Foo {}",
expandedSource: "struct Foo {}",
diagnostics: [
DiagnosticSpec(message: "accessor macro can only be applied to a variable or subscript", line: 1, column: 1)
],
macros: ["Test": TestMacro.self]
)
}
}