Skip to content

Commit 0cc623f

Browse files
authored
fix: added robust grouped variable declaration type detection (#3)
* fix: added robust grouped variable declaration type detection * wip: added scenario in test model
1 parent 9ac898f commit 0cc623f

File tree

2 files changed

+20
-15
lines changed

2 files changed

+20
-15
lines changed

Sources/CodableMacroPlugin/CodableMacro.swift

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -94,25 +94,30 @@ struct CodableMacro: ConformanceMacro, MemberMacro {
9494
else { return }
9595

9696
// is a grouped property declaration
97-
if decl.bindings.count > 1 {
98-
var fields: [TokenSyntax] = []
99-
var type: TypeSyntax!
97+
if decl.initializableBindings.count > 1 {
98+
var variables: [(TokenSyntax, TypeSyntax?)] = []
10099
for binding in decl.initializableBindings
101100
where binding.pattern.is(IdentifierPatternSyntax.self) {
102-
fields.append(
103-
binding.pattern
104-
.as(IdentifierPatternSyntax.self)!.identifier
105-
)
101+
variables.append((
102+
binding.pattern.as(IdentifierPatternSyntax.self)!
103+
.identifier,
104+
binding.typeAnnotation?.type
105+
))
106+
}
107+
108+
var datas: [Registrar.Node.Data] = []
109+
datas.reserveCapacity(variables.count)
106110

107-
guard let fType = binding.typeAnnotation?.type
108-
else { continue }
109-
type = fType
111+
var latestType: TypeSyntax!
112+
for (field, type) in variables.reversed() {
113+
if let type { latestType = type }
114+
datas.append(.init(field: field, type: latestType))
110115
}
111116

112-
for field in fields where type != nil {
117+
for data in datas.reversed() {
113118
registrar.add(
114-
data: .init(field: field, type: type),
115-
keyPath: [field.asKey],
119+
data: data,
120+
keyPath: [data.field.asKey],
116121
context: context
117122
)
118123
}

Tests/MetaCodableTests/Model.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import MetaCodable
33

44
@Codable
55
public struct CodableData {
6-
let groupedOne, groupedTwo, groupedThree: String
6+
let groupedOne, groupedTwo: String, groupedThree: Int
77

88
let optional: String?
99
let genericOptional: Optional<String>
@@ -50,7 +50,7 @@ public struct CodableData {
5050
let simulateWithoutArgumentWarning2: String?
5151

5252
var mutable: String = "some"
53-
var mutableOne = "any", mutableTwo, mutableThree: String
53+
var mutableOne = "any", mutableTwo: String, mutableThree: Int = 9
5454
var mutableOptional: String? = "some"
5555

5656
@CodablePath("customKey")

0 commit comments

Comments
 (0)