Skip to main content

parsec_xml/
tree.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! The document: an arena of nodes linked by index, the attributes in one
5//! vector, every string in one buffer, and names interned once each.
6
7use std::collections::HashMap;
8use std::fmt;
9
10use parsec_base::{Diagnostic, Span};
11
12/// The namespace the `xml` prefix is bound to, always.
13pub const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
14/// The namespace of `xmlns` and `xmlns:*` attributes.
15pub const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/";
16
17pub(crate) const NONE: u32 = u32::MAX;
18/// Namespace ids: 0 is no namespace.
19pub(crate) const NS_XML: u32 = 1;
20pub(crate) const NS_XMLNS: u32 = 2;
21
22/// A node of a [`Document`].
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
24pub struct NodeId(pub(crate) u32);
25
26impl NodeId {
27    /// Its place in the document's arena, which is document order.
28    pub fn index(self) -> usize {
29        self.0 as usize
30    }
31
32    /// The node at `index` in the arena: what [`NodeId::index`] gives
33    /// back, and what an XPath result names a node by. It's only a node of
34    /// the document whose `index` it came from.
35    ///
36    /// # Panics
37    ///
38    /// If `index` is over `u32::MAX`, which no document's ids reach.
39    pub fn from_index(index: usize) -> NodeId {
40        NodeId(u32::try_from(index).expect("a node index fits in a u32"))
41    }
42}
43
44/// A range of [`Document`]'s string buffer.
45#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
46pub(crate) struct Str {
47    pub start: u32,
48    pub len: u32,
49}
50
51impl Str {
52    pub fn end(self) -> u32 {
53        self.start + self.len
54    }
55}
56
57#[derive(Clone, Copy, Debug)]
58pub(crate) enum Data {
59    Document,
60    Doctype,
61    Element {
62        name: u32,
63        ns: u32,
64        attrs: u32,
65        attrs_len: u32,
66    },
67    Text(Str),
68    Cdata(Str),
69    Comment(Str),
70    Pi {
71        target: Str,
72        data: Str,
73    },
74    EntityRef(Str),
75}
76
77#[derive(Clone, Copy, Debug)]
78pub(crate) struct Node {
79    pub parent: u32,
80    pub first: u32,
81    pub last: u32,
82    pub prev: u32,
83    pub next: u32,
84    pub span: Span,
85    pub data: Data,
86}
87
88#[derive(Clone, Copy, Debug)]
89pub(crate) struct AttrData {
90    pub name: u32,
91    pub ns: u32,
92    pub value: Str,
93    pub span: Span,
94    pub specified: bool,
95}
96
97/// Prefix ids: 0 is no prefix.
98pub(crate) const PREFIX_XML: u32 = 1;
99pub(crate) const PREFIX_XMLNS: u32 = 2;
100
101#[derive(Debug)]
102pub(crate) struct QName {
103    pub qname: Box<str>,
104    /// Where the colon is: `NONE` for none, or with namespaces off.
105    pub colon: u32,
106    pub prefix: u32,
107}
108
109/// Element and attribute names, prefixes and namespace URIs, each stored
110/// once.
111#[derive(Debug)]
112pub(crate) struct Names {
113    qnames: Vec<QName>,
114    qname_ids: HashMap<Box<str>, u32>,
115    prefix_ids: HashMap<Box<str>, u32>,
116    uris: Vec<Box<str>>,
117    uri_ids: HashMap<Box<str>, u32>,
118}
119
120/// Names a document can have before they're looked up by hash.
121const SCAN: usize = 16;
122
123/// The URIs and prefixes every document has, which take no allocation.
124const BUILTIN_URIS: [&str; 3] = ["", XML_NS, XMLNS_NS];
125const BUILTIN_PREFIXES: [&str; 3] = ["", "xml", "xmlns"];
126
127impl Names {
128    pub fn new() -> Names {
129        Names {
130            qnames: Vec::new(),
131            qname_ids: HashMap::new(),
132            prefix_ids: HashMap::new(),
133            uris: Vec::new(),
134            uri_ids: HashMap::new(),
135        }
136    }
137
138    pub fn get(&self, qname: &str) -> Option<u32> {
139        // A small document's few names are quicker found by looking at
140        // each than by hashing; the map is built once there are more.
141        if self.qnames.len() <= SCAN {
142            return self
143                .qnames
144                .iter()
145                .position(|q| &*q.qname == qname)
146                .map(|i| i as u32);
147        }
148        self.qname_ids.get(qname).copied()
149    }
150
151    /// Adds a name [`Names::get`] didn't find.
152    pub fn insert(&mut self, qname: &str, colon: u32) -> u32 {
153        let prefix = match colon {
154            NONE => 0,
155            c => self.prefix(&qname[..c as usize]),
156        };
157        let id = self.qnames.len() as u32;
158        self.qnames.push(QName {
159            qname: qname.into(),
160            colon,
161            prefix,
162        });
163        if self.qnames.len() == SCAN + 1 {
164            self.qname_ids = self
165                .qnames
166                .iter()
167                .enumerate()
168                .map(|(i, q)| (q.qname.clone(), i as u32))
169                .collect();
170        } else if self.qnames.len() > SCAN + 1 {
171            self.qname_ids.insert(qname.into(), id);
172        }
173        id
174    }
175
176    pub fn prefix(&mut self, prefix: &str) -> u32 {
177        if let Some(i) = BUILTIN_PREFIXES.iter().position(|&p| p == prefix) {
178            return i as u32;
179        }
180        if let Some(&id) = self.prefix_ids.get(prefix) {
181            return id;
182        }
183        let id = (BUILTIN_PREFIXES.len() + self.prefix_ids.len()) as u32;
184        self.prefix_ids.insert(prefix.into(), id);
185        id
186    }
187
188    pub fn uri(&mut self, uri: &str) -> u32 {
189        if let Some(i) = BUILTIN_URIS.iter().position(|&u| u == uri) {
190            return i as u32;
191        }
192        if let Some(&id) = self.uri_ids.get(uri) {
193            return id;
194        }
195        let id = (BUILTIN_URIS.len() + self.uris.len()) as u32;
196        self.uris.push(uri.into());
197        self.uri_ids.insert(uri.into(), id);
198        id
199    }
200
201    pub fn qname_info(&self, id: u32) -> &QName {
202        &self.qnames[id as usize]
203    }
204
205    pub fn qname_str(&self, id: u32) -> &str {
206        &self.qnames[id as usize].qname
207    }
208
209    /// The part after the colon, or all of it.
210    pub fn local(&self, id: u32) -> &str {
211        let q = &self.qnames[id as usize];
212        match q.colon {
213            NONE => &q.qname,
214            c => &q.qname[c as usize + 1..],
215        }
216    }
217
218    pub fn uri_str(&self, id: u32) -> &str {
219        match BUILTIN_URIS.get(id as usize) {
220            Some(u) => u,
221            None => &self.uris[id as usize - BUILTIN_URIS.len()],
222        }
223    }
224
225    fn name(&self, qname: u32, ns: u32) -> Name<'_> {
226        let q = &self.qnames[qname as usize];
227        let (prefix, local) = match q.colon {
228            NONE => ("", &*q.qname),
229            c => (&q.qname[..c as usize], &q.qname[c as usize + 1..]),
230        };
231        Name {
232            qname: &q.qname,
233            prefix,
234            local,
235            namespace: self.uri_str(ns),
236        }
237    }
238}
239
240/// An element's or attribute's name: as written, and resolved.
241#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
242pub struct Name<'a> {
243    /// The name as written, prefix and all: `atom:link`.
244    pub qname: &'a str,
245    /// The prefix, `""` for none.
246    pub prefix: &'a str,
247    /// The local part: `link`.
248    pub local: &'a str,
249    /// The namespace URI the prefix was bound to, `""` for none.
250    pub namespace: &'a str,
251}
252
253impl fmt::Display for Name<'_> {
254    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255        f.write_str(self.qname)
256    }
257}
258
259/// An attribute of an element.
260#[derive(Clone, Copy, Debug, PartialEq, Eq)]
261pub struct Attribute<'a> {
262    pub name: Name<'a>,
263    /// The value, normalized as XML says: references replaced, and each
264    /// tab, line end and newline a space (and, for an attribute the
265    /// internal subset declares as anything but `CDATA`, spaces collapsed).
266    pub value: &'a str,
267    /// From the name to the closing quote; for a default from the DTD,
268    /// the element's start tag.
269    pub span: Span,
270    /// False for a default the DTD supplied.
271    pub specified: bool,
272}
273
274impl Attribute<'_> {
275    /// Whether this is a namespace declaration, `xmlns` or `xmlns:*`.
276    pub fn is_namespace_declaration(&self) -> bool {
277        self.name.namespace == XMLNS_NS
278    }
279}
280
281/// What a node is.
282#[derive(Clone, Copy, Debug, PartialEq, Eq)]
283pub enum NodeKind<'a> {
284    /// The root of the tree, above the document element.
285    Document,
286    /// The `<!DOCTYPE>`; [`Document::doctype`] has what it said.
287    Doctype,
288    Element(Name<'a>),
289    /// Character data, with line ends normalized and references replaced.
290    /// Adjacent character data is one node.
291    Text(&'a str),
292    /// A CDATA section's contents.
293    CData(&'a str),
294    Comment(&'a str),
295    ProcessingInstruction {
296        target: &'a str,
297        data: &'a str,
298    },
299    /// A reference to an entity this parser didn't read: one declared
300    /// external, or one an unread part of the DTD might declare. The
301    /// document's warnings say which.
302    EntityRef(&'a str),
303}
304
305/// The XML declaration, `<?xml version="1.0"?>`.
306#[derive(Clone, Debug, PartialEq, Eq)]
307pub struct XmlDecl {
308    pub version: String,
309    pub encoding: Option<String>,
310    pub standalone: Option<bool>,
311    pub span: Span,
312}
313
314/// What the `<!DOCTYPE>` said.
315#[derive(Clone, Debug, PartialEq, Eq)]
316pub struct Doctype {
317    /// The document element's name it gives.
318    pub name: String,
319    pub public_id: Option<String>,
320    /// The external subset's address. Parsec never reads it.
321    pub system_id: Option<String>,
322    /// The internal subset as written, without its brackets.
323    pub internal_subset: Option<String>,
324    pub span: Span,
325}
326
327/// An entity the internal subset declared.
328#[derive(Clone, Debug, PartialEq, Eq)]
329pub struct EntityDecl {
330    pub name: String,
331    /// A parameter entity (`<!ENTITY % name ...>`), for use in the DTD.
332    pub parameter: bool,
333    /// An internal entity's replacement text.
334    pub value: Option<String>,
335    pub public_id: Option<String>,
336    /// An external entity's address. Parsec never reads it.
337    pub system_id: Option<String>,
338    /// An unparsed entity's notation (`NDATA`).
339    pub notation: Option<String>,
340    pub span: Span,
341}
342
343/// A notation the internal subset declared.
344#[derive(Clone, Debug, PartialEq, Eq)]
345pub struct Notation {
346    pub name: String,
347    pub public_id: Option<String>,
348    pub system_id: Option<String>,
349    pub span: Span,
350}
351
352/// A parsed XML document.
353///
354/// Nodes are numbered in document order, from the document node at 0.
355/// Every node and attribute has the [`Span`] of the source it came from;
356/// a node an entity reference produced has the span of that reference.
357#[derive(Debug)]
358pub struct Document {
359    pub(crate) nodes: Vec<Node>,
360    pub(crate) attrs: Vec<AttrData>,
361    pub(crate) text: String,
362    pub(crate) names: Names,
363    pub(crate) decl: Option<XmlDecl>,
364    pub(crate) doctype: Option<Doctype>,
365    pub(crate) entities: Vec<EntityDecl>,
366    pub(crate) notations: Vec<Notation>,
367    /// The attribute the internal subset declares as an ID for each
368    /// element, both by qualified name id.
369    pub(crate) id_attrs: HashMap<u32, u32>,
370    /// For XPath, built on first use: see `xpath_tree.rs`.
371    #[cfg(feature = "xpath")]
372    pub(crate) xpath_attrs: std::sync::OnceLock<crate::xpath_tree::Declared>,
373    pub(crate) warnings: Vec<Diagnostic>,
374    pub(crate) namespaces: bool,
375}
376
377impl Document {
378    /// A document for a source of `len` bytes, whose text is rarely
379    /// longer than that.
380    pub(crate) fn new(namespaces: bool, len: usize) -> Document {
381        Document {
382            nodes: vec![Node {
383                parent: NONE,
384                first: NONE,
385                last: NONE,
386                prev: NONE,
387                next: NONE,
388                span: Span::default(),
389                data: Data::Document,
390            }],
391            attrs: Vec::new(),
392            text: String::with_capacity(len),
393            names: Names::new(),
394            decl: None,
395            doctype: None,
396            entities: Vec::new(),
397            notations: Vec::new(),
398            id_attrs: HashMap::new(),
399            #[cfg(feature = "xpath")]
400            xpath_attrs: std::sync::OnceLock::new(),
401            warnings: Vec::new(),
402            namespaces,
403        }
404    }
405
406    pub(crate) fn str(&self, s: Str) -> &str {
407        &self.text[s.start as usize..s.end() as usize]
408    }
409
410    /// Adds a node as `parent`'s last child.
411    pub(crate) fn append(&mut self, parent: u32, span: Span, data: Data) -> u32 {
412        let id = self.nodes.len() as u32;
413        let prev = self.nodes[parent as usize].last;
414        self.nodes.push(Node {
415            parent,
416            first: NONE,
417            last: NONE,
418            prev,
419            next: NONE,
420            span,
421            data,
422        });
423        if prev == NONE {
424            self.nodes[parent as usize].first = id;
425        } else {
426            self.nodes[prev as usize].next = id;
427        }
428        self.nodes[parent as usize].last = id;
429        id
430    }
431
432    /// The document node, the root of the tree.
433    pub fn root(&self) -> NodeId {
434        NodeId(0)
435    }
436
437    /// The document element.
438    pub fn root_element(&self) -> NodeId {
439        self.children(self.root())
440            .find(|&n| matches!(self.nodes[n.index()].data, Data::Element { .. }))
441            .expect("a parsed document has a document element")
442    }
443
444    /// How many nodes there are, the document node included.
445    pub fn len(&self) -> usize {
446        self.nodes.len()
447    }
448
449    /// The node at `index`, as [`NodeId::index`] numbers them, if there
450    /// is one: for a node number that came from outside, such as the C
451    /// API's.
452    ///
453    /// ```
454    /// let doc = parsec_xml::parse("<a/>").unwrap();
455    /// assert_eq!(doc.node(1), Some(doc.root_element()));
456    /// assert_eq!(doc.node(2), None);
457    /// ```
458    pub fn node(&self, index: usize) -> Option<NodeId> {
459        (index < self.nodes.len()).then_some(NodeId(index as u32))
460    }
461
462    /// Always false: there is at least the document node.
463    pub fn is_empty(&self) -> bool {
464        false
465    }
466
467    pub fn kind(&self, node: NodeId) -> NodeKind<'_> {
468        match self.nodes[node.index()].data {
469            Data::Document => NodeKind::Document,
470            Data::Doctype => NodeKind::Doctype,
471            Data::Element { name, ns, .. } => NodeKind::Element(self.names.name(name, ns)),
472            Data::Text(s) => NodeKind::Text(self.str(s)),
473            Data::Cdata(s) => NodeKind::CData(self.str(s)),
474            Data::Comment(s) => NodeKind::Comment(self.str(s)),
475            Data::Pi { target, data } => NodeKind::ProcessingInstruction {
476                target: self.str(target),
477                data: self.str(data),
478            },
479            Data::EntityRef(s) => NodeKind::EntityRef(self.str(s)),
480        }
481    }
482
483    pub fn is_element(&self, node: NodeId) -> bool {
484        matches!(self.nodes[node.index()].data, Data::Element { .. })
485    }
486
487    /// An element's name.
488    pub fn name(&self, node: NodeId) -> Option<Name<'_>> {
489        match self.nodes[node.index()].data {
490            Data::Element { name, ns, .. } => Some(self.names.name(name, ns)),
491            _ => None,
492        }
493    }
494
495    /// Where the node came from: an element's from its start tag's `<` to
496    /// its end tag's `>`.
497    pub fn span(&self, node: NodeId) -> Span {
498        self.nodes[node.index()].span
499    }
500
501    fn link(id: u32) -> Option<NodeId> {
502        (id != NONE).then_some(NodeId(id))
503    }
504
505    pub fn parent(&self, node: NodeId) -> Option<NodeId> {
506        Self::link(self.nodes[node.index()].parent)
507    }
508
509    pub fn first_child(&self, node: NodeId) -> Option<NodeId> {
510        Self::link(self.nodes[node.index()].first)
511    }
512
513    pub fn last_child(&self, node: NodeId) -> Option<NodeId> {
514        Self::link(self.nodes[node.index()].last)
515    }
516
517    pub fn next_sibling(&self, node: NodeId) -> Option<NodeId> {
518        Self::link(self.nodes[node.index()].next)
519    }
520
521    pub fn prev_sibling(&self, node: NodeId) -> Option<NodeId> {
522        Self::link(self.nodes[node.index()].prev)
523    }
524
525    pub fn children(&self, node: NodeId) -> impl Iterator<Item = NodeId> + '_ {
526        std::iter::successors(self.first_child(node), |&n| self.next_sibling(n))
527    }
528
529    /// The node's ancestors, nearest first, the document node last.
530    pub fn ancestors(&self, node: NodeId) -> impl Iterator<Item = NodeId> + '_ {
531        std::iter::successors(self.parent(node), |&n| self.parent(n))
532    }
533
534    /// The node and everything under it, in document order.
535    pub fn descendants(&self, node: NodeId) -> impl Iterator<Item = NodeId> + '_ {
536        // Ids are document order, and a subtree is a run of them: it ends
537        // where the next node after it, outside it, starts.
538        let mut end = node;
539        let stop = loop {
540            if let Some(next) = self.next_sibling(end) {
541                break next.0;
542            }
543            match self.parent(end) {
544                Some(p) => end = p,
545                None => break self.nodes.len() as u32,
546            }
547        };
548        (node.0..stop).map(NodeId)
549    }
550
551    /// An element's attributes, in the order of its start tag, then the
552    /// defaults the DTD supplied.
553    pub fn attributes(&self, node: NodeId) -> impl ExactSizeIterator<Item = Attribute<'_>> + '_ {
554        let range = match self.nodes[node.index()].data {
555            Data::Element {
556                attrs, attrs_len, ..
557            } => attrs as usize..(attrs + attrs_len) as usize,
558            _ => 0..0,
559        };
560        self.attrs[range].iter().map(|a| Attribute {
561            name: self.names.name(a.name, a.ns),
562            value: self.str(a.value),
563            span: a.span,
564            specified: a.specified,
565        })
566    }
567
568    /// The value of the attribute with this namespace (`""` for none)
569    /// and local name.
570    pub fn attribute(&self, node: NodeId, namespace: &str, local: &str) -> Option<&str> {
571        self.attributes(node)
572            .find(|a| a.name.local == local && a.name.namespace == namespace)
573            .map(|a| a.value)
574    }
575
576    /// The value of the attribute with this name as written, prefix and
577    /// all.
578    pub fn attribute_named(&self, node: NodeId, qname: &str) -> Option<&str> {
579        self.attributes(node)
580            .find(|a| a.name.qname == qname)
581            .map(|a| a.value)
582    }
583
584    /// The text of the node and everything under it, as XPath's
585    /// `string()` reads it: character data and CDATA, in order.
586    pub fn text(&self, node: NodeId) -> String {
587        let mut out = String::new();
588        for n in self.descendants(node) {
589            if let Data::Text(s) | Data::Cdata(s) = self.nodes[n.index()].data {
590                out.push_str(self.str(s));
591            }
592        }
593        out
594    }
595
596    /// The namespace `prefix` (`""` for the default namespace) is bound to
597    /// at `node`, from the declarations on it and its ancestors.
598    pub fn lookup_namespace(&self, node: NodeId, prefix: &str) -> Option<&str> {
599        if prefix == "xml" {
600            return Some(XML_NS);
601        }
602        for n in std::iter::once(node).chain(self.ancestors(node)) {
603            for a in self.attributes(n) {
604                if a.is_namespace_declaration()
605                    && (a.name.local == prefix && a.name.prefix == "xmlns"
606                        || prefix.is_empty() && a.name.qname == "xmlns")
607                {
608                    return (!a.value.is_empty()).then_some(a.value);
609                }
610            }
611        }
612        None
613    }
614
615    /// The nearest `xml:` attribute named `local` on the node or above it.
616    fn inherited(&self, node: NodeId, local: &str) -> Option<&str> {
617        std::iter::once(node)
618            .chain(self.ancestors(node))
619            .find_map(|n| self.attribute(n, XML_NS, local))
620    }
621
622    /// The node's language: the nearest `xml:lang` on it or above it.
623    pub fn xml_lang(&self, node: NodeId) -> Option<&str> {
624        self.inherited(node, "lang")
625    }
626
627    /// Whether white space at the node is to be kept: the nearest
628    /// `xml:space` on it or above it is `preserve`.
629    pub fn preserves_space(&self, node: NodeId) -> bool {
630        self.inherited(node, "space") == Some("preserve")
631    }
632
633    /// The XML declaration, if the document has one.
634    pub fn xml_decl(&self) -> Option<&XmlDecl> {
635        self.decl.as_ref()
636    }
637
638    pub fn doctype(&self) -> Option<&Doctype> {
639        self.doctype.as_ref()
640    }
641
642    /// The entities the internal subset declared, in order, the first
643    /// declaration of each name only (later ones don't count).
644    pub fn entities(&self) -> &[EntityDecl] {
645        &self.entities
646    }
647
648    pub fn notations(&self) -> &[Notation] {
649        &self.notations
650    }
651
652    /// What the parser didn't read and says so, as the XML spec asks of
653    /// a processor that doesn't validate: the external subset, external
654    /// entities, and declarations it skipped after a parameter entity it
655    /// didn't read. None of these is an error.
656    pub fn warnings(&self) -> &[Diagnostic] {
657        &self.warnings
658    }
659
660    /// Whether the document was parsed with namespaces on.
661    pub fn namespaces(&self) -> bool {
662        self.namespaces
663    }
664}
665
666// Documents go between threads.
667const _: () = {
668    const fn send_sync<T: Send + Sync>() {}
669    send_sync::<Document>();
670};
671
672#[cfg(test)]
673mod tests {
674    use super::*;
675
676    #[test]
677    fn names_are_found_either_side_of_the_map() {
678        let mut names = Names::new();
679        let ids: Vec<u32> = (0..40)
680            .map(|i| names.insert(&format!("n{i}"), NONE))
681            .collect();
682        for (i, &id) in ids.iter().enumerate() {
683            assert_eq!(names.get(&format!("n{i}")), Some(id));
684            assert_eq!(names.qname_str(id), format!("n{i}"));
685        }
686        assert_eq!(names.get("n40"), None);
687        assert_eq!(
688            (names.uri(""), names.uri(XML_NS), names.uri(XMLNS_NS)),
689            (0, NS_XML, NS_XMLNS)
690        );
691        let u = names.uri("urn:x");
692        assert_eq!(
693            (names.uri("urn:x"), names.uri_str(u), names.uri_str(NS_XML)),
694            (u, "urn:x", XML_NS)
695        );
696        assert_eq!(
697            (
698                names.prefix("xml"),
699                names.prefix("xmlns"),
700                names.prefix("p")
701            ),
702            (PREFIX_XML, PREFIX_XMLNS, 3)
703        );
704        assert_eq!(names.prefix("p"), 3);
705    }
706}