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