Skip to main content

parsec_xml/
xpath_tree.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! A [`Document`] as a tree XPath can query, with the `xpath` feature.
5
6use parsec_xpath::{Attr, NodeId as Id, NodeType, TagKey, Tree};
7
8use crate::tree::{AttrData, Data, Document, NS_XMLNS, NodeId};
9
10/// The elements that declare namespaces, where their declarations are and
11/// where their other attributes are, so XPath reads an attribute or a
12/// declaration by place in constant time on them too. Few elements declare
13/// namespaces, so this is small: built once, on the first query that reads
14/// an attribute or a declaration, in one pass over the attributes.
15#[derive(Debug, Default)]
16pub(crate) struct Declared {
17    /// Node ids, ascending.
18    elements: Vec<u32>,
19    /// Where each element's run of `positions` starts, and one past the
20    /// last element's.
21    starts: Vec<u32>,
22    /// Indexes into `Document::attrs`.
23    positions: Vec<u32>,
24    /// The same for the declarations: `decl_starts` into `decls`.
25    decl_starts: Vec<u32>,
26    decls: Vec<u32>,
27    /// The elements with an `xml:lang`, ascending, and its index into
28    /// `Document::attrs`: `lang()` reads it from an attribute's owner, so
29    /// a scan of the owner's attributes would make `@*[lang('en')]`
30    /// quadratic on one wide element.
31    langs: Vec<(u32, u32)>,
32}
33
34impl Declared {
35    fn build(doc: &Document) -> Declared {
36        let mut d = Declared::default();
37        let xml_lang = doc.names.get("xml:lang");
38        for (n, node) in doc.nodes.iter().enumerate() {
39            let Data::Element {
40                attrs, attrs_len, ..
41            } = node.data
42            else {
43                continue;
44            };
45            let range = attrs..attrs + attrs_len;
46            let own = &doc.attrs[range.start as usize..range.end as usize];
47            if let Some(at) = own.iter().position(|a| Some(a.name) == xml_lang) {
48                d.langs.push((n as u32, attrs + at as u32));
49            }
50            if !own.iter().any(|a| a.ns == NS_XMLNS) {
51                continue;
52            }
53            d.elements.push(n as u32);
54            d.starts.push(d.positions.len() as u32);
55            d.positions.extend(
56                range
57                    .clone()
58                    .filter(|&i| doc.attrs[i as usize].ns != NS_XMLNS),
59            );
60            d.decl_starts.push(d.decls.len() as u32);
61            d.decls
62                .extend(range.filter(|&i| doc.attrs[i as usize].ns == NS_XMLNS));
63        }
64        d.starts.push(d.positions.len() as u32);
65        d.decl_starts.push(d.decls.len() as u32);
66        d
67    }
68}
69
70enum Attrs<'d> {
71    Run(std::ops::Range<usize>),
72    Picked(&'d [u32]),
73}
74
75impl Document {
76    fn element(&self, n: Id) -> Option<(u32, u32)> {
77        match self.nodes[n as usize].data {
78            Data::Element { name, ns, .. } => Some((name, ns)),
79            _ => None,
80        }
81    }
82
83    fn declared(&self) -> &Declared {
84        self.xpath_attrs.get_or_init(|| Declared::build(self))
85    }
86
87    /// The element's attributes as a range of `self.attrs`.
88    fn attr_range(&self, n: Id) -> std::ops::Range<usize> {
89        match self.nodes[n as usize].data {
90            Data::Element {
91                attrs, attrs_len, ..
92            } => attrs as usize..(attrs + attrs_len) as usize,
93            _ => 0..0,
94        }
95    }
96
97    /// Where in `self.attrs` the element's attributes are, as XPath sees
98    /// them: its own run of them, or, on an element that declares
99    /// namespaces, the declarations left out.
100    fn xpath_attrs(&self, n: Id) -> Attrs<'_> {
101        let range = self.attr_range(n);
102        if !self.namespaces || range.is_empty() {
103            return Attrs::Run(range);
104        }
105        let declared = self.declared();
106        match declared.elements.binary_search(&n) {
107            Ok(k) => {
108                let (a, b) = (declared.starts[k], declared.starts[k + 1]);
109                Attrs::Picked(&declared.positions[a as usize..b as usize])
110            }
111            Err(_) => Attrs::Run(range),
112        }
113    }
114
115    /// Where in `self.attrs` the element's `xmlns` and `xmlns:*`
116    /// attributes are, in the order written.
117    fn declarations(&self, n: Id) -> &[u32] {
118        if !self.namespaces || self.attr_range(n).is_empty() {
119            return &[];
120        }
121        let declared = self.declared();
122        match declared.elements.binary_search(&n) {
123            Ok(k) => {
124                let (a, b) = (declared.decl_starts[k], declared.decl_starts[k + 1]);
125                &declared.decls[a as usize..b as usize]
126            }
127            Err(_) => &[],
128        }
129    }
130
131    fn xpath_attr(&self, n: Id, i: u32) -> Option<&AttrData> {
132        let at = match self.xpath_attrs(n) {
133            Attrs::Run(r) => r.start.checked_add(i as usize).filter(|&at| at < r.end)?,
134            Attrs::Picked(p) => *p.get(i as usize)? as usize,
135        };
136        Some(&self.attrs[at])
137    }
138
139    /// `n`, or the sibling `step` gives if `n` is the doctype: XPath's
140    /// data model has no node for it, so the links XPath reads go round it.
141    fn past_doctype(&self, n: NodeId, step: fn(&Document, NodeId) -> Option<NodeId>) -> Option<Id> {
142        match self.nodes[n.index()].data {
143            Data::Doctype => step(self, n).map(|s| s.0),
144            _ => Some(n.0),
145        }
146    }
147}
148
149/// Names compare exactly, prefixes resolve to the namespaces the document
150/// declared, and namespace declarations are namespace nodes, not
151/// attributes. With namespaces off ([`crate::Options::namespaces`]), every
152/// name is its own local name in no namespace and `xmlns` attributes are
153/// attributes like any other.
154/// The doctype isn't in the tree XPath reads, as XPath's data model has
155/// no node for it. An [`EntityRef`](crate::NodeKind::EntityRef) is a node
156/// XPath has no kind for, so no node test matches it.
157impl Tree for Document {
158    fn len(&self) -> usize {
159        self.nodes.len()
160    }
161
162    fn kind(&self, n: Id) -> NodeType {
163        match self.nodes[n as usize].data {
164            Data::Document => NodeType::Document,
165            Data::Doctype => NodeType::Doctype,
166            Data::Element { .. } => NodeType::Element,
167            Data::Text(_) => NodeType::Text,
168            Data::Cdata(_) => NodeType::Cdata,
169            Data::Comment(_) => NodeType::Comment,
170            Data::Pi { .. } => NodeType::ProcessingInstruction,
171            Data::EntityRef(_) => NodeType::Other,
172        }
173    }
174
175    fn parent(&self, n: Id) -> Option<Id> {
176        Document::parent(self, NodeId(n)).map(|p| p.0)
177    }
178
179    fn first_child(&self, n: Id) -> Option<Id> {
180        let first = Document::first_child(self, NodeId(n))?;
181        self.past_doctype(first, Document::next_sibling)
182    }
183
184    fn next_sibling(&self, n: Id) -> Option<Id> {
185        let next = Document::next_sibling(self, NodeId(n))?;
186        self.past_doctype(next, Document::next_sibling)
187    }
188
189    fn prev_sibling(&self, n: Id) -> Option<Id> {
190        let prev = Document::prev_sibling(self, NodeId(n))?;
191        self.past_doctype(prev, Document::prev_sibling)
192    }
193
194    fn qualified_name(&self, n: Id) -> &str {
195        self.element(n)
196            .map_or("", |(name, _)| self.names.qname_str(name))
197    }
198
199    fn local_name(&self, n: Id) -> &str {
200        self.element(n)
201            .map_or("", |(name, _)| self.names.local(name))
202    }
203
204    fn namespace_uri(&self, n: Id) -> &str {
205        self.element(n).map_or("", |(_, ns)| self.names.uri_str(ns))
206    }
207
208    fn tag_key(&self, n: Id) -> TagKey<'_> {
209        TagKey::Name(self.local_name(n))
210    }
211
212    fn attribute_count(&self, n: Id) -> u32 {
213        match self.xpath_attrs(n) {
214            Attrs::Run(r) => r.len() as u32,
215            Attrs::Picked(p) => p.len() as u32,
216        }
217    }
218
219    fn attribute(&self, n: Id, i: u32) -> Option<Attr<'_>> {
220        let a = self.xpath_attr(n, i)?;
221        let q = self.names.qname_info(a.name);
222        Some(Attr {
223            qualified_name: &q.qname,
224            local_name: self.names.local(a.name),
225            namespace_uri: self.names.uri_str(a.ns),
226            value: self.str(a.value),
227        })
228    }
229
230    fn namespace_declaration_count(&self, n: Id) -> u32 {
231        self.declarations(n).len() as u32
232    }
233
234    /// `xmlns=""` comes back with an empty URI, which takes the default
235    /// namespace away; parsec-xpath leaves no namespace node for it.
236    fn namespace_declaration(&self, n: Id, i: u32) -> Option<(&str, &str)> {
237        let a = &self.attrs[*self.declarations(n).get(i as usize)? as usize];
238        let prefix = match self.names.qname_str(a.name) {
239            "xmlns" => "",
240            _ => self.names.local(a.name),
241        };
242        Some((prefix, self.str(a.value)))
243    }
244
245    fn data(&self, n: Id) -> &str {
246        match self.nodes[n as usize].data {
247            Data::Text(s) | Data::Cdata(s) | Data::Comment(s) | Data::Pi { data: s, .. } => {
248                self.str(s)
249            }
250            _ => "",
251        }
252    }
253
254    fn pi_target(&self, n: Id) -> Option<&str> {
255        match self.nodes[n as usize].data {
256            Data::Pi { target, .. } => Some(self.str(target)),
257            _ => None,
258        }
259    }
260
261    fn is_xml(&self) -> bool {
262        true
263    }
264
265    fn id(&self, n: Id) -> Option<&str> {
266        let (name, _) = self.element(n)?;
267        if let Some(v) = self.attribute_named(NodeId(n), "xml:id") {
268            return Some(v);
269        }
270        let declared = *self.id_attrs.get(&name)?;
271        self.attrs[self.attr_range(n)]
272            .iter()
273            .find(|a| a.name == declared)
274            .map(|a| self.str(a.value))
275    }
276
277    fn lang(&self, n: Id) -> Option<&str> {
278        self.element(n)?;
279        let langs = &self.declared().langs;
280        let k = langs.binary_search_by_key(&n, |&(e, _)| e).ok()?;
281        Some(self.str(self.attrs[langs[k].1 as usize].value))
282    }
283}