1use std::borrow::Cow;
7use std::cell::{Cell, RefCell};
8use std::collections::{HashMap, HashSet};
9use std::rc::Rc;
10
11use crate::index::{CDATA, COMMENT, ELEMENT, PI, Scopes, TEXT};
12use crate::parser::{Axis, Expr, NodeTest, Op, Step};
13use crate::{Doc, Extensions, Item, NodeId, Value, XML_DECL, XML_NS, XValue};
14
15pub const WORK_LIMIT: u64 = 1 << 27;
23
24struct Context<'a, 'v> {
25 item: Item,
26 position: usize,
27 size: usize,
28 doc: Doc<'a>,
29 root: NodeId,
30 vars: &'v [(String, XValue)],
31 namespaces: &'v [(String, String)],
32 kept: &'v RefCell<Kept>,
33 in_scope: &'v RefCell<InScope>,
36 ext: &'v dyn Extensions,
37 spent: &'v Cell<u64>,
39 limit: u64,
40 nested: bool,
42}
43
44type Kept = HashMap<(usize, (u32, u64)), Scalar>;
47
48#[derive(Default)]
52struct InScope {
53 lists: HashMap<u32, Rc<[u32]>>,
54 passes: Vec<u8>,
57 seen: Vec<u32>,
59 pass: u32,
60}
61
62fn gather(
66 scopes: &Scopes,
67 lists: &HashMap<u32, Rc<[u32]>>,
68 seen: &mut [u32],
69 pass: &mut u32,
70 block: u32,
71 between: &[u32],
72) -> (Rc<[u32]>, usize) {
73 *pass = pass.wrapping_add(1);
74 if *pass == 0 {
75 seen.fill(0);
76 *pass = 1;
77 }
78 let mut found = Vec::new();
82 let mut looked = 0;
83 let mut keep = |d: u32| {
84 let decl = &scopes.decls[d as usize];
85 if seen[decl.prefix as usize] != *pass {
86 seen[decl.prefix as usize] = *pass;
87 if !decl.undeclares {
88 found.push(d);
89 }
90 }
91 };
92 let mut top = u32::MAX;
93 for &b in std::iter::once(&block).chain(between) {
94 let at = &scopes.blocks[b as usize];
95 looked += at.len as usize + 1;
96 for d in (at.first..at.first + at.len).rev() {
97 keep(d);
98 }
99 top = at.parent;
100 }
101 if let Some(above) = lists.get(&top) {
102 looked += above.len();
103 for &d in above.iter().rev() {
104 keep(d);
105 }
106 }
107 found.reverse();
108 (found.into(), looked)
109}
110
111#[derive(Debug, Clone, Copy)]
112enum Scalar {
113 Num(f64),
114 Bool(bool),
115}
116
117type Result<T> = std::result::Result<T, String>;
118
119fn text<'a>(s: String) -> Value<'a> {
120 Value::Str(Cow::Owned(s))
121}
122
123pub(crate) fn run<'a>(
125 expr: &Expr,
126 doc: Doc<'a>,
127 scope: NodeId,
128 vars: &[(String, XValue)],
129 namespaces: &[(String, String)],
130 ext: &dyn Extensions,
131 limit: u64,
132) -> Result<Value<'a>> {
133 let mut root = scope;
136 while let Some(up) = doc.tree.parent(root) {
137 root = up;
138 }
139 if doc.index.order(root) == u32::MAX {
140 return Err(format!(
141 "the top of node {scope}'s tree, node {root}, isn't in the index"
142 ));
143 }
144 let kept = RefCell::default();
145 let in_scope = RefCell::default();
146 let spent = Cell::new(0);
147 let ctx = Context {
148 item: Item::Node(scope),
149 position: 1,
150 size: 1,
151 doc,
152 root,
153 vars,
154 namespaces,
155 kept: &kept,
156 in_scope: &in_scope,
157 ext,
158 spent: &spent,
159 limit,
160 nested: false,
161 };
162 eval(expr, &ctx)
163}
164
165impl<'a> Context<'a, '_> {
166 fn spend(&self, units: usize) -> Result<()> {
168 let spent = self.spent.get().saturating_add(units as u64);
169 self.spent.set(spent);
170 if spent > self.limit {
171 return Err(format!(
172 "the query needs more than {} steps on this document, so it was stopped",
173 self.limit
174 ));
175 }
176 Ok(())
177 }
178
179 fn charge_text(&self, bytes: usize) {
181 let units = (bytes / 16) as u64;
182 self.spent.set(self.spent.get().saturating_add(units));
183 }
184
185 fn order(&self, n: NodeId) -> u32 {
186 self.doc.index.order(n)
187 }
188
189 fn key(&self, item: &Item) -> (u32, u64) {
193 match *item {
194 Item::Node(n) => (self.order(n), 0),
195 Item::Ns { owner, decl } => (
196 self.order(owner),
197 if decl == XML_DECL { 1 } else { decl as u64 + 2 },
198 ),
199 Item::Attr { owner, index } => (self.order(owner), (1 << 33) + index as u64),
200 }
201 }
202
203 fn namespaces(&self, n: NodeId) -> Result<Rc<[u32]>> {
206 let (scopes, built) = self.doc.index.scopes(self.doc.tree);
207 if built {
208 self.spend(self.doc.index.len())?;
209 }
210 let block = scopes.block_at(self.order(n));
211 if block == u32::MAX {
212 return Ok(Rc::from([]));
213 }
214 let mut cache = self.in_scope.borrow_mut();
215 let InScope {
216 lists,
217 passes,
218 seen,
219 pass,
220 } = &mut *cache;
221 if let Some(list) = lists.get(&block) {
222 return Ok(list.clone());
223 }
224 if seen.len() < scopes.prefixes {
225 seen.resize(scopes.prefixes, 0);
226 }
227 if passes.len() < scopes.blocks.len() {
228 passes.resize(scopes.blocks.len(), 0);
229 }
230 let mut climbed = Vec::new();
236 let mut b = scopes.blocks[block as usize].parent;
237 while b != u32::MAX && !lists.contains_key(&b) {
238 passes[b as usize] = passes[b as usize].saturating_add(1);
239 climbed.push(b);
240 b = scopes.blocks[b as usize].parent;
241 }
242 let again = climbed
243 .iter()
244 .position(|&b| passes[b as usize] > 1)
245 .unwrap_or(climbed.len());
246 let mut looked = 0;
247 for &b in climbed[again..].iter().rev() {
248 let (list, cost) = gather(scopes, lists, seen, pass, b, &[]);
249 looked += cost;
250 lists.insert(b, list);
251 }
252 let (list, cost) = gather(scopes, lists, seen, pass, block, &climbed[..again]);
253 looked += cost;
254 lists.insert(block, list.clone());
255 drop(cache);
256 self.spend(looked)?;
257 Ok(list)
258 }
259
260 fn kind(&self, n: NodeId) -> u8 {
261 self.doc.index.kind_at(self.order(n))
262 }
263
264 fn data(&self, n: NodeId) -> &'a str {
266 self.doc.tree.data(n)
267 }
268
269 fn string_value(&self, item: &Item) -> Cow<'a, str> {
270 let n = match item {
271 Item::Attr { owner, index, .. } => {
272 return Cow::Borrowed(self.doc.attr_at(*owner, *index).1);
273 }
274 Item::Ns { decl, .. } => return Cow::Borrowed(self.doc.namespace_at(*decl).1),
275 Item::Node(n) => *n,
276 };
277 let index = self.doc.index;
278 let at = self.order(n);
279 match index.kind_at(at) {
280 TEXT | CDATA | COMMENT | PI => {
281 let data = self.data(n);
282 self.charge_text(data.len());
283 Cow::Borrowed(data)
284 }
285 _ => {
286 let end = index.end_of(at);
288 self.spent
289 .set(self.spent.get().saturating_add((end - at) as u64));
290 let mut out = Cow::Borrowed("");
292 for j in at + 1..end {
293 if matches!(index.kind_at(j), TEXT | CDATA) {
294 let piece = self.data(index.node_at(j));
295 self.charge_text(piece.len());
298 if out.is_empty() {
299 out = Cow::Borrowed(piece);
300 } else {
301 out.to_mut().push_str(piece);
302 }
303 }
304 }
305 out
306 }
307 }
308 }
309
310 fn pi_target(&self, n: NodeId) -> Option<&'a str> {
311 self.doc.tree.pi_target(n)
312 }
313
314 fn attribute(&self, item: &Item) -> Option<crate::Attr<'a>> {
316 match item {
317 Item::Attr { owner, index } => self.doc.tree.attribute(*owner, *index),
318 _ => None,
319 }
320 }
321
322 fn name(&self, item: &Item) -> &'a str {
324 match item {
325 Item::Node(n) => match self.pi_target(*n) {
326 Some(target) => target,
327 None => self.doc.tree.qualified_name(*n),
328 },
329 Item::Attr { .. } => self.attribute(item).map_or("", |a| a.qualified_name),
330 Item::Ns { decl, .. } => self.doc.namespace_at(*decl).0,
332 }
333 }
334
335 fn local_name(&self, item: &Item) -> &'a str {
337 match item {
338 Item::Node(n) => match self.pi_target(*n) {
339 Some(target) => target,
340 None => self.doc.tree.local_name(*n),
341 },
342 Item::Attr { .. } => self.attribute(item).map_or("", |a| a.local_name),
343 Item::Ns { decl, .. } => self.doc.namespace_at(*decl).0,
344 }
345 }
346
347 fn namespace_uri(&self, item: &Item) -> &'a str {
348 match item {
349 Item::Node(n) => self.doc.tree.namespace_uri(*n),
350 Item::Attr { .. } => self.attribute(item).map_or("", |a| a.namespace_uri),
351 Item::Ns { .. } => "",
352 }
353 }
354
355 fn tree_range(&self) -> (u32, u32) {
358 let top = self.order(self.root);
359 (top, self.doc.index.end_of(top))
360 }
361}
362
363const RED_ZONE: usize = 64 * 1024;
367const GROW: usize = 1024 * 1024;
368
369fn eval<'a>(expr: &Expr, ctx: &Context<'a, '_>) -> Result<Value<'a>> {
370 stacker::maybe_grow(RED_ZONE, GROW, || eval_here(expr, ctx))
371}
372
373fn eval_here<'a>(expr: &Expr, ctx: &Context<'a, '_>) -> Result<Value<'a>> {
374 Ok(match expr {
375 Expr::Literal(s) => text(s.clone()),
376 Expr::Number(n) => Value::Num(*n),
377 Expr::Variable(name) => match ctx.vars.iter().find(|(k, _)| k == name) {
378 Some((_, XValue::Str(s))) => text(s.clone()),
379 Some((_, XValue::Num(n))) => Value::Num(*n),
380 Some((_, XValue::Bool(b))) => Value::Bool(*b),
381 None => return Err(format!("no value given for ${name}")),
382 },
383 Expr::Negate(e) => Value::Num(-number(eval(e, ctx)?, ctx)),
384 Expr::Binary(op, l, r) => binary(*op, l, r, ctx)?,
385 Expr::Union(l, r) => {
386 let (Value::Nodes(mut a), Value::Nodes(b)) = (eval(l, ctx)?, eval(r, ctx)?) else {
387 return Err("both sides of | must be node-sets".into());
388 };
389 a.extend(b);
390 Value::Nodes(in_document_order(a, ctx))
391 }
392 Expr::Call(name, args) => call(name, args, ctx)?,
393 Expr::Memo(e, slot) => {
394 let key = (*slot, ctx.key(&ctx.item));
395 let known = ctx.kept.borrow().get(&key).copied();
397 let scalar = match known {
398 Some(s) => s,
399 None => {
400 let s = match eval(e, ctx)? {
401 Value::Num(n) => Scalar::Num(n),
402 other => Scalar::Bool(boolean(&other)),
403 };
404 ctx.kept.borrow_mut().insert(key, s);
405 s
406 }
407 };
408 match scalar {
409 Scalar::Num(n) => Value::Num(n),
410 Scalar::Bool(b) => Value::Bool(b),
411 }
412 }
413 Expr::Path { absolute, steps } => {
414 let start = if *absolute {
415 Item::Node(ctx.root)
416 } else {
417 ctx.item
418 };
419 Value::Nodes(walk(vec![start], steps, ctx)?)
420 }
421 Expr::Filter {
422 primary,
423 predicates,
424 steps,
425 } => {
426 let Value::Nodes(mut items) = eval(primary, ctx)? else {
427 return Err("predicates and paths can only follow a node-set".into());
428 };
429 for p in predicates {
430 items = filter(items, p, ctx)?;
431 }
432 Value::Nodes(walk(items, steps, ctx)?)
433 }
434 })
435}
436
437fn in_document_order<'a>(items: Vec<Item>, ctx: &Context<'a, '_>) -> Vec<Item> {
438 if items.windows(2).all(|w| ctx.key(&w[0]) < ctx.key(&w[1])) {
440 return items;
441 }
442 let mut keyed: Vec<_> = items.into_iter().map(|i| (ctx.key(&i), i)).collect();
444 keyed.sort_unstable_by_key(|(k, _)| *k);
445 keyed.dedup_by_key(|(k, _)| *k);
446 keyed.into_iter().map(|(_, i)| i).collect()
447}
448
449fn walk<'a>(mut items: Vec<Item>, steps: &[Step], ctx: &Context<'a, '_>) -> Result<Vec<Item>> {
450 let index = ctx.doc.index;
451 let mut candidates = Vec::new();
452 let mut scanned = Vec::new();
453 let mut i = 0;
454 while i < steps.len() {
455 let step = &steps[i];
456 i += 1;
457 if let Some(next) = steps.get(i)
461 && step.axis == Axis::DescendantOrSelf
462 && step.test == NodeTest::Node
463 && step.predicates.is_empty()
464 && next.axis == Axis::Child
465 && !next.predicates.is_empty()
466 && let Some(grouped) = descendants_by_parent(&items, next, ctx)
467 {
468 items = grouped?;
469 i += 1;
470 continue;
471 }
472 let test = Test::resolve(&step.test, step.axis, ctx)?;
473 if step.predicates.is_empty()
478 && items.len() > 1
479 && let Some(found) = whole_set(&items, step.axis, &test, ctx)?
480 {
481 items = found;
482 continue;
483 }
484 let nth = match step.predicates.first() {
486 Some(Expr::Number(k)) if *k >= 1.0 && k.fract() == 0.0 && *k < usize::MAX as f64 => {
487 Some(*k as usize)
488 }
489 _ => None,
490 };
491 let mut next = Vec::new();
492 for item in &items {
493 candidates.clear();
494 let mut done = 0;
496 match (item, test.indexable()) {
497 (Item::Node(n), true)
500 if matches!(
501 step.axis,
502 Axis::Child | Axis::Descendant | Axis::DescendantOrSelf
503 ) =>
504 {
505 let at = ctx.order(*n);
506 let keep = |kind, tag| test.keeps(kind, tag);
507 scanned.clear();
508 match step.axis {
509 Axis::Child => index.children(at, keep, &mut scanned),
510 axis => {
511 ctx.spend((index.end_of(at) - at) as usize)?;
512 index.descendants(
513 at,
514 axis == Axis::DescendantOrSelf,
515 keep,
516 &mut scanned,
517 )
518 }
519 }
520 candidates.extend(
521 scanned
522 .iter()
523 .copied()
524 .map(Item::Node)
525 .filter(|i| !test.exact() || test.matches(i, ctx)),
526 );
527 }
528 _ => {
529 let looked = Cell::new(0usize);
530 let mut on_axis = axis(*item, step.axis, ctx)?
531 .inspect(|_| looked.set(looked.get() + 1))
532 .filter(|c| test.matches(c, ctx));
533 if nth.is_some() {
534 done = 1;
535 }
536 match nth {
537 Some(k) => candidates.extend(on_axis.nth(k - 1)),
540 None => candidates.extend(on_axis),
541 }
542 ctx.spend(looked.get())?;
543 }
544 }
545 ctx.spend(candidates.len() + 1)?;
546 let mut kept = std::mem::take(&mut candidates);
547 for p in &step.predicates[done..] {
548 kept = filter(kept, p, ctx)?;
549 }
550 next.extend_from_slice(&kept);
551 candidates = kept;
552 }
553 items = if items.len() == 1 && !step.axis.is_reverse() {
556 next
557 } else {
558 in_document_order(next, ctx)
559 };
560 }
561 Ok(items)
562}
563
564fn whole_set<'a>(
568 items: &[Item],
569 axis: Axis,
570 test: &Test<'_>,
571 ctx: &Context<'a, '_>,
572) -> Result<Option<Vec<Item>>> {
573 let index = ctx.doc.index;
574 let (_, tree_end) = ctx.tree_range();
575 let keep = |j: u32| {
576 let item = Item::Node(index.node_at(j));
577 if test.indexable() {
578 test.keeps(index.kind_at(j), index.tag_at(j))
579 && (!test.exact() || test.matches(&item, ctx))
580 } else {
581 test.matches(&item, ctx)
582 }
583 };
584 let mut out = Vec::new();
585 match axis {
586 Axis::Descendant | Axis::DescendantOrSelf => {
587 let mut covered_to = 0;
589 for item in items {
590 match item {
591 Item::Node(n) => {
592 let at = ctx.order(*n);
593 if at < covered_to {
594 continue;
595 }
596 covered_to = index.end_of(at);
597 let from = if axis == Axis::DescendantOrSelf {
598 at
599 } else {
600 at + 1
601 };
602 ctx.spend((covered_to - from) as usize)?;
603 out.extend(
604 (from..covered_to)
605 .filter(|&j| keep(j))
606 .map(|j| Item::Node(index.node_at(j))),
607 );
608 }
609 attr if axis == Axis::DescendantOrSelf && test.matches(attr, ctx) => {
611 out.push(*attr)
612 }
613 _ => {}
614 }
615 }
616 return Ok(Some(in_document_order(out, ctx)));
617 }
618 Axis::Following => {
619 let Some(from) = items
622 .iter()
623 .map(|i| match i {
624 Item::Node(n) => index.end_of(ctx.order(*n)),
625 Item::Attr { owner, .. } | Item::Ns { owner, .. } => ctx.order(*owner) + 1,
626 })
627 .min()
628 else {
629 return Ok(Some(out));
630 };
631 ctx.spend(tree_end.saturating_sub(from) as usize)?;
632 out.extend(
633 (from..tree_end)
634 .filter(|&j| keep(j))
635 .map(|j| Item::Node(index.node_at(j))),
636 );
637 }
638 Axis::Preceding => {
639 let Some(last) = items.iter().map(|i| ctx.key(i).0).max() else {
641 return Ok(Some(out));
642 };
643 let (top, _) = ctx.tree_range();
644 ctx.spend(last.saturating_sub(top) as usize)?;
645 out.extend(
647 (top..last)
648 .filter(|&j| index.end_of(j) <= last && keep(j))
649 .map(|j| Item::Node(index.node_at(j))),
650 );
651 }
652 Axis::Ancestor | Axis::AncestorOrSelf => {
653 let mut seen = HashSet::new();
655 for item in items {
656 let start = match item {
657 Item::Node(n) if axis == Axis::Ancestor => index.parent_of(ctx.order(*n)),
658 Item::Node(n) => ctx.order(*n),
659 Item::Attr { owner, .. } | Item::Ns { owner, .. } => {
660 if axis == Axis::AncestorOrSelf && test.matches(item, ctx) {
661 out.push(*item);
662 }
663 ctx.order(*owner)
664 }
665 };
666 let mut at = start;
667 while at != u32::MAX && seen.insert(at) {
668 ctx.spend(1)?;
669 if keep(at) {
670 out.push(Item::Node(index.node_at(at)));
671 }
672 at = index.parent_of(at);
673 }
674 }
675 return Ok(Some(in_document_order(out, ctx)));
676 }
677 Axis::FollowingSibling | Axis::PrecedingSibling => {
678 let tree = ctx.doc.tree;
681 let mut from: HashMap<NodeId, NodeId> = HashMap::new();
682 for item in items {
683 if let Item::Node(n) = item
684 && let Some(p) = tree.parent(*n)
685 {
686 if axis == Axis::FollowingSibling {
687 from.entry(p).or_insert(*n);
688 } else {
689 from.insert(p, *n);
690 }
691 }
692 }
693 for &n in from.values() {
694 let step = |&s: &NodeId| match axis {
695 Axis::FollowingSibling => tree.next_sibling(s),
696 _ => tree.prev_sibling(s),
697 };
698 for s in std::iter::successors(step(&n), step) {
699 ctx.spend(1)?;
700 if keep(ctx.order(s)) {
701 out.push(Item::Node(s));
702 }
703 }
704 }
705 return Ok(Some(in_document_order(out, ctx)));
706 }
707 _ => return Ok(None),
708 }
709 Ok(Some(out))
710}
711
712fn descendants_by_parent<'a>(
716 items: &[Item],
717 step: &Step,
718 ctx: &Context<'a, '_>,
719) -> Option<Result<Vec<Item>>> {
720 let test = match Test::resolve(&step.test, step.axis, ctx) {
721 Ok(test) => test,
722 Err(e) => return Some(Err(e)),
723 };
724 if !test.indexable() {
725 return None;
726 }
727 let index = ctx.doc.index;
728 let mut found = Vec::new();
729 let mut covered_to = 0;
733 for item in items {
734 let Item::Node(n) = item else { continue };
736 let at = ctx.order(*n);
737 if at < covered_to {
738 continue;
739 }
740 covered_to = index.end_of(at);
741 if let Err(e) = ctx.spend((covered_to - at) as usize) {
742 return Some(Err(e));
743 }
744 index.descendants(at, false, |k, t| test.keeps(k, t), &mut found);
745 }
746 if test.exact() {
747 found.retain(|&n| test.matches(&Item::Node(n), ctx));
748 }
749 if !step.predicates.iter().any(Expr::positional) {
753 let mut items: Vec<Item> = found.into_iter().map(Item::Node).collect();
754 for p in &step.predicates {
755 let p = match p {
756 Expr::Memo(inner, _) if !ctx.nested => inner,
757 p => p,
758 };
759 items = match filter(items, p, ctx) {
760 Ok(items) => items,
761 Err(e) => return Some(Err(e)),
762 };
763 }
764 return Some(Ok(items));
765 }
766 let mut groups: Vec<(u32, Vec<Item>)> = Vec::new();
768 let mut slot: HashMap<u32, usize> = HashMap::new();
769 for node in found {
770 let parent = index.parent_of(ctx.order(node));
771 let at = *slot.entry(parent).or_insert_with(|| {
772 groups.push((parent, Vec::new()));
773 groups.len() - 1
774 });
775 groups[at].1.push(Item::Node(node));
776 }
777 let run = || -> Result<Vec<Item>> {
778 let mut out = Vec::new();
779 for (_, mut group) in groups {
780 for p in &step.predicates {
781 group = filter(group, p, ctx)?;
782 }
783 out.extend(group);
784 }
785 Ok(in_document_order(out, ctx))
786 };
787 Some(run())
788}
789
790fn quick_predicate(pred: &Expr, item: &Item, doc: Doc<'_>) -> Option<bool> {
794 let attr_name = |e: &Expr| match e {
795 Expr::Path {
796 absolute: false,
797 steps,
798 } => match steps.as_slice() {
799 [
800 Step {
801 axis: Axis::Attribute,
802 test: NodeTest::Name(n),
803 predicates,
804 },
805 ] if predicates.is_empty() && !n.bytes().any(|b| b.is_ascii_uppercase()) => {
809 Some(n.clone())
810 }
811 _ => None,
812 },
813 _ => None,
814 };
815 let Item::Node(node) = item else { return None };
816 match pred {
817 Expr::Binary(Op::Eq, l, r) => {
818 let (name, value) = match (attr_name(l), attr_name(r), &**l, &**r) {
819 (Some(n), None, _, Expr::Literal(v)) | (None, Some(n), Expr::Literal(v), _) => {
820 (n, v)
821 }
822 _ => return None,
823 };
824 Some(doc.attr(*node, &name) == Some(value.as_str()))
825 }
826 other => attr_name(other).map(|n| doc.attr(*node, &n).is_some()),
827 }
828}
829
830fn filter<'a>(items: Vec<Item>, pred: &Expr, ctx: &Context<'a, '_>) -> Result<Vec<Item>> {
833 let size = items.len();
834 ctx.spend(size)?;
835 let mut kept = items;
837 let mut len = 0;
838 for i in 0..size {
839 let item = kept[i];
840 if let Some(keep) = quick_predicate(pred, &item, ctx.doc) {
841 if keep {
842 kept[len] = item;
843 len += 1;
844 }
845 continue;
846 }
847 let inner = Context {
848 item,
849 position: i + 1,
850 size,
851 nested: true,
852 ..*ctx
853 };
854 let keep = match eval(pred, &inner)? {
855 Value::Num(n) => n == (i + 1) as f64,
856 other => boolean(&other),
857 };
858 if keep {
859 kept[len] = item;
860 len += 1;
861 }
862 }
863 kept.truncate(len);
864 Ok(kept)
865}
866
867fn namespace<'v>(prefix: &str, ctx: &Context<'_, 'v>) -> Result<&'v str> {
869 if let Some((_, uri)) = ctx.namespaces.iter().rev().find(|(p, _)| p == prefix) {
870 return Ok(uri);
871 }
872 if prefix == "xml" {
873 return Ok(XML_NS);
874 }
875 Err(format!("undefined namespace prefix {prefix:?}"))
876}
877
878enum Test<'t> {
881 Node,
882 Text,
883 Comment,
884 Pi(Option<&'t str>),
886 Never,
887 AnyElement,
889 AnyAttribute,
890 AnyNamespace,
891 NamespaceName(&'t str),
893 ElementId(usize),
894 ElementName(&'t str),
897 AttributeName(&'t str),
898 XmlElement {
902 id: usize,
903 local: &'t str,
904 ns: &'t str,
905 },
906 XmlElementIn(&'t str),
908 XmlAttribute {
909 local: &'t str,
910 ns: &'t str,
911 },
912 XmlAttributeIn(&'t str),
913}
914
915impl<'t> Test<'t> {
916 fn resolve(test: &'t NodeTest, axis: Axis, ctx: &Context<'_, 't>) -> Result<Test<'t>> {
917 if axis == Axis::Namespace {
918 return Ok(match test {
920 NodeTest::Node => Test::Node,
921 NodeTest::Any => Test::AnyNamespace,
922 NodeTest::Name(prefix) => Test::NamespaceName(prefix),
923 NodeTest::Prefixed(p, _) | NodeTest::AnyIn(p) => {
924 namespace(p, ctx)?;
925 Test::Never
926 }
927 _ => Test::Never,
928 });
929 }
930 let attr = axis == Axis::Attribute;
931 let index = ctx.doc.index;
932 if ctx.doc.is_xml() {
933 let ns = |prefix: &str| namespace(prefix, ctx);
935 return Ok(match test {
936 NodeTest::Name(local) if attr => Test::XmlAttribute { local, ns: "" },
937 NodeTest::Prefixed(p, local) if attr => Test::XmlAttribute { local, ns: ns(p)? },
938 NodeTest::AnyIn(p) if attr => Test::XmlAttributeIn(ns(p)?),
939 NodeTest::Name(local) => match index.tag_id_named(local) {
940 Some(id) => Test::XmlElement { id, local, ns: "" },
941 None => Test::Never,
942 },
943 NodeTest::Prefixed(p, local) => match (ns(p)?, index.tag_id_named(local)) {
944 (ns, Some(id)) => Test::XmlElement { id, local, ns },
945 _ => Test::Never,
946 },
947 NodeTest::AnyIn(p) => Test::XmlElementIn(ns(p)?),
948 other => Test::resolve_html(other, attr, ctx),
949 });
950 }
951 if let NodeTest::Prefixed(p, _) | NodeTest::AnyIn(p) = test {
952 namespace(p, ctx)?;
955 return Ok(Test::Never);
956 }
957 Ok(Test::resolve_html(test, attr, ctx))
958 }
959
960 fn resolve_html(test: &'t NodeTest, attr: bool, ctx: &Context<'_, '_>) -> Test<'t> {
961 match test {
962 NodeTest::Node => Test::Node,
963 NodeTest::Text if attr => Test::Never,
964 NodeTest::Text => Test::Text,
965 NodeTest::Comment if attr => Test::Never,
966 NodeTest::Comment => Test::Comment,
967 NodeTest::ProcessingInstruction(_) if attr => Test::Never,
970 NodeTest::ProcessingInstruction(target) => Test::Pi(target.as_deref()),
971 NodeTest::Any if attr => Test::AnyAttribute,
972 NodeTest::Any => Test::AnyElement,
973 NodeTest::Name(name) if attr => Test::AttributeName(name),
974 NodeTest::Name(name) if name.bytes().any(|b| b.is_ascii_uppercase()) => {
975 Test::ElementName(name)
976 }
977 NodeTest::Name(name) => ctx
978 .doc
979 .index
980 .tag_id_named(name)
981 .map_or(Test::Never, Test::ElementId),
982 NodeTest::Prefixed(..) | NodeTest::AnyIn(_) => Test::Never,
983 }
984 }
985
986 fn indexable(&self) -> bool {
989 matches!(
990 self,
991 Test::Node
992 | Test::Text
993 | Test::Comment
994 | Test::Pi(None)
995 | Test::AnyElement
996 | Test::ElementId(_)
997 | Test::XmlElement { .. }
998 | Test::Never
999 )
1000 }
1001
1002 fn exact(&self) -> bool {
1004 matches!(self, Test::XmlElement { .. })
1005 }
1006
1007 fn keeps(&self, kind: u8, tag: usize) -> bool {
1009 match self {
1010 Test::Node => true,
1011 Test::Text => kind == TEXT || kind == CDATA,
1012 Test::Comment => kind == COMMENT,
1013 Test::Pi(None) => kind == PI,
1014 Test::AnyElement => kind == ELEMENT,
1015 Test::ElementId(id) | Test::XmlElement { id, .. } => kind == ELEMENT && tag == *id,
1016 _ => false,
1017 }
1018 }
1019
1020 fn matches(&self, item: &Item, ctx: &Context<'_, '_>) -> bool {
1021 let kind = |n: &NodeId| ctx.kind(*n);
1022 match (self, item) {
1023 (Test::Node, _) => true,
1024 (Test::Never, _) => false,
1025 (Test::ElementId(id), Item::Node(n)) => {
1026 let at = ctx.order(*n);
1027 ctx.doc.index.tag_at(at) == *id && ctx.doc.index.kind_at(at) == ELEMENT
1028 }
1029 (Test::ElementName(name), Item::Node(n)) => {
1030 kind(n) == ELEMENT && ctx.doc.tree.local_name(*n) == *name
1031 }
1032 (Test::AnyElement, Item::Node(n)) => kind(n) == ELEMENT,
1033 (Test::Text, Item::Node(n)) => matches!(kind(n), TEXT | CDATA),
1034 (Test::Comment, Item::Node(n)) => kind(n) == COMMENT,
1035 (Test::Pi(target), Item::Node(n)) => {
1036 kind(n) == PI && target.is_none_or(|t| ctx.pi_target(*n) == Some(t))
1037 }
1038 (Test::AnyAttribute, Item::Attr { .. }) => true,
1039 (Test::AnyNamespace, Item::Ns { .. }) => true,
1040 (Test::NamespaceName(prefix), Item::Ns { decl, .. }) => {
1041 ctx.doc.namespace_at(*decl).0 == *prefix
1042 }
1043 (Test::AttributeName(name), Item::Attr { owner, index }) => {
1044 ctx.doc.attr_at(*owner, *index).0 == *name
1045 }
1046 (Test::XmlElement { local, ns, .. }, Item::Node(n)) => {
1047 kind(n) == ELEMENT
1048 && ctx.doc.tree.local_name(*n) == *local
1049 && ctx.doc.tree.namespace_uri(*n) == *ns
1050 }
1051 (Test::XmlElementIn(ns), Item::Node(n)) => {
1052 kind(n) == ELEMENT && ctx.doc.tree.namespace_uri(*n) == *ns
1053 }
1054 (Test::XmlAttribute { local, ns }, i @ Item::Attr { .. }) => ctx
1055 .attribute(i)
1056 .is_some_and(|a| a.namespace_uri == *ns && a.local_name == *local),
1057 (Test::XmlAttributeIn(ns), i @ Item::Attr { .. }) => {
1058 ctx.attribute(i).is_some_and(|a| a.namespace_uri == *ns)
1059 }
1060 _ => false,
1061 }
1062 }
1063}
1064
1065fn attributes(n: NodeId, doc: Doc<'_>) -> impl Iterator<Item = Item> + use<> {
1066 (0..doc.tree.attribute_count(n)).map(move |index| Item::Attr { owner: n, index })
1067}
1068
1069fn axis<'a>(
1072 item: Item,
1073 axis: Axis,
1074 ctx: &Context<'a, '_>,
1075) -> Result<Box<dyn Iterator<Item = Item> + 'a>> {
1076 let doc = ctx.doc;
1077 let (tree, index) = (doc.tree, doc.index);
1078 let (top, tree_end) = ctx.tree_range();
1079 let node_at = move |j: u32| Item::Node(index.node_at(j));
1080 let ancestors =
1081 move |n: NodeId| std::iter::successors(tree.parent(n), move |&p| tree.parent(p));
1082 let children =
1083 move |n: NodeId| std::iter::successors(tree.first_child(n), move |&c| tree.next_sibling(c));
1084 let following = move |n: NodeId| (index.end_of(index.order(n))..tree_end).map(node_at);
1086 let preceding = move |n: NodeId| {
1088 let at = index.order(n);
1089 (top..at)
1090 .rev()
1091 .filter(move |&j| index.end_of(j) <= at)
1092 .map(node_at)
1093 };
1094 let descendants = move |n: NodeId| {
1095 let at = index.order(n);
1096 (at + 1..index.end_of(at)).map(node_at)
1097 };
1098 Ok(match item {
1099 Item::Node(n) => match axis {
1100 Axis::Child => Box::new(children(n).map(Item::Node)),
1101 Axis::Descendant => Box::new(descendants(n)),
1102 Axis::DescendantOrSelf => Box::new(std::iter::once(item).chain(descendants(n))),
1103 Axis::Parent => Box::new(tree.parent(n).map(Item::Node).into_iter()),
1104 Axis::Ancestor => Box::new(ancestors(n).map(Item::Node)),
1105 Axis::AncestorOrSelf => {
1106 Box::new(std::iter::once(n).chain(ancestors(n)).map(Item::Node))
1107 }
1108 Axis::FollowingSibling => Box::new(
1109 std::iter::successors(tree.next_sibling(n), move |&s| tree.next_sibling(s))
1110 .map(Item::Node),
1111 ),
1112 Axis::PrecedingSibling => Box::new(
1113 std::iter::successors(tree.prev_sibling(n), move |&s| tree.prev_sibling(s))
1114 .map(Item::Node),
1115 ),
1116 Axis::Following => Box::new(following(n)),
1117 Axis::Preceding => Box::new(preceding(n)),
1118 Axis::Attribute if ctx.kind(n) == ELEMENT => Box::new(attributes(n, doc)),
1119 Axis::Namespace if ctx.kind(n) == ELEMENT => {
1120 let list = ctx.namespaces(n)?;
1121 Box::new(
1122 std::iter::once(XML_DECL)
1123 .chain((0..list.len()).map(move |k| list[k]))
1124 .map(move |decl| Item::Ns { owner: n, decl }),
1125 )
1126 }
1127 Axis::Attribute | Axis::Namespace => Box::new(std::iter::empty()),
1128 Axis::Itself => Box::new(std::iter::once(item)),
1129 },
1130 Item::Attr { owner, .. } | Item::Ns { owner, .. } => match axis {
1131 Axis::Parent => Box::new(std::iter::once(Item::Node(owner))),
1132 Axis::Ancestor => Box::new(
1133 std::iter::once(owner)
1134 .chain(ancestors(owner))
1135 .map(Item::Node),
1136 ),
1137 Axis::AncestorOrSelf => Box::new(
1138 std::iter::once(item).chain(
1139 std::iter::once(owner)
1140 .chain(ancestors(owner))
1141 .map(Item::Node),
1142 ),
1143 ),
1144 Axis::Itself | Axis::DescendantOrSelf => Box::new(std::iter::once(item)),
1145 Axis::Following => Box::new(descendants(owner).chain(following(owner))),
1146 Axis::Preceding => Box::new(preceding(owner)),
1147 _ => Box::new(std::iter::empty()),
1148 },
1149 })
1150}
1151
1152fn string<'a>(v: &Value<'a>, ctx: &Context<'a, '_>) -> String {
1155 match v {
1156 Value::Str(s) => s.to_string(),
1157 Value::Num(n) => number_to_string(*n),
1158 Value::Bool(b) => b.to_string(),
1159 Value::Nodes(items) => items
1160 .first()
1161 .map(|i| ctx.string_value(i).into_owned())
1162 .unwrap_or_default(),
1163 }
1164}
1165
1166fn number_to_string(n: f64) -> String {
1167 if n.is_nan() {
1168 "NaN".into()
1169 } else if n.is_infinite() {
1170 if n > 0.0 { "Infinity" } else { "-Infinity" }.into()
1171 } else if n == 0.0 {
1172 "0".into()
1173 } else {
1174 format!("{n}")
1177 }
1178}
1179
1180fn number<'a>(v: Value<'a>, ctx: &Context<'a, '_>) -> f64 {
1181 match v {
1182 Value::Num(n) => n,
1183 Value::Bool(b) => b as u8 as f64,
1184 Value::Str(s) => parse_number(&s),
1185 nodes @ Value::Nodes(_) => parse_number(&string(&nodes, ctx)),
1186 }
1187}
1188
1189fn parse_number(s: &str) -> f64 {
1192 let t = s.trim_matches(|c| matches!(c, ' ' | '\t' | '\n' | '\r'));
1193 let digits = t.strip_prefix('-').unwrap_or(t);
1194 let valid = !digits.is_empty()
1195 && digits.chars().all(|c| c.is_ascii_digit() || c == '.')
1196 && digits.matches('.').count() <= 1
1197 && digits != ".";
1198 if valid {
1199 t.parse().unwrap_or(f64::NAN)
1200 } else {
1201 f64::NAN
1202 }
1203}
1204
1205fn boolean(v: &Value<'_>) -> bool {
1206 match v {
1207 Value::Bool(b) => *b,
1208 Value::Num(n) => *n != 0.0 && !n.is_nan(),
1209 Value::Str(s) => !s.is_empty(),
1210 Value::Nodes(items) => !items.is_empty(),
1211 }
1212}
1213
1214fn binary<'a>(op: Op, l: &Expr, r: &Expr, ctx: &Context<'a, '_>) -> Result<Value<'a>> {
1217 Ok(match op {
1218 Op::Or => Value::Bool(boolean(&eval(l, ctx)?) || boolean(&eval(r, ctx)?)),
1219 Op::And => Value::Bool(boolean(&eval(l, ctx)?) && boolean(&eval(r, ctx)?)),
1220 Op::Add | Op::Sub | Op::Mul | Op::Div | Op::Mod => {
1221 let (a, b) = (number(eval(l, ctx)?, ctx), number(eval(r, ctx)?, ctx));
1222 Value::Num(match op {
1223 Op::Add => a + b,
1224 Op::Sub => a - b,
1225 Op::Mul => a * b,
1226 Op::Div => a / b,
1227 _ => a % b,
1229 })
1230 }
1231 _ => Value::Bool(compare(op, eval(l, ctx)?, eval(r, ctx)?, ctx)),
1232 })
1233}
1234
1235fn compare_atoms<'a>(op: Op, a: &Value<'a>, b: &Value<'a>, ctx: &Context<'a, '_>) -> bool {
1236 if matches!(op, Op::Eq | Op::Neq) {
1237 let equal = if matches!(a, Value::Bool(_)) || matches!(b, Value::Bool(_)) {
1238 boolean(a) == boolean(b)
1239 } else if matches!(a, Value::Num(_)) || matches!(b, Value::Num(_)) {
1240 number(a.clone(), ctx) == number(b.clone(), ctx)
1241 } else {
1242 fn text<'v, 'a>(v: &'v Value<'a>, ctx: &Context<'a, '_>) -> Cow<'v, str> {
1245 match v {
1246 Value::Str(s) => Cow::Borrowed(s),
1247 other => Cow::Owned(string(other, ctx)),
1248 }
1249 }
1250 text(a, ctx) == text(b, ctx)
1251 };
1252 return equal == (op == Op::Eq);
1253 }
1254 let (x, y) = (number(a.clone(), ctx), number(b.clone(), ctx));
1255 match op {
1256 Op::Lt => x < y,
1257 Op::Le => x <= y,
1258 Op::Gt => x > y,
1259 _ => x >= y,
1260 }
1261}
1262
1263fn compare<'a>(op: Op, a: Value<'a>, b: Value<'a>, ctx: &Context<'a, '_>) -> bool {
1265 match (&a, &b) {
1266 (Value::Nodes(xs), Value::Nodes(ys)) => {
1267 let ys: Vec<Value<'_>> = ys.iter().map(|y| Value::Str(ctx.string_value(y))).collect();
1268 xs.iter().any(|x| {
1269 let x = Value::Str(ctx.string_value(x));
1270 ys.iter().any(|y| compare_atoms(op, &x, y, ctx))
1271 })
1272 }
1273 (Value::Nodes(_), Value::Bool(_)) | (Value::Bool(_), Value::Nodes(_)) => compare_atoms(
1274 op,
1275 &Value::Bool(boolean(&a)),
1276 &Value::Bool(boolean(&b)),
1277 ctx,
1278 ),
1279 (Value::Nodes(xs), other) => xs
1280 .iter()
1281 .any(|x| compare_atoms(op, &atom_like(x, other, ctx), other, ctx)),
1282 (other, Value::Nodes(ys)) => ys
1283 .iter()
1284 .any(|y| compare_atoms(op, other, &atom_like(y, other, ctx), ctx)),
1285 _ => compare_atoms(op, &a, &b, ctx),
1286 }
1287}
1288
1289fn atom_like<'a>(item: &Item, other: &Value<'_>, ctx: &Context<'a, '_>) -> Value<'a> {
1291 match other {
1292 Value::Num(_) => Value::Num(parse_number(&ctx.string_value(item))),
1293 _ => Value::Str(ctx.string_value(item)),
1294 }
1295}
1296
1297pub struct Args<'c, 'a> {
1302 name: &'c str,
1303 exprs: &'c [Expr],
1304 ctx: &'c Context<'a, 'c>,
1305}
1306
1307impl<'a> Args<'_, 'a> {
1308 pub fn len(&self) -> usize {
1309 self.exprs.len()
1310 }
1311
1312 pub fn is_empty(&self) -> bool {
1313 self.exprs.is_empty()
1314 }
1315
1316 pub fn arity(&self, min: usize, max: usize) -> Result<()> {
1318 arity(self.name, self.exprs.len(), min, max)
1319 }
1320
1321 pub fn value(&self, i: usize) -> Result<Value<'a>> {
1323 eval(&self.exprs[i], self.ctx)
1324 }
1325
1326 pub fn string(&self, i: usize) -> Result<String> {
1328 Ok(string(&self.value(i)?, self.ctx))
1329 }
1330
1331 pub fn context(&self) -> Item {
1333 self.ctx.item
1334 }
1335
1336 pub fn doc(&self) -> Doc<'a> {
1337 self.ctx.doc
1338 }
1339}
1340
1341fn arity(name: &str, got: usize, min: usize, max: usize) -> Result<()> {
1342 if got < min || got > max {
1343 let expected = if min == max {
1344 format!("{min}")
1345 } else if max == usize::MAX {
1346 format!("at least {min}")
1347 } else {
1348 format!("{min} to {max}")
1349 };
1350 return Err(format!("{name}() takes {expected} arguments, got {got}"));
1351 }
1352 Ok(())
1353}
1354
1355fn call<'a>(name: &str, args: &[Expr], ctx: &Context<'a, '_>) -> Result<Value<'a>> {
1356 let arity = |min: usize, max: usize| arity(name, args.len(), min, max);
1357 let arg = |i: usize| eval(&args[i], ctx);
1358 let str_arg = |i: usize| -> Result<String> { Ok(string(&eval(&args[i], ctx)?, ctx)) };
1359 let nodes_arg = |i: usize| -> Result<Vec<Item>> {
1360 match eval(&args[i], ctx)? {
1361 Value::Nodes(n) => Ok(n),
1362 _ => Err(format!("{name}() needs a node-set argument")),
1363 }
1364 };
1365 let context_or = |i: usize| -> Result<Vec<Item>> {
1368 if args.len() > i {
1369 nodes_arg(i)
1370 } else {
1371 Ok(vec![ctx.item])
1372 }
1373 };
1374 Ok(match name {
1375 "last" => {
1376 arity(0, 0)?;
1377 Value::Num(ctx.size as f64)
1378 }
1379 "position" => {
1380 arity(0, 0)?;
1381 Value::Num(ctx.position as f64)
1382 }
1383 "count" => {
1384 arity(1, 1)?;
1385 Value::Num(nodes_arg(0)?.len() as f64)
1386 }
1387 "id" => {
1388 arity(1, 1)?;
1389 let wanted: Vec<String> = match arg(0)? {
1390 Value::Nodes(items) => items
1391 .iter()
1392 .map(|i| ctx.string_value(i).into_owned())
1393 .collect(),
1394 other => vec![string(&other, ctx)],
1395 };
1396 let index = ctx.doc.index;
1397 let doc = ctx.doc;
1398 let (top, end) = ctx.tree_range();
1399 let found = wanted
1400 .iter()
1401 .flat_map(|s| s.split_whitespace())
1402 .flat_map(|id| index.with_id(id, |n| doc.tree.id(n)))
1403 .filter(|&n| (top..end).contains(&ctx.order(n)))
1404 .map(Item::Node)
1405 .collect();
1406 Value::Nodes(in_document_order(found, ctx))
1407 }
1408 "local-name" | "name" | "namespace-uri" => {
1409 arity(0, 1)?;
1410 let first = in_document_order(context_or(0)?, ctx).into_iter().next();
1411 text(
1412 first
1413 .map(|i| match name {
1414 "name" => ctx.name(&i),
1415 "local-name" => ctx.local_name(&i),
1416 _ => ctx.namespace_uri(&i),
1417 })
1418 .unwrap_or_default()
1419 .to_string(),
1420 )
1421 }
1422 "string" => {
1423 arity(0, 1)?;
1424 text(if args.is_empty() {
1425 ctx.string_value(&ctx.item).into_owned()
1426 } else {
1427 str_arg(0)?
1428 })
1429 }
1430 "concat" => {
1431 arity(2, usize::MAX)?;
1432 let mut out = String::new();
1433 for i in 0..args.len() {
1434 out.push_str(&str_arg(i)?);
1435 }
1436 text(out)
1437 }
1438 "starts-with" => {
1439 arity(2, 2)?;
1440 Value::Bool(str_arg(0)?.starts_with(&str_arg(1)?))
1441 }
1442 "contains" => {
1443 arity(2, 2)?;
1444 Value::Bool(str_arg(0)?.contains(&str_arg(1)?))
1445 }
1446 "substring-before" => {
1447 arity(2, 2)?;
1448 let (s, t) = (str_arg(0)?, str_arg(1)?);
1449 text(s.find(&t).map(|i| s[..i].to_string()).unwrap_or_default())
1450 }
1451 "substring-after" => {
1452 arity(2, 2)?;
1453 let (s, t) = (str_arg(0)?, str_arg(1)?);
1454 text(
1455 s.find(&t)
1456 .map(|i| s[i + t.len()..].to_string())
1457 .unwrap_or_default(),
1458 )
1459 }
1460 "substring" => {
1461 arity(2, 3)?;
1462 let s = str_arg(0)?;
1463 let start = round(number(arg(1)?, ctx));
1464 let end = if args.len() == 3 {
1465 start + round(number(arg(2)?, ctx))
1466 } else {
1467 f64::INFINITY
1468 };
1469 text(
1471 s.chars()
1472 .enumerate()
1473 .filter(|(i, _)| {
1474 let p = (*i + 1) as f64;
1475 p >= start && p < end
1476 })
1477 .map(|(_, c)| c)
1478 .collect(),
1479 )
1480 }
1481 "string-length" => {
1482 arity(0, 1)?;
1483 let s = if args.is_empty() {
1484 ctx.string_value(&ctx.item).into_owned()
1485 } else {
1486 str_arg(0)?
1487 };
1488 Value::Num(s.chars().count() as f64)
1489 }
1490 "normalize-space" => {
1491 arity(0, 1)?;
1492 let s = if args.is_empty() {
1493 ctx.string_value(&ctx.item).into_owned()
1494 } else {
1495 str_arg(0)?
1496 };
1497 text(
1498 s.split([' ', '\t', '\n', '\r'])
1499 .filter(|w| !w.is_empty())
1500 .collect::<Vec<_>>()
1501 .join(" "),
1502 )
1503 }
1504 "translate" => {
1505 arity(3, 3)?;
1506 let (s, from, to) = (str_arg(0)?, str_arg(1)?, str_arg(2)?);
1507 let from: Vec<char> = from.chars().collect();
1508 let to: Vec<char> = to.chars().collect();
1509 text(
1510 s.chars()
1511 .filter_map(|c| match from.iter().position(|&f| f == c) {
1512 Some(i) => to.get(i).copied(),
1513 None => Some(c),
1514 })
1515 .collect(),
1516 )
1517 }
1518 "boolean" => {
1519 arity(1, 1)?;
1520 Value::Bool(boolean(&arg(0)?))
1521 }
1522 "not" => {
1523 arity(1, 1)?;
1524 Value::Bool(!boolean(&arg(0)?))
1525 }
1526 "true" => {
1527 arity(0, 0)?;
1528 Value::Bool(true)
1529 }
1530 "false" => {
1531 arity(0, 0)?;
1532 Value::Bool(false)
1533 }
1534 "lang" => {
1535 arity(1, 1)?;
1536 let want = str_arg(0)?.to_ascii_lowercase();
1537 let node = match ctx.item {
1538 Item::Node(n) => n,
1539 Item::Attr { owner, .. } | Item::Ns { owner, .. } => owner,
1540 };
1541 let tree = ctx.doc.tree;
1542 let mut declared = None;
1544 let mut at = Some(node);
1545 while let Some(n) = at {
1546 ctx.spend(1)?;
1547 declared = tree.lang(n);
1548 if declared.is_some() {
1549 break;
1550 }
1551 at = tree.parent(n);
1552 }
1553 let declared = declared.map(str::to_ascii_lowercase);
1554 Value::Bool(declared.is_some_and(|l| l == want || l.starts_with(&format!("{want}-"))))
1555 }
1556 "number" => {
1557 arity(0, 1)?;
1558 Value::Num(if args.is_empty() {
1559 parse_number(&ctx.string_value(&ctx.item))
1560 } else {
1561 number(arg(0)?, ctx)
1562 })
1563 }
1564 "sum" => {
1565 arity(1, 1)?;
1566 Value::Num(
1568 nodes_arg(0)?
1569 .iter()
1570 .map(|i| parse_number(&ctx.string_value(i)))
1571 .fold(0.0, |a, b| a + b),
1572 )
1573 }
1574 "floor" => {
1575 arity(1, 1)?;
1576 Value::Num(number(arg(0)?, ctx).floor())
1577 }
1578 "ceiling" => {
1579 arity(1, 1)?;
1580 Value::Num(number(arg(0)?, ctx).ceil())
1581 }
1582 "round" => {
1583 arity(1, 1)?;
1584 Value::Num(round(number(arg(0)?, ctx)))
1585 }
1586 _ => {
1587 let args = Args {
1588 name,
1589 exprs: args,
1590 ctx,
1591 };
1592 return ctx
1593 .ext
1594 .call(name, &args)
1595 .unwrap_or_else(|| Err(format!("unknown function {name}()")));
1596 }
1597 })
1598}
1599
1600fn round(x: f64) -> f64 {
1602 if x.is_nan() || x.is_infinite() {
1603 x
1604 } else if (-0.5..0.0).contains(&x) {
1605 -0.0
1606 } else {
1607 let f = x.floor();
1610 if x - f >= 0.5 { f + 1.0 } else { f }
1611 }
1612}
1613
1614#[cfg(test)]
1615mod tests {
1616 use super::*;
1617
1618 #[test]
1619 fn xpath_number_grammar() {
1620 assert_eq!(parse_number(" 12.5\n"), 12.5);
1621 assert_eq!(parse_number("-.5"), -0.5);
1622 assert_eq!(parse_number("5."), 5.0);
1623 for bad in ["", ".", "1e3", "+1", "0x10", "1.2.3", "inf", "NaN", "- 1"] {
1624 assert!(parse_number(bad).is_nan(), "{bad:?}");
1625 }
1626 }
1627}