1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use context::EvaluationCtx;
use eval::Evaluatable;
pub use eval_value::{NodesetHelpers, Value};
use parser::OwnedParserError;
pub use parser::{parse as parse_impl, Expr};

use super::dom::node::Node;

mod context;
mod eval;
mod eval_function;
mod eval_value;
mod parser;

/// The failure modes of executing an XPath.
#[derive(Debug, PartialEq)]
pub enum Error {
    /// The XPath was syntactically invalid
    Parsing { source: OwnedParserError },
    /// The XPath could not be executed
    Evaluating { source: eval::Error },
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Error::Parsing { source } => write!(f, "Unable to parse XPath: {}", source),
            Error::Evaluating { source } => write!(f, "Unable to evaluate XPath: {}", source),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Parsing { source } => Some(source),
            Error::Evaluating { source } => Some(source),
        }
    }
}

/// Parse an XPath expression from a string
pub fn parse(xpath: &str) -> Result<Expr, Error> {
    match parse_impl(xpath) {
        Ok(expr) => {
            debug!("Parsed XPath: {:?}", expr);
            Ok(expr)
        },
        Err(e) => {
            debug!("Unable to parse XPath: {}", e);
            Err(Error::Parsing { source: e })
        },
    }
}

/// Evaluate an already-parsed XPath expression
pub fn evaluate_parsed_xpath(expr: &Expr, context_node: &Node) -> Result<Value, Error> {
    let context = EvaluationCtx::new(context_node);
    match expr.evaluate(&context) {
        Ok(v) => {
            debug!("Evaluated XPath: {:?}", v);
            Ok(v)
        },
        Err(e) => {
            debug!("Unable to evaluate XPath: {}", e);
            Err(Error::Evaluating { source: e })
        },
    }
}