-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathPropertyVariableTreeNode.swift
More file actions
232 lines (223 loc) · 9.09 KB
/
PropertyVariableTreeNode.swift
File metadata and controls
232 lines (223 loc) · 9.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import OrderedCollections
import SwiftSyntax
import SwiftSyntaxBuilder
import SwiftSyntaxMacros
/// A type storing variable and `CodingKey`
/// data using the "trie" tree algorithm.
///
/// Use `register` method to register new data and
/// use `decoding`, `encoding` to get registered
/// variable decoding/encoding expressions.
///
/// See https://en.wikipedia.org/wiki/Trie
/// for more information.
final class PropertyVariableTreeNode: Variable, VariableTreeNode {
/// All the variables registered at this node.
var variables: [any PropertyVariable] = []
/// Nested registration node associated with keys.
var children:
OrderedDictionary<CodingKeysMap.Key, PropertyVariableTreeNode> = [:]
/// The container for decoding variables linked to this node.
///
/// This is used for caching the container variable name to be reused,
/// allowing not to retrieve container repeatedly.
private var decodingContainer: TokenSyntax?
/// Whether the encoding container variable linked to this node
/// should be declared as immutable.
///
/// This is used to suppress mutability warning in case of
/// internally tagged enums.
var immutableEncodeContainer: Bool = false
}
// MARK: Decoding
extension PropertyVariableTreeNode {
/// Provides the code block list syntax for decoding individual
/// fields using registered variables at current and linked nodes.
///
/// - Parameters:
/// - data: The data to use to choose variables to be decoded.
/// - context: The context in which to perform the macro expansion.
/// - location: The decoding location for the current node.
///
/// - Returns: The generated code block list.
func decoding(
with data: CodingData?,
in context: some MacroExpansionContext,
from location: CodingLocation
) -> Generated {
let varLocation = location.context.forVariable
let decodingSyntax = CodeBlockItemListSyntax {
for variable in data?.variables ?? variables
where variable.decode ?? true {
if variable.dependenciesCount == 0 {
variable.decoding(in: context, from: varLocation)
let _ = location.coded(variable)
} else {
let _ = location.pending(variable)
}
}
}
let childrenDecodable =
data?.children.contains { _, node in
node.linkedVariables.contains { $0.decode ?? true }
}
?? children.contains { _, node in
node.linkedVariables.contains { $0.decode ?? true }
}
guard !(data?.children.isEmpty ?? children.isEmpty), childrenDecodable
else {
return .init(
containerSyntax: "", codingSyntax: decodingSyntax,
conditionalSyntax: ""
)
}
let decodableChildren = children.lazy
.filter { data?.hasKey($0.key) ?? true }
return decodableChildren.lazy
.flatMap(\.value.linkedVariables)
.map { variable in
switch variable.decodingFallback {
case .ifMissing where variable.dependenciesCount > 0:
return .ifMissing("", ifError: "")
case .onlyIfMissing where variable.dependenciesCount > 0:
return .onlyIfMissing("")
default:
return variable.decodingFallback
}
}
.reduce(.ifMissing([], ifError: []), +)
.represented(
context: location.context, nestedContainer: decodingContainer,
nestedContainerHasVariables: !self.children.lazy
.flatMap(\.value.variables)
.filter { $0.decode ?? true }.isEmpty
) { container in
self.decodingContainer = container.name
let generated = decodableChildren.map { cKey, node in
return node.decoding(
with: data?.children[cKey],
in: context,
from: location.withContainer(container, key: cKey)
)
}.reduce(
.init(
containerSyntax: "", codingSyntax: "",
conditionalSyntax: ""
), +
)
return .init(
containerSyntax: CodeBlockItemListSyntax {
generated.containerSyntax
},
codingSyntax: decodingSyntax,
conditionalSyntax: CodeBlockItemListSyntax {
generated.codingSyntax
generated.conditionalSyntax
}
)
}
}
/// Provides the code block list syntax for decoding individual
/// fields using registered variables at current and linked nodes.
///
/// - Parameters:
/// - context: The context in which to perform the macro expansion.
/// - location: The decoding location for the current node.
///
/// - Returns: The generated code block list.
func decoding(
in context: some MacroExpansionContext,
from location: CodingLocation
) -> Generated {
self.decoding(with: nil, in: context, from: location)
}
}
// MARK: Encoding
extension PropertyVariableTreeNode {
/// Provides the code block list syntax for encoding individual
/// fields using registered metadata at current and linked nodes.
///
/// - Parameters:
/// - data: The data to use to choose variables to be encoded.
/// - context: The context in which to perform the macro expansion.
/// - location: The encoding location for the current node.
///
/// - Returns: The generated code block list.
func encoding(
with data: CodingData?,
in context: some MacroExpansionContext,
to location: CodingLocation
) -> Generated {
let varLocation = location.context.forVariable
let specifier: TokenSyntax = immutableEncodeContainer ? "let" : "var"
let syntax = CodeBlockItemListSyntax {
for variable in data?.variables ?? variables
where variable.encode ?? true {
variable.encoding(in: context, to: varLocation)
let _ = location.coded(variable)
}
let childrenEncodable =
data?.children.contains { _, node in
node.linkedVariables.contains { $0.encode ?? true }
}
?? children.contains { _, node in
node.linkedVariables.contains { $0.encode ?? true }
}
if !(data?.children.isEmpty ?? children.isEmpty), childrenEncodable
{
switch location.context {
case .coder(let encoder, let type):
let container: TokenSyntax = "container"
"""
\(specifier) \(container) = \(encoder).container(keyedBy: \(type))
"""
for (cKey, node) in children
where data?.hasKey(cKey) ?? true {
node.encoding(
with: data?.children[cKey],
in: context,
to: location.withContainer(
.init(name: container, isOptional: false),
key: cKey
)
).combined()
}
case .container(let container, let key):
let nestedContainer: TokenSyntax =
"\(key.raw)_\(container.name)"
"""
\(specifier) \(nestedContainer) = \(container.name).nestedContainer(keyedBy: \(key.type), forKey: \(key.expr))
"""
for (cKey, node) in children
where data?.hasKey(cKey) ?? true {
node.encoding(
with: data?.children[cKey],
in: context,
to: location.withContainer(
.init(name: nestedContainer, isOptional: false),
key: cKey
)
).combined()
}
}
}
}
return .init(
containerSyntax: "", codingSyntax: syntax, conditionalSyntax: ""
)
}
/// Provides the code block list syntax for encoding individual
/// fields using registered metadata at current and linked nodes.
///
/// - Parameters:
/// - context: The context in which to perform the macro expansion.
/// - location: The encoding location for the current node.
///
/// - Returns: The generated code block list.
func encoding(
in context: some MacroExpansionContext,
to location: CodingLocation
) -> Generated {
self.encoding(with: nil, in: context, to: location)
}
}