mod eval;
#[cfg(feature = "html")]
mod html;
mod index;
mod lexer;
mod parser;
mod tree;
use std::borrow::Cow;
use std::fmt;
#[cfg(feature = "html")]
use parsec::Document;
pub use eval::{Args, WORK_LIMIT};
#[cfg(feature = "html")]
pub use html::{Namespaces, XmlTree};
pub use index::{CDATA, COMMENT, DOCTYPE, DOCUMENT, ELEMENT, Index, PI, TEXT};
pub use tree::{Attr, NodeId, NodeType, TagKey, Tree};
pub const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct XPathError {
pub query: String,
pub reason: String,
}
impl fmt::Display for XPathError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid XPath {:?}: {}", self.query, self.reason)
}
}
impl std::error::Error for XPathError {}
#[derive(Debug, Clone, PartialEq)]
pub enum XValue {
Str(String),
Num(f64),
Bool(bool),
}
#[derive(Clone, Copy)]
pub struct Doc<'a> {
pub(crate) tree: &'a dyn Tree,
pub(crate) index: &'a Index,
xml: bool,
}
impl<'a> Doc<'a> {
pub fn new(tree: &'a dyn Tree, index: &'a Index) -> Doc<'a> {
Doc {
tree,
index,
xml: tree.is_xml(),
}
}
#[cfg(feature = "html")]
pub fn html(tree: &'a Document, index: &'a Index) -> Doc<'a> {
Doc::new(tree, index)
}
pub fn tree(&self) -> &'a dyn Tree {
self.tree
}
pub fn is_xml(&self) -> bool {
self.xml
}
pub fn attr(&self, node: NodeId, name: &str) -> Option<&'a str> {
let (tree, xml) = (self.tree, self.xml);
(0..tree.attribute_count(node))
.filter_map(|i| tree.attribute(node, i))
.find(|a| {
if xml {
a.qualified_name == name
} else {
a.qualified_name.eq_ignore_ascii_case(name)
}
})
.map(|a| a.value)
}
pub fn attr_at(&self, owner: NodeId, index: u32) -> (&'a str, &'a str) {
self.tree
.attribute(owner, index)
.map_or(("", ""), |a| (a.qualified_name, a.value))
}
pub fn namespace_at(&self, decl: u32) -> (&'a str, &'a str) {
if decl == XML_DECL {
return ("xml", XML_NS);
}
let (scopes, _) = self.index.scopes(self.tree);
scopes
.decls
.get(decl as usize)
.and_then(|d| self.tree.namespace_declaration(d.node, d.index))
.unwrap_or(("", ""))
}
}
pub const XML_DECL: u32 = u32::MAX;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Item {
Node(NodeId),
Attr {
owner: NodeId,
index: u32,
},
Ns {
owner: NodeId,
decl: u32,
},
}
const _: () = assert!(std::mem::size_of::<Item>() == 12);
#[derive(Debug, Clone)]
pub enum Value<'a> {
Nodes(Vec<Item>),
Str(Cow<'a, str>),
Num(f64),
Bool(bool),
}
pub trait Extensions: Sync {
fn call<'a>(&self, name: &str, args: &Args<'_, 'a>) -> Option<Result<Value<'a>, String>>;
fn scalar(&self, _name: &str) -> bool {
false
}
}
pub struct NoExtensions;
impl Extensions for NoExtensions {
fn call<'a>(&self, _: &str, _: &Args<'_, 'a>) -> Option<Result<Value<'a>, String>> {
None
}
}
#[derive(Debug, Clone)]
pub struct XPath {
src: String,
expr: parser::Expr,
variables: Vec<String>,
}
impl XPath {
pub fn new(src: &str) -> Result<XPath, XPathError> {
XPath::with_extensions(src, &NoExtensions)
}
pub fn with_extensions(src: &str, extensions: &dyn Extensions) -> Result<XPath, XPathError> {
let tokens = lexer::tokenize(src)?;
let mut expr = parser::parse(src, tokens)?;
parser::memoize(&mut expr, &|name| extensions.scalar(name));
let mut variables = Vec::new();
expr.variables(&mut variables);
Ok(XPath {
src: src.to_string(),
expr,
variables,
})
}
pub fn source(&self) -> &str {
&self.src
}
pub fn evaluate<'a>(
&self,
doc: Doc<'a>,
scope: NodeId,
vars: &[(String, XValue)],
namespaces: &[(String, String)],
extensions: &dyn Extensions,
) -> Result<Value<'a>, XPathError> {
self.evaluate_within(doc, scope, vars, namespaces, extensions, WORK_LIMIT)
}
pub fn evaluate_within<'a>(
&self,
doc: Doc<'a>,
scope: NodeId,
vars: &[(String, XValue)],
namespaces: &[(String, String)],
extensions: &dyn Extensions,
limit: u64,
) -> Result<Value<'a>, XPathError> {
if let Some(missing) = self
.variables
.iter()
.find(|v| !vars.iter().any(|(k, _)| k == *v))
{
return Err(XPathError {
query: self.src.clone(),
reason: format!("no value given for ${missing}"),
});
}
let index = doc.index;
let at = index.order(scope);
if (scope as usize) >= doc.tree.len()
|| !index.covers(doc.tree)
|| at == u32::MAX
|| index.node_at(at) != scope
{
return Err(XPathError {
query: self.src.clone(),
reason: format!(
"node {scope} isn't in the index: it was built for another document, \
or before the node was made, or without the node's tree"
),
});
}
eval::run(&self.expr, doc, scope, vars, namespaces, extensions, limit).map_err(|reason| {
XPathError {
query: self.src.clone(),
reason,
}
})
}
}
const _: () = {
const fn shareable<T: Send + Sync>() {}
shareable::<XPath>();
shareable::<Index>();
};