forked from media-io/yaserde
-
Notifications
You must be signed in to change notification settings - Fork 0
/
expand_struct.rs
523 lines (472 loc) · 16.5 KB
/
expand_struct.rs
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
use crate::common::{Field, YaSerdeAttribute, YaSerdeField};
use crate::de::build_default_value::build_default_value;
use heck::CamelCase;
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::{DataStruct, Ident};
pub fn parse(
data_struct: &DataStruct,
name: &Ident,
root: &str,
root_attributes: &YaSerdeAttribute,
) -> TokenStream {
let namespaces_matching = root_attributes.get_namespace_matching(
&None,
quote!(struct_namespace),
quote!(named_element),
true,
);
let variables: TokenStream = data_struct
.fields
.iter()
.map(|field| YaSerdeField::new(field.clone()))
.map(|field| match field.get_type() {
Field::FieldStruct { struct_name } => build_default_value(
&field,
Some(quote!(#struct_name)),
quote!(<#struct_name as ::std::default::Default>::default()),
),
Field::FieldOption { .. } => {
build_default_value(&field, None, quote!(::std::option::Option::None))
}
Field::FieldVec { data_type } => match *data_type {
Field::FieldStruct { ref struct_name } => build_default_value(
&field,
Some(quote!(::std::vec::Vec<#struct_name>)),
quote!(::std::vec![]),
),
Field::FieldOption { .. } | Field::FieldVec { .. } => {
unimplemented!();
}
simple_type => {
let type_token: TokenStream = simple_type.into();
build_default_value(
&field,
Some(quote!(::std::vec::Vec<#type_token>)),
quote!(::std::vec![]),
)
}
},
simple_type => {
let type_token: TokenStream = simple_type.into();
let value_builder = quote!(<#type_token as ::std::default::Default>::default());
build_default_value(&field, Some(type_token), value_builder)
}
})
.flatten()
.collect();
let field_visitors: TokenStream = data_struct
.fields
.iter()
.map(|field| YaSerdeField::new(field.clone()))
.map(|field| {
let struct_visitor = |struct_name: syn::Path| {
let struct_id: String = struct_name
.segments
.iter()
.map(|s| s.ident.to_string())
.collect();
let visitor_label = field.get_visitor_ident(Some(&struct_name));
Some(quote! {
#[allow(non_snake_case, non_camel_case_types)]
struct #visitor_label;
impl<'de> ::yaserde::Visitor<'de> for #visitor_label {
type Value = #struct_name;
fn visit_str(
self,
v: &str,
) -> ::std::result::Result<Self::Value, ::std::string::String> {
let content = "<".to_string() + #struct_id + ">" + v + "</" + #struct_id + ">";
::yaserde::de::from_str(&content)
}
}
})
};
let simple_type_visitor = |simple_type: Field| {
let visitor = simple_type.get_simple_type_visitor();
let visitor_label = field.get_visitor_ident(None);
let field_type = TokenStream::from(simple_type);
let map_if_bool = if field_type.to_string() == "bool" {
quote!(match v {
"1" => "true",
"0" => "false",
_ => v,
})
} else {
quote!(v)
};
Some(quote! {
#[allow(non_snake_case, non_camel_case_types)]
struct #visitor_label;
impl<'de> ::yaserde::Visitor<'de> for #visitor_label {
type Value = #field_type;
fn #visitor(
self,
v: &str,
) -> ::std::result::Result<Self::Value, ::std::string::String> {
::std::result::Result::Ok(#field_type::from_str(#map_if_bool).unwrap())
}
}
})
};
match field.get_type() {
Field::FieldStruct { struct_name } => struct_visitor(struct_name),
Field::FieldOption { data_type } => match *data_type {
Field::FieldStruct { struct_name } => struct_visitor(struct_name),
Field::FieldOption { .. } | Field::FieldVec { .. } => None,
simple_type => simple_type_visitor(simple_type),
},
Field::FieldVec { data_type } => match *data_type {
Field::FieldStruct { struct_name } => struct_visitor(struct_name),
Field::FieldOption { .. } | Field::FieldVec { .. } => None,
simple_type => simple_type_visitor(simple_type),
},
simple_type => simple_type_visitor(simple_type),
}
})
.flatten()
.collect();
let call_visitors: TokenStream = data_struct
.fields
.iter()
.map(|field| YaSerdeField::new(field.clone()))
.filter(|field| !field.is_attribute() || !field.is_flatten())
.map(|field| {
let value_label = field.get_value_label();
let label_name = field.renamed_label_without_namespace();
let visit_struct = |struct_name: syn::Path, action: TokenStream| {
Some(quote! {
#label_name => {
if depth == 0 {
// Don't count current struct's StartElement as substruct's StartElement
let _root = reader.next_event();
}
if let Ok(::yaserde::__xml::reader::XmlEvent::StartElement { .. }) = reader.peek() {
// If substruct's start element found then deserialize substruct
let value = <#struct_name as ::yaserde::YaDeserialize>::deserialize(reader)?;
#value_label #action;
}
}
})
};
let visit_simple = |simple_type: Field, action: TokenStream| {
let field_visitor = simple_type.get_simple_type_visitor();
let field_type = TokenStream::from(simple_type);
build_call_visitor(
&field_type,
&field_visitor,
&action,
&field,
&root_attributes,
)
};
let visit_sub = |sub_type: Box<Field>, action: TokenStream| match *sub_type {
Field::FieldOption { .. } | Field::FieldVec { .. } => unimplemented!(),
Field::FieldStruct { struct_name } => visit_struct(struct_name, action),
simple_type => visit_simple(simple_type, action),
};
match field.get_type() {
Field::FieldStruct { struct_name } => visit_struct(struct_name, quote! { = value }),
Field::FieldOption { data_type } => {
visit_sub(data_type, quote! { = ::std::option::Option::Some(value) })
}
Field::FieldVec { data_type } => visit_sub(data_type, quote! { .push(value) }),
simple_type => visit_simple(simple_type, quote! { = value }),
}
})
.flatten()
.collect();
let call_flatten_visitors: TokenStream = data_struct
.fields
.iter()
.map(|field| YaSerdeField::new(field.clone()))
.filter(|field| !field.is_attribute() && field.is_flatten())
.map(|field| {
let value_label = field.get_value_label();
match field.get_type() {
Field::FieldStruct { .. } => Some(quote! {
#value_label = ::yaserde::de::from_str(&unused_xml_elements)?;
}),
Field::FieldOption { data_type } => match *data_type {
Field::FieldStruct { .. } => Some(quote! {
#value_label = ::yaserde::de::from_str(&unused_xml_elements).ok();
}),
field_type => unimplemented!(r#""flatten" is not implemented for {:?}"#, field_type),
},
field_type => unimplemented!(r#""flatten" is not implemented for {:?}"#, field_type),
}
})
.flatten()
.collect();
let attributes_loading: TokenStream = data_struct
.fields
.iter()
.map(|field| YaSerdeField::new(field.clone()))
.filter(|field| field.is_attribute())
.map(|field| {
let label = field.get_value_label();
let label_name = field.renamed_label_without_namespace();
let visitor_label = build_visitor_ident(&label_name, field.get_span(), None);
let visit = |action: &TokenStream, visitor: &Ident, visitor_label: &Ident| {
Some(quote! {
for attr in attributes {
if attr.name.local_name == #label_name {
let visitor = #visitor_label{};
let value = visitor.#visitor(&attr.value)?;
#label #action;
}
}
})
};
let visit_string = || {
Some(quote! {
for attr in attributes {
if attr.name.local_name == #label_name {
#label = attr.value.to_owned();
}
}
})
};
let visit_struct = |struct_name: syn::Path, action: TokenStream| {
visit(
&action,
&Ident::new("visit_str", Span::call_site()),
&build_visitor_ident(&label_name, field.get_span(), Some(&struct_name)),
)
};
let visit_simple = |simple_type: Field, action: TokenStream| {
visit(
&action,
&simple_type.get_simple_type_visitor(),
&visitor_label,
)
};
let visit_sub = |sub_type: Box<Field>, action: TokenStream| match *sub_type {
Field::FieldOption { .. } | Field::FieldVec { .. } => unimplemented!(),
Field::FieldStruct { struct_name } => visit_struct(struct_name, action),
simple_type => visit_simple(simple_type, action),
};
match field.get_type() {
Field::FieldString => visit_string(),
Field::FieldOption { data_type } => {
visit_sub(data_type, quote! { = ::std::option::Option::Some(value) })
}
Field::FieldVec { .. } => unimplemented!(),
Field::FieldStruct { struct_name } => visit_struct(struct_name, quote! { = value }),
simple_type => visit_simple(simple_type, quote! { = value }),
}
})
.flatten()
.collect();
let set_text: TokenStream = data_struct
.fields
.iter()
.map(|field| YaSerdeField::new(field.clone()))
.map(|field| {
let label = field.get_value_label();
let set_text = |action: &TokenStream| {
if field.is_text_content() {
Some(quote! { #label = #action; })
} else {
None
}
};
match field.get_type() {
Field::FieldString => set_text("e! { text_content.to_owned() }),
Field::FieldOption { data_type } => match *data_type {
Field::FieldString => set_text(
"e! { if text_content.is_empty() { None } else { Some(text_content.to_owned()) }},
),
_ => None,
},
Field::FieldStruct { .. } | Field::FieldVec { .. } => None,
simple_type => {
let type_token = TokenStream::from(simple_type);
set_text("e! { #type_token::from_str(text_content).unwrap() })
}
}
})
.flatten()
.collect();
let struct_builder: TokenStream = data_struct
.fields
.iter()
.map(|field| YaSerdeField::new(field.clone()))
.map(|field| {
let label = &field.label();
let value_label = field.get_value_label();
quote! { #label: #value_label, }
})
.collect();
let (init_unused, write_unused, visit_unused) = if call_flatten_visitors.is_empty() {
(None, None, None)
} else {
build_code_for_unused_xml_events(&call_flatten_visitors)
};
let flatten = root_attributes.flatten;
quote! {
impl ::yaserde::YaDeserialize for #name {
#[allow(unused_variables)]
fn deserialize<R: ::std::io::Read>(
reader: &mut ::yaserde::de::Deserializer<R>,
) -> ::std::result::Result<Self, ::std::string::String> {
let (named_element, struct_namespace) =
if let ::yaserde::__xml::reader::XmlEvent::StartElement { name, .. } = reader.peek()?.to_owned() {
(name.local_name.to_owned(), name.namespace.clone())
} else {
(::std::string::String::from(#root), ::std::option::Option::None)
};
let start_depth = reader.depth();
::yaserde::__derive_debug!("Struct {} @ {}: start to parse {:?}", stringify!(#name), start_depth,
named_element);
if reader.depth() == 0 {
#namespaces_matching
}
#variables
#field_visitors
#init_unused
let mut depth = 0;
loop {
let event = reader.peek()?.to_owned();
::yaserde::__derive_trace!(
"Struct {} @ {}: matching {:?}",
stringify!(#name), start_depth, event,
);
match event {
::yaserde::__xml::reader::XmlEvent::StartElement{ref name, ref attributes, ..} => {
if depth == 0 && name.local_name == #root {
// Consume root element. We must do this first. In the case it shares a name with a child element, we don't
// want to prematurely match the child element below.
let event = reader.next_event()?;
#write_unused
} else {
match name.local_name.as_str() {
#call_visitors
_ => {
let event = reader.next_event()?;
#write_unused
if depth > 0 { // Don't skip root element
reader.skip_element(|event| {
#write_unused
})?;
}
}
}
}
if depth == 0 { // Look for attributes only at element start
#attributes_loading
}
depth += 1;
}
::yaserde::__xml::reader::XmlEvent::EndElement { ref name } => {
if name.local_name == named_element {
#write_unused
break;
}
let event = reader.next_event()?;
#write_unused
depth -= 1;
}
::yaserde::__xml::reader::XmlEvent::EndDocument => {
if #flatten {
break;
}
}
::yaserde::__xml::reader::XmlEvent::Characters(ref text_content) => {
#set_text
let event = reader.next_event()?;
#write_unused
}
event => {
return ::std::result::Result::Err(::std::format!("unknown event {:?}", event));
}
}
}
#visit_unused
::yaserde::__derive_debug!("Struct {} @ {}: success", stringify!(#name), start_depth);
::std::result::Result::Ok(#name{#struct_builder})
}
}
}
}
fn build_call_visitor(
field_type: &TokenStream,
visitor: &Ident,
action: &TokenStream,
field: &YaSerdeField,
root_attributes: &YaSerdeAttribute,
) -> Option<TokenStream> {
let value_label = field.get_value_label();
let label_name = field.renamed_label_without_namespace();
let visitor_label = build_visitor_ident(&label_name, field.get_span(), None);
let namespaces_matching = field.get_namespace_matching(
root_attributes,
quote!(name.namespace.as_ref()),
quote!(name.local_name.as_str()),
);
Some(quote! {
#label_name => {
let visitor = #visitor_label{};
#namespaces_matching
let result = reader.read_inner_value::<#field_type, _>(|reader| {
if let ::std::result::Result::Ok(::yaserde::__xml::reader::XmlEvent::Characters(s)) = reader.peek() {
let val = visitor.#visitor(&s);
let _event = reader.next_event()?;
val
} else {
::std::result::Result::Err(::std::format!("unable to parse content for {}", #label_name))
}
});
if let ::std::result::Result::Ok(value) = result {
#value_label#action
}
}
})
}
fn build_visitor_ident(label: &str, span: Span, struct_name: Option<&syn::Path>) -> Ident {
let struct_id = struct_name.map_or_else(
|| "".to_string(),
|struct_name| {
struct_name
.segments
.iter()
.map(|s| s.ident.to_string())
.collect()
},
);
Ident::new(
&format!(
"__Visitor_{}_{}",
label.replace(".", "_").to_camel_case(),
struct_id
),
span,
)
}
fn build_code_for_unused_xml_events(
call_flatten_visitors: &TokenStream,
) -> (
Option<TokenStream>,
Option<TokenStream>,
Option<TokenStream>,
) {
(
Some(quote! {
let mut buf = ::std::vec![];
let mut writer = ::std::option::Option::Some(::yaserde::__xml::writer::EventWriter::new(&mut buf));
}),
Some(quote! {
if let ::std::option::Option::Some(ref mut w) = writer {
if w.write(event.as_writer_event().unwrap()).is_err() {
writer = ::std::option::Option::None;
}
}
}),
Some(quote! {
if writer.is_some() {
let unused_xml_elements = ::std::string::String::from_utf8(buf).unwrap();
#call_flatten_visitors
}
}),
)
}