From 1c754f5bdd1b828c28f69dddcb9093459554c80a Mon Sep 17 00:00:00 2001 From: phoenix Date: Tue, 1 Dec 2026 12:33:38 +0800 Subject: [PATCH] fix: strip backticks from coding keys of escaped identifiers Escaped identifiers such as `class` / `default` used their backticked source spelling as coding keys, so {"class":1} decoded to nil. Keep the source spelling for generated Swift code and derive an unescaped keyName for coding keys in PropertyInfo, EnumCase and AssociatedValue. This covers properties, case styles, enum raw values, enum case keys, associated value labels and @CodingCase .label matching. Fixes #47 --- Sources/ReerCodableMacros/PropertyInfo.swift | 12 +- Sources/ReerCodableMacros/TypeInfo.swift | 45 ++++-- .../EscapedIdentifierTests.swift | 138 ++++++++++++++++++ 3 files changed, 175 insertions(+), 20 deletions(-) create mode 100644 Tests/ReerCodableTests/EscapedIdentifierTests.swift diff --git a/Sources/ReerCodableMacros/PropertyInfo.swift b/Sources/ReerCodableMacros/PropertyInfo.swift index f891684..20d39e1 100644 --- a/Sources/ReerCodableMacros/PropertyInfo.swift +++ b/Sources/ReerCodableMacros/PropertyInfo.swift @@ -24,6 +24,7 @@ import SwiftSyntaxMacros struct PropertyInfo { var modifiers: DeclModifierListSyntax = [] + /// Source spelling, may be backticked (e.g. `` `class` ``). Use for generated Swift code. var name: String var type: String var isOptional = false @@ -45,14 +46,17 @@ struct PropertyInfo { var isFlexibleType = false var isFlat = false + /// Name used for coding keys, without backticks. + var keyName: String { name.unescapedIdentifier } + var codingKeys: [String] { var result: [String] = keys if !caseStyles.isEmpty { - let convertedKey = KeyConverter.convert(value: name, caseStyles: caseStyles) + let convertedKey = KeyConverter.convert(value: keyName, caseStyles: caseStyles) result.append(contentsOf: convertedKey.map { "\"\($0)\"" }) } if result.isEmpty { - result.append("\"\(name)\"") + result.append("\"\(keyName)\"") } return result.reduce(into: [String]()) { array, element in @@ -66,11 +70,11 @@ struct PropertyInfo { var stringCodingKeys: [String] { var result: [String] = keys if !caseStyles.isEmpty { - let convertedKey = KeyConverter.convert(value: name, caseStyles: caseStyles) + let convertedKey = KeyConverter.convert(value: keyName, caseStyles: caseStyles) result.append(contentsOf: convertedKey.map { "\"\($0)\"" }) } if result.isEmpty { - result.append("\"\(name)\"") + result.append("\"\(keyName)\"") } return result.reduce(into: [String]()) { array, element in diff --git a/Sources/ReerCodableMacros/TypeInfo.swift b/Sources/ReerCodableMacros/TypeInfo.swift index 918716f..8ba7c28 100644 --- a/Sources/ReerCodableMacros/TypeInfo.swift +++ b/Sources/ReerCodableMacros/TypeInfo.swift @@ -32,6 +32,9 @@ struct AssociatedValue { var variableName: String { return label ?? "_\(index)" } + + /// Name used for coding keys, without backticks. + var keyName: String { variableName.unescapedIdentifier } } struct AssociatedMatch { @@ -51,7 +54,10 @@ struct PathValueMatch { } struct EnumCase { + /// Source spelling, may be backticked. Use for generated Swift code. var caseName: String + /// Name used for coding keys / raw values, without backticks. + var keyName: String { caseName.unescapedIdentifier } var rawValue: String var hasExplicitRawValue: Bool = false // [Type: Value] @@ -130,7 +136,7 @@ struct TypeInfo { raw = if index == 0 { "0" } else { String(lastIntRawValue + 1) } lastIntRawValue = Int(raw) ?? lastIntRawValue + 1 case "String": - raw = "\"\(name)\"" + raw = "\"\(name.unescapedIdentifier)\"" case "Double", "Float": raw = if index == 0 { "0" } else { String(lastIntRawValue + 1) } lastIntRawValue = Int(raw) ?? lastIntRawValue + 1 @@ -138,7 +144,7 @@ struct TypeInfo { throw MacroError(text: "Can not handle enum raw type: \(enumRawType)") } } else { - raw = "\"\(name)\"" + raw = "\"\(name.unescapedIdentifier)\"" } var associated: [AssociatedValue] = [] var paramIndex = 0 @@ -550,15 +556,16 @@ extension TypeInfo { try enumCase.associatedMatch.forEach { if let matchLabel = $0.label, !enumCase.associated.contains(where: { - guard let label = $0.label else { return false } - return "\"\(label)\"" == matchLabel + guard $0.label != nil else { return false } + return "\"\($0.keyName)\"" == matchLabel }) { throw MacroError(text: "Can not found an associated value named \(matchLabel) in case '\(enumCase.caseName)'.") } if let index = $0.index, let int = Int(index) { if int >= enumCase.associated.count { throw MacroError(text: "Can not found an associated value at index \(int) in case '\(enumCase.caseName)'.") - } else if let label = enumCase.associated[int].label { + } else if enumCase.associated[int].label != nil { + let label = enumCase.associated[int].keyName var keysFromMatchLabel = enumCase.associatedMatch.first { $0.label == "\"\(label)\"" }?.keys ?? [] keysFromMatchLabel.append(contentsOf: $0.keys) throw MacroError(text: "Associated value in case '\(enumCase.caseName)' at index \(int) has a label, use '.label(\"\(label)\", keys: \(keysFromMatchLabel.joined(separator: ", ")))' instead.") @@ -649,7 +656,7 @@ extension TypeInfo { // P2: Add explicit rawValue when it differs from the case name if ec.hasExplicitRawValue { - let quotedCaseName = "\"\(ec.caseName)\"" + let quotedCaseName = "\"\(ec.keyName)\"" if ec.rawValue != quotedCaseName { if !ec.matchOrder.contains("String") { ec.matchOrder.append("String") @@ -663,7 +670,7 @@ extension TypeInfo { } // P3/P4: Add style-converted names (case-level styles first, then enum-level) - let converted = KeyConverter.convert(value: ec.caseName, caseStyles: effectiveStyles) + let converted = KeyConverter.convert(value: ec.keyName, caseStyles: effectiveStyles) for name in converted { let quotedName = "\"\(name)\"" if !ec.matchOrder.contains("String") { @@ -1035,7 +1042,7 @@ extension TypeInfo { } else { var keys = theCase.matches["String"] ?? [] if keys.isEmpty { - keys.append("\"\(theCase.caseName)\"") + keys.append("\"\(theCase.keyName)\"") } keys.removeDuplicates() condition = """ @@ -1047,17 +1054,17 @@ extension TypeInfo { \(index > 0 ? "else " : "")if \(condition) { \(theCase.associated.compactMap { value in var keys: [String] = [] - if let label = value.label { - keys = theCase.associatedMatch.first { $0.label == "\"\(label)\"" }?.keys ?? [] + if value.label != nil { + keys = theCase.associatedMatch.first { $0.label == "\"\(value.keyName)\"" }?.keys ?? [] } else { keys = theCase.associatedMatch.first { $0.index == "\(value.index)" }?.keys ?? [] } let assocEffectiveStyles = theCase.caseStyles.uniqueMerged(with: self.caseStyles) if !assocEffectiveStyles.isEmpty && theCase.associatedMatch.isEmpty { - let convertedKeys = KeyConverter.convert(value: value.variableName, caseStyles: assocEffectiveStyles) + let convertedKeys = KeyConverter.convert(value: value.keyName, caseStyles: assocEffectiveStyles) keys.append(contentsOf: convertedKeys.map { "\"\($0)\"" }) } - keys.append("\"\(value.variableName)\"") + keys.append("\"\(value.keyName)\"") keys.removeDuplicates() let hasDefault = value.defaultValue != nil return """ @@ -1142,9 +1149,9 @@ extension TypeInfo { let postfix = $0.associated.isEmpty ? "\(associated)" : "(\(associated))" let hasAssociated = !$0.associated.isEmpty let matchValue = if hasPathValue { - firstKeyPathMatchValue(for: $0) ?? "\"\($0.caseName)\"" + firstKeyPathMatchValue(for: $0) ?? "\"\($0.keyName)\"" } else { - firstMatchValue(for: $0) ?? "\"\($0.caseName)\"" + firstMatchValue(for: $0) ?? "\"\($0.keyName)\"" } let encodeCase = if hasPathValue { """ @@ -1161,8 +1168,8 @@ extension TypeInfo { \(encodeCase) \($0.associated.compactMap { value in let encodingKey = convertAssocKeys - ? KeyConverter.convert(value: value.variableName, caseStyle: effectiveAssocStyles.first!) - : value.variableName + ? KeyConverter.convert(value: value.keyName, caseStyle: effectiveAssocStyles.first!) + : value.keyName return """ try \(hasPathValue ? "container" : "nestedContainer").encode(\(value.variableName), forKey: AnyCodingKey("\(encodingKey)")) """ @@ -1246,3 +1253,9 @@ extension String { return contains(".") } } + +extension String { + var unescapedIdentifier: String { + count >= 2 && hasPrefix("`") && hasSuffix("`") ? String(dropFirst().dropLast()) : self + } +} diff --git a/Tests/ReerCodableTests/EscapedIdentifierTests.swift b/Tests/ReerCodableTests/EscapedIdentifierTests.swift new file mode 100644 index 0000000..b821093 --- /dev/null +++ b/Tests/ReerCodableTests/EscapedIdentifierTests.swift @@ -0,0 +1,138 @@ +@testable import ReerCodable +import Testing +import Foundation + +@Codable +struct EscapedKeywordModel: Equatable { + var `class`: Int? + var `type`: Int? + var `default`: Int? + var `protocol`: Int? + var name: Int? + var `plain`: Int? +} + +@Codable +struct EscapedKeywordRequired { + var `class`: Int +} + +@Codable +struct EscapedKeywordWithCodingKey { + @CodingKey("class") + var `class`: Int? +} + +@Codable +@SnakeCase +struct EscapedKeywordSnakeCase { + var `class`: Int? +} + +@Codable +enum EscapedKeywordStringEnum: String { + case `default` + case normal +} + +@Codable +enum EscapedKeywordEnum: Equatable { + case `default` + case normal +} + +@Codable +enum EscapedKeywordAssociatedEnum: Equatable { + case `class`(`default`: Int) +} + +@Codable +@SnakeCase +enum EscapedKeywordSnakeCaseEnum: Equatable { + case `class` +} + +@Codable +enum EscapedKeywordCodingCaseEnum: Equatable { + @CodingCase(match: .string("k"), values: [.label("class", keys: "cls")]) + case `kind`(`class`: Int) +} + +extension TestReerCodable { + @Test + func escapedIdentifierDefaultKeys() throws { + let json = """ + {"class":1,"type":2,"default":3,"protocol":5,"name":6,"plain":7} + """.data(using: .utf8)! + + let model = try JSONDecoder().decode(EscapedKeywordModel.self, from: json) + #expect(model.`class` == 1) + #expect(model.`type` == 2) + #expect(model.`default` == 3) + #expect(model.`protocol` == 5) + #expect(model.name == 6) + #expect(model.`plain` == 7) + + let dict = try JSONEncoder().encode(model).stringAnyDictionary + #expect(dict.int("class") == 1) + #expect(dict.int("type") == 2) + #expect(dict.int("default") == 3) + #expect(dict.int("protocol") == 5) + #expect(dict.int("name") == 6) + #expect(dict.int("plain") == 7) + #expect(dict?.keys.contains("`class`") != true) + } + + @Test + func escapedIdentifierRequiredAndCodingKey() throws { + let required = try JSONDecoder().decode( + EscapedKeywordRequired.self, + from: #"{"class":1}"#.data(using: .utf8)! + ) + #expect(required.`class` == 1) + #expect(try JSONEncoder().encode(required).stringAnyDictionary.int("class") == 1) + + let tagged = try JSONDecoder().decode( + EscapedKeywordWithCodingKey.self, + from: #"{"class":1}"#.data(using: .utf8)! + ) + #expect(tagged.`class` == 1) + #expect(try JSONEncoder().encode(tagged).stringAnyDictionary.int("class") == 1) + } + + @Test + func escapedIdentifierWithCaseStyle() throws { + let model = try JSONDecoder().decode( + EscapedKeywordSnakeCase.self, + from: #"{"class":1}"#.data(using: .utf8)! + ) + #expect(model.`class` == 1) + #expect(try JSONEncoder().encode(model).stringAnyDictionary.int("class") == 1) + } + + @Test + func escapedIdentifierEnumKeys() throws { + #expect(String(data: try JSONEncoder().encode([EscapedKeywordStringEnum.default]), encoding: .utf8) == #"["default"]"#) + #expect(try JSONDecoder().decode([EscapedKeywordStringEnum].self, from: #"["default"]"#.data(using: .utf8)!) == [.default]) + + #expect(String(data: try JSONEncoder().encode([EscapedKeywordEnum.default]), encoding: .utf8) == #"["default"]"#) + #expect(try JSONDecoder().decode([EscapedKeywordEnum].self, from: #"["default"]"#.data(using: .utf8)!) == [.default]) + + #expect(String(data: try JSONEncoder().encode([EscapedKeywordSnakeCaseEnum.class]), encoding: .utf8) == #"["class"]"#) + #expect(try JSONDecoder().decode([EscapedKeywordSnakeCaseEnum].self, from: #"["class"]"#.data(using: .utf8)!) == [.class]) + + let associated = EscapedKeywordAssociatedEnum.class(default: 1) + let dict = try JSONEncoder().encode(associated).stringAnyDictionary + #expect((dict?["class"] as? [String: Any])?["default"] as? Int == 1) + #expect(try JSONDecoder().decode(EscapedKeywordAssociatedEnum.self, from: #"{"class":{"default":1}}"#.data(using: .utf8)!) == associated) + } + + @Test + func escapedIdentifierCodingCaseLabel() throws { + let value = try JSONDecoder().decode( + EscapedKeywordCodingCaseEnum.self, + from: #"{"k":{"cls":1}}"#.data(using: .utf8)! + ) + #expect(value == .kind(class: 1)) + } +}