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    /// The string value (XDM `dm:string-value`).
891    #[must_use]
892    pub fn string_value(&self) -> Cow<'_, str> {
893        self.doc.string_value(self.index)
894    }
895
896    /// The element of the node's tree with the ID `id`: for a [`TreeView::Tiny`] tree,
897    /// the first element in document order with an `xml:id` attribute of that value
898    /// (whitespace-collapsed), as Saxon-HE 12.10 finds it; never for a
899    /// [`TreeView::Dom`] tree.
900    #[must_use]
901    pub fn by_id(&self, id: &str) -> Option<Self> {
902        let doc = &self.doc;
903        if doc.view == TreeView::Dom {
904            return None;
905        }
906        let ids = doc.ids.get_or_init(|| {
907            let mut ids = HashMap::new();
908            for (index, record) in (0_u32..).zip(&doc.records) {
909                if record.kind != NodeKind::Attribute {
910                    continue;
911                }
912                let is_xml_id = doc.name(index).is_some_and(|n| {
913                    n.local == "id" && n.namespace.as_deref() == Some(XML_NAMESPACE)
914                });
915                if is_xml_id {
916                    let value: Vec<&str> = doc
917                        .own_text(index)
918                        .split([' ', '\t', '\n', '\r'])
919                        .filter(|t| !t.is_empty())
920                        .collect();
921                    ids.entry(value.join(" ")).or_insert(record.parent);
922                }
923            }
924            ids
925        });
926        ids.get(id).map(|&i| Self::new(Rc::clone(doc), i))
927    }
928
929    /// `generate-id()` as Saxon-HE 12.10 forms it for the kind of tree
930    /// ([`TreeView`]); the document number is the creation order of the document, which
931    /// in Saxon depends on what the JVM read before (so are its IDs: only their form is
932    /// Saxon's). An attribute of a [`TreeView::Tiny`] tree gets its element's ID, `a` and
933    /// its number among the attributes of the tree (Saxon's, the fingerprint of its name
934    /// in Saxon's name pool, depends on the JVM too).
935    #[must_use]
936    pub fn generate_id(&self) -> String {
937        let doc = &self.doc;
938        let number = doc.serial + 1;
939        match doc.view {
940            TreeView::Tiny => {
941                let attributes_before = |index: u32| {
942                    doc.records[..index as usize]
943                        .iter()
944                        .filter(|r| r.kind == NodeKind::Attribute)
945                        .count()
946                };
947                let tiny = |index: u32| {
948                    let kind = doc.kind(index);
949                    if kind == NodeKind::Document {
950                        return format!("d{number}");
951                    }
952                    let letter = match kind {
953                        NodeKind::Text => 't',
954                        NodeKind::Comment => 'c',
955                        NodeKind::ProcessingInstruction => 'p',
956                        _ => 'e',
957                    };
958                    let node_number = index as usize - attributes_before(index);
959                    format!("d{number}{letter}{node_number}")
960                };
961                if self.kind() == NodeKind::Attribute {
962                    let parent = doc.record(self.index).parent;
963                    let owner = if parent == NONE {
964                        format!("d{number}")
965                    } else {
966                        tiny(parent)
967                    };
968                    format!("{owner}a{}", attributes_before(self.index))
969                } else {
970                    tiny(self.index)
971                }
972            }
973            TreeView::Dom => {
974                let lineage: Vec<u32> = doc
975                    .cursor(self.index, NodeAxis::AncestorOrSelf)
976                    .walk(doc)
977                    .collect();
978                let mut id = format!("w{number}");
979                for &index in lineage.iter().rev() {
980                    let record = doc.record(index);
981                    if record.parent == NONE {
982                        continue;
983                    }
984                    let position = if record.kind == NodeKind::Attribute {
985                        id.push('a');
986                        index - record.parent - 1
987                    } else {
988                        u32::try_from(
989                            doc.cursor(index, NodeAxis::PrecedingSibling)
990                                .walk(doc)
991                                .count(),
992                        )
993                        .unwrap_or(u32::MAX)
994                    };
995                    id.push_str(&alpha_key(position));
996                }
997                id
998            }
999        }
1000    }
1001
1002    /// The typed value of the node in an untyped tree: `xs:untypedAtomic`, except for
1003    /// comments and processing instructions, whose typed value is an `xs:string`.
1004    #[must_use]
1005    pub fn typed_value(&self) -> AtomicValue {
1006        let value = self.string_value().into_owned();
1007        match self.kind() {
1008            NodeKind::Comment | NodeKind::ProcessingInstruction => AtomicValue::String(value),
1009            _ => AtomicValue::UntypedAtomic(value),
1010        }
1011    }
1012
1013    /// The nodes on an axis from this node, in axis order (reverse document order for
1014    /// the reverse axes).
1015    #[must_use]
1016    pub fn axis(&self, axis: NodeAxis) -> Axis {
1017        Axis {
1018            cursor: self.doc.cursor(self.index, axis),
1019            doc: Rc::clone(&self.doc),
1020        }
1021    }
1022
1023    /// The children, in document order.
1024    #[must_use]
1025    pub fn children(&self) -> Axis {
1026        self.axis(NodeAxis::Child)
1027    }
1028
1029    /// The attributes, in document order (the order of the source).
1030    #[must_use]
1031    pub fn attributes(&self) -> Axis {
1032        self.axis(NodeAxis::Attribute)
1033    }
1034
1035    /// Document order. Nodes of different documents are ordered by the creation of their
1036    /// documents.
1037    #[must_use]
1038    pub fn cmp_document_order(&self, other: &Self) -> Ordering {
1039        self.doc
1040            .serial
1041            .cmp(&other.doc.serial)
1042            .then(self.index.cmp(&other.index))
1043    }
1044}
1045
1046/// The nodes on an axis from a node, in axis order.
1047#[derive(Debug, Clone)]
1048pub struct Axis {
1049    cursor: Cursor,
1050    doc: Rc<Document>,
1051}
1052
1053impl Iterator for Axis {
1054    type Item = Node;
1055
1056    fn next(&mut self) -> Option<Node> {
1057        let index = self.cursor.next(&self.doc)?;
1058        Some(Node::new(Rc::clone(&self.doc), index))
1059    }
1060
1061    fn count(self) -> usize {
1062        self.cursor.walk(&self.doc).count()
1063    }
1064}
1065
1066/// Documents that `fn:document` loads, parsed once and given to every transformation that
1067/// loads them again: the code lists a stylesheet reads, the same text under the same URI
1068/// for each document it validates.
1069///
1070/// [`DocumentCache::parse_loaded`] returns the tree [`Document::parse_loaded_with_max_depth`]
1071/// would build from the text, without parsing it again when the same text was parsed under
1072/// the same URI and maximum depth before: a copy of that tree, which is a new document
1073/// (created now, as a parse now would create it, for the document order of nodes in
1074/// different trees). The cache is shared between threads; it keeps at most
1075/// [`DocumentCache::MAX_DOCUMENTS`] documents of at most [`DocumentCache::MAX_BYTES`] of
1076/// text in all, and parses the others each time.
1077#[derive(Debug, Default)]
1078pub struct DocumentCache {
1079    entries: std::sync::Mutex<Vec<CachedDocument>>,
1080}
1081
1082/// A parsed document kept by a [`DocumentCache`], with what it was parsed under.
1083#[derive(Debug)]
1084struct CachedDocument {
1085    max_depth: u32,
1086    document: Document,
1087}
1088
1089impl DocumentCache {
1090    /// The most documents a cache keeps.
1091    pub const MAX_DOCUMENTS: usize = 64;
1092    /// The most text, in bytes, of the documents a cache keeps.
1093    pub const MAX_BYTES: usize = 64 << 20;
1094
1095    /// An empty cache.
1096    #[must_use]
1097    pub fn new() -> Self {
1098        Self::default()
1099    }
1100
1101    /// The document [`Document::parse_loaded_with_max_depth`] parses from `text`, loaded
1102    /// from `uri`: a copy of the one parsed before from the same text, URI and maximum
1103    /// depth, or parsed now (and kept, room permitting).
1104    ///
1105    /// # Errors
1106    ///
1107    /// Those of [`Document::parse`]; a text that does not parse is not kept.
1108    pub fn parse_loaded(
1109        &self,
1110        text: String,
1111        uri: &str,
1112        max_depth: u32,
1113    ) -> Result<Rc<Document>, DocumentError> {
1114        {
1115            let entries = self
1116                .entries
1117                .lock()
1118                .unwrap_or_else(std::sync::PoisonError::into_inner);
1119            if let Some(entry) = entries.iter().find(|e| {
1120                e.max_depth == max_depth
1121                    && e.document.uri.as_deref() == Some(uri)
1122                    && e.document.source == text
1123            }) {
1124                return Ok(Rc::new(entry.document.copy_with_source(text)));
1125            }
1126        }
1127        let document = Document::parse_loaded_with_max_depth(text, uri, max_depth)?;
1128        let mut entries = self
1129            .entries
1130            .lock()
1131            .unwrap_or_else(std::sync::PoisonError::into_inner);
1132        let bytes: usize = entries.iter().map(|e| e.document.source.len()).sum();
1133        if entries.len() < Self::MAX_DOCUMENTS
1134            && bytes.saturating_add(document.source.len()) <= Self::MAX_BYTES
1135            && !entries.iter().any(|e| {
1136                e.max_depth == max_depth
1137                    && e.document.uri.as_deref() == Some(uri)
1138                    && e.document.source == document.source
1139            })
1140        {
1141            entries.push(CachedDocument {
1142                max_depth,
1143                document: document.copy_with_source(document.source.clone()),
1144            });
1145        }
1146        Ok(document)
1147    }
1148}
1149
1150/// Builds a [`Document`] from events, in document order.
1151///
1152/// Adjacent text is merged into one text node and empty text is dropped, as the XDM
1153/// requires (except at the top of a parentless tree, see [`TreeBuilder::parentless`]). Attributes must come right after their element's start, before its content;
1154/// an attribute whose expanded name is already on the element replaces it.
1155#[derive(Debug)]
1156pub struct TreeBuilder {
1157    records: Vec<Record>,
1158    names: Vec<QName>,
1159    name_ids: HashMap<QName, u32>,
1160    /// The namespace nodes given to elements, by element index.
1161    namespaces: Vec<(u32, Arc<[NamespaceBinding]>)>,
1162    /// Whether the tree has no document node: its one top-level node is its root.
1163    parentless: bool,
1164    /// The length of the source text the text space starts with (see [`Document`]): the
1165    /// texts added are stored from that offset on.
1166    source_len: usize,
1167    text: String,
1168    /// The open nodes, the document node first (none for a parentless tree).
1169    open: Vec<u32>,
1170    /// The last child of each open node, or [`NONE`].
1171    last_child: Vec<u32>,
1172    has_xml_base: bool,
1173    view: TreeView,
1174}
1175
1176impl Default for TreeBuilder {
1177    fn default() -> Self {
1178        Self::new()
1179    }
1180}
1181
1182fn to_u32(value: usize) -> Result<u32, DocumentError> {
1183    u32::try_from(value)
1184        .ok()
1185        .filter(|&v| v != NONE)
1186        .ok_or_else(|| DocumentError::new("document too large"))
1187}
1188
1189/// Where the text of a node comes from.
1190#[derive(Debug, Clone, Copy)]
1191enum NodeText<'s> {
1192    /// A range of the source text: offset and length.
1193    Source(u32, u32),
1194    /// Text to store.
1195    Copy(&'s str),
1196}
1197
1198impl TreeBuilder {
1199    /// A builder holding only the document node.
1200    #[must_use]
1201    pub fn new() -> Self {
1202        Self {
1203            records: vec![Record::new(NodeKind::Document, NONE, NONE, NONE, 0, (0, 0))],
1204            names: Vec::new(),
1205            name_ids: HashMap::new(),
1206            namespaces: Vec::new(),
1207            parentless: false,
1208            source_len: 0,
1209            text: String::new(),
1210            open: vec![0],
1211            last_child: vec![NONE],
1212            has_xml_base: false,
1213            view: TreeView::Tiny,
1214        }
1215    }
1216
1217    /// The tree is the view Saxon has of a DOM document it wraps ([`TreeView::Dom`]).
1218    #[must_use]
1219    pub const fn dom_view(mut self) -> Self {
1220        self.view = TreeView::Dom;
1221        self
1222    }
1223
1224    /// A builder of a tree without document node, whose root is the one node added at
1225    /// the top: a parentless element (with its content), attribute, text node or comment
1226    /// (XDM nodes without parent, as XSLT constructs them in a sequence). Text added at
1227    /// the top makes one text node; anything added after the top-level node is an error.
1228    #[must_use]
1229    pub fn parentless() -> Self {
1230        Self {
1231            records: Vec::new(),
1232            open: Vec::new(),
1233            parentless: true,
1234            ..Self::new()
1235        }
1236    }
1237
1238    /// A builder whose text space starts with a source text of `source_len` bytes, with
1239    /// room for exactly `nodes` nodes (the document node included) and `text` bytes of
1240    /// copied text.
1241    fn with_capacity(nodes: usize, text: usize, source_len: usize) -> Self {
1242        let mut builder = Self::new();
1243        builder.records.reserve_exact(nodes.saturating_sub(1));
1244        builder.text.reserve_exact(text);
1245        builder.source_len = source_len;
1246        builder
1247    }
1248
1249    fn intern(&mut self, name: QName) -> Result<u32, DocumentError> {
1250        if let Some(&id) = self.name_ids.get(&name) {
1251            return Ok(id);
1252        }
1253        let id = self.push_name(name.clone())?;
1254        self.name_ids.insert(name, id);
1255        Ok(id)
1256    }
1257
1258    /// Adds a name to the table, without interning it.
1259    fn push_name(&mut self, name: QName) -> Result<u32, DocumentError> {
1260        let id = to_u32(self.names.len())?;
1261        self.names.push(name);
1262        Ok(id)
1263    }
1264
1265    /// The range of the text space a text occupies: its offset and length.
1266    fn store_text(&mut self, value: NodeText<'_>) -> Result<(u32, u32), DocumentError> {
1267        match value {
1268            NodeText::Source(start, len) => Ok((start, len)),
1269            NodeText::Copy(value) => {
1270                let start = to_u32(self.source_len + self.text.len())?;
1271                let len = to_u32(value.len())?;
1272                to_u32(self.source_len + self.text.len() + value.len())?;
1273                self.text.push_str(value);
1274                Ok((start, len))
1275            }
1276        }
1277    }
1278
1279    /// The innermost open node, or [`NONE`] at the top of a parentless tree.
1280    fn top(&self) -> u32 {
1281        self.open.last().copied().unwrap_or(NONE)
1282    }
1283
1284    /// The number of open nodes that are not elements (the document node).
1285    const fn base(&self) -> usize {
1286        if self.parentless { 0 } else { 1 }
1287    }
1288
1289    /// Appends a child of the innermost open node and returns its index: an element (its
1290    /// text is ignored), or a node with a text.
1291    fn append(
1292        &mut self,
1293        kind: NodeKind,
1294        name: u32,
1295        text: NodeText<'_>,
1296    ) -> Result<u32, DocumentError> {
1297        let index = to_u32(self.records.len())?;
1298        to_u32(self.records.len() + 1)?;
1299        if self.parentless && self.open.is_empty() && !self.records.is_empty() {
1300            return Err(DocumentError::new(
1301                "a second node at the top of a parentless tree",
1302            ));
1303        }
1304        let text = if kind == NodeKind::Element {
1305            (0, 0)
1306        } else {
1307            self.store_text(text)?
1308        };
1309        let parent = self.top();
1310        let last = self.last_child.last_mut().map_or(NONE, |l| {
1311            let previous = *l;
1312            *l = index;
1313            previous
1314        });
1315        self.records
1316            .push(Record::new(kind, name, parent, last, index, text));
1317        Ok(index)
1318    }
1319
1320    /// Opens an element.
1321    ///
1322    /// # Errors
1323    ///
1324    /// A document too large for the arena.
1325    pub fn start_element(&mut self, name: QName) -> Result<(), DocumentError> {
1326        let name = self.intern(name)?;
1327        self.open_element(name)
1328    }
1329
1330    /// Adds a namespace node to the element just opened (before its content).
1331    ///
1332    /// # Errors
1333    ///
1334    /// No element is open, or it already has content.
1335    pub fn add_namespace(&mut self, binding: NamespaceBinding) -> Result<(), DocumentError> {
1336        let element = self.top();
1337        let has_content = self.last_child.last().is_some_and(|&l| l != NONE);
1338        if element == NONE
1339            || self.records[element as usize].kind != NodeKind::Element
1340            || has_content
1341        {
1342            return Err(DocumentError::new(format!(
1343                "namespace {:?} outside an element start",
1344                binding.prefix
1345            )));
1346        }
1347        match self.namespaces.last_mut() {
1348            Some((e, bindings)) if *e == element => {
1349                let mut extended: Vec<NamespaceBinding> = bindings.to_vec();
1350                extended.retain(|b| b.prefix != binding.prefix);
1351                extended.push(binding);
1352                *bindings = extended.into();
1353            }
1354            _ => self.namespaces.push((element, vec![binding].into())),
1355        }
1356        Ok(())
1357    }
1358
1359    /// Opens an element with namespace nodes (besides those it inherits from its
1360    /// ancestors in the tree, see [`Node::namespaces_in_scope`]).
1361    ///
1362    /// # Errors
1363    ///
1364    /// A document too large for the arena.
1365    pub fn start_element_with_namespaces(
1366        &mut self,
1367        name: QName,
1368        namespaces: Arc<[NamespaceBinding]>,
1369    ) -> Result<(), DocumentError> {
1370        self.start_element(name)?;
1371        if !namespaces.is_empty() {
1372            let element = self.top();
1373            self.namespaces.push((element, namespaces));
1374        }
1375        Ok(())
1376    }
1377
1378    fn open_element(&mut self, name: u32) -> Result<(), DocumentError> {
1379        let index = self.append(NodeKind::Element, name, NodeText::Copy(""))?;
1380        self.open.push(index);
1381        self.last_child.push(NONE);
1382        Ok(())
1383    }
1384
1385    /// Adds an attribute to the element just opened.
1386    ///
1387    /// # Errors
1388    ///
1389    /// No element is open, or the element already has content.
1390    pub fn attribute(&mut self, name: QName, value: &str) -> Result<(), DocumentError> {
1391        if self.parentless && self.records.is_empty() {
1392            // A parentless attribute: the root of its tree.
1393            let xml_base = is_xml_base(name.namespace.as_deref(), &name.local);
1394            let id = self.intern(name)?;
1395            let text = self.store_text(NodeText::Copy(value))?;
1396            self.records
1397                .push(Record::new(NodeKind::Attribute, id, NONE, NONE, 0, text));
1398            self.has_xml_base |= xml_base;
1399            return Ok(());
1400        }
1401        let element = self.top();
1402        let has_content = self.last_child.last().is_some_and(|&l| l != NONE);
1403        if element == NONE
1404            || self.records[element as usize].kind != NodeKind::Element
1405            || has_content
1406        {
1407            return Err(DocumentError::new(format!(
1408                "attribute {name} outside an element start"
1409            )));
1410        }
1411        let first = element as usize + 1;
1412        let existing = (first..self.records.len()).find(|&i| {
1413            let id = self.records[i].name;
1414            self.names[id as usize].same_expanded_name(&name)
1415        });
1416        let xml_base = is_xml_base(name.namespace.as_deref(), &name.local);
1417        let id = self.intern(name)?;
1418        if let Some(i) = existing {
1419            let (text_start, text_len) = self.store_text(NodeText::Copy(value))?;
1420            let record = &mut self.records[i];
1421            record.name = id;
1422            record.text_start = text_start;
1423            record.text_len = text_len;
1424            self.has_xml_base |= xml_base;
1425            return Ok(());
1426        }
1427        self.push_attribute(id, xml_base, NodeText::Copy(value))
1428    }
1429
1430    /// Adds an attribute, known not to be on the element yet, to the element just opened.
1431    fn push_attribute(
1432        &mut self,
1433        name: u32,
1434        xml_base: bool,
1435        value: NodeText<'_>,
1436    ) -> Result<(), DocumentError> {
1437        let element = self.top();
1438        let index = to_u32(self.records.len())?;
1439        to_u32(self.records.len() + 1)?;
1440        let previous = if index == element + 1 {
1441            NONE
1442        } else {
1443            index - 1
1444        };
1445        let text = self.store_text(value)?;
1446        self.records.push(Record::new(
1447            NodeKind::Attribute,
1448            name,
1449            element,
1450            previous,
1451            index,
1452            text,
1453        ));
1454        self.records[element as usize].first_child = index + 1;
1455        self.has_xml_base |= xml_base;
1456        Ok(())
1457    }
1458
1459    /// Adds text, merged with text added just before.
1460    ///
1461    /// # Errors
1462    ///
1463    /// A document too large for the arena.
1464    pub fn text(&mut self, value: &str) -> Result<(), DocumentError> {
1465        if value.is_empty() {
1466            // At the top of a parentless tree, a zero-length text node (XSLT constructs
1467            // them in sequences); dropped anywhere else.
1468            if self.parentless && self.records.is_empty() {
1469                return self
1470                    .append(NodeKind::Text, NONE, NodeText::Copy(""))
1471                    .map(drop);
1472            }
1473            return Ok(());
1474        }
1475        let last = self.last_child.last().copied().unwrap_or(NONE);
1476        // Text merges with the text node just before when that node's text is the end of
1477        // the copied texts (always so for a built tree, whose texts are all copied).
1478        let mergeable = last != NONE
1479            && last as usize + 1 == self.records.len()
1480            && self.records[last as usize].kind == NodeKind::Text
1481            && {
1482                let r = &self.records[last as usize];
1483                r.text_start as usize + r.text_len as usize == self.source_len + self.text.len()
1484                    && r.text_start as usize >= self.source_len
1485            };
1486        if mergeable {
1487            self.store_text(NodeText::Copy(value))?;
1488            let record = &mut self.records[last as usize];
1489            record.text_len = to_u32(record.text_len as usize + value.len())?;
1490            return Ok(());
1491        }
1492        self.append(NodeKind::Text, NONE, NodeText::Copy(value))
1493            .map(drop)
1494    }
1495
1496    /// Adds a comment.
1497    ///
1498    /// # Errors
1499    ///
1500    /// A document too large for the arena.
1501    pub fn comment(&mut self, value: &str) -> Result<(), DocumentError> {
1502        self.append(NodeKind::Comment, NONE, NodeText::Copy(value))
1503            .map(drop)
1504    }
1505
1506    /// Adds a processing instruction.
1507    ///
1508    /// # Errors
1509    ///
1510    /// A document too large for the arena.
1511    pub fn processing_instruction(
1512        &mut self,
1513        target: &str,
1514        value: &str,
1515    ) -> Result<(), DocumentError> {
1516        let name = self.intern(QName::local(target))?;
1517        self.append(NodeKind::ProcessingInstruction, name, NodeText::Copy(value))
1518            .map(drop)
1519    }
1520
1521    /// Closes the innermost open element.
1522    ///
1523    /// # Errors
1524    ///
1525    /// No element is open.
1526    pub fn end_element(&mut self) -> Result<(), DocumentError> {
1527        if self.open.len() <= self.base() {
1528            return Err(DocumentError::new("end of element without a start"));
1529        }
1530        let element = self.top();
1531        self.open.pop();
1532        self.last_child.pop();
1533        let end = to_u32(self.records.len())?;
1534        self.records[element as usize].end = end;
1535        Ok(())
1536    }
1537
1538    /// The finished document, with its document URI and the base URI of its nodes.
1539    ///
1540    /// # Errors
1541    ///
1542    /// An element is still open.
1543    pub fn finish(
1544        self,
1545        document_uri: Option<String>,
1546        base_uri: Option<String>,
1547    ) -> Result<Rc<Document>, DocumentError> {
1548        self.finish_with_source(String::new(), document_uri, base_uri)
1549    }
1550
1551    /// The finished document, whose text space starts with `source` (as long as the
1552    /// builder was told).
1553    fn finish_with_source(
1554        mut self,
1555        source: String,
1556        document_uri: Option<String>,
1557        base_uri: Option<String>,
1558    ) -> Result<Rc<Document>, DocumentError> {
1559        if self.open.len() != self.base() {
1560            return Err(DocumentError::new("unclosed element"));
1561        }
1562        if source.len() != self.source_len {
1563            return Err(DocumentError::new("source text of another length"));
1564        }
1565        if self.parentless {
1566            if self.records.is_empty() {
1567                return Err(DocumentError::new("a parentless tree without a node"));
1568            }
1569        } else {
1570            self.records[0].end = to_u32(self.records.len())?;
1571        }
1572        // No spare capacity is kept: a parsed tree is sized exactly, a built one is
1573        // trimmed once.
1574        self.records.shrink_to_fit();
1575        self.names.shrink_to_fit();
1576        self.text.shrink_to_fit();
1577        Ok(Rc::new(Document {
1578            serial: NEXT_SERIAL.fetch_add(1, AtomicOrdering::Relaxed),
1579            uri: document_uri,
1580            base_uri,
1581            has_xml_base: self.has_xml_base,
1582            records: self.records,
1583            names: self.names,
1584            namespaces: self.namespaces,
1585            source,
1586            text: self.text,
1587            elements: OnceCell::new(),
1588            searches: Cell::new(0),
1589            view: self.view,
1590            ids: OnceCell::new(),
1591        }))
1592    }
1593}
1594
1595/// Saxon's `Navigator.alphaKey`: a number as a string that sorts as the number does, a
1596/// letter for its number of digits first.
1597fn alpha_key(value: u32) -> String {
1598    if value < 1 {
1599        return "a".to_owned();
1600    }
1601    let digits = value.to_string();
1602    let letter = char::from(b'a' + u8::try_from(digits.len()).unwrap_or(10));
1603    format!("{letter}{digits}")
1604}
1605
1606fn is_xml_base(namespace: Option<&str>, local: &str) -> bool {
1607    local == "base" && namespace == Some(XML_NAMESPACE)
1608}
1609
1610/// The offset of `part` in `input`, if `part` is a slice of it.
1611fn offset_in(input: &str, part: &str) -> Option<usize> {
1612    let start = part.as_ptr().addr().checked_sub(input.as_ptr().addr())?;
1613    (start.checked_add(part.len())? <= input.len()).then_some(start)
1614}
1615
1616/// The error of a document the reader refuses.
1617fn xml_error(e: &einvoice_xml::Error) -> DocumentError {
1618    DocumentError::new(format!("XML: {e}"))
1619}
1620
1621/// The namespace names of a parsed document, numbered in order of appearance, so that
1622/// a name is looked up by its prefix, local part and namespace number: the namespace
1623/// names the reader gives only live until its next event.
1624struct Namespaces<'a> {
1625    input: &'a str,
1626    ids: HashMap<Box<str>, u32>,
1627    /// The last namespace name looked up, when it is a slice of the input (whose
1628    /// content its address and length then identify): its offset, length and number.
1629    last: Option<(usize, usize, u32)>,
1630}
1631
1632impl<'a> Namespaces<'a> {
1633    fn new(input: &'a str) -> Self {
1634        Self {
1635            input,
1636            ids: HashMap::new(),
1637            last: None,
1638        }
1639    }
1640
1641    /// The number of a namespace name, [`NONE`] for no namespace.
1642    fn id(&mut self, namespace: Option<&str>) -> Result<u32, DocumentError> {
1643        let Some(namespace) = namespace else {
1644            return Ok(NONE);
1645        };
1646        let at = offset_in(self.input, namespace);
1647        if let (Some(at), Some((last, len, id))) = (at, self.last)
1648            && at == last
1649            && namespace.len() == len
1650        {
1651            return Ok(id);
1652        }
1653        let id = if let Some(&id) = self.ids.get(namespace) {
1654            id
1655        } else {
1656            let id = to_u32(self.ids.len())?;
1657            self.ids.insert(namespace.into(), id);
1658            id
1659        };
1660        if let Some(at) = at {
1661            self.last = Some((at, namespace.len(), id));
1662        }
1663        Ok(id)
1664    }
1665}
1666
1667/// A name as the reader gives it: prefix as written (empty for none), local part (both
1668/// slices of the text) and the number of its namespace name ([`Namespaces::id`]).
1669type NameKey<'a> = (&'a str, &'a str, u32);
1670
1671/// The names of a parsed document in the builder's table, by [`NameKey`].
1672struct Names<'a> {
1673    namespaces: Namespaces<'a>,
1674    ids: HashMap<NameKey<'a>, u32>,
1675}
1676
1677impl<'a> Names<'a> {
1678    fn new(input: &'a str) -> Self {
1679        Self {
1680            namespaces: Namespaces::new(input),
1681            ids: HashMap::new(),
1682        }
1683    }
1684
1685    /// The identity of a name in the builder's table, added on first sight.
1686    fn id(
1687        &mut self,
1688        builder: &mut TreeBuilder,
1689        name: einvoice_xml::Name<'_, 'a>,
1690    ) -> Result<u32, DocumentError> {
1691        let key = (name.prefix, name.local, self.namespaces.id(name.namespace)?);
1692        if let Some(&id) = self.ids.get(&key) {
1693            return Ok(id);
1694        }
1695        let id = builder.push_name(QName {
1696            prefix: (!name.prefix.is_empty()).then(|| name.prefix.to_owned()),
1697            namespace: name.namespace.map(str::to_owned),
1698            local: name.local.to_owned(),
1699        })?;
1700        self.ids.insert(key, id);
1701        Ok(id)
1702    }
1703}
1704
1705/// What a pass over the events of a document does with its nodes, in document order.
1706/// Adjacent text events make one text node, given to [`Pass::text`] once complete and
1707/// only when not empty; text outside the document element is not part of the data
1708/// model and is not given.
1709trait Pass<'a> {
1710    fn start(&mut self, start: einvoice_xml::StartElement<'_, 'a>) -> Result<(), DocumentError>;
1711    fn end(&mut self) -> Result<(), DocumentError>;
1712    fn text(&mut self, text: &str) -> Result<(), DocumentError>;
1713    fn comment(&mut self, value: &str) -> Result<(), DocumentError>;
1714    fn processing_instruction(
1715        &mut self,
1716        pi: &einvoice_xml::ProcessingInstruction<'a>,
1717    ) -> Result<(), DocumentError>;
1718}
1719
1720/// Reads `input` to the end, giving its nodes to `pass`. A well-formedness error comes
1721/// first, wherever it is in the text; then an element nested deeper than `max_depth`
1722/// (the first in document order), the elements after it not being given to `pass`.
1723fn read<'a>(input: &'a str, max_depth: u32, pass: &mut impl Pass<'a>) -> Result<(), DocumentError> {
1724    let mut reader = einvoice_xml::Reader::new(input);
1725    let mut depth = 0u32;
1726    // The text node being read: adjacent text events (character data and CDATA
1727    // sections) make one.
1728    let mut text: Option<Cow<'a, str>> = None;
1729    let mut too_deep: Option<LimitExceeded> = None;
1730    while let Some(event) = reader.next_event().map_err(|e| xml_error(&e))? {
1731        if let einvoice_xml::Event::Text(t) = event {
1732            if depth > 0 && too_deep.is_none() {
1733                match &mut text {
1734                    None => text = Some(t.value),
1735                    Some(joined) => joined.to_mut().push_str(&t.value),
1736                }
1737            }
1738            continue;
1739        }
1740        if let Some(joined) = text.take()
1741            && !joined.is_empty()
1742        {
1743            pass.text(&joined)?;
1744        }
1745        match event {
1746            einvoice_xml::Event::Start(start) => {
1747                depth = depth.saturating_add(1);
1748                if depth > max_depth && too_deep.is_none() {
1749                    // The rest is only checked for well-formedness.
1750                    let at = einvoice_xml::TextPos::at(input, start.range().start);
1751                    too_deep = Some(LimitExceeded::Depth {
1752                        max: max_depth,
1753                        line: at.row,
1754                        column: at.col,
1755                    });
1756                }
1757                if too_deep.is_none() {
1758                    pass.start(start)?;
1759                }
1760            }
1761            einvoice_xml::Event::End(_) => {
1762                depth = depth.saturating_sub(1);
1763                if too_deep.is_none() {
1764                    pass.end()?;
1765                }
1766            }
1767            einvoice_xml::Event::Comment(comment) if too_deep.is_none() => {
1768                pass.comment(&comment.value)?;
1769            }
1770            einvoice_xml::Event::ProcessingInstruction(pi) if too_deep.is_none() => {
1771                pass.processing_instruction(&pi)?;
1772            }
1773            _ => {}
1774        }
1775    }
1776    match too_deep {
1777        Some(limit) => Err(DocumentError::limit_exceeded(limit)),
1778        None => Ok(()),
1779    }
1780}
1781
1782/// The first pass: the number of nodes of the tree (the document node included) and
1783/// the bytes of text to copy into it: all of them, or with `keep_source` those that
1784/// are not slices of the text.
1785struct Sizes<'a> {
1786    input: &'a str,
1787    keep_source: bool,
1788    nodes: usize,
1789    text_bytes: usize,
1790}
1791
1792impl Sizes<'_> {
1793    fn add(&mut self, text: &str) {
1794        self.nodes += 1;
1795        if !(self.keep_source && offset_in(self.input, text).is_some()) {
1796            self.text_bytes += text.len();
1797        }
1798    }
1799}
1800
1801impl<'a> Pass<'a> for Sizes<'a> {
1802    fn start(&mut self, start: einvoice_xml::StartElement<'_, 'a>) -> Result<(), DocumentError> {
1803        self.nodes += 1;
1804        for attribute in start.attributes() {
1805            self.add(attribute.value);
1806        }
1807        Ok(())
1808    }
1809
1810    fn end(&mut self) -> Result<(), DocumentError> {
1811        Ok(())
1812    }
1813
1814    fn text(&mut self, text: &str) -> Result<(), DocumentError> {
1815        self.add(text);
1816        Ok(())
1817    }
1818
1819    fn comment(&mut self, value: &str) -> Result<(), DocumentError> {
1820        self.add(value);
1821        Ok(())
1822    }
1823
1824    fn processing_instruction(
1825        &mut self,
1826        pi: &einvoice_xml::ProcessingInstruction<'a>,
1827    ) -> Result<(), DocumentError> {
1828        self.add(pi.value.as_deref().unwrap_or(""));
1829        Ok(())
1830    }
1831}
1832
1833/// The second pass: the tree, in a builder sized by the first.
1834struct Fill<'a> {
1835    input: &'a str,
1836    keep_source: bool,
1837    builder: TreeBuilder,
1838    names: Names<'a>,
1839}
1840
1841impl Fill<'_> {
1842    /// Where a text is stored: as a range of the input if `keep_source` and it is a
1843    /// slice of it, else copied.
1844    fn node_text<'s>(&self, text: &'s str) -> Result<NodeText<'s>, DocumentError> {
1845        Ok(
1846            match self
1847                .keep_source
1848                .then(|| offset_in(self.input, text))
1849                .flatten()
1850            {
1851                Some(start) => NodeText::Source(to_u32(start)?, to_u32(text.len())?),
1852                None => NodeText::Copy(text),
1853            },
1854        )
1855    }
1856}
1857
1858impl<'a> Pass<'a> for Fill<'a> {
1859    fn start(&mut self, start: einvoice_xml::StartElement<'_, 'a>) -> Result<(), DocumentError> {
1860        let id = self.names.id(&mut self.builder, start.name())?;
1861        self.builder.open_element(id)?;
1862        let declarations = start.namespace_declarations();
1863        if declarations.len() > 0 {
1864            let bindings: Arc<[NamespaceBinding]> = declarations
1865                .map(|(prefix, uri)| NamespaceBinding {
1866                    prefix: (!prefix.is_empty()).then(|| prefix.to_owned()),
1867                    uri: uri.to_owned(),
1868                })
1869                .collect();
1870            let element = self.builder.top();
1871            self.builder.namespaces.push((element, bindings));
1872        }
1873        // The reader refuses duplicate attributes: each one is new.
1874        for attribute in start.attributes() {
1875            let id = self.names.id(&mut self.builder, attribute.name)?;
1876            let text = self.node_text(attribute.value)?;
1877            self.builder.push_attribute(
1878                id,
1879                is_xml_base(attribute.name.namespace, attribute.name.local),
1880                text,
1881            )?;
1882        }
1883        Ok(())
1884    }
1885
1886    fn end(&mut self) -> Result<(), DocumentError> {
1887        self.builder.end_element()
1888    }
1889
1890    fn text(&mut self, text: &str) -> Result<(), DocumentError> {
1891        let text = self.node_text(text)?;
1892        self.builder.append(NodeKind::Text, NONE, text).map(drop)
1893    }
1894
1895    fn comment(&mut self, value: &str) -> Result<(), DocumentError> {
1896        let text = self.node_text(value)?;
1897        self.builder.append(NodeKind::Comment, NONE, text).map(drop)
1898    }
1899
1900    fn processing_instruction(
1901        &mut self,
1902        pi: &einvoice_xml::ProcessingInstruction<'a>,
1903    ) -> Result<(), DocumentError> {
1904        let target = einvoice_xml::Name {
1905            prefix: "",
1906            local: pi.target,
1907            namespace: None,
1908        };
1909        let id = self.names.id(&mut self.builder, target)?;
1910        let text = self.node_text(pi.value.as_deref().unwrap_or(""))?;
1911        self.builder
1912            .append(NodeKind::ProcessingInstruction, id, text)
1913            .map(drop)
1914    }
1915}
1916
1917/// Builds the tree of a document, in two passes of the streaming reader over its text:
1918/// the first checks it (well-formedness, then depth) and counts the nodes and the bytes
1919/// of text to copy, so that the arena is allocated once at its exact size; the second
1920/// fills it. With `keep_source`, every text that is a slice of `input` is stored as a
1921/// range of it instead of being copied (the document then keeps `input`). An element
1922/// nested deeper than `max_depth` is refused by the first pass, before the arena is
1923/// allocated.
1924fn build_parsed(
1925    input: &str,
1926    keep_source: bool,
1927    max_depth: u32,
1928) -> Result<TreeBuilder, DocumentError> {
1929    let mut sizes = Sizes {
1930        input,
1931        keep_source,
1932        nodes: 1,
1933        text_bytes: 0,
1934    };
1935    read(input, max_depth, &mut sizes)?;
1936    let mut fill = Fill {
1937        input,
1938        keep_source,
1939        builder: TreeBuilder::with_capacity(
1940            sizes.nodes,
1941            sizes.text_bytes,
1942            if keep_source { input.len() } else { 0 },
1943        ),
1944        names: Names::new(input),
1945    };
1946    read(input, max_depth, &mut fill)?;
1947    Ok(fill.builder)
1948}
1949
1950/// The `file:` URI that Saxon-HE gives a document read from a file: Java's
1951/// `File.toURI().toString()` of the absolute path. ASCII characters outside the URI path
1952/// syntax, Unicode space separators and control characters are percent-encoded (UTF-8,
1953/// upper-case hex); other non-ASCII characters are kept. On Windows, `C:\a\b` becomes
1954/// `file:/C:/a/b`.
1955///
1956/// Returns `None` for a relative path or one that is not valid Unicode.
1957#[must_use]
1958pub fn file_uri(path: &Path) -> Option<String> {
1959    if !path.is_absolute() {
1960        return None;
1961    }
1962    let text = path.to_str()?.replace('\\', "/");
1963    let mut uri = String::from("file:");
1964    if !text.starts_with('/') {
1965        uri.push('/');
1966    }
1967    for c in text.chars() {
1968        let keep = if c.is_ascii() {
1969            c.is_ascii_alphanumeric() || "-_.!~*'():@&=+$,;/".contains(c)
1970        } else {
1971            // java.lang.Character.isSpaceChar (Zs, Zl, Zp) and isISOControl.
1972            !(matches!(
1973                c,
1974                '\u{A0}' | '\u{1680}' | '\u{2000}'
1975                    ..='\u{200A}' | '\u{2028}' | '\u{2029}' | '\u{202F}' | '\u{205F}' | '\u{3000}'
1976            ) || c.is_control())
1977        };
1978        if keep {
1979            uri.push(c);
1980        } else {
1981            let mut buffer = [0; 4];
1982            for byte in c.encode_utf8(&mut buffer).bytes() {
1983                let _ = write!(uri, "%{byte:02X}");
1984            }
1985        }
1986    }
1987    Some(uri)
1988}
1989
1990#[cfg(test)]
1991mod tests {
1992    use super::*;
1993
1994    fn parse(xml: &str) -> Rc<Document> {
1995        Document::parse(xml, Some("file:/t.xml")).unwrap()
1996    }
1997
1998    fn describe(node: &Node) -> String {
1999        match node.kind() {
2000            NodeKind::Document => "/".to_owned(),
2001            NodeKind::Element => node.name().unwrap().to_string(),
2002            NodeKind::Attribute => format!("@{}", node.name().unwrap()),
2003            NodeKind::Text => format!("{:?}", node.string_value()),
2004            NodeKind::Comment => format!("<!--{}-->", node.string_value()),
2005            NodeKind::ProcessingInstruction => format!("<?{}?>", node.name().unwrap()),
2006        }
2007    }
2008
2009    fn walk(node: &Node, axis: NodeAxis) -> Vec<String> {
2010        node.axis(axis).map(|n| describe(&n)).collect()
2011    }
2012
2013    fn find(tree: &Rc<Document>, local: &str) -> Node {
2014        tree.root()
2015            .axis(NodeAxis::Descendant)
2016            .find(|n| n.name().is_some_and(|name| name.local == local))
2017            .unwrap()
2018    }
2019
2020    const XML: &str = "<?xml version='1.0'?><!--c0--><r xmlns:p='urn:p' a='1' p:b='2'> \
2021        <x>1<y q='3'>2</y>3</x><p:z/><!--c1--><?pi data?><w><v/></w></r>";
2022
2023    const NONE: [&str; 0] = [];
2024
2025    #[test]
2026    fn document_order_and_axes() {
2027        let tree = parse(XML);
2028        let root = tree.root();
2029        assert_eq!(walk(&root, NodeAxis::Child), ["<!--c0-->", "r"]);
2030        let top = find(&tree, "r");
2031        assert_eq!(walk(&top, NodeAxis::Attribute), ["@a", "@p:b"]);
2032        assert_eq!(
2033            walk(&top, NodeAxis::Child),
2034            ["\" \"", "x", "p:z", "<!--c1-->", "<?pi?>", "w"]
2035        );
2036        assert_eq!(
2037            walk(&top, NodeAxis::Descendant),
2038            [
2039                "\" \"",
2040                "x",
2041                "\"1\"",
2042                "y",
2043                "\"2\"",
2044                "\"3\"",
2045                "p:z",
2046                "<!--c1-->",
2047                "<?pi?>",
2048                "w",
2049                "v"
2050            ]
2051        );
2052        let y = find(&tree, "y");
2053        assert_eq!(walk(&y, NodeAxis::Ancestor), ["x", "r", "/"]);
2054        assert_eq!(walk(&y, NodeAxis::AncestorOrSelf), ["y", "x", "r", "/"]);
2055        assert_eq!(walk(&y, NodeAxis::PrecedingSibling), ["\"1\""]);
2056        assert_eq!(walk(&y, NodeAxis::FollowingSibling), ["\"3\""]);
2057        assert_eq!(
2058            walk(&y, NodeAxis::Preceding),
2059            ["\"1\"", "\" \"", "<!--c0-->"]
2060        );
2061        let v = find(&tree, "v");
2062        assert_eq!(
2063            walk(&v, NodeAxis::Preceding),
2064            [
2065                "<?pi?>",
2066                "<!--c1-->",
2067                "p:z",
2068                "\"3\"",
2069                "\"2\"",
2070                "y",
2071                "\"1\"",
2072                "x",
2073                "\" \"",
2074                "<!--c0-->"
2075            ]
2076        );
2077        let q = y.attributes().next().unwrap();
2078        assert_eq!(walk(&q, NodeAxis::Parent), ["y"]);
2079        assert_eq!(
2080            walk(&q, NodeAxis::Preceding),
2081            ["\"1\"", "\" \"", "<!--c0-->"]
2082        );
2083        assert_eq!(walk(&q, NodeAxis::FollowingSibling), NONE);
2084        assert_eq!(walk(&q, NodeAxis::PrecedingSibling), NONE);
2085        assert_eq!(walk(&q, NodeAxis::DescendantOrSelf), ["@q"]);
2086        assert_eq!(walk(&q, NodeAxis::Child), NONE);
2087        let all: Vec<Node> = root.axis(NodeAxis::DescendantOrSelf).collect();
2088        assert!(
2089            all.windows(2)
2090                .all(|w| w[0].cmp_document_order(&w[1]) == Ordering::Less)
2091        );
2092    }
2093
2094    #[test]
2095    fn values_names_and_prefixes() {
2096        let tree = parse(XML);
2097        let top = find(&tree, "r");
2098        assert_eq!(top.string_value(), " 123");
2099        assert_eq!(find(&tree, "x").string_value(), "123");
2100        assert_eq!(find(&tree, "y").string_value(), "2");
2101        assert_eq!(find(&tree, "w").string_value(), "");
2102        let z = find(&tree, "z");
2103        assert_eq!(z.name().unwrap().to_string(), "p:z");
2104        assert_eq!(z.name().unwrap().namespace.as_deref(), Some("urn:p"));
2105        let prefixed = top.attributes().nth(1).unwrap();
2106        assert_eq!(prefixed.name().unwrap().prefix.as_deref(), Some("p"));
2107        assert!(matches!(prefixed.typed_value(), AtomicValue::UntypedAtomic(s) if s == "2"));
2108        let comment = tree.root().children().next().unwrap();
2109        assert!(matches!(comment.typed_value(), AtomicValue::String(s) if s == "c0"));
2110        assert_eq!(tree.document_uri(), None);
2111        assert_eq!(tree.base_uri(), Some("file:/t.xml"));
2112        let loaded = Document::parse_loaded("<a/>", "file:/t.xml").unwrap();
2113        assert_eq!(loaded.document_uri(), Some("file:/t.xml"));
2114        assert_eq!(loaded.base_uri(), Some("file:/t.xml"));
2115        assert_eq!(z.root(), tree.root());
2116        assert_ne!(z, top);
2117    }
2118
2119    #[test]
2120    fn undeclared_default_namespace_is_no_namespace() {
2121        let tree = parse("<r xmlns='urn:d'><n xmlns=''><m/></n></r>");
2122        assert_eq!(
2123            find(&tree, "r").name().unwrap().namespace.as_deref(),
2124            Some("urn:d")
2125        );
2126        assert_eq!(find(&tree, "n").name().unwrap().namespace, None);
2127        assert_eq!(find(&tree, "m").name().unwrap().namespace, None);
2128    }
2129
2130    #[test]
2131    fn same_namespace_two_prefixes() {
2132        let tree = parse("<a:r xmlns:a='urn:x' xmlns:b='urn:x'><b:c a:d='1'/></a:r>");
2133        let inner = find(&tree, "c");
2134        assert_eq!(inner.name().unwrap().to_string(), "b:c");
2135        assert_eq!(find(&tree, "r").name().unwrap().to_string(), "a:r");
2136        let attribute = inner.attributes().next().unwrap();
2137        assert_eq!(attribute.name().unwrap().to_string(), "a:d");
2138    }
2139
2140    #[test]
2141    fn builder_merges_text_and_replaces_attributes() {
2142        let mut builder = TreeBuilder::new();
2143        builder.start_element(QName::local("e")).unwrap();
2144        builder.attribute(QName::local("a"), "1").unwrap();
2145        builder.attribute(QName::local("a"), "2").unwrap();
2146        builder.text("x").unwrap();
2147        builder.text("").unwrap();
2148        builder.text("y").unwrap();
2149        assert!(builder.attribute(QName::local("late"), "1").is_err());
2150        builder.end_element().unwrap();
2151        assert!(builder.end_element().is_err());
2152        let tree = builder.finish(None, None).unwrap();
2153        let element = tree.root().children().next().unwrap();
2154        let attributes: Vec<_> = element
2155            .attributes()
2156            .map(|a| a.string_value().into_owned())
2157            .collect();
2158        assert_eq!(attributes, ["2"]);
2159        let texts: Vec<_> = element
2160            .children()
2161            .map(|t| t.string_value().into_owned())
2162            .collect();
2163        assert_eq!(texts, ["xy"]);
2164    }
2165
2166    #[test]
2167    fn whitespace_text_kept_and_dtd_refused() {
2168        let tree = parse("<r>\n  <a/>\n</r>\n");
2169        let top = tree.root().children().next().unwrap();
2170        assert_eq!(top.children().count(), 3);
2171        assert!(Document::parse("<!DOCTYPE r [<!ENTITY e 'x'>]><r>&e;</r>", None).is_err());
2172        assert!(Document::parse("<r><a></r>", None).is_err());
2173    }
2174
2175    #[test]
2176    fn adjacent_text_is_one_node() {
2177        let text = "<r>a<![CDATA[<b>]]>c&amp;d<!--x-->e\r\nf<s/></r>";
2178        for tree in [parse(text), Document::parse(text.to_owned(), None).unwrap()] {
2179            let top = tree.root().children().next().unwrap();
2180            let children: Vec<_> = top
2181                .children()
2182                .map(|t| (t.kind(), t.string_value().into_owned()))
2183                .collect();
2184            assert_eq!(
2185                children,
2186                [
2187                    (NodeKind::Text, "a<b>c&d".to_owned()),
2188                    (NodeKind::Comment, "x".to_owned()),
2189                    (NodeKind::Text, "e\nf".to_owned()),
2190                    (NodeKind::Element, String::new()),
2191                ]
2192            );
2193        }
2194        // Line ends are normalised in comments and processing instructions too (XML 1.0,
2195        // section 2.11).
2196        let tree = parse("<r><!--a\r\nb\rc--><?p a\r\nb?></r>");
2197        let values: Vec<_> = tree
2198            .root()
2199            .children()
2200            .next()
2201            .unwrap()
2202            .children()
2203            .map(|n| n.string_value().into_owned())
2204            .collect();
2205        assert_eq!(values, ["a\nb\nc", "a\nb"]);
2206        // A carriage return next to a reference is a line end like any other.
2207        assert_eq!(parse("<r>x\r&amp;y</r>").root().string_value(), "x\n&y");
2208    }
2209
2210    #[test]
2211    fn errors_are_those_of_the_reader() {
2212        let error = Document::parse("<r>\n<a></r>", None).unwrap_err();
2213        assert_eq!(error.message(), "XML: expected 'a' tag, not 'r' at 2:4");
2214        assert_eq!(error.limit(), None);
2215        let error = Document::parse("<!DOCTYPE r><r/>", None).unwrap_err();
2216        assert_eq!(error.message(), "XML: XML with DTD detected");
2217    }
2218
2219    #[test]
2220    fn records_are_compact() {
2221        assert_eq!(std::mem::size_of::<Record>(), 32);
2222    }
2223
2224    /// Kind, name, string value and parent of every node, in document order.
2225    fn dump(tree: &Rc<Document>) -> Vec<String> {
2226        (0..tree.node_count())
2227            .map(|i| {
2228                let node = Node::new(Rc::clone(tree), u32::try_from(i).unwrap());
2229                let name = node.name().map(|n| {
2230                    format!(
2231                        "{}{{{}}}{}",
2232                        n,
2233                        n.namespace.as_deref().unwrap_or(""),
2234                        n.local
2235                    )
2236                });
2237                format!(
2238                    "{:?} {name:?} {:?} {:?}",
2239                    node.kind(),
2240                    node.string_value(),
2241                    node.parent().map(|p| p.index())
2242                )
2243            })
2244            .collect()
2245    }
2246
2247    /// Texts written verbatim in an owned source are ranges of it; the others (character
2248    /// and entity references, line ends, attribute whitespace, CDATA sections merged with
2249    /// text) are copied. The tree is the same as from the borrowed text, which is copied
2250    /// whole, and its arenas are sized exactly.
2251    #[test]
2252    fn owned_source_is_referred_to() {
2253        let xml = "<?xml version='1.0'?><!--top--><?pi top data?>\
2254            <p:r xmlns:p='urn:p' xmlns='urn:d' a='plain' b='x&amp;y' c='t\tu'>\
2255            verbatim<e p:f='1'>a&#65;b</e>line\r\nend<![CDATA[<&>]]>more<!--c-->\
2256            <?pi in?><e/>tail</p:r>";
2257        let borrowed = Document::parse(xml, None).unwrap();
2258        let owned = Document::parse(xml.to_owned(), None).unwrap();
2259        assert_eq!(dump(&borrowed), dump(&owned));
2260        assert_eq!(borrowed.source, "");
2261        assert_eq!(owned.source, xml);
2262        // Copied: "x&y", "t u", "aAb", "line\nend<&>more"; everything else is a range.
2263        assert_eq!(owned.text, "x&yt uaAbline\nend<&>more");
2264        let copied_whole: usize = (0..borrowed.node_count())
2265            .map(|i| {
2266                let i = u32::try_from(i).unwrap();
2267                match borrowed.kind(i) {
2268                    NodeKind::Element | NodeKind::Document => 0,
2269                    _ => borrowed.own_text(i).len(),
2270                }
2271            })
2272            .sum();
2273        assert_eq!(borrowed.text.len(), copied_whole);
2274        for tree in [&borrowed, &owned] {
2275            assert_eq!(tree.records.capacity(), tree.records.len());
2276            assert_eq!(tree.text.capacity(), tree.text.len());
2277            assert_eq!(tree.names.capacity(), tree.names.len());
2278        }
2279        let r = find(&owned, "r");
2280        let values: Vec<_> = r
2281            .attributes()
2282            .map(|a| a.string_value().into_owned())
2283            .collect();
2284        assert_eq!(values, ["plain", "x&y", "t u"]);
2285        assert_eq!(r.string_value(), "verbatimaAbline\nend<&>moretail");
2286        assert_eq!(r.name().unwrap().to_string(), "p:r");
2287        let e = find(&owned, "e");
2288        assert_eq!(e.name().unwrap().namespace.as_deref(), Some("urn:d"));
2289        let f = e.attributes().next().unwrap();
2290        assert_eq!(f.name().unwrap().to_string(), "p:f");
2291        assert_eq!(f.name().unwrap().namespace.as_deref(), Some("urn:p"));
2292        // Names are interned: the two `e` elements share one entry.
2293        assert_eq!(owned.names.iter().filter(|n| n.local == "e").count(), 1);
2294    }
2295
2296    #[test]
2297    fn built_trees_merge_text_after_a_parsed_shape() {
2298        // A built tree has no source: all its texts are copied, and adjacent text merges
2299        // even after other copied texts.
2300        let mut builder = TreeBuilder::new();
2301        builder.start_element(QName::local("e")).unwrap();
2302        builder.attribute(QName::local("a"), "v").unwrap();
2303        builder.comment("c").unwrap();
2304        builder.text("x").unwrap();
2305        builder.text("y").unwrap();
2306        builder.processing_instruction("t", "d").unwrap();
2307        builder.text("z").unwrap();
2308        builder.end_element().unwrap();
2309        let tree = builder.finish(None, None).unwrap();
2310        let e = tree.root().children().next().unwrap();
2311        let children: Vec<_> = e
2312            .children()
2313            .map(|c| (c.kind(), c.string_value().into_owned()))
2314            .collect();
2315        assert_eq!(
2316            children,
2317            [
2318                (NodeKind::Comment, "c".to_owned()),
2319                (NodeKind::Text, "xy".to_owned()),
2320                (NodeKind::ProcessingInstruction, "d".to_owned()),
2321                (NodeKind::Text, "z".to_owned()),
2322            ]
2323        );
2324        assert_eq!(tree.text, "vcxydz");
2325    }
2326
2327    #[test]
2328    fn the_document_cache_parses_a_text_once() {
2329        fn shape(doc: &Rc<Document>) -> Vec<String> {
2330            doc.root()
2331                .axis(NodeAxis::Descendant)
2332                .flat_map(|n| std::iter::once(n.clone()).chain(n.attributes()))
2333                .map(|n| format!("{} {}", describe(&n), n.string_value()))
2334                .collect()
2335        }
2336        let cache = DocumentCache::new();
2337        let xml = "<cl id='1'><e v='a'/>text &amp; more<e v='b'/></cl>";
2338        let uri = "file:/codes.xml";
2339        let first = cache.parse_loaded(xml.to_owned(), uri, 8).unwrap();
2340        let between = parse("<x/>");
2341        let second = cache.parse_loaded(xml.to_owned(), uri, 8).unwrap();
2342        // The same tree, as a new document created after the one parsed in between.
2343        assert_eq!(shape(&first), shape(&second));
2344        assert_eq!(second.document_uri(), Some(uri));
2345        assert_eq!(second.base_uri(), Some(uri));
2346        assert_eq!(second.node_count(), first.node_count());
2347        assert_ne!(first.root(), second.root());
2348        assert_eq!(
2349            between.root().cmp_document_order(&second.root()),
2350            Ordering::Less
2351        );
2352        assert_eq!(
2353            first.root().cmp_document_order(&between.root()),
2354            Ordering::Less
2355        );
2356        assert_eq!(cache.entries.lock().unwrap().len(), 1);
2357        // Another text, URI or maximum depth is parsed, and kept apart.
2358        let other = cache.parse_loaded("<cl/>".to_owned(), uri, 8).unwrap();
2359        assert_eq!(other.node_count(), 2);
2360        let elsewhere = cache
2361            .parse_loaded(xml.to_owned(), "file:/other.xml", 8)
2362            .unwrap();
2363        assert_eq!(elsewhere.document_uri(), Some("file:/other.xml"));
2364        assert_eq!(shape(&elsewhere), shape(&first));
2365        let deeper = cache.parse_loaded(xml.to_owned(), uri, 1).unwrap_err();
2366        assert!(deeper.limit().is_some());
2367        assert_eq!(cache.entries.lock().unwrap().len(), 3);
2368        // A text that does not parse is not kept.
2369        assert!(cache.parse_loaded("<cl>".to_owned(), uri, 8).is_err());
2370        assert_eq!(cache.entries.lock().unwrap().len(), 3);
2371    }
2372
2373    #[test]
2374    fn the_element_index_lists_the_elements_of_a_name_in_document_order() {
2375        let mut xml = String::from(r#"<r xmlns:a="urn:x" xmlns:b="urn:x" xmlns="urn:x">"#);
2376        for i in 0..40 {
2377            let prefix = ["a:", "b:", ""][i % 3];
2378            write!(xml, r#"<{prefix}e n="{i}"><f/><e/></{prefix}e><g>t</g>"#).unwrap();
2379        }
2380        xml.push_str("</r>");
2381        let doc = parse(&xml);
2382        let scan = |start: u32, end: u32| -> Vec<u32> {
2383            (start..end)
2384                .filter(|&i| {
2385                    doc.kind(i) == NodeKind::Element
2386                        && doc.name(i).is_some_and(|n| {
2387                            n.local == "e" && n.namespace.as_deref() == Some("urn:x")
2388                        })
2389                })
2390                .collect()
2391        };
2392        let (first, end) = doc.descendant_range(0);
2393        // The first search is answered without an index, the second builds it.
2394        assert_eq!(doc.elements_named(Some("urn:x"), "e", first, end), None);
2395        let all = doc.elements_named(Some("urn:x"), "e", first, end).unwrap();
2396        assert_eq!(all, scan(first, end).as_slice());
2397        assert_eq!(all.len(), 80);
2398        // A range inside the document, and names it does not have.
2399        let inner = doc.elements_named(Some("urn:x"), "e", 10, 200).unwrap();
2400        assert_eq!(inner, scan(10, 200).as_slice());
2401        assert_eq!(doc.elements_named(None, "e", first, end), Some(&[][..]));
2402        assert_eq!(
2403            doc.elements_named(Some("urn:x"), "zz", first, end),
2404            Some(&[][..])
2405        );
2406        // Small ranges are searched.
2407        assert_eq!(doc.elements_named(Some("urn:x"), "e", 10, 20), None);
2408    }
2409
2410    #[test]
2411    fn file_uris() {
2412        if cfg!(windows) {
2413            return;
2414        }
2415        assert_eq!(
2416            file_uri(Path::new("/a b/c,d%é#[1]\u{a0}.xml")).as_deref(),
2417            Some("file:/a%20b/c,d%25é%23%5B1%5D%C2%A0.xml")
2418        );
2419        assert_eq!(file_uri(Path::new("rel.xml")), None);
2420    }
2421}