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`).
13//!
14//! The model has no namespace nodes and no type annotations: every element and attribute is
15//! untyped, so its typed value is `xs:untypedAtomic`.
16//!
17//! A parsed document may be nested at most [`DEFAULT_MAX_DEPTH`] elements deep, or the
18//! maximum given to [`Document::parse_with_max_depth`]: beyond it the parse fails with
19//! [`LimitExceeded::Depth`], so that what walks the tree recursively (the template rules of
20//! a stylesheet) has a bounded depth. Parsing, building and walking a tree use no
21//! recursion.
22
23use std::borrow::Cow;
24use std::cmp::Ordering;
25use std::collections::HashMap;
26use std::fmt::{self, Write as _};
27use std::path::Path;
28use std::rc::Rc;
29use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
30
31use einvoice_xdm::AtomicValue;
32use einvoice_xpath::{QName, XML_NAMESPACE};
33
34use crate::limit::{DEFAULT_MAX_DEPTH, LimitExceeded};
35
36/// "No node" in the parent, previous sibling and name fields.
37const NONE: u32 = u32::MAX;
38
39/// Creation order of documents, for the document order of nodes in different trees.
40static NEXT_SERIAL: AtomicU64 = AtomicU64::new(0);
41
42/// The kind of a node.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44pub enum NodeKind {
45    /// The document node, root of every tree.
46    Document,
47    /// An element.
48    Element,
49    /// An attribute.
50    Attribute,
51    /// A text node (never empty, never adjacent to another text node).
52    Text,
53    /// A comment.
54    Comment,
55    /// A processing instruction.
56    ProcessingInstruction,
57}
58
59/// The axes, in the sense of XPath 2.0 section 3.2.1.1, that the evaluator walks.
60/// `descendant` is not in the supported XPath subset but is used internally for `//name`.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62pub enum NodeAxis {
63    /// `child`
64    Child,
65    /// `attribute`
66    Attribute,
67    /// `self`
68    SelfAxis,
69    /// `descendant`
70    Descendant,
71    /// `descendant-or-self`
72    DescendantOrSelf,
73    /// `following-sibling`
74    FollowingSibling,
75    /// `parent`
76    Parent,
77    /// `ancestor`
78    Ancestor,
79    /// `ancestor-or-self`
80    AncestorOrSelf,
81    /// `preceding-sibling`
82    PrecedingSibling,
83    /// `preceding`
84    Preceding,
85}
86
87impl NodeAxis {
88    /// Whether the axis delivers nodes in reverse document order.
89    #[must_use]
90    pub const fn is_reverse(self) -> bool {
91        matches!(
92            self,
93            Self::Parent
94                | Self::Ancestor
95                | Self::AncestorOrSelf
96                | Self::PrecedingSibling
97                | Self::Preceding
98        )
99    }
100}
101
102/// One node of the arena: 32 bytes.
103///
104/// Every field is read directly by the axis walks and node tests, which run in chains of
105/// dependent loads: packing the kind with the name, or sharing fields between the subtree
106/// range of an element and the text range of the other nodes, measured 2 to 3% slower
107/// over a whole validation.
108#[derive(Debug, Clone, Copy)]
109struct Record {
110    kind: NodeKind,
111    /// Index in [`Document::names`], or [`NONE`].
112    name: u32,
113    parent: u32,
114    prev_sibling: u32,
115    /// The index just after the node's attributes: its first child if it has one. For a
116    /// node that cannot have attributes, the index just after it.
117    first_child: u32,
118    /// The index just after the node's subtree (attributes and descendants).
119    end: u32,
120    /// The range of the text of a text node, comment, processing instruction or
121    /// attribute in the document's text space (see [`Document::own_text`]): start and
122    /// length.
123    text_start: u32,
124    text_len: u32,
125}
126
127impl Record {
128    /// A node at `index` without children (yet), with its text range.
129    const fn new(
130        kind: NodeKind,
131        name: u32,
132        parent: u32,
133        prev_sibling: u32,
134        index: u32,
135        (text_start, text_len): (u32, u32),
136    ) -> Self {
137        Self {
138            kind,
139            name,
140            parent,
141            prev_sibling,
142            first_child: index + 1,
143            end: index + 1,
144            text_start,
145            text_len,
146        }
147    }
148}
149
150/// A problem building or parsing a tree.
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct DocumentError {
153    message: String,
154    limit: Option<LimitExceeded>,
155}
156
157impl DocumentError {
158    fn new(message: impl Into<String>) -> Self {
159        Self {
160            message: message.into(),
161            limit: None,
162        }
163    }
164
165    fn limit_exceeded(limit: LimitExceeded) -> Self {
166        Self {
167            message: limit.to_string(),
168            limit: Some(limit),
169        }
170    }
171
172    /// The explanation.
173    #[must_use]
174    pub fn message(&self) -> &str {
175        &self.message
176    }
177
178    /// The limit the document exceeded, when that is the problem: an element nested
179    /// deeper than the maximum depth ([`LimitExceeded::Depth`]).
180    #[must_use]
181    pub const fn limit(&self) -> Option<LimitExceeded> {
182        self.limit
183    }
184}
185
186impl fmt::Display for DocumentError {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        f.write_str(&self.message)
189    }
190}
191
192impl std::error::Error for DocumentError {}
193
194/// An immutable XML tree.
195///
196/// The texts of its nodes live in one text space: the source text the document was
197/// parsed from, when the parser was given it as an owned `String` (offsets below its
198/// length), followed by the texts that are not written verbatim in it (offsets from its
199/// length on).
200pub struct Document {
201    serial: u64,
202    uri: Option<String>,
203    base_uri: Option<String>,
204    has_xml_base: bool,
205    records: Vec<Record>,
206    names: Vec<QName>,
207    /// The source text, or empty when the texts were copied out of it.
208    source: String,
209    /// The texts that are not in `source`.
210    text: String,
211}
212
213impl fmt::Debug for Document {
214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215        f.debug_struct("Document")
216            .field("serial", &self.serial)
217            .field("uri", &self.uri)
218            .field("nodes", &self.records.len())
219            .finish_non_exhaustive()
220    }
221}
222
223impl Document {
224    /// Parses XML text. Every text node is kept, whitespace-only ones included; a document
225    /// type declaration is refused (its default attributes and entities would change the
226    /// tree without notice). `base_uri`, if given, is the base URI of every node (the
227    /// location the text was read from, Saxon's system id).
228    ///
229    /// The text can be borrowed (`&str`) or given (`String`). Borrowed, the texts of the
230    /// nodes are copied into the tree. Given, the tree keeps it and refers to it for every
231    /// text written verbatim in it (text without entity or character references, line
232    /// ends or, in attributes, whitespace to normalize): only the others are copied.
233    ///
234    /// The document has no document URI: in Saxon-HE 12.10, `fn:document-uri` only knows
235    /// the documents of its document pool, those that `fn:document` or `fn:doc` loaded,
236    /// and is empty for a document given to the transformation, such as the one being
237    /// validated. (Saxon 9.9 fell back to the system id.) A document loaded by
238    /// `fn:document` is parsed with [`Document::parse_loaded`].
239    ///
240    /// An element may be nested at most [`DEFAULT_MAX_DEPTH`] deep (the document element
241    /// is at depth 1); [`Document::parse_with_max_depth`] sets another maximum.
242    ///
243    /// # Errors
244    ///
245    /// XML that is not well-formed or not namespace-well-formed, or that has a document
246    /// type declaration; an element nested deeper than the maximum depth
247    /// ([`DocumentError::limit`] is then [`LimitExceeded::Depth`]).
248    pub fn parse<'t>(
249        text: impl Into<Cow<'t, str>>,
250        base_uri: Option<&str>,
251    ) -> Result<Rc<Self>, DocumentError> {
252        Self::parse_with_uris(text.into(), None, base_uri, DEFAULT_MAX_DEPTH)
253    }
254
255    /// [`Document::parse`] with another maximum element depth than
256    /// [`DEFAULT_MAX_DEPTH`]. What walks a tree recursively (the template rules of a
257    /// stylesheet) needs stack in proportion to its depth: a larger maximum needs a
258    /// larger stack.
259    ///
260    /// # Errors
261    ///
262    /// Those of [`Document::parse`].
263    pub fn parse_with_max_depth<'t>(
264        text: impl Into<Cow<'t, str>>,
265        base_uri: Option<&str>,
266        max_depth: u32,
267    ) -> Result<Rc<Self>, DocumentError> {
268        Self::parse_with_uris(text.into(), None, base_uri, max_depth)
269    }
270
271    /// Parses XML text as [`Document::parse`] does, for a document that `fn:document`
272    /// loaded from `uri` (the absolute URI it resolved): `uri` is both its document URI
273    /// and the base URI of its nodes, as for a document in Saxon's document pool.
274    ///
275    /// # Errors
276    ///
277    /// Those of [`Document::parse`].
278    pub fn parse_loaded<'t>(
279        text: impl Into<Cow<'t, str>>,
280        uri: &str,
281    ) -> Result<Rc<Self>, DocumentError> {
282        Self::parse_with_uris(text.into(), Some(uri), Some(uri), DEFAULT_MAX_DEPTH)
283    }
284
285    /// [`Document::parse_loaded`] with another maximum element depth than
286    /// [`DEFAULT_MAX_DEPTH`].
287    ///
288    /// # Errors
289    ///
290    /// Those of [`Document::parse`].
291    pub fn parse_loaded_with_max_depth<'t>(
292        text: impl Into<Cow<'t, str>>,
293        uri: &str,
294        max_depth: u32,
295    ) -> Result<Rc<Self>, DocumentError> {
296        Self::parse_with_uris(text.into(), Some(uri), Some(uri), max_depth)
297    }
298
299    fn parse_with_uris(
300        text: Cow<'_, str>,
301        document_uri: Option<&str>,
302        base_uri: Option<&str>,
303        max_depth: u32,
304    ) -> Result<Rc<Self>, DocumentError> {
305        let keep_source = matches!(text, Cow::Owned(_));
306        let builder = build_parsed(&text, keep_source, max_depth)?;
307        let source = match text {
308            Cow::Owned(source) => source,
309            Cow::Borrowed(_) => String::new(),
310        };
311        builder.finish_with_source(
312            source,
313            document_uri.map(str::to_owned),
314            base_uri.map(str::to_owned),
315        )
316    }
317
318    /// The document node.
319    #[must_use]
320    pub fn root(self: &Rc<Self>) -> Node {
321        Node {
322            doc: Rc::clone(self),
323            index: 0,
324        }
325    }
326
327    /// The document URI (`fn:document-uri`), if any: only a document loaded by
328    /// `fn:document` has one (see [`Document::parse`]).
329    #[must_use]
330    pub fn document_uri(&self) -> Option<&str> {
331        self.uri.as_deref()
332    }
333
334    /// The base URI of the document's nodes, if any.
335    #[must_use]
336    pub fn base_uri(&self) -> Option<&str> {
337        self.base_uri.as_deref()
338    }
339
340    /// Whether some element has an `xml:base` attribute (whose effect on base URIs is not
341    /// implemented).
342    #[must_use]
343    pub const fn has_xml_base(&self) -> bool {
344        self.has_xml_base
345    }
346
347    /// The number of nodes, the document node and attributes included.
348    #[must_use]
349    pub fn node_count(&self) -> usize {
350        self.records.len()
351    }
352
353    fn record(&self, index: u32) -> &Record {
354        // Indices only ever come from this document's own records.
355        &self.records[index as usize]
356    }
357
358    pub(crate) fn kind(&self, index: u32) -> NodeKind {
359        self.record(index).kind
360    }
361
362    pub(crate) fn name(&self, index: u32) -> Option<&QName> {
363        let name = self.record(index).name;
364        (name != NONE).then(|| &self.names[name as usize])
365    }
366
367    pub(crate) fn parent_index(&self, index: u32) -> Option<u32> {
368        let parent = self.record(index).parent;
369        (parent != NONE).then_some(parent)
370    }
371
372    /// The text of a text node, comment, processing instruction or attribute: a range of
373    /// the text space, in `source` or, from the length of `source` on, in `text`.
374    fn own_text(&self, index: u32) -> &str {
375        let r = self.record(index);
376        let start = r.text_start as usize;
377        let end = start + r.text_len as usize;
378        match start.checked_sub(self.source.len()) {
379            None => &self.source[start..end],
380            Some(start) => &self.text[start..end - self.source.len()],
381        }
382    }
383
384    pub(crate) fn string_value(&self, index: u32) -> Cow<'_, str> {
385        match self.kind(index) {
386            NodeKind::Text
387            | NodeKind::Comment
388            | NodeKind::ProcessingInstruction
389            | NodeKind::Attribute => Cow::Borrowed(self.own_text(index)),
390            NodeKind::Element | NodeKind::Document => {
391                let mut texts = self
392                    .cursor(index, NodeAxis::Descendant)
393                    .walk(self)
394                    .filter(|&i| self.kind(i) == NodeKind::Text);
395                let Some(first) = texts.next() else {
396                    return Cow::Borrowed("");
397                };
398                let Some(second) = texts.next() else {
399                    return Cow::Borrowed(self.own_text(first));
400                };
401                let mut value = String::from(self.own_text(first));
402                value.push_str(self.own_text(second));
403                for i in texts {
404                    value.push_str(self.own_text(i));
405                }
406                Cow::Owned(value)
407            }
408        }
409    }
410
411    /// The start of an axis walk from the node at `index`.
412    pub(crate) fn cursor(&self, index: u32, axis: NodeAxis) -> Cursor {
413        let r = self.record(index);
414        let kind = r.kind;
415        let is_attribute = kind == NodeKind::Attribute;
416        match axis {
417            NodeAxis::SelfAxis => Cursor::One(index),
418            NodeAxis::Parent => match r.parent {
419                NONE => Cursor::Done,
420                parent => Cursor::One(parent),
421            },
422            NodeAxis::Child => Cursor::Siblings {
423                next: r.first_child,
424                end: r.end,
425            },
426            NodeAxis::Attribute => {
427                if kind == NodeKind::Element {
428                    Cursor::Range {
429                        next: index + 1,
430                        end: r.first_child,
431                    }
432                } else {
433                    Cursor::Done
434                }
435            }
436            NodeAxis::Descendant => Cursor::Descendants {
437                next: r.first_child,
438                end: r.end,
439            },
440            NodeAxis::DescendantOrSelf => Cursor::Descendants {
441                next: index,
442                end: r.end,
443            },
444            NodeAxis::FollowingSibling => match r.parent {
445                NONE => Cursor::Done,
446                _ if is_attribute => Cursor::Done,
447                parent => Cursor::Siblings {
448                    next: r.end,
449                    end: self.record(parent).end,
450                },
451            },
452            NodeAxis::Ancestor => Cursor::Ancestors { next: r.parent },
453            NodeAxis::AncestorOrSelf => Cursor::Ancestors { next: index },
454            NodeAxis::PrecedingSibling => {
455                if is_attribute {
456                    Cursor::Done
457                } else {
458                    Cursor::PrecedingSiblings {
459                        next: r.prev_sibling,
460                    }
461                }
462            }
463            NodeAxis::Preceding => Cursor::Preceding {
464                next: index,
465                ancestor: r.parent,
466            },
467        }
468    }
469}
470
471/// The state of an axis walk over node indices, in axis order.
472#[derive(Debug, Clone, Copy)]
473pub(crate) enum Cursor {
474    Done,
475    One(u32),
476    /// Consecutive indices (attributes).
477    Range {
478        next: u32,
479        end: u32,
480    },
481    /// Nodes whose subtrees follow each other (children, following siblings).
482    Siblings {
483        next: u32,
484        end: u32,
485    },
486    /// Every node of a range except attributes, in document order.
487    Descendants {
488        next: u32,
489        end: u32,
490    },
491    Ancestors {
492        next: u32,
493    },
494    PrecedingSiblings {
495        next: u32,
496    },
497    /// `next` is one past the next candidate; `ancestor` the nearest ancestor not yet
498    /// passed, skipped when reached.
499    Preceding {
500        next: u32,
501        ancestor: u32,
502    },
503}
504
505impl Cursor {
506    pub(crate) fn next(&mut self, doc: &Document) -> Option<u32> {
507        match self {
508            Self::Done => None,
509            Self::One(index) => {
510                let index = *index;
511                *self = Self::Done;
512                Some(index)
513            }
514            Self::Range { next, end } => {
515                if *next >= *end {
516                    return None;
517                }
518                let index = *next;
519                *next += 1;
520                Some(index)
521            }
522            Self::Siblings { next, end } => {
523                if *next >= *end {
524                    return None;
525                }
526                let index = *next;
527                *next = doc.record(index).end;
528                Some(index)
529            }
530            Self::Descendants { next, end } => {
531                if *next >= *end {
532                    return None;
533                }
534                let index = *next;
535                // Skips the node's attributes (they directly follow an element).
536                *next = doc.record(index).first_child;
537                Some(index)
538            }
539            Self::Ancestors { next } => {
540                if *next == NONE {
541                    return None;
542                }
543                let index = *next;
544                *next = doc.record(index).parent;
545                Some(index)
546            }
547            Self::PrecedingSiblings { next } => {
548                if *next == NONE {
549                    return None;
550                }
551                let index = *next;
552                *next = doc.record(index).prev_sibling;
553                Some(index)
554            }
555            Self::Preceding { next, ancestor } => loop {
556                if *next == 0 {
557                    return None;
558                }
559                *next -= 1;
560                let index = *next;
561                if index == *ancestor {
562                    *ancestor = doc.record(index).parent;
563                    continue;
564                }
565                if doc.record(index).kind != NodeKind::Attribute {
566                    return Some(index);
567                }
568            },
569        }
570    }
571
572    /// The walk as an iterator borrowing the document.
573    pub(crate) fn walk(self, doc: &Document) -> impl Iterator<Item = u32> + '_ {
574        let mut cursor = self;
575        std::iter::from_fn(move || cursor.next(doc))
576    }
577}
578
579/// A node: a document and the position of the node in it.
580///
581/// Two `Node` values are equal when they are the same node (XPath `is`).
582#[derive(Clone)]
583pub struct Node {
584    doc: Rc<Document>,
585    index: u32,
586}
587
588impl PartialEq for Node {
589    fn eq(&self, other: &Self) -> bool {
590        self.index == other.index && Rc::ptr_eq(&self.doc, &other.doc)
591    }
592}
593
594impl Eq for Node {}
595
596impl fmt::Debug for Node {
597    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
598        write!(f, "Node({:?}", self.kind())?;
599        if let Some(name) = self.name() {
600            write!(f, " {name}")?;
601        }
602        write!(f, " #{} of document {})", self.index, self.doc.serial)
603    }
604}
605
606impl Node {
607    pub(crate) fn new(doc: Rc<Document>, index: u32) -> Self {
608        Self { doc, index }
609    }
610
611    pub(crate) const fn index(&self) -> u32 {
612        self.index
613    }
614
615    /// The document the node belongs to.
616    #[must_use]
617    pub fn document(&self) -> &Rc<Document> {
618        &self.doc
619    }
620
621    /// The node kind.
622    #[must_use]
623    pub fn kind(&self) -> NodeKind {
624        self.doc.kind(self.index)
625    }
626
627    /// The name of an element or attribute, with the prefix it was written with, or the
628    /// target of a processing instruction (as a local name); `None` for other nodes.
629    #[must_use]
630    pub fn name(&self) -> Option<&QName> {
631        self.doc.name(self.index)
632    }
633
634    /// The parent node.
635    #[must_use]
636    pub fn parent(&self) -> Option<Self> {
637        self.doc
638            .parent_index(self.index)
639            .map(|p| Self::new(Rc::clone(&self.doc), p))
640    }
641
642    /// The root of the tree: always the document node.
643    #[must_use]
644    pub fn root(&self) -> Self {
645        Self::new(Rc::clone(&self.doc), 0)
646    }
647
648    /// The string value (XDM `dm:string-value`).
649    #[must_use]
650    pub fn string_value(&self) -> Cow<'_, str> {
651        self.doc.string_value(self.index)
652    }
653
654    /// The typed value of the node in an untyped tree: `xs:untypedAtomic`, except for
655    /// comments and processing instructions, whose typed value is an `xs:string`.
656    #[must_use]
657    pub fn typed_value(&self) -> AtomicValue {
658        let value = self.string_value().into_owned();
659        match self.kind() {
660            NodeKind::Comment | NodeKind::ProcessingInstruction => AtomicValue::String(value),
661            _ => AtomicValue::UntypedAtomic(value),
662        }
663    }
664
665    /// The nodes on an axis from this node, in axis order (reverse document order for
666    /// the reverse axes).
667    #[must_use]
668    pub fn axis(&self, axis: NodeAxis) -> Axis {
669        Axis {
670            cursor: self.doc.cursor(self.index, axis),
671            doc: Rc::clone(&self.doc),
672        }
673    }
674
675    /// The children, in document order.
676    #[must_use]
677    pub fn children(&self) -> Axis {
678        self.axis(NodeAxis::Child)
679    }
680
681    /// The attributes, in document order (the order of the source).
682    #[must_use]
683    pub fn attributes(&self) -> Axis {
684        self.axis(NodeAxis::Attribute)
685    }
686
687    /// Document order. Nodes of different documents are ordered by the creation of their
688    /// documents.
689    #[must_use]
690    pub fn cmp_document_order(&self, other: &Self) -> Ordering {
691        self.doc
692            .serial
693            .cmp(&other.doc.serial)
694            .then(self.index.cmp(&other.index))
695    }
696}
697
698/// The nodes on an axis from a node, in axis order.
699#[derive(Debug, Clone)]
700pub struct Axis {
701    cursor: Cursor,
702    doc: Rc<Document>,
703}
704
705impl Iterator for Axis {
706    type Item = Node;
707
708    fn next(&mut self) -> Option<Node> {
709        let index = self.cursor.next(&self.doc)?;
710        Some(Node::new(Rc::clone(&self.doc), index))
711    }
712}
713
714/// Builds a [`Document`] from events, in document order.
715///
716/// Adjacent text is merged into one text node and empty text is dropped, as the XDM
717/// requires. Attributes must come right after their element's start, before its content;
718/// an attribute whose expanded name is already on the element replaces it.
719#[derive(Debug)]
720pub struct TreeBuilder {
721    records: Vec<Record>,
722    names: Vec<QName>,
723    name_ids: HashMap<QName, u32>,
724    /// The length of the source text the text space starts with (see [`Document`]): the
725    /// texts added are stored from that offset on.
726    source_len: usize,
727    text: String,
728    /// The open nodes, the document node first.
729    open: Vec<u32>,
730    /// The last child of each open node, or [`NONE`].
731    last_child: Vec<u32>,
732    has_xml_base: bool,
733}
734
735impl Default for TreeBuilder {
736    fn default() -> Self {
737        Self::new()
738    }
739}
740
741fn to_u32(value: usize) -> Result<u32, DocumentError> {
742    u32::try_from(value)
743        .ok()
744        .filter(|&v| v != NONE)
745        .ok_or_else(|| DocumentError::new("document too large"))
746}
747
748/// Where the text of a node comes from.
749#[derive(Debug, Clone, Copy)]
750enum NodeText<'s> {
751    /// A range of the source text: offset and length.
752    Source(u32, u32),
753    /// Text to store.
754    Copy(&'s str),
755}
756
757impl TreeBuilder {
758    /// A builder holding only the document node.
759    #[must_use]
760    pub fn new() -> Self {
761        Self {
762            records: vec![Record::new(NodeKind::Document, NONE, NONE, NONE, 0, (0, 0))],
763            names: Vec::new(),
764            name_ids: HashMap::new(),
765            source_len: 0,
766            text: String::new(),
767            open: vec![0],
768            last_child: vec![NONE],
769            has_xml_base: false,
770        }
771    }
772
773    /// A builder whose text space starts with a source text of `source_len` bytes, with
774    /// room for exactly `nodes` nodes (the document node included) and `text` bytes of
775    /// copied text.
776    fn with_capacity(nodes: usize, text: usize, source_len: usize) -> Self {
777        let mut builder = Self::new();
778        builder.records.reserve_exact(nodes.saturating_sub(1));
779        builder.text.reserve_exact(text);
780        builder.source_len = source_len;
781        builder
782    }
783
784    fn intern(&mut self, name: QName) -> Result<u32, DocumentError> {
785        if let Some(&id) = self.name_ids.get(&name) {
786            return Ok(id);
787        }
788        let id = self.push_name(name.clone())?;
789        self.name_ids.insert(name, id);
790        Ok(id)
791    }
792
793    /// Adds a name to the table, without interning it.
794    fn push_name(&mut self, name: QName) -> Result<u32, DocumentError> {
795        let id = to_u32(self.names.len())?;
796        self.names.push(name);
797        Ok(id)
798    }
799
800    /// The range of the text space a text occupies: its offset and length.
801    fn store_text(&mut self, value: NodeText<'_>) -> Result<(u32, u32), DocumentError> {
802        match value {
803            NodeText::Source(start, len) => Ok((start, len)),
804            NodeText::Copy(value) => {
805                let start = to_u32(self.source_len + self.text.len())?;
806                let len = to_u32(value.len())?;
807                to_u32(self.source_len + self.text.len() + value.len())?;
808                self.text.push_str(value);
809                Ok((start, len))
810            }
811        }
812    }
813
814    fn top(&self) -> u32 {
815        self.open.last().copied().unwrap_or(0)
816    }
817
818    /// Appends a child of the innermost open node and returns its index: an element (its
819    /// text is ignored), or a node with a text.
820    fn append(
821        &mut self,
822        kind: NodeKind,
823        name: u32,
824        text: NodeText<'_>,
825    ) -> Result<u32, DocumentError> {
826        let index = to_u32(self.records.len())?;
827        to_u32(self.records.len() + 1)?;
828        let text = if kind == NodeKind::Element {
829            (0, 0)
830        } else {
831            self.store_text(text)?
832        };
833        let parent = self.top();
834        let last = self.last_child.last_mut().map_or(NONE, |l| {
835            let previous = *l;
836            *l = index;
837            previous
838        });
839        self.records
840            .push(Record::new(kind, name, parent, last, index, text));
841        Ok(index)
842    }
843
844    /// Opens an element.
845    ///
846    /// # Errors
847    ///
848    /// A document too large for the arena.
849    pub fn start_element(&mut self, name: QName) -> Result<(), DocumentError> {
850        let name = self.intern(name)?;
851        self.open_element(name)
852    }
853
854    fn open_element(&mut self, name: u32) -> Result<(), DocumentError> {
855        let index = self.append(NodeKind::Element, name, NodeText::Copy(""))?;
856        self.open.push(index);
857        self.last_child.push(NONE);
858        Ok(())
859    }
860
861    /// Adds an attribute to the element just opened.
862    ///
863    /// # Errors
864    ///
865    /// No element is open, or the element already has content.
866    pub fn attribute(&mut self, name: QName, value: &str) -> Result<(), DocumentError> {
867        let element = self.top();
868        let has_content = self.last_child.last().is_some_and(|&l| l != NONE);
869        if element == 0 || has_content {
870            return Err(DocumentError::new(format!(
871                "attribute {name} outside an element start"
872            )));
873        }
874        let first = element as usize + 1;
875        let existing = (first..self.records.len()).find(|&i| {
876            let id = self.records[i].name;
877            self.names[id as usize].same_expanded_name(&name)
878        });
879        let xml_base = is_xml_base(name.namespace.as_deref(), &name.local);
880        let id = self.intern(name)?;
881        if let Some(i) = existing {
882            let (text_start, text_len) = self.store_text(NodeText::Copy(value))?;
883            let record = &mut self.records[i];
884            record.name = id;
885            record.text_start = text_start;
886            record.text_len = text_len;
887            self.has_xml_base |= xml_base;
888            return Ok(());
889        }
890        self.push_attribute(id, xml_base, NodeText::Copy(value))
891    }
892
893    /// Adds an attribute, known not to be on the element yet, to the element just opened.
894    fn push_attribute(
895        &mut self,
896        name: u32,
897        xml_base: bool,
898        value: NodeText<'_>,
899    ) -> Result<(), DocumentError> {
900        let element = self.top();
901        let index = to_u32(self.records.len())?;
902        to_u32(self.records.len() + 1)?;
903        let previous = if index == element + 1 {
904            NONE
905        } else {
906            index - 1
907        };
908        let text = self.store_text(value)?;
909        self.records.push(Record::new(
910            NodeKind::Attribute,
911            name,
912            element,
913            previous,
914            index,
915            text,
916        ));
917        self.records[element as usize].first_child = index + 1;
918        self.has_xml_base |= xml_base;
919        Ok(())
920    }
921
922    /// Adds text, merged with text added just before.
923    ///
924    /// # Errors
925    ///
926    /// A document too large for the arena.
927    pub fn text(&mut self, value: &str) -> Result<(), DocumentError> {
928        if value.is_empty() {
929            return Ok(());
930        }
931        let last = self.last_child.last().copied().unwrap_or(NONE);
932        // Text merges with the text node just before when that node's text is the end of
933        // the copied texts (always so for a built tree, whose texts are all copied).
934        let mergeable = last != NONE
935            && last as usize + 1 == self.records.len()
936            && self.records[last as usize].kind == NodeKind::Text
937            && {
938                let r = &self.records[last as usize];
939                r.text_start as usize + r.text_len as usize == self.source_len + self.text.len()
940                    && r.text_start as usize >= self.source_len
941            };
942        if mergeable {
943            self.store_text(NodeText::Copy(value))?;
944            let record = &mut self.records[last as usize];
945            record.text_len = to_u32(record.text_len as usize + value.len())?;
946            return Ok(());
947        }
948        self.append(NodeKind::Text, NONE, NodeText::Copy(value))
949            .map(drop)
950    }
951
952    /// Adds a comment.
953    ///
954    /// # Errors
955    ///
956    /// A document too large for the arena.
957    pub fn comment(&mut self, value: &str) -> Result<(), DocumentError> {
958        self.append(NodeKind::Comment, NONE, NodeText::Copy(value))
959            .map(drop)
960    }
961
962    /// Adds a processing instruction.
963    ///
964    /// # Errors
965    ///
966    /// A document too large for the arena.
967    pub fn processing_instruction(
968        &mut self,
969        target: &str,
970        value: &str,
971    ) -> Result<(), DocumentError> {
972        let name = self.intern(QName::local(target))?;
973        self.append(NodeKind::ProcessingInstruction, name, NodeText::Copy(value))
974            .map(drop)
975    }
976
977    /// Closes the innermost open element.
978    ///
979    /// # Errors
980    ///
981    /// No element is open.
982    pub fn end_element(&mut self) -> Result<(), DocumentError> {
983        if self.open.len() < 2 {
984            return Err(DocumentError::new("end of element without a start"));
985        }
986        let element = self.top();
987        self.open.pop();
988        self.last_child.pop();
989        let end = to_u32(self.records.len())?;
990        self.records[element as usize].end = end;
991        Ok(())
992    }
993
994    /// The finished document, with its document URI and the base URI of its nodes.
995    ///
996    /// # Errors
997    ///
998    /// An element is still open.
999    pub fn finish(
1000        self,
1001        document_uri: Option<String>,
1002        base_uri: Option<String>,
1003    ) -> Result<Rc<Document>, DocumentError> {
1004        self.finish_with_source(String::new(), document_uri, base_uri)
1005    }
1006
1007    /// The finished document, whose text space starts with `source` (as long as the
1008    /// builder was told).
1009    fn finish_with_source(
1010        mut self,
1011        source: String,
1012        document_uri: Option<String>,
1013        base_uri: Option<String>,
1014    ) -> Result<Rc<Document>, DocumentError> {
1015        if self.open.len() != 1 {
1016            return Err(DocumentError::new("unclosed element"));
1017        }
1018        if source.len() != self.source_len {
1019            return Err(DocumentError::new("source text of another length"));
1020        }
1021        self.records[0].end = to_u32(self.records.len())?;
1022        // No spare capacity is kept: a parsed tree is sized exactly, a built one is
1023        // trimmed once.
1024        self.records.shrink_to_fit();
1025        self.names.shrink_to_fit();
1026        self.text.shrink_to_fit();
1027        Ok(Rc::new(Document {
1028            serial: NEXT_SERIAL.fetch_add(1, AtomicOrdering::Relaxed),
1029            uri: document_uri,
1030            base_uri,
1031            has_xml_base: self.has_xml_base,
1032            records: self.records,
1033            names: self.names,
1034            source,
1035            text: self.text,
1036        }))
1037    }
1038}
1039
1040fn is_xml_base(namespace: Option<&str>, local: &str) -> bool {
1041    local == "base" && namespace == Some(XML_NAMESPACE)
1042}
1043
1044/// The offset of `part` in `input`, if `part` is a slice of it.
1045fn offset_in(input: &str, part: &str) -> Option<usize> {
1046    let start = part.as_ptr().addr().checked_sub(input.as_ptr().addr())?;
1047    (start.checked_add(part.len())? <= input.len()).then_some(start)
1048}
1049
1050/// A name as the parser sees it: prefix as written (empty for none), namespace URI and
1051/// local part, all borrowed from the text or the parsed document.
1052type NameKey<'a> = (&'a str, Option<&'a str>, &'a str);
1053
1054/// Builds the tree of a parsed document, in two passes over the parser's tree: the first
1055/// counts the nodes and the bytes of text to copy, so that the arena is allocated once at
1056/// its exact size; the second fills it. With `keep_source`, every text that is a slice of
1057/// `input` is stored as a range of it instead of being copied (the document then keeps
1058/// `input`). An element nested deeper than `max_depth` is refused by the first pass,
1059/// before the arena is allocated.
1060fn build_parsed(
1061    input: &str,
1062    keep_source: bool,
1063    max_depth: u32,
1064) -> Result<TreeBuilder, DocumentError> {
1065    let options = roxmltree::ParsingOptions {
1066        allow_dtd: false,
1067        nodes_limit: u32::MAX,
1068        ..roxmltree::ParsingOptions::default()
1069    };
1070    let parsed = roxmltree::Document::parse_with_options(input, options)
1071        .map_err(|e| DocumentError::new(format!("XML: {e}")))?;
1072    let (nodes, text_bytes) = sizes(&parsed, input, keep_source, max_depth)?;
1073    let mut builder =
1074        TreeBuilder::with_capacity(nodes, text_bytes, if keep_source { input.len() } else { 0 });
1075    let mut names: HashMap<NameKey<'_>, u32> = HashMap::new();
1076    let node_text = |text| node_text(input, keep_source, text);
1077    // Elements still open, innermost last: closed when the walk in document order
1078    // reaches a node that is not inside them.
1079    let mut open: Vec<roxmltree::NodeId> = Vec::new();
1080    for node in parsed.root().descendants().skip(1) {
1081        let parent = node.parent().map(|p| p.id());
1082        while open.last().is_some_and(|&id| Some(id) != parent) {
1083            open.pop();
1084            builder.end_element()?;
1085        }
1086        match node.node_type() {
1087            roxmltree::NodeType::Root => {}
1088            roxmltree::NodeType::Element => {
1089                let tag = node.tag_name();
1090                let key = (
1091                    element_prefix(input, node),
1092                    tag.namespace().filter(|ns| !ns.is_empty()),
1093                    tag.name(),
1094                );
1095                let id = name_id(&mut builder, &mut names, key)?;
1096                builder.open_element(id)?;
1097                // The parser refuses duplicate attributes: each one is new.
1098                for attribute in node.attributes() {
1099                    let namespace = attribute.namespace().filter(|ns| !ns.is_empty());
1100                    let local = attribute.name();
1101                    let prefix = input
1102                        .get(attribute.range_qname())
1103                        .and_then(|q| q.split_once(':'))
1104                        .map_or("", |(prefix, _)| prefix);
1105                    let id = name_id(&mut builder, &mut names, (prefix, namespace, local))?;
1106                    builder.push_attribute(
1107                        id,
1108                        is_xml_base(namespace, local),
1109                        node_text(attribute.value())?,
1110                    )?;
1111                }
1112                open.push(node.id());
1113            }
1114            roxmltree::NodeType::Text => {
1115                // The parser merges adjacent text, so the text nodes it gives are never
1116                // adjacent.
1117                if is_in_element(node) {
1118                    let text = node.text().unwrap_or_default();
1119                    if !text.is_empty() {
1120                        builder.append(NodeKind::Text, NONE, node_text(text)?)?;
1121                    }
1122                }
1123            }
1124            roxmltree::NodeType::Comment => {
1125                let text = node_text(node.text().unwrap_or_default())?;
1126                builder.append(NodeKind::Comment, NONE, text)?;
1127            }
1128            roxmltree::NodeType::PI => {
1129                if let Some(pi) = node.pi() {
1130                    let id = name_id(&mut builder, &mut names, ("", None, pi.target))?;
1131                    let text = node_text(pi.value.unwrap_or(""))?;
1132                    builder.append(NodeKind::ProcessingInstruction, id, text)?;
1133                }
1134            }
1135        }
1136    }
1137    for _ in open {
1138        builder.end_element()?;
1139    }
1140    Ok(builder)
1141}
1142
1143/// The number of nodes of the tree of a parsed document (the document node included) and
1144/// the bytes of text to copy into it: all of them, or with `keep_source` those that are
1145/// not slices of `input`.
1146///
1147/// # Errors
1148///
1149/// An element nested deeper than `max_depth` ([`LimitExceeded::Depth`]).
1150fn sizes(
1151    parsed: &roxmltree::Document<'_>,
1152    input: &str,
1153    keep_source: bool,
1154    max_depth: u32,
1155) -> Result<(usize, usize), DocumentError> {
1156    let copied = |text: &str| {
1157        if keep_source && offset_in(input, text).is_some() {
1158            0
1159        } else {
1160            text.len()
1161        }
1162    };
1163    let (mut nodes, mut text_bytes) = (1usize, 0usize);
1164    // The elements still open, innermost last, as in `build_parsed`: their number is
1165    // the depth of the parent of the next element.
1166    let mut open: Vec<roxmltree::NodeId> = Vec::new();
1167    for node in parsed.root().descendants().skip(1) {
1168        match node.node_type() {
1169            roxmltree::NodeType::Root => {}
1170            roxmltree::NodeType::Element => {
1171                let parent = node.parent().map(|p| p.id());
1172                while open.last().is_some_and(|&id| Some(id) != parent) {
1173                    open.pop();
1174                }
1175                if u32::try_from(open.len()).map_or(true, |depth| depth >= max_depth) {
1176                    let at = parsed.text_pos_at(node.range().start);
1177                    return Err(DocumentError::limit_exceeded(LimitExceeded::Depth {
1178                        max: max_depth,
1179                        line: at.row,
1180                        column: at.col,
1181                    }));
1182                }
1183                open.push(node.id());
1184                nodes += 1;
1185                for attribute in node.attributes() {
1186                    nodes += 1;
1187                    text_bytes += copied(attribute.value());
1188                }
1189            }
1190            roxmltree::NodeType::Text => {
1191                if is_in_element(node) {
1192                    nodes += 1;
1193                    text_bytes += copied(node.text().unwrap_or_default());
1194                }
1195            }
1196            roxmltree::NodeType::Comment => {
1197                nodes += 1;
1198                text_bytes += copied(node.text().unwrap_or_default());
1199            }
1200            roxmltree::NodeType::PI => {
1201                nodes += 1;
1202                text_bytes += node.pi().map_or(0, |pi| copied(pi.value.unwrap_or("")));
1203            }
1204        }
1205    }
1206    Ok((nodes, text_bytes))
1207}
1208
1209/// The identity of a name in the builder's table, added on first sight.
1210fn name_id<'a>(
1211    builder: &mut TreeBuilder,
1212    names: &mut HashMap<NameKey<'a>, u32>,
1213    key: NameKey<'a>,
1214) -> Result<u32, DocumentError> {
1215    if let Some(&id) = names.get(&key) {
1216        return Ok(id);
1217    }
1218    let (prefix, namespace, local) = key;
1219    let id = builder.push_name(QName {
1220        prefix: (!prefix.is_empty()).then(|| prefix.to_owned()),
1221        namespace: namespace.map(str::to_owned),
1222        local: local.to_owned(),
1223    })?;
1224    names.insert(key, id);
1225    Ok(id)
1226}
1227
1228/// Where the text of a parsed node is stored: as a range of `input` if `keep_source` and
1229/// it is a slice of it, else copied.
1230fn node_text<'s>(
1231    input: &str,
1232    keep_source: bool,
1233    text: &'s str,
1234) -> Result<NodeText<'s>, DocumentError> {
1235    Ok(
1236        match keep_source.then(|| offset_in(input, text)).flatten() {
1237            Some(start) => NodeText::Source(to_u32(start)?, to_u32(text.len())?),
1238            None => NodeText::Copy(text),
1239        },
1240    )
1241}
1242
1243/// Whether a node is inside an element: text between the top-level nodes is not part of
1244/// the data model.
1245fn is_in_element(node: roxmltree::Node<'_, '_>) -> bool {
1246    node.parent().is_some_and(|p| !p.is_root())
1247}
1248
1249/// The prefix an element name is written with, empty for none.
1250fn element_prefix<'a>(input: &'a str, node: roxmltree::Node<'_, '_>) -> &'a str {
1251    let start = node.range().start + 1;
1252    let written = input
1253        .get(start..)
1254        .map(|rest| {
1255            let end = rest
1256                .find(|c: char| c.is_ascii_whitespace() || c == '/' || c == '>')
1257                .unwrap_or(rest.len());
1258            &rest[..end]
1259        })
1260        .unwrap_or_default();
1261    written.split_once(':').map_or("", |(prefix, _)| prefix)
1262}
1263
1264/// The `file:` URI that Saxon-HE gives a document read from a file: Java's
1265/// `File.toURI().toString()` of the absolute path. ASCII characters outside the URI path
1266/// syntax, Unicode space separators and control characters are percent-encoded (UTF-8,
1267/// upper-case hex); other non-ASCII characters are kept. On Windows, `C:\a\b` becomes
1268/// `file:/C:/a/b`.
1269///
1270/// Returns `None` for a relative path or one that is not valid Unicode.
1271#[must_use]
1272pub fn file_uri(path: &Path) -> Option<String> {
1273    if !path.is_absolute() {
1274        return None;
1275    }
1276    let text = path.to_str()?.replace('\\', "/");
1277    let mut uri = String::from("file:");
1278    if !text.starts_with('/') {
1279        uri.push('/');
1280    }
1281    for c in text.chars() {
1282        let keep = if c.is_ascii() {
1283            c.is_ascii_alphanumeric() || "-_.!~*'():@&=+$,;/".contains(c)
1284        } else {
1285            // java.lang.Character.isSpaceChar (Zs, Zl, Zp) and isISOControl.
1286            !(matches!(
1287                c,
1288                '\u{A0}' | '\u{1680}' | '\u{2000}'
1289                    ..='\u{200A}' | '\u{2028}' | '\u{2029}' | '\u{202F}' | '\u{205F}' | '\u{3000}'
1290            ) || c.is_control())
1291        };
1292        if keep {
1293            uri.push(c);
1294        } else {
1295            let mut buffer = [0; 4];
1296            for byte in c.encode_utf8(&mut buffer).bytes() {
1297                let _ = write!(uri, "%{byte:02X}");
1298            }
1299        }
1300    }
1301    Some(uri)
1302}
1303
1304#[cfg(test)]
1305mod tests {
1306    use super::*;
1307
1308    fn parse(xml: &str) -> Rc<Document> {
1309        Document::parse(xml, Some("file:/t.xml")).unwrap()
1310    }
1311
1312    fn describe(node: &Node) -> String {
1313        match node.kind() {
1314            NodeKind::Document => "/".to_owned(),
1315            NodeKind::Element => node.name().unwrap().to_string(),
1316            NodeKind::Attribute => format!("@{}", node.name().unwrap()),
1317            NodeKind::Text => format!("{:?}", node.string_value()),
1318            NodeKind::Comment => format!("<!--{}-->", node.string_value()),
1319            NodeKind::ProcessingInstruction => format!("<?{}?>", node.name().unwrap()),
1320        }
1321    }
1322
1323    fn walk(node: &Node, axis: NodeAxis) -> Vec<String> {
1324        node.axis(axis).map(|n| describe(&n)).collect()
1325    }
1326
1327    fn find(tree: &Rc<Document>, local: &str) -> Node {
1328        tree.root()
1329            .axis(NodeAxis::Descendant)
1330            .find(|n| n.name().is_some_and(|name| name.local == local))
1331            .unwrap()
1332    }
1333
1334    const XML: &str = "<?xml version='1.0'?><!--c0--><r xmlns:p='urn:p' a='1' p:b='2'> \
1335        <x>1<y q='3'>2</y>3</x><p:z/><!--c1--><?pi data?><w><v/></w></r>";
1336
1337    const NONE: [&str; 0] = [];
1338
1339    #[test]
1340    fn document_order_and_axes() {
1341        let tree = parse(XML);
1342        let root = tree.root();
1343        assert_eq!(walk(&root, NodeAxis::Child), ["<!--c0-->", "r"]);
1344        let top = find(&tree, "r");
1345        assert_eq!(walk(&top, NodeAxis::Attribute), ["@a", "@p:b"]);
1346        assert_eq!(
1347            walk(&top, NodeAxis::Child),
1348            ["\" \"", "x", "p:z", "<!--c1-->", "<?pi?>", "w"]
1349        );
1350        assert_eq!(
1351            walk(&top, NodeAxis::Descendant),
1352            [
1353                "\" \"",
1354                "x",
1355                "\"1\"",
1356                "y",
1357                "\"2\"",
1358                "\"3\"",
1359                "p:z",
1360                "<!--c1-->",
1361                "<?pi?>",
1362                "w",
1363                "v"
1364            ]
1365        );
1366        let y = find(&tree, "y");
1367        assert_eq!(walk(&y, NodeAxis::Ancestor), ["x", "r", "/"]);
1368        assert_eq!(walk(&y, NodeAxis::AncestorOrSelf), ["y", "x", "r", "/"]);
1369        assert_eq!(walk(&y, NodeAxis::PrecedingSibling), ["\"1\""]);
1370        assert_eq!(walk(&y, NodeAxis::FollowingSibling), ["\"3\""]);
1371        assert_eq!(
1372            walk(&y, NodeAxis::Preceding),
1373            ["\"1\"", "\" \"", "<!--c0-->"]
1374        );
1375        let v = find(&tree, "v");
1376        assert_eq!(
1377            walk(&v, NodeAxis::Preceding),
1378            [
1379                "<?pi?>",
1380                "<!--c1-->",
1381                "p:z",
1382                "\"3\"",
1383                "\"2\"",
1384                "y",
1385                "\"1\"",
1386                "x",
1387                "\" \"",
1388                "<!--c0-->"
1389            ]
1390        );
1391        let q = y.attributes().next().unwrap();
1392        assert_eq!(walk(&q, NodeAxis::Parent), ["y"]);
1393        assert_eq!(
1394            walk(&q, NodeAxis::Preceding),
1395            ["\"1\"", "\" \"", "<!--c0-->"]
1396        );
1397        assert_eq!(walk(&q, NodeAxis::FollowingSibling), NONE);
1398        assert_eq!(walk(&q, NodeAxis::PrecedingSibling), NONE);
1399        assert_eq!(walk(&q, NodeAxis::DescendantOrSelf), ["@q"]);
1400        assert_eq!(walk(&q, NodeAxis::Child), NONE);
1401        let all: Vec<Node> = root.axis(NodeAxis::DescendantOrSelf).collect();
1402        assert!(
1403            all.windows(2)
1404                .all(|w| w[0].cmp_document_order(&w[1]) == Ordering::Less)
1405        );
1406    }
1407
1408    #[test]
1409    fn values_names_and_prefixes() {
1410        let tree = parse(XML);
1411        let top = find(&tree, "r");
1412        assert_eq!(top.string_value(), " 123");
1413        assert_eq!(find(&tree, "x").string_value(), "123");
1414        assert_eq!(find(&tree, "y").string_value(), "2");
1415        assert_eq!(find(&tree, "w").string_value(), "");
1416        let z = find(&tree, "z");
1417        assert_eq!(z.name().unwrap().to_string(), "p:z");
1418        assert_eq!(z.name().unwrap().namespace.as_deref(), Some("urn:p"));
1419        let prefixed = top.attributes().nth(1).unwrap();
1420        assert_eq!(prefixed.name().unwrap().prefix.as_deref(), Some("p"));
1421        assert!(matches!(prefixed.typed_value(), AtomicValue::UntypedAtomic(s) if s == "2"));
1422        let comment = tree.root().children().next().unwrap();
1423        assert!(matches!(comment.typed_value(), AtomicValue::String(s) if s == "c0"));
1424        assert_eq!(tree.document_uri(), None);
1425        assert_eq!(tree.base_uri(), Some("file:/t.xml"));
1426        let loaded = Document::parse_loaded("<a/>", "file:/t.xml").unwrap();
1427        assert_eq!(loaded.document_uri(), Some("file:/t.xml"));
1428        assert_eq!(loaded.base_uri(), Some("file:/t.xml"));
1429        assert_eq!(z.root(), tree.root());
1430        assert_ne!(z, top);
1431    }
1432
1433    #[test]
1434    fn undeclared_default_namespace_is_no_namespace() {
1435        let tree = parse("<r xmlns='urn:d'><n xmlns=''><m/></n></r>");
1436        assert_eq!(
1437            find(&tree, "r").name().unwrap().namespace.as_deref(),
1438            Some("urn:d")
1439        );
1440        assert_eq!(find(&tree, "n").name().unwrap().namespace, None);
1441        assert_eq!(find(&tree, "m").name().unwrap().namespace, None);
1442    }
1443
1444    #[test]
1445    fn same_namespace_two_prefixes() {
1446        let tree = parse("<a:r xmlns:a='urn:x' xmlns:b='urn:x'><b:c a:d='1'/></a:r>");
1447        let inner = find(&tree, "c");
1448        assert_eq!(inner.name().unwrap().to_string(), "b:c");
1449        assert_eq!(find(&tree, "r").name().unwrap().to_string(), "a:r");
1450        let attribute = inner.attributes().next().unwrap();
1451        assert_eq!(attribute.name().unwrap().to_string(), "a:d");
1452    }
1453
1454    #[test]
1455    fn builder_merges_text_and_replaces_attributes() {
1456        let mut builder = TreeBuilder::new();
1457        builder.start_element(QName::local("e")).unwrap();
1458        builder.attribute(QName::local("a"), "1").unwrap();
1459        builder.attribute(QName::local("a"), "2").unwrap();
1460        builder.text("x").unwrap();
1461        builder.text("").unwrap();
1462        builder.text("y").unwrap();
1463        assert!(builder.attribute(QName::local("late"), "1").is_err());
1464        builder.end_element().unwrap();
1465        assert!(builder.end_element().is_err());
1466        let tree = builder.finish(None, None).unwrap();
1467        let element = tree.root().children().next().unwrap();
1468        let attributes: Vec<_> = element
1469            .attributes()
1470            .map(|a| a.string_value().into_owned())
1471            .collect();
1472        assert_eq!(attributes, ["2"]);
1473        let texts: Vec<_> = element
1474            .children()
1475            .map(|t| t.string_value().into_owned())
1476            .collect();
1477        assert_eq!(texts, ["xy"]);
1478    }
1479
1480    #[test]
1481    fn whitespace_text_kept_and_dtd_refused() {
1482        let tree = parse("<r>\n  <a/>\n</r>\n");
1483        let top = tree.root().children().next().unwrap();
1484        assert_eq!(top.children().count(), 3);
1485        assert!(Document::parse("<!DOCTYPE r [<!ENTITY e 'x'>]><r>&e;</r>", None).is_err());
1486        assert!(Document::parse("<r><a></r>", None).is_err());
1487    }
1488
1489    #[test]
1490    fn records_are_compact() {
1491        assert_eq!(std::mem::size_of::<Record>(), 32);
1492    }
1493
1494    /// Kind, name, string value and parent of every node, in document order.
1495    fn dump(tree: &Rc<Document>) -> Vec<String> {
1496        (0..tree.node_count())
1497            .map(|i| {
1498                let node = Node::new(Rc::clone(tree), u32::try_from(i).unwrap());
1499                let name = node.name().map(|n| {
1500                    format!(
1501                        "{}{{{}}}{}",
1502                        n,
1503                        n.namespace.as_deref().unwrap_or(""),
1504                        n.local
1505                    )
1506                });
1507                format!(
1508                    "{:?} {name:?} {:?} {:?}",
1509                    node.kind(),
1510                    node.string_value(),
1511                    node.parent().map(|p| p.index())
1512                )
1513            })
1514            .collect()
1515    }
1516
1517    /// Texts written verbatim in an owned source are ranges of it; the others (character
1518    /// and entity references, line ends, attribute whitespace, CDATA sections merged with
1519    /// text) are copied. The tree is the same as from the borrowed text, which is copied
1520    /// whole, and its arenas are sized exactly.
1521    #[test]
1522    fn owned_source_is_referred_to() {
1523        let xml = "<?xml version='1.0'?><!--top--><?pi top data?>\
1524            <p:r xmlns:p='urn:p' xmlns='urn:d' a='plain' b='x&amp;y' c='t\tu'>\
1525            verbatim<e p:f='1'>a&#65;b</e>line\r\nend<![CDATA[<&>]]>more<!--c-->\
1526            <?pi in?><e/>tail</p:r>";
1527        let borrowed = Document::parse(xml, None).unwrap();
1528        let owned = Document::parse(xml.to_owned(), None).unwrap();
1529        assert_eq!(dump(&borrowed), dump(&owned));
1530        assert_eq!(borrowed.source, "");
1531        assert_eq!(owned.source, xml);
1532        // Copied: "x&y", "t u", "aAb", "line\nend<&>more"; everything else is a range.
1533        assert_eq!(owned.text, "x&yt uaAbline\nend<&>more");
1534        let copied_whole: usize = (0..borrowed.node_count())
1535            .map(|i| {
1536                let i = u32::try_from(i).unwrap();
1537                match borrowed.kind(i) {
1538                    NodeKind::Element | NodeKind::Document => 0,
1539                    _ => borrowed.own_text(i).len(),
1540                }
1541            })
1542            .sum();
1543        assert_eq!(borrowed.text.len(), copied_whole);
1544        for tree in [&borrowed, &owned] {
1545            assert_eq!(tree.records.capacity(), tree.records.len());
1546            assert_eq!(tree.text.capacity(), tree.text.len());
1547            assert_eq!(tree.names.capacity(), tree.names.len());
1548        }
1549        let r = find(&owned, "r");
1550        let values: Vec<_> = r
1551            .attributes()
1552            .map(|a| a.string_value().into_owned())
1553            .collect();
1554        assert_eq!(values, ["plain", "x&y", "t u"]);
1555        assert_eq!(r.string_value(), "verbatimaAbline\nend<&>moretail");
1556        assert_eq!(r.name().unwrap().to_string(), "p:r");
1557        let e = find(&owned, "e");
1558        assert_eq!(e.name().unwrap().namespace.as_deref(), Some("urn:d"));
1559        let f = e.attributes().next().unwrap();
1560        assert_eq!(f.name().unwrap().to_string(), "p:f");
1561        assert_eq!(f.name().unwrap().namespace.as_deref(), Some("urn:p"));
1562        // Names are interned: the two `e` elements share one entry.
1563        assert_eq!(owned.names.iter().filter(|n| n.local == "e").count(), 1);
1564    }
1565
1566    #[test]
1567    fn built_trees_merge_text_after_a_parsed_shape() {
1568        // A built tree has no source: all its texts are copied, and adjacent text merges
1569        // even after other copied texts.
1570        let mut builder = TreeBuilder::new();
1571        builder.start_element(QName::local("e")).unwrap();
1572        builder.attribute(QName::local("a"), "v").unwrap();
1573        builder.comment("c").unwrap();
1574        builder.text("x").unwrap();
1575        builder.text("y").unwrap();
1576        builder.processing_instruction("t", "d").unwrap();
1577        builder.text("z").unwrap();
1578        builder.end_element().unwrap();
1579        let tree = builder.finish(None, None).unwrap();
1580        let e = tree.root().children().next().unwrap();
1581        let children: Vec<_> = e
1582            .children()
1583            .map(|c| (c.kind(), c.string_value().into_owned()))
1584            .collect();
1585        assert_eq!(
1586            children,
1587            [
1588                (NodeKind::Comment, "c".to_owned()),
1589                (NodeKind::Text, "xy".to_owned()),
1590                (NodeKind::ProcessingInstruction, "d".to_owned()),
1591                (NodeKind::Text, "z".to_owned()),
1592            ]
1593        );
1594        assert_eq!(tree.text, "vcxydz");
1595    }
1596
1597    #[test]
1598    fn file_uris() {
1599        if cfg!(windows) {
1600            return;
1601        }
1602        assert_eq!(
1603            file_uri(Path::new("/a b/c,d%é#[1]\u{a0}.xml")).as_deref(),
1604            Some("file:/a%20b/c,d%25é%23%5B1%5D%C2%A0.xml")
1605        );
1606        assert_eq!(file_uri(Path::new("rel.xml")), None);
1607    }
1608}