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

use quote::{quote, quote_spanned};
use syn::{spanned::Spanned, *};

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

use super::{Field, FieldParsePart};

/// 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_try_from_element(
        &self,
        container_name: &ParentRef,
        _container_namespace_expr: &Expr,
        tempname: Ident,
        member: &Member,
        ty: &Type,
    ) -> Result<FieldParsePart> {
        let test = self
            .selector
            .build_test(&Ident::new("residual", Span::call_site()));
        let missingerr = error_message::on_missing_child(container_name, member);
        let duperr = error_message::on_duplicate_child(container_name, member);
        let ty_span = ty.span();
        let ty_default = quote_spanned! {ty_span=> <#ty as std::default::Default>::default};
        let ty_from_element =
            quote_spanned! {ty_span=> <#ty as From<::xso::exports::minidom::Element>>::from};
        let on_missing = match self.default_ {
            FlagOr::Absent => {
                quote! {
                    return Err(::xso::error::Error::ParseError(#missingerr));
                }
            }
            FlagOr::Present(_) => {
                quote! {
                    #ty_default()
                }
            }
            FlagOr::Value { ref value, .. } => {
                quote! {
                    #value()
                }
            }
        };
        Ok(FieldParsePart {
            tempinit: quote! {
                let mut #tempname: Option<::xso::exports::minidom::Element> = None;
            },
            childiter: quote! {
                residual = if #test {
                    if #tempname.is_some() {
                        return Err(::xso::error::Error::ParseError(#duperr));
                    }
                    #tempname = Some(residual);
                    continue;
                } else {
                    residual
                };
            },
            value: quote! {
                if let Some(v) = #tempname {
                    #ty_from_element(v)
                } else {
                    #on_missing
                }
            },
            ..FieldParsePart::default()
        })
    }

    fn build_into_element(
        &self,
        _container_name: &ParentRef,
        _container_namespace_expr: &Expr,
        _member: &Member,
        ty: &Type,
        access: Expr,
    ) -> Result<TokenStream> {
        Ok(quote! {
            match <#ty as Into<Option<::xso::exports::minidom::Element>>>::into(#access) {
                Some(v) => builder.append(::xso::exports::minidom::Node::Element(v)),
                None => builder
            }
        })
    }

    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_try_from_element(
        &self,
        _container_name: &ParentRef,
        _container_namespace_expr: &Expr,
        tempname: Ident,
        _member: &Member,
        _ty: &Type,
    ) -> Result<FieldParsePart> {
        match self.selector {
            Some((ref field_namespace, ref field_name)) => {
                let childiter = match field_name {
                    // namespace match only
                    None => quote! {
                        residual = if residual.has_ns(#field_namespace) {
                            #tempname.push(residual);
                            continue;
                        } else {
                            residual
                        };
                    },
                    Some(field_name) => quote! {
                        residual = if residual.is(#field_name, #field_namespace) {
                            #tempname.push(residual);
                            continue;
                        } else {
                            residual
                        };
                    },
                };
                Ok(FieldParsePart {
                    tempinit: quote! {
                        let mut #tempname: Vec<::xso::exports::minidom::Element> = Vec::new();
                    },
                    childiter,
                    value: quote! { #tempname },
                    ..FieldParsePart::default()
                })
            }
            None => Ok(FieldParsePart {
                tempinit: quote! {
                    let mut #tempname: Vec<::xso::exports::minidom::Element> = Vec::new();
                },
                childfallback: Some(quote! {
                    #tempname.push(residual);
                }),
                value: quote! { #tempname },
                ..FieldParsePart::default()
            }),
        }
    }

    fn build_into_element(
        &self,
        _container_name: &ParentRef,
        _container_namespace_expr: &Expr,
        _member: &Member,
        _ty: &Type,
        access: Expr,
    ) -> Result<TokenStream> {
        Ok(quote! {
            builder.append_all(#access.into_iter().map(|elem| ::xso::exports::minidom::Node::Element(elem)))
        })
    }

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