script/xpath/
mod.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::rc::Rc;
6
7use context::EvaluationCtx;
8use eval::{Error as EvaluationError, Evaluatable};
9pub(crate) use eval_value::{NodesetHelpers, Value};
10pub(crate) use parser::{Expr, parse as parse_impl};
11
12use super::dom::node::Node;
13use crate::dom::bindings::codegen::Bindings::XPathNSResolverBinding::XPathNSResolver;
14use crate::dom::bindings::error::{Error as JsError, Error, Fallible};
15
16mod context;
17#[allow(dead_code)]
18mod eval;
19mod eval_function;
20#[allow(dead_code)]
21mod eval_value;
22#[allow(dead_code)]
23mod parser;
24
25/// Parse an XPath expression from a string
26pub(crate) fn parse(xpath: &str) -> Fallible<Expr> {
27    match parse_impl(xpath) {
28        Ok(expr) => {
29            debug!("Parsed XPath: {expr:?}");
30            Ok(expr)
31        },
32        Err(error) => {
33            debug!("Unable to parse XPath: {error}");
34            Err(Error::Operation)
35        },
36    }
37}
38
39/// Evaluate an already-parsed XPath expression
40pub(crate) fn evaluate_parsed_xpath(
41    expr: &Expr,
42    context_node: &Node,
43    resolver: Option<Rc<XPathNSResolver>>,
44) -> Fallible<Value> {
45    let context = EvaluationCtx::new(context_node, resolver);
46    match expr.evaluate(&context) {
47        Ok(value) => {
48            debug!("Evaluated XPath: {value:?}");
49            Ok(value)
50        },
51        Err(error) => {
52            debug!("Unable to evaluate XPath: {error}");
53
54            let error = match error {
55                EvaluationError::JsException(exception) => exception,
56                _ => JsError::Operation,
57            };
58
59            Err(error)
60        },
61    }
62}