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
//! Infrastructure for parsing fields from attributes.
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, StaticNamespace};
use crate::types::*;

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

/// A field parsed from an XML attribute.
///
/// Maps to `#[xml(attribute)]`.
#[derive(Debug)]
pub(crate) struct AttributeField {
    /// The XML namespace of the attribute.
    pub(super) namespace: Option<StaticNamespace>,

    /// The XML name of the attribute.
    pub(super) name: Name,

    /// Whether [`Default`] or a given callable should be used to obtain a
    /// value if the attribute is missing.
    ///
    /// If the flag is *not* set, an error is returned when parsing an element
    /// without the attribute.
    pub(super) default_: FlagOr<Path>,

    /// The codec implementation to use.
    ///
    /// If set, parsing does not use the `FromXmlText` / `IntoXmlText` traits
    /// but instead uses the `TextCodec` trait on the given type.
    pub(super) codec: Option<Type>,
}

impl AttributeField {
    /// Construct a new `#[xml(attribute)]` field.
    ///
    /// The `field_ident` must be the field's identifier (if in a named
    /// compound).
    ///
    /// `name` must be the XML name assigned to the attribtue, if any, as
    /// parsed from the `#[xml(..)]` meta on the field.
    ///
    /// `default_on_missing` must be the `default` flag as parsed from the
    /// `#[xml(..)]` meta on the field.
    ///
    /// `codec` must be the value of the `codec = ..` option, which, if given
    /// overrides how the attribute's text is converted to a rust value.
    ///
    /// `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,
        field_ident: Option<&Ident>,
        namespace: Option<StaticNamespace>,
        name: Option<NameRef>,
        default_: FlagOr<Path>,
        codec: Option<Type>,
    ) -> Result<Self> {
        let name = name
            .map(Name::Lit)
            .or_else(|| field_ident.map(|ident| Name::Ident(ident.clone())));
        let Some(name) = name else {
            return Err(Error::new(attr_span.clone(), "missing attribute name on unnamed field. specify using #[xml(attribute = \"foo\")]"));
        };

        Ok(Self {
            namespace,
            name,
            default_,
            codec,
        })
    }
}

impl Field for AttributeField {
    fn build_from_events_builder(
        &self,
        scope: &Scope,
        container_name: &ParentRef,
        _tempname: Ident,
        member: &Member,
        ty: &Type,
    ) -> Result<FieldFromEventsPart> {
        let Scope { ref attrs, .. } = scope;

        let missing_msg = error_message::on_missing_attribute(container_name, &member);
        let name = &self.name;
        let namespace = match self.namespace.as_ref() {
            Some(namespace) => quote! { #namespace },
            None => quote! { ::xso::exports::rxml::Namespace::none() },
        };
        let on_missing = match self.default_ {
            FlagOr::Absent => {
                quote! {
                    return Err(::xso::error::Error::ParseError(
                        #missing_msg,
                    ).into())
                }
            }
            FlagOr::Present(_) => default_value(ty.clone()).into_token_stream(),
            FlagOr::Value { ref value, .. } => {
                quote! {
                    #value()
                }
            }
        };
        // TODO: namespaced attributes
        let lookup = quote! {
            .remove(#namespace, #name)
        };
        // TODO: CData support
        let fetch = match self.codec {
            Some(ref codec_ty) => {
                let codec_ty_decode = text_codec_decode_fn(codec_ty.clone(), ty.clone());
                quote! {
                    #attrs #lookup.map(|s| #codec_ty_decode(s.as_str())).transpose()?
                }
            }
            None => {
                let ty_from_optional_xml_text = from_optional_xml_text_fn(ty.clone());
                quote! {
                    #ty_from_optional_xml_text(#attrs #lookup.as_ref().map(|x| x.as_str()))?
                }
            }
        };

        Ok(FieldFromEventsPart::Init {
            value: FieldTempInit {
                ty: ty.clone(),
                init: quote! {
                    match #fetch {
                        Some(v) => v,
                        None => #on_missing,
                    }
                },
            },
        })
    }

    fn build_into_events_iterator(
        &self,
        scope: &Scope,
        _container_name: &ParentRef,
        tempname: Ident,
        _member: &Member,
        ty: &Type,
    ) -> Result<FieldIntoEventsPart> {
        let Scope { ref attrs, .. } = scope;

        let encode = match self.codec {
            Some(ref codec_ty) => {
                let codec_ty_encode = text_codec_encode_fn(codec_ty.clone(), ty.clone());
                quote! {
                    #codec_ty_encode(#tempname)
                }
            }
            None => {
                let ty_into_optional_xml_text = into_optional_xml_text_fn(ty.clone());
                quote! {
                    #ty_into_optional_xml_text(#tempname)
                }
            }
        };
        let name = &self.name;
        let namespace = match self.namespace.as_ref() {
            Some(namespace) => quote! {
                ::xso::exports::rxml::Namespace::try_from(#namespace)?
            },
            None => quote! { ::xso::exports::rxml::Namespace::NONE },
        };

        Ok(FieldIntoEventsPart::Header {
            setter: quote! {
                match #encode {
                    Some(v) => {
                        #attrs.insert(#namespace, #name.try_into()?, v.try_into()?);
                    },
                    None => (),
                };
            },
        })
    }

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