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
//! Infrastructure for parsing boolean fields indicating child presence.
use proc_macro2::{Span, TokenStream};

use quote::quote;
use syn::*;

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

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

/// A field parsed from the presence of an empty XML child.
///
/// Maps to `#[xml(flag)]`.
#[derive(Debug)]
pub(crate) struct FlagField {
    /// The XML namespace of the child element to look for.
    namespace: StaticNamespace,

    /// The XML name of the child element to look for.
    name: Name,
}

impl FlagField {
    /// Construct a new `#[xml(flag)]` field.
    ///
    /// `namespace` and `name` must both be set and `namespace` must be a
    /// [`NamespaceRef::Static`].
    ///
    /// `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 => {
                return Err(Error::new(
                    attr_span.clone(),
                    "#[xml(flag)] requires namespace attribute",
                ))
            }
            Some(NamespaceRef::Static(ns)) => ns,
            Some(NamespaceRef::Dyn(ns)) => {
                return Err(Error::new_spanned(
                    ns,
                    "dynamic namespaces cannot be used with #[xml(flag)]",
                ))
            }
            Some(NamespaceRef::Super(ns)) => {
                return Err(Error::new_spanned(
                    ns,
                    "flag elements cannot refer to the parent namespace",
                ))
            }
        };
        let name = match name {
            None => {
                return Err(Error::new(
                    attr_span.clone(),
                    "#[xml(flag)] requires name attribute",
                ))
            }
            Some(name) => name,
        };
        Ok(Self {
            namespace,
            name: name.into(),
        })
    }
}

impl Field for FlagField {
    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 child_name = &self.name;
        let child_namespace = &self.namespace;
        let access = scope.access_field(member);
        let duperr = error_message::on_duplicate_child(container_name, member);
        Ok(FieldFromEventsPart::Nested {
            extra_defs: TokenStream::default(),
            temp: FieldTempInit {
                ty: Type::Path(TypePath {
                    qself: None,
                    path: Ident::new("bool", Span::call_site()).into(),
                }),
                init: quote! { false },
            },
            matcher: NestedMatcher::Inline(quote! {
                if #start_ev_qname.0 == #child_namespace && #start_ev_qname.1 == #child_name {
                    if #access {
                        ::std::result::Result::Err(::xso::FromEventsError::Invalid(::xso::error::Error::ParseError(#duperr)))
                    } else {
                        // TODO: reject contents
                        ::std::result::Result::Ok(::xso::DiscardEvents::new())
                    }
                } else {
                    ::std::result::Result::Err(::xso::FromEventsError::Mismatch { name: #start_ev_qname, attrs: #start_ev_attrs })
                }
            }),
            builder: discard_events_ty(Span::call_site()),
            collect: quote! {
                let _ = #substate_result;
                #access = true;
            },
            finish: quote! {
                #access
            },
        })
    }

    fn build_into_events_iterator(
        &self,
        _scope: &Scope,
        _container_name: &ParentRef,
        tempname: Ident,
        _member: &Member,
        _ty: &Type,
    ) -> Result<FieldIntoEventsPart> {
        let child_name = &self.name;
        let child_namespace = &self.namespace;
        let state_ty = primitive_ty("u8", Span::call_site());
        Ok(FieldIntoEventsPart::ContentMut {
            extra_defs: TokenStream::default(),
            ty: state_ty,
            init: quote! {
                if #tempname {
                    0
                } else {
                    255
                }
            },
            emitter: quote! {
                match #tempname {
                    0 => {
                        #tempname = 1;
                        ::std::option::Option::Some(::xso::exports::rxml::Event::StartElement(
                        ::xso::exports::rxml::parser::EventMetrics::zero(),
                            (
                                ::xso::exports::rxml::Namespace::try_from(#child_namespace)?,
                                ::xso::exports::rxml::NcName::try_from(#child_name)?,
                            ),
                            ::xso::exports::rxml::AttrMap::new(),
                        ))
                    },
                    1 => {
                        #tempname = 2;
                        ::std::option::Option::Some(::xso::exports::rxml::Event::EndElement(
                        ::xso::exports::rxml::parser::EventMetrics::zero(),
                        ))
                    },
                    _ => ::std::option::Option::None,
                }
            },
        })
    }

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