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
//! Infrastructure for parsing fields from child elements without
//! destructuring their contents.
use proc_macro2::{Span, TokenStream};

use quote::{quote, ToTokens};
use syn::*;

use crate::common::Scope;
use crate::error_message::{self, ParentRef};
use crate::meta::{FlagOr, Name, NameRef, NamespaceRef, StaticNamespace};
use crate::structs::ElementSelector;
use crate::types::*;

use super::{Field, FieldFromEventsPart, FieldIntoEventsPart, FieldTempInit, NestedMatcher};

/// A field parsed from an XML child, without destructuring it into Rust
/// data structures.
///
/// Maps to `#[xml(element)]`.
#[derive(Debug)]
pub(crate) struct ElementField {
    /// Logic to select matching child elements.
    selector: ElementSelector,

    /// If set, the field value will be generated using
    /// [`std::default::Default`] or the given callable if no matching child
    /// element is encountered during parsing. If unset, an error is generated
    /// instead and parsing of the parent element fails.
    default_: FlagOr<Path>,
}

impl ElementField {
    /// Construct a new `#[xml(element)]` field.
    ///
    /// `namespace` must be a [`NamespaceRef::Static`] describing the
    /// XML namespace of the target child element. Otherwise, a compile-time
    /// error is returned.
    ///
    /// `name` must be a [`NameRef`] describing the XML name of the target
    /// child element. Otherwise, a compile-time error is returned.
    ///
    /// `attr_span` is used for emitting error messages when no better span
    /// can be constructed. This should point at the `#[xml(..)]` meta of the
    /// field or another closely-related object.
    pub(super) fn new(
        _attr_span: &Span,
        namespace: Option<NamespaceRef>,
        name: Option<NameRef>,
        default_: FlagOr<Path>,
    ) -> Result<Self> {
        let namespace = match namespace {
            None => None,
            Some(NamespaceRef::Static(ns)) => Some(ns),
            Some(NamespaceRef::Dyn(ns)) => {
                return Err(Error::new_spanned(
                    ns,
                    "dynamic namespaces cannot be used with #[xml(element)]",
                ))
            }
            Some(NamespaceRef::Super(ns)) => {
                return Err(Error::new_spanned(
                    ns,
                    "collected elements cannot refer to the parent namespace",
                ))
            }
        };
        let name = name.map(Name::from);
        let selector = match (namespace, name) {
            (Some(namespace), Some(name)) => ElementSelector::Qualified { namespace, name },
            (Some(namespace), None) => ElementSelector::ByNamespace(namespace),
            (None, Some(name)) => ElementSelector::ByName(name),
            (None, None) => ElementSelector::Any,
        };
        Ok(Self { selector, default_ })
    }
}

impl Field for ElementField {
    fn build_from_events_builder(
        &self,
        scope: &Scope,
        container_name: &ParentRef,
        _tempname: Ident,
        member: &Member,
        ty: &Type,
    ) -> Result<FieldFromEventsPart> {
        let Scope {
            ref start_ev_attrs,
            ref start_ev_qname,
            ref substate_result,
            ..
        } = scope;
        let access = scope.access_field(member);
        let test = self.selector.build_test(start_ev_qname);

        let missingerr = error_message::on_missing_child(container_name, member);
        let duperr = error_message::on_duplicate_child(container_name, member);
        let on_missing = match self.default_ {
            FlagOr::Absent => {
                quote! {
                    return Err(::xso::error::Error::ParseError(#missingerr));
                }
            }
            FlagOr::Present(_) => default_value(ty.clone()).into_token_stream(),
            FlagOr::Value { ref value, .. } => {
                quote! {
                    #value()
                }
            }
        };

        let dupcheck = match self.selector {
            ElementSelector::Any => quote! {},
            _ => quote! {
                .and_then(|ok| {
                    if #access.is_some() {
                        ::std::result::Result::Err(::xso::FromEventsError::Invalid(::xso::error::Error::ParseError(#duperr)))
                    } else {
                        ::std::result::Result::Ok(ok)
                    }
                })
            },
        };

        let matcher = NestedMatcher::Inline(quote! {
            if #test {
                <::xso::exports::minidom::Element as ::xso::FromXml>::from_events(#start_ev_qname, #start_ev_attrs) #dupcheck
            } else {
                ::std::result::Result::Err(::xso::FromEventsError::Mismatch { name: #start_ev_qname, attrs: #start_ev_attrs})
            }
        });

        Ok(FieldFromEventsPart::Nested {
            extra_defs: TokenStream::default(),
            temp: FieldTempInit {
                ty: option_ty(element_ty(Span::call_site())),
                init: quote! { ::std::option::Option::None },
            },
            matcher,
            builder: from_xml_builder_ty(element_ty(Span::call_site())),
            collect: quote! {
                #access = ::std::option::Option::Some(#substate_result);
            },
            finish: quote! {
                if let ::std::option::Option::Some(value) = #access {
                    value.into()
                } else {
                    #on_missing
                }
            },
        })
    }

    fn build_into_events_iterator(
        &self,
        _scope: &Scope,
        _container_name: &ParentRef,
        tempname: Ident,
        _member: &Member,
        _ty: &Type,
    ) -> Result<FieldIntoEventsPart> {
        Ok(FieldIntoEventsPart::ContentMut {
            extra_defs: TokenStream::default(),
            ty: option_ty(event_iter_ty(element_ty(Span::call_site()))),
            init: quote! {
                ::std::option::Option::<::xso::exports::minidom::Element>::from(#tempname).map(<::xso::exports::minidom::Element as ::xso::IntoXml>::into_event_iter).transpose()?
            },
            emitter: quote! {
                match #tempname.as_mut().and_then(|x| x.next()) {
                    ::std::option::Option::Some(::std::result::Result::Ok(ev)) => ::std::option::Option::Some(ev),
                    ::std::option::Option::Some(::std::result::Result::Err(e)) => return ::std::result::Result::Err(e),
                    ::std::option::Option::None => ::std::option::Option::None,
                }
            },
        })
    }

    fn build_set_namespace(
        &self,
        _input: &Ident,
        _ty: &Type,
        _access: Expr,
    ) -> Result<TokenStream> {
        Ok(TokenStream::default())
    }
}

/// A field parsed from a XML children, without destructuring them into Rust
/// data structures.
///
/// Maps to `#[xml(elements)]`.
#[derive(Debug)]
pub(crate) struct ElementsField {
    /// Selector to choose the child elements to collect.
    ///
    /// - If `None`, *all* children are collected. This is equivalent to
    ///   `#[xml(elements)]` on a field and may only occur once in a compound.
    /// - If `Some((ns, None))`, all children matching the namespace,
    ///   irrespective of the XML name, are collected.
    /// - If `Some((ns, Some(name)))`, only children matching the namespace
    ///   and name are collected.
    pub(super) selector: Option<(StaticNamespace, Option<Name>)>,
}

impl ElementsField {
    /// Construct a new `#[xml(elements)]`.
    ///
    /// `namespace` and `name` are optional selectors for XML child elements
    /// to match. If `namespace` is not set, `name` must not be set either,
    /// or a compile-time error is returned.
    ///
    /// `attr_span` is used for emitting error messages when no better span
    /// can be constructed. This should point at the `#[xml(..)]` meta of the
    /// field or another closely-related object.
    pub(super) fn new(
        _attr_span: &Span,
        namespace: Option<NamespaceRef>,
        name: Option<NameRef>,
    ) -> Result<Self> {
        let namespace = match namespace {
            None => {
                if let Some(name) = name {
                    return Err(Error::new_spanned(
                        name,
                        "#[xml(elements(..))] cannot be used with an unnamespaced name",
                    ));
                }
                None
            }
            Some(NamespaceRef::Static(ns)) => Some(ns),
            Some(NamespaceRef::Dyn(ns)) => {
                return Err(Error::new_spanned(
                    ns,
                    "dynamic namespaces cannot be used with #[xml(elements)]",
                ))
            }
            Some(NamespaceRef::Super(ns)) => {
                return Err(Error::new_spanned(
                    ns,
                    "collected elements cannot refer to the parent namespace",
                ))
            }
        };

        Ok(Self {
            selector: namespace.map(|x| (x, name.map(|x| x.into()))),
        })
    }
}

impl Field for ElementsField {
    fn is_child_wildcard(&self) -> bool {
        match self.selector {
            None => true,
            _ => false,
        }
    }

    fn build_from_events_builder(
        &self,
        scope: &Scope,
        _container_name: &ParentRef,
        _tempname: Ident,
        member: &Member,
        ty: &Type,
    ) -> Result<FieldFromEventsPart> {
        let Scope {
            ref start_ev_attrs,
            ref start_ev_qname,
            ref substate_result,
            ..
        } = scope;
        let access = scope.access_field(member);

        let builder_cons = quote! {
            <::xso::exports::minidom::Element as ::xso::FromXml>::from_events(#start_ev_qname, #start_ev_attrs)
        };

        let matcher = match self.selector {
            Some((ref field_namespace, ref field_name)) => {
                let mut condition = quote! {
                    #start_ev_qname.0 == #field_namespace
                };
                if let Some(field_name) = field_name {
                    condition.extend(quote! { && #start_ev_qname.1 == #field_name });
                }
                NestedMatcher::Inline(quote! {
                    if #condition {
                        #builder_cons
                    } else {
                        ::std::result::Result::Err(::xso::FromEventsError::Mismatch { name: #start_ev_qname, attrs: #start_ev_attrs })
                    }
                })
            }
            None => NestedMatcher::Fallback(quote! {
                match #builder_cons {
                    ::std::result::Result::Ok(v) => v,
                    ::std::result::Result::Err(::xso::FromEventsError::Invalid(e)) => return ::std::result::Result::Err(e),
                    ::std::result::Result::Err(::xso::FromEventsError::Mismatch { .. }) => unreachable!(),
                }
            }),
        };

        Ok(FieldFromEventsPart::Nested {
            extra_defs: TokenStream::default(),
            temp: FieldTempInit {
                ty: ty.clone(),
                init: quote! { ::std::vec::Vec::new() },
            },
            matcher,
            builder: from_xml_builder_ty(element_ty(Span::call_site())),
            collect: quote! {
                #access.push(#substate_result);
            },
            finish: quote! {
                #access
            },
        })
    }

    fn build_into_events_iterator(
        &self,
        _scope: &Scope,
        _container_name: &ParentRef,
        tempname: Ident,
        _member: &Member,
        _ty: &Type,
    ) -> Result<FieldIntoEventsPart> {
        let state_ty = Type::Tuple(TypeTuple {
            paren_token: syn::token::Paren::default(),
            elems: [
                vec_into_iter_ty(element_ty(Span::call_site())),
                option_ty(event_iter_ty(element_ty(Span::call_site()))),
            ]
            .into_iter()
            .collect(),
        });

        Ok(FieldIntoEventsPart::ContentMut {
            extra_defs: TokenStream::default(),
            ty: state_ty,
            init: quote! {
                (#tempname.into_iter(), ::std::option::Option::None)
            },
            emitter: quote! {
                loop {
                    if let ::std::option::Option::Some(current) = #tempname.1.as_mut() {
                        if let ::std::option::Option::Some(item) = current.next() {
                            break ::std::option::Option::Some(item?);
                        }
                    }
                    if let ::std::option::Option::Some(item) = #tempname.0.next() {
                        #tempname.1 = ::std::option::Option::Some(<::xso::exports::minidom::Element as ::xso::IntoXml>::into_event_iter(item)?);
                    } else {
                        break ::std::option::Option::None;
                    }
                }
            },
        })
    }

    fn build_set_namespace(
        &self,
        _input: &Ident,
        _ty: &Type,
        _access: Expr,
    ) -> Result<TokenStream> {
        Ok(TokenStream::default())
    }
}