logisheets_derives 0.3.0

macros that help LogiSheets serde the xml files
Documentation
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
use syn::DeriveInput;

use crate::container::{self, Container, EleType, FieldsSummary, Generic, StructField};

pub fn get_de_impl_block(input: DeriveInput) -> proc_macro2::TokenStream {
    let container = Container::from_ast(&input, container::Derive::Deserialize);
    if container.is_enum() {
        get_de_enum_impl_block(container)
    } else {
        get_de_struct_impl_block(container)
    }
}

pub fn get_de_enum_impl_block(container: Container) -> proc_macro2::TokenStream {
    let ident = &container.original.ident;
    let event_start_branches = container.enum_variants.iter().map(|v| {
        let name = &v.name;
        let ty = v.ty;
        let ident = v.ident;
        quote! {
            #name => {
                let _r = #ty::deserialize(
                    #name,
                    reader,
                    _s.attributes(),
                    false,
                );
                result = Some(Self::#ident(_r));
            }
        }
    });
    let event_empty_branches = container.enum_variants.iter().map(|v| {
        let name = &v.name;
        let ty = v.ty;
        let ident = v.ident;
        quote! {
            #name => {
                let _r = #ty::deserialize(
                    #name,
                    reader,
                    _s.attributes(),
                    true,
                );
                result = Some(Self::#ident(_r));
            }
        }
    });
    quote! {
        #[allow(unused_assignments)]
        impl crate::XmlDeserialize for #ident {
            fn deserialize<B: std::io::BufRead>(
                tag: &[u8],
                reader: &mut quick_xml::Reader<B>,
                attrs: quick_xml::events::attributes::Attributes,
                is_empty: bool,
            ) -> Self {
                use quick_xml::events::*;
                let mut buf = Vec::<u8>::new();
                let mut result = Option::<Self>::None;
                loop {
                    match reader.read_event(&mut buf) {
                        Ok(Event::End(e)) if e.name() == tag => {
                            break
                        },
                        Ok(Event::Start(_s)) => match _s.name() {
                            #(#event_start_branches)*
                            _ => {},
                        },
                        Ok(Event::Empty(_s)) => match _s.name() {
                            #(#event_empty_branches)*
                            _ => {},
                        }
                        Ok(Event::Eof) => break,
                        Err(_) => break,
                        _ => {},
                    }
                }
                result.unwrap()
            }
        }
    }
}

pub fn get_de_struct_impl_block(container: Container) -> proc_macro2::TokenStream {
    let result = get_result(&container.struct_fields);
    let summary = FieldsSummary::from_fields(container.struct_fields);
    let fields_init = get_fields_init(&summary);
    let FieldsSummary {
        children,
        text,
        attrs,
        self_closed_children,
    } = summary;
    let vec_init = get_vec_init(&children);
    let attr_branches = attrs.into_iter().map(|a| attr_match_branch(a));
    let child_branches = children_match_branch(children);
    let sfc_branch = sfc_match_branch(self_closed_children);
    let ident = &container.original.ident;
    let text_branch = {
        if let Some(t) = text {
            Some(text_match_branch(t))
        } else {
            None
        }
    };
    quote! {
        #[allow(unused_assignments)]
        impl crate::XmlDeserialize for #ident {
            fn deserialize<B: std::io::BufRead>(
                tag: &[u8],
                reader: &mut quick_xml::Reader<B>,
                attrs: quick_xml::events::attributes::Attributes,
                is_empty: bool,
            ) -> Self {
                #fields_init
                attrs.into_iter().for_each(|attr| {
                    if let Ok(attr) = attr {
                        match attr.key {
                            #(#attr_branches)*
                            _ => {},
                        }
                    }
                });
                let mut buf = Vec::<u8>::new();
                use quick_xml::events::Event;
                #vec_init
                if is_empty {} else {
                    loop {
                        match reader.read_event(&mut buf) {
                            Ok(Event::End(e)) if e.name() == tag => {
                                break
                            },
                            #sfc_branch
                            #child_branches
                            #text_branch
                            Ok(Event::Eof) => break,
                            Err(_) => break,
                            _ => {},
                        }
                    }
                }
                Self {
                    #result
                }
            }
        }
    }
}

fn get_result(fields: &[StructField]) -> proc_macro2::TokenStream {
    let branch = fields.iter().map(|f| {
        let ident = f.original.ident.as_ref().unwrap();
        if f.is_required() {
            quote! {
                #ident: #ident.unwrap(),
            }
        } else {
            quote! {
                #ident,
            }
        }
    });
    quote! {#(#branch)*}
}

fn get_fields_init(fields: &FieldsSummary) -> proc_macro2::TokenStream {
    let attrs_inits = fields.attrs.iter().map(|f| {
        let ident = f.original.ident.as_ref().unwrap();
        let ty = &f.original.ty;
        match &f.default {
            Some(p) => {
                quote! {let mut #ident = #p();}
            }
            None => {
                if let Some(opt) = f.generic.get_opt() {
                    quote! {
                        let mut #ident = Option::<#opt>::None;
                    }
                } else {
                    quote! {let mut #ident = Option::<#ty>::None;}
                }
            }
        }
    });
    let children_inits = fields.children.iter().map(|f| {
        let ident = f.original.ident.as_ref().unwrap();
        let ty = &f.original.ty;
        match &f.default {
            Some(p) => {
                quote! {let mut #ident = #p;}
            }
            None => match f.generic {
                Generic::Vec(v) => quote! {
                    let mut #ident = Vec::<#v>::new();
                },
                Generic::Opt(opt) => quote! {
                    let mut #ident = Option::<#opt>::None;
                },
                Generic::None => quote! {
                    let mut #ident = Option::<#ty>::None;
                },
            },
        }
    });
    let text_init = match &fields.text {
        Some(f) => {
            let ident = f.original.ident.as_ref().unwrap();
            let ty = match f.generic {
                Generic::Vec(_) => panic!("text element should not be Vec<T>"),
                Generic::Opt(t) => t,
                Generic::None => &f.original.ty,
            };
            // let ty = &f.original.ty;
            match &f.default {
                Some(e) => quote! {
                        let mut #ident = #e();
                },
                None => quote! {
                    let mut #ident = Option::<#ty>::None;
                },
            }
        }
        None => quote! {},
    };
    let sfc_init = fields.self_closed_children.iter().map(|f| {
        let ident = f.original.ident.as_ref().unwrap();
        quote! {
            let mut #ident = false;
        }
    });
    quote! {
        #(#attrs_inits)*
        #(#sfc_init)*
        #(#children_inits)*
        #text_init
    }
}

fn get_vec_init(children: &[StructField]) -> proc_macro2::TokenStream {
    let vec_inits = children
        .iter()
        .filter(|c| c.generic.is_vec())
        .map(|c| match &c.vec_size {
            Some(lit) => {
                let vec_ty = &c.generic.get_vec().unwrap();
                let ident = c.original.ident.as_ref().unwrap();
                match lit {
                    syn::Lit::Str(_) => {
                        let path = container::parse_lit_into_expr_path(lit).unwrap();
                        quote! {
                            #ident = Vec::<#vec_ty>::with_capacity(#path as usize);
                        }
                    }
                    syn::Lit::Int(i) => {
                        quote! {
                            #ident = Vec::<#vec_ty>::with_capacity(#i);
                        }
                    }
                    _ => panic!(""),
                }
            }
            None => {
                quote! {}
            }
        });
    quote! {
        #(#vec_inits)*
    }
}

fn sfc_match_branch(fields: Vec<StructField>) -> proc_macro2::TokenStream {
    if fields.len() == 0 {
        return quote! {};
    }
    let mut idents = vec![];
    let mut tags = vec![];
    fields.iter().for_each(|f| {
        if !matches!(f.ty, EleType::SelfClosedChild) {
            panic!("")
        }
        let tag = f.name.as_ref().unwrap();
        tags.push(tag);
        let ident = f.original.ident.as_ref().unwrap();
        idents.push(ident);
    });
    quote! {
        #(Ok(Event::Empty(__s)) if __s.name() == #tags => {
            #idents = true;
        })*
    }
    // quote! {
    //     Ok(Event::Empty(s)) => {
    //         match s.name() {
    //             #(#tags => {#idents = true;})*
    //             _ => {},
    //         }
    //     },
    // }
}

fn attr_match_branch(field: StructField) -> proc_macro2::TokenStream {
    if !matches!(field.ty, EleType::Attr) {
        panic!("")
    }
    let t = &field.original.ty;
    let tag = field.name.as_ref().unwrap();
    let ident = field.original.ident.as_ref().unwrap();
    if field.generic.is_opt() {
        let opt_ty = field.generic.get_opt().unwrap();
        quote! {
            #tag => {
                use crate::{XmlValue, XmlDeserialize};
                let s = String::from_utf8(attr.value.into_iter().map(|c| *c).collect()).unwrap();
                match #opt_ty::deserialize(&s) {
                    Ok(__v) => {
                        #ident = Some(__v);
                    },
                    Err(_) => {
                        // If we used format! here. It would panic!.
                        // let err_msg = format!("xml value deserialize error: {:?} to {:?}", s, #t);
                        panic!("deserialize failed in attr opt")
                    },
                }
            }
        }
    } else {
        let tt = if field.is_required() {
            quote! {#ident = Some(__v);}
        } else {
            quote! {#ident = __v;}
        };
        quote! {
            #tag => {
                use crate::{XmlValue, XmlDeserialize};
                let __s = String::from_utf8(attr.value.into_iter().map(|c| *c).collect()).unwrap();
                match #t::deserialize(&__s) {
                    Ok(__v) => {
                        #tt
                    },
                    Err(_) => {
                        // If we used format! here. It would panic!.
                        // let err_msg = format!("xml value deserialize error: {:?} to {:?}", s, #t);
                        panic!("deserialize failed in attr")
                    },
                }
            },
        }
    }
}

fn text_match_branch(field: StructField) -> proc_macro2::TokenStream {
    if !matches!(field.ty, EleType::Text) {
        panic!("")
    }
    let ident = field.original.ident.as_ref().unwrap();
    // let t = &field.original.ty;
    let (t, is_opt) = match field.generic {
        Generic::Vec(_) => panic!("text element should not be Vec<T>"),
        Generic::Opt(ty) => (ty, true),
        Generic::None => (&field.original.ty, false),
    };
    let tt = if field.is_required() || is_opt {
        quote! {#ident = Some(__v);}
    } else {
        quote! {#ident = __v;}
    };
    quote! {
        Ok(Event::Text(__s)) => {
            use crate::{XmlValue, XmlDeserialize};
            let __r = __s.unescape_and_decode(reader).unwrap();
            match #t::deserialize(&__r) {
                Ok(__v) => {
                    // #ident = v;
                    #tt
                },
                Err(_) => {
                    panic!("deserialize failed in text element")
                }
            }
        },
    }
}

fn children_match_branch(fields: Vec<StructField>) -> proc_macro2::TokenStream {
    if fields.len() == 0 {
        return quote! {};
    }
    let mut branches = vec![];
    fields.iter().for_each(|f| {
        if !matches!(f.ty, EleType::Child) {
            panic!("")
        }
        let tag = f.name.as_ref().unwrap();
        let ident = f.original.ident.as_ref().unwrap();
        let t = &f.original.ty;
        let branch = match f.generic {
            Generic::Vec(vec_ty) => {
                quote! {
                    #tag => {
                        let __ele = #vec_ty::deserialize(#tag, reader, s.attributes(), is_empty);
                        #ident.push(__ele);
                    }
                }
            }
            Generic::Opt(opt_ty) => {
                quote! {
                    #tag => {
                        let __f = #opt_ty::deserialize(#tag, reader, s.attributes(), is_empty);
                        #ident = Some(__f);
                    },
                }
            }
            Generic::None => {
                let tt = if f.is_required() {
                    quote! {
                        #ident = Some(__f);
                    }
                } else {
                    quote! {
                        #ident = __f;
                    }
                };
                quote! {
                    #tag => {
                        let __f = #t::deserialize(#tag, reader, s.attributes(), is_empty);
                        #tt
                    },
                }
            }
        };
        branches.push(branch);
    });
    quote! {
        Ok(Event::Empty(s)) => {
            let is_empty = true;
            match s.name() {
                #(#branches)*
                _ => {},
            }
        }
        Ok(Event::Start(s)) => {
            let is_empty = false;
            match s.name() {
                #(#branches)*
                _ => {},
            }
        }
    }
}