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-or-self::` (from `//`)
247 DescendantOrSelf,
248 /// `following-sibling::`
249 FollowingSibling,
250 /// `parent::` or `..`
251 Parent,
252 /// `ancestor::`
253 Ancestor,
254 /// `ancestor-or-self::`
255 AncestorOrSelf,
256 /// `preceding-sibling::`
257 PrecedingSibling,
258 /// `preceding::`
259 Preceding,
260}
261
262impl Axis {
263 /// The axis name as written before `::`.
264 #[must_use]
265 pub fn name(self) -> &'static str {
266 match self {
267 Self::Child => "child",
268 Self::Attribute => "attribute",
269 Self::SelfAxis => "self",
270 Self::DescendantOrSelf => "descendant-or-self",
271 Self::FollowingSibling => "following-sibling",
272 Self::Parent => "parent",
273 Self::Ancestor => "ancestor",
274 Self::AncestorOrSelf => "ancestor-or-self",
275 Self::PrecedingSibling => "preceding-sibling",
276 Self::Preceding => "preceding",
277 }
278 }
279
280 /// Whether the axis is a reverse axis (positions count backwards in a predicate).
281 #[must_use]
282 pub fn is_reverse(self) -> bool {
283 matches!(
284 self,
285 Self::Parent
286 | Self::Ancestor
287 | Self::AncestorOrSelf
288 | Self::PrecedingSibling
289 | Self::Preceding
290 )
291 }
292}
293
294/// A node test (\[35\] `NodeTest`).
295#[derive(Debug, Clone, PartialEq, Eq)]
296pub enum NodeTest {
297 /// A name test (\[36\] `NameTest`).
298 Name(NameTest),
299 /// A kind test (\[54\] `KindTest`).
300 Kind(KindTest),
301}
302
303/// A name test: a `QName` or a wildcard (\[36\] `NameTest`, \[37\] `Wildcard`).
304#[derive(Debug, Clone, PartialEq, Eq)]
305pub enum NameTest {
306 /// A name. Unprefixed element names take the default element namespace, unprefixed
307 /// attribute names are in no namespace.
308 Name(QName),
309 /// `*`
310 Any,
311 /// `prefix:*`: any local name in one namespace.
312 AnyLocal {
313 /// The prefix as written.
314 prefix: String,
315 /// The namespace it is bound to.
316 namespace: String,
317 },
318 /// `*:local`: one local name in any namespace (or none).
319 AnyNamespace {
320 /// The local name.
321 local: String,
322 },
323}
324
325/// The supported kind tests (\[54\] `KindTest`). `document-node()`, `schema-element()`,
326/// `schema-attribute()`, `processing-instruction(name)` and type names in `element()` and
327/// `attribute()` are refused by the parser.
328#[derive(Debug, Clone, PartialEq, Eq)]
329pub enum KindTest {
330 /// `node()`
331 AnyKind,
332 /// `text()`
333 Text,
334 /// `comment()`
335 Comment,
336 /// `processing-instruction()`
337 ProcessingInstruction,
338 /// `element()`, `element(*)` or `element(name)`.
339 Element(Option<NameOrWildcard>),
340 /// `attribute()`, `attribute(*)` or `attribute(name)`.
341 Attribute(Option<NameOrWildcard>),
342}
343
344/// The argument of `element(...)` or `attribute(...)`.
345#[derive(Debug, Clone, PartialEq, Eq)]
346pub enum NameOrWildcard {
347 /// A name.
348 Name(QName),
349 /// `*`
350 Wildcard,
351}
352
353/// A sequence type (\[50\] `SequenceType`), as in `instance of` and XSLT `as` attributes.
354/// `empty-sequence()` and `item()` are refused by the parser.
355#[derive(Debug, Clone, PartialEq, Eq)]
356pub struct SequenceType {
357 /// The item type.
358 pub item: ItemType,
359 /// How many items.
360 pub occurrence: Occurrence,
361}
362
363/// An item type (\[52\] `ItemType`).
364#[derive(Debug, Clone, PartialEq, Eq)]
365pub enum ItemType {
366 /// An atomic type.
367 Atomic(AtomicType),
368 /// A node kind.
369 Kind(KindTest),
370}
371
372/// An occurrence indicator (\[51\] `OccurrenceIndicator`), or its absence.
373#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
374pub enum Occurrence {
375 /// Exactly one (no indicator).
376 One,
377 /// `?`
378 ZeroOrOne,
379 /// `*`
380 ZeroOrMore,
381 /// `+`
382 OneOrMore,
383}
384
385/// A single type (\[49\] `SingleType`), the target of `cast as` and `castable as`.
386#[derive(Debug, Clone, PartialEq, Eq)]
387pub struct SingleType {
388 /// The atomic type.
389 pub atomic: AtomicType,
390 /// Whether `?` follows it (the empty sequence is then castable).
391 pub allows_empty: bool,
392}
393
394/// An atomic type name (\[53\] `AtomicType`), limited to the supported types.
395#[derive(Debug, Clone, PartialEq, Eq)]
396pub struct AtomicType {
397 /// The name as written and resolved.
398 pub name: QName,
399 /// Which type it is.
400 pub kind: AtomicKind,
401}
402
403/// The atomic types accepted in sequence types and `castable as`.
404#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
405pub enum AtomicKind {
406 /// `xs:string`
407 String,
408 /// `xs:anyURI`
409 AnyUri,
410 /// `xs:boolean`
411 Boolean,
412 /// `xs:integer`
413 Integer,
414 /// `xs:decimal`
415 Decimal,
416 /// `xs:date`
417 Date,
418}
419
420impl AtomicKind {
421 /// The kind whose local name in the XML Schema namespace is `local`, if supported.
422 #[must_use]
423 pub fn from_local_name(local: &str) -> Option<Self> {
424 Some(match local {
425 "string" => Self::String,
426 "anyURI" => Self::AnyUri,
427 "boolean" => Self::Boolean,
428 "integer" => Self::Integer,
429 "decimal" => Self::Decimal,
430 "date" => Self::Date,
431 _ => return None,
432 })
433 }
434}
435
436/// An XSLT match pattern: one or more alternatives separated by `|` (XSLT 2.0 section 5.5.2
437/// production \[1\] `Pattern`).
438#[derive(Debug, Clone, PartialEq, Eq)]
439pub struct Pattern {
440 /// The alternatives, in source order (at least one).
441 pub alternatives: Vec<PatternAlternative>,
442}
443
444/// One alternative of a pattern.
445#[derive(Debug, Clone, PartialEq, Eq)]
446pub enum PatternAlternative {
447 /// `/`: matches a document node.
448 DocumentRoot,
449 /// `root()` (an XSLT 3.0 `RootedPath`, accepted by XSLT 3.0 processors running a 2.0
450 /// stylesheet): matches the root of any tree.
451 RootFunction,
452 /// A path pattern (XSLT 2.0 production \[2\] `PathPattern`, without `IdKeyPattern`).
453 Path(PathPattern),
454 /// `(pattern)[predicate]...` (XSLT 3.0 `PostfixExprP`): at least one predicate, and
455 /// nothing after it.
456 Parenthesized {
457 /// The pattern inside the parentheses.
458 inner: Box<Pattern>,
459 /// The predicates (at least one).
460 predicates: Vec<Expr>,
461 },
462}
463
464/// A path pattern: `step`, `/step`, `//step`, then steps separated by `/` or `//`.
465#[derive(Debug, Clone, PartialEq, Eq)]
466pub struct PathPattern {
467 /// What precedes the first step.
468 pub anchor: PatternAnchor,
469 /// The first step.
470 pub first: PatternStep,
471 /// The following steps, each with the separator before it.
472 pub rest: Vec<(PatternLink, PatternStep)>,
473}
474
475/// What precedes the first step of a path pattern.
476#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
477pub enum PatternAnchor {
478 /// Nothing: the first step may be at any depth.
479 Relative,
480 /// `/`: the first step is a child of a document node.
481 Root,
482 /// `//`: the first step is a descendant of a document node.
483 RootDescendant,
484}
485
486/// The separator between two pattern steps.
487#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
488pub enum PatternLink {
489 /// `/`: the previous step matches the parent.
490 Child,
491 /// `//`: the previous step matches an ancestor.
492 Descendant,
493}
494
495/// A pattern step (XSLT 2.0 production \[4\] `PatternStep`).
496#[derive(Debug, Clone, PartialEq, Eq)]
497pub struct PatternStep {
498 /// The axis: patterns allow only `child` and `attribute`.
499 pub axis: PatternAxis,
500 /// The node test.
501 pub test: NodeTest,
502 /// The predicates.
503 pub predicates: Vec<Expr>,
504}
505
506/// The axes allowed in a pattern step (XSLT 2.0 production \[5\] `PatternAxis`).
507#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
508pub enum PatternAxis {
509 /// `child::` or no axis.
510 Child,
511 /// `attribute::` or `@`.
512 Attribute,
513}
514
515/// An attribute value template: literal text and `{expression}` parts.
516#[derive(Debug, Clone, PartialEq, Eq)]
517pub struct Avt {
518 /// The parts, in order; adjacent text parts never occur.
519 pub parts: Vec<AvtPart>,
520}
521
522impl Avt {
523 /// The value, when the template has no expression part.
524 #[must_use]
525 pub fn as_literal(&self) -> Option<String> {
526 let mut out = String::new();
527 for part in &self.parts {
528 match part {
529 AvtPart::Text(text) => out.push_str(text),
530 AvtPart::Expr(_) => return None,
531 }
532 }
533 Some(out)
534 }
535}
536
537/// One part of an attribute value template.
538#[derive(Debug, Clone, PartialEq, Eq)]
539pub enum AvtPart {
540 /// Literal text, with `{{` and `}}` already reduced.
541 Text(String),
542 /// An `{expression}`.
543 Expr(Expr),
544}