diff --git a/Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift b/Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift index 1c539aeb296..7d923c99a0a 100644 --- a/Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift +++ b/Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift @@ -633,6 +633,7 @@ private enum MacroApplicationError: DiagnosticMessage, Error { case accessorMacroOnVariableWithMultipleBindings case peerMacroOnVariableWithMultipleBindings case malformedAccessor + case accessorMacroOnLetVariable var diagnosticID: MessageID { return MessageID(domain: diagnosticDomain, id: "\(self)") @@ -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 .accessorMacroOnLetVariable: + return "accessor macro is not allowed to be applied to a 'let' variable" } } } @@ -923,6 +926,11 @@ private class MacroApplication: SyntaxRewriter { return DeclSyntax(node) } + guard node.bindingSpecifier.tokenKind != .keyword(.let) else { + contextGenerator(Syntax(node)).addDiagnostics(from: MacroApplicationError.accessorMacroOnLetVariable, node: node) + return DeclSyntax(node) + } + guard node.bindings.count == 1, let binding = node.bindings.first else { contextGenerator(Syntax(node)).addDiagnostics( from: MacroApplicationError.accessorMacroOnVariableWithMultipleBindings, diff --git a/Tests/SwiftSyntaxMacroExpansionTest/AccessorMacroTests.swift b/Tests/SwiftSyntaxMacroExpansionTest/AccessorMacroTests.swift index 471a34c7684..624831d0ce9 100644 --- a/Tests/SwiftSyntaxMacroExpansionTest/AccessorMacroTests.swift +++ b/Tests/SwiftSyntaxMacroExpansionTest/AccessorMacroTests.swift @@ -411,4 +411,21 @@ final class AccessorMacroTests: XCTestCase { indentationWidth: indentationWidth ) } + + func testAccessorOnLetVariableDeclaration() { + assertMacroExpansion( + """ + @constantOne + let x: Int = 1 + """, + expandedSource: """ + let x: Int = 1 + """, + diagnostics: [ + DiagnosticSpec(message: "accessor macro is not allowed to be applied to a 'let' variable", line: 1, column: 1) + ], + macros: ["constantOne": ConstantOneGetter.self], + indentationWidth: indentationWidth + ) + } }