1use std::borrow::Cow;
11use std::rc::Rc;
12use std::sync::Arc;
13
14use einvoice_xdm::{AtomicValue, Integer, ops};
15
16use crate::compile::{
17 Calculator, CompareStrategy, CompiledExpr, Expr, HostArg, ItemTest, NameMatch, NodeTest,
18 PathMode, Predicate, PredicateKind, Step,
19};
20use crate::context::{Context, DynamicContext, FunctionId};
21use crate::error::{Error, ErrorCode, Result, err};
22use crate::functions::Builtin;
23use crate::item::Item;
24use crate::library::ordinal;
25use crate::tree::{Cursor, Document, Node, NodeAxis, NodeKind};
26
27pub(crate) type Iter<'s> = Box<dyn Iterator<Item = Result<Item>> + 's>;
29
30#[derive(Debug, Clone, Copy)]
33pub(crate) enum What<'w> {
34 Text(&'w str),
36 Operand(bool, &'w str),
38 Argument(usize, &'w str),
40}
41
42impl std::fmt::Display for What<'_> {
43 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 match self {
45 Self::Text(text) => f.write_str(text),
46 Self::Operand(first, of) => {
47 let nth = if *first { "first" } else { "second" };
48 write!(f, "{nth} operand of {of}")
49 }
50 Self::Argument(index, function) => {
51 write!(f, "{} argument of {function}()", ordinal(*index))
52 }
53 }
54 }
55}
56
57#[derive(Debug)]
59pub(crate) struct Env {
60 item: Item,
61 parent: Option<Rc<Env>>,
62}
63
64#[derive(Debug, Clone)]
66pub(crate) struct Ctx {
67 pub(crate) item: Option<Item>,
68 pub(crate) position: usize,
69 pub(crate) size: Option<usize>,
72 env: Option<Rc<Env>>,
73}
74
75impl Ctx {
76 fn with_focus(&self, item: Item, position: usize, size: Option<usize>) -> Self {
77 Self {
78 item: Some(item),
79 position,
80 size,
81 env: self.env.clone(),
82 }
83 }
84
85 fn with_local(&self, item: Item) -> Self {
86 Self {
87 env: Some(Rc::new(Env {
88 item,
89 parent: self.env.clone(),
90 })),
91 ..self.clone()
92 }
93 }
94}
95
96#[derive(Debug, Clone)]
101pub struct Argument(ArgumentValue);
102
103#[derive(Debug, Clone)]
104enum ArgumentValue {
105 Value(Rc<[Item]>),
106 Lazy {
107 expr: Arc<Expr>,
108 ctx: Ctx,
109 current: Option<Item>,
110 },
111}
112
113impl Argument {
114 pub(crate) fn value(items: Vec<Item>) -> Self {
115 Self(ArgumentValue::Value(items.into()))
116 }
117
118 pub(crate) const fn lazy(expr: Arc<Expr>, ctx: Ctx, current: Option<Item>) -> Self {
119 Self(ArgumentValue::Lazy { expr, ctx, current })
120 }
121
122 #[must_use]
124 pub fn of(items: Vec<Item>) -> Self {
125 Self::value(items)
126 }
127
128 #[must_use]
135 pub fn site(&self) -> Option<usize> {
136 match &self.0 {
137 ArgumentValue::Value(_) => None,
138 ArgumentValue::Lazy { expr, .. } => Some(Arc::as_ptr(expr).addr()),
139 }
140 }
141
142 pub fn evaluate(&self, dc: &DynamicContext<'_>) -> Result<Vec<Item>> {
149 match &self.0 {
150 ArgumentValue::Value(items) => Ok(items.to_vec()),
151 ArgumentValue::Lazy { expr, ctx, current } => {
152 let run = Run {
153 dc,
154 current: current.clone(),
155 };
156 run.seq(expr, ctx)?.collect()
157 }
158 }
159 }
160}
161
162pub(crate) struct Run<'a> {
163 pub(crate) dc: &'a DynamicContext<'a>,
164 pub(crate) current: Option<Item>,
165}
166
167const GENERAL_OPERAND: &str = "operand of a general comparison";
169
170fn optional<'s>(value: Option<AtomicValue>) -> Iter<'s> {
172 match value {
173 Some(value) => once(Item::Atomic(value)),
174 None => Box::new(std::iter::empty()),
175 }
176}
177
178pub(crate) fn once<'s>(item: Item) -> Iter<'s> {
179 Box::new(std::iter::once(Ok(item)))
180}
181
182pub(crate) fn failed<'s>(error: Error) -> Iter<'s> {
183 Box::new(std::iter::once(Err(error)))
184}
185
186pub(crate) fn from_vec<'s>(items: Vec<Item>) -> Iter<'s> {
187 Box::new(items.into_iter().map(Ok))
188}
189
190pub(crate) fn sort_nodes(mut nodes: Vec<Node>) -> Vec<Item> {
191 nodes.sort_by(Node::cmp_document_order);
192 nodes.dedup();
193 nodes.into_iter().map(Item::Node).collect()
194}
195
196fn ebv_of(mut items: Iter<'_>) -> Result<bool> {
198 match items.next() {
199 None => Ok(false),
200 Some(first) => match first? {
201 Item::Node(_) => Ok(true),
202 Item::Atomic(value) => {
203 if let Some(second) = items.next() {
204 second?;
205 return err(
206 ErrorCode::Forg0006,
207 format!(
208 "Effective boolean value is not defined for a sequence of two or more items starting with a {} value",
209 value.atomic_type()
210 ),
211 );
212 }
213 Ok(ops::effective_boolean_value(&value)?)
214 }
215 },
216 }
217}
218
219impl CompiledExpr {
220 pub fn evaluate(&self, dc: &DynamicContext<'_>, context: &Context) -> Result<Vec<Item>> {
226 let run = Run {
227 dc,
228 current: context.current.clone(),
229 };
230 let ctx = initial(context);
231 if let Some(nodes) = run.nodes_in_place(&self.expr, &ctx)? {
232 return Ok(nodes);
233 }
234 if walkable(&self.expr, Order::Kept) {
235 let mut nodes = Vec::new();
236 run.walk(&self.expr, &ctx, Order::Kept, &mut |node| {
237 nodes.push(Item::Node(node));
238 Ok(false)
239 })?;
240 return Ok(nodes);
241 }
242 run.seq(&self.expr, &ctx)?.collect()
243 }
244
245 pub fn effective_boolean_value(
252 &self,
253 dc: &DynamicContext<'_>,
254 context: &Context,
255 ) -> Result<bool> {
256 let run = Run {
257 dc,
258 current: context.current.clone(),
259 };
260 run.ebv(&self.expr, &initial(context))
261 }
262}
263
264fn initial(context: &Context) -> Ctx {
265 match &context.focus {
266 Some(focus) => Ctx {
267 item: Some(focus.item.clone()),
268 position: focus.position,
269 size: Some(focus.size),
270 env: None,
271 },
272 None => Ctx {
273 item: None,
274 position: 0,
275 size: None,
276 env: None,
277 },
278 }
279}
280
281fn boolean<'s>(value: bool) -> Iter<'s> {
282 once(Item::Atomic(AtomicValue::Boolean(value)))
283}
284
285impl<'a> Run<'a> {
286 fn host_call(&self, id: FunctionId, args: &[HostArg], ctx: &Ctx) -> Result<Vec<Item>> {
289 let arguments = args
290 .iter()
291 .map(|a| {
292 Ok(if a.lazy {
293 Argument::lazy(Arc::clone(&a.expr), ctx.clone(), self.current.clone())
294 } else {
295 Argument::value(self.seq(&a.expr, ctx)?.collect::<Result<Vec<_>>>()?)
296 })
297 })
298 .collect::<Result<Vec<_>>>()?;
299 self.dc.host.call_function(id, arguments, self.dc)
300 }
301
302 pub(crate) fn seq<'s>(&'s self, expr: &'s Expr, ctx: &Ctx) -> Result<Iter<'s>>
307 where
308 'a: 's,
309 {
310 self.dc.check_stack()?;
311 match expr {
312 Expr::Literal(_)
313 | Expr::ContextItem
314 | Expr::Root
315 | Expr::Local(_)
316 | Expr::External(_) => self.leaf(expr, ctx),
317 Expr::Sequence(items) => Ok(self.sequence(items, ctx)),
318 Expr::Filter { base, predicates } => self.filtered(base, predicates, ctx),
319 Expr::Step(step) => self.step(step, ctx),
320 Expr::Path {
321 lhs,
322 rhs,
323 mode,
324 rhs_uses_last,
325 } => self.path(lhs, rhs, *mode, *rhs_uses_last, ctx),
326 Expr::Union {
327 lhs,
328 rhs,
329 lhs_ordered,
330 rhs_ordered,
331 } => self.union(lhs, *lhs_ordered, rhs, *rhs_ordered, ctx),
332 Expr::Range(lhs, rhs) => self.range(lhs, rhs, ctx),
333 Expr::If {
334 condition,
335 then,
336 otherwise,
337 } => self.conditional(condition, then, otherwise, ctx),
338 Expr::For { sequence, body } => self.for_each(sequence, body, ctx),
339 Expr::Call {
340 function,
341 args,
342 data,
343 } => self.call(*function, args, data, ctx),
344 Expr::HostCall { id, args } => self.host_call(*id, args, ctx).map(from_vec),
345 Expr::Cast { .. } => self.cast(expr, ctx).map(optional),
346 Expr::Negate(..) | Expr::Arithmetic { .. } | Expr::ValueComparison { .. } => {
347 self.atomic_operation(expr, ctx).map(optional)
348 }
349 Expr::GeneralComparison { .. }
350 | Expr::And(..)
351 | Expr::Or(..)
352 | Expr::Quantified { .. }
353 | Expr::InstanceOf { .. }
354 | Expr::Castable { .. } => self.ebv(expr, ctx).map(boolean),
355 }
356 }
357
358 #[inline]
360 fn leaf<'s>(&'s self, expr: &'s Expr, ctx: &Ctx) -> Result<Iter<'s>>
361 where
362 'a: 's,
363 {
364 Ok(match expr {
365 Expr::Literal(value) => once(Item::Atomic(value.clone())),
366 Expr::ContextItem => once(context_item(ctx)?),
367 Expr::Root => {
368 let root = context_node(ctx, None)?.root();
369 if root.kind() != NodeKind::Document {
370 return err(
371 ErrorCode::Xpdy0050,
372 "The root of the tree containing the context item is not a document node",
373 );
374 }
375 once(Item::Node(root))
376 }
377 Expr::Local(depth) => once(local(ctx, *depth)?),
378 Expr::External(id) => {
379 let value = self.dc.host.variable(*id)?;
380 Box::new((0..value.len()).map(move |i| Ok(value[i].clone())))
381 }
382 _ => return err(ErrorCode::Internal, "not a leaf"),
383 })
384 }
385
386 #[inline]
388 fn sequence<'s>(&'s self, items: &'s [Expr], ctx: &Ctx) -> Iter<'s>
389 where
390 'a: 's,
391 {
392 let ctx = ctx.clone();
393 Box::new(
394 items
395 .iter()
396 .flat_map(move |e| self.seq(e, &ctx).unwrap_or_else(failed)),
397 )
398 }
399
400 #[inline]
402 fn filtered<'s>(
403 &'s self,
404 base: &'s Expr,
405 predicates: &'s [Predicate],
406 ctx: &Ctx,
407 ) -> Result<Iter<'s>>
408 where
409 'a: 's,
410 {
411 let input = self.seq(base, ctx)?;
412 self.filter(input, predicates, ctx)
413 }
414
415 #[inline]
417 fn union<'s>(
418 &'s self,
419 lhs: &'s Expr,
420 lhs_ordered: bool,
421 rhs: &'s Expr,
422 rhs_ordered: bool,
423 ctx: &Ctx,
424 ) -> Result<Iter<'s>>
425 where
426 'a: 's,
427 {
428 let left = self.union_operand(lhs, lhs_ordered, ctx, "first")?;
429 let right = self.union_operand(rhs, rhs_ordered, ctx, "second")?;
430 Ok(Box::new(Merge {
431 left,
432 right,
433 heads: None,
434 }))
435 }
436
437 #[inline]
439 fn conditional<'s>(
440 &'s self,
441 condition: &'s Expr,
442 then: &'s Expr,
443 otherwise: &'s Expr,
444 ctx: &Ctx,
445 ) -> Result<Iter<'s>>
446 where
447 'a: 's,
448 {
449 let branch = if self.ebv(condition, ctx)? {
450 then
451 } else {
452 otherwise
453 };
454 self.seq(branch, ctx)
455 }
456
457 #[inline]
459 fn for_each<'s>(&'s self, sequence: &'s Expr, body: &'s Expr, ctx: &Ctx) -> Result<Iter<'s>>
460 where
461 'a: 's,
462 {
463 let input = self.seq(sequence, ctx)?;
464 let ctx = ctx.clone();
465 Ok(Box::new(input.flat_map(move |item| match item {
466 Ok(item) => self.seq(body, &ctx.with_local(item)).unwrap_or_else(failed),
467 Err(e) => failed(e),
468 })))
469 }
470
471 fn cast(&self, expr: &Expr, ctx: &Ctx) -> Result<Option<AtomicValue>> {
475 let Expr::Cast {
476 operand,
477 target,
478 allows_empty,
479 upcast,
480 } = expr
481 else {
482 return err(ErrorCode::Internal, "not a cast");
483 };
484 match self.atomic_opt(operand, ctx, What::Text("value in 'cast as' expression"))? {
485 None if *allows_empty => Ok(None),
486 None => err(
487 ErrorCode::Xpty0004,
488 "An empty sequence is not allowed as the value in 'cast as' expression",
489 ),
490 Some(value) if *upcast => Ok(Some(value.upcast(*target)?)),
491 Some(value) => Ok(Some(value.cast(*target)?)),
492 }
493 }
494
495 fn atomic_operation(&self, expr: &Expr, ctx: &Ctx) -> Result<Option<AtomicValue>> {
498 match expr {
499 Expr::Negate(operand) => self.negated(operand, ctx),
500 Expr::Arithmetic {
501 op,
502 lhs,
503 rhs,
504 calculator,
505 } => self.arithmetic_value(*op, *calculator, lhs, rhs, ctx),
506 Expr::ValueComparison { op, lhs, rhs } => self.value_comparison(*op, lhs, rhs, ctx),
507 _ => err(ErrorCode::Internal, "not an atomic operation"),
508 }
509 }
510
511 #[inline]
514 fn operands(
515 &self,
516 lhs: &Expr,
517 rhs: &Expr,
518 what: &str,
519 ctx: &Ctx,
520 ) -> Result<Option<(AtomicValue, AtomicValue)>> {
521 let Some(a) = self.atomic_opt(lhs, ctx, What::Operand(true, what))? else {
522 return Ok(None);
523 };
524 let Some(b) = self.atomic_opt(rhs, ctx, What::Operand(false, what))? else {
525 return Ok(None);
526 };
527 Ok(Some((a, b)))
528 }
529
530 #[inline]
532 fn negated(&self, operand: &Expr, ctx: &Ctx) -> Result<Option<AtomicValue>> {
533 match self.atomic_opt(operand, ctx, What::Text("operand of '-'"))? {
534 Some(value) => Ok(Some(ops::negate(&value)?)),
535 None => Ok(None),
536 }
537 }
538
539 #[inline]
541 fn arithmetic_value(
542 &self,
543 op: ops::ArithmeticOp,
544 calculator: Calculator,
545 lhs: &Expr,
546 rhs: &Expr,
547 ctx: &Ctx,
548 ) -> Result<Option<AtomicValue>> {
549 match self.operands(lhs, rhs, arithmetic_name(op), ctx)? {
550 Some((a, b)) => Ok(Some(arithmetic(op, calculator, &a, &b)?)),
551 None => Ok(None),
552 }
553 }
554
555 #[inline]
557 fn value_comparison(
558 &self,
559 op: ops::ComparisonOp,
560 lhs: &Expr,
561 rhs: &Expr,
562 ctx: &Ctx,
563 ) -> Result<Option<AtomicValue>> {
564 match self.operands(lhs, rhs, "a value comparison", ctx)? {
565 Some((a, b)) => Ok(Some(AtomicValue::Boolean(ops::value_compare(
566 &a,
567 op,
568 &b,
569 self.dc.implicit_timezone,
570 )?))),
571 None => Ok(None),
572 }
573 }
574
575 fn and_or(&self, lhs: &Expr, rhs: &Expr, decisive: bool, ctx: &Ctx) -> Result<bool> {
582 match self.ebv(lhs, ctx) {
583 Ok(value) if value == decisive => Ok(decisive),
584 Ok(_) => self.ebv(rhs, ctx),
585 Err(e)
586 if matches!(
587 e.code(),
588 ErrorCode::Unsupported | ErrorCode::Internal | ErrorCode::Limit
589 ) =>
590 {
591 Err(e)
592 }
593 Err(e) => {
594 if self.ebv(rhs, ctx)? == decisive {
595 Ok(decisive)
596 } else {
597 Err(e)
598 }
599 }
600 }
601 }
602
603 pub(crate) fn ebv(&self, expr: &Expr, ctx: &Ctx) -> Result<bool> {
605 self.dc.check_stack()?;
606 match expr {
607 Expr::GeneralComparison {
608 op,
609 lhs,
610 rhs,
611 strategy,
612 } => self.general_comparison(*op, lhs, rhs, *strategy, ctx),
613 Expr::And(lhs, rhs) => self.and_or(lhs, rhs, false, ctx),
614 Expr::Union { lhs, rhs, .. } => {
616 Ok(self.has_node(lhs, ctx, "first")? || self.has_node(rhs, ctx, "second")?)
617 }
618 Expr::Or(lhs, rhs) => self.and_or(lhs, rhs, true, ctx),
619 Expr::Quantified {
620 every,
621 sequence,
622 satisfies,
623 } => self.quantified(*every, sequence, satisfies, ctx),
624 Expr::InstanceOf {
625 operand,
626 item,
627 occurrence,
628 } => self.instance_of(operand, item, *occurrence, ctx),
629 Expr::Castable {
630 operand,
631 target,
632 allows_empty,
633 } => self.castable(operand, *target, *allows_empty, ctx),
634 Expr::Call {
636 function: Builtin::Count,
637 args,
638 ..
639 } => self.non_empty(&args[0], ctx),
640 Expr::Call {
641 function: Builtin::Boolean,
642 args,
643 ..
644 } => self.ebv(&args[0], ctx),
645 Expr::Step(step) if simple(step) => Ok(Self::first_of_step(step, ctx)?.is_some()),
647 _ if walkable(expr, Order::Free) => {
648 self.walk(expr, ctx, Order::Free, &mut |_| Ok(true))
649 }
650 _ => ebv_of(self.seq(expr, ctx)?),
651 }
652 }
653
654 pub(crate) fn walk(
661 &self,
662 expr: &Expr,
663 ctx: &Ctx,
664 order: Order,
665 f: &mut dyn FnMut(Node) -> Result<bool>,
666 ) -> Result<bool> {
667 self.dc.check_stack()?;
668 match expr {
669 Expr::Step(step) => self.walk_step(step, ctx, f),
670 Expr::Path { lhs, rhs, .. } => {
671 let mut position = 0;
672 let mut each = |item: Item| -> Result<bool> {
673 position += 1;
674 match item {
675 Item::Node(node) => {
676 let focus = ctx.with_focus(Item::Node(node), position, None);
677 self.walk(rhs, &focus, order, f)
678 }
679 Item::Atomic(value) => err(
680 ErrorCode::Xpty0019,
681 format!(
682 "Required item type of first operand of '/' is node(); supplied value has item type {}",
683 value.atomic_type()
684 ),
685 ),
686 }
687 };
688 if walkable(lhs, order) {
689 return self.walk(lhs, ctx, order, &mut |node| each(Item::Node(node)));
690 }
691 for item in self.seq(lhs, ctx)? {
692 if each(item?)? {
693 return Ok(true);
694 }
695 }
696 Ok(false)
697 }
698 _ => err(ErrorCode::Internal, "not a walkable expression"),
699 }
700 }
701
702 fn walk_step(
704 &self,
705 step: &Step,
706 ctx: &Ctx,
707 f: &mut dyn FnMut(Node) -> Result<bool>,
708 ) -> Result<bool> {
709 let node = focus_node(ctx, Some(step.axis))?;
710 let doc = node.document();
711 let predicates = &step.predicates;
712 if predicates
713 .iter()
714 .any(|p| p.kind == PredicateKind::Position(None))
715 {
716 return Ok(false);
717 }
718 let mut seen = [0_usize; MAX_WALKED_PREDICATES];
720 for index in step_nodes(doc, node.index(), step) {
721 let candidate = Node::new(Rc::clone(doc), index);
722 let mut passes = true;
723 let mut last = false;
724 for (predicate, seen) in predicates.iter().zip(seen.iter_mut()) {
725 *seen += 1;
726 let holds = match predicate.kind {
727 PredicateKind::Position(Some(n)) => {
730 let nth = *seen == n;
731 last |= nth;
732 nth
733 }
734 _ => self.predicate_holds(
735 predicate,
736 &ctx.with_focus(Item::Node(candidate.clone()), *seen, None),
737 )?,
738 };
739 if !holds {
740 passes = false;
741 break;
742 }
743 }
744 if passes && f(candidate)? {
745 return Ok(true);
746 }
747 if last {
748 return Ok(false);
749 }
750 }
751 Ok(false)
752 }
753
754 fn nodes_in_place(&self, expr: &Expr, ctx: &Ctx) -> Result<Option<Vec<Item>>> {
759 let doc = match &ctx.item {
762 Some(Item::Node(node)) => Some(node.document()),
763 _ => None,
764 };
765 let mut items = Vec::new();
766 let read = select_indices(self.dc, expr, ctx.item.as_ref(), &mut |index| {
767 if let Some(doc) = doc {
768 items.push(Item::Node(Node::new(Rc::clone(doc), index)));
769 }
770 })?;
771 Ok(read.map(|_| items))
772 }
773
774 #[inline]
777 fn first_of_step(step: &Step, ctx: &Ctx) -> Result<Option<u32>> {
778 let node = focus_node(ctx, Some(step.axis))?;
779 Ok(step_nodes(node.document(), node.index(), step).next())
780 }
781
782 #[inline]
784 fn two_of_step(step: &Step, ctx: &Ctx) -> Result<(Option<Node>, bool)> {
785 let node = focus_node(ctx, Some(step.axis))?;
786 let doc = node.document();
787 let mut matching = step_nodes(doc, node.index(), step);
788 let Some(first) = matching.next() else {
789 return Ok((None, false));
790 };
791 let more = matching.next().is_some();
792 Ok((Some(Node::new(Rc::clone(doc), first)), more))
793 }
794
795 #[inline]
797 fn quantified(
798 &self,
799 every: bool,
800 sequence: &Expr,
801 satisfies: &Expr,
802 ctx: &Ctx,
803 ) -> Result<bool> {
804 for item in self.seq(sequence, ctx)? {
805 let holds = self.ebv(satisfies, &ctx.with_local(item?))?;
806 if holds != every {
807 return Ok(holds);
808 }
809 }
810 Ok(every)
811 }
812
813 #[inline]
815 fn castable(
816 &self,
817 operand: &Expr,
818 target: einvoice_xdm::AtomicType,
819 allows_empty: bool,
820 ctx: &Ctx,
821 ) -> Result<bool> {
822 let mut values = self.seq(operand, ctx)?;
823 let Some(first) = values.next() else {
824 return Ok(allows_empty);
825 };
826 let first = first?.atomize();
827 if let Some(second) = values.next() {
828 second?;
829 return Ok(false);
830 }
831 match first.cast(target) {
832 Ok(_) => Ok(true),
833 Err(e) if e.code() == einvoice_xdm::ErrorCode::Unsupported => Err(e.into()),
834 Err(_) => Ok(false),
835 }
836 }
837
838 pub(crate) fn non_empty(&self, expr: &Expr, ctx: &Ctx) -> Result<bool> {
841 match expr {
842 Expr::Union { lhs, rhs, .. } => {
843 return Ok(self.has_node(lhs, ctx, "first")? || self.has_node(rhs, ctx, "second")?);
844 }
845 Expr::Step(step) if simple(step) => {
846 self.dc.check_stack()?;
847 return Ok(Self::first_of_step(step, ctx)?.is_some());
848 }
849 _ if walkable(expr, Order::Free) => {
850 return self.walk(expr, ctx, Order::Free, &mut |_| Ok(true));
851 }
852 _ => {}
853 }
854 Ok(self.seq(expr, ctx)?.next().transpose()?.is_some())
855 }
856
857 fn has_node(&self, expr: &Expr, ctx: &Ctx, side: &str) -> Result<bool> {
859 match self.seq(expr, ctx)?.next().transpose()? {
860 None => Ok(false),
861 Some(Item::Node(_)) => Ok(true),
862 Some(Item::Atomic(value)) => err(
863 ErrorCode::Xpty0004,
864 format!(
865 "Required item type of {side} operand of '|' is node(); supplied value has item type {}",
866 value.atomic_type()
867 ),
868 ),
869 }
870 }
871
872 fn instance_of(
873 &self,
874 operand: &Expr,
875 test: &ItemTest,
876 occurrence: einvoice_xpath::Occurrence,
877 ctx: &Ctx,
878 ) -> Result<bool> {
879 use einvoice_xpath::Occurrence;
880 let mut count = 0_usize;
881 for item in self.seq(operand, ctx)? {
882 let item = item?;
883 count += 1;
884 let matches = match (test, &item) {
885 (ItemTest::Atomic(t), Item::Atomic(v)) => v.is_instance_of(*t),
886 (ItemTest::Node(t), Item::Node(n)) => t.matches(n.document(), n.index()),
887 _ => false,
888 };
889 if !matches {
890 return Ok(false);
891 }
892 if count > 1 && matches!(occurrence, Occurrence::One | Occurrence::ZeroOrOne) {
893 return Ok(false);
894 }
895 }
896 Ok(match occurrence {
897 Occurrence::One | Occurrence::OneOrMore => count >= 1,
898 Occurrence::ZeroOrOne | Occurrence::ZeroOrMore => true,
899 })
900 }
901
902 pub(crate) fn atomized<'s>(
904 &'s self,
905 expr: &'s Expr,
906 ctx: &Ctx,
907 ) -> Result<impl Iterator<Item = Result<AtomicValue>> + 's>
908 where
909 'a: 's,
910 {
911 Ok(self.seq(expr, ctx)?.map(|item| item.map(|i| i.atomize())))
912 }
913
914 pub(crate) fn atomic_opt(
916 &self,
917 expr: &Expr,
918 ctx: &Ctx,
919 what: What<'_>,
920 ) -> Result<Option<AtomicValue>> {
921 Ok(self.item_opt(expr, ctx, what)?.map(|i| i.atomize()))
922 }
923
924 pub(crate) fn item_opt(&self, expr: &Expr, ctx: &Ctx, what: What<'_>) -> Result<Option<Item>> {
926 match expr {
928 Expr::Literal(value) => {
929 self.dc.check_stack()?;
930 return Ok(Some(Item::Atomic(value.clone())));
931 }
932 Expr::ContextItem => {
933 self.dc.check_stack()?;
934 return context_item(ctx).map(Some);
935 }
936 Expr::Local(depth) => {
937 self.dc.check_stack()?;
938 return local(ctx, *depth).map(Some);
939 }
940 Expr::Step(step) if simple(step) => {
941 self.dc.check_stack()?;
942 let (first, more) = Self::two_of_step(step, ctx)?;
943 if more {
944 return err(
945 ErrorCode::Xpty0004,
946 format!("A sequence of more than one item is not allowed as the {what}"),
947 );
948 }
949 return Ok(first.map(Item::Node));
950 }
951 _ if walkable(expr, Order::Kept) => {
952 let mut first = None;
953 let more = self.walk(expr, ctx, Order::Kept, &mut |node| {
954 if first.is_some() {
955 return Ok(true);
956 }
957 first = Some(node);
958 Ok(false)
959 })?;
960 if more {
961 return err(
962 ErrorCode::Xpty0004,
963 format!("A sequence of more than one item is not allowed as the {what}"),
964 );
965 }
966 return Ok(first.map(Item::Node));
967 }
968 _ => {}
969 }
970 let mut items = self.seq(expr, ctx)?;
971 let Some(first) = items.next() else {
972 return Ok(None);
973 };
974 let first = first?;
975 if let Some(second) = items.next() {
976 second?;
977 return err(
978 ErrorCode::Xpty0004,
979 format!("A sequence of more than one item is not allowed as the {what}"),
980 );
981 }
982 Ok(Some(first))
983 }
984
985 fn general_comparison(
986 &self,
987 op: ops::ComparisonOp,
988 lhs: &Expr,
989 rhs: &Expr,
990 strategy: CompareStrategy,
991 ctx: &Ctx,
992 ) -> Result<bool> {
993 match strategy {
994 CompareStrategy::OneToOne => self.one_to_one(op, lhs, rhs, ctx),
995 CompareStrategy::ManyToOne => self.many_to_one(op, lhs, rhs, ctx),
996 CompareStrategy::OneToMany => self.one_to_many(op, lhs, rhs, ctx),
997 CompareStrategy::ManyToMany => {
998 let tz = self.dc.implicit_timezone;
999 let compare = |a: &AtomicValue, b: &AtomicValue| -> Result<bool> {
1000 Ok(ops::general_compare(a, op, b, tz)?)
1001 };
1002 let left = self.atomized(lhs, ctx)?;
1003 let right = self.atomized(rhs, ctx)?;
1004 many_to_many(left, right, &compare)
1005 }
1006 }
1007 }
1008
1009 #[inline]
1011 fn one_to_one(&self, op: ops::ComparisonOp, lhs: &Expr, rhs: &Expr, ctx: &Ctx) -> Result<bool> {
1012 let Some(a) = self.item_opt(lhs, ctx, What::Text(GENERAL_OPERAND))? else {
1013 return Ok(false);
1014 };
1015 let Some(b) = self.item_opt(rhs, ctx, What::Text(GENERAL_OPERAND))? else {
1016 return Ok(false);
1017 };
1018 compare_items(&a, op, &b, self.dc.implicit_timezone)
1019 }
1020
1021 #[inline]
1023 fn many_to_one(
1024 &self,
1025 op: ops::ComparisonOp,
1026 lhs: &Expr,
1027 rhs: &Expr,
1028 ctx: &Ctx,
1029 ) -> Result<bool> {
1030 let Some(b) = self.atomic_opt(rhs, ctx, What::Text(GENERAL_OPERAND))? else {
1031 return Ok(false);
1032 };
1033 if walkable(lhs, Order::Free) {
1034 let tz = self.dc.implicit_timezone;
1035 return self.walk(lhs, ctx, Order::Free, &mut |node| {
1036 compare_node(&node, op, &b, tz, false)
1037 });
1038 }
1039 for a in self.atomized(lhs, ctx)? {
1040 if ops::general_compare(&a?, op, &b, self.dc.implicit_timezone)? {
1041 return Ok(true);
1042 }
1043 }
1044 Ok(false)
1045 }
1046
1047 #[inline]
1049 fn one_to_many(
1050 &self,
1051 op: ops::ComparisonOp,
1052 lhs: &Expr,
1053 rhs: &Expr,
1054 ctx: &Ctx,
1055 ) -> Result<bool> {
1056 let Some(a) = self.atomic_opt(lhs, ctx, What::Text(GENERAL_OPERAND))? else {
1057 return Ok(false);
1058 };
1059 if walkable(rhs, Order::Free) {
1060 let tz = self.dc.implicit_timezone;
1061 return self.walk(rhs, ctx, Order::Free, &mut |node| {
1062 compare_node(&node, op, &a, tz, true)
1063 });
1064 }
1065 for b in self.atomized(rhs, ctx)? {
1066 if ops::general_compare(&a, op, &b?, self.dc.implicit_timezone)? {
1067 return Ok(true);
1068 }
1069 }
1070 Ok(false)
1071 }
1072
1073 fn filter<'s>(
1074 &'s self,
1075 input: Iter<'s>,
1076 predicates: &'s [Predicate],
1077 ctx: &Ctx,
1078 ) -> Result<Iter<'s>>
1079 where
1080 'a: 's,
1081 {
1082 let mut current = input;
1083 for predicate in predicates {
1084 current = self.apply_predicate(current, predicate, ctx)?;
1085 }
1086 Ok(current)
1087 }
1088
1089 fn apply_predicate<'s>(
1090 &'s self,
1091 input: Iter<'s>,
1092 predicate: &'s Predicate,
1093 ctx: &Ctx,
1094 ) -> Result<Iter<'s>>
1095 where
1096 'a: 's,
1097 {
1098 if let PredicateKind::Position(position) = predicate.kind {
1099 let Some(n) = position else {
1100 return Ok(Box::new(std::iter::empty()));
1101 };
1102 let mut input = input;
1103 let mut done = false;
1104 return Ok(Box::new(std::iter::from_fn(move || {
1105 if done {
1106 return None;
1107 }
1108 done = true;
1109 for _ in 1..n {
1110 match input.next()? {
1111 Ok(_) => {}
1112 Err(e) => return Some(Err(e)),
1113 }
1114 }
1115 input.next()
1116 })));
1117 }
1118 let (input, size): (Iter<'s>, Option<usize>) = if predicate.uses_last {
1119 let items = input.collect::<Result<Vec<_>>>()?;
1120 let size = items.len();
1121 (from_vec(items), Some(size))
1122 } else {
1123 (input, None)
1124 };
1125 let ctx = ctx.clone();
1126 let mut position = 0;
1127 Ok(Box::new(input.filter_map(move |item| {
1128 let item = match item {
1129 Ok(item) => item,
1130 Err(e) => return Some(Err(e)),
1131 };
1132 position += 1;
1133 let focus = ctx.with_focus(item.clone(), position, size);
1134 match self.predicate_holds(predicate, &focus) {
1135 Ok(true) => Some(Ok(item)),
1136 Ok(false) => None,
1137 Err(e) => Some(Err(e)),
1138 }
1139 })))
1140 }
1141
1142 fn predicate_holds(&self, predicate: &Predicate, ctx: &Ctx) -> Result<bool> {
1143 if predicate.kind == PredicateKind::Boolean {
1144 return self.ebv(&predicate.expr, ctx);
1145 }
1146 let mut values = self.seq(&predicate.expr, ctx)?;
1147 let Some(first) = values.next() else {
1148 return Ok(false);
1149 };
1150 match first? {
1151 Item::Node(_) => Ok(true),
1152 Item::Atomic(value) => {
1153 if let Some(second) = values.next() {
1154 second?;
1155 return err(
1156 ErrorCode::Forg0006,
1157 format!(
1158 "Effective boolean value is not defined for a sequence of two or more items starting with a {} value",
1159 value.atomic_type()
1160 ),
1161 );
1162 }
1163 if value.is_numeric() {
1164 let position = AtomicValue::Integer(Integer::from(
1165 i64::try_from(ctx.position).unwrap_or(i64::MAX),
1166 ));
1167 return Ok(ops::value_compare(
1168 &value,
1169 ops::ComparisonOp::Equal,
1170 &position,
1171 self.dc.implicit_timezone,
1172 )?);
1173 }
1174 Ok(ops::effective_boolean_value(&value)?)
1175 }
1176 }
1177 }
1178
1179 fn step<'s>(&'s self, step: &'s Step, ctx: &Ctx) -> Result<Iter<'s>>
1180 where
1181 'a: 's,
1182 {
1183 let node = context_node(ctx, Some(step.axis))?;
1184 let doc = Rc::clone(node.document());
1185 let nodes: Iter<'s> = if let Some(listed) = indexed(&doc, node.index(), step) {
1186 let listed = listed.to_vec();
1187 Box::new(
1188 listed
1189 .into_iter()
1190 .map(move |index| Ok(Item::Node(Node::new(Rc::clone(&doc), index)))),
1191 )
1192 } else {
1193 let mut cursor = doc.cursor(node.index(), step.axis);
1194 let test = &step.test;
1195 Box::new(std::iter::from_fn(move || {
1196 loop {
1197 let index = cursor.next(&doc)?;
1198 if test.matches(&doc, index) {
1199 return Some(Ok(Item::Node(Node::new(Rc::clone(&doc), index))));
1200 }
1201 }
1202 }))
1203 };
1204 let filtered = self.filter(nodes, &step.predicates, ctx)?;
1205 if step.axis.is_reverse() && step.axis != NodeAxis::Parent {
1206 let mut items = filtered.collect::<Result<Vec<_>>>()?;
1208 items.reverse();
1209 return Ok(from_vec(items));
1210 }
1211 Ok(filtered)
1212 }
1213
1214 fn path<'s>(
1215 &'s self,
1216 lhs: &'s Expr,
1217 rhs: &'s Expr,
1218 mode: PathMode,
1219 rhs_uses_last: bool,
1220 ctx: &Ctx,
1221 ) -> Result<Iter<'s>>
1222 where
1223 'a: 's,
1224 {
1225 let left = self.seq(lhs, ctx)?;
1226 let (left, size): (Iter<'s>, Option<usize>) = if rhs_uses_last {
1227 let items = left.collect::<Result<Vec<_>>>()?;
1228 let size = items.len();
1229 (from_vec(items), Some(size))
1230 } else {
1231 (left, None)
1232 };
1233 let ctx = ctx.clone();
1234 let mapped = left.enumerate().flat_map(move |(i, item)| match item {
1235 Err(e) => failed(e),
1236 Ok(Item::Atomic(value)) => failed(Error::new(
1237 ErrorCode::Xpty0019,
1238 format!(
1239 "Required item type of first operand of '/' is node(); supplied value has item type {}",
1240 value.atomic_type()
1241 ),
1242 )),
1243 Ok(node) => self
1244 .seq(rhs, &ctx.with_focus(node, i + 1, size))
1245 .unwrap_or_else(failed),
1246 });
1247 match mode {
1248 PathMode::Ordered | PathMode::Atomic => Ok(Box::new(mapped)),
1249 PathMode::Sort | PathMode::Dynamic => {
1250 let mut nodes = Vec::new();
1251 let mut atomics = Vec::new();
1252 for item in mapped {
1253 match item? {
1254 Item::Node(node) => nodes.push(node),
1255 Item::Atomic(value) => atomics.push(Item::Atomic(value)),
1256 }
1257 }
1258 if atomics.is_empty() {
1259 Ok(from_vec(sort_nodes(nodes)))
1260 } else if nodes.is_empty() {
1261 Ok(from_vec(atomics))
1262 } else {
1263 err(
1264 ErrorCode::Xpty0018,
1265 "Cannot mix nodes and atomic values in the result of a path expression",
1266 )
1267 }
1268 }
1269 }
1270 }
1271
1272 fn union_operand<'s>(
1275 &'s self,
1276 expr: &'s Expr,
1277 ordered: bool,
1278 ctx: &Ctx,
1279 side: &'static str,
1280 ) -> Result<Box<dyn Iterator<Item = Result<Node>> + 's>>
1281 where
1282 'a: 's,
1283 {
1284 let nodes = self.seq(expr, ctx)?.map(move |item| match item? {
1285 Item::Node(node) => Ok(node),
1286 Item::Atomic(value) => err(
1287 ErrorCode::Xpty0004,
1288 format!(
1289 "Required item type of {side} operand of '|' is node(); supplied value has item type {}",
1290 value.atomic_type()
1291 ),
1292 ),
1293 });
1294 if ordered {
1295 return Ok(Box::new(nodes));
1296 }
1297 let sorted = sort_nodes(nodes.collect::<Result<Vec<_>>>()?);
1298 Ok(Box::new(sorted.into_iter().filter_map(|item| match item {
1299 Item::Node(node) => Some(Ok(node)),
1300 Item::Atomic(_) => None,
1301 })))
1302 }
1303
1304 fn range<'s>(&'s self, lhs: &'s Expr, rhs: &'s Expr, ctx: &Ctx) -> Result<Iter<'s>>
1305 where
1306 'a: 's,
1307 {
1308 let bound = |expr: &Expr, what: &str| -> Result<Option<i64>> {
1309 let Some(value) = self.atomic_opt(expr, ctx, What::Text(what))? else {
1310 return Ok(None);
1311 };
1312 let value = match value {
1313 AtomicValue::UntypedAtomic(_) => value.cast(einvoice_xdm::AtomicType::Integer)?,
1314 AtomicValue::Integer(_) => value,
1315 other => {
1316 return err(
1317 ErrorCode::Xpty0004,
1318 format!(
1319 "Required item type of the {what} is xs:integer; supplied value has item type {}",
1320 other.atomic_type()
1321 ),
1322 );
1323 }
1324 };
1325 match value {
1326 AtomicValue::Integer(i) => i.to_i64().map(Some).ok_or_else(|| {
1327 Error::new(ErrorCode::Unsupported, "range bound beyond 64 bits")
1328 }),
1329 _ => err(ErrorCode::Internal, "range bound"),
1330 }
1331 };
1332 let Some(from) = bound(lhs, "first operand of 'to'")? else {
1333 return Ok(Box::new(std::iter::empty()));
1334 };
1335 let Some(to) = bound(rhs, "second operand of 'to'")? else {
1336 return Ok(Box::new(std::iter::empty()));
1337 };
1338 Ok(Box::new((from..=to).map(|i| {
1339 Ok(Item::Atomic(AtomicValue::Integer(Integer::from(i))))
1340 })))
1341 }
1342}
1343
1344type NodeIter<'s> = Box<dyn Iterator<Item = Result<Node>> + 's>;
1345
1346struct Merge<'s> {
1349 left: NodeIter<'s>,
1350 right: NodeIter<'s>,
1351 heads: Option<(Option<Node>, Option<Node>)>,
1353}
1354
1355impl Merge<'_> {
1356 fn pull(
1358 &mut self,
1359 heads: (Option<Node>, Option<Node>),
1360 left: bool,
1361 right: bool,
1362 ) -> Result<(Option<Node>, Option<Node>)> {
1363 let (mut l, mut r) = heads;
1364 if left {
1365 l = self.left.next().transpose()?;
1366 }
1367 if right {
1368 r = self.right.next().transpose()?;
1369 }
1370 Ok((l, r))
1371 }
1372
1373 fn step(&mut self) -> Result<Option<Node>> {
1374 let heads = if let Some(heads) = self.heads.take() {
1375 heads
1376 } else {
1377 self.pull((None, None), true, true)?
1378 };
1379 let (output, left, right) = match &heads {
1380 (None, None) => {
1381 self.heads = Some(heads);
1382 return Ok(None);
1383 }
1384 (Some(l), None) => (l.clone(), true, false),
1385 (None, Some(r)) => (r.clone(), false, true),
1386 (Some(l), Some(r)) => match l.cmp_document_order(r) {
1387 std::cmp::Ordering::Less => (l.clone(), true, false),
1388 std::cmp::Ordering::Greater => (r.clone(), false, true),
1389 std::cmp::Ordering::Equal => (l.clone(), true, true),
1390 },
1391 };
1392 self.heads = Some(self.pull(heads, left, right)?);
1395 Ok(Some(output))
1396 }
1397}
1398
1399impl Iterator for Merge<'_> {
1400 type Item = Result<Item>;
1401
1402 fn next(&mut self) -> Option<Result<Item>> {
1403 self.step().map(|n| n.map(Item::Node)).transpose()
1404 }
1405}
1406
1407fn context_item(ctx: &Ctx) -> Result<Item> {
1408 ctx.item
1409 .clone()
1410 .ok_or_else(|| Error::new(ErrorCode::Xpdy0002, "The context item is absent"))
1411}
1412
1413fn step_nodes<'d>(doc: &'d Document, from: u32, step: &'d Step) -> StepNodes<'d> {
1417 if let Some(listed) = indexed(doc, from, step) {
1418 return StepNodes::Listed(listed.iter());
1419 }
1420 StepNodes::Walked {
1421 cursor: doc.cursor(from, step.axis),
1422 doc,
1423 test: &step.test,
1424 }
1425}
1426
1427fn indexed<'d>(doc: &'d Document, from: u32, step: &Step) -> Option<&'d [u32]> {
1430 let NodeTest::Named {
1431 kind: NodeKind::Element,
1432 name: NameMatch::Exact { namespace, local },
1433 } = &step.test
1434 else {
1435 return None;
1436 };
1437 let (first_child, end) = doc.descendant_range(from);
1438 let start = match step.axis {
1439 NodeAxis::Descendant => first_child,
1440 NodeAxis::DescendantOrSelf => from,
1441 _ => return None,
1442 };
1443 doc.elements_named(namespace.as_deref(), local, start, end)
1444}
1445
1446enum StepNodes<'d> {
1448 Listed(std::slice::Iter<'d, u32>),
1450 Walked {
1452 cursor: Cursor,
1453 doc: &'d Document,
1454 test: &'d NodeTest,
1455 },
1456}
1457
1458impl Iterator for StepNodes<'_> {
1459 type Item = u32;
1460
1461 #[inline]
1462 fn next(&mut self) -> Option<u32> {
1463 match self {
1464 Self::Listed(listed) => listed.next().copied(),
1465 Self::Walked { cursor, doc, test } => loop {
1466 let index = cursor.next(doc)?;
1467 if test.matches(doc, index) {
1468 return Some(index);
1469 }
1470 },
1471 }
1472 }
1473}
1474
1475#[derive(Debug, Clone)]
1478pub struct NodeSelection {
1479 doc: Rc<Document>,
1480 indices: Vec<u32>,
1481}
1482
1483impl NodeSelection {
1484 #[must_use]
1486 pub fn len(&self) -> usize {
1487 self.indices.len()
1488 }
1489
1490 #[must_use]
1492 pub fn is_empty(&self) -> bool {
1493 self.indices.is_empty()
1494 }
1495
1496 #[must_use]
1498 pub fn get(&self, position: usize) -> Option<Node> {
1499 let index = *self.indices.get(position)?;
1500 Some(Node::new(Rc::clone(&self.doc), index))
1501 }
1502
1503 pub fn iter(&self) -> impl Iterator<Item = Node> + '_ {
1505 self.indices
1506 .iter()
1507 .map(|&index| Node::new(Rc::clone(&self.doc), index))
1508 }
1509
1510 #[must_use]
1513 pub fn into_storage(self) -> SelectionStorage {
1514 let mut indices = self.indices;
1515 indices.clear();
1516 SelectionStorage(indices)
1517 }
1518}
1519
1520#[derive(Debug, Clone, Default)]
1522pub struct SelectionStorage(Vec<u32>);
1523
1524impl CompiledExpr {
1525 pub fn select_in_place(
1539 &self,
1540 dc: &DynamicContext<'_>,
1541 context: &Context,
1542 storage: SelectionStorage,
1543 ) -> Result<Option<NodeSelection>> {
1544 select_in_place(
1545 dc,
1546 &self.expr,
1547 context.focus.as_ref().map(|f| &f.item),
1548 storage,
1549 )
1550 }
1551}
1552
1553fn select_in_place(
1555 dc: &DynamicContext<'_>,
1556 expr: &Expr,
1557 item: Option<&Item>,
1558 storage: SelectionStorage,
1559) -> Result<Option<NodeSelection>> {
1560 let mut indices = storage.0;
1561 indices.clear();
1562 let doc = select_indices(dc, expr, item, &mut |index| indices.push(index))?;
1563 Ok(doc.map(|doc| NodeSelection { doc, indices }))
1564}
1565
1566fn select_indices(
1571 dc: &DynamicContext<'_>,
1572 expr: &Expr,
1573 item: Option<&Item>,
1574 out: &mut dyn FnMut(u32),
1575) -> Result<Option<Rc<Document>>> {
1576 if let Expr::ContextItem = expr {
1577 return Ok(match item {
1580 Some(Item::Node(node)) => {
1581 dc.check_stack()?;
1582 out(node.index());
1583 Some(Rc::clone(node.document()))
1584 }
1585 _ => None,
1586 });
1587 }
1588 let mut steps: [Option<&Step>; MAX_SELECTED_STEPS] = [None; MAX_SELECTED_STEPS];
1589 let mut count = 0;
1590 if !union_of_steps(expr, &mut steps, &mut count) {
1591 return Ok(None);
1592 }
1593 let [Some(first), second, ..] = steps else {
1594 return Ok(None);
1595 };
1596 dc.check_stack()?;
1597 let node = focus_node_of(item, Some(first.axis))?;
1598 let doc = node.document();
1599 let from = node.index();
1600 match (second, count) {
1601 (None, _) => step_nodes(doc, from, first).for_each(out),
1602 (Some(second), 2) => merge_two(
1603 step_nodes(doc, from, first),
1604 step_nodes(doc, from, second),
1605 out,
1606 ),
1607 _ => {
1608 let mut walks = steps.map(|step| step.map(|step| step_nodes(doc, from, step)));
1610 let mut heads = [None; MAX_SELECTED_STEPS];
1611 for (head, walk) in heads.iter_mut().zip(walks.iter_mut()) {
1612 *head = walk.as_mut().and_then(Iterator::next);
1613 }
1614 while let Some(next) = heads.iter().flatten().min().copied() {
1615 out(next);
1616 for (head, walk) in heads.iter_mut().zip(walks.iter_mut()) {
1617 if *head == Some(next) {
1618 *head = walk.as_mut().and_then(Iterator::next);
1619 }
1620 }
1621 }
1622 }
1623 }
1624 Ok(Some(Rc::clone(doc)))
1625}
1626
1627fn merge_two(
1629 mut left: impl Iterator<Item = u32>,
1630 mut right: impl Iterator<Item = u32>,
1631 out: &mut dyn FnMut(u32),
1632) {
1633 let (mut l, mut r) = (left.next(), right.next());
1634 loop {
1635 let next = match (l, r) {
1636 (None, None) => break,
1637 (Some(a), None) => {
1638 l = left.next();
1639 a
1640 }
1641 (None, Some(b)) => {
1642 r = right.next();
1643 b
1644 }
1645 (Some(a), Some(b)) => {
1646 if a <= b {
1647 l = left.next();
1648 }
1649 if b <= a {
1650 r = right.next();
1651 }
1652 a.min(b)
1653 }
1654 };
1655 out(next);
1656 }
1657}
1658
1659const MAX_SELECTED_STEPS: usize = 4;
1661
1662fn union_of_steps<'e>(
1665 expr: &'e Expr,
1666 steps: &mut [Option<&'e Step>; MAX_SELECTED_STEPS],
1667 count: &mut usize,
1668) -> bool {
1669 match expr {
1670 Expr::Step(step) if simple(step) => match steps.get_mut(*count) {
1671 Some(slot) => {
1672 *slot = Some(step);
1673 *count += 1;
1674 true
1675 }
1676 None => false,
1677 },
1678 Expr::Union { lhs, rhs, .. } => {
1679 union_of_steps(lhs, steps, count) && union_of_steps(rhs, steps, count)
1680 }
1681 _ => false,
1682 }
1683}
1684
1685const MAX_WALKED_PREDICATES: usize = 4;
1687
1688#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1691pub(crate) enum Order {
1692 Kept,
1694 Free,
1699}
1700
1701pub(crate) fn walkable(expr: &Expr, order: Order) -> bool {
1709 match expr {
1710 Expr::Step(step) => {
1711 (!step.axis.is_reverse() || step.axis == NodeAxis::Parent)
1712 && step.predicates.len() <= MAX_WALKED_PREDICATES
1713 && step.predicates.iter().all(|p| !p.uses_last)
1714 }
1715 Expr::Path {
1716 lhs,
1717 rhs,
1718 mode,
1719 rhs_uses_last: false,
1720 } => {
1721 let step = matches!(&**rhs, Expr::Step(_)) && walkable(rhs, order);
1722 match (mode, order) {
1723 (PathMode::Ordered, _) => step,
1724 (PathMode::Sort, Order::Free) => {
1725 step && (walkable(lhs, order)
1726 || !matches!(&**lhs, Expr::Step(_) | Expr::Path { .. }))
1727 }
1728 _ => false,
1729 }
1730 }
1731 _ => false,
1732 }
1733}
1734
1735fn simple(step: &Step) -> bool {
1738 step.predicates.is_empty() && (!step.axis.is_reverse() || step.axis == NodeAxis::Parent)
1739}
1740
1741fn context_node(ctx: &Ctx, axis: Option<NodeAxis>) -> Result<Node> {
1743 focus_node(ctx, axis).cloned()
1744}
1745
1746fn focus_node(ctx: &Ctx, axis: Option<NodeAxis>) -> Result<&Node> {
1748 focus_node_of(ctx.item.as_ref(), axis)
1749}
1750
1751fn focus_node_of(item: Option<&Item>, axis: Option<NodeAxis>) -> Result<&Node> {
1753 let what = || match axis {
1754 Some(axis) => format!("the axis step {}::", axis_name(axis)),
1755 None => "the root expression /".to_owned(),
1756 };
1757 match item {
1758 None => err(
1759 ErrorCode::Xpdy0002,
1760 format!("The context item for {} is absent", what()),
1761 ),
1762 Some(Item::Atomic(v)) => err(
1763 ErrorCode::Xpty0020,
1764 format!(
1765 "The context item for {} is not a node (it is a {})",
1766 what(),
1767 v.atomic_type()
1768 ),
1769 ),
1770 Some(Item::Node(node)) => Ok(node),
1771 }
1772}
1773
1774fn local(ctx: &Ctx, depth: usize) -> Result<Item> {
1775 let mut env = ctx.env.as_ref();
1776 for _ in 0..depth {
1777 env = env.and_then(|e| e.parent.as_ref());
1778 }
1779 env.map(|e| e.item.clone())
1780 .ok_or_else(|| Error::new(ErrorCode::Internal, "range variable out of scope"))
1781}
1782
1783fn untyped_text(item: &Item) -> Option<Cow<'_, str>> {
1787 match item {
1788 Item::Node(node) => match node.kind() {
1789 NodeKind::Comment | NodeKind::ProcessingInstruction => None,
1790 _ => Some(node.string_value()),
1791 },
1792 Item::Atomic(AtomicValue::UntypedAtomic(text)) => Some(Cow::Borrowed(text)),
1793 Item::Atomic(_) => None,
1794 }
1795}
1796
1797fn atomized_item(item: &Item) -> Cow<'_, AtomicValue> {
1799 match item {
1800 Item::Atomic(value) => Cow::Borrowed(value),
1801 Item::Node(node) => Cow::Owned(node.typed_value()),
1802 }
1803}
1804
1805fn compare_items(a: &Item, op: ops::ComparisonOp, b: &Item, tz: i16) -> Result<bool> {
1808 Ok(match (untyped_text(a), untyped_text(b)) {
1809 (Some(x), Some(y)) => ops::general_compare_untyped_pair(&x, op, &y),
1810 (Some(x), None) => ops::general_compare_untyped(&x, op, &atomized_item(b), tz, false)?,
1811 (None, Some(y)) => ops::general_compare_untyped(&y, op, &atomized_item(a), tz, true)?,
1812 (None, None) => ops::general_compare(&atomized_item(a), op, &atomized_item(b), tz)?,
1813 })
1814}
1815
1816fn compare_node(
1819 node: &Node,
1820 op: ops::ComparisonOp,
1821 other: &AtomicValue,
1822 tz: i16,
1823 node_is_right: bool,
1824) -> Result<bool> {
1825 Ok(match node.kind() {
1826 NodeKind::Comment | NodeKind::ProcessingInstruction => {
1827 let value = node.typed_value();
1828 if node_is_right {
1829 ops::general_compare(other, op, &value, tz)?
1830 } else {
1831 ops::general_compare(&value, op, other, tz)?
1832 }
1833 }
1834 _ => ops::general_compare_untyped(&node.string_value(), op, other, tz, node_is_right)?,
1835 })
1836}
1837
1838fn many_to_many(
1841 mut left: impl Iterator<Item = Result<AtomicValue>>,
1842 mut right: impl Iterator<Item = Result<AtomicValue>>,
1843 compare: &dyn Fn(&AtomicValue, &AtomicValue) -> Result<bool>,
1844) -> Result<bool> {
1845 let (mut left_done, mut right_done) = (false, false);
1846 let (mut left_seen, mut right_seen) = (Vec::new(), Vec::new());
1847 loop {
1848 if !left_done {
1849 match left.next() {
1850 None => {
1851 if right_done {
1852 return Ok(false);
1853 }
1854 left_done = true;
1855 }
1856 Some(a) => {
1857 let a = a?;
1858 for b in &right_seen {
1859 if compare(&a, b)? {
1860 return Ok(true);
1861 }
1862 }
1863 if !right_done {
1864 left_seen.push(a);
1865 }
1866 }
1867 }
1868 }
1869 if !right_done {
1870 match right.next() {
1871 None => {
1872 if left_done {
1873 return Ok(false);
1874 }
1875 right_done = true;
1876 }
1877 Some(b) => {
1878 let b = b?;
1879 for a in &left_seen {
1880 if compare(a, &b)? {
1881 return Ok(true);
1882 }
1883 }
1884 if !left_done {
1885 right_seen.push(b);
1886 }
1887 }
1888 }
1889 }
1890 }
1891}
1892
1893fn arithmetic(
1898 op: ops::ArithmeticOp,
1899 calculator: Calculator,
1900 a: &AtomicValue,
1901 b: &AtomicValue,
1902) -> Result<AtomicValue> {
1903 match (calculator, a, b) {
1904 (Calculator::DecimalDivide, AtomicValue::Integer(i), AtomicValue::Integer(j)) => {
1905 Ok(AtomicValue::Decimal(
1906 i.as_decimal_operand()
1907 .checked_div(&j.as_decimal_operand())?,
1908 ))
1909 }
1910 _ => Ok(ops::arithmetic(op, a, b)?),
1911 }
1912}
1913
1914const fn arithmetic_name(op: ops::ArithmeticOp) -> &'static str {
1916 match op {
1917 ops::ArithmeticOp::Add => "'+'",
1918 ops::ArithmeticOp::Subtract => "'-'",
1919 ops::ArithmeticOp::Multiply => "'*'",
1920 ops::ArithmeticOp::Divide => "'div'",
1921 ops::ArithmeticOp::IntegerDivide => "'idiv'",
1922 ops::ArithmeticOp::Modulo => "'mod'",
1923 }
1924}
1925
1926const fn axis_name(axis: NodeAxis) -> &'static str {
1927 match axis {
1928 NodeAxis::Child => "child",
1929 NodeAxis::Attribute => "attribute",
1930 NodeAxis::SelfAxis => "self",
1931 NodeAxis::Descendant => "descendant",
1932 NodeAxis::DescendantOrSelf => "descendant-or-self",
1933 NodeAxis::FollowingSibling => "following-sibling",
1934 NodeAxis::Parent => "parent",
1935 NodeAxis::Ancestor => "ancestor",
1936 NodeAxis::AncestorOrSelf => "ancestor-or-self",
1937 NodeAxis::PrecedingSibling => "preceding-sibling",
1938 NodeAxis::Preceding => "preceding",
1939 }
1940}