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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
use proc_macro2::Span;
use syn::{parse_quote, spanned::Spanned, Expr, Generics, Ident, Lifetime, Stmt, Type};
use crate::{
common::FieldIdent,
de::{
builders::DeserializeBuilderExt,
common::{
builder_element_field_visitor, deserialize_option_value_expr, one_stop_field_expression,
},
},
derive::{DeriveError, DeriveResult},
options::{
records::fields::{ChildOpts, FieldValueGroupOpts},
AllowUnknown, ElementOrder, FieldWithOpts, IgnoreComments, IgnoreWhitespace,
},
};
pub struct SeqLoopAccessor {
allow_unknown_children: AllowUnknown,
order: ElementOrder,
ignore_whitespace: IgnoreWhitespace,
ignore_comments: IgnoreComments,
}
impl SeqLoopAccessor {
pub fn new(
allow_unknown_children: AllowUnknown,
order: ElementOrder,
ignore_whitespace: IgnoreWhitespace,
ignore_comments: IgnoreComments,
) -> Self {
Self {
allow_unknown_children,
order,
ignore_whitespace,
ignore_comments,
}
}
pub fn field_definitions<
F: IntoIterator<Item = FieldWithOpts<FieldIdent, FieldValueGroupOpts>>,
>(
&self,
fields: F,
) -> DeriveResult<Vec<Stmt>> {
fields
.into_iter()
.map::<DeriveResult<Stmt>, _>(
|FieldWithOpts {
field_ident,
field_type,
options,
..
}| {
let builder_initializer: syn::Expr = match options {
FieldValueGroupOpts::Value(_) => parse_quote! {
::core::option::Option::<#field_type>::None
},
FieldValueGroupOpts::Group(_) => parse_quote! {
<#field_type as ::xmlity::de::DeserializationGroup>::builder()
},
};
let mut builder_field_ident = field_ident.to_named_ident().into_owned();
builder_field_ident.set_span(Span::call_site());
Ok(parse_quote! {
let mut #builder_field_ident = #builder_initializer;
})
},
)
.collect()
}
pub fn access_loop<F: IntoIterator<Item = FieldWithOpts<FieldIdent, FieldValueGroupOpts>>>(
&self,
fields: F,
seq_access: &Expr,
seq_access_ty: &Type,
visitor_lifetime: &Lifetime,
) -> DeriveResult<Vec<Stmt>> {
let Self {
allow_unknown_children,
order,
ignore_whitespace,
ignore_comments,
} = self;
let whitespace_ty: syn::Type = parse_quote! {::xmlity::types::utils::Whitespace};
let ignore_whitespace_expression: Vec<Stmt> = match ignore_whitespace {
IgnoreWhitespace::Any => {
parse_quote! {
if let Ok(Some(_)) = ::xmlity::de::SeqAccess::next_element::<#whitespace_ty>(#seq_access) {
continue;
}
}
}
IgnoreWhitespace::None => {
vec![]
}
};
let comment_ty: syn::Type = parse_quote! {::xmlity::value::XmlComment};
let ignore_comments_expression: Vec<Stmt> = match ignore_comments {
IgnoreComments::Any => {
parse_quote! {
if let Ok(Some(_)) = ::xmlity::de::SeqAccess::next_element::<#comment_ty>(#seq_access) {
continue;
}
}
}
IgnoreComments::None => {
vec![]
}
};
let ignored_any_ty: syn::Type = parse_quote! {::xmlity::types::utils::IgnoredAny};
match order {
ElementOrder::Strict => {
let end_check: Vec<Stmt> = match allow_unknown_children {
AllowUnknown::Any => {
return Err(DeriveError::custom(
"An unknown element in any position is not allowed in strict order",
))
}
AllowUnknown::AtEnd => {
//Ignore whatever is left
Vec::new()
}
AllowUnknown::None => {
//Check that nothing is left
parse_quote! {
if let Ok(Some(_)) = ::xmlity::de::SeqAccess::next_element::<#ignored_any_ty>(#seq_access) {
return Err(::xmlity::de::Error::custom("Unexpected element at end of sequence."));
}
}
}
};
let field_visits = fields.into_iter().map::<DeriveResult<(_, syn::Expr, Vec<Stmt>)>, _>(|f| {
let (condition, deserialize_stmts) = match &f.options {
FieldValueGroupOpts::Value(child_opts) => {
let wrapper_ident = Ident::new("__W", Span::call_site());
let empty_generics: Generics = parse_quote!();
let (prefix, wrapped_de_type, unwrap_function) = match child_opts {
ChildOpts::Value(_) => (Vec::new(), None, None),
ChildOpts::Element(element_opts) => {
let builder = element_opts.to_builder(
&f.field_ident,
&wrapper_ident,
&empty_generics,
&f.field_type,
);
let deserialize_wrapper_def: Vec<Stmt> = {
let def = builder.struct_definition();
let trait_impl = builder.deserialize_trait_impl()?;
parse_quote!(
#def
#trait_impl
)
};
let struct_type: Type = parse_quote!(#wrapper_ident);
let unwrap_function = builder.unwrap_expression();
(
deserialize_wrapper_def,
Some(struct_type),
Some(unwrap_function),
)
}
};
let value_expr = one_stop_field_expression(
seq_access_ty,
seq_access,
visitor_lifetime,
wrapped_de_type.as_ref().unwrap_or(&f.field_type),
f.field_ident.to_string().as_str(),
child_opts.default_or_else().as_ref(),
unwrap_function,
);
let builder_ident = f.field_ident.to_named_ident();
let condition: syn::Expr = parse_quote!(
::core::option::Option::is_none(&#builder_ident)
);
let deserialize_stmts = parse_quote!(
#(#prefix)*
#builder_ident = ::core::option::Option::Some(#value_expr);
);
(condition, deserialize_stmts)
}
FieldValueGroupOpts::Group(_) => {
let builder_ident = f.field_ident.to_named_ident();
let condition: syn::Expr = parse_quote!(
!::xmlity::de::DeserializationGroupBuilder::elements_done(&#builder_ident)
);
let deserialize_expr: Expr = parse_quote!(
::xmlity::de::DeserializationGroupBuilder::contribute_elements(&mut #builder_ident, ::xmlity::de::SeqAccess::sub_access(#seq_access)?)?
);
let deserialize_stmts = parse_quote! {
if !#deserialize_expr {
return ::core::result::Result::Err(::xmlity::de::Error::custom("Failed to deserialize group"));
}
};
(condition, deserialize_stmts)
}
};
Ok((f, condition, deserialize_stmts))
}).collect::<Result<Vec<_>, _>>()?;
let if_statements =
field_visits
.into_iter()
.map(|(_f, condition, deserialize_stmts)| {
parse_quote!(
if #condition {
#(#deserialize_stmts)*
}
)
});
// Bind the if_statements together to if else if else if else
let if_statements: Option<proc_macro2::TokenStream> =
if_statements.reduce(|acc, e| {
parse_quote! {
#acc else #e
}
});
let end_statement: Vec<Stmt> = parse_quote!(
#(#end_check)*
break;
);
let if_statements = if let Some(if_statements) = if_statements {
parse_quote! {
#if_statements else {
#(#end_statement)*
}
}
} else {
end_statement
};
Ok(parse_quote! {
loop {
#(#ignore_whitespace_expression)*
#(#ignore_comments_expression)*
#(#if_statements)*
}
})
}
ElementOrder::None => {
let field_visits = builder_element_field_visitor(
seq_access,
|field| {
let field = field.to_named_ident();
parse_quote!(#field)
},
fields,
parse_quote! {break;},
match order {
ElementOrder::Strict => parse_quote! {break;},
ElementOrder::None => parse_quote! {continue;},
},
parse_quote! {continue;},
parse_quote! {},
false,
)?;
let skip_unknown: Vec<Stmt> = match allow_unknown_children {
AllowUnknown::Any => {
// Currently, allow any unknown is not supported with strict ordering.
if matches!(order, ElementOrder::Strict) {
return Err(DeriveError::custom(
"An unknown element in any position is not allowed in strict order",
));
}
let skip_ident = Ident::new("__skip", seq_access.span());
parse_quote! {
let #skip_ident = ::core::result::Result::unwrap_or(
::xmlity::de::SeqAccess::next_element::<#ignored_any_ty>(#seq_access),
None
);
if ::core::option::Option::is_none(&#skip_ident) {
break;
}
continue;
}
}
AllowUnknown::AtEnd => {
//Ignore whatever is left
parse_quote! {
break;
}
}
AllowUnknown::None => {
//Check that nothing is left
let skip_ident = Ident::new("__skip", seq_access.span());
parse_quote! {
let #skip_ident = ::core::result::Result::unwrap_or(
::xmlity::de::SeqAccess::next_element::<#ignored_any_ty>(#seq_access),
None
);
if ::core::option::Option::is_none(&#skip_ident) {
break;
}
return Err(::xmlity::de::Error::unknown_child());
}
}
};
Ok(parse_quote! {
loop {
#(#ignore_whitespace_expression)*
#(#ignore_comments_expression)*
#(#field_visits)*
#(#skip_unknown)*
}
})
}
}
}
pub fn value_expressions<
F: IntoIterator<Item = FieldWithOpts<FieldIdent, FieldValueGroupOpts>>,
>(
&self,
fields: F,
visitor_lifetime: &syn::Lifetime,
error_type: &syn::Type,
) -> DeriveResult<Vec<(FieldIdent, Expr)>> {
fields
.into_iter()
.map(
|FieldWithOpts { field_ident, field_type, options }| {
let builder_field_ident = field_ident.to_named_ident();
let expr = match options {
FieldValueGroupOpts::Value(opts) => match self.order {
ElementOrder::Strict => {
parse_quote!(
::core::option::Option::expect(
#builder_field_ident,
"Should have been set by the time we get here. This is a bug in xmlity.",
)
)
},
ElementOrder::None => {
deserialize_option_value_expr(
&field_type,
&parse_quote!(#builder_field_ident),
opts.default_or_else(),
self.order == ElementOrder::None && matches!(opts, ChildOpts::Value(_)),
visitor_lifetime,
error_type,
&field_ident.to_string(),
)
},
} ,
FieldValueGroupOpts::Group(_) => {
parse_quote! {
::xmlity::de::DeserializationGroupBuilder::finish::<#error_type>(#builder_field_ident)?
}
},
};
Ok((field_ident, expr))
},
).collect::<Result<Vec<_>, _>>()
}
}