mod eval;
mod index;
mod lexer;
mod parser;
use std::borrow::Cow;
use std::fmt;
use parsec::{Document, NodeId};
pub use eval::{Args, WORK_LIMIT};
pub use index::{CDATA, COMMENT, DOCTYPE, DOCUMENT, ELEMENT, Index, PI, TEXT};
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),
}
pub trait Namespaces: Sync {
fn ns_of(&self, element: NodeId) -> u32;
fn uri(&self, id: u32) -> &str;
fn id_of(&self, uri: &str) -> Option<u32>;
}
#[derive(Clone, Copy)]
pub struct Doc<'a> {
pub(crate) tree: &'a Document,
pub(crate) index: &'a Index,
pub(crate) names: Option<&'a dyn Namespaces>,
}
impl<'a> Doc<'a> {
pub fn html(tree: &'a Document, index: &'a Index) -> Doc<'a> {
Doc {
tree,
index,
names: None,
}
}
pub fn xml(tree: &'a Document, index: &'a Index, names: &'a dyn Namespaces) -> Doc<'a> {
Doc {
tree,
index,
names: Some(names),
}
}
pub fn tree(&self) -> &'a Document {
self.tree
}
pub fn is_xml(&self) -> bool {
self.names.is_some()
}
pub fn attr(&self, node: NodeId, name: &str) -> Option<&'a str> {
let mut attrs = self.tree.attrs(node);
if self.is_xml() {
return attrs.find(|(_, n, _)| *n == name).map(|(_, _, v)| v);
}
attrs
.find(|(_, n, _)| n.eq_ignore_ascii_case(name))
.map(|(_, _, v)| v)
}
pub fn attr_at(&self, owner: NodeId, index: u32) -> (&'a str, &'a str) {
self.tree
.attrs(owner)
.nth(index as usize)
.map_or(("", ""), |(_, name, value)| (name, value))
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Item {
Node(NodeId),
Attr {
owner: NodeId,
index: u32,
ns: u32,
},
}
const _: () = assert!(std::mem::size_of::<Item>() == 16);
#[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}"),
});
}
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>();
};