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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
use indextree::NodeId;
use xmlparser::{ElementEnd, Token, Tokenizer};

use crate::entity::{parse_attribute, parse_text};
use crate::error::Error;
use crate::name::{Name, NameId};
use crate::namespace::Namespace;
use crate::prefix::{Prefix, PrefixId};
use crate::xmlvalue::{
    Attributes, Comment, Element, NamespaceInfo, ProcessingInstruction, Text, ToNamespace, Value,
};
use crate::xotdata::{Node, Xot};

struct ElementBuilder {
    prefix: String,
    name: String,
    namespace_info: NamespaceInfo,
    attributes: Vec<((String, String), String)>,
}

impl ElementBuilder {
    fn new(prefix: String, name: String) -> Self {
        ElementBuilder {
            prefix,
            name,
            namespace_info: NamespaceInfo::new(),
            attributes: Vec::new(),
        }
    }

    fn build_attributes(
        &mut self,
        document_builder: &mut DocumentBuilder,
    ) -> Result<Attributes, Error> {
        let mut attributes = Attributes::new();
        for ((prefix, name), value) in self.attributes.drain(..) {
            let name_id = document_builder.name_id_builder.attribute_name_id(
                prefix,
                name,
                document_builder.xot,
            )?;
            attributes.insert(name_id, value);
        }
        Ok(attributes)
    }

    fn into_element(mut self, document_builder: &mut DocumentBuilder) -> Result<Element, Error> {
        document_builder
            .name_id_builder
            .push(&self.namespace_info.to_namespace);
        let attributes = self.build_attributes(document_builder)?;
        let name_id = document_builder.name_id_builder.element_name_id(
            self.prefix,
            self.name,
            document_builder.xot,
        )?;
        Ok(Element {
            name_id,
            namespace_info: self.namespace_info,
            attributes,
        })
    }
}

struct DocumentBuilder<'a> {
    xot: &'a mut Xot,
    tree: NodeId,
    current_node_id: NodeId,
    name_id_builder: NameIdBuilder,
    element_builder: Option<ElementBuilder>,
}

impl<'a> DocumentBuilder<'a> {
    fn new(xot: &'a mut Xot) -> Self {
        let root = xot.arena.new_node(Value::Root);
        let mut name_id_builder = NameIdBuilder::new(xot.base_to_namespace());
        let mut base_to_namespace = ToNamespace::new();
        base_to_namespace.insert(xot.empty_prefix_id, xot.no_namespace_id);
        name_id_builder.push(&base_to_namespace);
        DocumentBuilder {
            xot,
            tree: root,
            current_node_id: root,
            name_id_builder,
            element_builder: None,
        }
    }

    fn element(&mut self, prefix: &str, name: &str) {
        self.element_builder = Some(ElementBuilder::new(prefix.to_string(), name.to_string()));
    }

    fn prefix(&mut self, prefix: &'a str, namespace_uri: &'a str) {
        let prefix_id = self
            .xot
            .prefix_lookup
            .get_id_mut(Prefix::new(prefix.into()));
        let namespace_id = self
            .xot
            .namespace_lookup
            .get_id_mut(Namespace::new(namespace_uri.into()));
        self.element_builder
            .as_mut()
            .unwrap()
            .namespace_info
            .add(prefix_id, namespace_id);
    }

    fn attribute(&mut self, prefix: &'a str, name: &'a str, value: &'a str) -> Result<(), Error> {
        let attributes = &mut self.element_builder.as_mut().unwrap().attributes;
        let is_duplicate = attributes
            .iter()
            .any(|((p, n), _)| p == prefix && n == name);
        if is_duplicate {
            let attr_name = if prefix.is_empty() {
                name.to_string()
            } else {
                format!("{}:{}", prefix, name)
            };
            return Err(Error::DuplicateAttribute(attr_name));
        }
        attributes.push((
            (prefix.into(), name.into()),
            parse_attribute(value.into())?.to_string(),
        ));
        Ok(())
    }

    fn add(&mut self, value: Value) -> NodeId {
        let node_id = self.xot.arena.new_node(value);
        self.current_node_id.append(node_id, &mut self.xot.arena);
        node_id
    }

    fn open_element(&mut self) -> Result<(), Error> {
        let element_builder = self.element_builder.take().unwrap();
        let element = Value::Element(element_builder.into_element(self)?);
        let node_id = self.add(element);
        self.current_node_id = node_id;
        Ok(())
    }

    fn text(&mut self, content: &str) -> Result<(), Error> {
        let content = parse_text(content.into())?;
        self.add(Value::Text(Text::new(content.to_string())));
        Ok(())
    }

    fn close_element_immediate(&mut self) {
        let current_node = self.xot.arena.get(self.current_node_id).unwrap();
        if let Value::Element(element) = current_node.get() {
            self.name_id_builder
                .pop(&element.namespace_info.to_namespace);
        }
        self.current_node_id = current_node.parent().expect("Cannot close root node");
    }

    fn close_element(&mut self, prefix: &str, name: &str) -> Result<(), Error> {
        let name_id =
            self.name_id_builder
                .element_name_id(prefix.to_string(), name.to_string(), self.xot)?;
        let current_node = self.xot.arena.get(self.current_node_id).unwrap();
        if let Value::Element(element) = current_node.get() {
            if element.name_id != name_id {
                return Err(Error::InvalidCloseTag(prefix.to_string(), name.to_string()));
            }
            self.name_id_builder
                .pop(&element.namespace_info.to_namespace);
        }
        self.current_node_id = current_node.parent().expect("Cannot close root node");
        Ok(())
    }

    fn comment(&mut self, content: &str) -> Result<(), Error> {
        // XXX are there illegal comments, like those with -- inside? or
        // won't they pass the parser?
        self.add(Value::Comment(Comment::new(content.to_string())));
        Ok(())
    }

    fn processing_instruction(&mut self, target: &str, content: Option<&str>) -> Result<(), Error> {
        // XXX are there illegal processing instructions, like those with
        // ?> inside? or won't they pass the parser?
        self.add(Value::ProcessingInstruction(ProcessingInstruction::new(
            target.to_string(),
            content.map(|s| s.to_string()),
        )));
        Ok(())
    }

    fn is_current_node_root(&self) -> bool {
        matches!(self.xot.arena[self.current_node_id].get(), Value::Root)
    }
}

struct NameIdBuilder {
    namespace_stack: Vec<ToNamespace>,
}

impl NameIdBuilder {
    fn new(to_namespace: ToNamespace) -> Self {
        let namespace_stack = vec![to_namespace];
        Self { namespace_stack }
    }

    fn push(&mut self, to_namespace: &ToNamespace) {
        if to_namespace.is_empty() {
            return;
        }
        // can always use top as there's a bottom entry
        let mut entry = self.top().clone();
        entry.extend(to_namespace);
        self.namespace_stack.push(entry);
    }

    fn pop(&mut self, to_namespace: &ToNamespace) {
        if to_namespace.is_empty() {
            return;
        }
        // should always be able to pop as there's a bottom entry
        self.namespace_stack.pop();
    }

    #[inline]
    fn top(&self) -> &ToNamespace {
        &self.namespace_stack[self.namespace_stack.len() - 1]
    }

    fn element_name_id(
        &mut self,
        prefix: String,
        name: String,
        xot: &mut Xot,
    ) -> Result<NameId, Error> {
        let prefix_clone = prefix.clone();
        let prefix_id = xot.prefix_lookup.get_id_mut(Prefix::new(prefix));
        if let Ok(name_id) = self.name_id_with_prefix_id(prefix_id, name, xot) {
            Ok(name_id)
        } else {
            Err(Error::UnknownPrefix(prefix_clone))
        }
    }

    fn attribute_name_id(
        &mut self,
        prefix: String,
        name: String,
        xot: &mut Xot,
    ) -> Result<NameId, Error> {
        // an unprefixed attribute is in no namespace, not
        // in the default namespace
        // https://stackoverflow.com/questions/3312390/xml-default-namespaces-for-unqualified-attribute-names
        let prefix_clone = prefix.clone();
        let prefix_id = xot.prefix_lookup.get_id_mut(Prefix::new(prefix));
        if prefix_id == xot.empty_prefix_id {
            let name = Name::new(name, xot.no_namespace_id);
            return Ok(xot.name_lookup.get_id_mut(name));
        }
        if let Ok(name_id) = self.name_id_with_prefix_id(prefix_id, name, xot) {
            Ok(name_id)
        } else {
            Err(Error::UnknownPrefix(prefix_clone))
        }
    }

    fn name_id_with_prefix_id(
        &mut self,
        prefix_id: PrefixId,
        name: String,
        xot: &mut Xot,
    ) -> Result<NameId, ()> {
        let namespace_id = if !self.namespace_stack.is_empty() {
            self.top().get(&prefix_id)
        } else {
            None
        };
        let namespace_id = namespace_id.ok_or(())?;
        let name = Name::new(name, *namespace_id);
        Ok(xot.name_lookup.get_id_mut(name))
    }
}

/// ## Parsing
impl Xot {
    /// Parse a string containing XML into a node.
    ///
    /// The returned node is the root node of the
    /// parsed XML document.
    ///
    /// ```rust
    /// use xot::Xot;
    ///
    /// let mut xot = Xot::new();
    /// let root = xot.parse("<hello/>").unwrap();
    /// ```
    pub fn parse(&mut self, xml: &str) -> Result<Node, Error> {
        use Token::*;

        let mut builder = DocumentBuilder::new(self);

        for token in Tokenizer::from(xml) {
            match token? {
                Attribute {
                    prefix,
                    local,
                    value,
                    span: _,
                } => {
                    if prefix.as_str() == "xmlns" {
                        builder.prefix(local.as_str(), value.as_str());
                    } else if local.as_str() == "xmlns" {
                        builder.prefix("", value.as_str());
                    } else {
                        builder.attribute(prefix.as_str(), local.as_str(), value.as_str())?;
                    }
                }
                Text { text } => {
                    builder.text(text.as_str())?;
                }
                ElementStart {
                    prefix,
                    local,
                    span: _,
                } => {
                    builder.element(prefix.as_str(), local.as_str());
                }
                ElementEnd { end, span: _ } => {
                    use self::ElementEnd::*;

                    match end {
                        Open => {
                            builder.open_element()?;
                        }
                        Close(prefix, local) => {
                            builder.close_element(prefix.as_str(), local.as_str())?;
                        }
                        Empty => {
                            builder.open_element()?;
                            builder.close_element_immediate();
                        }
                    }
                }
                Comment { text, span: _ } => {
                    builder.comment(text.as_str())?;
                }
                ProcessingInstruction {
                    target,
                    content,
                    span: _,
                } => {
                    builder.processing_instruction(target.as_str(), content.map(|s| s.as_str()))?
                }
                Declaration {
                    version,
                    encoding,
                    standalone,
                    span: _,
                } => {
                    if version.as_str() != "1.0" {
                        return Err(Error::UnsupportedVersion(version.to_string()));
                    }
                    if let Some(encoding) = encoding {
                        if encoding.as_str() != "UTF-8" {
                            return Err(Error::UnsupportedEncoding(encoding.to_string()));
                        }
                    }
                    if let Some(standalone) = standalone {
                        if !standalone {
                            return Err(Error::UnsupportedNotStandalone);
                        }
                    }
                }
                Cdata { text, span: _ } => {
                    builder.text(text.as_str())?;
                }
                DtdStart { .. } => {
                    return Err(Error::DtdUnsupported);
                }
                DtdEnd { .. } => {
                    return Err(Error::DtdUnsupported);
                }
                EmptyDtd { .. } => {
                    return Err(Error::DtdUnsupported);
                }
                EntityDeclaration { .. } => {
                    return Err(Error::DtdUnsupported);
                }
            }
        }

        if builder.is_current_node_root() {
            Ok(Node::new(builder.tree))
        } else {
            Err(Error::UnclosedTag)
        }
    }
}