use crate::query::QueryOp;
use crate::xpath_syntax::{self, Expr, PathStart};
pub fn translate(src: &str) -> Result<Vec<QueryOp>, String> {
let s = src.trim();
if s.is_empty() {
return Err("xpath: empty expression".into());
}
if let Some(rest) = s.strip_prefix('@') {
if crate::jqlang::FORMAT_NAMES.contains(&rest) {
return Err(format!(
"xpath: `@{rest}` is a jq format string, which is outside the \
supported subset (a leading `@` here is an xpath attribute step; \
use `attr {rest}` for a literal attribute of that name)"
));
}
}
if !s.contains(['/', '@', ':', '(', '[', '|']) {
return Err(format!(
"xpath: `{src}` has no xpath-only syntax, so it is read as a verb name (spell the step `//{src}`, `./{src}` or `child::{src}` to force xpath)"
));
}
let expr = xpath_syntax::parse(s).map_err(|e| format!("xpath: {e} in `{src}`"))?;
let per_line = is_relative_location(&expr);
Ok(vec![QueryOp::XPath(Box::new(XPath {
src: s.to_string(),
expr,
per_line,
}))])
}
#[derive(Debug, Clone)]
pub struct XPath {
pub src: String,
pub expr: Expr,
pub per_line: bool,
}
impl XPath {
pub fn run(&self, lines: &[String]) -> Result<Vec<String>, String> {
use crate::xpath_eval::{eval, render, Doc};
if !self.per_line {
let doc = Doc::parse(&lines.join("\n"));
let v = eval(&doc, &self.expr, doc.root())
.map_err(|e| format!("xpath: {e} in `{}`", self.src))?;
return Ok(render(&doc, &v));
}
let mut out = Vec::new();
for l in lines {
let doc = Doc::parse(l);
let ctx = first_element(&doc).unwrap_or_else(|| doc.root());
let v =
eval(&doc, &self.expr, ctx).map_err(|e| format!("xpath: {e} in `{}`", self.src))?;
out.extend(render(&doc, &v));
}
Ok(out)
}
}
fn first_element(doc: &crate::xpath_eval::Doc) -> Option<crate::xpath_eval::XNode> {
use crate::xpath_eval::{Kind, XNode};
let mut best: Option<XNode> = None;
for n in doc.document_nodes() {
if doc.kind(n) == Kind::Element {
let name = doc.name(n).unwrap_or_default();
if name == "html" || name == "body" || name == "head" {
continue;
}
best = Some(n);
break;
}
}
best
}
fn is_relative_location(e: &Expr) -> bool {
match e {
Expr::Path(PathStart::Relative, _) => true,
Expr::Union(a, b) => is_relative_location(a) && is_relative_location(b),
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::query::{eval, QueryResult};
fn run(src: &str, html: &str) -> Vec<String> {
match eval(&translate(src).unwrap(), &[html.to_string()], 0.0) {
QueryResult::Lines(v) => v,
other => panic!("expected Lines, got {other:?}"),
}
}
#[test]
fn descendant_and_child_paths() {
let doc = "<html><body><div><span>A</span></div><span>B</span></body></html>";
assert_eq!(run("//span/text()", doc), vec!["A", "B"]);
assert_eq!(run("//div/span/text()", doc), vec!["A"]);
assert_eq!(run("/html/body/span/text()", doc), vec!["B"]);
}
#[test]
fn attr_predicate_and_accessors() {
let doc = "<div><a href=\"x\">1</a><a href=\"y\">2</a></div>";
assert_eq!(run("//a/@href", doc), vec!["x", "y"]);
assert_eq!(run("//a/text()", doc), vec!["1", "2"]);
let two = [translate("//a").unwrap(), translate("@href").unwrap()].concat();
match eval(&two, &[doc.to_string()], 0.0) {
QueryResult::Lines(v) => assert_eq!(v, vec!["x", "y"]),
other => panic!("{other:?}"),
}
}
#[test]
fn a_malformed_expression_is_a_parse_error_not_an_empty_answer() {
for bad in [
"//a[", "//a[@href", "count(", "//a[@class=btn", "'unterminated", "//a!", "//a/@href extra", "//nosuchfn()", "//bogus-axis::a", "", ] {
assert!(translate(bad).is_err(), "expected `{bad}` to be refused");
}
}
}