use std::collections::{HashMap, HashSet};
use std::hash::{BuildHasherDefault, Hasher};
use ego_tree::NodeId;
use scraper::{ElementRef, Html};
use crate::xpath_syntax::{Axis, Expr, NodeTest, PathStart, Principal, RelOp, Step};
fn decode_cdata(src: &str) -> std::borrow::Cow<'_, str> {
const OPEN: &str = "<![CDATA[";
const CLOSE: &str = "]]>";
if !src.contains(OPEN) {
return std::borrow::Cow::Borrowed(src);
}
let mut out = String::with_capacity(src.len());
let mut rest = src;
while let Some(i) = rest.find(OPEN) {
out.push_str(&rest[..i]);
let after = &rest[i + OPEN.len()..];
match after.find(CLOSE) {
Some(j) => {
out.push_str(&escape_text(&after[..j]));
rest = &after[j + CLOSE.len()..];
}
None => {
out.push_str(&escape_text(after));
rest = "";
}
}
}
out.push_str(rest);
std::borrow::Cow::Owned(out)
}
#[derive(Default)]
struct NodeHasher(u64);
impl Hasher for NodeHasher {
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, bytes: &[u8]) {
for b in bytes {
self.write_u8(*b);
}
}
fn write_u8(&mut self, n: u8) {
self.write_usize(n as usize);
}
fn write_usize(&mut self, n: usize) {
const SEED: u64 = 0x51_7c_c1_b7_27_22_0a_95;
self.0 = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(SEED);
}
}
type NodeMap<V> = HashMap<NodeId, V, BuildHasherDefault<NodeHasher>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum XNode {
Tree(NodeId),
Attr(NodeId, usize),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
Root,
Element,
Text,
Attribute,
Comment,
Pi,
Namespace,
}
pub struct Doc {
html: Html,
order: NodeMap<usize>,
hidden: HashSet<NodeId>,
ordered: Vec<XNode>,
end: NodeMap<usize>,
}
impl Doc {
pub fn parse(src: &str) -> Doc {
let html = Html::parse_document(&decode_cdata(src));
let source_has_tbody = src.to_ascii_lowercase().contains("<tbody");
let mut hidden = HashSet::new();
for n in html.tree.nodes() {
let hide = match n.value() {
scraper::node::Node::Doctype(_) => true,
scraper::node::Node::Element(e) => match e.name() {
"head" => n.children().next().is_none(),
"tbody" => !source_has_tbody,
_ => false,
},
_ => false,
};
if hide {
hidden.insert(n.id());
}
}
let mut order = NodeMap::default();
let mut stack = vec![html.tree.root().id()];
let mut next = 0usize;
while let Some(id) = stack.pop() {
if !hidden.contains(&id) {
order.insert(id, next);
next += 1;
}
let node = html.tree.get(id).expect("id came from this tree");
let kids: Vec<NodeId> = node.children().map(|c| c.id()).collect();
for k in kids.into_iter().rev() {
stack.push(k);
}
}
let mut doc = Doc {
html,
order,
hidden,
ordered: Vec::new(),
end: NodeMap::default(),
};
doc.ordered = doc.build_ordered();
doc.end = doc.build_ends();
doc
}
fn build_ordered(&self) -> Vec<XNode> {
let mut v: Vec<XNode> = self
.order
.keys()
.filter(|id| self.visible(**id))
.map(|id| XNode::Tree(*id))
.collect();
v.sort_by_cached_key(|m| self.key(*m));
v
}
fn build_ends(&self) -> NodeMap<usize> {
let mut end =
NodeMap::with_capacity_and_hasher(self.ordered.len(), BuildHasherDefault::default());
for (i, n) in self.ordered.iter().enumerate().rev() {
let XNode::Tree(id) = *n else { continue };
let mut e = i + 1;
for c in self.children_of(*n) {
if let XNode::Tree(cid) = c {
if let Some(ce) = end.get(&cid) {
e = e.max(*ce);
}
}
}
end.insert(id, e);
}
end
}
fn index_of(&self, n: XNode) -> usize {
match n {
XNode::Tree(id) => *self.order.get(&id).unwrap_or(&0),
XNode::Attr(id, _) => *self.order.get(&id).unwrap_or(&0),
}
}
fn end_of(&self, n: XNode) -> usize {
match n {
XNode::Tree(id) => *self.end.get(&id).unwrap_or(&0),
XNode::Attr(id, _) => *self.end.get(&id).unwrap_or(&0),
}
}
pub fn root(&self) -> XNode {
XNode::Tree(self.html.tree.root().id())
}
fn visible(&self, id: NodeId) -> bool {
!self.hidden.contains(&id)
}
fn key(&self, n: XNode) -> (usize, usize) {
match n {
XNode::Tree(id) => (*self.order.get(&id).unwrap_or(&usize::MAX), 0),
XNode::Attr(id, i) => (*self.order.get(&id).unwrap_or(&usize::MAX), i + 1),
}
}
pub fn kind(&self, n: XNode) -> Kind {
match n {
XNode::Attr(..) => Kind::Attribute,
XNode::Tree(id) => match self.html.tree.get(id).map(|n| n.value()) {
Some(scraper::node::Node::Document | scraper::node::Node::Fragment) => Kind::Root,
Some(scraper::node::Node::Element(_)) => Kind::Element,
Some(scraper::node::Node::Text(_)) => Kind::Text,
Some(scraper::node::Node::Comment(_)) => Kind::Comment,
Some(scraper::node::Node::ProcessingInstruction(_)) => Kind::Pi,
_ => Kind::Root,
},
}
}
pub fn name(&self, n: XNode) -> Option<String> {
match n {
XNode::Attr(id, i) => self.attr_at(id, i).map(|(k, _)| k),
XNode::Tree(id) => match self.html.tree.get(id).map(|n| n.value()) {
Some(scraper::node::Node::Element(e)) => Some(e.name().to_string()),
Some(scraper::node::Node::ProcessingInstruction(p)) => Some(p.target.to_string()),
_ => None,
},
}
}
fn attr_at(&self, id: NodeId, i: usize) -> Option<(String, String)> {
let n = self.html.tree.get(id)?;
let e = n.value().as_element()?;
e.attrs()
.nth(i)
.map(|(k, v)| (k.to_string(), v.to_string()))
}
pub fn string_value(&self, n: XNode) -> String {
match n {
XNode::Attr(id, i) => self.attr_at(id, i).map(|(_, v)| v).unwrap_or_default(),
XNode::Tree(id) => match self.html.tree.get(id).map(|x| x.value()) {
Some(scraper::node::Node::Text(t)) => t.text.to_string(),
Some(scraper::node::Node::Comment(c)) => c.comment.to_string(),
Some(scraper::node::Node::ProcessingInstruction(p)) => p.data.to_string(),
_ => {
let mut s = String::new();
if let Some(node) = self.html.tree.get(id) {
for d in node.descendants() {
if !self.visible(d.id()) {
continue;
}
if let scraper::node::Node::Text(t) = d.value() {
s.push_str(&t.text);
}
}
}
s
}
},
}
}
pub fn render(&self, n: XNode) -> String {
match n {
XNode::Attr(..) => self.string_value(n),
XNode::Tree(id) => match self.html.tree.get(id).map(|x| x.value()) {
Some(scraper::node::Node::Element(_)) => {
if self.subtree_is_clean(id) {
self.html
.tree
.get(id)
.and_then(ElementRef::wrap)
.map(|e| e.html())
.unwrap_or_default()
} else {
let mut out = String::new();
self.write_node(&mut out, id);
out
}
}
Some(scraper::node::Node::Comment(c)) => format!("<!--{}-->", c.comment),
Some(scraper::node::Node::ProcessingInstruction(p)) => {
format!("<?{} {}?>", p.target, p.data)
}
_ => self.string_value(n),
},
}
}
fn subtree_is_clean(&self, id: NodeId) -> bool {
match self.html.tree.get(id) {
Some(n) => n.descendants().all(|d| self.visible(d.id())),
None => true,
}
}
fn write_node(&self, out: &mut String, id: NodeId) {
if !self.visible(id) {
if let Some(n) = self.html.tree.get(id) {
for c in n.children() {
self.write_node(out, c.id());
}
}
return;
}
let Some(node) = self.html.tree.get(id) else {
return;
};
match node.value() {
scraper::node::Node::Text(t) => out.push_str(&escape_text(&t.text)),
scraper::node::Node::Comment(c) => {
out.push_str("<!--");
out.push_str(&c.comment);
out.push_str("-->");
}
scraper::node::Node::ProcessingInstruction(p) => {
out.push_str(&format!("<?{} {}?>", p.target, p.data));
}
scraper::node::Node::Element(e) => {
out.push('<');
out.push_str(e.name());
for (k, v) in e.attrs() {
out.push(' ');
out.push_str(k);
out.push_str("=\"");
out.push_str(&escape_attr(v));
out.push('"');
}
out.push('>');
if is_void(e.name()) {
return;
}
for c in node.children() {
self.write_node(out, c.id());
}
out.push_str("</");
out.push_str(e.name());
out.push('>');
}
_ => {
for c in node.children() {
self.write_node(out, c.id());
}
}
}
}
fn parent_of(&self, n: XNode) -> Option<XNode> {
match n {
XNode::Attr(id, _) => Some(XNode::Tree(id)),
XNode::Tree(id) => {
let mut cur = self.html.tree.get(id)?.parent()?;
while !self.visible(cur.id()) {
cur = cur.parent()?;
}
Some(XNode::Tree(cur.id()))
}
}
}
fn children_of(&self, n: XNode) -> Vec<XNode> {
match n {
XNode::Attr(..) => Vec::new(),
XNode::Tree(id) => {
let Some(node) = self.html.tree.get(id) else {
return Vec::new();
};
let mut out = Vec::new();
for c in node.children() {
if self.visible(c.id()) {
out.push(XNode::Tree(c.id()));
} else {
out.extend(self.children_of(XNode::Tree(c.id())));
}
}
out
}
}
}
fn descendants_of(&self, n: XNode) -> Vec<XNode> {
let mut out = Vec::new();
let mut stack: Vec<XNode> = self.children_of(n).into_iter().rev().collect();
while let Some(c) = stack.pop() {
out.push(c);
for k in self.children_of(c).into_iter().rev() {
stack.push(k);
}
}
out
}
fn ancestors_of(&self, n: XNode) -> Vec<XNode> {
let mut out = Vec::new();
let mut cur = n;
while let Some(p) = self.parent_of(cur) {
out.push(p);
cur = p;
}
out
}
fn siblings(&self, n: XNode, following: bool) -> Vec<XNode> {
let Some(p) = self.parent_of(n) else {
return Vec::new();
};
if matches!(n, XNode::Attr(..)) {
return Vec::new();
}
let kids = self.children_of(p);
let Some(pos) = kids.iter().position(|k| *k == n) else {
return Vec::new();
};
if following {
kids[pos + 1..].to_vec()
} else {
kids[..pos].iter().rev().copied().collect()
}
}
fn following_of(&self, n: XNode) -> Vec<XNode> {
self.ordered
.get(self.end_of(n).min(self.ordered.len())..)
.map(<[XNode]>::to_vec)
.unwrap_or_default()
}
fn preceding_of(&self, n: XNode) -> Vec<XNode> {
let i = self.index_of(n);
let mut out: Vec<XNode> = self.ordered[..i.min(self.ordered.len())]
.iter()
.filter(|m| self.end_of(**m) <= i)
.copied()
.collect();
out.reverse();
out
}
pub fn document_nodes(&self) -> Vec<XNode> {
self.ordered.clone()
}
fn attributes_of(&self, n: XNode) -> Vec<XNode> {
match n {
XNode::Tree(id) => match self.html.tree.get(id).and_then(|x| x.value().as_element()) {
Some(e) => (0..e.attrs().count()).map(|i| XNode::Attr(id, i)).collect(),
None => Vec::new(),
},
XNode::Attr(..) => Vec::new(),
}
}
fn axis(&self, axis: Axis, n: XNode) -> Vec<XNode> {
match axis {
Axis::SelfAxis => vec![n],
Axis::Child => self.children_of(n),
Axis::Parent => self.parent_of(n).into_iter().collect(),
Axis::Descendant => self.descendants_of(n),
Axis::DescendantOrSelf => {
let mut v = vec![n];
v.extend(self.descendants_of(n));
v
}
Axis::Ancestor => self.ancestors_of(n),
Axis::AncestorOrSelf => {
let mut v = vec![n];
v.extend(self.ancestors_of(n));
v
}
Axis::FollowingSibling => self.siblings(n, true),
Axis::PrecedingSibling => self.siblings(n, false),
Axis::Following => self.following_of(n),
Axis::Preceding => self.preceding_of(n),
Axis::Attribute => self.attributes_of(n),
Axis::Namespace => Vec::new(),
}
}
fn passes(&self, test: &NodeTest, axis: Axis, n: XNode) -> bool {
let kind = self.kind(n);
match test {
NodeTest::Node => true,
NodeTest::Text => kind == Kind::Text,
NodeTest::Comment => kind == Kind::Comment,
NodeTest::Pi(target) => {
kind == Kind::Pi
&& match target {
None => true,
Some(t) => self.name(n).as_deref() == Some(t.as_str()),
}
}
NodeTest::Any => principal_kind(axis.principal()) == kind,
NodeTest::AnyInPrefix(_) => {
false
}
NodeTest::Name(want) => {
if principal_kind(axis.principal()) != kind {
return false;
}
match self.name(n) {
Some(got) => got.eq_ignore_ascii_case(want),
None => false,
}
}
}
}
fn lang_of(&self, n: XNode) -> Option<String> {
let mut cur = Some(n);
while let Some(c) = cur {
if let XNode::Tree(id) = c {
if let Some(e) = self.html.tree.get(id).and_then(|x| x.value().as_element()) {
if let Some(v) = e.attr("xml:lang").or_else(|| e.attr("lang")) {
return Some(v.to_string());
}
}
}
cur = self.parent_of(c);
}
None
}
}
fn is_void(name: &str) -> bool {
matches!(
name,
"area"
| "base"
| "basefont"
| "bgsound"
| "br"
| "col"
| "embed"
| "frame"
| "hr"
| "img"
| "input"
| "keygen"
| "link"
| "meta"
| "param"
| "source"
| "track"
| "wbr"
)
}
fn escape_text(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'\u{a0}' => out.push_str(" "),
_ => out.push(c),
}
}
out
}
fn escape_attr(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'"' => out.push_str("""),
'\u{a0}' => out.push_str(" "),
_ => out.push(c),
}
}
out
}
fn principal_kind(p: Principal) -> Kind {
match p {
Principal::Element => Kind::Element,
Principal::Attribute => Kind::Attribute,
Principal::Namespace => Kind::Namespace,
}
}
#[derive(Debug, Clone)]
pub enum Value {
NodeSet(Vec<XNode>),
Str(String),
Num(f64),
Bool(bool),
}
pub fn fmt_number(v: f64) -> String {
if v.is_nan() {
return "NaN".into();
}
if v.is_infinite() {
return if v > 0.0 {
"Infinity".into()
} else {
"-Infinity".into()
};
}
if v == 0.0 {
return "0".into();
}
if v == v.trunc() && v.abs() < 1e21 {
return format!("{}", v as i64);
}
let s = format!("{v}");
if s.contains('e') || s.contains('E') {
let mut t = format!("{v:.17}");
while t.contains('.') && (t.ends_with('0') || t.ends_with('.')) {
t.pop();
}
return t;
}
s
}
impl Value {
pub fn boolean(&self) -> bool {
match self {
Value::Bool(b) => *b,
Value::Num(n) => *n != 0.0 && !n.is_nan(),
Value::Str(s) => !s.is_empty(),
Value::NodeSet(v) => !v.is_empty(),
}
}
pub fn string(&self, doc: &Doc) -> String {
match self {
Value::Str(s) => s.clone(),
Value::Bool(b) => if *b { "true" } else { "false" }.to_string(),
Value::Num(n) => fmt_number(*n),
Value::NodeSet(v) => v.first().map(|n| doc.string_value(*n)).unwrap_or_default(),
}
}
pub fn number(&self, doc: &Doc) -> f64 {
match self {
Value::Num(n) => *n,
Value::Bool(b) => {
if *b {
1.0
} else {
0.0
}
}
Value::Str(s) => str_to_num(s),
Value::NodeSet(_) => str_to_num(&self.string(doc)),
}
}
fn nodes(&self) -> Option<&[XNode]> {
match self {
Value::NodeSet(v) => Some(v),
_ => None,
}
}
}
fn str_to_num(s: &str) -> f64 {
let t = s.trim();
if t.is_empty() {
return f64::NAN;
}
let body = t.strip_prefix('-').unwrap_or(t);
let mut seen_dot = false;
if body.is_empty() {
return f64::NAN;
}
for c in body.chars() {
match c {
'0'..='9' => {}
'.' if !seen_dot => seen_dot = true,
_ => return f64::NAN,
}
}
if body == "." {
return f64::NAN;
}
t.parse::<f64>().unwrap_or(f64::NAN)
}
#[derive(Debug, Clone, Copy)]
struct Ctx {
node: XNode,
pos: usize,
size: usize,
}
pub fn eval(doc: &Doc, expr: &Expr, start: XNode) -> Result<Value, String> {
let ctx = Ctx {
node: start,
pos: 1,
size: 1,
};
ev(doc, expr, ctx)
}
fn ev(doc: &Doc, e: &Expr, c: Ctx) -> Result<Value, String> {
Ok(match e {
Expr::Number(n) => Value::Num(*n),
Expr::Literal(s) => Value::Str(s.clone()),
Expr::Or(a, b) => {
Value::Bool(ev(doc, a, c)?.boolean() || ev(doc, b, c)?.boolean())
}
Expr::And(a, b) => Value::Bool(ev(doc, a, c)?.boolean() && ev(doc, b, c)?.boolean()),
Expr::Eq(a, b) => Value::Bool(compare_eq(doc, &ev(doc, a, c)?, &ev(doc, b, c)?, true)),
Expr::Ne(a, b) => Value::Bool(compare_eq(doc, &ev(doc, a, c)?, &ev(doc, b, c)?, false)),
Expr::Rel(op, a, b) => Value::Bool(compare_rel(doc, *op, &ev(doc, a, c)?, &ev(doc, b, c)?)),
Expr::Add(a, b) => Value::Num(ev(doc, a, c)?.number(doc) + ev(doc, b, c)?.number(doc)),
Expr::Sub(a, b) => Value::Num(ev(doc, a, c)?.number(doc) - ev(doc, b, c)?.number(doc)),
Expr::Mul(a, b) => Value::Num(ev(doc, a, c)?.number(doc) * ev(doc, b, c)?.number(doc)),
Expr::Div(a, b) => Value::Num(ev(doc, a, c)?.number(doc) / ev(doc, b, c)?.number(doc)),
Expr::Mod(a, b) => Value::Num(ev(doc, a, c)?.number(doc) % ev(doc, b, c)?.number(doc)),
Expr::Neg(a) => Value::Num(-ev(doc, a, c)?.number(doc)),
Expr::Union(a, b) => {
let (x, y) = (ev(doc, a, c)?, ev(doc, b, c)?);
let (xs, ys) = (
x.nodes().ok_or("`|` needs a node-set on the left")?,
y.nodes().ok_or("`|` needs a node-set on the right")?,
);
let mut v: Vec<XNode> = xs.iter().chain(ys.iter()).copied().collect();
sort_unique(doc, &mut v);
Value::NodeSet(v)
}
Expr::Call(name, args) => call(doc, name, args, c)?,
Expr::Path(start, steps) => {
let mut set = match start {
PathStart::Root => vec![doc.root()],
PathStart::Relative => vec![c.node],
PathStart::Filter(base, preds) => {
let v = ev(doc, base, c)?;
let mut nodes = v
.nodes()
.ok_or("a path can only continue from a node-set")?
.to_vec();
for p in preds {
nodes = filter(doc, nodes, p, false)?;
}
nodes
}
};
for s in steps {
set = step(doc, &set, s)?;
}
Value::NodeSet(set)
}
})
}
fn step(doc: &Doc, set: &[XNode], s: &Step) -> Result<Vec<XNode>, String> {
let mut out: Vec<XNode> = Vec::new();
for n in set {
let mut hits: Vec<XNode> = doc
.axis(s.axis, *n)
.into_iter()
.filter(|m| doc.passes(&s.test, s.axis, *m))
.collect();
for p in &s.preds {
hits = filter(doc, hits, p, s.axis.is_reverse())?;
}
out.extend(hits);
}
sort_unique(doc, &mut out);
Ok(out)
}
fn filter(doc: &Doc, nodes: Vec<XNode>, pred: &Expr, _reverse: bool) -> Result<Vec<XNode>, String> {
let size = nodes.len();
let mut out = Vec::new();
for (i, n) in nodes.into_iter().enumerate() {
let c = Ctx {
node: n,
pos: i + 1,
size,
};
let v = ev(doc, pred, c)?;
let keep = match v {
Value::Num(x) => x == (i + 1) as f64,
other => other.boolean(),
};
if keep {
out.push(n);
}
}
Ok(out)
}
fn sort_unique(doc: &Doc, v: &mut Vec<XNode>) {
v.sort_by_cached_key(|n| doc.key(*n));
v.dedup();
}
fn compare_eq(doc: &Doc, a: &Value, b: &Value, want_eq: bool) -> bool {
let test = |x: &str, y: &str| if want_eq { x == y } else { x != y };
match (a, b) {
(Value::NodeSet(xs), Value::NodeSet(ys)) => xs.iter().any(|x| {
let sx = doc.string_value(*x);
ys.iter().any(|y| test(&sx, &doc.string_value(*y)))
}),
(Value::NodeSet(xs), other) | (other, Value::NodeSet(xs)) => match other {
Value::Bool(b2) => {
let lhs = !xs.is_empty();
if want_eq {
lhs == *b2
} else {
lhs != *b2
}
}
Value::Num(n2) => xs.iter().any(|x| {
let v = str_to_num(&doc.string_value(*x));
if want_eq {
v == *n2
} else {
v != *n2
}
}),
_ => {
let s2 = other.string(doc);
xs.iter().any(|x| test(&doc.string_value(*x), &s2))
}
},
_ => {
if matches!(a, Value::Bool(_)) || matches!(b, Value::Bool(_)) {
let (x, y) = (a.boolean(), b.boolean());
if want_eq {
x == y
} else {
x != y
}
} else if matches!(a, Value::Num(_)) || matches!(b, Value::Num(_)) {
let (x, y) = (a.number(doc), b.number(doc));
if want_eq {
x == y
} else {
x != y
}
} else {
test(&a.string(doc), &b.string(doc))
}
}
}
}
fn compare_rel(doc: &Doc, op: RelOp, a: &Value, b: &Value) -> bool {
let cmp = |x: f64, y: f64| match op {
RelOp::Lt => x < y,
RelOp::Gt => x > y,
RelOp::Le => x <= y,
RelOp::Ge => x >= y,
};
match (a, b) {
(Value::NodeSet(xs), Value::NodeSet(ys)) => xs.iter().any(|x| {
let vx = str_to_num(&doc.string_value(*x));
ys.iter()
.any(|y| cmp(vx, str_to_num(&doc.string_value(*y))))
}),
(Value::NodeSet(xs), other) => {
let n = other.number(doc);
xs.iter().any(|x| cmp(str_to_num(&doc.string_value(*x)), n))
}
(other, Value::NodeSet(ys)) => {
let n = other.number(doc);
ys.iter().any(|y| cmp(n, str_to_num(&doc.string_value(*y))))
}
_ => cmp(a.number(doc), b.number(doc)),
}
}
fn arity(name: &str, args: &[Expr], lo: usize, hi: usize) -> Result<(), String> {
if args.len() < lo || args.len() > hi {
let want = if lo == hi {
format!("{lo}")
} else {
format!("{lo} to {hi}")
};
return Err(format!(
"`{name}()` takes {want} argument(s), got {}",
args.len()
));
}
Ok(())
}
fn call(doc: &Doc, name: &str, args: &[Expr], c: Ctx) -> Result<Value, String> {
let num = |i: usize| -> Result<f64, String> { Ok(ev(doc, &args[i], c)?.number(doc)) };
let stringy = |i: usize| -> Result<String, String> { Ok(ev(doc, &args[i], c)?.string(doc)) };
let str_or_ctx = |i: usize| -> Result<String, String> {
if args.len() > i {
stringy(i)
} else {
Ok(doc.string_value(c.node))
}
};
let nodeset = |i: usize| -> Result<Vec<XNode>, String> {
match ev(doc, &args[i], c)? {
Value::NodeSet(v) => Ok(v),
_ => Err(format!("`{name}()` needs a node-set argument")),
}
};
Ok(match name {
"last" => {
arity(name, args, 0, 0)?;
Value::Num(c.size as f64)
}
"position" => {
arity(name, args, 0, 0)?;
Value::Num(c.pos as f64)
}
"count" => {
arity(name, args, 1, 1)?;
Value::Num(nodeset(0)?.len() as f64)
}
"id" => {
arity(name, args, 1, 1)?;
let v = ev(doc, &args[0], c)?;
let ids: Vec<String> = match &v {
Value::NodeSet(ns) => ns
.iter()
.flat_map(|n| {
doc.string_value(*n)
.split_whitespace()
.map(str::to_string)
.collect::<Vec<_>>()
})
.collect(),
other => other
.string(doc)
.split_whitespace()
.map(str::to_string)
.collect(),
};
let mut out: Vec<XNode> = Vec::new();
for n in doc.document_nodes() {
if let XNode::Tree(tid) = n {
if let Some(e) = doc.html.tree.get(tid).and_then(|x| x.value().as_element()) {
if e.attr("id").is_some_and(|v| ids.iter().any(|i| i == v)) {
out.push(n);
}
}
}
}
sort_unique(doc, &mut out);
Value::NodeSet(out)
}
"local-name" | "name" => {
arity(name, args, 0, 1)?;
let n = if args.is_empty() {
Some(c.node)
} else {
nodeset(0)?.first().copied()
};
Value::Str(n.and_then(|n| doc.name(n)).unwrap_or_default())
}
"namespace-uri" => {
arity(name, args, 0, 1)?;
if !args.is_empty() {
nodeset(0)?;
}
Value::Str(String::new())
}
"string" => {
arity(name, args, 0, 1)?;
Value::Str(if args.is_empty() {
doc.string_value(c.node)
} else {
stringy(0)?
})
}
"concat" => {
arity(name, args, 2, usize::MAX)?;
let mut s = String::new();
for i in 0..args.len() {
s.push_str(&stringy(i)?);
}
Value::Str(s)
}
"starts-with" => {
arity(name, args, 2, 2)?;
Value::Bool(stringy(0)?.starts_with(&stringy(1)?))
}
"contains" => {
arity(name, args, 2, 2)?;
Value::Bool(stringy(0)?.contains(&stringy(1)?))
}
"substring-before" => {
arity(name, args, 2, 2)?;
let (h, n) = (stringy(0)?, stringy(1)?);
Value::Str(match h.find(&n) {
Some(i) => h[..i].to_string(),
None => String::new(),
})
}
"substring-after" => {
arity(name, args, 2, 2)?;
let (h, n) = (stringy(0)?, stringy(1)?);
Value::Str(match h.find(&n) {
Some(i) => h[i + n.len()..].to_string(),
None => String::new(),
})
}
"substring" => {
arity(name, args, 2, 3)?;
let chars: Vec<char> = stringy(0)?.chars().collect();
let start = num(1)?;
let end = if args.len() > 2 {
let l = num(2)?;
if l.is_nan() || start.is_nan() {
f64::NAN
} else {
round_half_up(start) + round_half_up(l)
}
} else {
f64::INFINITY
};
let lo = if start.is_nan() {
f64::NAN
} else {
round_half_up(start)
};
let mut s = String::new();
for (i, ch) in chars.iter().enumerate() {
let p = (i + 1) as f64;
if p >= lo && p < end {
s.push(*ch);
}
}
Value::Str(s)
}
"string-length" => {
arity(name, args, 0, 1)?;
Value::Num(str_or_ctx(0)?.chars().count() as f64)
}
"normalize-space" => {
arity(name, args, 0, 1)?;
Value::Str(
str_or_ctx(0)?
.split_whitespace()
.collect::<Vec<_>>()
.join(" "),
)
}
"translate" => {
arity(name, args, 3, 3)?;
let (s, from, to) = (stringy(0)?, stringy(1)?, stringy(2)?);
let from: Vec<char> = from.chars().collect();
let to: Vec<char> = to.chars().collect();
let mut out = String::new();
for ch in s.chars() {
match from.iter().position(|f| *f == ch) {
Some(i) => {
if let Some(r) = to.get(i) {
out.push(*r);
}
}
None => out.push(ch),
}
}
Value::Str(out)
}
"boolean" => {
arity(name, args, 1, 1)?;
Value::Bool(ev(doc, &args[0], c)?.boolean())
}
"not" => {
arity(name, args, 1, 1)?;
Value::Bool(!ev(doc, &args[0], c)?.boolean())
}
"true" => {
arity(name, args, 0, 0)?;
Value::Bool(true)
}
"false" => {
arity(name, args, 0, 0)?;
Value::Bool(false)
}
"lang" => {
arity(name, args, 1, 1)?;
let want = stringy(0)?.to_ascii_lowercase();
Value::Bool(match doc.lang_of(c.node) {
Some(have) => {
let have = have.to_ascii_lowercase();
have == want || have.starts_with(&format!("{want}-"))
}
None => false,
})
}
"number" => {
arity(name, args, 0, 1)?;
Value::Num(if args.is_empty() {
str_to_num(&doc.string_value(c.node))
} else {
ev(doc, &args[0], c)?.number(doc)
})
}
"sum" => {
arity(name, args, 1, 1)?;
Value::Num(
nodeset(0)?
.iter()
.map(|n| str_to_num(&doc.string_value(*n)))
.sum(),
)
}
"floor" => {
arity(name, args, 1, 1)?;
Value::Num(num(0)?.floor())
}
"ceiling" => {
arity(name, args, 1, 1)?;
Value::Num(num(0)?.ceil())
}
"round" => {
arity(name, args, 1, 1)?;
Value::Num(round_half_up(num(0)?))
}
other => {
return Err(format!(
"`{other}()` is not an XPath 1.0 core function (the library is \
last, position, count, id, local-name, namespace-uri, name, string, \
concat, starts-with, contains, substring-before, substring-after, \
substring, string-length, normalize-space, translate, boolean, not, \
true, false, lang, number, sum, floor, ceiling, round)"
))
}
})
}
fn round_half_up(x: f64) -> f64 {
if x.is_nan() || x.is_infinite() {
return x;
}
(x + 0.5).floor()
}
pub fn render(doc: &Doc, v: &Value) -> Vec<String> {
match v {
Value::NodeSet(ns) => ns.iter().map(|n| doc.render(*n)).collect(),
Value::Str(s) => vec![s.clone()],
Value::Num(n) => vec![fmt_number(*n)],
Value::Bool(b) => vec![if *b { "true" } else { "false" }.to_string()],
}
}