From 259dbfe144ccc4b305c5348917cf13a1b887c497 Mon Sep 17 00:00:00 2001 From: Andreas Bauer Date: Tue, 10 Sep 2024 14:46:09 +0200 Subject: [PATCH] Prevent adding initializer syntax to a binding --- .../SpeziAccountMacros/AccountKeyMacro.swift | 4 +++ .../AccountKeyMacroTests.swift | 36 +++++++++++++++++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/Sources/SpeziAccountMacros/AccountKeyMacro.swift b/Sources/SpeziAccountMacros/AccountKeyMacro.swift index 9f58fa7..322b8aa 100644 --- a/Sources/SpeziAccountMacros/AccountKeyMacro.swift +++ b/Sources/SpeziAccountMacros/AccountKeyMacro.swift @@ -93,6 +93,10 @@ extension AccountKeyMacro: PeerMacro { throw DiagnosticsError(syntax: binding, message: "Variable binding is missing a type annotation", id: .invalidSyntax) } + if let initializer = binding.initializer { + throw DiagnosticsError(syntax: initializer, message: "Variable binding cannot have a initializer", id: .invalidSyntax) + } + guard case let .argumentList(argumentList) = node.arguments else { throw DiagnosticsError(syntax: node, message: "Unexpected arguments passed to '@AccountKey'", id: .invalidSyntax) } diff --git a/Tests/SpeziAccountMacrosTests/AccountKeyMacroTests.swift b/Tests/SpeziAccountMacrosTests/AccountKeyMacroTests.swift index badbf5f..42e8d84 100644 --- a/Tests/SpeziAccountMacrosTests/AccountKeyMacroTests.swift +++ b/Tests/SpeziAccountMacrosTests/AccountKeyMacroTests.swift @@ -398,16 +398,46 @@ final class AccountKeyMacroTests: XCTestCase { // swiftlint:disable:this type_bo extension NotAccountDetails { var genderIdentity: GenderIdentity? { get { - self[__Key_genderIdentity.self] + self [__Key_genderIdentity.self] } set { - self[__Key_genderIdentity.self] = newValue + self [__Key_genderIdentity.self] = newValue + } + } + } + """, + diagnostics: [ + DiagnosticSpec( + message: "'@AccountKey' can only be applied to 'var' declarations inside of an extension to 'AccountDetails'", + line: 2, + column: 5 + ) + ], + macros: testMacros + ) + + assertMacroExpansion( + """ + extension AccountDetails { + @AccountKey(name: "Gender Identity", category: .personalDetails, as: GenderIdentity.self, initial: .default(.preferNotToState)) + var genderIdentity: GenderIdentity? = .male + } + """, + expandedSource: + """ + extension AccountDetails { + var genderIdentity: GenderIdentity? { + get { + self [__Key_genderIdentity.self] + } + set { + self [__Key_genderIdentity.self] = newValue } } } """, diagnostics: [ - DiagnosticSpec(message: "'@AccountKey' can only be applied to 'var' declarations inside of 'AccountDetails'", line: 2, column: 5) + DiagnosticSpec(message: "Variable binding cannot have a initializer", line: 3, column: 41) ], macros: testMacros )