einvoice_xpath/ast.rs
1//! The syntax tree of the supported XPath 2.0 subset, of XSLT patterns, sequence types and
2//! attribute value templates.
3//!
4//! The tree is canonical: parentheses are not kept (the nesting of the tree carries the
5//! grouping), abbreviations are expanded where the XPath 2.0 specification defines them as
6//! abbreviations (`//` is `/descendant-or-self::node()/`, `..` is `parent::node()`, `@n` is
7//! `attribute::n`). Printing a tree with [`std::fmt::Display`] and parsing the text again
8//! gives the same tree.
9
10use crate::names::QName;
11
12/// An XPath expression (XPath 2.0 production \[2\] `Expr` and below).
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum Expr {
15 /// A string or numeric literal (\[42\] `Literal`).
16 Literal(Literal),
17 /// `$name` (\[44\] `VarRef`). Unprefixed variable names are in no namespace.
18 VarRef(QName),
19 /// `.` (\[47\] `ContextItemExpr`).
20 ContextItem,
21 /// `name(args)` (\[48\] `FunctionCall`). Unprefixed function names are in the
22 /// [`FN_NAMESPACE`](crate::FN_NAMESPACE); which function the name and arity designate
23 /// is decided when the expression is compiled, not by the parser.
24 FunctionCall {
25 /// The function name.
26 name: QName,
27 /// The arguments, each an `ExprSingle`.
28 args: Vec<Expr>,
29 },
30 /// The comma operator (\[2\] `Expr`) with two or more operands, or `()` (\[46\]
31 /// `ParenthesizedExpr` with no content) with none. A single parenthesized expression is
32 /// that expression itself.
33 Sequence(Vec<Expr>),
34 /// A primary expression followed by one or more predicates (\[38\] `FilterExpr`).
35 Filter {
36 /// The filtered expression.
37 base: Box<Expr>,
38 /// The predicates, applied left to right.
39 predicates: Vec<Expr>,
40 },
41 /// A path expression with at least one `/` or `//`, or a single axis step (\[25\]
42 /// `PathExpr`). A single filter expression without slash is not a path.
43 Path(PathExpr),
44 /// Unary minus (\[20\] `UnaryExpr`); `--x` is two nested negations.
45 Negate(Box<Expr>),
46 /// `operand castable as T?` (\[18\] `CastableExpr`).
47 Castable {
48 /// The tested expression.
49 operand: Box<Expr>,
50 /// The target type.
51 target: SingleType,
52 },
53 /// `operand instance of T` (\[16\] `InstanceofExpr`).
54 InstanceOf {
55 /// The tested expression.
56 operand: Box<Expr>,
57 /// The tested type.
58 target: SequenceType,
59 },
60 /// `lhs | rhs` (\[14\] `UnionExpr`), left associative.
61 Union(Box<Expr>, Box<Expr>),
62 /// `+ - * div idiv mod` (\[12\] `AdditiveExpr`, \[13\] `MultiplicativeExpr`), left
63 /// associative.
64 Arithmetic {
65 /// The operator.
66 op: ArithmeticOp,
67 /// Left operand.
68 lhs: Box<Expr>,
69 /// Right operand.
70 rhs: Box<Expr>,
71 },
72 /// `lhs to rhs` (\[11\] `RangeExpr`), not associative.
73 Range(Box<Expr>, Box<Expr>),
74 /// A general or value comparison (\[10\] `ComparisonExpr`), not associative.
75 Comparison {
76 /// The operator.
77 op: ComparisonOp,
78 /// Left operand.
79 lhs: Box<Expr>,
80 /// Right operand.
81 rhs: Box<Expr>,
82 },
83 /// `lhs and rhs` (\[9\] `AndExpr`), left associative.
84 And(Box<Expr>, Box<Expr>),
85 /// `lhs or rhs` (\[8\] `OrExpr`), left associative.
86 Or(Box<Expr>, Box<Expr>),
87 /// `if (condition) then a else b` (\[7\] `IfExpr`).
88 If {
89 /// The condition (an `Expr`, so possibly a sequence).
90 condition: Box<Expr>,
91 /// The `then` branch.
92 then: Box<Expr>,
93 /// The `else` branch.
94 otherwise: Box<Expr>,
95 },
96 /// `for $v in e, ... return body` (\[4\] `ForExpr`).
97 For {
98 /// The bindings, in order (one or more).
99 bindings: Vec<Binding>,
100 /// The `return` expression.
101 body: Box<Expr>,
102 },
103 /// `some|every $v in e, ... satisfies test` (\[6\] `QuantifiedExpr`).
104 Quantified {
105 /// `some` or `every`.
106 quantifier: Quantifier,
107 /// The bindings, in order (one or more).
108 bindings: Vec<Binding>,
109 /// The `satisfies` expression.
110 satisfies: Box<Expr>,
111 },
112}
113
114/// `$variable in sequence` in a `for`, `some` or `every` expression.
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct Binding {
117 /// The range variable.
118 pub variable: QName,
119 /// The binding sequence.
120 pub sequence: Expr,
121}
122
123/// `some` or `every`.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
125pub enum Quantifier {
126 /// `some`
127 Some,
128 /// `every`
129 Every,
130}
131
132/// A literal (\[42\] `Literal`). Numeric literals keep their kind and their exact lexical
133/// form: the value is computed when the expression is compiled.
134#[derive(Debug, Clone, PartialEq, Eq, Hash)]
135pub enum Literal {
136 /// A string literal, with its doubled quotes already reduced.
137 String(String),
138 /// \[71\] `IntegerLiteral`: digits only, of any length.
139 Integer(String),
140 /// \[72\] `DecimalLiteral`, as written (`1.50`, `.5`, `1.`).
141 Decimal(String),
142 /// \[73\] `DoubleLiteral`, as written (`1e3`, `1.5E-2`).
143 Double(String),
144}
145
146/// An arithmetic operator.
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
148pub enum ArithmeticOp {
149 /// `+`
150 Add,
151 /// `-`
152 Subtract,
153 /// `*`
154 Multiply,
155 /// `div`
156 Divide,
157 /// `idiv`
158 IntegerDivide,
159 /// `mod`
160 Modulo,
161}
162
163/// A comparison operator.
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
165pub enum ComparisonOp {
166 /// A general comparison (\[22\] `GeneralComp`): existentially quantified over both
167 /// operand sequences.
168 General(CompareKind),
169 /// A value comparison (\[23\] `ValueComp`): on single atomic values.
170 Value(CompareKind),
171}
172
173/// Which comparison: `=`/`eq`, `!=`/`ne`, `<`/`lt`, `<=`/`le`, `>`/`gt`, `>=`/`ge`.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
175pub enum CompareKind {
176 /// `=` or `eq`
177 Eq,
178 /// `!=` or `ne`
179 Ne,
180 /// `<` or `lt`
181 Lt,
182 /// `<=` or `le`
183 Le,
184 /// `>` or `gt`
185 Gt,
186 /// `>=` or `ge`
187 Ge,
188}
189
190/// A path expression: an optional leading `/` and the steps between slashes.
191#[derive(Debug, Clone, PartialEq, Eq)]
192pub struct PathExpr {
193 /// Whether the path starts at the root of the context node's tree.
194 pub start: PathStart,
195 /// The steps; empty only for the lone `/`. `//` appears as a
196 /// `descendant-or-self::node()` step.
197 pub steps: Vec<Step>,
198}
199
200/// Where a path expression starts.
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
202pub enum PathStart {
203 /// At the context item.
204 Relative,
205 /// At the root of the tree that contains the context node (`/`, `//`).
206 Root,
207}
208
209/// One step of a path (\[27\] `StepExpr`).
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub enum Step {
212 /// An axis step (\[28\] `AxisStep`).
213 Axis(AxisStep),
214 /// A filter expression used as a step (\[38\] `FilterExpr`): a function call, a
215 /// variable, `.`, a parenthesized expression or a literal, with any predicates.
216 Expr(Expr),
217}
218
219/// `axis::test[predicate]...`
220#[derive(Debug, Clone, PartialEq, Eq)]
221pub struct AxisStep {
222 /// The axis.
223 pub axis: Axis,
224 /// The node test.
225 pub test: NodeTest,
226 /// The predicates, applied left to right.
227 pub predicates: Vec<Expr>,
228}
229
230/// The supported axes. `descendant`, `following` and `namespace` are refused by the parser.
231#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
232pub enum Axis {
233 /// `child::` (also the default axis)
234 Child,
235 /// `attribute::` or `@`
236 Attribute,
237 /// `self::`
238 SelfAxis,
239 /// `descendant-or-self::` (from `//`)
240 DescendantOrSelf,
241 /// `following-sibling::`
242 FollowingSibling,
243 /// `parent::` or `..`
244 Parent,
245 /// `ancestor::`
246 Ancestor,
247 /// `ancestor-or-self::`
248 AncestorOrSelf,
249 /// `preceding-sibling::`
250 PrecedingSibling,
251 /// `preceding::`
252 Preceding,
253}
254
255impl Axis {
256 /// The axis name as written before `::`.
257 #[must_use]
258 pub fn name(self) -> &'static str {
259 match self {
260 Self::Child => "child",
261 Self::Attribute => "attribute",
262 Self::SelfAxis => "self",
263 Self::DescendantOrSelf => "descendant-or-self",
264 Self::FollowingSibling => "following-sibling",
265 Self::Parent => "parent",
266 Self::Ancestor => "ancestor",
267 Self::AncestorOrSelf => "ancestor-or-self",
268 Self::PrecedingSibling => "preceding-sibling",
269 Self::Preceding => "preceding",
270 }
271 }
272
273 /// Whether the axis is a reverse axis (positions count backwards in a predicate).
274 #[must_use]
275 pub fn is_reverse(self) -> bool {
276 matches!(
277 self,
278 Self::Parent
279 | Self::Ancestor
280 | Self::AncestorOrSelf
281 | Self::PrecedingSibling
282 | Self::Preceding
283 )
284 }
285}
286
287/// A node test (\[35\] `NodeTest`).
288#[derive(Debug, Clone, PartialEq, Eq)]
289pub enum NodeTest {
290 /// A name test (\[36\] `NameTest`).
291 Name(NameTest),
292 /// A kind test (\[54\] `KindTest`).
293 Kind(KindTest),
294}
295
296/// A name test: a `QName` or a wildcard (\[36\] `NameTest`, \[37\] `Wildcard`).
297#[derive(Debug, Clone, PartialEq, Eq)]
298pub enum NameTest {
299 /// A name. Unprefixed element names take the default element namespace, unprefixed
300 /// attribute names are in no namespace.
301 Name(QName),
302 /// `*`
303 Any,
304 /// `prefix:*`: any local name in one namespace.
305 AnyLocal {
306 /// The prefix as written.
307 prefix: String,
308 /// The namespace it is bound to.
309 namespace: String,
310 },
311 /// `*:local`: one local name in any namespace (or none).
312 AnyNamespace {
313 /// The local name.
314 local: String,
315 },
316}
317
318/// The supported kind tests (\[54\] `KindTest`). `document-node()`, `schema-element()`,
319/// `schema-attribute()`, `processing-instruction(name)` and type names in `element()` and
320/// `attribute()` are refused by the parser.
321#[derive(Debug, Clone, PartialEq, Eq)]
322pub enum KindTest {
323 /// `node()`
324 AnyKind,
325 /// `text()`
326 Text,
327 /// `comment()`
328 Comment,
329 /// `processing-instruction()`
330 ProcessingInstruction,
331 /// `element()`, `element(*)` or `element(name)`.
332 Element(Option<NameOrWildcard>),
333 /// `attribute()`, `attribute(*)` or `attribute(name)`.
334 Attribute(Option<NameOrWildcard>),
335}
336
337/// The argument of `element(...)` or `attribute(...)`.
338#[derive(Debug, Clone, PartialEq, Eq)]
339pub enum NameOrWildcard {
340 /// A name.
341 Name(QName),
342 /// `*`
343 Wildcard,
344}
345
346/// A sequence type (\[50\] `SequenceType`), as in `instance of` and XSLT `as` attributes.
347/// `empty-sequence()` and `item()` are refused by the parser.
348#[derive(Debug, Clone, PartialEq, Eq)]
349pub struct SequenceType {
350 /// The item type.
351 pub item: ItemType,
352 /// How many items.
353 pub occurrence: Occurrence,
354}
355
356/// An item type (\[52\] `ItemType`).
357#[derive(Debug, Clone, PartialEq, Eq)]
358pub enum ItemType {
359 /// An atomic type.
360 Atomic(AtomicType),
361 /// A node kind.
362 Kind(KindTest),
363}
364
365/// An occurrence indicator (\[51\] `OccurrenceIndicator`), or its absence.
366#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
367pub enum Occurrence {
368 /// Exactly one (no indicator).
369 One,
370 /// `?`
371 ZeroOrOne,
372 /// `*`
373 ZeroOrMore,
374 /// `+`
375 OneOrMore,
376}
377
378/// A single type (\[49\] `SingleType`), the target of `castable as`.
379#[derive(Debug, Clone, PartialEq, Eq)]
380pub struct SingleType {
381 /// The atomic type.
382 pub atomic: AtomicType,
383 /// Whether `?` follows it (the empty sequence is then castable).
384 pub allows_empty: bool,
385}
386
387/// An atomic type name (\[53\] `AtomicType`), limited to the supported types.
388#[derive(Debug, Clone, PartialEq, Eq)]
389pub struct AtomicType {
390 /// The name as written and resolved.
391 pub name: QName,
392 /// Which type it is.
393 pub kind: AtomicKind,
394}
395
396/// The atomic types accepted in sequence types and `castable as`.
397#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
398pub enum AtomicKind {
399 /// `xs:string`
400 String,
401 /// `xs:anyURI`
402 AnyUri,
403 /// `xs:boolean`
404 Boolean,
405 /// `xs:integer`
406 Integer,
407 /// `xs:decimal`
408 Decimal,
409 /// `xs:date`
410 Date,
411}
412
413impl AtomicKind {
414 /// The kind whose local name in the XML Schema namespace is `local`, if supported.
415 #[must_use]
416 pub fn from_local_name(local: &str) -> Option<Self> {
417 Some(match local {
418 "string" => Self::String,
419 "anyURI" => Self::AnyUri,
420 "boolean" => Self::Boolean,
421 "integer" => Self::Integer,
422 "decimal" => Self::Decimal,
423 "date" => Self::Date,
424 _ => return None,
425 })
426 }
427}
428
429/// An XSLT match pattern: one or more alternatives separated by `|` (XSLT 2.0 section 5.5.2
430/// production \[1\] `Pattern`).
431#[derive(Debug, Clone, PartialEq, Eq)]
432pub struct Pattern {
433 /// The alternatives, in source order (at least one).
434 pub alternatives: Vec<PatternAlternative>,
435}
436
437/// One alternative of a pattern.
438#[derive(Debug, Clone, PartialEq, Eq)]
439pub enum PatternAlternative {
440 /// `/`: matches a document node.
441 DocumentRoot,
442 /// `root()` (an XSLT 3.0 `RootedPath`, accepted by XSLT 3.0 processors running a 2.0
443 /// stylesheet): matches the root of any tree.
444 RootFunction,
445 /// A path pattern (XSLT 2.0 production \[2\] `PathPattern`, without `IdKeyPattern`).
446 Path(PathPattern),
447 /// `(pattern)[predicate]...` (XSLT 3.0 `PostfixExprP`): at least one predicate, and
448 /// nothing after it.
449 Parenthesized {
450 /// The pattern inside the parentheses.
451 inner: Box<Pattern>,
452 /// The predicates (at least one).
453 predicates: Vec<Expr>,
454 },
455}
456
457/// A path pattern: `step`, `/step`, `//step`, then steps separated by `/` or `//`.
458#[derive(Debug, Clone, PartialEq, Eq)]
459pub struct PathPattern {
460 /// What precedes the first step.
461 pub anchor: PatternAnchor,
462 /// The first step.
463 pub first: PatternStep,
464 /// The following steps, each with the separator before it.
465 pub rest: Vec<(PatternLink, PatternStep)>,
466}
467
468/// What precedes the first step of a path pattern.
469#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
470pub enum PatternAnchor {
471 /// Nothing: the first step may be at any depth.
472 Relative,
473 /// `/`: the first step is a child of a document node.
474 Root,
475 /// `//`: the first step is a descendant of a document node.
476 RootDescendant,
477}
478
479/// The separator between two pattern steps.
480#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
481pub enum PatternLink {
482 /// `/`: the previous step matches the parent.
483 Child,
484 /// `//`: the previous step matches an ancestor.
485 Descendant,
486}
487
488/// A pattern step (XSLT 2.0 production \[4\] `PatternStep`).
489#[derive(Debug, Clone, PartialEq, Eq)]
490pub struct PatternStep {
491 /// The axis: patterns allow only `child` and `attribute`.
492 pub axis: PatternAxis,
493 /// The node test.
494 pub test: NodeTest,
495 /// The predicates.
496 pub predicates: Vec<Expr>,
497}
498
499/// The axes allowed in a pattern step (XSLT 2.0 production \[5\] `PatternAxis`).
500#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
501pub enum PatternAxis {
502 /// `child::` or no axis.
503 Child,
504 /// `attribute::` or `@`.
505 Attribute,
506}
507
508/// An attribute value template: literal text and `{expression}` parts.
509#[derive(Debug, Clone, PartialEq, Eq)]
510pub struct Avt {
511 /// The parts, in order; adjacent text parts never occur.
512 pub parts: Vec<AvtPart>,
513}
514
515impl Avt {
516 /// The value, when the template has no expression part.
517 #[must_use]
518 pub fn as_literal(&self) -> Option<String> {
519 let mut out = String::new();
520 for part in &self.parts {
521 match part {
522 AvtPart::Text(text) => out.push_str(text),
523 AvtPart::Expr(_) => return None,
524 }
525 }
526 Some(out)
527 }
528}
529
530/// One part of an attribute value template.
531#[derive(Debug, Clone, PartialEq, Eq)]
532pub enum AvtPart {
533 /// Literal text, with `{{` and `}}` already reduced.
534 Text(String),
535 /// An `{expression}`.
536 Expr(Expr),
537}