parsec_xpath/lib.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! XPath 1.0 over any document tree that implements [`Tree`], written
5//! from the W3C recommendation: every axis, node test and function of the
6//! core library, with the number, string and boolean rules of sections 3
7//! and 4.
8//!
9//! With the default `html` feature, parsec-web's [`Document`] is a
10//! [`Tree`], read as lxml reads an HTML page, which is what scrapers
11//! expect: element and attribute names are the parser's lowercase ones
12//! (SVG's `clippath`, `viewbox`) in no namespace, so `//div` and `@href`
13//! match, `//DIV` and `@HREF` don't, and a prefixed name (`svg:rect`)
14//! matches nothing. An XML document built into the same tree is read
15//! through [`XmlTree`], which takes its namespaces from the host. In XML,
16//! names with a prefix take theirs from the prefixes a query is run with.
17//!
18//! A query reads the document through an [`Index`], which its owner
19//! builds once per version of the tree. Functions beyond the core library
20//! come from the caller through [`Extensions`].
21//!
22//! Shadow roots are left out, as `document.evaluate` leaves them out: the
23//! XPath data model has no shadow trees, so the axes follow the node tree
24//! and never cross into a host's shadow root or out of one. A shadow tree
25//! is queried on its own by indexing its root as one of [`Index::build`]'s
26//! roots, where it's a root node as a template's contents are: `/` from
27//! inside it is the shadow root, and its host isn't an ancestor.
28
29mod eval;
30#[cfg(feature = "html")]
31mod html;
32mod index;
33mod lexer;
34mod parser;
35mod tree;
36
37use std::borrow::Cow;
38use std::fmt;
39
40#[cfg(feature = "html")]
41use parsec::Document;
42
43pub use eval::{Args, WORK_LIMIT};
44#[cfg(feature = "html")]
45pub use html::{Namespaces, XmlTree};
46pub use index::{CDATA, COMMENT, DOCTYPE, DOCUMENT, ELEMENT, Index, PI, TEXT};
47pub use tree::{Attr, NodeId, NodeType, TagKey, Tree};
48
49/// The namespace the `xml` prefix is always bound to.
50pub const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
51
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct XPathError {
54 pub query: String,
55 pub reason: String,
56}
57
58impl fmt::Display for XPathError {
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 write!(f, "invalid XPath {:?}: {}", self.query, self.reason)
61 }
62}
63
64impl std::error::Error for XPathError {}
65
66/// A value a caller can bind to a `$variable`.
67#[derive(Debug, Clone, PartialEq)]
68pub enum XValue {
69 Str(String),
70 Num(f64),
71 Bool(bool),
72}
73
74/// The document a query runs over: its tree and the tree's index.
75#[derive(Clone, Copy)]
76pub struct Doc<'a> {
77 pub(crate) tree: &'a dyn Tree,
78 pub(crate) index: &'a Index,
79 /// The tree's [`Tree::is_xml`], read once rather than on every name.
80 xml: bool,
81}
82
83impl<'a> Doc<'a> {
84 /// `index` must be of `tree` as it is now.
85 pub fn new(tree: &'a dyn Tree, index: &'a Index) -> Doc<'a> {
86 Doc {
87 tree,
88 index,
89 xml: tree.is_xml(),
90 }
91 }
92
93 /// An HTML page. `index` must be of `tree` as it is now.
94 #[cfg(feature = "html")]
95 pub fn html(tree: &'a Document, index: &'a Index) -> Doc<'a> {
96 Doc::new(tree, index)
97 }
98
99 pub fn tree(&self) -> &'a dyn Tree {
100 self.tree
101 }
102
103 pub fn is_xml(&self) -> bool {
104 self.xml
105 }
106
107 /// An attribute's value by name: exact in XML, and in HTML compared
108 /// ignoring ASCII case, as HTML names are lowercase.
109 pub fn attr(&self, node: NodeId, name: &str) -> Option<&'a str> {
110 let (tree, xml) = (self.tree, self.xml);
111 (0..tree.attribute_count(node))
112 .filter_map(|i| tree.attribute(node, i))
113 .find(|a| {
114 if xml {
115 a.qualified_name == name
116 } else {
117 a.qualified_name.eq_ignore_ascii_case(name)
118 }
119 })
120 .map(|a| a.value)
121 }
122
123 /// The name (as written, with any prefix) and value of the `index`th
124 /// attribute of `owner`, as an [`Item::Attr`] names it.
125 pub fn attr_at(&self, owner: NodeId, index: u32) -> (&'a str, &'a str) {
126 self.tree
127 .attribute(owner, index)
128 .map_or(("", ""), |a| (a.qualified_name, a.value))
129 }
130
131 /// The prefix ("" for the default namespace) and URI of the namespace
132 /// node an [`Item::Ns`] with this `decl` names.
133 pub fn namespace_at(&self, decl: u32) -> (&'a str, &'a str) {
134 if decl == XML_DECL {
135 return ("xml", XML_NS);
136 }
137 let (scopes, _) = self.index.scopes(self.tree);
138 scopes
139 .decls
140 .get(decl as usize)
141 .and_then(|d| self.tree.namespace_declaration(d.node, d.index))
142 .unwrap_or(("", ""))
143 }
144}
145
146/// The `decl` of an [`Item::Ns`] for the `xml` namespace, which every
147/// element has.
148pub const XML_DECL: u32 = u32::MAX;
149
150/// A node in XPath's data model: a tree node, or an attribute or
151/// namespace node (which the tree keeps on its element rather than as a
152/// node of its own). Twelve bytes: a node-set can hold every node of a big
153/// page, so its name, namespace and value are read from the tree
154/// ([`Tree::attribute`], [`Doc::namespace_at`]), not kept here.
155#[derive(Debug, Clone, Copy, PartialEq)]
156pub enum Item {
157 Node(NodeId),
158 Attr {
159 owner: NodeId,
160 /// Its place among the element's attributes.
161 index: u32,
162 },
163 /// A namespace in scope at an element, from `namespace::`.
164 Ns {
165 /// The element: the namespace node's parent.
166 owner: NodeId,
167 /// Which declaration binds it, numbered by the index;
168 /// [`XML_DECL`] for the `xml` namespace.
169 decl: u32,
170 },
171}
172
173const _: () = assert!(std::mem::size_of::<Item>() == 12);
174
175/// What an expression evaluates to. A node-set is in document order,
176/// without duplicates.
177#[derive(Debug, Clone)]
178pub enum Value<'a> {
179 Nodes(Vec<Item>),
180 Str(Cow<'a, str>),
181 Num(f64),
182 Bool(bool),
183}
184
185/// Functions beyond XPath 1.0's core library, which a caller provides. A
186/// core function of the same name wins.
187pub trait Extensions: Sync {
188 /// Works out `name()`, or None if this has no function of that name.
189 fn call<'a>(&self, name: &str, args: &Args<'_, 'a>) -> Option<Result<Value<'a>, String>>;
190
191 /// Whether `name()` only ever gives a number or a yes or no, so a
192 /// predicate's call of it can be kept per node (see `memoize`).
193 fn scalar(&self, _name: &str) -> bool {
194 false
195 }
196}
197
198/// No functions beyond the core library.
199pub struct NoExtensions;
200
201impl Extensions for NoExtensions {
202 fn call<'a>(&self, _: &str, _: &Args<'_, 'a>) -> Option<Result<Value<'a>, String>> {
203 None
204 }
205}
206
207/// A compiled XPath expression. It holds no state of any document, so one
208/// can be shared by many threads.
209#[derive(Debug, Clone)]
210pub struct XPath {
211 src: String,
212 expr: parser::Expr,
213 /// The `$variables` the expression uses, found once here rather than
214 /// on every run.
215 variables: Vec<String>,
216}
217
218impl XPath {
219 pub fn new(src: &str) -> Result<XPath, XPathError> {
220 XPath::with_extensions(src, &NoExtensions)
221 }
222
223 /// [`XPath::new`], for running with `extensions`.
224 pub fn with_extensions(src: &str, extensions: &dyn Extensions) -> Result<XPath, XPathError> {
225 let tokens = lexer::tokenize(src)?;
226 let mut expr = parser::parse(src, tokens)?;
227 parser::memoize(&mut expr, &|name| extensions.scalar(name));
228 let mut variables = Vec::new();
229 expr.variables(&mut variables);
230 Ok(XPath {
231 src: src.to_string(),
232 expr,
233 variables,
234 })
235 }
236
237 /// The expression as written.
238 pub fn source(&self) -> &str {
239 &self.src
240 }
241
242 /// Evaluates with `scope` as the context node, `vars` giving the
243 /// `$variables` and `namespaces` binding prefixes to URIs as
244 /// `(prefix, uri)` (a later pair for a prefix wins). `extensions`
245 /// should be what the expression was compiled with.
246 pub fn evaluate<'a>(
247 &self,
248 doc: Doc<'a>,
249 scope: NodeId,
250 vars: &[(String, XValue)],
251 namespaces: &[(String, String)],
252 extensions: &dyn Extensions,
253 ) -> Result<Value<'a>, XPathError> {
254 self.evaluate_within(doc, scope, vars, namespaces, extensions, WORK_LIMIT)
255 }
256
257 /// [`XPath::evaluate`], giving up after `limit` units of work rather
258 /// than [`WORK_LIMIT`].
259 pub fn evaluate_within<'a>(
260 &self,
261 doc: Doc<'a>,
262 scope: NodeId,
263 vars: &[(String, XValue)],
264 namespaces: &[(String, String)],
265 extensions: &dyn Extensions,
266 limit: u64,
267 ) -> Result<Value<'a>, XPathError> {
268 if let Some(missing) = self
269 .variables
270 .iter()
271 .find(|v| !vars.iter().any(|(k, _)| k == *v))
272 {
273 return Err(XPathError {
274 query: self.src.clone(),
275 reason: format!("no value given for ${missing}"),
276 });
277 }
278 // An index of another document, or one older than a node in it,
279 // would send the walk past its tables.
280 let index = doc.index;
281 let at = index.order(scope);
282 if (scope as usize) >= doc.tree.len()
283 || !index.covers(doc.tree)
284 || at == u32::MAX
285 || index.node_at(at) != scope
286 {
287 return Err(XPathError {
288 query: self.src.clone(),
289 reason: format!(
290 "node {scope} isn't in the index: it was built for another document, \
291 or before the node was made, or without the node's tree"
292 ),
293 });
294 }
295 eval::run(&self.expr, doc, scope, vars, namespaces, extensions, limit).map_err(|reason| {
296 XPathError {
297 query: self.src.clone(),
298 reason,
299 }
300 })
301 }
302}
303
304// A compiled expression is shared between threads; this fails the build
305// if a change ever stops that.
306const _: () = {
307 const fn shareable<T: Send + Sync>() {}
308 shareable::<XPath>();
309 shareable::<Index>();
310};