Skip to main content

einvoice_xpath/
lib.rs

1//! Parser and syntax tree for the XPath 2.0 subset that the official e-invoicing validation
2//! stylesheets use, and for the XSLT pieces built on it: match patterns, sequence types
3//! (`as` attributes) and attribute value templates.
4//!
5//! Only syntax is handled here: function names are resolved to namespaces but not to
6//! functions, and nothing is evaluated. The subset is closed: a construct outside it is
7//! refused with an [`ErrorKind::Unsupported`] error naming it, never parsed as something
8//! else. Supported:
9//!
10//! - path expressions on the axes `child`, `attribute`, `self`, `parent`, `ancestor`,
11//!   `ancestor-or-self`, `descendant`, `descendant-or-self` (and `//`), `preceding-sibling`,
12//!   `preceding`, `following-sibling`; name tests, wildcards and the kind tests `node()`, `text()`,
13//!   `comment()`, `processing-instruction()`, `element(name?)`, `attribute(name?)`;
14//!   predicates; filter expressions as steps;
15//! - `for`, `some`, `every` (one or more bindings), `if then else`, `to`, `instance of`,
16//!   `cast as`, `castable as`, general and value comparisons, `or`, `and`, `+ - * div idiv mod`,
17//!   unary `-`, `|`, sequences, literals (numeric literals keep their kind and text),
18//!   variable references, `.`, function calls;
19//! - patterns of XSLT 2.0 without `id()`/`key()`, plus the XSLT 3.0 forms `root()` and
20//!   parenthesized patterns as Saxon-HE 12.10 reads them (see [`parse_pattern`]).
21//!
22//! Refused: `intersect`, `except`, the `union` keyword, `treat as`, node
23//! comparisons, unary `+`, XPath comments, the `following` and `namespace` axes (in
24//! patterns, the axes other than `child` and `attribute`), `document-node()`,
25//! `schema-element()`, `schema-attribute()`, typed `element()` and `attribute()` tests, `item()`, `empty-sequence()`, atomic types other than `xs:string`,
26//! `xs:anyURI`, `xs:boolean`, `xs:integer`, `xs:decimal` and `xs:date`, and every XPath 3.0
27//! addition except the zero-argument `document-uri()`, which is an ordinary function call
28//! here.
29//!
30//! Refused as well, with an [`ErrorKind::TooDeep`] error: an expression or pattern nested
31//! deeper than [`MAX_DEPTH`], which would otherwise need a call stack in proportion to
32//! its depth to be read, compiled and evaluated.
33//!
34//! ```
35//! use einvoice_xpath::{parse_expr, NamespaceMap, XS_NAMESPACE};
36//!
37//! let ns = NamespaceMap::new().bind("xs", XS_NAMESPACE);
38//! let expr = parse_expr("xs:decimal(Amount) * 2 = 10", &ns)?;
39//! assert_eq!(expr.to_string(), "xs:decimal(Amount) * 2 = 10");
40//! assert!(parse_expr("a intersect b", &ns).is_err());
41//! # Ok::<(), einvoice_xpath::Error>(())
42//! ```
43
44mod ast;
45mod error;
46mod lexer;
47mod names;
48mod parser;
49mod print;
50
51pub use ast::{
52    ArithmeticOp, AtomicKind, AtomicType, Avt, AvtPart, Axis, AxisStep, Binding, CompareKind,
53    ComparisonOp, Expr, ItemType, KindTest, Literal, NameOrWildcard, NameTest, NodeTest,
54    Occurrence, PathExpr, PathPattern, PathStart, PathStep, Pattern, PatternAlternative,
55    PatternAnchor, PatternAxis, PatternLink, PatternStep, Quantifier, SequenceType, SingleType,
56    Step,
57};
58pub use error::{Error, ErrorKind, Result};
59pub use names::{
60    FN_NAMESPACE, NamespaceBinding, NamespaceMap, Namespaces, QName, XML_NAMESPACE, XS_NAMESPACE,
61    is_name_char, is_name_start_char, is_ncname, is_xml_whitespace,
62};
63
64use parser::Parser;
65
66/// The maximum depth of an expression or pattern: deeper, it is refused with an
67/// [`ErrorKind::TooDeep`] error.
68///
69/// Reading, printing, compiling and evaluating an expression recurse over its tree, so
70/// the call stack they need grows with its depth: without a bound, a short text nested
71/// deeply enough (`((((...))))`, `1+1+...+1`) would overflow the stack of its thread,
72/// which aborts the whole process. The depth is 1 for a literal, a variable reference,
73/// `.` and a call without argument; every other expression is one level deeper than its
74/// deepest operand. A chain of left-associative operators nests too (`a + b + c` is
75/// `(a + b) + c`, depth 3), and so do the steps of a path (`a/b/c` is `(a/b)/c`), the
76/// predicates of a step (each filters what the previous ones kept), the bindings of a
77/// `for`, `some` or `every` (each binds inside the previous one) and the steps of a
78/// pattern; parentheses add no level, but the nesting of parentheses is bounded by the
79/// same maximum. The steps of a path written with `//` count the
80/// `descendant-or-self::node()` step `//` stands for.
81///
82/// 128: the official stylesheets nest their expressions 32 deep at most (CEN, Peppol,
83/// Factur-X, XRechnung and the French rules), most often through a chain of `or` or
84/// `and`.
85pub const MAX_DEPTH: u32 = 128;
86
87/// Parses an XPath expression (XPath 2.0 production \[1\] `XPath ::= Expr`).
88///
89/// # Errors
90///
91/// A syntax error, a construct outside the supported subset, or an undeclared prefix.
92pub fn parse_expr(src: &str, namespaces: &dyn Namespaces) -> Result<Expr> {
93    let mut parser = Parser::new(src, 0, namespaces);
94    let expr = parser.expr()?;
95    parser.expect_end()?;
96    Ok(*expr.expr)
97}
98
99/// Parses an XSLT match pattern.
100///
101/// XSLT 3.0 parenthesized patterns are read as Saxon-HE 12.10 reads them, normalised:
102///
103/// - `(P)` without predicate, as the whole of an alternative, is `P`: its alternatives
104///   become alternatives of the pattern (`(a | b)` is `a | b`, two template rules with
105///   their own default priorities when the template has no `priority`);
106/// - a path ending with a parenthesized step without predicate is distributed over the
107///   alternatives of that step: `r/(a | b/c)` is `r/a | r/b/c` (Saxon makes it a union
108///   pattern, split like one);
109/// - kept as a [`PathStep::Parenthesized`]: the first step of a path, with or without
110///   predicates (`(a | b)[p]`, `(a/b | c)[p]/d`), and a step between two others
111///   without predicate whose alternatives are single steps (`(a | b)/(c | d)/e`).
112///
113/// Refused as unsupported: a predicate on a parenthesized step after the first (Saxon
114/// refuses most of them, XTSE0340), a parenthesized step nested inside another one that
115/// is kept, and, inside a parenthesized step that is not the first, or after `/` or
116/// `//`, alternatives other than single relative steps.
117///
118/// # Errors
119///
120/// A syntax error, a construct outside the supported subset, or an undeclared prefix.
121pub fn parse_pattern(src: &str, namespaces: &dyn Namespaces) -> Result<Pattern> {
122    let mut parser = Parser::new(src, 0, namespaces);
123    let (pattern, _) = parser.pattern()?;
124    parser.expect_end()?;
125    Ok(pattern)
126}
127
128/// Parses a sequence type, as in an XSLT `as` attribute.
129///
130/// # Errors
131///
132/// A syntax error, an unsupported or unknown type, or an undeclared prefix.
133pub fn parse_sequence_type(src: &str, namespaces: &dyn Namespaces) -> Result<SequenceType> {
134    let mut parser = Parser::new(src, 0, namespaces);
135    let sequence_type = parser.sequence_type()?;
136    parser.expect_end()?;
137    Ok(sequence_type)
138}
139
140/// Parses an attribute value template.
141///
142/// # Errors
143///
144/// A misplaced `}`, an empty or unterminated `{...}`, or an error in an expression.
145pub fn parse_avt(src: &str, namespaces: &dyn Namespaces) -> Result<Avt> {
146    parser::parse_avt(src, namespaces)
147}