Skip to main content

einvoice_xpath_eval/
eval.rs

1//! Evaluation of compiled expressions.
2//!
3//! Sequences are produced lazily, as iterators of fallible items, so that a consumer that
4//! needs only part of a sequence (an effective boolean value, `exists`, a general
5//! comparison that finds a match, a positional predicate, `some` and `every`) stops
6//! reading it there, as Saxon does. This decides which dynamic errors are raised: an item
7//! that is never read never raises its error. Sequences whose order is not known
8//! statically (see `compile`) are materialised and sorted.
9
10use std::rc::Rc;
11
12use einvoice_xdm::{AtomicValue, Integer, ops};
13
14use crate::compile::{
15    Calculator, CompareStrategy, CompiledExpr, Expr, ItemTest, PathMode, Predicate, PredicateKind,
16    Step,
17};
18use crate::context::{Context, DynamicContext};
19use crate::error::{Error, ErrorCode, Result, err};
20use crate::functions::Builtin;
21use crate::item::Item;
22use crate::tree::{Node, NodeAxis};
23
24/// A lazily produced sequence.
25pub(crate) type Iter<'s> = Box<dyn Iterator<Item = Result<Item>> + 's>;
26
27/// The range variables in scope, innermost first.
28#[derive(Debug)]
29pub(crate) struct Env {
30    item: Item,
31    parent: Option<Rc<Env>>,
32}
33
34/// The focus and range variables of a subexpression.
35#[derive(Debug, Clone)]
36pub(crate) struct Ctx {
37    pub(crate) item: Option<Item>,
38    pub(crate) position: usize,
39    /// `None` when the size was not counted: the compiler counts it wherever `last()`
40    /// is called.
41    pub(crate) size: Option<usize>,
42    env: Option<Rc<Env>>,
43}
44
45impl Ctx {
46    fn with_focus(&self, item: Item, position: usize, size: Option<usize>) -> Self {
47        Self {
48            item: Some(item),
49            position,
50            size,
51            env: self.env.clone(),
52        }
53    }
54
55    fn with_local(&self, item: Item) -> Self {
56        Self {
57            env: Some(Rc::new(Env {
58                item,
59                parent: self.env.clone(),
60            })),
61            ..self.clone()
62        }
63    }
64}
65
66/// One evaluation: the dynamic context and the current item.
67pub(crate) struct Run<'a> {
68    pub(crate) dc: &'a DynamicContext<'a>,
69    pub(crate) current: Option<Item>,
70}
71
72pub(crate) fn once<'s>(item: Item) -> Iter<'s> {
73    Box::new(std::iter::once(Ok(item)))
74}
75
76pub(crate) fn failed<'s>(error: Error) -> Iter<'s> {
77    Box::new(std::iter::once(Err(error)))
78}
79
80pub(crate) fn from_vec<'s>(items: Vec<Item>) -> Iter<'s> {
81    Box::new(items.into_iter().map(Ok))
82}
83
84pub(crate) fn sort_nodes(mut nodes: Vec<Node>) -> Vec<Item> {
85    nodes.sort_by(Node::cmp_document_order);
86    nodes.dedup();
87    nodes.into_iter().map(Item::Node).collect()
88}
89
90/// The effective boolean value of a sequence, reading at most two items.
91fn ebv_of(mut items: Iter<'_>) -> Result<bool> {
92    match items.next() {
93        None => Ok(false),
94        Some(first) => match first? {
95            Item::Node(_) => Ok(true),
96            Item::Atomic(value) => {
97                if let Some(second) = items.next() {
98                    second?;
99                    return err(
100                        ErrorCode::Forg0006,
101                        format!(
102                            "Effective boolean value is not defined for a sequence of two or more items starting with a {} value",
103                            value.atomic_type()
104                        ),
105                    );
106                }
107                Ok(ops::effective_boolean_value(&value)?)
108            }
109        },
110    }
111}
112
113impl CompiledExpr {
114    /// Evaluates the expression: the whole sequence.
115    ///
116    /// # Errors
117    ///
118    /// The dynamic error the evaluation raises.
119    pub fn evaluate(&self, dc: &DynamicContext<'_>, context: &Context) -> Result<Vec<Item>> {
120        let run = Run {
121            dc,
122            current: context.current.clone(),
123        };
124        let ctx = initial(context);
125        run.seq(&self.expr, &ctx)?.collect()
126    }
127
128    /// Evaluates the effective boolean value of the expression, reading no more of the
129    /// sequence than needed (as `xsl:if` and `xsl:when` do).
130    ///
131    /// # Errors
132    ///
133    /// The dynamic error the evaluation raises.
134    pub fn effective_boolean_value(
135        &self,
136        dc: &DynamicContext<'_>,
137        context: &Context,
138    ) -> Result<bool> {
139        let run = Run {
140            dc,
141            current: context.current.clone(),
142        };
143        run.ebv(&self.expr, &initial(context))
144    }
145}
146
147fn initial(context: &Context) -> Ctx {
148    match &context.focus {
149        Some(focus) => Ctx {
150            item: Some(focus.item.clone()),
151            position: focus.position,
152            size: Some(focus.size),
153            env: None,
154        },
155        None => Ctx {
156            item: None,
157            position: 0,
158            size: None,
159            env: None,
160        },
161    }
162}
163
164fn boolean<'s>(value: bool) -> Iter<'s> {
165    once(Item::Atomic(AtomicValue::Boolean(value)))
166}
167
168impl<'a> Run<'a> {
169    /// The sequence of `expr`, lazily.
170    pub(crate) fn seq<'s>(&'s self, expr: &'s Expr, ctx: &Ctx) -> Result<Iter<'s>>
171    where
172        'a: 's,
173    {
174        Ok(match expr {
175            Expr::Literal(value) => once(Item::Atomic(value.clone())),
176            Expr::ContextItem => once(context_item(ctx)?),
177            Expr::Root => {
178                let node = context_node(ctx, "the root expression /")?;
179                once(Item::Node(node.root()))
180            }
181            Expr::Local(depth) => once(local(ctx, *depth)?),
182            Expr::External(id) => {
183                let value = self.dc.host.variable(*id)?;
184                Box::new((0..value.len()).map(move |i| Ok(value[i].clone())))
185            }
186            Expr::Sequence(items) => {
187                let ctx = ctx.clone();
188                Box::new(
189                    items
190                        .iter()
191                        .flat_map(move |e| self.seq(e, &ctx).unwrap_or_else(failed)),
192                )
193            }
194            Expr::Filter { base, predicates } => {
195                let input = self.seq(base, ctx)?;
196                self.filter(input, predicates, ctx)?
197            }
198            Expr::Step(step) => self.step(step, ctx)?,
199            Expr::Path {
200                lhs,
201                rhs,
202                mode,
203                rhs_uses_last,
204            } => self.path(lhs, rhs, *mode, *rhs_uses_last, ctx)?,
205            Expr::Union {
206                lhs,
207                rhs,
208                lhs_ordered,
209                rhs_ordered,
210            } => {
211                let left = self.union_operand(lhs, *lhs_ordered, ctx, "first")?;
212                let right = self.union_operand(rhs, *rhs_ordered, ctx, "second")?;
213                Box::new(Merge {
214                    left,
215                    right,
216                    heads: None,
217                })
218            }
219            Expr::Range(lhs, rhs) => self.range(lhs, rhs, ctx)?,
220            Expr::If {
221                condition,
222                then,
223                otherwise,
224            } => {
225                let branch = if self.ebv(condition, ctx)? {
226                    then
227                } else {
228                    otherwise
229                };
230                self.seq(branch, ctx)?
231            }
232            Expr::For { sequence, body } => {
233                let input = self.seq(sequence, ctx)?;
234                let ctx = ctx.clone();
235                Box::new(input.flat_map(move |item| match item {
236                    Ok(item) => self.seq(body, &ctx.with_local(item)).unwrap_or_else(failed),
237                    Err(e) => failed(e),
238                }))
239            }
240            Expr::Call {
241                function,
242                args,
243                data,
244            } => self.call(*function, args, data, ctx)?,
245            Expr::HostCall { id, args } => {
246                let values = args
247                    .iter()
248                    .map(|a| self.seq(a, ctx)?.collect::<Result<Vec<_>>>())
249                    .collect::<Result<Vec<_>>>()?;
250                from_vec(self.dc.host.call_function(*id, values)?)
251            }
252            Expr::Cast { .. } => match self.cast(expr, ctx)? {
253                Some(value) => once(Item::Atomic(value)),
254                None => Box::new(std::iter::empty()),
255            },
256            Expr::Negate(..) | Expr::Arithmetic { .. } | Expr::ValueComparison { .. } => {
257                match self.atomic_operation(expr, ctx)? {
258                    Some(value) => once(Item::Atomic(value)),
259                    None => Box::new(std::iter::empty()),
260                }
261            }
262            Expr::GeneralComparison { .. }
263            | Expr::And(..)
264            | Expr::Or(..)
265            | Expr::Quantified { .. }
266            | Expr::InstanceOf { .. }
267            | Expr::Castable { .. } => boolean(self.ebv(expr, ctx)?),
268        })
269    }
270
271    /// `operand cast as target`, `?` when `allows_empty`: the atomized operand, at most
272    /// one item, cast to the target (up-cast for an operand statically typed
273    /// `xs:integer` and the target `xs:decimal`).
274    fn cast(&self, expr: &Expr, ctx: &Ctx) -> Result<Option<AtomicValue>> {
275        let Expr::Cast {
276            operand,
277            target,
278            allows_empty,
279            upcast,
280        } = expr
281        else {
282            return err(ErrorCode::Internal, "not a cast");
283        };
284        match self.atomic_opt(operand, ctx, "value in 'cast as' expression")? {
285            None if *allows_empty => Ok(None),
286            None => err(
287                ErrorCode::Xpty0004,
288                "An empty sequence is not allowed as the value in 'cast as' expression",
289            ),
290            Some(value) if *upcast => Ok(Some(value.upcast(*target)?)),
291            Some(value) => Ok(Some(value.cast(*target)?)),
292        }
293    }
294
295    /// Unary minus, arithmetic and value comparisons: the operands are atomized and read
296    /// left to right, and an empty one makes the result empty without reading the next.
297    fn atomic_operation(&self, expr: &Expr, ctx: &Ctx) -> Result<Option<AtomicValue>> {
298        let operands = |lhs: &Expr,
299                        rhs: &Expr,
300                        what: &str|
301         -> Result<Option<(AtomicValue, AtomicValue)>> {
302            let Some(a) = self.atomic_opt(lhs, ctx, &format!("first operand of {what}"))? else {
303                return Ok(None);
304            };
305            let Some(b) = self.atomic_opt(rhs, ctx, &format!("second operand of {what}"))? else {
306                return Ok(None);
307            };
308            Ok(Some((a, b)))
309        };
310        Ok(match expr {
311            Expr::Negate(operand) => match self.atomic_opt(operand, ctx, "operand of '-'")? {
312                Some(value) => Some(ops::negate(&value)?),
313                None => None,
314            },
315            Expr::Arithmetic {
316                op,
317                lhs,
318                rhs,
319                calculator,
320            } => match operands(lhs, rhs, &format!("'{}'", arithmetic_name(*op)))? {
321                Some((a, b)) => Some(arithmetic(*op, *calculator, &a, &b)?),
322                None => None,
323            },
324            Expr::ValueComparison { op, lhs, rhs } => {
325                match operands(lhs, rhs, "a value comparison")? {
326                    Some((a, b)) => Some(AtomicValue::Boolean(ops::value_compare(
327                        &a,
328                        *op,
329                        &b,
330                        self.dc.implicit_timezone,
331                    )?)),
332                    None => None,
333                }
334            }
335            _ => return err(ErrorCode::Internal, "not an atomic operation"),
336        })
337    }
338
339    /// `lhs and rhs` (`decisive` false) or `lhs or rhs` (`decisive` true), as Saxon-HE
340    /// 12.10 evaluates them (`AndElaborator`, `OrElaborator`): the first operand first,
341    /// and its value decides when it is `decisive`; when it raises a dynamic error, the
342    /// second operand is evaluated all the same, and the error is raised only if the
343    /// second does not decide the result (an error of the second wins). A refusal or a
344    /// bug of this crate is never set aside.
345    fn and_or(&self, lhs: &Expr, rhs: &Expr, decisive: bool, ctx: &Ctx) -> Result<bool> {
346        match self.ebv(lhs, ctx) {
347            Ok(value) if value == decisive => Ok(decisive),
348            Ok(_) => self.ebv(rhs, ctx),
349            Err(e) if matches!(e.code(), ErrorCode::Unsupported | ErrorCode::Internal) => Err(e),
350            Err(e) => {
351                if self.ebv(rhs, ctx)? == decisive {
352                    Ok(decisive)
353                } else {
354                    Err(e)
355                }
356            }
357        }
358    }
359
360    /// The effective boolean value of `expr`.
361    pub(crate) fn ebv(&self, expr: &Expr, ctx: &Ctx) -> Result<bool> {
362        match expr {
363            Expr::GeneralComparison {
364                op,
365                lhs,
366                rhs,
367                strategy,
368            } => self.general_comparison(*op, lhs, rhs, *strategy, ctx),
369            Expr::And(lhs, rhs) => self.and_or(lhs, rhs, false, ctx),
370            // As Saxon: the union is not empty when one operand is not, read in turn.
371            Expr::Union { lhs, rhs, .. } => {
372                Ok(self.has_node(lhs, ctx, "first")? || self.has_node(rhs, ctx, "second")?)
373            }
374            Expr::Or(lhs, rhs) => self.and_or(lhs, rhs, true, ctx),
375            Expr::Quantified {
376                every,
377                sequence,
378                satisfies,
379            } => {
380                for item in self.seq(sequence, ctx)? {
381                    let holds = self.ebv(satisfies, &ctx.with_local(item?))?;
382                    if holds != *every {
383                        return Ok(holds);
384                    }
385                }
386                Ok(*every)
387            }
388            Expr::InstanceOf {
389                operand,
390                item,
391                occurrence,
392            } => self.instance_of(operand, item, *occurrence, ctx),
393            Expr::Castable {
394                operand,
395                target,
396                allows_empty,
397            } => {
398                let mut values = self.seq(operand, ctx)?;
399                let Some(first) = values.next() else {
400                    return Ok(*allows_empty);
401                };
402                let first = first?.atomize();
403                if let Some(second) = values.next() {
404                    second?;
405                    return Ok(false);
406                }
407                match first.cast(*target) {
408                    Ok(_) => Ok(true),
409                    Err(e) if e.code() == einvoice_xdm::ErrorCode::Unsupported => Err(e.into()),
410                    Err(_) => Ok(false),
411                }
412            }
413            // As Saxon: `count(E)` as a boolean is `exists(E)`.
414            Expr::Call {
415                function: Builtin::Count,
416                args,
417                ..
418            } => self.non_empty(&args[0], ctx),
419            Expr::Call {
420                function: Builtin::Boolean,
421                args,
422                ..
423            } => self.ebv(&args[0], ctx),
424            _ => ebv_of(self.seq(expr, ctx)?),
425        }
426    }
427
428    /// Whether `expr` has an item (`fn:exists`), reading at most one: the operands of a
429    /// union are tried in turn, as Saxon does.
430    pub(crate) fn non_empty(&self, expr: &Expr, ctx: &Ctx) -> Result<bool> {
431        if let Expr::Union { lhs, rhs, .. } = expr {
432            return Ok(self.has_node(lhs, ctx, "first")? || self.has_node(rhs, ctx, "second")?);
433        }
434        Ok(self.seq(expr, ctx)?.next().transpose()?.is_some())
435    }
436
437    /// Whether an operand of `|` has an item (which must be a node).
438    fn has_node(&self, expr: &Expr, ctx: &Ctx, side: &str) -> Result<bool> {
439        match self.seq(expr, ctx)?.next().transpose()? {
440            None => Ok(false),
441            Some(Item::Node(_)) => Ok(true),
442            Some(Item::Atomic(value)) => err(
443                ErrorCode::Xpty0004,
444                format!(
445                    "Required item type of {side} operand of '|' is node(); supplied value has item type {}",
446                    value.atomic_type()
447                ),
448            ),
449        }
450    }
451
452    fn instance_of(
453        &self,
454        operand: &Expr,
455        test: &ItemTest,
456        occurrence: einvoice_xpath::Occurrence,
457        ctx: &Ctx,
458    ) -> Result<bool> {
459        use einvoice_xpath::Occurrence;
460        let mut count = 0_usize;
461        for item in self.seq(operand, ctx)? {
462            let item = item?;
463            count += 1;
464            let matches = match (test, &item) {
465                (ItemTest::Atomic(t), Item::Atomic(v)) => v.is_instance_of(*t),
466                (ItemTest::Node(t), Item::Node(n)) => t.matches(n.document(), n.index()),
467                _ => false,
468            };
469            if !matches {
470                return Ok(false);
471            }
472            if count > 1 && matches!(occurrence, Occurrence::One | Occurrence::ZeroOrOne) {
473                return Ok(false);
474            }
475        }
476        Ok(match occurrence {
477            Occurrence::One | Occurrence::OneOrMore => count >= 1,
478            Occurrence::ZeroOrOne | Occurrence::ZeroOrMore => true,
479        })
480    }
481
482    /// The atomized items of `expr`, lazily.
483    pub(crate) fn atomized<'s>(
484        &'s self,
485        expr: &'s Expr,
486        ctx: &Ctx,
487    ) -> Result<impl Iterator<Item = Result<AtomicValue>> + 's>
488    where
489        'a: 's,
490    {
491        Ok(self.seq(expr, ctx)?.map(|item| item.map(|i| i.atomize())))
492    }
493
494    /// At most one item of `expr`, atomized; `XPTY0004` when there are more.
495    pub(crate) fn atomic_opt(
496        &self,
497        expr: &Expr,
498        ctx: &Ctx,
499        what: &str,
500    ) -> Result<Option<AtomicValue>> {
501        Ok(self.item_opt(expr, ctx, what)?.map(|i| i.atomize()))
502    }
503
504    /// At most one item of `expr`; `XPTY0004` when there are more.
505    pub(crate) fn item_opt(&self, expr: &Expr, ctx: &Ctx, what: &str) -> Result<Option<Item>> {
506        let mut items = self.seq(expr, ctx)?;
507        let Some(first) = items.next() else {
508            return Ok(None);
509        };
510        let first = first?;
511        if let Some(second) = items.next() {
512            second?;
513            return err(
514                ErrorCode::Xpty0004,
515                format!("A sequence of more than one item is not allowed as the {what}"),
516            );
517        }
518        Ok(Some(first))
519    }
520
521    fn general_comparison(
522        &self,
523        op: ops::ComparisonOp,
524        lhs: &Expr,
525        rhs: &Expr,
526        strategy: CompareStrategy,
527        ctx: &Ctx,
528    ) -> Result<bool> {
529        let tz = self.dc.implicit_timezone;
530        let compare = |a: &AtomicValue, b: &AtomicValue| -> Result<bool> {
531            Ok(ops::general_compare(a, op, b, tz)?)
532        };
533        let what = "operand of a general comparison";
534        match strategy {
535            CompareStrategy::OneToOne => {
536                let Some(a) = self.atomic_opt(lhs, ctx, what)? else {
537                    return Ok(false);
538                };
539                let Some(b) = self.atomic_opt(rhs, ctx, what)? else {
540                    return Ok(false);
541                };
542                compare(&a, &b)
543            }
544            CompareStrategy::ManyToOne => {
545                let Some(b) = self.atomic_opt(rhs, ctx, what)? else {
546                    return Ok(false);
547                };
548                for a in self.atomized(lhs, ctx)? {
549                    if compare(&a?, &b)? {
550                        return Ok(true);
551                    }
552                }
553                Ok(false)
554            }
555            CompareStrategy::OneToMany => {
556                let Some(a) = self.atomic_opt(lhs, ctx, what)? else {
557                    return Ok(false);
558                };
559                for b in self.atomized(rhs, ctx)? {
560                    if compare(&a, &b?)? {
561                        return Ok(true);
562                    }
563                }
564                Ok(false)
565            }
566            CompareStrategy::ManyToMany => {
567                let left = self.atomized(lhs, ctx)?;
568                let right = self.atomized(rhs, ctx)?;
569                many_to_many(left, right, &compare)
570            }
571        }
572    }
573
574    fn filter<'s>(
575        &'s self,
576        input: Iter<'s>,
577        predicates: &'s [Predicate],
578        ctx: &Ctx,
579    ) -> Result<Iter<'s>>
580    where
581        'a: 's,
582    {
583        let mut current = input;
584        for predicate in predicates {
585            current = self.apply_predicate(current, predicate, ctx)?;
586        }
587        Ok(current)
588    }
589
590    fn apply_predicate<'s>(
591        &'s self,
592        input: Iter<'s>,
593        predicate: &'s Predicate,
594        ctx: &Ctx,
595    ) -> Result<Iter<'s>>
596    where
597        'a: 's,
598    {
599        if let PredicateKind::Position(position) = predicate.kind {
600            let Some(n) = position else {
601                return Ok(Box::new(std::iter::empty()));
602            };
603            let mut input = input;
604            let mut done = false;
605            return Ok(Box::new(std::iter::from_fn(move || {
606                if done {
607                    return None;
608                }
609                done = true;
610                for _ in 1..n {
611                    match input.next()? {
612                        Ok(_) => {}
613                        Err(e) => return Some(Err(e)),
614                    }
615                }
616                input.next()
617            })));
618        }
619        let (input, size): (Iter<'s>, Option<usize>) = if predicate.uses_last {
620            let items = input.collect::<Result<Vec<_>>>()?;
621            let size = items.len();
622            (from_vec(items), Some(size))
623        } else {
624            (input, None)
625        };
626        let ctx = ctx.clone();
627        let mut position = 0;
628        Ok(Box::new(input.filter_map(move |item| {
629            let item = match item {
630                Ok(item) => item,
631                Err(e) => return Some(Err(e)),
632            };
633            position += 1;
634            let focus = ctx.with_focus(item.clone(), position, size);
635            match self.predicate_holds(predicate, &focus) {
636                Ok(true) => Some(Ok(item)),
637                Ok(false) => None,
638                Err(e) => Some(Err(e)),
639            }
640        })))
641    }
642
643    fn predicate_holds(&self, predicate: &Predicate, ctx: &Ctx) -> Result<bool> {
644        if predicate.kind == PredicateKind::Boolean {
645            return self.ebv(&predicate.expr, ctx);
646        }
647        let mut values = self.seq(&predicate.expr, ctx)?;
648        let Some(first) = values.next() else {
649            return Ok(false);
650        };
651        match first? {
652            Item::Node(_) => Ok(true),
653            Item::Atomic(value) => {
654                if let Some(second) = values.next() {
655                    second?;
656                    return err(
657                        ErrorCode::Forg0006,
658                        format!(
659                            "Effective boolean value is not defined for a sequence of two or more items starting with a {} value",
660                            value.atomic_type()
661                        ),
662                    );
663                }
664                if value.is_numeric() {
665                    let position = AtomicValue::Integer(Integer::from(
666                        i64::try_from(ctx.position).unwrap_or(i64::MAX),
667                    ));
668                    return Ok(ops::value_compare(
669                        &value,
670                        ops::ComparisonOp::Equal,
671                        &position,
672                        self.dc.implicit_timezone,
673                    )?);
674                }
675                Ok(ops::effective_boolean_value(&value)?)
676            }
677        }
678    }
679
680    fn step<'s>(&'s self, step: &'s Step, ctx: &Ctx) -> Result<Iter<'s>>
681    where
682        'a: 's,
683    {
684        let node = context_node(ctx, &format!("the axis step {}::", axis_name(step.axis)))?;
685        let doc = Rc::clone(node.document());
686        let mut cursor = doc.cursor(node.index(), step.axis);
687        let test = &step.test;
688        let nodes: Iter<'s> = Box::new(std::iter::from_fn(move || {
689            loop {
690                let index = cursor.next(&doc)?;
691                if test.matches(&doc, index) {
692                    return Some(Ok(Item::Node(Node::new(Rc::clone(&doc), index))));
693                }
694            }
695        }));
696        let filtered = self.filter(nodes, &step.predicates, ctx)?;
697        if step.axis.is_reverse() && step.axis != NodeAxis::Parent {
698            // Predicates count in axis order; the step delivers document order.
699            let mut items = filtered.collect::<Result<Vec<_>>>()?;
700            items.reverse();
701            return Ok(from_vec(items));
702        }
703        Ok(filtered)
704    }
705
706    fn path<'s>(
707        &'s self,
708        lhs: &'s Expr,
709        rhs: &'s Expr,
710        mode: PathMode,
711        rhs_uses_last: bool,
712        ctx: &Ctx,
713    ) -> Result<Iter<'s>>
714    where
715        'a: 's,
716    {
717        let left = self.seq(lhs, ctx)?;
718        let (left, size): (Iter<'s>, Option<usize>) = if rhs_uses_last {
719            let items = left.collect::<Result<Vec<_>>>()?;
720            let size = items.len();
721            (from_vec(items), Some(size))
722        } else {
723            (left, None)
724        };
725        let ctx = ctx.clone();
726        let mapped = left.enumerate().flat_map(move |(i, item)| match item {
727            Err(e) => failed(e),
728            Ok(Item::Atomic(value)) => failed(Error::new(
729                ErrorCode::Xpty0019,
730                format!(
731                    "Required item type of first operand of '/' is node(); supplied value has item type {}",
732                    value.atomic_type()
733                ),
734            )),
735            Ok(node) => self
736                .seq(rhs, &ctx.with_focus(node, i + 1, size))
737                .unwrap_or_else(failed),
738        });
739        match mode {
740            PathMode::Ordered | PathMode::Atomic => Ok(Box::new(mapped)),
741            PathMode::Sort | PathMode::Dynamic => {
742                let mut nodes = Vec::new();
743                let mut atomics = Vec::new();
744                for item in mapped {
745                    match item? {
746                        Item::Node(node) => nodes.push(node),
747                        Item::Atomic(value) => atomics.push(Item::Atomic(value)),
748                    }
749                }
750                if atomics.is_empty() {
751                    Ok(from_vec(sort_nodes(nodes)))
752                } else if nodes.is_empty() {
753                    Ok(from_vec(atomics))
754                } else {
755                    err(
756                        ErrorCode::Xpty0018,
757                        "Cannot mix nodes and atomic values in the result of a path expression",
758                    )
759                }
760            }
761        }
762    }
763
764    /// An operand of `|`, as nodes in document order: read lazily when it is known to be
765    /// in that order, sorted first otherwise.
766    fn union_operand<'s>(
767        &'s self,
768        expr: &'s Expr,
769        ordered: bool,
770        ctx: &Ctx,
771        side: &'static str,
772    ) -> Result<Box<dyn Iterator<Item = Result<Node>> + 's>>
773    where
774        'a: 's,
775    {
776        let nodes = self.seq(expr, ctx)?.map(move |item| match item? {
777            Item::Node(node) => Ok(node),
778            Item::Atomic(value) => err(
779                ErrorCode::Xpty0004,
780                format!(
781                    "Required item type of {side} operand of '|' is node(); supplied value has item type {}",
782                    value.atomic_type()
783                ),
784            ),
785        });
786        if ordered {
787            return Ok(Box::new(nodes));
788        }
789        let sorted = sort_nodes(nodes.collect::<Result<Vec<_>>>()?);
790        Ok(Box::new(sorted.into_iter().filter_map(|item| match item {
791            Item::Node(node) => Some(Ok(node)),
792            Item::Atomic(_) => None,
793        })))
794    }
795
796    fn range<'s>(&'s self, lhs: &'s Expr, rhs: &'s Expr, ctx: &Ctx) -> Result<Iter<'s>>
797    where
798        'a: 's,
799    {
800        let bound = |expr: &Expr, what: &str| -> Result<Option<i64>> {
801            let Some(value) = self.atomic_opt(expr, ctx, what)? else {
802                return Ok(None);
803            };
804            let value = match value {
805                AtomicValue::UntypedAtomic(_) => value.cast(einvoice_xdm::AtomicType::Integer)?,
806                AtomicValue::Integer(_) => value,
807                other => {
808                    return err(
809                        ErrorCode::Xpty0004,
810                        format!(
811                            "Required item type of the {what} is xs:integer; supplied value has item type {}",
812                            other.atomic_type()
813                        ),
814                    );
815                }
816            };
817            match value {
818                AtomicValue::Integer(i) => i.to_i64().map(Some).ok_or_else(|| {
819                    Error::new(ErrorCode::Unsupported, "range bound beyond 64 bits")
820                }),
821                _ => err(ErrorCode::Internal, "range bound"),
822            }
823        };
824        let Some(from) = bound(lhs, "first operand of 'to'")? else {
825            return Ok(Box::new(std::iter::empty()));
826        };
827        let Some(to) = bound(rhs, "second operand of 'to'")? else {
828            return Ok(Box::new(std::iter::empty()));
829        };
830        Ok(Box::new((from..=to).map(|i| {
831            Ok(Item::Atomic(AtomicValue::Integer(Integer::from(i))))
832        })))
833    }
834}
835
836type NodeIter<'s> = Box<dyn Iterator<Item = Result<Node>> + 's>;
837
838/// The union of two node sequences in document order, read lazily (Saxon's
839/// `VennIterator`): the first node of each operand is read on the first call.
840struct Merge<'s> {
841    left: NodeIter<'s>,
842    right: NodeIter<'s>,
843    /// The next node of each side, once started (`None` inside: that side is done).
844    heads: Option<(Option<Node>, Option<Node>)>,
845}
846
847impl Merge<'_> {
848    /// The next node of each side that needs one.
849    fn pull(
850        &mut self,
851        heads: (Option<Node>, Option<Node>),
852        left: bool,
853        right: bool,
854    ) -> Result<(Option<Node>, Option<Node>)> {
855        let (mut l, mut r) = heads;
856        if left {
857            l = self.left.next().transpose()?;
858        }
859        if right {
860            r = self.right.next().transpose()?;
861        }
862        Ok((l, r))
863    }
864
865    fn step(&mut self) -> Result<Option<Node>> {
866        let heads = if let Some(heads) = self.heads.take() {
867            heads
868        } else {
869            self.pull((None, None), true, true)?
870        };
871        let (output, left, right) = match &heads {
872            (None, None) => {
873                self.heads = Some(heads);
874                return Ok(None);
875            }
876            (Some(l), None) => (l.clone(), true, false),
877            (None, Some(r)) => (r.clone(), false, true),
878            (Some(l), Some(r)) => match l.cmp_document_order(r) {
879                std::cmp::Ordering::Less => (l.clone(), true, false),
880                std::cmp::Ordering::Greater => (r.clone(), false, true),
881                std::cmp::Ordering::Equal => (l.clone(), true, true),
882            },
883        };
884        // As Saxon's union iterator: the side just read from is read again before the
885        // node is returned.
886        self.heads = Some(self.pull(heads, left, right)?);
887        Ok(Some(output))
888    }
889}
890
891impl Iterator for Merge<'_> {
892    type Item = Result<Item>;
893
894    fn next(&mut self) -> Option<Result<Item>> {
895        self.step().map(|n| n.map(Item::Node)).transpose()
896    }
897}
898
899fn context_item(ctx: &Ctx) -> Result<Item> {
900    ctx.item
901        .clone()
902        .ok_or_else(|| Error::new(ErrorCode::Xpdy0002, "The context item is absent"))
903}
904
905/// The context item of an axis step or of `/`.
906fn context_node(ctx: &Ctx, what: &str) -> Result<Node> {
907    match &ctx.item {
908        None => err(
909            ErrorCode::Xpdy0002,
910            format!("The context item for {what} is absent"),
911        ),
912        Some(Item::Atomic(v)) => err(
913            ErrorCode::Xpty0020,
914            format!(
915                "The context item for {what} is not a node (it is a {})",
916                v.atomic_type()
917            ),
918        ),
919        Some(Item::Node(node)) => Ok(node.clone()),
920    }
921}
922
923fn local(ctx: &Ctx, depth: usize) -> Result<Item> {
924    let mut env = ctx.env.as_ref();
925    for _ in 0..depth {
926        env = env.and_then(|e| e.parent.as_ref());
927    }
928    env.map(|e| e.item.clone())
929        .ok_or_else(|| Error::new(ErrorCode::Internal, "range variable out of scope"))
930}
931
932/// Saxon's many-to-many general comparison: items are read from the two sides in turn,
933/// each compared with the items already read from the other side.
934fn many_to_many(
935    mut left: impl Iterator<Item = Result<AtomicValue>>,
936    mut right: impl Iterator<Item = Result<AtomicValue>>,
937    compare: &dyn Fn(&AtomicValue, &AtomicValue) -> Result<bool>,
938) -> Result<bool> {
939    let (mut left_done, mut right_done) = (false, false);
940    let (mut left_seen, mut right_seen) = (Vec::new(), Vec::new());
941    loop {
942        if !left_done {
943            match left.next() {
944                None => {
945                    if right_done {
946                        return Ok(false);
947                    }
948                    left_done = true;
949                }
950                Some(a) => {
951                    let a = a?;
952                    for b in &right_seen {
953                        if compare(&a, b)? {
954                            return Ok(true);
955                        }
956                    }
957                    if !right_done {
958                        left_seen.push(a);
959                    }
960                }
961            }
962        }
963        if !right_done {
964            match right.next() {
965                None => {
966                    if left_done {
967                        return Ok(false);
968                    }
969                    right_done = true;
970                }
971                Some(b) => {
972                    let b = b?;
973                    for a in &left_seen {
974                        if compare(a, &b)? {
975                            return Ok(true);
976                        }
977                    }
978                    if !left_done {
979                        right_seen.push(b);
980                    }
981                }
982            }
983        }
984    }
985}
986
987/// `a op b` with the calculator chosen at compile time. Saxon's decimal division
988/// (`DecimalDivDecimal`) divides two integer values as decimals of scale 0; any other pair
989/// of values is divided as [`ops::arithmetic`] divides it, which is what that calculator
990/// does with them.
991fn arithmetic(
992    op: ops::ArithmeticOp,
993    calculator: Calculator,
994    a: &AtomicValue,
995    b: &AtomicValue,
996) -> Result<AtomicValue> {
997    match (calculator, a, b) {
998        (Calculator::DecimalDivide, AtomicValue::Integer(i), AtomicValue::Integer(j)) => {
999            Ok(AtomicValue::Decimal(
1000                i.as_decimal_operand()
1001                    .checked_div(&j.as_decimal_operand())?,
1002            ))
1003        }
1004        _ => Ok(ops::arithmetic(op, a, b)?),
1005    }
1006}
1007
1008const fn arithmetic_name(op: ops::ArithmeticOp) -> &'static str {
1009    match op {
1010        ops::ArithmeticOp::Add => "+",
1011        ops::ArithmeticOp::Subtract => "-",
1012        ops::ArithmeticOp::Multiply => "*",
1013        ops::ArithmeticOp::Divide => "div",
1014        ops::ArithmeticOp::IntegerDivide => "idiv",
1015        ops::ArithmeticOp::Modulo => "mod",
1016    }
1017}
1018
1019const fn axis_name(axis: NodeAxis) -> &'static str {
1020    match axis {
1021        NodeAxis::Child => "child",
1022        NodeAxis::Attribute => "attribute",
1023        NodeAxis::SelfAxis => "self",
1024        NodeAxis::Descendant => "descendant",
1025        NodeAxis::DescendantOrSelf => "descendant-or-self",
1026        NodeAxis::FollowingSibling => "following-sibling",
1027        NodeAxis::Parent => "parent",
1028        NodeAxis::Ancestor => "ancestor",
1029        NodeAxis::AncestorOrSelf => "ancestor-or-self",
1030        NodeAxis::PrecedingSibling => "preceding-sibling",
1031        NodeAxis::Preceding => "preceding",
1032    }
1033}