Skip to main content

einvoice_xpath_eval/
tree.rs

1//! The node model: immutable XML trees stored in an arena, one per document.
2//!
3//! A [`Document`] holds its nodes in document order: the document node first, then each
4//! element followed by its attributes and then by its children. The index of a node in the
5//! arena is therefore its position in document order, which makes document order a
6//! comparison of two integers and every axis a walk over neighbouring records. Nodes of
7//! different documents are ordered by the documents' creation order.
8//!
9//! Trees are built with a [`TreeBuilder`] (the XSLT layer builds its temporary trees with
10//! it) or parsed from XML text with [`Document::parse`], which keeps every text node,
11//! whitespace-only ones included, as Saxon does with `-strip:none`, and the namespace
12//! prefixes as written in the source (they appear in `fn:name`). Parsing reads the text
13//! twice with the streaming reader of `einvoice-xml`, which builds no tree of its own:
14//! once to check it and count its nodes, then to fill an arena of exactly that size.
15//!
16//! A built tree may have no document node: a parentless element, attribute, text node,
17//! comment or processing instruction ([`TreeBuilder::parentless`]), as the XSLT layer
18//! constructs them in a sequence (the root of its tree is the node itself). The elements
19//! of a built tree have the namespace nodes they were given
20//! ([`TreeBuilder::start_element_with_namespaces`], [`TreeBuilder::add_namespace`]), and
21//! those of their ancestors in the tree; the elements of a parsed document have those
22//! declared on them and on their ancestors ([`Node::namespaces_in_scope`]). There are no
23//! type annotations: every element and attribute is untyped, so its typed value is
24//! `xs:untypedAtomic`.
25//!
26//! A parsed document may be nested at most [`DEFAULT_MAX_DEPTH`] elements deep, or the
27//! maximum given to [`Document::parse_with_max_depth`]: beyond it the parse fails with
28//! [`LimitExceeded::Depth`], so that what walks the tree recursively (the template rules of
29//! a stylesheet) has a bounded depth. Parsing, building and walking a tree use no
30//! recursion.
31
32use std::borrow::Cow;
33use std::cell::{Cell, OnceCell};
34use std::cmp::Ordering;
35use std::collections::HashMap;
36use std::fmt::{self, Write as _};
37use std::path::Path;
38use std::rc::Rc;
39use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
40
41use std::sync::Arc;
42
43use einvoice_xdm::AtomicValue;
44use einvoice_xpath::{NamespaceBinding, QName, XML_NAMESPACE};
45
46use crate::limit::{DEFAULT_MAX_DEPTH, LimitExceeded};
47
48/// "No node" in the parent, previous sibling and name fields.
49const NONE: u32 = u32::MAX;
50
51/// Creation order of documents, for the document order of nodes in different trees.
52static NEXT_SERIAL: AtomicU64 = AtomicU64::new(0);
53
54/// The kind of a node.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
56pub enum NodeKind {
57    /// The document node, root of every tree.
58    Document,
59    /// An element.
60    Element,
61    /// An attribute.
62    Attribute,
63    /// A text node (never empty, never adjacent to another text node).
64    Text,
65    /// A comment.
66    Comment,
67    /// A processing instruction.
68    ProcessingInstruction,
69}
70
71/// The axes, in the sense of XPath 2.0 section 3.2.1.1, that the evaluator walks.
72/// `descendant` is not in the supported XPath subset but is used internally for `//name`.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74pub enum NodeAxis {
75    /// `child`
76    Child,
77    /// `attribute`
78    Attribute,
79    /// `self`
80    SelfAxis,
81    /// `descendant`
82    Descendant,
83    /// `descendant-or-self`
84    DescendantOrSelf,
85    /// `following-sibling`
86    FollowingSibling,
87    /// `parent`
88    Parent,
89    /// `ancestor`
90    Ancestor,
91    /// `ancestor-or-self`
92    AncestorOrSelf,
93    /// `preceding-sibling`
94    PrecedingSibling,
95    /// `preceding`
96    Preceding,
97}
98
99impl NodeAxis {
100    /// Whether the axis delivers nodes in reverse document order.
101    #[must_use]
102    pub const fn is_reverse(self) -> bool {
103        matches!(
104            self,
105            Self::Parent
106                | Self::Ancestor
107                | Self::AncestorOrSelf
108                | Self::PrecedingSibling
109                | Self::Preceding
110        )
111    }
112}
113
114/// One node of the arena: 32 bytes.
115///
116/// Every field is read directly by the axis walks and node tests, which run in chains of
117/// dependent loads: packing the kind with the name, or sharing fields between the subtree
118/// range of an element and the text range of the other nodes, measured 2 to 3% slower
119/// over a whole validation.
120#[derive(Debug, Clone, Copy)]
121struct Record {
122    kind: NodeKind,
123    /// Index in [`Document::names`], or [`NONE`].
124    name: u32,
125    parent: u32,
126    prev_sibling: u32,
127    /// The index just after the node's attributes: its first child if it has one. For a
128    /// node that cannot have attributes, the index just after it.
129    first_child: u32,
130    /// The index just after the node's subtree (attributes and descendants).
131    end: u32,
132    /// The range of the text of a text node, comment, processing instruction or
133    /// attribute in the document's text space (see [`Document::own_text`]): start and
134    /// length.
135    text_start: u32,
136    text_len: u32,
137}
138
139impl Record {
140    /// A node at `index` without children (yet), with its text range.
141    const fn new(
142        kind: NodeKind,
143        name: u32,
144        parent: u32,
145        prev_sibling: u32,
146        index: u32,
147        (text_start, text_len): (u32, u32),
148    ) -> Self {
149        Self {
150            kind,
151            name,
152            parent,
153            prev_sibling,
154            first_child: index + 1,
155            end: index + 1,
156            text_start,
157            text_len,
158        }
159    }
160}
161
162/// A problem building or parsing a tree.
163#[derive(Debug, Clone, PartialEq, Eq)]
164pub struct DocumentError {
165    message: String,
166    limit: Option<LimitExceeded>,
167}
168
169impl DocumentError {
170    fn new(message: impl Into<String>) -> Self {
171        Self {
172            message: message.into(),
173            limit: None,
174        }
175    }
176
177    fn limit_exceeded(limit: LimitExceeded) -> Self {
178        Self {
179            message: limit.to_string(),
180            limit: Some(limit),
181        }
182    }
183
184    /// The explanation.
185    #[must_use]
186    pub fn message(&self) -> &str {
187        &self.message
188    }
189
190    /// The limit the document exceeded, when that is the problem: an element nested
191    /// deeper than the maximum depth ([`LimitExceeded::Depth`]).
192    #[must_use]
193    pub const fn limit(&self) -> Option<LimitExceeded> {
194        self.limit
195    }
196}
197
198impl fmt::Display for DocumentError {
199    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200        f.write_str(&self.message)
201    }
202}
203
204impl std::error::Error for DocumentError {}
205
206/// An immutable XML tree.
207///
208/// The texts of its nodes live in one text space: the source text the document was
209/// parsed from, when the parser was given it as an owned `String` (offsets below its
210/// length), followed by the texts that are not written verbatim in it (offsets from its
211/// length on).
212pub struct Document {
213    serial: u64,
214    uri: Option<String>,
215    base_uri: Option<String>,
216    has_xml_base: bool,
217    records: Vec<Record>,
218    names: Vec<QName>,
219    /// The namespace nodes given to elements of a built tree, by element index, in
220    /// document order.
221    namespaces: Vec<(u32, Arc<[NamespaceBinding]>)>,
222    /// The source text, or empty when the texts were copied out of it.
223    source: String,
224    /// The texts that are not in `source`.
225    text: String,
226    /// The elements by expanded name, built by the second search for elements of a
227    /// name among many nodes ([`Document::elements_named`]).
228    elements: OnceCell<ElementIndex>,
229    /// The searches [`Document::elements_named`] answered without the index.
230    searches: Cell<u32>,
231    /// What kind of tree Saxon would hold: its `id()` and `generate-id()`.
232    view: TreeView,
233    /// The elements by ID (`xml:id`), built by the first call of [`Node::by_id`].
234    ids: OnceCell<HashMap<String, u32>>,
235}
236
237/// The kind of tree Saxon-HE 12.10 holds for a document, which decides what `id()` finds
238/// and the form of `generate-id()`.
239#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
240pub enum TreeView {
241    /// A tree Saxon builds itself (a `TinyTree`): a parsed document, a temporary tree.
242    /// Its `xml:id` attributes are IDs (their value whitespace-collapsed), and
243    /// `generate-id()` gives `d` + document number + node kind letter + node number.
244    #[default]
245    Tiny,
246    /// A DOM document Saxon wraps (a `DOMSource` built by its `DOMWriter`): no attribute
247    /// is an ID for the DOM, and `generate-id()` gives `w` + document number + the
248    /// sibling positions down from the root (`Navigator.getSequentialKey`).
249    Dom,
250}
251
252/// The fewest nodes a search for elements of a name must span to use an index.
253const INDEXED_SEARCH: u32 = 64;
254
255/// The elements of a document by expanded name, in two allocations: the elements of
256/// each name in document order, one name after the other, and for each name its hash
257/// ([`name_hash`]), a node name number with it and the range of its elements, by hash.
258#[derive(Debug, Default)]
259struct ElementIndex {
260    names: Vec<IndexedName>,
261    elements: Vec<u32>,
262}
263
264/// A name of [`ElementIndex`].
265#[derive(Debug, Clone, Copy)]
266struct IndexedName {
267    hash: u64,
268    /// The number of a name with it in [`Document::names`].
269    name: u32,
270    start: u32,
271    len: u32,
272}
273
274/// The hash of an expanded name, for [`ElementIndex`].
275fn name_hash(namespace: Option<&str>, local: &str) -> u64 {
276    use std::hash::{Hash as _, Hasher as _};
277    let mut hasher = std::hash::DefaultHasher::new();
278    (namespace, local).hash(&mut hasher);
279    hasher.finish()
280}
281
282impl fmt::Debug for Document {
283    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284        f.debug_struct("Document")
285            .field("serial", &self.serial)
286            .field("uri", &self.uri)
287            .field("nodes", &self.records.len())
288            .finish_non_exhaustive()
289    }
290}
291
292impl Document {
293    /// Parses XML text. Every text node is kept, whitespace-only ones included; a document
294    /// type declaration is refused (its default attributes and entities would change the
295    /// tree without notice). Line ends are normalised as XML 1.0 requires (section
296    /// 2.11), in comments and processing instructions too. `base_uri`, if given, is the
297    /// base URI of every node (the location the text was read from, Saxon's system id).
298    ///
299    /// The text can be borrowed (`&str`) or given (`String`). Borrowed, the texts of the
300    /// nodes are copied into the tree. Given, the tree keeps it and refers to it for every
301    /// text written verbatim in it (text without entity or character references, line
302    /// ends or, in attributes, whitespace to normalize): only the others are copied.
303    ///
304    /// The document has no document URI: in Saxon-HE 12.10, `fn:document-uri` only knows
305    /// the documents of its document pool, those that `fn:document` or `fn:doc` loaded,
306    /// and is empty for a document given to the transformation, such as the one being
307    /// validated. (Saxon 9.9 fell back to the system id.) A document loaded by
308    /// `fn:document` is parsed with [`Document::parse_loaded`].
309    ///
310    /// An element may be nested at most [`DEFAULT_MAX_DEPTH`] deep (the document element
311    /// is at depth 1); [`Document::parse_with_max_depth`] sets another maximum.
312    ///
313    /// # Errors
314    ///
315    /// XML that is not well-formed or not namespace-well-formed, or that has a document
316    /// type declaration; an element nested deeper than the maximum depth
317    /// ([`DocumentError::limit`] is then [`LimitExceeded::Depth`]).
318    pub fn parse<'t>(
319        text: impl Into<Cow<'t, str>>,
320        base_uri: Option<&str>,
321    ) -> Result<Rc<Self>, DocumentError> {
322        Self::parse_with_uris(text.into(), None, base_uri, DEFAULT_MAX_DEPTH)
323    }
324
325    /// [`Document::parse`] with another maximum element depth than
326    /// [`DEFAULT_MAX_DEPTH`]. What walks a tree recursively (the template rules of a
327    /// stylesheet) needs stack in proportion to its depth: a larger maximum needs a
328    /// larger stack.
329    ///
330    /// # Errors
331    ///
332    /// Those of [`Document::parse`].
333    pub fn parse_with_max_depth<'t>(
334        text: impl Into<Cow<'t, str>>,
335        base_uri: Option<&str>,
336        max_depth: u32,
337    ) -> Result<Rc<Self>, DocumentError> {
338        Self::parse_with_uris(text.into(), None, base_uri, max_depth)
339    }
340
341    /// Parses XML text as [`Document::parse`] does, for a document that `fn:document`
342    /// loaded from `uri` (the absolute URI it resolved): `uri` is both its document URI
343    /// and the base URI of its nodes, as for a document in Saxon's document pool.
344    ///
345    /// # Errors
346    ///
347    /// Those of [`Document::parse`].
348    pub fn parse_loaded<'t>(
349        text: impl Into<Cow<'t, str>>,
350        uri: &str,
351    ) -> Result<Rc<Self>, DocumentError> {
352        Self::parse_with_uris(text.into(), Some(uri), Some(uri), DEFAULT_MAX_DEPTH)
353    }
354
355    /// [`Document::parse_loaded`] with another maximum element depth than
356    /// [`DEFAULT_MAX_DEPTH`].
357    ///
358    /// # Errors
359    ///
360    /// Those of [`Document::parse`].
361    pub fn parse_loaded_with_max_depth<'t>(
362        text: impl Into<Cow<'t, str>>,
363        uri: &str,
364        max_depth: u32,
365    ) -> Result<Rc<Self>, DocumentError> {
366        Self::parse_with_uris(text.into(), Some(uri), Some(uri), max_depth)
367    }
368
369    fn parse_with_uris(
370        text: Cow<'_, str>,
371        document_uri: Option<&str>,
372        base_uri: Option<&str>,
373        max_depth: u32,
374    ) -> Result<Rc<Self>, DocumentError> {
375        let keep_source = matches!(text, Cow::Owned(_));
376        let builder = build_parsed(&text, keep_source, max_depth)?;
377        let source = match text {
378            Cow::Owned(source) => source,
379            Cow::Borrowed(_) => String::new(),
380        };
381        builder.finish_with_source(
382            source,
383            document_uri.map(str::to_owned),
384            base_uri.map(str::to_owned),
385        )
386    }
387
388    /// A new document with the same tree, whose text space starts with `source`, which
389    /// must be the text this one starts with.
390    fn copy_with_source(&self, source: String) -> Self {
391        debug_assert_eq!(source, self.source);
392        Self {
393            serial: NEXT_SERIAL.fetch_add(1, AtomicOrdering::Relaxed),
394            uri: self.uri.clone(),
395            base_uri: self.base_uri.clone(),
396            has_xml_base: self.has_xml_base,
397            records: self.records.clone(),
398            names: self.names.clone(),
399            namespaces: self.namespaces.clone(),
400            source,
401            text: self.text.clone(),
402            elements: OnceCell::new(),
403            searches: Cell::new(0),
404            view: self.view,
405            ids: OnceCell::new(),
406        }
407    }
408
409    /// The document node.
410    #[must_use]
411    pub fn root(self: &Rc<Self>) -> Node {
412        Node {
413            doc: Rc::clone(self),
414            index: 0,
415        }
416    }
417
418    /// The document URI (`fn:document-uri`), if any: only a document loaded by
419    /// `fn:document` has one (see [`Document::parse`]).
420    #[must_use]
421    pub fn document_uri(&self) -> Option<&str> {
422        self.uri.as_deref()
423    }
424
425    /// The base URI of the document's nodes, if any.
426    #[must_use]
427    pub fn base_uri(&self) -> Option<&str> {
428        self.base_uri.as_deref()
429    }
430
431    /// Whether some element has an `xml:base` attribute (whose effect on base URIs is not
432    /// implemented).
433    #[must_use]
434    pub const fn has_xml_base(&self) -> bool {
435        self.has_xml_base
436    }
437
438    /// The number of distinct names of its nodes ([`Node::name_id`]).
439    #[must_use]
440    pub fn name_count(&self) -> usize {
441        self.names.len()
442    }
443
444    /// The number of nodes, the document node and attributes included.
445    #[must_use]
446    pub fn node_count(&self) -> usize {
447        self.records.len()
448    }
449
450    fn record(&self, index: u32) -> &Record {
451        // Indices only ever come from this document's own records.
452        &self.records[index as usize]
453    }
454
455    pub(crate) fn kind(&self, index: u32) -> NodeKind {
456        self.record(index).kind
457    }
458
459    pub(crate) fn name(&self, index: u32) -> Option<&QName> {
460        let name = self.record(index).name;
461        (name != NONE).then(|| &self.names[name as usize])
462    }
463
464    pub(crate) fn parent_index(&self, index: u32) -> Option<u32> {
465        let parent = self.record(index).parent;
466        (parent != NONE).then_some(parent)
467    }
468
469    /// The text of a text node, comment, processing instruction or attribute: a range of
470    /// the text space, in `source` or, from the length of `source` on, in `text`.
471    fn own_text(&self, index: u32) -> &str {
472        let r = self.record(index);
473        let start = r.text_start as usize;
474        let end = start + r.text_len as usize;
475        match start.checked_sub(self.source.len()) {
476            None => &self.source[start..end],
477            Some(start) => &self.text[start..end - self.source.len()],
478        }
479    }
480
481    pub(crate) fn string_value(&self, index: u32) -> Cow<'_, str> {
482        match self.kind(index) {
483            NodeKind::Text
484            | NodeKind::Comment
485            | NodeKind::ProcessingInstruction
486            | NodeKind::Attribute => Cow::Borrowed(self.own_text(index)),
487            NodeKind::Element | NodeKind::Document => {
488                let mut texts = self
489                    .cursor(index, NodeAxis::Descendant)
490                    .walk(self)
491                    .filter(|&i| self.kind(i) == NodeKind::Text);
492                let Some(first) = texts.next() else {
493                    return Cow::Borrowed("");
494                };
495                let Some(second) = texts.next() else {
496                    return Cow::Borrowed(self.own_text(first));
497                };
498                let mut value = String::from(self.own_text(first));
499                value.push_str(self.own_text(second));
500                for i in texts {
501                    value.push_str(self.own_text(i));
502                }
503                Cow::Owned(value)
504            }
505        }
506    }
507
508    /// The elements named `{namespace}local` among the nodes from `start` (included) to
509    /// `end` (excluded), in document order, read from an index of the document's
510    /// elements by name, which the second search of [`INDEXED_SEARCH`] nodes or more
511    /// builds. `None` when there is no index (yet): the caller searches the nodes.
512    pub(crate) fn elements_named(
513        &self,
514        namespace: Option<&str>,
515        local: &str,
516        start: u32,
517        end: u32,
518    ) -> Option<&[u32]> {
519        if end.saturating_sub(start) < INDEXED_SEARCH {
520            return None;
521        }
522        let index = if let Some(index) = self.elements.get() {
523            index
524        } else {
525            let searches = self.searches.get().saturating_add(1);
526            self.searches.set(searches);
527            if searches < 2 {
528                return None;
529            }
530            self.elements.get_or_init(|| self.index_elements())
531        };
532        let hash = name_hash(namespace, local);
533        let first = index.names.partition_point(|n| n.hash < hash);
534        let all = index.names[first..]
535            .iter()
536            .take_while(|n| n.hash == hash)
537            .find(|n| {
538                self.names.get(n.name as usize).is_some_and(|name| {
539                    name.local == local && name.namespace.as_deref() == namespace
540                })
541            })
542            .and_then(|n| {
543                let start = n.start as usize;
544                index.elements.get(start..start + n.len as usize)
545            })
546            .unwrap_or_default();
547        let from = all.partition_point(|&i| i < start);
548        let to = all.partition_point(|&i| i < end);
549        all.get(from..to)
550    }
551
552    /// The index of the elements by expanded name.
553    fn index_elements(&self) -> ElementIndex {
554        // The list of each name: names that differ only by prefix share one, numbered
555        // by its first name.
556        let mut first_of_key: HashMap<(Option<&str>, &str), u32> =
557            HashMap::with_capacity(self.names.len());
558        let list_of_name: Vec<u32> = (0_u32..)
559            .zip(&self.names)
560            .map(|(id, name)| {
561                *first_of_key
562                    .entry((name.namespace.as_deref(), name.local.as_str()))
563                    .or_insert(id)
564            })
565            .collect();
566        drop(first_of_key);
567        let element_list = |record: &Record| {
568            (record.kind == NodeKind::Element)
569                .then(|| list_of_name.get(record.name as usize).copied())
570                .flatten()
571        };
572        let mut counts = vec![0_u32; self.names.len()];
573        for record in &self.records {
574            if let Some(count) = element_list(record).and_then(|l| counts.get_mut(l as usize)) {
575                *count += 1;
576            }
577        }
578        let mut names = Vec::new();
579        let mut next = vec![0_u32; self.names.len()];
580        let mut total = 0_u32;
581        for (list, (&count, next)) in (0_u32..).zip(counts.iter().zip(next.iter_mut())) {
582            if count > 0 {
583                let name = &self.names[list as usize];
584                names.push(IndexedName {
585                    hash: name_hash(name.namespace.as_deref(), &name.local),
586                    name: list,
587                    start: total,
588                    len: count,
589                });
590                *next = total;
591                total += count;
592            }
593        }
594        drop(counts);
595        let mut elements = vec![0_u32; total as usize];
596        for (index, record) in (0_u32..).zip(&self.records) {
597            if let Some(next) = element_list(record).and_then(|l| next.get_mut(l as usize))
598                && let Some(slot) = elements.get_mut(*next as usize)
599            {
600                *slot = index;
601                *next += 1;
602            }
603        }
604        names.sort_by_key(|n| n.hash);
605        names.shrink_to_fit();
606        ElementIndex { names, elements }
607    }
608
609    /// The first index after the attributes of the node at `index` and the first after
610    /// its subtree: the range of its descendants.
611    pub(crate) fn descendant_range(&self, index: u32) -> (u32, u32) {
612        let r = self.record(index);
613        (r.first_child, r.end)
614    }
615
616    /// The start of an axis walk from the node at `index`.
617    pub(crate) fn cursor(&self, index: u32, axis: NodeAxis) -> Cursor {
618        let r = self.record(index);
619        let kind = r.kind;
620        let is_attribute = kind == NodeKind::Attribute;
621        match axis {
622            NodeAxis::SelfAxis => Cursor::One(index),
623            NodeAxis::Parent => match r.parent {
624                NONE => Cursor::Done,
625                parent => Cursor::One(parent),
626            },
627            NodeAxis::Child => Cursor::Siblings {
628                next: r.first_child,
629                end: r.end,
630            },
631            NodeAxis::Attribute => {
632                if kind == NodeKind::Element {
633                    Cursor::Range {
634                        next: index + 1,
635                        end: r.first_child,
636                    }
637                } else {
638                    Cursor::Done
639                }
640            }
641            NodeAxis::Descendant => Cursor::Descendants {
642                next: r.first_child,
643                end: r.end,
644            },
645            NodeAxis::DescendantOrSelf => Cursor::Descendants {
646                next: index,
647                end: r.end,
648            },
649            NodeAxis::FollowingSibling => match r.parent {
650                NONE => Cursor::Done,
651                _ if is_attribute => Cursor::Done,
652                parent => Cursor::Siblings {
653                    next: r.end,
654                    end: self.record(parent).end,
655                },
656            },
657            NodeAxis::Ancestor => Cursor::Ancestors { next: r.parent },
658            NodeAxis::AncestorOrSelf => Cursor::Ancestors { next: index },
659            NodeAxis::PrecedingSibling => {
660                if is_attribute {
661                    Cursor::Done
662                } else {
663                    Cursor::PrecedingSiblings {
664                        next: r.prev_sibling,
665                    }
666                }
667            }
668            NodeAxis::Preceding => Cursor::Preceding {
669                next: index,
670                ancestor: r.parent,
671            },
672        }
673    }
674}
675
676/// The state of an axis walk over node indices, in axis order.
677#[derive(Debug, Clone, Copy)]
678pub(crate) enum Cursor {
679    Done,
680    One(u32),
681    /// Consecutive indices (attributes).
682    Range {
683        next: u32,
684        end: u32,
685    },
686    /// Nodes whose subtrees follow each other (children, following siblings).
687    Siblings {
688        next: u32,
689        end: u32,
690    },
691    /// Every node of a range except attributes, in document order.
692    Descendants {
693        next: u32,
694        end: u32,
695    },
696    Ancestors {
697        next: u32,
698    },
699    PrecedingSiblings {
700        next: u32,
701    },
702    /// `next` is one past the next candidate; `ancestor` the nearest ancestor not yet
703    /// passed, skipped when reached.
704    Preceding {
705        next: u32,
706        ancestor: u32,
707    },
708}
709
710impl Cursor {
711    pub(crate) fn next(&mut self, doc: &Document) -> Option<u32> {
712        match self {
713            Self::Done => None,
714            Self::One(index) => {
715                let index = *index;
716                *self = Self::Done;
717                Some(index)
718            }
719            Self::Range { next, end } => {
720                if *next >= *end {
721                    return None;
722                }
723                let index = *next;
724                *next += 1;
725                Some(index)
726            }
727            Self::Siblings { next, end } => {
728                if *next >= *end {
729                    return None;
730                }
731                let index = *next;
732                *next = doc.record(index).end;
733                Some(index)
734            }
735            Self::Descendants { next, end } => {
736                if *next >= *end {
737                    return None;
738                }
739                let index = *next;
740                // Skips the node's attributes (they directly follow an element).
741                *next = doc.record(index).first_child;
742                Some(index)
743            }
744            Self::Ancestors { next } => {
745                if *next == NONE {
746                    return None;
747                }
748                let index = *next;
749                *next = doc.record(index).parent;
750                Some(index)
751            }
752            Self::PrecedingSiblings { next } => {
753                if *next == NONE {
754                    return None;
755                }
756                let index = *next;
757                *next = doc.record(index).prev_sibling;
758                Some(index)
759            }
760            Self::Preceding { next, ancestor } => loop {
761                if *next == 0 {
762                    return None;
763                }
764                *next -= 1;
765                let index = *next;
766                if index == *ancestor {
767                    *ancestor = doc.record(index).parent;
768                    continue;
769                }
770                if doc.record(index).kind != NodeKind::Attribute {
771                    return Some(index);
772                }
773            },
774        }
775    }
776
777    /// The walk as an iterator borrowing the document.
778    pub(crate) fn walk(self, doc: &Document) -> impl Iterator<Item = u32> + '_ {
779        let mut cursor = self;
780        std::iter::from_fn(move || cursor.next(doc))
781    }
782}
783
784/// A node: a document and the position of the node in it.
785///
786/// Two `Node` values are equal when they are the same node (XPath `is`).
787#[derive(Clone)]
788pub struct Node {
789    doc: Rc<Document>,
790    index: u32,
791}
792
793impl PartialEq for Node {
794    fn eq(&self, other: &Self) -> bool {
795        self.index == other.index && Rc::ptr_eq(&self.doc, &other.doc)
796    }
797}
798
799impl Eq for Node {}
800
801impl fmt::Debug for Node {
802    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
803        write!(f, "Node({:?}", self.kind())?;
804        if let Some(name) = self.name() {
805            write!(f, " {name}")?;
806        }
807        write!(f, " #{} of document {})", self.index, self.doc.serial)
808    }
809}
810
811impl Node {
812    pub(crate) fn new(doc: Rc<Document>, index: u32) -> Self {
813        Self { doc, index }
814    }
815
816    pub(crate) const fn index(&self) -> u32 {
817        self.index
818    }
819
820    /// The document the node belongs to.
821    #[must_use]
822    pub fn document(&self) -> &Rc<Document> {
823        &self.doc
824    }
825
826    /// The node kind.
827    #[must_use]
828    pub fn kind(&self) -> NodeKind {
829        self.doc.kind(self.index)
830    }
831
832    /// The name of an element or attribute, with the prefix it was written with, or the
833    /// target of a processing instruction (as a local name); `None` for other nodes.
834    #[must_use]
835    pub fn name(&self) -> Option<&QName> {
836        self.doc.name(self.index)
837    }
838
839    /// The number of the node's name in its document, `None` for a node without name:
840    /// two nodes of a document have the same number when their names have the same
841    /// prefix, local name and namespace. Numbers are below [`Document::name_count`].
842    #[must_use]
843    pub fn name_id(&self) -> Option<u32> {
844        let name = self.doc.record(self.index).name;
845        (name != NONE).then_some(name)
846    }
847
848    /// The parent node.
849    #[must_use]
850    pub fn parent(&self) -> Option<Self> {
851        self.doc
852            .parent_index(self.index)
853            .map(|p| Self::new(Rc::clone(&self.doc), p))
854    }
855
856    /// The root of the tree: the document node, or the parentless node of a tree built
857    /// without one ([`TreeBuilder::parentless`]).
858    #[must_use]
859    pub fn root(&self) -> Self {
860        Self::new(Rc::clone(&self.doc), 0)
861    }
862
863    /// The namespace nodes of an element (XDM `dm:namespace-nodes`, the implicit `xml`
864    /// namespace excepted): those it was given, or declared in the text it was parsed
865    /// from, and those of its ancestors, the nearest binding of a prefix winning,
866    /// innermost element first; a binding to the empty URI (`xmlns=""`) takes the default
867    /// namespace away. Empty for other nodes.
868    #[must_use]
869    pub fn namespaces_in_scope(&self) -> Vec<NamespaceBinding> {
870        let doc = &self.doc;
871        let mut out: Vec<NamespaceBinding> = Vec::new();
872        if doc.namespaces.is_empty() || self.kind() != NodeKind::Element {
873            return out;
874        }
875        let mut index = self.index;
876        while index != NONE {
877            if let Ok(i) = doc.namespaces.binary_search_by_key(&index, |(e, _)| *e) {
878                for binding in doc.namespaces[i].1.iter() {
879                    if !out.iter().any(|b| b.prefix == binding.prefix) {
880                        out.push(binding.clone());
881                    }
882                }
883            }
884            index = doc.record(index).parent;
885        }
886        out.retain(|b| !b.uri.is_empty());
887        out
888    }
889
890    /// Whether the node is an element with namespace bindings of its own (given to it,
891    /// or declared in the text it was parsed from). An element without has the
892    /// [namespaces in scope](Node::namespaces_in_scope) of its parent.
893    #[must_use]
894    pub fn has_own_namespaces(&self) -> bool {
895        self.kind() == NodeKind::Element
896            && self
897                .doc
898                .namespaces
899                .binary_search_by_key(&self.index, |(e, _)| *e)
900                .is_ok()
901    }
902
903    /// The string value (XDM `dm:string-value`).
904    #[must_use]
905    pub fn string_value(&self) -> Cow<'_, str> {
906        self.doc.string_value(self.index)
907    }
908
909    /// The element of the node's tree with the ID `id`: for a [`TreeView::Tiny`] tree,
910    /// the first element in document order with an `xml:id` attribute of that value
911    /// (whitespace-collapsed), as Saxon-HE 12.10 finds it; never for a
912    /// [`TreeView::Dom`] tree.
913    #[must_use]
914    pub fn by_id(&self, id: &str) -> Option<Self> {
915        let doc = &self.doc;
916        if doc.view == TreeView::Dom {
917            return None;
918        }
919        let ids = doc.ids.get_or_init(|| {
920            let mut ids = HashMap::new();
921            for (index, record) in (0_u32..).zip(&doc.records) {
922                if record.kind != NodeKind::Attribute {
923                    continue;
924                }
925                let is_xml_id = doc.name(index).is_some_and(|n| {
926                    n.local == "id" && n.namespace.as_deref() == Some(XML_NAMESPACE)
927                });
928                if is_xml_id {
929                    let value: Vec<&str> = doc
930                        .own_text(index)
931                        .split([' ', '\t', '\n', '\r'])
932                        .filter(|t| !t.is_empty())
933                        .collect();
934                    ids.entry(value.join(" ")).or_insert(record.parent);
935                }
936            }
937            ids
938        });
939        ids.get(id).map(|&i| Self::new(Rc::clone(doc), i))
940    }
941
942    /// `generate-id()` as Saxon-HE 12.10 forms it for the kind of tree
943    /// ([`TreeView`]); the document number is the creation order of the document, which
944    /// in Saxon depends on what the JVM read before (so are its IDs: only their form is
945    /// Saxon's). An attribute of a [`TreeView::Tiny`] tree gets its element's ID, `a` and
946    /// its number among the attributes of the tree (Saxon's, the fingerprint of its name
947    /// in Saxon's name pool, depends on the JVM too).
948    #[must_use]
949    pub fn generate_id(&self) -> String {
950        let doc = &self.doc;
951        let number = doc.serial + 1;
952        match doc.view {
953            TreeView::Tiny => {
954                let attributes_before = |index: u32| {
955                    doc.records[..index as usize]
956                        .iter()
957                        .filter(|r| r.kind == NodeKind::Attribute)
958                        .count()
959                };
960                let tiny = |index: u32| {
961                    let kind = doc.kind(index);
962                    if kind == NodeKind::Document {
963                        return format!("d{number}");
964                    }
965                    let letter = match kind {
966                        NodeKind::Text => 't',
967                        NodeKind::Comment => 'c',
968                        NodeKind::ProcessingInstruction => 'p',
969                        _ => 'e',
970                    };
971                    let node_number = index as usize - attributes_before(index);
972                    format!("d{number}{letter}{node_number}")
973                };
974                if self.kind() == NodeKind::Attribute {
975                    let parent = doc.record(self.index).parent;
976                    let owner = if parent == NONE {
977                        format!("d{number}")
978                    } else {
979                        tiny(parent)
980                    };
981                    format!("{owner}a{}", attributes_before(self.index))
982                } else {
983                    tiny(self.index)
984                }
985            }
986            TreeView::Dom => {
987                let lineage: Vec<u32> = doc
988                    .cursor(self.index, NodeAxis::AncestorOrSelf)
989                    .walk(doc)
990                    .collect();
991                let mut id = format!("w{number}");
992                for &index in lineage.iter().rev() {
993                    let record = doc.record(index);
994                    if record.parent == NONE {
995                        continue;
996                    }
997                    let position = if record.kind == NodeKind::Attribute {
998                        id.push('a');
999                        index - record.parent - 1
1000                    } else {
1001                        u32::try_from(
1002                            doc.cursor(index, NodeAxis::PrecedingSibling)
1003                                .walk(doc)
1004                                .count(),
1005                        )
1006                        .unwrap_or(u32::MAX)
1007                    };
1008                    id.push_str(&alpha_key(position));
1009                }
1010                id
1011            }
1012        }
1013    }
1014
1015    /// The typed value of the node in an untyped tree: `xs:untypedAtomic`, except for
1016    /// comments and processing instructions, whose typed value is an `xs:string`.
1017    #[must_use]
1018    pub fn typed_value(&self) -> AtomicValue {
1019        let value = self.string_value().into_owned();
1020        match self.kind() {
1021            NodeKind::Comment | NodeKind::ProcessingInstruction => AtomicValue::String(value),
1022            _ => AtomicValue::UntypedAtomic(value),
1023        }
1024    }
1025
1026    /// The nodes on an axis from this node, in axis order (reverse document order for
1027    /// the reverse axes).
1028    #[must_use]
1029    pub fn axis(&self, axis: NodeAxis) -> Axis {
1030        Axis {
1031            cursor: self.doc.cursor(self.index, axis),
1032            doc: Rc::clone(&self.doc),
1033        }
1034    }
1035
1036    /// The children, in document order.
1037    #[must_use]
1038    pub fn children(&self) -> Axis {
1039        self.axis(NodeAxis::Child)
1040    }
1041
1042    /// The attributes, in document order (the order of the source).
1043    #[must_use]
1044    pub fn attributes(&self) -> Axis {
1045        self.axis(NodeAxis::Attribute)
1046    }
1047
1048    /// Document order. Nodes of different documents are ordered by the creation of their
1049    /// documents.
1050    #[must_use]
1051    pub fn cmp_document_order(&self, other: &Self) -> Ordering {
1052        self.doc
1053            .serial
1054            .cmp(&other.doc.serial)
1055            .then(self.index.cmp(&other.index))
1056    }
1057}
1058
1059/// The nodes on an axis from a node, in axis order.
1060#[derive(Debug, Clone)]
1061pub struct Axis {
1062    cursor: Cursor,
1063    doc: Rc<Document>,
1064}
1065
1066impl Iterator for Axis {
1067    type Item = Node;
1068
1069    fn next(&mut self) -> Option<Node> {
1070        let index = self.cursor.next(&self.doc)?;
1071        Some(Node::new(Rc::clone(&self.doc), index))
1072    }
1073
1074    fn count(self) -> usize {
1075        self.cursor.walk(&self.doc).count()
1076    }
1077}
1078
1079/// Documents that `fn:document` loads, parsed once and given to every transformation that
1080/// loads them again: the code lists a stylesheet reads, the same text under the same URI
1081/// for each document it validates.
1082///
1083/// [`DocumentCache::parse_loaded`] returns the tree [`Document::parse_loaded_with_max_depth`]
1084/// would build from the text, without parsing it again when the same text was parsed under
1085/// the same URI and maximum depth before: a copy of that tree, which is a new document
1086/// (created now, as a parse now would create it, for the document order of nodes in
1087/// different trees). The cache is shared between threads; it keeps at most
1088/// [`DocumentCache::MAX_DOCUMENTS`] documents of at most [`DocumentCache::MAX_BYTES`] of
1089/// text in all, and parses the others each time.
1090#[derive(Debug, Default)]
1091pub struct DocumentCache {
1092    entries: std::sync::Mutex<Vec<CachedDocument>>,
1093}
1094
1095/// A parsed document kept by a [`DocumentCache`], with what it was parsed under.
1096#[derive(Debug)]
1097struct CachedDocument {
1098    max_depth: u32,
1099    document: Document,
1100}
1101
1102impl DocumentCache {
1103    /// The most documents a cache keeps.
1104    pub const MAX_DOCUMENTS: usize = 64;
1105    /// The most text, in bytes, of the documents a cache keeps.
1106    pub const MAX_BYTES: usize = 64 << 20;
1107
1108    /// An empty cache.
1109    #[must_use]
1110    pub fn new() -> Self {
1111        Self::default()
1112    }
1113
1114    /// The document [`Document::parse_loaded_with_max_depth`] parses from `text`, loaded
1115    /// from `uri`: a copy of the one parsed before from the same text, URI and maximum
1116    /// depth, or parsed now (and kept, room permitting).
1117    ///
1118    /// # Errors
1119    ///
1120    /// Those of [`Document::parse`]; a text that does not parse is not kept.
1121    pub fn parse_loaded(
1122        &self,
1123        text: String,
1124        uri: &str,
1125        max_depth: u32,
1126    ) -> Result<Rc<Document>, DocumentError> {
1127        {
1128            let entries = self
1129                .entries
1130                .lock()
1131                .unwrap_or_else(std::sync::PoisonError::into_inner);
1132            if let Some(entry) = entries.iter().find(|e| {
1133                e.max_depth == max_depth
1134                    && e.document.uri.as_deref() == Some(uri)
1135                    && e.document.source == text
1136            }) {
1137                return Ok(Rc::new(entry.document.copy_with_source(text)));
1138            }
1139        }
1140        let document = Document::parse_loaded_with_max_depth(text, uri, max_depth)?;
1141        let mut entries = self
1142            .entries
1143            .lock()
1144            .unwrap_or_else(std::sync::PoisonError::into_inner);
1145        let bytes: usize = entries.iter().map(|e| e.document.source.len()).sum();
1146        if entries.len() < Self::MAX_DOCUMENTS
1147            && bytes.saturating_add(document.source.len()) <= Self::MAX_BYTES
1148            && !entries.iter().any(|e| {
1149                e.max_depth == max_depth
1150                    && e.document.uri.as_deref() == Some(uri)
1151                    && e.document.source == document.source
1152            })
1153        {
1154            entries.push(CachedDocument {
1155                max_depth,
1156                document: document.copy_with_source(document.source.clone()),
1157            });
1158        }
1159        Ok(document)
1160    }
1161}
1162
1163/// Builds a [`Document`] from events, in document order.
1164///
1165/// Adjacent text is merged into one text node and empty text is dropped, as the XDM
1166/// requires (except at the top of a parentless tree, see [`TreeBuilder::parentless`]). Attributes must come right after their element's start, before its content;
1167/// an attribute whose expanded name is already on the element replaces it.
1168#[derive(Debug)]
1169pub struct TreeBuilder {
1170    records: Vec<Record>,
1171    names: Vec<QName>,
1172    name_ids: HashMap<QName, u32>,
1173    /// The namespace nodes given to elements, by element index.
1174    namespaces: Vec<(u32, Arc<[NamespaceBinding]>)>,
1175    /// Whether the tree has no document node: its one top-level node is its root.
1176    parentless: bool,
1177    /// The length of the source text the text space starts with (see [`Document`]): the
1178    /// texts added are stored from that offset on.
1179    source_len: usize,
1180    text: String,
1181    /// The open nodes, the document node first (none for a parentless tree).
1182    open: Vec<u32>,
1183    /// The last child of each open node, or [`NONE`].
1184    last_child: Vec<u32>,
1185    has_xml_base: bool,
1186    view: TreeView,
1187}
1188
1189impl Default for TreeBuilder {
1190    fn default() -> Self {
1191        Self::new()
1192    }
1193}
1194
1195fn to_u32(value: usize) -> Result<u32, DocumentError> {
1196    u32::try_from(value)
1197        .ok()
1198        .filter(|&v| v != NONE)
1199        .ok_or_else(|| DocumentError::new("document too large"))
1200}
1201
1202/// Where the text of a node comes from.
1203#[derive(Debug, Clone, Copy)]
1204enum NodeText<'s> {
1205    /// A range of the source text: offset and length.
1206    Source(u32, u32),
1207    /// Text to store.
1208    Copy(&'s str),
1209}
1210
1211impl TreeBuilder {
1212    /// A builder holding only the document node.
1213    #[must_use]
1214    pub fn new() -> Self {
1215        Self {
1216            records: vec![Record::new(NodeKind::Document, NONE, NONE, NONE, 0, (0, 0))],
1217            names: Vec::new(),
1218            name_ids: HashMap::new(),
1219            namespaces: Vec::new(),
1220            parentless: false,
1221            source_len: 0,
1222            text: String::new(),
1223            open: vec![0],
1224            last_child: vec![NONE],
1225            has_xml_base: false,
1226            view: TreeView::Tiny,
1227        }
1228    }
1229
1230    /// The tree is the view Saxon has of a DOM document it wraps ([`TreeView::Dom`]).
1231    #[must_use]
1232    pub const fn dom_view(mut self) -> Self {
1233        self.view = TreeView::Dom;
1234        self
1235    }
1236
1237    /// A builder of a tree without document node, whose root is the one node added at
1238    /// the top: a parentless element (with its content), attribute, text node or comment
1239    /// (XDM nodes without parent, as XSLT constructs them in a sequence). Text added at
1240    /// the top makes one text node; anything added after the top-level node is an error.
1241    #[must_use]
1242    pub fn parentless() -> Self {
1243        Self {
1244            records: Vec::new(),
1245            open: Vec::new(),
1246            parentless: true,
1247            ..Self::new()
1248        }
1249    }
1250
1251    /// A builder whose text space starts with a source text of `source_len` bytes, with
1252    /// room for exactly `nodes` nodes (the document node included) and `text` bytes of
1253    /// copied text.
1254    fn with_capacity(nodes: usize, text: usize, source_len: usize) -> Self {
1255        let mut builder = Self::new();
1256        builder.records.reserve_exact(nodes.saturating_sub(1));
1257        builder.text.reserve_exact(text);
1258        builder.source_len = source_len;
1259        builder
1260    }
1261
1262    fn intern(&mut self, name: QName) -> Result<u32, DocumentError> {
1263        if let Some(&id) = self.name_ids.get(&name) {
1264            return Ok(id);
1265        }
1266        let id = self.push_name(name.clone())?;
1267        self.name_ids.insert(name, id);
1268        Ok(id)
1269    }
1270
1271    /// Adds a name to the table, without interning it.
1272    fn push_name(&mut self, name: QName) -> Result<u32, DocumentError> {
1273        let id = to_u32(self.names.len())?;
1274        self.names.push(name);
1275        Ok(id)
1276    }
1277
1278    /// The range of the text space a text occupies: its offset and length.
1279    fn store_text(&mut self, value: NodeText<'_>) -> Result<(u32, u32), DocumentError> {
1280        match value {
1281            NodeText::Source(start, len) => Ok((start, len)),
1282            NodeText::Copy(value) => {
1283                let start = to_u32(self.source_len + self.text.len())?;
1284                let len = to_u32(value.len())?;
1285                to_u32(self.source_len + self.text.len() + value.len())?;
1286                self.text.push_str(value);
1287                Ok((start, len))
1288            }
1289        }
1290    }
1291
1292    /// The innermost open node, or [`NONE`] at the top of a parentless tree.
1293    fn top(&self) -> u32 {
1294        self.open.last().copied().unwrap_or(NONE)
1295    }
1296
1297    /// The number of open nodes that are not elements (the document node).
1298    const fn base(&self) -> usize {
1299        if self.parentless { 0 } else { 1 }
1300    }
1301
1302    /// Appends a child of the innermost open node and returns its index: an element (its
1303    /// text is ignored), or a node with a text.
1304    fn append(
1305        &mut self,
1306        kind: NodeKind,
1307        name: u32,
1308        text: NodeText<'_>,
1309    ) -> Result<u32, DocumentError> {
1310        let index = to_u32(self.records.len())?;
1311        to_u32(self.records.len() + 1)?;
1312        if self.parentless && self.open.is_empty() && !self.records.is_empty() {
1313            return Err(DocumentError::new(
1314                "a second node at the top of a parentless tree",
1315            ));
1316        }
1317        let text = if kind == NodeKind::Element {
1318            (0, 0)
1319        } else {
1320            self.store_text(text)?
1321        };
1322        let parent = self.top();
1323        let last = self.last_child.last_mut().map_or(NONE, |l| {
1324            let previous = *l;
1325            *l = index;
1326            previous
1327        });
1328        self.records
1329            .push(Record::new(kind, name, parent, last, index, text));
1330        Ok(index)
1331    }
1332
1333    /// Opens an element.
1334    ///
1335    /// # Errors
1336    ///
1337    /// A document too large for the arena.
1338    pub fn start_element(&mut self, name: QName) -> Result<(), DocumentError> {
1339        let name = self.intern(name)?;
1340        self.open_element(name)
1341    }
1342
1343    /// Adds a namespace node to the element just opened (before its content).
1344    ///
1345    /// # Errors
1346    ///
1347    /// No element is open, or it already has content.
1348    pub fn add_namespace(&mut self, binding: NamespaceBinding) -> Result<(), DocumentError> {
1349        let element = self.top();
1350        let has_content = self.last_child.last().is_some_and(|&l| l != NONE);
1351        if element == NONE
1352            || self.records[element as usize].kind != NodeKind::Element
1353            || has_content
1354        {
1355            return Err(DocumentError::new(format!(
1356                "namespace {:?} outside an element start",
1357                binding.prefix
1358            )));
1359        }
1360        match self.namespaces.last_mut() {
1361            Some((e, bindings)) if *e == element => {
1362                let mut extended: Vec<NamespaceBinding> = bindings.to_vec();
1363                extended.retain(|b| b.prefix != binding.prefix);
1364                extended.push(binding);
1365                *bindings = extended.into();
1366            }
1367            _ => self.namespaces.push((element, vec![binding].into())),
1368        }
1369        Ok(())
1370    }
1371
1372    /// Opens an element with namespace nodes (besides those it inherits from its
1373    /// ancestors in the tree, see [`Node::namespaces_in_scope`]).
1374    ///
1375    /// # Errors
1376    ///
1377    /// A document too large for the arena.
1378    pub fn start_element_with_namespaces(
1379        &mut self,
1380        name: QName,
1381        namespaces: Arc<[NamespaceBinding]>,
1382    ) -> Result<(), DocumentError> {
1383        self.start_element(name)?;
1384        if !namespaces.is_empty() {
1385            let element = self.top();
1386            self.namespaces.push((element, namespaces));
1387        }
1388        Ok(())
1389    }
1390
1391    fn open_element(&mut self, name: u32) -> Result<(), DocumentError> {
1392        let index = self.append(NodeKind::Element, name, NodeText::Copy(""))?;
1393        self.open.push(index);
1394        self.last_child.push(NONE);
1395        Ok(())
1396    }
1397
1398    /// Adds an attribute to the element just opened.
1399    ///
1400    /// # Errors
1401    ///
1402    /// No element is open, or the element already has content.
1403    pub fn attribute(&mut self, name: QName, value: &str) -> Result<(), DocumentError> {
1404        if self.parentless && self.records.is_empty() {
1405            // A parentless attribute: the root of its tree.
1406            let xml_base = is_xml_base(name.namespace.as_deref(), &name.local);
1407            let id = self.intern(name)?;
1408            let text = self.store_text(NodeText::Copy(value))?;
1409            self.records
1410                .push(Record::new(NodeKind::Attribute, id, NONE, NONE, 0, text));
1411            self.has_xml_base |= xml_base;
1412            return Ok(());
1413        }
1414        let element = self.top();
1415        let has_content = self.last_child.last().is_some_and(|&l| l != NONE);
1416        if element == NONE
1417            || self.records[element as usize].kind != NodeKind::Element
1418            || has_content
1419        {
1420            return Err(DocumentError::new(format!(
1421                "attribute {name} outside an element start"
1422            )));
1423        }
1424        let first = element as usize + 1;
1425        let existing = (first..self.records.len()).find(|&i| {
1426            let id = self.records[i].name;
1427            self.names[id as usize].same_expanded_name(&name)
1428        });
1429        let xml_base = is_xml_base(name.namespace.as_deref(), &name.local);
1430        let id = self.intern(name)?;
1431        if let Some(i) = existing {
1432            let (text_start, text_len) = self.store_text(NodeText::Copy(value))?;
1433            let record = &mut self.records[i];
1434            record.name = id;
1435            record.text_start = text_start;
1436            record.text_len = text_len;
1437            self.has_xml_base |= xml_base;
1438            return Ok(());
1439        }
1440        self.push_attribute(id, xml_base, NodeText::Copy(value))
1441    }
1442
1443    /// Adds an attribute, known not to be on the element yet, to the element just opened.
1444    fn push_attribute(
1445        &mut self,
1446        name: u32,
1447        xml_base: bool,
1448        value: NodeText<'_>,
1449    ) -> Result<(), DocumentError> {
1450        let element = self.top();
1451        let index = to_u32(self.records.len())?;
1452        to_u32(self.records.len() + 1)?;
1453        let previous = if index == element + 1 {
1454            NONE
1455        } else {
1456            index - 1
1457        };
1458        let text = self.store_text(value)?;
1459        self.records.push(Record::new(
1460            NodeKind::Attribute,
1461            name,
1462            element,
1463            previous,
1464            index,
1465            text,
1466        ));
1467        self.records[element as usize].first_child = index + 1;
1468        self.has_xml_base |= xml_base;
1469        Ok(())
1470    }
1471
1472    /// Adds text, merged with text added just before.
1473    ///
1474    /// # Errors
1475    ///
1476    /// A document too large for the arena.
1477    pub fn text(&mut self, value: &str) -> Result<(), DocumentError> {
1478        if value.is_empty() {
1479            // At the top of a parentless tree, a zero-length text node (XSLT constructs
1480            // them in sequences); dropped anywhere else.
1481            if self.parentless && self.records.is_empty() {
1482                return self
1483                    .append(NodeKind::Text, NONE, NodeText::Copy(""))
1484                    .map(drop);
1485            }
1486            return Ok(());
1487        }
1488        let last = self.last_child.last().copied().unwrap_or(NONE);
1489        // Text merges with the text node just before when that node's text is the end of
1490        // the copied texts (always so for a built tree, whose texts are all copied).
1491        let mergeable = last != NONE
1492            && last as usize + 1 == self.records.len()
1493            && self.records[last as usize].kind == NodeKind::Text
1494            && {
1495                let r = &self.records[last as usize];
1496                r.text_start as usize + r.text_len as usize == self.source_len + self.text.len()
1497                    && r.text_start as usize >= self.source_len
1498            };
1499        if mergeable {
1500            self.store_text(NodeText::Copy(value))?;
1501            let record = &mut self.records[last as usize];
1502            record.text_len = to_u32(record.text_len as usize + value.len())?;
1503            return Ok(());
1504        }
1505        self.append(NodeKind::Text, NONE, NodeText::Copy(value))
1506            .map(drop)
1507    }
1508
1509    /// Adds a comment.
1510    ///
1511    /// # Errors
1512    ///
1513    /// A document too large for the arena.
1514    pub fn comment(&mut self, value: &str) -> Result<(), DocumentError> {
1515        self.append(NodeKind::Comment, NONE, NodeText::Copy(value))
1516            .map(drop)
1517    }
1518
1519    /// Adds a processing instruction.
1520    ///
1521    /// # Errors
1522    ///
1523    /// A document too large for the arena.
1524    pub fn processing_instruction(
1525        &mut self,
1526        target: &str,
1527        value: &str,
1528    ) -> Result<(), DocumentError> {
1529        let name = self.intern(QName::local(target))?;
1530        self.append(NodeKind::ProcessingInstruction, name, NodeText::Copy(value))
1531            .map(drop)
1532    }
1533
1534    /// Closes the innermost open element.
1535    ///
1536    /// # Errors
1537    ///
1538    /// No element is open.
1539    pub fn end_element(&mut self) -> Result<(), DocumentError> {
1540        if self.open.len() <= self.base() {
1541            return Err(DocumentError::new("end of element without a start"));
1542        }
1543        let element = self.top();
1544        self.open.pop();
1545        self.last_child.pop();
1546        let end = to_u32(self.records.len())?;
1547        self.records[element as usize].end = end;
1548        Ok(())
1549    }
1550
1551    /// The finished document, with its document URI and the base URI of its nodes.
1552    ///
1553    /// # Errors
1554    ///
1555    /// An element is still open.
1556    pub fn finish(
1557        self,
1558        document_uri: Option<String>,
1559        base_uri: Option<String>,
1560    ) -> Result<Rc<Document>, DocumentError> {
1561        self.finish_with_source(String::new(), document_uri, base_uri)
1562    }
1563
1564    /// The finished document, whose text space starts with `source` (as long as the
1565    /// builder was told).
1566    fn finish_with_source(
1567        mut self,
1568        source: String,
1569        document_uri: Option<String>,
1570        base_uri: Option<String>,
1571    ) -> Result<Rc<Document>, DocumentError> {
1572        if self.open.len() != self.base() {
1573            return Err(DocumentError::new("unclosed element"));
1574        }
1575        if source.len() != self.source_len {
1576            return Err(DocumentError::new("source text of another length"));
1577        }
1578        if self.parentless {
1579            if self.records.is_empty() {
1580                return Err(DocumentError::new("a parentless tree without a node"));
1581            }
1582        } else {
1583            self.records[0].end = to_u32(self.records.len())?;
1584        }
1585        // No spare capacity is kept: a parsed tree is sized exactly, a built one is
1586        // trimmed once.
1587        self.records.shrink_to_fit();
1588        self.names.shrink_to_fit();
1589        self.text.shrink_to_fit();
1590        Ok(Rc::new(Document {
1591            serial: NEXT_SERIAL.fetch_add(1, AtomicOrdering::Relaxed),
1592            uri: document_uri,
1593            base_uri,
1594            has_xml_base: self.has_xml_base,
1595            records: self.records,
1596            names: self.names,
1597            namespaces: self.namespaces,
1598            source,
1599            text: self.text,
1600            elements: OnceCell::new(),
1601            searches: Cell::new(0),
1602            view: self.view,
1603            ids: OnceCell::new(),
1604        }))
1605    }
1606}
1607
1608/// Saxon's `Navigator.alphaKey`: a number as a string that sorts as the number does, a
1609/// letter for its number of digits first.
1610fn alpha_key(value: u32) -> String {
1611    if value < 1 {
1612        return "a".to_owned();
1613    }
1614    let digits = value.to_string();
1615    let letter = char::from(b'a' + u8::try_from(digits.len()).unwrap_or(10));
1616    format!("{letter}{digits}")
1617}
1618
1619fn is_xml_base(namespace: Option<&str>, local: &str) -> bool {
1620    local == "base" && namespace == Some(XML_NAMESPACE)
1621}
1622
1623/// The offset of `part` in `input`, if `part` is a slice of it.
1624fn offset_in(input: &str, part: &str) -> Option<usize> {
1625    let start = part.as_ptr().addr().checked_sub(input.as_ptr().addr())?;
1626    (start.checked_add(part.len())? <= input.len()).then_some(start)
1627}
1628
1629/// The error of a document the reader refuses.
1630fn xml_error(e: &einvoice_xml::Error) -> DocumentError {
1631    DocumentError::new(format!("XML: {e}"))
1632}
1633
1634/// The namespace names of a parsed document, numbered in order of appearance, so that
1635/// a name is looked up by its prefix, local part and namespace number: the namespace
1636/// names the reader gives only live until its next event.
1637struct Namespaces<'a> {
1638    input: &'a str,
1639    ids: HashMap<Box<str>, u32>,
1640    /// The last namespace name looked up, when it is a slice of the input (whose
1641    /// content its address and length then identify): its offset, length and number.
1642    last: Option<(usize, usize, u32)>,
1643}
1644
1645impl<'a> Namespaces<'a> {
1646    fn new(input: &'a str) -> Self {
1647        Self {
1648            input,
1649            ids: HashMap::new(),
1650            last: None,
1651        }
1652    }
1653
1654    /// The number of a namespace name, [`NONE`] for no namespace.
1655    fn id(&mut self, namespace: Option<&str>) -> Result<u32, DocumentError> {
1656        let Some(namespace) = namespace else {
1657            return Ok(NONE);
1658        };
1659        let at = offset_in(self.input, namespace);
1660        if let (Some(at), Some((last, len, id))) = (at, self.last)
1661            && at == last
1662            && namespace.len() == len
1663        {
1664            return Ok(id);
1665        }
1666        let id = if let Some(&id) = self.ids.get(namespace) {
1667            id
1668        } else {
1669            let id = to_u32(self.ids.len())?;
1670            self.ids.insert(namespace.into(), id);
1671            id
1672        };
1673        if let Some(at) = at {
1674            self.last = Some((at, namespace.len(), id));
1675        }
1676        Ok(id)
1677    }
1678}
1679
1680/// A name as the reader gives it: prefix as written (empty for none), local part (both
1681/// slices of the text) and the number of its namespace name ([`Namespaces::id`]).
1682type NameKey<'a> = (&'a str, &'a str, u32);
1683
1684/// The names of a parsed document in the builder's table, by [`NameKey`].
1685struct Names<'a> {
1686    namespaces: Namespaces<'a>,
1687    ids: HashMap<NameKey<'a>, u32>,
1688}
1689
1690impl<'a> Names<'a> {
1691    fn new(input: &'a str) -> Self {
1692        Self {
1693            namespaces: Namespaces::new(input),
1694            ids: HashMap::new(),
1695        }
1696    }
1697
1698    /// The identity of a name in the builder's table, added on first sight.
1699    fn id(
1700        &mut self,
1701        builder: &mut TreeBuilder,
1702        name: einvoice_xml::Name<'_, 'a>,
1703    ) -> Result<u32, DocumentError> {
1704        let key = (name.prefix, name.local, self.namespaces.id(name.namespace)?);
1705        if let Some(&id) = self.ids.get(&key) {
1706            return Ok(id);
1707        }
1708        let id = builder.push_name(QName {
1709            prefix: (!name.prefix.is_empty()).then(|| name.prefix.to_owned()),
1710            namespace: name.namespace.map(str::to_owned),
1711            local: name.local.to_owned(),
1712        })?;
1713        self.ids.insert(key, id);
1714        Ok(id)
1715    }
1716}
1717
1718/// What a pass over the events of a document does with its nodes, in document order.
1719/// Adjacent text events make one text node, given to [`Pass::text`] once complete and
1720/// only when not empty; text outside the document element is not part of the data
1721/// model and is not given.
1722trait Pass<'a> {
1723    fn start(&mut self, start: einvoice_xml::StartElement<'_, 'a>) -> Result<(), DocumentError>;
1724    fn end(&mut self) -> Result<(), DocumentError>;
1725    fn text(&mut self, text: &str) -> Result<(), DocumentError>;
1726    fn comment(&mut self, value: &str) -> Result<(), DocumentError>;
1727    fn processing_instruction(
1728        &mut self,
1729        pi: &einvoice_xml::ProcessingInstruction<'a>,
1730    ) -> Result<(), DocumentError>;
1731}
1732
1733/// Reads `input` to the end, giving its nodes to `pass`. A well-formedness error comes
1734/// first, wherever it is in the text; then an element nested deeper than `max_depth`
1735/// (the first in document order), the elements after it not being given to `pass`.
1736fn read<'a>(input: &'a str, max_depth: u32, pass: &mut impl Pass<'a>) -> Result<(), DocumentError> {
1737    let mut reader = einvoice_xml::Reader::new(input);
1738    let mut depth = 0u32;
1739    // The text node being read: adjacent text events (character data and CDATA
1740    // sections) make one.
1741    let mut text: Option<Cow<'a, str>> = None;
1742    let mut too_deep: Option<LimitExceeded> = None;
1743    while let Some(event) = reader.next_event().map_err(|e| xml_error(&e))? {
1744        if let einvoice_xml::Event::Text(t) = event {
1745            if depth > 0 && too_deep.is_none() {
1746                match &mut text {
1747                    None => text = Some(t.value),
1748                    Some(joined) => joined.to_mut().push_str(&t.value),
1749                }
1750            }
1751            continue;
1752        }
1753        if let Some(joined) = text.take()
1754            && !joined.is_empty()
1755        {
1756            pass.text(&joined)?;
1757        }
1758        match event {
1759            einvoice_xml::Event::Start(start) => {
1760                depth = depth.saturating_add(1);
1761                if depth > max_depth && too_deep.is_none() {
1762                    // The rest is only checked for well-formedness.
1763                    let at = einvoice_xml::TextPos::at(input, start.range().start);
1764                    too_deep = Some(LimitExceeded::Depth {
1765                        max: max_depth,
1766                        line: at.row,
1767                        column: at.col,
1768                    });
1769                }
1770                if too_deep.is_none() {
1771                    pass.start(start)?;
1772                }
1773            }
1774            einvoice_xml::Event::End(_) => {
1775                depth = depth.saturating_sub(1);
1776                if too_deep.is_none() {
1777                    pass.end()?;
1778                }
1779            }
1780            einvoice_xml::Event::Comment(comment) if too_deep.is_none() => {
1781                pass.comment(&comment.value)?;
1782            }
1783            einvoice_xml::Event::ProcessingInstruction(pi) if too_deep.is_none() => {
1784                pass.processing_instruction(&pi)?;
1785            }
1786            _ => {}
1787        }
1788    }
1789    match too_deep {
1790        Some(limit) => Err(DocumentError::limit_exceeded(limit)),
1791        None => Ok(()),
1792    }
1793}
1794
1795/// The first pass: the number of nodes of the tree (the document node included) and
1796/// the bytes of text to copy into it: all of them, or with `keep_source` those that
1797/// are not slices of the text.
1798struct Sizes<'a> {
1799    input: &'a str,
1800    keep_source: bool,
1801    nodes: usize,
1802    text_bytes: usize,
1803}
1804
1805impl Sizes<'_> {
1806    fn add(&mut self, text: &str) {
1807        self.nodes += 1;
1808        if !(self.keep_source && offset_in(self.input, text).is_some()) {
1809            self.text_bytes += text.len();
1810        }
1811    }
1812}
1813
1814impl<'a> Pass<'a> for Sizes<'a> {
1815    fn start(&mut self, start: einvoice_xml::StartElement<'_, 'a>) -> Result<(), DocumentError> {
1816        self.nodes += 1;
1817        for attribute in start.attributes() {
1818            self.add(attribute.value);
1819        }
1820        Ok(())
1821    }
1822
1823    fn end(&mut self) -> Result<(), DocumentError> {
1824        Ok(())
1825    }
1826
1827    fn text(&mut self, text: &str) -> Result<(), DocumentError> {
1828        self.add(text);
1829        Ok(())
1830    }
1831
1832    fn comment(&mut self, value: &str) -> Result<(), DocumentError> {
1833        self.add(value);
1834        Ok(())
1835    }
1836
1837    fn processing_instruction(
1838        &mut self,
1839        pi: &einvoice_xml::ProcessingInstruction<'a>,
1840    ) -> Result<(), DocumentError> {
1841        self.add(pi.value.as_deref().unwrap_or(""));
1842        Ok(())
1843    }
1844}
1845
1846/// The second pass: the tree, in a builder sized by the first.
1847struct Fill<'a> {
1848    input: &'a str,
1849    keep_source: bool,
1850    builder: TreeBuilder,
1851    names: Names<'a>,
1852}
1853
1854impl Fill<'_> {
1855    /// Where a text is stored: as a range of the input if `keep_source` and it is a
1856    /// slice of it, else copied.
1857    fn node_text<'s>(&self, text: &'s str) -> Result<NodeText<'s>, DocumentError> {
1858        Ok(
1859            match self
1860                .keep_source
1861                .then(|| offset_in(self.input, text))
1862                .flatten()
1863            {
1864                Some(start) => NodeText::Source(to_u32(start)?, to_u32(text.len())?),
1865                None => NodeText::Copy(text),
1866            },
1867        )
1868    }
1869}
1870
1871impl<'a> Pass<'a> for Fill<'a> {
1872    fn start(&mut self, start: einvoice_xml::StartElement<'_, 'a>) -> Result<(), DocumentError> {
1873        let id = self.names.id(&mut self.builder, start.name())?;
1874        self.builder.open_element(id)?;
1875        let declarations = start.namespace_declarations();
1876        if declarations.len() > 0 {
1877            let bindings: Arc<[NamespaceBinding]> = declarations
1878                .map(|(prefix, uri)| NamespaceBinding {
1879                    prefix: (!prefix.is_empty()).then(|| prefix.to_owned()),
1880                    uri: uri.to_owned(),
1881                })
1882                .collect();
1883            let element = self.builder.top();
1884            self.builder.namespaces.push((element, bindings));
1885        }
1886        // The reader refuses duplicate attributes: each one is new.
1887        for attribute in start.attributes() {
1888            let id = self.names.id(&mut self.builder, attribute.name)?;
1889            let text = self.node_text(attribute.value)?;
1890            self.builder.push_attribute(
1891                id,
1892                is_xml_base(attribute.name.namespace, attribute.name.local),
1893                text,
1894            )?;
1895        }
1896        Ok(())
1897    }
1898
1899    fn end(&mut self) -> Result<(), DocumentError> {
1900        self.builder.end_element()
1901    }
1902
1903    fn text(&mut self, text: &str) -> Result<(), DocumentError> {
1904        let text = self.node_text(text)?;
1905        self.builder.append(NodeKind::Text, NONE, text).map(drop)
1906    }
1907
1908    fn comment(&mut self, value: &str) -> Result<(), DocumentError> {
1909        let text = self.node_text(value)?;
1910        self.builder.append(NodeKind::Comment, NONE, text).map(drop)
1911    }
1912
1913    fn processing_instruction(
1914        &mut self,
1915        pi: &einvoice_xml::ProcessingInstruction<'a>,
1916    ) -> Result<(), DocumentError> {
1917        let target = einvoice_xml::Name {
1918            prefix: "",
1919            local: pi.target,
1920            namespace: None,
1921        };
1922        let id = self.names.id(&mut self.builder, target)?;
1923        let text = self.node_text(pi.value.as_deref().unwrap_or(""))?;
1924        self.builder
1925            .append(NodeKind::ProcessingInstruction, id, text)
1926            .map(drop)
1927    }
1928}
1929
1930/// Builds the tree of a document, in two passes of the streaming reader over its text:
1931/// the first checks it (well-formedness, then depth) and counts the nodes and the bytes
1932/// of text to copy, so that the arena is allocated once at its exact size; the second
1933/// fills it. With `keep_source`, every text that is a slice of `input` is stored as a
1934/// range of it instead of being copied (the document then keeps `input`). An element
1935/// nested deeper than `max_depth` is refused by the first pass, before the arena is
1936/// allocated.
1937fn build_parsed(
1938    input: &str,
1939    keep_source: bool,
1940    max_depth: u32,
1941) -> Result<TreeBuilder, DocumentError> {
1942    let mut sizes = Sizes {
1943        input,
1944        keep_source,
1945        nodes: 1,
1946        text_bytes: 0,
1947    };
1948    read(input, max_depth, &mut sizes)?;
1949    let mut fill = Fill {
1950        input,
1951        keep_source,
1952        builder: TreeBuilder::with_capacity(
1953            sizes.nodes,
1954            sizes.text_bytes,
1955            if keep_source { input.len() } else { 0 },
1956        ),
1957        names: Names::new(input),
1958    };
1959    read(input, max_depth, &mut fill)?;
1960    Ok(fill.builder)
1961}
1962
1963/// The `file:` URI that Saxon-HE gives a document read from a file: Java's
1964/// `File.toURI().toString()` of the absolute path. ASCII characters outside the URI path
1965/// syntax, Unicode space separators and control characters are percent-encoded (UTF-8,
1966/// upper-case hex); other non-ASCII characters are kept. On Windows, `C:\a\b` becomes
1967/// `file:/C:/a/b`.
1968///
1969/// Returns `None` for a relative path or one that is not valid Unicode.
1970#[must_use]
1971pub fn file_uri(path: &Path) -> Option<String> {
1972    if !path.is_absolute() {
1973        return None;
1974    }
1975    let text = path.to_str()?.replace('\\', "/");
1976    let mut uri = String::from("file:");
1977    if !text.starts_with('/') {
1978        uri.push('/');
1979    }
1980    for c in text.chars() {
1981        let keep = if c.is_ascii() {
1982            c.is_ascii_alphanumeric() || "-_.!~*'():@&=+$,;/".contains(c)
1983        } else {
1984            // java.lang.Character.isSpaceChar (Zs, Zl, Zp) and isISOControl.
1985            !(matches!(
1986                c,
1987                '\u{A0}' | '\u{1680}' | '\u{2000}'
1988                    ..='\u{200A}' | '\u{2028}' | '\u{2029}' | '\u{202F}' | '\u{205F}' | '\u{3000}'
1989            ) || c.is_control())
1990        };
1991        if keep {
1992            uri.push(c);
1993        } else {
1994            let mut buffer = [0; 4];
1995            for byte in c.encode_utf8(&mut buffer).bytes() {
1996                let _ = write!(uri, "%{byte:02X}");
1997            }
1998        }
1999    }
2000    Some(uri)
2001}
2002
2003#[cfg(test)]
2004mod tests {
2005    use super::*;
2006
2007    fn parse(xml: &str) -> Rc<Document> {
2008        Document::parse(xml, Some("file:/t.xml")).unwrap()
2009    }
2010
2011    fn describe(node: &Node) -> String {
2012        match node.kind() {
2013            NodeKind::Document => "/".to_owned(),
2014            NodeKind::Element => node.name().unwrap().to_string(),
2015            NodeKind::Attribute => format!("@{}", node.name().unwrap()),
2016            NodeKind::Text => format!("{:?}", node.string_value()),
2017            NodeKind::Comment => format!("<!--{}-->", node.string_value()),
2018            NodeKind::ProcessingInstruction => format!("<?{}?>", node.name().unwrap()),
2019        }
2020    }
2021
2022    fn walk(node: &Node, axis: NodeAxis) -> Vec<String> {
2023        node.axis(axis).map(|n| describe(&n)).collect()
2024    }
2025
2026    fn find(tree: &Rc<Document>, local: &str) -> Node {
2027        tree.root()
2028            .axis(NodeAxis::Descendant)
2029            .find(|n| n.name().is_some_and(|name| name.local == local))
2030            .unwrap()
2031    }
2032
2033    const XML: &str = "<?xml version='1.0'?><!--c0--><r xmlns:p='urn:p' a='1' p:b='2'> \
2034        <x>1<y q='3'>2</y>3</x><p:z/><!--c1--><?pi data?><w><v/></w></r>";
2035
2036    const NONE: [&str; 0] = [];
2037
2038    #[test]
2039    fn document_order_and_axes() {
2040        let tree = parse(XML);
2041        let root = tree.root();
2042        assert_eq!(walk(&root, NodeAxis::Child), ["<!--c0-->", "r"]);
2043        let top = find(&tree, "r");
2044        assert_eq!(walk(&top, NodeAxis::Attribute), ["@a", "@p:b"]);
2045        assert_eq!(
2046            walk(&top, NodeAxis::Child),
2047            ["\" \"", "x", "p:z", "<!--c1-->", "<?pi?>", "w"]
2048        );
2049        assert_eq!(
2050            walk(&top, NodeAxis::Descendant),
2051            [
2052                "\" \"",
2053                "x",
2054                "\"1\"",
2055                "y",
2056                "\"2\"",
2057                "\"3\"",
2058                "p:z",
2059                "<!--c1-->",
2060                "<?pi?>",
2061                "w",
2062                "v"
2063            ]
2064        );
2065        let y = find(&tree, "y");
2066        assert_eq!(walk(&y, NodeAxis::Ancestor), ["x", "r", "/"]);
2067        assert_eq!(walk(&y, NodeAxis::AncestorOrSelf), ["y", "x", "r", "/"]);
2068        assert_eq!(walk(&y, NodeAxis::PrecedingSibling), ["\"1\""]);
2069        assert_eq!(walk(&y, NodeAxis::FollowingSibling), ["\"3\""]);
2070        assert_eq!(
2071            walk(&y, NodeAxis::Preceding),
2072            ["\"1\"", "\" \"", "<!--c0-->"]
2073        );
2074        let v = find(&tree, "v");
2075        assert_eq!(
2076            walk(&v, NodeAxis::Preceding),
2077            [
2078                "<?pi?>",
2079                "<!--c1-->",
2080                "p:z",
2081                "\"3\"",
2082                "\"2\"",
2083                "y",
2084                "\"1\"",
2085                "x",
2086                "\" \"",
2087                "<!--c0-->"
2088            ]
2089        );
2090        let q = y.attributes().next().unwrap();
2091        assert_eq!(walk(&q, NodeAxis::Parent), ["y"]);
2092        assert_eq!(
2093            walk(&q, NodeAxis::Preceding),
2094            ["\"1\"", "\" \"", "<!--c0-->"]
2095        );
2096        assert_eq!(walk(&q, NodeAxis::FollowingSibling), NONE);
2097        assert_eq!(walk(&q, NodeAxis::PrecedingSibling), NONE);
2098        assert_eq!(walk(&q, NodeAxis::DescendantOrSelf), ["@q"]);
2099        assert_eq!(walk(&q, NodeAxis::Child), NONE);
2100        let all: Vec<Node> = root.axis(NodeAxis::DescendantOrSelf).collect();
2101        assert!(
2102            all.windows(2)
2103                .all(|w| w[0].cmp_document_order(&w[1]) == Ordering::Less)
2104        );
2105    }
2106
2107    #[test]
2108    fn values_names_and_prefixes() {
2109        let tree = parse(XML);
2110        let top = find(&tree, "r");
2111        assert_eq!(top.string_value(), " 123");
2112        assert_eq!(find(&tree, "x").string_value(), "123");
2113        assert_eq!(find(&tree, "y").string_value(), "2");
2114        assert_eq!(find(&tree, "w").string_value(), "");
2115        let z = find(&tree, "z");
2116        assert_eq!(z.name().unwrap().to_string(), "p:z");
2117        assert_eq!(z.name().unwrap().namespace.as_deref(), Some("urn:p"));
2118        let prefixed = top.attributes().nth(1).unwrap();
2119        assert_eq!(prefixed.name().unwrap().prefix.as_deref(), Some("p"));
2120        assert!(matches!(prefixed.typed_value(), AtomicValue::UntypedAtomic(s) if s == "2"));
2121        let comment = tree.root().children().next().unwrap();
2122        assert!(matches!(comment.typed_value(), AtomicValue::String(s) if s == "c0"));
2123        assert_eq!(tree.document_uri(), None);
2124        assert_eq!(tree.base_uri(), Some("file:/t.xml"));
2125        let loaded = Document::parse_loaded("<a/>", "file:/t.xml").unwrap();
2126        assert_eq!(loaded.document_uri(), Some("file:/t.xml"));
2127        assert_eq!(loaded.base_uri(), Some("file:/t.xml"));
2128        assert_eq!(z.root(), tree.root());
2129        assert_ne!(z, top);
2130    }
2131
2132    #[test]
2133    fn undeclared_default_namespace_is_no_namespace() {
2134        let tree = parse("<r xmlns='urn:d'><n xmlns=''><m/></n></r>");
2135        assert_eq!(
2136            find(&tree, "r").name().unwrap().namespace.as_deref(),
2137            Some("urn:d")
2138        );
2139        assert_eq!(find(&tree, "n").name().unwrap().namespace, None);
2140        assert_eq!(find(&tree, "m").name().unwrap().namespace, None);
2141    }
2142
2143    #[test]
2144    fn same_namespace_two_prefixes() {
2145        let tree = parse("<a:r xmlns:a='urn:x' xmlns:b='urn:x'><b:c a:d='1'/></a:r>");
2146        let inner = find(&tree, "c");
2147        assert_eq!(inner.name().unwrap().to_string(), "b:c");
2148        assert_eq!(find(&tree, "r").name().unwrap().to_string(), "a:r");
2149        let attribute = inner.attributes().next().unwrap();
2150        assert_eq!(attribute.name().unwrap().to_string(), "a:d");
2151    }
2152
2153    #[test]
2154    fn builder_merges_text_and_replaces_attributes() {
2155        let mut builder = TreeBuilder::new();
2156        builder.start_element(QName::local("e")).unwrap();
2157        builder.attribute(QName::local("a"), "1").unwrap();
2158        builder.attribute(QName::local("a"), "2").unwrap();
2159        builder.text("x").unwrap();
2160        builder.text("").unwrap();
2161        builder.text("y").unwrap();
2162        assert!(builder.attribute(QName::local("late"), "1").is_err());
2163        builder.end_element().unwrap();
2164        assert!(builder.end_element().is_err());
2165        let tree = builder.finish(None, None).unwrap();
2166        let element = tree.root().children().next().unwrap();
2167        let attributes: Vec<_> = element
2168            .attributes()
2169            .map(|a| a.string_value().into_owned())
2170            .collect();
2171        assert_eq!(attributes, ["2"]);
2172        let texts: Vec<_> = element
2173            .children()
2174            .map(|t| t.string_value().into_owned())
2175            .collect();
2176        assert_eq!(texts, ["xy"]);
2177    }
2178
2179    #[test]
2180    fn whitespace_text_kept_and_dtd_refused() {
2181        let tree = parse("<r>\n  <a/>\n</r>\n");
2182        let top = tree.root().children().next().unwrap();
2183        assert_eq!(top.children().count(), 3);
2184        assert!(Document::parse("<!DOCTYPE r [<!ENTITY e 'x'>]><r>&e;</r>", None).is_err());
2185        assert!(Document::parse("<r><a></r>", None).is_err());
2186    }
2187
2188    #[test]
2189    fn adjacent_text_is_one_node() {
2190        let text = "<r>a<![CDATA[<b>]]>c&amp;d<!--x-->e\r\nf<s/></r>";
2191        for tree in [parse(text), Document::parse(text.to_owned(), None).unwrap()] {
2192            let top = tree.root().children().next().unwrap();
2193            let children: Vec<_> = top
2194                .children()
2195                .map(|t| (t.kind(), t.string_value().into_owned()))
2196                .collect();
2197            assert_eq!(
2198                children,
2199                [
2200                    (NodeKind::Text, "a<b>c&d".to_owned()),
2201                    (NodeKind::Comment, "x".to_owned()),
2202                    (NodeKind::Text, "e\nf".to_owned()),
2203                    (NodeKind::Element, String::new()),
2204                ]
2205            );
2206        }
2207        // Line ends are normalised in comments and processing instructions too (XML 1.0,
2208        // section 2.11).
2209        let tree = parse("<r><!--a\r\nb\rc--><?p a\r\nb?></r>");
2210        let values: Vec<_> = tree
2211            .root()
2212            .children()
2213            .next()
2214            .unwrap()
2215            .children()
2216            .map(|n| n.string_value().into_owned())
2217            .collect();
2218        assert_eq!(values, ["a\nb\nc", "a\nb"]);
2219        // A carriage return next to a reference is a line end like any other.
2220        assert_eq!(parse("<r>x\r&amp;y</r>").root().string_value(), "x\n&y");
2221    }
2222
2223    #[test]
2224    fn errors_are_those_of_the_reader() {
2225        let error = Document::parse("<r>\n<a></r>", None).unwrap_err();
2226        assert_eq!(error.message(), "XML: expected 'a' tag, not 'r' at 2:4");
2227        assert_eq!(error.limit(), None);
2228        let error = Document::parse("<!DOCTYPE r><r/>", None).unwrap_err();
2229        assert_eq!(error.message(), "XML: XML with DTD detected");
2230    }
2231
2232    #[test]
2233    fn records_are_compact() {
2234        assert_eq!(std::mem::size_of::<Record>(), 32);
2235    }
2236
2237    /// Kind, name, string value and parent of every node, in document order.
2238    fn dump(tree: &Rc<Document>) -> Vec<String> {
2239        (0..tree.node_count())
2240            .map(|i| {
2241                let node = Node::new(Rc::clone(tree), u32::try_from(i).unwrap());
2242                let name = node.name().map(|n| {
2243                    format!(
2244                        "{}{{{}}}{}",
2245                        n,
2246                        n.namespace.as_deref().unwrap_or(""),
2247                        n.local
2248                    )
2249                });
2250                format!(
2251                    "{:?} {name:?} {:?} {:?}",
2252                    node.kind(),
2253                    node.string_value(),
2254                    node.parent().map(|p| p.index())
2255                )
2256            })
2257            .collect()
2258    }
2259
2260    /// Texts written verbatim in an owned source are ranges of it; the others (character
2261    /// and entity references, line ends, attribute whitespace, CDATA sections merged with
2262    /// text) are copied. The tree is the same as from the borrowed text, which is copied
2263    /// whole, and its arenas are sized exactly.
2264    #[test]
2265    fn owned_source_is_referred_to() {
2266        let xml = "<?xml version='1.0'?><!--top--><?pi top data?>\
2267            <p:r xmlns:p='urn:p' xmlns='urn:d' a='plain' b='x&amp;y' c='t\tu'>\
2268            verbatim<e p:f='1'>a&#65;b</e>line\r\nend<![CDATA[<&>]]>more<!--c-->\
2269            <?pi in?><e/>tail</p:r>";
2270        let borrowed = Document::parse(xml, None).unwrap();
2271        let owned = Document::parse(xml.to_owned(), None).unwrap();
2272        assert_eq!(dump(&borrowed), dump(&owned));
2273        assert_eq!(borrowed.source, "");
2274        assert_eq!(owned.source, xml);
2275        // Copied: "x&y", "t u", "aAb", "line\nend<&>more"; everything else is a range.
2276        assert_eq!(owned.text, "x&yt uaAbline\nend<&>more");
2277        let copied_whole: usize = (0..borrowed.node_count())
2278            .map(|i| {
2279                let i = u32::try_from(i).unwrap();
2280                match borrowed.kind(i) {
2281                    NodeKind::Element | NodeKind::Document => 0,
2282                    _ => borrowed.own_text(i).len(),
2283                }
2284            })
2285            .sum();
2286        assert_eq!(borrowed.text.len(), copied_whole);
2287        for tree in [&borrowed, &owned] {
2288            assert_eq!(tree.records.capacity(), tree.records.len());
2289            assert_eq!(tree.text.capacity(), tree.text.len());
2290            assert_eq!(tree.names.capacity(), tree.names.len());
2291        }
2292        let r = find(&owned, "r");
2293        let values: Vec<_> = r
2294            .attributes()
2295            .map(|a| a.string_value().into_owned())
2296            .collect();
2297        assert_eq!(values, ["plain", "x&y", "t u"]);
2298        assert_eq!(r.string_value(), "verbatimaAbline\nend<&>moretail");
2299        assert_eq!(r.name().unwrap().to_string(), "p:r");
2300        let e = find(&owned, "e");
2301        assert_eq!(e.name().unwrap().namespace.as_deref(), Some("urn:d"));
2302        let f = e.attributes().next().unwrap();
2303        assert_eq!(f.name().unwrap().to_string(), "p:f");
2304        assert_eq!(f.name().unwrap().namespace.as_deref(), Some("urn:p"));
2305        // Names are interned: the two `e` elements share one entry.
2306        assert_eq!(owned.names.iter().filter(|n| n.local == "e").count(), 1);
2307    }
2308
2309    #[test]
2310    fn built_trees_merge_text_after_a_parsed_shape() {
2311        // A built tree has no source: all its texts are copied, and adjacent text merges
2312        // even after other copied texts.
2313        let mut builder = TreeBuilder::new();
2314        builder.start_element(QName::local("e")).unwrap();
2315        builder.attribute(QName::local("a"), "v").unwrap();
2316        builder.comment("c").unwrap();
2317        builder.text("x").unwrap();
2318        builder.text("y").unwrap();
2319        builder.processing_instruction("t", "d").unwrap();
2320        builder.text("z").unwrap();
2321        builder.end_element().unwrap();
2322        let tree = builder.finish(None, None).unwrap();
2323        let e = tree.root().children().next().unwrap();
2324        let children: Vec<_> = e
2325            .children()
2326            .map(|c| (c.kind(), c.string_value().into_owned()))
2327            .collect();
2328        assert_eq!(
2329            children,
2330            [
2331                (NodeKind::Comment, "c".to_owned()),
2332                (NodeKind::Text, "xy".to_owned()),
2333                (NodeKind::ProcessingInstruction, "d".to_owned()),
2334                (NodeKind::Text, "z".to_owned()),
2335            ]
2336        );
2337        assert_eq!(tree.text, "vcxydz");
2338    }
2339
2340    #[test]
2341    fn the_document_cache_parses_a_text_once() {
2342        fn shape(doc: &Rc<Document>) -> Vec<String> {
2343            doc.root()
2344                .axis(NodeAxis::Descendant)
2345                .flat_map(|n| std::iter::once(n.clone()).chain(n.attributes()))
2346                .map(|n| format!("{} {}", describe(&n), n.string_value()))
2347                .collect()
2348        }
2349        let cache = DocumentCache::new();
2350        let xml = "<cl id='1'><e v='a'/>text &amp; more<e v='b'/></cl>";
2351        let uri = "file:/codes.xml";
2352        let first = cache.parse_loaded(xml.to_owned(), uri, 8).unwrap();
2353        let between = parse("<x/>");
2354        let second = cache.parse_loaded(xml.to_owned(), uri, 8).unwrap();
2355        // The same tree, as a new document created after the one parsed in between.
2356        assert_eq!(shape(&first), shape(&second));
2357        assert_eq!(second.document_uri(), Some(uri));
2358        assert_eq!(second.base_uri(), Some(uri));
2359        assert_eq!(second.node_count(), first.node_count());
2360        assert_ne!(first.root(), second.root());
2361        assert_eq!(
2362            between.root().cmp_document_order(&second.root()),
2363            Ordering::Less
2364        );
2365        assert_eq!(
2366            first.root().cmp_document_order(&between.root()),
2367            Ordering::Less
2368        );
2369        assert_eq!(cache.entries.lock().unwrap().len(), 1);
2370        // Another text, URI or maximum depth is parsed, and kept apart.
2371        let other = cache.parse_loaded("<cl/>".to_owned(), uri, 8).unwrap();
2372        assert_eq!(other.node_count(), 2);
2373        let elsewhere = cache
2374            .parse_loaded(xml.to_owned(), "file:/other.xml", 8)
2375            .unwrap();
2376        assert_eq!(elsewhere.document_uri(), Some("file:/other.xml"));
2377        assert_eq!(shape(&elsewhere), shape(&first));
2378        let deeper = cache.parse_loaded(xml.to_owned(), uri, 1).unwrap_err();
2379        assert!(deeper.limit().is_some());
2380        assert_eq!(cache.entries.lock().unwrap().len(), 3);
2381        // A text that does not parse is not kept.
2382        assert!(cache.parse_loaded("<cl>".to_owned(), uri, 8).is_err());
2383        assert_eq!(cache.entries.lock().unwrap().len(), 3);
2384    }
2385
2386    #[test]
2387    fn the_element_index_lists_the_elements_of_a_name_in_document_order() {
2388        let mut xml = String::from(r#"<r xmlns:a="urn:x" xmlns:b="urn:x" xmlns="urn:x">"#);
2389        for i in 0..40 {
2390            let prefix = ["a:", "b:", ""][i % 3];
2391            write!(xml, r#"<{prefix}e n="{i}"><f/><e/></{prefix}e><g>t</g>"#).unwrap();
2392        }
2393        xml.push_str("</r>");
2394        let doc = parse(&xml);
2395        let scan = |start: u32, end: u32| -> Vec<u32> {
2396            (start..end)
2397                .filter(|&i| {
2398                    doc.kind(i) == NodeKind::Element
2399                        && doc.name(i).is_some_and(|n| {
2400                            n.local == "e" && n.namespace.as_deref() == Some("urn:x")
2401                        })
2402                })
2403                .collect()
2404        };
2405        let (first, end) = doc.descendant_range(0);
2406        // The first search is answered without an index, the second builds it.
2407        assert_eq!(doc.elements_named(Some("urn:x"), "e", first, end), None);
2408        let all = doc.elements_named(Some("urn:x"), "e", first, end).unwrap();
2409        assert_eq!(all, scan(first, end).as_slice());
2410        assert_eq!(all.len(), 80);
2411        // A range inside the document, and names it does not have.
2412        let inner = doc.elements_named(Some("urn:x"), "e", 10, 200).unwrap();
2413        assert_eq!(inner, scan(10, 200).as_slice());
2414        assert_eq!(doc.elements_named(None, "e", first, end), Some(&[][..]));
2415        assert_eq!(
2416            doc.elements_named(Some("urn:x"), "zz", first, end),
2417            Some(&[][..])
2418        );
2419        // Small ranges are searched.
2420        assert_eq!(doc.elements_named(Some("urn:x"), "e", 10, 20), None);
2421    }
2422
2423    #[test]
2424    fn file_uris() {
2425        if cfg!(windows) {
2426            return;
2427        }
2428        assert_eq!(
2429            file_uri(Path::new("/a b/c,d%é#[1]\u{a0}.xml")).as_deref(),
2430            Some("file:/a%20b/c,d%25é%23%5B1%5D%C2%A0.xml")
2431        );
2432        assert_eq!(file_uri(Path::new("rel.xml")), None);
2433    }
2434}