xso_proc/
structs.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
// Copyright (c) 2024 Jonas Schäfer <jonas@zombofant.net>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

//! Handling of structs

use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::{spanned::Spanned, *};

use crate::common::{AsXmlParts, FromXmlParts, ItemDef};
use crate::compound::Compound;
use crate::error_message::ParentRef;
use crate::meta::{reject_key, Flag, NameRef, NamespaceRef, QNameRef, XmlCompoundMeta};
use crate::state::{AsItemsSubmachine, FromEventsSubmachine, State};
use crate::types::{
    as_xml_iter_fn, feed_fn, from_events_fn, from_xml_builder_ty, item_iter_ty, ref_ty,
    ty_from_ident,
};

/// The inner parts of the struct.
///
/// This contains all data necessary for the matching logic.
pub(crate) enum StructInner {
    /// Single-field struct declared with `#[xml(transparent)]`.
    ///
    /// Transparent struct delegate all parsing and serialising to their
    /// only field, which is why they do not need to store a lot of
    /// information and come with extra restrictions, such as:
    ///
    /// - no XML namespace can be declared (it is determined by inner type)
    /// - no XML name can be declared (it is determined by inner type)
    /// - there must be only exactly one field
    /// - that field has no `#[xml]` attribute
    Transparent {
        /// The member identifier of the only field.
        member: Member,

        /// Type of the only field.
        ty: Type,
    },

    /// A compound of fields, *not* declared as transparent.
    ///
    /// This can be a unit, tuple-like, or named struct.
    Compound {
        /// The XML namespace of the element to map the struct to.
        xml_namespace: NamespaceRef,

        /// The XML name of the element to map the struct to.
        xml_name: NameRef,

        /// The field(s) of this struct.
        inner: Compound,
    },
}

impl StructInner {
    pub(crate) fn new(meta: XmlCompoundMeta, fields: &Fields) -> Result<Self> {
        // We destructure here so that we get informed when new fields are
        // added and can handle them, either by processing them or raising
        // an error if they are present.
        let XmlCompoundMeta {
            span: meta_span,
            qname: QNameRef { namespace, name },
            exhaustive,
            debug,
            builder,
            iterator,
            on_unknown_attribute,
            on_unknown_child,
            transparent,
        } = meta;

        // These must've been cleared by the caller. Because these being set
        // is a programming error (in xso-proc) and not a usage error, we
        // assert here instead of using reject_key!.
        assert!(builder.is_none());
        assert!(iterator.is_none());
        assert!(!debug.is_set());

        reject_key!(exhaustive flag not on "structs" only on "enums");

        if let Flag::Present(_) = transparent {
            reject_key!(namespace not on "transparent structs");
            reject_key!(name not on "transparent structs");
            reject_key!(on_unknown_attribute not on "transparent structs");
            reject_key!(on_unknown_child not on "transparent structs");

            let fields_span = fields.span();
            let fields = match fields {
                Fields::Unit => {
                    return Err(Error::new(
                        fields_span,
                        "transparent structs or enum variants must have exactly one field",
                    ))
                }
                Fields::Named(FieldsNamed {
                    named: ref fields, ..
                })
                | Fields::Unnamed(FieldsUnnamed {
                    unnamed: ref fields,
                    ..
                }) => fields,
            };

            if fields.len() != 1 {
                return Err(Error::new(
                    fields_span,
                    "transparent structs or enum variants must have exactly one field",
                ));
            }

            let field = &fields[0];
            for attr in field.attrs.iter() {
                if attr.meta.path().is_ident("xml") {
                    return Err(Error::new_spanned(
                        attr,
                        "#[xml(..)] attributes are not allowed inside transparent structs",
                    ));
                }
            }
            let member = match field.ident.as_ref() {
                Some(v) => Member::Named(v.clone()),
                None => Member::Unnamed(Index {
                    span: field.ty.span(),
                    index: 0,
                }),
            };
            let ty = field.ty.clone();
            Ok(Self::Transparent { ty, member })
        } else {
            let Some(xml_namespace) = namespace else {
                return Err(Error::new(
                    meta_span,
                    "`namespace` is required on non-transparent structs",
                ));
            };

            let Some(xml_name) = name else {
                return Err(Error::new(
                    meta_span,
                    "`name` is required on non-transparent structs",
                ));
            };

            Ok(Self::Compound {
                inner: Compound::from_fields(
                    fields,
                    &xml_namespace,
                    on_unknown_attribute,
                    on_unknown_child,
                )?,
                xml_namespace,
                xml_name,
            })
        }
    }

    pub(crate) fn make_from_events_statemachine(
        &self,
        state_ty_ident: &Ident,
        output_name: &ParentRef,
        state_prefix: &str,
    ) -> Result<FromEventsSubmachine> {
        match self {
            Self::Transparent { ty, member } => {
                let from_xml_builder_ty = from_xml_builder_ty(ty.clone());
                let from_events_fn = from_events_fn(ty.clone());
                let feed_fn = feed_fn(from_xml_builder_ty.clone());

                let output_cons = match output_name {
                    ParentRef::Named(ref path) => quote! {
                        #path { #member: result }
                    },
                    ParentRef::Unnamed { .. } => quote! {
                        ( result, )
                    },
                };

                let state_name = quote::format_ident!("{}Default", state_prefix);
                let builder_data_ident = quote::format_ident!("__xso_data");

                // Here, we generate a partial statemachine which really only
                // proxies the FromXmlBuilder implementation of the inner
                // type.
                Ok(FromEventsSubmachine {
                    defs: TokenStream::default(),
                    states: vec![
                        State::new_with_builder(
                            state_name.clone(),
                            &builder_data_ident,
                            &from_xml_builder_ty,
                        )
                            .with_impl(quote! {
                                match #feed_fn(&mut #builder_data_ident, ev)? {
                                    ::core::option::Option::Some(result) => {
                                        ::core::result::Result::Ok(::core::ops::ControlFlow::Continue(#output_cons))
                                    }
                                    ::core::option::Option::None => {
                                        ::core::result::Result::Ok(::core::ops::ControlFlow::Break(Self::#state_name {
                                            #builder_data_ident,
                                        }))
                                    }
                                }
                            })
                    ],
                    init: quote! {
                        #from_events_fn(name, attrs).map(|#builder_data_ident| Self::#state_name { #builder_data_ident })
                    },
                })
            }

            Self::Compound {
                ref inner,
                ref xml_namespace,
                ref xml_name,
            } => Ok(inner
                .make_from_events_statemachine(state_ty_ident, output_name, state_prefix)?
                .with_augmented_init(|init| {
                    quote! {
                        if name.0 != #xml_namespace || name.1 != #xml_name {
                            ::core::result::Result::Err(::xso::error::FromEventsError::Mismatch {
                                name,
                                attrs,
                            })
                        } else {
                            #init
                        }
                    }
                })),
        }
    }

    pub(crate) fn make_as_item_iter_statemachine(
        &self,
        input_name: &ParentRef,
        state_ty_ident: &Ident,
        state_prefix: &str,
        item_iter_ty_lifetime: &Lifetime,
    ) -> Result<AsItemsSubmachine> {
        match self {
            Self::Transparent { ty, member } => {
                let item_iter_ty = item_iter_ty(ty.clone(), item_iter_ty_lifetime.clone());
                let as_xml_iter_fn = as_xml_iter_fn(ty.clone());

                let state_name = quote::format_ident!("{}Default", state_prefix);
                let iter_ident = quote::format_ident!("__xso_data");

                let destructure = match input_name {
                    ParentRef::Named(ref path) => quote! {
                        #path { #member: #iter_ident }
                    },
                    ParentRef::Unnamed { .. } => quote! {
                        (#iter_ident, )
                    },
                };

                // Here, we generate a partial statemachine which really only
                // proxies the AsXml iterator implementation from the inner
                // type.
                Ok(AsItemsSubmachine {
                    defs: TokenStream::default(),
                    states: vec![State::new_with_builder(
                        state_name.clone(),
                        &iter_ident,
                        &item_iter_ty,
                    )
                    .with_mut(&iter_ident)
                    .with_impl(quote! {
                        #iter_ident.next().transpose()?
                    })],
                    destructure,
                    init: quote! {
                        #as_xml_iter_fn(#iter_ident).map(|#iter_ident| Self::#state_name { #iter_ident })?
                    },
                })
            }

            Self::Compound {
                ref inner,
                ref xml_namespace,
                ref xml_name,
            } => Ok(inner
                .make_as_item_iter_statemachine(
                    input_name,
                    state_ty_ident,
                    state_prefix,
                    item_iter_ty_lifetime,
                )?
                .with_augmented_init(|init| {
                    quote! {
                        let name = (
                            ::xso::exports::rxml::Namespace::from(#xml_namespace),
                            ::xso::exports::alloc::borrow::Cow::Borrowed(#xml_name),
                        );
                        #init
                    }
                })),
        }
    }
}

/// Definition of a struct and how to parse it.
pub(crate) struct StructDef {
    /// Name of the target type.
    target_ty_ident: Ident,

    /// Name of the builder type.
    builder_ty_ident: Ident,

    /// Name of the iterator type.
    item_iter_ty_ident: Ident,

    /// Flag whether debug mode is enabled.
    debug: bool,

    /// The matching logic and contents of the struct.
    inner: StructInner,
}

impl StructDef {
    /// Create a new struct from its name, meta, and fields.
    pub(crate) fn new(ident: &Ident, mut meta: XmlCompoundMeta, fields: &Fields) -> Result<Self> {
        let builder_ty_ident = match meta.builder.take() {
            Some(v) => v,
            None => quote::format_ident!("{}FromXmlBuilder", ident.to_string()),
        };

        let item_iter_ty_ident = match meta.iterator.take() {
            Some(v) => v,
            None => quote::format_ident!("{}AsXmlIterator", ident.to_string()),
        };

        let debug = meta.debug.take();

        let inner = StructInner::new(meta, fields)?;

        Ok(Self {
            inner,
            target_ty_ident: ident.clone(),
            builder_ty_ident,
            item_iter_ty_ident,
            debug: debug.is_set(),
        })
    }
}

impl ItemDef for StructDef {
    fn make_from_events_builder(
        &self,
        vis: &Visibility,
        name_ident: &Ident,
        attrs_ident: &Ident,
    ) -> Result<FromXmlParts> {
        let target_ty_ident = &self.target_ty_ident;
        let builder_ty_ident = &self.builder_ty_ident;
        let state_ty_ident = quote::format_ident!("{}State", builder_ty_ident);

        let defs = self
            .inner
            .make_from_events_statemachine(
                &state_ty_ident,
                &Path::from(target_ty_ident.clone()).into(),
                "Struct",
            )?
            .compile()
            .render(
                vis,
                builder_ty_ident,
                &state_ty_ident,
                &TypePath {
                    qself: None,
                    path: target_ty_ident.clone().into(),
                }
                .into(),
            )?;

        Ok(FromXmlParts {
            defs,
            from_events_body: quote! {
                #builder_ty_ident::new(#name_ident, #attrs_ident)
            },
            builder_ty_ident: builder_ty_ident.clone(),
        })
    }

    fn make_as_xml_iter(&self, vis: &Visibility) -> Result<AsXmlParts> {
        let target_ty_ident = &self.target_ty_ident;
        let item_iter_ty_ident = &self.item_iter_ty_ident;
        let item_iter_ty_lifetime = Lifetime {
            apostrophe: Span::call_site(),
            ident: Ident::new("xso_proc_as_xml_iter_lifetime", Span::call_site()),
        };
        let item_iter_ty = Type::Path(TypePath {
            qself: None,
            path: Path {
                leading_colon: None,
                segments: [PathSegment {
                    ident: item_iter_ty_ident.clone(),
                    arguments: PathArguments::AngleBracketed(AngleBracketedGenericArguments {
                        colon2_token: None,
                        lt_token: token::Lt {
                            spans: [Span::call_site()],
                        },
                        args: [GenericArgument::Lifetime(item_iter_ty_lifetime.clone())]
                            .into_iter()
                            .collect(),
                        gt_token: token::Gt {
                            spans: [Span::call_site()],
                        },
                    }),
                }]
                .into_iter()
                .collect(),
            },
        });
        let state_ty_ident = quote::format_ident!("{}State", item_iter_ty_ident);

        let defs = self
            .inner
            .make_as_item_iter_statemachine(
                &Path::from(target_ty_ident.clone()).into(),
                &state_ty_ident,
                "Struct",
                &item_iter_ty_lifetime,
            )?
            .compile()
            .render(
                vis,
                &ref_ty(
                    ty_from_ident(target_ty_ident.clone()).into(),
                    item_iter_ty_lifetime.clone(),
                ),
                &state_ty_ident,
                &item_iter_ty_lifetime,
                &item_iter_ty,
            )?;

        Ok(AsXmlParts {
            defs,
            as_xml_iter_body: quote! {
                #item_iter_ty_ident::new(self)
            },
            item_iter_ty,
            item_iter_ty_lifetime,
        })
    }

    fn debug(&self) -> bool {
        self.debug
    }
}