Skip to main content

xsd_schema/compose/
value.rs

1//! Query results, and the Rust values that can be bound into a query.
2//!
3//! [`Value`] is what an evaluation hands back: an XDM sequence, unchanged,
4//! with the conversions a host actually asks for on top of it.
5//! [`IntoXPathValue`] is the way in: it turns Rust scalars, navigators,
6//! documents and sequences into the engine's value type so they can be bound
7//! to an external variable.
8
9use std::fmt;
10
11use num_bigint::BigInt;
12use rust_decimal::Decimal;
13
14use crate::types::value::XmlValue;
15use crate::xpath::atomize::{atomize_node, node_atoms, single_atom, to_number, Atoms};
16use crate::xpath::functions::effective_boolean_value;
17use crate::xpath::{XPathError, XPathValue, XmlItem};
18
19use super::{ComposeError, Doc, Nav};
20
21/// The result of one evaluation.
22///
23/// A `Value` is a thin wrapper around the engine's own
24/// [`XPathValue`]: nothing is atomized, copied or
25/// flattened until a method asks for it. The accessors are the ones a host
26/// needs — the nodes, the atomic values, a boolean, a string, a number, an
27/// order-by key — and each says exactly when it refuses.
28///
29/// ```
30/// use bumpalo::Bump;
31/// use xsd_schema::compose::Composer;
32/// use xsd_schema::namespace::NameTable;
33///
34/// let arena = Bump::new();
35/// let names = NameTable::new();
36/// let c = Composer::new(&arena, &names);
37/// let doc = c.load_str("<a><b>1</b><b>2</b></a>")?;
38///
39/// let bs = c.eval("//b", &[], Some(doc.root()), Vec::new())?;
40/// assert_eq!(bs.len(), 2);
41/// assert_eq!(bs.nodes()?.len(), 2);
42///
43/// let total = c.eval("sum(//b)", &[], Some(doc.root()), Vec::new())?;
44/// assert_eq!(total.number()?, 3.0);
45/// assert_eq!(total.string()?, "3");
46/// # Ok::<(), Box<dyn std::error::Error>>(())
47/// ```
48#[derive(Clone)]
49pub struct Value<'a>(XPathValue<Nav<'a>>);
50
51impl<'a> Value<'a> {
52    /// The node items, in order.
53    ///
54    /// An atomic item is [`ComposeError::NotANode`]: dropping it silently
55    /// would hide a mistake in the expression.
56    /// [`pipe::nodes`](crate::compose::pipe::nodes) is the streaming
57    /// counterpart.
58    ///
59    /// ```
60    /// use bumpalo::Bump;
61    /// use xsd_schema::compose::{ComposeError, Composer};
62    /// use xsd_schema::namespace::NameTable;
63    /// use xsd_schema::navigator::DomNavigator;
64    ///
65    /// let arena = Bump::new();
66    /// let names = NameTable::new();
67    /// let c = Composer::new(&arena, &names);
68    /// let doc = c.load_str("<a><b/></a>")?;
69    ///
70    /// let nodes = c.eval("//b", &[], Some(doc.root()), Vec::new())?.nodes()?;
71    /// assert_eq!(nodes[0].local_name(), "b");
72    ///
73    /// // A string is not a node.
74    /// let atomic = c.eval("'x'", &[], None, Vec::new())?;
75    /// assert!(matches!(atomic.nodes(), Err(ComposeError::NotANode)));
76    /// # Ok::<(), Box<dyn std::error::Error>>(())
77    /// ```
78    pub fn nodes(&self) -> Result<Vec<Nav<'a>>, ComposeError> {
79        let mut out = Vec::with_capacity(self.len());
80        for item in self.iter() {
81            match item {
82                XmlItem::Node(node) => out.push(node.clone()),
83                XmlItem::Atomic(_) => return Err(ComposeError::NotANode),
84            }
85        }
86        Ok(out)
87    }
88
89    /// Every item atomized, in order.
90    ///
91    /// A node is atomized with
92    /// [`atomize_node`], so an untyped
93    /// element yields its `xs:untypedAtomic` string value and a typed one its
94    /// typed value: one value per member when its type is a list type
95    /// (XDM §3.3.1.2). A nilled element contributes nothing.
96    ///
97    /// ```
98    /// use bumpalo::Bump;
99    /// use xsd_schema::compose::Composer;
100    /// use xsd_schema::namespace::NameTable;
101    ///
102    /// let arena = Bump::new();
103    /// let names = NameTable::new();
104    /// let c = Composer::new(&arena, &names);
105    /// let doc = c.load_str("<a><b>1</b><b>2</b></a>")?;
106    ///
107    /// let atomics = c.eval("//b", &[], Some(doc.root()), Vec::new())?.atomics()?;
108    /// let text: Vec<String> = atomics.iter().map(|v| v.to_string_value()).collect();
109    /// assert_eq!(text, ["1", "2"]);
110    /// # Ok::<(), Box<dyn std::error::Error>>(())
111    /// ```
112    pub fn atomics(&self) -> Result<Vec<XmlValue>, ComposeError> {
113        let mut out = Vec::with_capacity(self.len());
114        for item in self.iter() {
115            match item {
116                XmlItem::Atomic(value) => out.extend(Atoms::of(value.clone())),
117                XmlItem::Node(node) => out.extend(node_atoms(node)?),
118            }
119        }
120        Ok(out)
121    }
122
123    /// The effective boolean value (XPath 2.0 §2.4.3).
124    ///
125    /// ```
126    /// use bumpalo::Bump;
127    /// use xsd_schema::compose::Composer;
128    /// use xsd_schema::namespace::NameTable;
129    ///
130    /// let arena = Bump::new();
131    /// let names = NameTable::new();
132    /// let c = Composer::new(&arena, &names);
133    /// let doc = c.load_str("<a><b>x</b></a>")?;
134    ///
135    /// assert!(c.eval("//b", &[], Some(doc.root()), Vec::new())?.boolean()?);
136    /// assert!(!c.eval("//zzz", &[], Some(doc.root()), Vec::new())?.boolean()?);
137    /// # Ok::<(), Box<dyn std::error::Error>>(())
138    /// ```
139    pub fn boolean(&self) -> Result<bool, ComposeError> {
140        Ok(effective_boolean_value(&self.0)?)
141    }
142
143    /// The string value of the single item, `""` for the empty sequence.
144    ///
145    /// More than one item is [`ComposeError::NotSingleton`]; use
146    /// [`atomics`](Self::atomics) to join a sequence yourself.
147    ///
148    /// ```
149    /// use bumpalo::Bump;
150    /// use xsd_schema::compose::{ComposeError, Composer};
151    /// use xsd_schema::namespace::NameTable;
152    ///
153    /// let arena = Bump::new();
154    /// let names = NameTable::new();
155    /// let c = Composer::new(&arena, &names);
156    /// let doc = c.load_str("<a><b>one</b><b>two</b></a>")?;
157    ///
158    /// assert_eq!(c.eval("//b[1]", &[], Some(doc.root()), Vec::new())?.string()?, "one");
159    /// assert_eq!(c.eval("()", &[], None, Vec::new())?.string()?, "");
160    /// assert!(matches!(
161    ///     c.eval("//b", &[], Some(doc.root()), Vec::new())?.string(),
162    ///     Err(ComposeError::NotSingleton { len: 2 }),
163    /// ));
164    /// # Ok::<(), Box<dyn std::error::Error>>(())
165    /// ```
166    pub fn string(&self) -> Result<String, ComposeError> {
167        match self.single()? {
168            None => Ok(String::new()),
169            Some(XmlItem::Atomic(value)) => Ok(value.to_string_value()),
170            Some(XmlItem::Node(node)) => Ok(crate::navigator::DomNavigator::value(node)),
171        }
172    }
173
174    /// `fn:number()` of the single item: `NaN` when it does not convert, and
175    /// `NaN` for the empty sequence.
176    ///
177    /// More than one item is [`ComposeError::NotSingleton`].
178    ///
179    /// ```
180    /// use bumpalo::Bump;
181    /// use xsd_schema::compose::Composer;
182    /// use xsd_schema::namespace::NameTable;
183    ///
184    /// let arena = Bump::new();
185    /// let names = NameTable::new();
186    /// let c = Composer::new(&arena, &names);
187    ///
188    /// assert_eq!(c.eval("2 + 3", &[], None, Vec::new())?.number()?, 5.0);
189    /// assert!(c.eval("'nope'", &[], None, Vec::new())?.number()?.is_nan());
190    /// assert!(c.eval("()", &[], None, Vec::new())?.number()?.is_nan());
191    /// # Ok::<(), Box<dyn std::error::Error>>(())
192    /// ```
193    pub fn number(&self) -> Result<f64, ComposeError> {
194        match self.atomize_single()? {
195            None => Ok(f64::NAN),
196            Some(value) => Ok(to_number(&value)),
197        }
198    }
199
200    /// The `order by` key: the single atomized item, or `None` for the empty
201    /// sequence.
202    ///
203    /// More than one item is `XPTY0004`, reported as
204    /// [`ComposeError::XPath`] — an order-by key must be at most one value
205    /// (XQuery 1.0 §3.8.3).
206    ///
207    /// ```
208    /// use bumpalo::Bump;
209    /// use xsd_schema::compose::Composer;
210    /// use xsd_schema::namespace::NameTable;
211    ///
212    /// let arena = Bump::new();
213    /// let names = NameTable::new();
214    /// let c = Composer::new(&arena, &names);
215    /// let doc = c.load_str("<a><b>7</b></a>")?;
216    ///
217    /// let key = c.eval("b", &[], Some(doc.document_element().unwrap()), Vec::new())?.key()?;
218    /// assert_eq!(key.unwrap().to_string_value(), "7");
219    /// assert!(c.eval("()", &[], None, Vec::new())?.key()?.is_none());
220    /// # Ok::<(), Box<dyn std::error::Error>>(())
221    /// ```
222    pub fn key(&self) -> Result<Option<XmlValue>, ComposeError> {
223        let len = self.len();
224        if len > 1 {
225            return Err(ComposeError::XPath {
226                source: XPathError::type_mismatch(
227                    "xs:anyAtomicType?",
228                    format!("a sequence of {len} items"),
229                ),
230                expr: String::new(),
231            });
232        }
233        self.atomize_single()
234    }
235
236    /// How many items the sequence holds.
237    ///
238    /// ```
239    /// use bumpalo::Bump;
240    /// use xsd_schema::compose::Composer;
241    /// use xsd_schema::namespace::NameTable;
242    ///
243    /// let arena = Bump::new();
244    /// let names = NameTable::new();
245    /// let c = Composer::new(&arena, &names);
246    ///
247    /// assert_eq!(c.eval("()", &[], None, Vec::new())?.len(), 0);
248    /// assert_eq!(c.eval("1", &[], None, Vec::new())?.len(), 1);
249    /// assert_eq!(c.eval("(1, 2, 3)", &[], None, Vec::new())?.len(), 3);
250    /// # Ok::<(), Box<dyn std::error::Error>>(())
251    /// ```
252    pub fn len(&self) -> usize {
253        self.0.len()
254    }
255
256    /// Whether the sequence is empty.
257    ///
258    /// ```
259    /// use bumpalo::Bump;
260    /// use xsd_schema::compose::Composer;
261    /// use xsd_schema::namespace::NameTable;
262    ///
263    /// let arena = Bump::new();
264    /// let names = NameTable::new();
265    /// let c = Composer::new(&arena, &names);
266    ///
267    /// assert!(c.eval("()", &[], None, Vec::new())?.is_empty());
268    /// assert!(!c.eval("1", &[], None, Vec::new())?.is_empty());
269    /// # Ok::<(), Box<dyn std::error::Error>>(())
270    /// ```
271    pub fn is_empty(&self) -> bool {
272        self.0.is_empty()
273    }
274
275    /// Borrows the items, in order.
276    ///
277    /// A one-item sequence is one item here: the engine stores a singleton
278    /// without a backing vector, and this iterator yields it all the same.
279    ///
280    /// ```
281    /// use bumpalo::Bump;
282    /// use xsd_schema::compose::Composer;
283    /// use xsd_schema::namespace::NameTable;
284    ///
285    /// let arena = Bump::new();
286    /// let names = NameTable::new();
287    /// let c = Composer::new(&arena, &names);
288    ///
289    /// assert_eq!(c.eval("1", &[], None, Vec::new())?.iter().count(), 1);
290    /// assert_eq!(c.eval("(1, 2, 3)", &[], None, Vec::new())?.iter().count(), 3);
291    /// # Ok::<(), Box<dyn std::error::Error>>(())
292    /// ```
293    pub fn iter(&self) -> impl Iterator<Item = &XmlItem<Nav<'a>>> + '_ {
294        self.0.as_slice().iter()
295    }
296
297    /// The wrapped engine value.
298    ///
299    /// ```
300    /// use bumpalo::Bump;
301    /// use xsd_schema::compose::Composer;
302    /// use xsd_schema::namespace::NameTable;
303    ///
304    /// let arena = Bump::new();
305    /// let names = NameTable::new();
306    /// let c = Composer::new(&arena, &names);
307    ///
308    /// let sequence = c.eval("(1, 2)", &[], None, Vec::new())?.into_inner();
309    /// assert_eq!(sequence.into_vec().len(), 2);
310    /// # Ok::<(), Box<dyn std::error::Error>>(())
311    /// ```
312    pub fn into_inner(self) -> XPathValue<Nav<'a>> {
313        self.0
314    }
315
316    /// Borrows the wrapped engine value.
317    ///
318    /// ```
319    /// use bumpalo::Bump;
320    /// use xsd_schema::compose::Composer;
321    /// use xsd_schema::namespace::NameTable;
322    ///
323    /// let arena = Bump::new();
324    /// let names = NameTable::new();
325    /// let c = Composer::new(&arena, &names);
326    ///
327    /// let value = c.eval("(1, 2)", &[], None, Vec::new())?;
328    /// assert_eq!(value.inner().len(), 2);
329    /// // …and the `Value` is still usable afterwards.
330    /// assert_eq!(value.len(), 2);
331    /// # Ok::<(), Box<dyn std::error::Error>>(())
332    /// ```
333    pub fn inner(&self) -> &XPathValue<Nav<'a>> {
334        &self.0
335    }
336
337    /// The one item, `None` when empty, [`ComposeError::NotSingleton`] beyond
338    /// one.
339    fn single(&self) -> Result<Option<&XmlItem<Nav<'a>>>, ComposeError> {
340        match self.len() {
341            0 => Ok(None),
342            1 => Ok(self.0.first()),
343            len => Err(ComposeError::NotSingleton { len }),
344        }
345    }
346
347    /// [`single`](Self::single), atomized: `None` when the item atomizes to
348    /// the empty sequence (a nilled element, an empty list), `XPTY0004` when it
349    /// atomizes to more than one value (a list-typed node with several
350    /// members).
351    fn atomize_single(&self) -> Result<Option<XmlValue>, ComposeError> {
352        match self.single()? {
353            None => Ok(None),
354            Some(XmlItem::Atomic(value)) => Ok(single_atom(value.clone())?),
355            Some(XmlItem::Node(node)) => match atomize_node(node)? {
356                None => Ok(None),
357                Some(value) => Ok(single_atom(value)?),
358            },
359        }
360    }
361}
362
363impl<'a> From<XPathValue<Nav<'a>>> for Value<'a> {
364    fn from(value: XPathValue<Nav<'a>>) -> Self {
365        Self(value)
366    }
367}
368
369/// One line per item, for a `Debug` rendering.
370///
371/// The navigator type has no `Debug` of its own, and printing a whole subtree
372/// would be worse than useless in an assertion message, so a node is named by
373/// its kind and its qualified name and an atomic value by its string value.
374pub(super) fn describe_items(value: &XPathValue<Nav<'_>>) -> Vec<String> {
375    let items: Vec<&XmlItem<Nav<'_>>> = match value {
376        XPathValue::Empty => Vec::new(),
377        XPathValue::Item(item) => vec![item],
378        XPathValue::Sequence(items) => items.iter().collect(),
379    };
380    items
381        .into_iter()
382        .map(|item| match item {
383            XmlItem::Atomic(atomic) => format!("{:?}", atomic.to_string_value()),
384            XmlItem::Node(node) => {
385                use crate::navigator::DomNavigator;
386                format!("{:?}({})", node.node_type(), node.name())
387            }
388        })
389        .collect()
390}
391
392impl fmt::Debug for Value<'_> {
393    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394        f.debug_tuple("Value")
395            .field(&describe_items(&self.0))
396            .finish()
397    }
398}
399
400// ── IntoXPathValue ────────────────────────────────────────────────────
401
402/// A Rust value that can be bound to an external XPath variable.
403///
404/// Binding never parses or serializes anything: a navigator becomes a node
405/// item, a document becomes its document node, a `Vec` becomes a sequence,
406/// and a scalar becomes the atomic value XDM gives it.
407///
408/// ```
409/// use bumpalo::Bump;
410/// use xsd_schema::compose::{Composer, IntoXPathValue};
411/// use xsd_schema::namespace::NameTable;
412///
413/// let arena = Bump::new();
414/// let names = NameTable::new();
415/// let c = Composer::new(&arena, &names);
416/// let doc = c.load_str("<a><b>1</b><b>2</b></a>")?;
417///
418/// // A document binds as its document node …
419/// let n = c.eval(
420///     "count($d//b)",
421///     &["d"],
422///     None,
423///     vec![("d", doc.into_xpath_value())],
424/// )?;
425/// assert_eq!(n.string()?, "2");
426///
427/// // … and a scalar as an atomic value.
428/// let doubled = c.eval("$x * 2", &["x"], None, vec![("x", 21.into_xpath_value())])?;
429/// assert_eq!(doubled.string()?, "42");
430/// # Ok::<(), Box<dyn std::error::Error>>(())
431/// ```
432pub trait IntoXPathValue<'a> {
433    /// Converts `self` into a bindable sequence.
434    fn into_xpath_value(self) -> XPathValue<Nav<'a>>;
435}
436
437impl<'a> IntoXPathValue<'a> for XPathValue<Nav<'a>> {
438    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
439        self
440    }
441}
442
443impl<'a> IntoXPathValue<'a> for Value<'a> {
444    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
445        self.into_inner()
446    }
447}
448
449impl<'a> IntoXPathValue<'a> for &Value<'a> {
450    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
451        self.inner().clone()
452    }
453}
454
455impl<'a> IntoXPathValue<'a> for Nav<'a> {
456    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
457        XPathValue::from_node(self)
458    }
459}
460
461impl<'a> IntoXPathValue<'a> for &Nav<'a> {
462    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
463        XPathValue::from_node(self.clone())
464    }
465}
466
467impl<'a> IntoXPathValue<'a> for Doc<'a> {
468    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
469        XPathValue::from_node(self.root())
470    }
471}
472
473impl<'a> IntoXPathValue<'a> for &Doc<'a> {
474    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
475        XPathValue::from_node(self.root())
476    }
477}
478
479impl<'a> IntoXPathValue<'a> for XmlValue {
480    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
481        XPathValue::from_atomic(self)
482    }
483}
484
485impl<'a> IntoXPathValue<'a> for &XmlValue {
486    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
487        XPathValue::from_atomic(self.clone())
488    }
489}
490
491impl<'a> IntoXPathValue<'a> for bool {
492    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
493        XPathValue::boolean(self)
494    }
495}
496
497impl<'a> IntoXPathValue<'a> for i32 {
498    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
499        XPathValue::integer(BigInt::from(self))
500    }
501}
502
503impl<'a> IntoXPathValue<'a> for i64 {
504    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
505        XPathValue::integer(BigInt::from(self))
506    }
507}
508
509impl<'a> IntoXPathValue<'a> for BigInt {
510    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
511        XPathValue::integer(self)
512    }
513}
514
515impl<'a> IntoXPathValue<'a> for f64 {
516    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
517        XPathValue::double(self)
518    }
519}
520
521impl<'a> IntoXPathValue<'a> for Decimal {
522    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
523        XPathValue::decimal(self)
524    }
525}
526
527impl<'a> IntoXPathValue<'a> for &str {
528    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
529        XPathValue::string(self)
530    }
531}
532
533impl<'a> IntoXPathValue<'a> for String {
534    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
535        XPathValue::string(self)
536    }
537}
538
539impl<'a> IntoXPathValue<'a> for Vec<Nav<'a>> {
540    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
541        XPathValue::from_sequence(self.into_iter().map(XmlItem::Node).collect())
542    }
543}
544
545impl<'a> IntoXPathValue<'a> for &[Nav<'a>] {
546    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
547        XPathValue::from_sequence(self.iter().cloned().map(XmlItem::Node).collect())
548    }
549}
550
551impl<'a> IntoXPathValue<'a> for Vec<XmlItem<Nav<'a>>> {
552    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
553        XPathValue::from_sequence(self)
554    }
555}
556
557impl<'a> IntoXPathValue<'a> for Vec<XmlValue> {
558    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
559        XPathValue::from_sequence(self.into_iter().map(XmlItem::Atomic).collect())
560    }
561}
562
563impl<'a, T: IntoXPathValue<'a>> IntoXPathValue<'a> for Option<T> {
564    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
565        match self {
566            Some(value) => value.into_xpath_value(),
567            None => XPathValue::Empty,
568        }
569    }
570}
571
572impl<'a> IntoXPathValue<'a> for () {
573    fn into_xpath_value(self) -> XPathValue<Nav<'a>> {
574        XPathValue::Empty
575    }
576}
577
578// ── IntoContextNode ───────────────────────────────────────────────────
579
580/// A value usable as the context item of an evaluation.
581///
582/// The context item of a composed query is always a node in v1: a navigator,
583/// or a document standing for its document node.
584///
585/// ```
586/// use bumpalo::Bump;
587/// use xsd_schema::compose::{Composer, IntoContextNode};
588/// use xsd_schema::namespace::NameTable;
589///
590/// let arena = Bump::new();
591/// let names = NameTable::new();
592/// let c = Composer::new(&arena, &names);
593/// let doc = c.load_str("<a><b>deep</b></a>")?;
594///
595/// // A document and a navigator reach the same node here.
596/// let from_doc = c.eval("string(//b)", &[], Some(doc.into_context_node()), Vec::new())?;
597/// let root = doc.root();
598/// let from_nav = c.eval("string(//b)", &[], Some((&root).into_context_node()), Vec::new())?;
599/// assert_eq!(from_doc.string()?, from_nav.string()?);
600/// # Ok::<(), Box<dyn std::error::Error>>(())
601/// ```
602pub trait IntoContextNode<'a> {
603    /// Converts `self` into the navigator to focus on.
604    fn into_context_node(self) -> Nav<'a>;
605}
606
607impl<'a> IntoContextNode<'a> for Nav<'a> {
608    fn into_context_node(self) -> Nav<'a> {
609        self
610    }
611}
612
613impl<'a> IntoContextNode<'a> for &Nav<'a> {
614    fn into_context_node(self) -> Nav<'a> {
615        self.clone()
616    }
617}
618
619impl<'a> IntoContextNode<'a> for Doc<'a> {
620    fn into_context_node(self) -> Nav<'a> {
621        self.root()
622    }
623}
624
625impl<'a> IntoContextNode<'a> for &Doc<'a> {
626    fn into_context_node(self) -> Nav<'a> {
627        self.root()
628    }
629}
630
631#[cfg(test)]
632mod tests {
633    use bumpalo::Bump;
634
635    use super::*;
636    use crate::compose::Composer;
637    use crate::namespace::NameTable;
638    use crate::navigator::DomNavigator;
639
640    fn composer<'a>(arena: &'a Bump, names: &'a NameTable) -> Composer<'a> {
641        Composer::new(arena, names)
642    }
643
644    #[test]
645    fn iter_keeps_a_singleton() {
646        let value: Value<'_> = XPathValue::string("only").into();
647        assert_eq!(value.len(), 1);
648        assert_eq!(value.iter().count(), 1);
649        assert!(!value.is_empty());
650    }
651
652    #[test]
653    fn iter_walks_empty_and_sequences() {
654        let empty: Value<'_> = XPathValue::Empty.into();
655        assert_eq!(empty.iter().count(), 0);
656        assert!(empty.is_empty());
657
658        let many: Value<'_> = XPathValue::from_sequence(vec![
659            XmlItem::Atomic(XmlValue::string("a")),
660            XmlItem::Atomic(XmlValue::string("b")),
661        ])
662        .into();
663        assert_eq!(many.iter().count(), 2);
664    }
665
666    #[test]
667    fn nodes_refuses_an_atomic_item() {
668        let value: Value<'_> = XPathValue::string("x").into();
669        assert!(matches!(value.nodes(), Err(ComposeError::NotANode)));
670    }
671
672    #[test]
673    fn accessors_over_a_loaded_document() {
674        let arena = Bump::new();
675        let names = NameTable::new();
676        let c = composer(&arena, &names);
677        let doc = c.load_str("<a><b>1</b><b>2</b></a>").unwrap();
678
679        let bs = c.eval("//b", &[], Some(doc.root()), Vec::new()).unwrap();
680        assert_eq!(bs.nodes().unwrap().len(), 2);
681        assert_eq!(bs.atomics().unwrap().len(), 2);
682        assert!(bs.boolean().unwrap());
683        assert!(matches!(
684            bs.string(),
685            Err(ComposeError::NotSingleton { len: 2 })
686        ));
687        assert!(matches!(
688            bs.number(),
689            Err(ComposeError::NotSingleton { len: 2 })
690        ));
691    }
692
693    #[test]
694    fn string_and_number_of_a_node() {
695        let arena = Bump::new();
696        let names = NameTable::new();
697        let c = composer(&arena, &names);
698        let doc = c.load_str("<a><b>42</b></a>").unwrap();
699
700        let b = c.eval("//b", &[], Some(doc.root()), Vec::new()).unwrap();
701        assert_eq!(b.string().unwrap(), "42");
702        assert_eq!(b.number().unwrap(), 42.0);
703        assert_eq!(b.key().unwrap().unwrap().to_string_value(), "42");
704    }
705
706    #[test]
707    fn empty_string_number_and_key() {
708        let arena = Bump::new();
709        let names = NameTable::new();
710        let c = composer(&arena, &names);
711        let empty = c.eval("()", &[], None, Vec::new()).unwrap();
712        assert_eq!(empty.string().unwrap(), "");
713        assert!(empty.number().unwrap().is_nan());
714        assert!(empty.key().unwrap().is_none());
715    }
716
717    #[test]
718    fn key_refuses_more_than_one_item() {
719        let arena = Bump::new();
720        let names = NameTable::new();
721        let c = composer(&arena, &names);
722        let two = c.eval("(1, 2)", &[], None, Vec::new()).unwrap();
723        match two.key() {
724            Err(ComposeError::XPath { source, .. }) => {
725                assert_eq!(source.error_code(), Some("XPTY0004"));
726            }
727            other => panic!("expected XPTY0004, got {other:?}"),
728        }
729    }
730
731    /// A packed list value — the stored typed value of a list-typed node —
732    /// atomizes to its members, one per member (XDM §3.3.1.2), and a singleton
733    /// accessor takes at most one of them.
734    #[test]
735    fn a_packed_list_value_atomizes_to_its_members() {
736        use crate::types::value::XmlValueKind;
737        use crate::types::XmlTypeCode;
738
739        let list = |members: &[i64]| -> Value<'_> {
740            XPathValue::from_atomic(XmlValue::new(
741                XmlTypeCode::Integer,
742                XmlValueKind::List {
743                    item_type: XmlTypeCode::Integer,
744                    items: members
745                        .iter()
746                        .map(|&m| XmlValue::integer(BigInt::from(m)))
747                        .collect(),
748                },
749            ))
750            .into()
751        };
752
753        let two = list(&[4, 5]);
754        let atomics = two.atomics().unwrap();
755        assert_eq!(atomics.len(), 2);
756        assert!(atomics.iter().all(|v| v.type_code == XmlTypeCode::Integer));
757        assert_eq!(atomics[1].to_string_value(), "5");
758        match two.key() {
759            Err(ComposeError::XPath { source, .. }) => {
760                assert_eq!(source.error_code(), Some("XPTY0004"));
761            }
762            other => panic!("expected XPTY0004, got {other:?}"),
763        }
764
765        assert_eq!(list(&[6]).number().unwrap(), 6.0);
766        assert!(list(&[]).number().unwrap().is_nan());
767        assert!(list(&[]).key().unwrap().is_none());
768        assert!(list(&[]).atomics().unwrap().is_empty());
769    }
770
771    #[test]
772    fn every_into_xpath_value_impl() {
773        let arena = Bump::new();
774        let names = NameTable::new();
775        let c = composer(&arena, &names);
776        let doc = c.load_str("<a><b>1</b><b>2</b></a>").unwrap();
777        let root = doc.root();
778        let bs = c.eval("//b", &[], Some(doc.root()), Vec::new()).unwrap();
779        let node_list = bs.nodes().unwrap();
780
781        // Each binding is checked through an expression that only holds for
782        // the value that impl is supposed to produce.
783        let cases: Vec<(&str, XPathValue<Nav<'_>>, &str)> = vec![
784            ("$x", true.into_xpath_value(), "true"),
785            ("$x", 7i32.into_xpath_value(), "7"),
786            ("$x", 8i64.into_xpath_value(), "8"),
787            ("$x", BigInt::from(9).into_xpath_value(), "9"),
788            ("$x", 1.5f64.into_xpath_value(), "1.5"),
789            ("$x", Decimal::new(25, 1).into_xpath_value(), "2.5"),
790            ("$x", "text".into_xpath_value(), "text"),
791            ("$x", String::from("owned").into_xpath_value(), "owned"),
792            ("$x", XmlValue::string("atom").into_xpath_value(), "atom"),
793            ("$x", (&XmlValue::string("ref")).into_xpath_value(), "ref"),
794            ("name($x)", root.clone().into_xpath_value(), ""),
795            ("name($x)", (&root).into_xpath_value(), ""),
796            ("count($x//b)", doc.into_xpath_value(), "2"),
797            ("count($x//b)", (&doc).into_xpath_value(), "2"),
798            ("count($x)", bs.clone().into_xpath_value(), "2"),
799            ("count($x)", (&bs).into_xpath_value(), "2"),
800            (
801                "count($x)",
802                XPathValue::from_sequence(vec![XmlItem::Atomic(XmlValue::string("q"))])
803                    .into_xpath_value(),
804                "1",
805            ),
806            ("count($x)", node_list.clone().into_xpath_value(), "2"),
807            ("count($x)", node_list.as_slice().into_xpath_value(), "2"),
808            (
809                "count($x)",
810                vec![
811                    XmlItem::Atomic(XmlValue::string("a")),
812                    XmlItem::Atomic(XmlValue::string("b")),
813                ]
814                .into_xpath_value(),
815                "2",
816            ),
817            (
818                "count($x)",
819                vec![XmlValue::string("a"), XmlValue::string("b")].into_xpath_value(),
820                "2",
821            ),
822            ("$x", Some(3i32).into_xpath_value(), "3"),
823            ("count($x)", Option::<i32>::None.into_xpath_value(), "0"),
824            ("count($x)", ().into_xpath_value(), "0"),
825        ];
826
827        for (expr, bound, expected) in cases {
828            let got = c
829                .eval(expr, &["x"], None, vec![("x", bound)])
830                .unwrap()
831                .string()
832                .unwrap();
833            if !expected.is_empty() {
834                assert_eq!(got, expected, "binding for {expr}");
835            }
836        }
837    }
838
839    #[test]
840    fn into_context_node_impls_agree() {
841        let arena = Bump::new();
842        let names = NameTable::new();
843        let c = composer(&arena, &names);
844        let doc = c.load_str("<a><b>deep</b></a>").unwrap();
845        let root = doc.root();
846
847        for node in [
848            doc.into_context_node(),
849            (&doc).into_context_node(),
850            root.clone().into_context_node(),
851            (&root).into_context_node(),
852        ] {
853            assert!(node.is_same_position(&root));
854        }
855    }
856}