Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions Sources/ReerCodableMacros/PropertyInfo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
45 changes: 29 additions & 16 deletions Sources/ReerCodableMacros/TypeInfo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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]
Expand Down Expand Up @@ -130,15 +136,15 @@ 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
default:
throw MacroError(text: "Can not handle enum raw type: \(enumRawType)")
}
} else {
raw = "\"\(name)\""
raw = "\"\(name.unescapedIdentifier)\""
}
var associated: [AssociatedValue] = []
var paramIndex = 0
Expand Down Expand Up @@ -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.")
Expand Down Expand Up @@ -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")
Expand All @@ -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") {
Expand Down Expand Up @@ -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 = """
Expand All @@ -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 """
Expand Down Expand Up @@ -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 {
"""
Expand All @@ -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)"))
"""
Expand Down Expand Up @@ -1246,3 +1253,9 @@ extension String {
return contains(".")
}
}

extension String {
var unescapedIdentifier: String {
count >= 2 && hasPrefix("`") && hasSuffix("`") ? String(dropFirst().dropLast()) : self
}
}
138 changes: 138 additions & 0 deletions Tests/ReerCodableTests/EscapedIdentifierTests.swift
Original file line number Diff line number Diff line change
@@ -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))
}
}
Loading