einvoice-xpath 0.3.0

Parser and syntax tree for the XPath 2.0 subset used by the official e-invoicing validation stylesheets
Documentation
//! Parser and syntax tree for the XPath 2.0 subset that the official e-invoicing validation
//! stylesheets use, and for the XSLT pieces built on it: match patterns, sequence types
//! (`as` attributes) and attribute value templates.
//!
//! Only syntax is handled here: function names are resolved to namespaces but not to
//! functions, and nothing is evaluated. The subset is closed: a construct outside it is
//! refused with an [`ErrorKind::Unsupported`] error naming it, never parsed as something
//! else. Supported:
//!
//! - path expressions on the axes `child`, `attribute`, `self`, `parent`, `ancestor`,
//!   `ancestor-or-self`, `descendant`, `descendant-or-self` (and `//`), `preceding-sibling`,
//!   `preceding`, `following-sibling`; name tests, wildcards and the kind tests `node()`, `text()`,
//!   `comment()`, `processing-instruction()`, `element(name?)`, `attribute(name?)`;
//!   predicates; filter expressions as steps;
//! - `for`, `some`, `every` (one or more bindings), `if then else`, `to`, `instance of`,
//!   `cast as`, `castable as`, general and value comparisons, `or`, `and`, `+ - * div idiv mod`,
//!   unary `-`, `|`, sequences, literals (numeric literals keep their kind and text),
//!   variable references, `.`, function calls;
//! - patterns of XSLT 2.0 without `id()`/`key()`, plus the XSLT 3.0 forms `root()` and
//!   parenthesized patterns as Saxon-HE 12.10 reads them (see [`parse_pattern`]).
//!
//! Refused: `intersect`, `except`, the `union` keyword, `treat as`, node
//! comparisons, unary `+`, XPath comments, the `following` and `namespace` axes (in
//! patterns, the axes other than `child` and `attribute`), `document-node()`,
//! `schema-element()`, `schema-attribute()`, typed `element()` and `attribute()` tests, `item()`, `empty-sequence()`, atomic types other than `xs:string`,
//! `xs:anyURI`, `xs:boolean`, `xs:integer`, `xs:decimal` and `xs:date`, and every XPath 3.0
//! addition except the zero-argument `document-uri()`, which is an ordinary function call
//! here.
//!
//! Refused as well, with an [`ErrorKind::TooDeep`] error: an expression or pattern nested
//! deeper than [`MAX_DEPTH`], which would otherwise need a call stack in proportion to
//! its depth to be read, compiled and evaluated.
//!
//! ```
//! use einvoice_xpath::{parse_expr, NamespaceMap, XS_NAMESPACE};
//!
//! let ns = NamespaceMap::new().bind("xs", XS_NAMESPACE);
//! let expr = parse_expr("xs:decimal(Amount) * 2 = 10", &ns)?;
//! assert_eq!(expr.to_string(), "xs:decimal(Amount) * 2 = 10");
//! assert!(parse_expr("a intersect b", &ns).is_err());
//! # Ok::<(), einvoice_xpath::Error>(())
//! ```

mod ast;
mod error;
mod lexer;
mod names;
mod parser;
mod print;

pub use ast::{
    ArithmeticOp, AtomicKind, AtomicType, Avt, AvtPart, Axis, AxisStep, Binding, CompareKind,
    ComparisonOp, Expr, ItemType, KindTest, Literal, NameOrWildcard, NameTest, NodeTest,
    Occurrence, PathExpr, PathPattern, PathStart, PathStep, Pattern, PatternAlternative,
    PatternAnchor, PatternAxis, PatternLink, PatternStep, Quantifier, SequenceType, SingleType,
    Step,
};
pub use error::{Error, ErrorKind, Result};
pub use names::{
    FN_NAMESPACE, NamespaceBinding, NamespaceMap, Namespaces, QName, XML_NAMESPACE, XS_NAMESPACE,
    is_name_char, is_name_start_char, is_ncname, is_xml_whitespace,
};

use parser::Parser;

/// The maximum depth of an expression or pattern: deeper, it is refused with an
/// [`ErrorKind::TooDeep`] error.
///
/// Reading, printing, compiling and evaluating an expression recurse over its tree, so
/// the call stack they need grows with its depth: without a bound, a short text nested
/// deeply enough (`((((...))))`, `1+1+...+1`) would overflow the stack of its thread,
/// which aborts the whole process. The depth is 1 for a literal, a variable reference,
/// `.` and a call without argument; every other expression is one level deeper than its
/// deepest operand. A chain of left-associative operators nests too (`a + b + c` is
/// `(a + b) + c`, depth 3), and so do the steps of a path (`a/b/c` is `(a/b)/c`), the
/// predicates of a step (each filters what the previous ones kept), the bindings of a
/// `for`, `some` or `every` (each binds inside the previous one) and the steps of a
/// pattern; parentheses add no level, but the nesting of parentheses is bounded by the
/// same maximum. The steps of a path written with `//` count the
/// `descendant-or-self::node()` step `//` stands for.
///
/// 128: the official stylesheets nest their expressions 32 deep at most (CEN, Peppol,
/// Factur-X, XRechnung and the French rules), most often through a chain of `or` or
/// `and`.
pub const MAX_DEPTH: u32 = 128;

/// Parses an XPath expression (XPath 2.0 production \[1\] `XPath ::= Expr`).
///
/// # Errors
///
/// A syntax error, a construct outside the supported subset, or an undeclared prefix.
pub fn parse_expr(src: &str, namespaces: &dyn Namespaces) -> Result<Expr> {
    let mut parser = Parser::new(src, 0, namespaces);
    let expr = parser.expr()?;
    parser.expect_end()?;
    Ok(*expr.expr)
}

/// Parses an XSLT match pattern.
///
/// XSLT 3.0 parenthesized patterns are read as Saxon-HE 12.10 reads them, normalised:
///
/// - `(P)` without predicate, as the whole of an alternative, is `P`: its alternatives
///   become alternatives of the pattern (`(a | b)` is `a | b`, two template rules with
///   their own default priorities when the template has no `priority`);
/// - a path ending with a parenthesized step without predicate is distributed over the
///   alternatives of that step: `r/(a | b/c)` is `r/a | r/b/c` (Saxon makes it a union
///   pattern, split like one);
/// - kept as a [`PathStep::Parenthesized`]: the first step of a path, with or without
///   predicates (`(a | b)[p]`, `(a/b | c)[p]/d`), and a step between two others
///   without predicate whose alternatives are single steps (`(a | b)/(c | d)/e`).
///
/// Refused as unsupported: a predicate on a parenthesized step after the first (Saxon
/// refuses most of them, XTSE0340), a parenthesized step nested inside another one that
/// is kept, and, inside a parenthesized step that is not the first, or after `/` or
/// `//`, alternatives other than single relative steps.
///
/// # Errors
///
/// A syntax error, a construct outside the supported subset, or an undeclared prefix.
pub fn parse_pattern(src: &str, namespaces: &dyn Namespaces) -> Result<Pattern> {
    let mut parser = Parser::new(src, 0, namespaces);
    let (pattern, _) = parser.pattern()?;
    parser.expect_end()?;
    Ok(pattern)
}

/// Parses a sequence type, as in an XSLT `as` attribute.
///
/// # Errors
///
/// A syntax error, an unsupported or unknown type, or an undeclared prefix.
pub fn parse_sequence_type(src: &str, namespaces: &dyn Namespaces) -> Result<SequenceType> {
    let mut parser = Parser::new(src, 0, namespaces);
    let sequence_type = parser.sequence_type()?;
    parser.expect_end()?;
    Ok(sequence_type)
}

/// Parses an attribute value template.
///
/// # Errors
///
/// A misplaced `}`, an empty or unterminated `{...}`, or an error in an expression.
pub fn parse_avt(src: &str, namespaces: &dyn Namespaces) -> Result<Avt> {
    parser::parse_avt(src, namespaces)
}