hard-xml-derive 1.41.0

Derive marco of hard-xml.
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
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};
use syn::{spanned::Spanned, *};

use crate::{
    attrs, duplicate_mode::DuplicateMode, utils::{elide_type_lifetimes, Context}
};
use bitflags::bitflags;

type Result<T, E = Vec<syn::Error>> = std::result::Result<T, E>;

pub enum Element {
    Struct { name: Ident, fields: Fields },
    Enum { name: Ident, variants: Vec<Fields> },
}

pub enum Fields {
    /// Named fields of a struct or struct variant
    ///
    /// ```ignore
    /// #[xml(tag = "$tag")]
    /// struct $name {
    ///     $( $fields )*
    /// }
    /// ```
    ///
    /// ```ignore
    /// enum Foo {
    ///     #[xml(tag = "$tag")]
    ///     $name {
    ///         $( $fields )*
    ///     }
    /// }
    /// ```
    Named {
        tag: LitStr,
        strict: StrictMode,
        name: Ident,
        fields: Vec<Field>,
    },
    /// Newtype struct or newtype variant
    ///
    /// ```ignore
    /// #[xml($(tag = "$tags",)*)]
    /// struct $name($ty);
    /// ```
    ///
    /// ```ignore
    /// enum Foo {
    ///     #[xml($(tag = "$tags",)*)]
    ///     $name($ty)
    /// }
    /// ```
    Newtype {
        tags: Vec<LitStr>,
        name: Ident,
        ty: Box<Type>,
    },
}

pub enum Field {
    /// Arrtibute Field
    ///
    /// ```ignore
    /// struct Foo {
    ///     #[xml(attr = "$tag", $default)]
    ///     $name: $ty,
    /// }
    /// ```
    Attribute {
        name: TokenStream,
        bind: Ident,
        duplicate_last: bool,
        ty: Type,
        with: Option<ExprPath>,
        tag: LitStr,
        default: bool,
    },
    /// Child(ren) Field
    ///
    /// ```ignore
    /// struct Foo {
    ///     #[xml(child = "$tag", child = "$tag", $default)]
    ///     $name: $ty,
    /// }
    /// ```
    Child {
        name: TokenStream,
        bind: Ident,
        duplicate_last: bool,
        ty: Type,
        default: bool,
        tags: Vec<LitStr>,
    },
    /// Text Field
    ///
    /// ```ignore
    /// struct Foo {
    ///     #[xml(text, $default)]
    ///     $name: $ty,
    /// }
    /// ```
    Text {
        name: TokenStream,
        bind: Ident,
        ty: Type,
        with: Option<ExprPath>,
        is_cdata: bool,
    },
    /// Flatten Text
    ///
    /// ```ignore
    /// struct Foo {
    ///     #[xml(flatten_text = "$tag", $default)]
    ///     $name: $ty,
    /// }
    /// ```
    FlattenText {
        name: TokenStream,
        bind: Ident,
        duplicate_last: bool,
        ty: Type,
        with: Option<ExprPath>,
        default: bool,
        tag: LitStr,
        is_cdata: bool,
    },
}

pub enum Type {
    // Cow<'a, str>
    CowStr,
    // Option<Cow<'a, str>>
    OptionCowStr,
    // Vec<Cow<'a, str>>
    VecCowStr,
    // T
    T(syn::Type),
    // Option<T>
    OptionT(syn::Type),
    // Vec<T>
    VecT(syn::Type),
    // bool
    Bool,
    // Vec<bool>
    VecBool,
    // Option<bool>
    OptionBool,
}

impl Element {
    pub fn parse(input: DeriveInput) -> Result<Element> {
        let mut ctx = Context::default();

        let element = match input.data {
            Data::Struct(data) => Element::Struct {
                name: input.ident.clone(),
                fields: Fields::parse(&mut ctx, data.fields, input.attrs, input.ident),
            },
            Data::Enum(data) => Element::Enum {
                name: input.ident,
                variants: data
                    .variants
                    .into_iter()
                    .map(|variant| {
                        Fields::parse(&mut ctx, variant.fields, variant.attrs, variant.ident)
                    })
                    .collect(),
            },
            Data::Union(_) => {
                return Err(vec![syn::Error::new_spanned(
                    input,
                    "hard-xml doesn't support union",
                )]);
            }
        };

        ctx.check().map(|_| element)
    }
}

impl Fields {
    pub fn parse(
        ctx: &mut Context,
        mut fields: syn::Fields,
        attrs: Vec<Attribute>,
        name: Ident,
    ) -> Fields {
        // Finding `tag` attribute
        let attrs::Container {
            mut tags,
            strict_mode,
        } = attrs::Container::parse(ctx, attrs);

        if tags.is_empty() {
            ctx.push_spanned_error(&name, "missing `tag` attribute");
        }

        // Special handling for newtypes, which can have multiple tags
        if let syn::Fields::Unnamed(ref mut fields) = fields {
            if is_new_type(fields) {
                let ty = fields.unnamed.pop().unwrap().into_value().ty;
                let ty = Box::new(Type::parse(ty));

                return Fields::Newtype { tags, name, ty };
            }
        }

        let fields = match fields {
            syn::Fields::Unit => Vec::new(),

            syn::Fields::Unnamed(fields) => fields
                .unnamed
                .into_iter()
                .enumerate()
                .filter_map(|(index, field)| {
                    let index = syn::Index::from(index);
                    let bind = format_ident!("__self_{}", index);

                    Field::parse(ctx, quote!(#index), bind, field)
                })
                .collect(),

            syn::Fields::Named(_) => fields
                .into_iter()
                .filter_map(|field| {
                    let name = field.ident.clone().unwrap();
                    let bind = format_ident!("__self_{}", name);

                    Field::parse(ctx, quote!(#name), bind, field)
                })
                .collect(),
        };

        // TODO should extraneous tags be an error?
        let tag = if !tags.is_empty() {
            tags.swap_remove(0)
        } else {
            LitStr::new("", Span::call_site())
        };

        Fields::Named {
            tag,
            strict: strict_mode,
            name,
            fields,
        }
    }
}

fn is_new_type(fields: &FieldsUnnamed) -> bool {
    fields.unnamed.len() == 1
        && fields.unnamed[0]
            .attrs
            .iter()
            .all(|attr| attrs::get_xml_meta(attr).is_none())
}

impl Field {
    pub fn parse(
        ctx: &mut Context,
        name: TokenStream,
        bind: Ident,
        field: syn::Field,
    ) -> Option<Field> {
        let span = field.span();

        let mut attrs = attrs::Field::parse(ctx, field.attrs);
        let with = attrs.with.take();
        let kind = FieldKind::from_attributes(ctx, attrs, span)?;

        let span = field.ty.span();
        let ty = Type::parse(field.ty);

        kind.into_field(ctx, name, bind, ty, with, span)
    }
}

enum FieldKind {
    Attribute {
        default: bool,
        duplicate_last: bool,
        tag: LitStr,
    },
    Child {
        default: bool,
        duplicate_last: bool,
        tags: Vec<LitStr>,
    },
    FlattenText {
        tag: LitStr,
        cdata: bool,
        default: bool,
        duplicate_last: bool,
    },
    Text {
        cdata: bool,
    },
}

impl FieldKind {
    fn into_field(
        self,
        ctx: &mut Context,
        name: TokenStream,
        bind: Ident,
        ty: Type,
        with: Option<ExprPath>,
        span: Span,
    ) -> Option<Field> {
        self.verify_type(ctx, &ty, span).then(|| match self {
            FieldKind::Attribute { default, duplicate_last, tag } => Field::Attribute {
                name,
                bind,
                duplicate_last,
                ty,
                with,
                tag,
                default,
            },
            FieldKind::Child { default, duplicate_last, tags } => Field::Child {
                name,
                bind,
                duplicate_last,
                ty,
                default,
                tags,
            },
            FieldKind::FlattenText {
                tag,
                cdata,
                default,
                duplicate_last,
            } => Field::FlattenText {
                name,
                bind,
                duplicate_last,
                ty,
                with,
                default,
                tag,
                is_cdata: cdata,
            },
            FieldKind::Text { cdata } => Field::Text {
                name,
                bind,
                ty,
                with,
                is_cdata: cdata,
            },
        })
    }

    fn from_attributes(ctx: &mut Context, attrs: attrs::Field, span: Span) -> Option<Self> {
        let attrs::Field {
            attr_tag,
            child_tags,
            flatten_text_tag,
            is_text,
            ..
        } = attrs;

        match (attr_tag, child_tags.as_slice(), flatten_text_tag, is_text) {
            (Some(tag), &[], None, false) => Some(Self::Attribute {
                default: attrs.default,
                duplicate_last: match attrs.duplicate_mode {
                    Some(DuplicateMode::Error) => false,
                    Some(DuplicateMode::Last) => true,
                    None => false,
                },
                tag,
            }),
            (None, &[_, ..], None, false) => Some(Self::Child {
                default: attrs.default,
                duplicate_last: match attrs.duplicate_mode {
                    Some(DuplicateMode::Error) => false,
                    Some(DuplicateMode::Last) => true,
                    None => true, // Somewhat unsafe, but allowed.
                },
                tags: child_tags,
            }),
            (None, &[], Some(tag), false) => Some(Self::FlattenText {
                tag,
                cdata: attrs.is_cdata,
                default: attrs.default,
                duplicate_last: match attrs.duplicate_mode {
                    Some(DuplicateMode::Error) => false,
                    Some(DuplicateMode::Last) => true,
                    None => true, // Somewhat unsafe, but allowed.
                },
            }),
            (None, &[], None, true) => Some(Self::Text {
                cdata: attrs.is_cdata,
            }),
            (None, &[], None, false) => {
                ctx.push_new_error(
                    span,
                    "field should have one of `attr`, `child`, `text` or `flatten_text` attribute",
                );
                None
            }
            _ => {
                ctx.push_new_error(
                    span,
                    "the attributes `attr`, `child`, `text` and `flatten_text` are mutually exclusive",
                );
                None
            }
        }
    }

    fn verify_type(&self, ctx: &mut Context, ty: &Type, span: Span) -> bool {
        match self {
            FieldKind::Attribute { .. } if ty.is_vec() => {
                ctx.push_new_error(span, "`attr` attribute doesn't support Vec");
                false
            }
            FieldKind::Child { .. }
                if !matches!(ty, Type::OptionT(_) | Type::T(_) | Type::VecT(_)) =>
            {
                ctx.push_new_error(
                    span,
                    "`child` attribute only supports Vec<T>, Option<T>, and T",
                );
                false
            }
            FieldKind::Text { .. } if ty.is_vec() => {
                ctx.push_new_error(span, "`text` attribute doesn't support Vec");
                false
            }

            _ => true,
        }
    }
}

impl Type {
    pub fn is_option(&self) -> bool {
        matches!(
            self,
            Type::OptionCowStr | Type::OptionT(_) | Type::OptionBool
        )
    }

    pub fn is_vec(&self) -> bool {
        matches!(self, Type::VecCowStr | Type::VecT(_) | Type::VecBool)
    }

    fn parse(mut ty: syn::Type) -> Self {
        fn is_vec(ty: &syn::Type) -> Option<&syn::Type> {
            let path = match ty {
                syn::Type::Path(ty) => &ty.path,
                _ => return None,
            };
            let seg = path.segments.last()?;
            let args = match &seg.arguments {
                PathArguments::AngleBracketed(bracketed) => &bracketed.args,
                _ => return None,
            };
            if seg.ident == "Vec" && args.len() == 1 {
                match args[0] {
                    GenericArgument::Type(ref arg) => Some(arg),
                    _ => None,
                }
            } else {
                None
            }
        }

        fn is_option(ty: &syn::Type) -> Option<&syn::Type> {
            let path = match ty {
                syn::Type::Path(ty) => &ty.path,
                _ => return None,
            };
            let seg = path.segments.last()?;
            let args = match &seg.arguments {
                PathArguments::AngleBracketed(bracketed) => &bracketed.args,
                _ => return None,
            };
            if seg.ident == "Option" && args.len() == 1 {
                match &args[0] {
                    GenericArgument::Type(arg) => Some(arg),
                    _ => None,
                }
            } else {
                None
            }
        }

        fn is_cow_str(ty: &syn::Type) -> bool {
            let path = match ty {
                syn::Type::Path(ty) => &ty.path,
                _ => return false,
            };
            let seg = match path.segments.last() {
                Some(seg) => seg,
                None => return false,
            };
            let args = match &seg.arguments {
                PathArguments::AngleBracketed(bracketed) => &bracketed.args,
                _ => return false,
            };
            if seg.ident == "Cow" && args.len() == 2 {
                match &args[1] {
                    GenericArgument::Type(syn::Type::Path(ty)) => ty.path.is_ident("str"),
                    _ => false,
                }
            } else {
                false
            }
        }

        fn is_bool(ty: &syn::Type) -> bool {
            matches!(ty, syn::Type::Path(ty) if ty.path.is_ident("bool"))
        }

        elide_type_lifetimes(&mut ty);

        if let Some(ty) = is_vec(&ty) {
            if is_cow_str(ty) {
                Type::VecCowStr
            } else if is_bool(ty) {
                Type::VecBool
            } else {
                Type::VecT(ty.clone())
            }
        } else if let Some(ty) = is_option(&ty) {
            if is_cow_str(ty) {
                Type::OptionCowStr
            } else if is_bool(ty) {
                Type::OptionBool
            } else {
                Type::OptionT(ty.clone())
            }
        } else if is_cow_str(&ty) {
            Type::CowStr
        } else if is_bool(&ty) {
            Type::Bool
        } else {
            Type::T(ty)
        }
    }
}

bitflags! {
    #[derive(Copy,Clone)]
    pub struct StrictMode: u8 {
        const UNKNOWN_ATTRIBUTE = 0b0000_0001;
        const UNKNOWN_ELEMENT = 0b0000_0010;
    }
}