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
#![doc=include_str!("../README.md")]
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::Ident;
use quote::{quote, ToTokens};
use syn::{
    ext::IdentExt as _,
    parse::{Parse, ParseStream},
    parse_macro_input,
    spanned::Spanned,
    token, Block, LitStr, Token,
};

/// An xml tag
struct XmlTag {
    /// The open token
    #[allow(dead_code)]
    open: Token![<],
    is_end_tag: Option<Token![/]>,
    name: XmlId,
    attributes: Vec<XmlAttribute>,
    self_close: Option<Token![/]>,
    #[allow(dead_code)]
    close: Token![>],
}

impl Parse for XmlTag {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        Ok(Self {
            open: input.parse()?,
            is_end_tag: input.parse()?,
            name: input.parse()?,
            attributes: {
                let mut vec = Vec::new();
                loop {
                    let lookahead = input.lookahead1();
                    if lookahead.peek(Token![/]) || lookahead.peek(Token![>]) {
                        break;
                    } else {
                        vec.push(input.parse()?)
                    }
                }
                vec
            },
            self_close: input.parse()?,
            close: input.parse()?,
        })
    }
}

struct XmlId(Vec<ExtraXmlIdSeg>);

impl XmlId {
    pub fn to_lit_str(&self) -> LitStr {
        let mut buf = String::new();
        for x in &self.0 {
            match x {
                ExtraXmlIdSeg::Ident(x) => buf.push_str(&x.to_string()),
                ExtraXmlIdSeg::Dot(_) => buf.push('.'),
                ExtraXmlIdSeg::Colon(_) => buf.push(':'),
                ExtraXmlIdSeg::Dash(_) => buf.push('-'),
            }
        }
        LitStr::new(&buf, self.0[0].span())
    }
}

impl Parse for XmlId {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut vec = Vec::new();
        let mut last_one_ident = false;
        loop {
            if (input.peek(syn::Ident::peek_any) && !last_one_ident)
                || input.peek(Token![.])
                || input.peek(Token![:])
                || input.peek(Token![-])
            {
                if input.peek(syn::Ident::peek_any) {
                    last_one_ident = true;
                } else {
                    last_one_ident = false;
                }
                vec.push(input.parse()?);
            } else {
                break;
            }
        }
        Ok(Self(vec))
    }
}

impl ToTokens for XmlId {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        for seg in &self.0 {
            seg.to_tokens(tokens);
        }
    }
}

enum ExtraXmlIdSeg {
    Ident(Ident),
    Dot(Token![.]),
    Colon(Token![:]),
    Dash(Token![-]),
}

impl ExtraXmlIdSeg {
    fn span(&self) -> proc_macro2::Span {
        match self {
            ExtraXmlIdSeg::Ident(x) => x.span(),
            ExtraXmlIdSeg::Dot(x) => x.span(),
            ExtraXmlIdSeg::Colon(x) => x.span(),
            ExtraXmlIdSeg::Dash(x) => x.span(),
        }
    }
}

impl Parse for ExtraXmlIdSeg {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let lookahead = input.lookahead1();
        if lookahead.peek(Token![.]) {
            Ok(ExtraXmlIdSeg::Dot(input.parse()?))
        } else if lookahead.peek(Token![:]) {
            Ok(ExtraXmlIdSeg::Colon(input.parse()?))
        } else if lookahead.peek(Token![-]) {
            Ok(ExtraXmlIdSeg::Dash(input.parse()?))
        } else {
            Ok(ExtraXmlIdSeg::Ident(input.parse()?))
        }
    }
}

impl ToTokens for ExtraXmlIdSeg {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        match self {
            Self::Dot(x) => x.to_tokens(tokens),
            Self::Colon(x) => x.to_tokens(tokens),
            Self::Dash(x) => x.to_tokens(tokens),
            Self::Ident(x) => x.to_tokens(tokens),
        }
    }
}

/// An attribute in xml, such as `name="Josh"`
struct XmlAttribute {
    name: XmlId,
    #[allow(dead_code)]
    eq: Token![=],
    value: XmlVal,
}

impl Parse for XmlAttribute {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        Ok(Self {
            name: input.parse()?,
            eq: input.parse()?,
            value: input.parse()?,
        })
    }
}

enum XmlVal {
    Str(LitStr),
    Block(Block),
}

impl ToTokens for XmlVal {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        match self {
            Self::Str(x) => x.to_tokens(tokens),
            Self::Block(x) => quote! {#x}.to_tokens(tokens),
        }
    }
}

impl Parse for XmlVal {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let lookahead = input.lookahead1();
        if lookahead.peek(token::Brace) {
            Ok(XmlVal::Block(input.parse()?))
        } else {
            Ok(XmlVal::Str(input.parse()?))
        }
    }
}

#[proc_macro]
pub fn xml(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as XmlTag);
    let mut attrs = Vec::new();
    for attribute in input.attributes {
        let name = attribute.name.to_lit_str();
        let val = attribute.value;
        attrs.push(quote! {
            event_start.push_attribute((#name, #val));
        });
    }

    let name = input.name.to_lit_str();
    let expanded = if input.is_end_tag.is_some() {
        if input.self_close.is_some() {
            quote! { compile_error!("Tag cannot start with `</` and end with `/>`") }
        } else {
            if !attrs.is_empty() {
                quote! { compile_error!("End tag cannot have attribute") }
            } else {
                quote! {{
                let mut event = ::quick_xml::events::BytesEnd::new(#name);
                ::quick_xml::events::Event::End(event)
                }}
            }
        }
    } else {
        let event_type = if input.self_close.is_some() {
            quote! {Empty}
        } else {
            quote! {Start}
        };
        quote! {{
            let mut event_start = ::quick_xml::events::BytesStart::new(#name);
            #(#attrs)*
            ::quick_xml::events::Event::#event_type(event_start)
        }}
    };

    TokenStream::from(expanded)
}