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