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

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

use crate::common::Scope;
use crate::error_message::ParentRef;
use crate::types::*;

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

/// A field parsed from a XML text.
///
/// Maps to `#[xml(text)]`.
#[derive(Debug)]
pub(crate) struct TextField {
    /// 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 TextField {
    /// Construct a new `#[xml(text)]` field.
    ///
    /// `codec` must be the value of the `codec = ..` option, which, if given
    /// overrides how the 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, codec: Option<Type>) -> Result<Self> {
        Ok(Self { codec })
    }
}

impl Field for TextField {
    fn is_text(&self) -> bool {
        true
    }

    fn build_from_events_builder(
        &self,
        scope: &Scope,
        _container_name: &ParentRef,
        _tempname: Ident,
        member: &Member,
        ty: &Type,
    ) -> Result<FieldFromEventsPart> {
        let Scope { ref text, .. } = scope;
        let access = scope.access_field(member);
        let decode = match self.codec {
            Some(ref codec_ty) => {
                let codec_ty_decode = text_codec_decode_fn(codec_ty.clone(), ty.clone());
                quote! {
                    #codec_ty_decode(#access.0.as_str())?
                }
            }
            None => {
                let ty_from_xml_text = from_xml_text_fn(ty.clone());
                quote! {
                    #ty_from_xml_text(#access.0.as_str())?
                }
            }
        };
        let field_ty = Type::Tuple(TypeTuple {
            paren_token: syn::token::Paren::default(),
            elems: [string_ty(Span::call_site()), phantom_ty(ty.clone())]
                .into_iter()
                .collect(),
        });
        Ok(FieldFromEventsPart::Text {
            temp: FieldTempInit {
                ty: field_ty,
                init: quote! { (
                    ::std::string::String::new(),
                    ::std::marker::PhantomData::<#ty>,
                ) },
            },
            accum: quote! {
                #access.0.push_str(&#text);
            },
            finalize: decode,
        })
    }

    fn build_into_events_iterator(
        &self,
        _scope: &Scope,
        _container_name: &ParentRef,
        tempname: Ident,
        _member: &Member,
        ty: &Type,
    ) -> Result<FieldIntoEventsPart> {
        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).unwrap_or_else(String::new)
                }
            }
            None => {
                let ty_into_xml_text = into_xml_text_fn(ty.clone());
                quote! {
                    #ty_into_xml_text(#tempname)
                }
            }
        };

        Ok(FieldIntoEventsPart::ContentConsume {
            prepare: quote! { #tempname },
            emitter: quote! {
                {
                    let value = #encode;
                    if value.len() > 0 {
                        ::std::option::Option::Some(::xso::exports::rxml::Event::Text(::xso::exports::rxml::parser::EventMetrics::zero(), value.try_into()?))
                    } else {
                        ::std::option::Option::None
                    }
                }
            },
        })
    }

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