parsec_xpath/index.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! A flat index of a document's nodes in document order. A node's
5//! descendants are the contiguous range after it, so scanning them is a
6//! pass over small arrays rather than a walk through the tree's links.
7
8use std::collections::HashMap;
9use std::sync::OnceLock;
10
11use crate::tree::{NodeId, NodeType, TagKey, Tree};
12
13/// The node kinds, as the index stores them: the DOM's nodeType numbers.
14pub const ELEMENT: u8 = NodeType::Element as u8;
15pub const TEXT: u8 = NodeType::Text as u8;
16pub const CDATA: u8 = NodeType::Cdata as u8;
17pub const PI: u8 = NodeType::ProcessingInstruction as u8;
18pub const COMMENT: u8 = NodeType::Comment as u8;
19pub const DOCUMENT: u8 = NodeType::Document as u8;
20pub const DOCTYPE: u8 = NodeType::Doctype as u8;
21
22/// The index of one version of a tree. Its owner builds it once and keeps
23/// it until the tree changes: every query reads it, none builds it.
24pub struct Index {
25 raw: Vec<u32>,
26 /// Each node's parent's position; u32::MAX for the root.
27 parent: Vec<u32>,
28 /// One past the last descendant of each node.
29 end: Vec<u32>,
30 kind: Vec<u8>,
31 /// u32, as node ids are: one for every node adds up on a big page.
32 /// 0 for a node that isn't an element.
33 tag: Vec<u32>,
34 /// Each node's position, by node id; u32::MAX for one not indexed.
35 order: Vec<u32>,
36 /// Tag ids by lowercase name, from 1.
37 names: HashMap<String, usize>,
38 /// Positions of the elements carrying each `id`, built on first use.
39 ids: OnceLock<HashMap<String, Vec<u32>>>,
40 /// The namespace declarations, built on the namespace axis's first use.
41 scopes: OnceLock<Scopes>,
42}
43
44/// Where a tree declares namespaces, for the namespace axis. Each node
45/// that declares some is a block, and every other node is in the block of
46/// the nearest one above it, so working out what's in scope at a node
47/// climbs only through nodes that declare something.
48pub(crate) struct Scopes {
49 /// The block of the node at each position; u32::MAX for none.
50 block_at: Vec<u32>,
51 pub(crate) blocks: Vec<Block>,
52 /// Every declaration, numbered as the namespace axis orders them.
53 pub(crate) decls: Vec<Decl>,
54 /// How many different prefixes there are.
55 pub(crate) prefixes: usize,
56}
57
58/// A node's declarations: `decls[first..first + len]`, and the block
59/// above it.
60pub(crate) struct Block {
61 pub(crate) first: u32,
62 pub(crate) len: u32,
63 pub(crate) parent: u32,
64}
65
66pub(crate) struct Decl {
67 /// The declaring node, and the declaration's place among its own.
68 pub(crate) node: NodeId,
69 pub(crate) index: u32,
70 /// The prefix, numbered from 0 by [`Scopes`].
71 pub(crate) prefix: u32,
72 /// `xmlns=""` or `xmlns:p=""`, which takes a binding away.
73 pub(crate) undeclares: bool,
74}
75
76impl Scopes {
77 /// The block in effect at position `at`; u32::MAX for none.
78 pub(crate) fn block_at(&self, at: u32) -> u32 {
79 self.block_at.get(at as usize).copied().unwrap_or(u32::MAX)
80 }
81}
82
83/// The tag id of the lowercase name `key`, given the next free one if new.
84fn tag_id(names: &mut HashMap<String, usize>, key: String) -> u32 {
85 let next = names.len() + 1;
86 *names.entry(key).or_insert(next) as u32
87}
88
89impl Index {
90 /// Indexes the tree under each of `roots` in turn: the document, then
91 /// any subtrees removed from it or built apart from it, so every node
92 /// a caller can hold has a position.
93 ///
94 /// Generic, unlike a query's reading of the tree: building reads every
95 /// node, and a call through `dyn` for each read showed in benchmarks.
96 pub fn build<T: Tree + ?Sized>(tree: &T, roots: &[NodeId]) -> Index {
97 let mut raw = Vec::with_capacity(tree.len());
98 let mut parent = Vec::with_capacity(tree.len());
99 let mut kind = Vec::with_capacity(tree.len());
100 let mut tag = Vec::with_capacity(tree.len());
101 let mut order = vec![u32::MAX; tree.len()];
102 let mut names: HashMap<String, usize> = HashMap::new();
103 // Tag ids by the tree's own tag number, 0 for one not yet seen.
104 let mut known: Vec<u32> = Vec::new();
105 for &root in roots {
106 // Preorder by the tree's links, keeping each node's parent's
107 // position on a stack of the open ancestors.
108 let mut ancestors: Vec<u32> = Vec::new();
109 let mut at = Some(root);
110 while let Some(n) = at {
111 let pos = raw.len() as u32;
112 order[n as usize] = pos;
113 raw.push(n);
114 parent.push(ancestors.last().copied().unwrap_or(u32::MAX));
115 let k = tree.kind(n) as u8;
116 kind.push(k);
117 // From the lowercase name alone, as tag_id_named works it
118 // out: an XML <title> shares HTML title's id.
119 tag.push(if k != ELEMENT {
120 0
121 } else {
122 match tree.tag_key(n) {
123 TagKey::Known(t) => {
124 let t = t as usize;
125 match known.get(t) {
126 Some(&id) if id != 0 => id,
127 _ => {
128 let key = tree.local_name(n).to_ascii_lowercase();
129 let id = tag_id(&mut names, key);
130 if known.len() <= t {
131 known.resize(t + 1, 0);
132 }
133 known[t] = id;
134 id
135 }
136 }
137 }
138 TagKey::Name(name) => tag_id(&mut names, name.to_ascii_lowercase()),
139 }
140 });
141 at = match tree.first_child(n) {
142 Some(child) => {
143 ancestors.push(pos);
144 Some(child)
145 }
146 None => {
147 let mut up = n;
148 loop {
149 if up == root {
150 break None;
151 }
152 if let Some(s) = tree.next_sibling(up) {
153 break Some(s);
154 }
155 up = tree
156 .parent(up)
157 .expect("a node inside the root has a parent");
158 ancestors.pop();
159 }
160 }
161 };
162 }
163 }
164 let n = raw.len();
165 // Children come after their parent, so one backward pass carries
166 // each subtree's end up to its parent.
167 let mut end: Vec<u32> = (1..=n as u32).collect();
168 for i in (1..n).rev() {
169 let p = parent[i] as usize;
170 if p < n && end[i] > end[p] {
171 end[p] = end[i];
172 }
173 }
174 Index {
175 raw,
176 parent,
177 end,
178 kind,
179 tag,
180 order,
181 names,
182 ids: OnceLock::new(),
183 scopes: OnceLock::new(),
184 }
185 }
186
187 /// The namespace declarations of `tree`, which must be the tree this
188 /// indexes, and whether this call is the one that read them: one pass
189 /// over the nodes, done once per index.
190 pub(crate) fn scopes(&self, tree: &dyn Tree) -> (&Scopes, bool) {
191 let mut built = false;
192 let scopes = self.scopes.get_or_init(|| {
193 built = true;
194 let mut block_at = Vec::with_capacity(self.raw.len());
195 let mut blocks = Vec::new();
196 let mut decls = Vec::new();
197 let mut prefixes: HashMap<&str, u32> = HashMap::new();
198 for (pos, &n) in self.raw.iter().enumerate() {
199 let up = match self.parent[pos] {
200 u32::MAX => u32::MAX,
201 p => block_at[p as usize],
202 };
203 let count = tree.namespace_declaration_count(n);
204 if count == 0 {
205 block_at.push(up);
206 continue;
207 }
208 let first = decls.len() as u32;
209 // Last written first: the order libxml2, and so lxml, gives
210 // a node's namespaces in.
211 for i in (0..count).rev() {
212 let Some((prefix, uri)) = tree.namespace_declaration(n, i) else {
213 continue;
214 };
215 // `xml` is always in scope, bound to XML_NS, and never
216 // declared twice.
217 if prefix == "xml" {
218 continue;
219 }
220 let next = prefixes.len() as u32;
221 decls.push(Decl {
222 node: n,
223 index: i,
224 prefix: *prefixes.entry(prefix).or_insert(next),
225 undeclares: uri.is_empty(),
226 });
227 }
228 blocks.push(Block {
229 first,
230 len: decls.len() as u32 - first,
231 parent: up,
232 });
233 block_at.push(blocks.len() as u32 - 1);
234 }
235 Scopes {
236 block_at,
237 blocks,
238 decls,
239 prefixes: prefixes.len(),
240 }
241 });
242 (scopes, built)
243 }
244
245 /// Whether the index has a place for every node `tree` has, as it does
246 /// for the document it was built from until a node is made in it.
247 pub fn covers(&self, tree: &dyn Tree) -> bool {
248 self.order.len() == tree.len()
249 }
250
251 /// How many nodes are indexed.
252 pub fn len(&self) -> usize {
253 self.raw.len()
254 }
255
256 pub fn is_empty(&self) -> bool {
257 self.raw.is_empty()
258 }
259
260 /// A node's position; u32::MAX if it was made after the index was.
261 pub fn order(&self, id: NodeId) -> u32 {
262 self.order.get(id as usize).copied().unwrap_or(u32::MAX)
263 }
264
265 /// The node at position `at`.
266 pub fn node_at(&self, at: u32) -> NodeId {
267 self.raw[at as usize]
268 }
269
270 /// The kind ([`ELEMENT`], [`TEXT`] and so on) at position `at`.
271 pub fn kind_at(&self, at: u32) -> u8 {
272 self.kind[at as usize]
273 }
274
275 /// The tag id at position `at`.
276 pub fn tag_at(&self, at: u32) -> usize {
277 self.tag.get(at as usize).map_or(0, |&t| t as usize)
278 }
279
280 /// The tag id elements named `name` (compared lowercased) carry, if
281 /// some element in the index has that name.
282 pub fn tag_id_named(&self, name: &str) -> Option<usize> {
283 self.names.get(&name.to_ascii_lowercase()).copied()
284 }
285
286 /// The elements whose `id` is `id`, in document order. `id_of` reads a
287 /// node's `id` attribute; the first call's is used for every call.
288 pub fn with_id<'t>(&self, id: &str, id_of: impl Fn(NodeId) -> Option<&'t str>) -> Vec<NodeId> {
289 let ids = self.ids.get_or_init(|| {
290 let mut ids: HashMap<String, Vec<u32>> = HashMap::new();
291 for (j, &raw) in self.raw.iter().enumerate() {
292 if let Some(v) = id_of(raw) {
293 ids.entry(v.to_string()).or_default().push(j as u32);
294 }
295 }
296 ids
297 });
298 ids.get(id)
299 .map(|at| at.iter().map(|&j| self.raw[j as usize]).collect())
300 .unwrap_or_default()
301 }
302
303 /// Appends to `out` the nodes below `at` (from `at` itself if
304 /// `include_self`) that pass `keep(kind, tag)`, in document order.
305 pub fn descendants(
306 &self,
307 at: u32,
308 include_self: bool,
309 keep: impl Fn(u8, usize) -> bool,
310 out: &mut Vec<NodeId>,
311 ) {
312 let start = if include_self { at } else { at + 1 } as usize;
313 for j in start..self.end[at as usize] as usize {
314 if keep(self.kind[j], self.tag[j] as usize) {
315 out.push(self.raw[j]);
316 }
317 }
318 }
319
320 /// One past the last descendant of `at`.
321 pub fn end_of(&self, at: u32) -> u32 {
322 self.end[at as usize]
323 }
324
325 /// The position of the parent of the node at `at`; u32::MAX for a
326 /// root.
327 pub fn parent_of(&self, at: u32) -> u32 {
328 self.parent[at as usize]
329 }
330
331 /// Appends to `out` the children of `at` that pass `keep(kind, tag)`.
332 pub fn children(&self, at: u32, keep: impl Fn(u8, usize) -> bool, out: &mut Vec<NodeId>) {
333 let stop = self.end[at as usize] as usize;
334 let mut c = at as usize + 1;
335 while c < stop {
336 if keep(self.kind[c], self.tag[c] as usize) {
337 out.push(self.raw[c]);
338 }
339 c = self.end[c] as usize;
340 }
341 }
342}