Skip to main content

xsd_schema/compose/
form.rs

1//! The description of a result element, before any document exists.
2//!
3//! A [`Form`] is an owned, eager tree: a name, the namespace declarations the
4//! author asked for, attributes, and content. Nothing in it is a closure and
5//! nothing in it is lazy — every Rust value that goes into a form has already
6//! been evaluated — so a form can be returned from a function, stored in a
7//! `Vec`, and handed to [`Composer::build`](crate::compose::Composer::build)
8//! later.
9
10use std::fmt;
11
12use crate::namespace::is_ncname;
13use crate::types::value::XmlValue;
14use crate::xpath::{XPathValue, XmlItem};
15
16use super::value::describe_items;
17use super::{ComposeError, IntoXPathValue, Nav, Value};
18
19/// An element or attribute name as the author wrote it.
20///
21/// A `Name` is a prefix and a local part, not a resolved name: the prefix is
22/// looked up when the document is built, against the form's own declarations
23/// first and the composer's namespace table second. An empty prefix on an
24/// element takes the composer's default element namespace; an empty prefix on
25/// an attribute means no namespace, as Namespaces in XML 1.0 §6.2 requires.
26///
27/// ```
28/// use xsd_schema::compose::Name;
29///
30/// assert_eq!(Name::local("item").to_string(), "item");
31/// assert_eq!(Name::prefixed("p", "item").to_string(), "p:item");
32/// assert_eq!(Name::parse("p:item")?.prefix(), "p");
33/// assert!(Name::parse("not a name").is_err());
34/// # Ok::<(), Box<dyn std::error::Error>>(())
35/// ```
36#[derive(Clone, Debug, PartialEq, Eq, Hash)]
37pub struct Name {
38    prefix: String,
39    local: String,
40}
41
42impl Name {
43    /// A name with no prefix.
44    ///
45    /// ```
46    /// use xsd_schema::compose::Name;
47    ///
48    /// let n = Name::local("high_bid");
49    /// assert_eq!(n.prefix(), "");
50    /// assert_eq!(n.local_name(), "high_bid");
51    /// ```
52    pub fn local(local: &str) -> Self {
53        Self {
54            prefix: String::new(),
55            local: local.to_string(),
56        }
57    }
58
59    /// A name with a prefix to resolve at build time.
60    ///
61    /// ```
62    /// use xsd_schema::compose::Name;
63    ///
64    /// let n = Name::prefixed("xml", "lang");
65    /// assert_eq!(n.prefix(), "xml");
66    /// assert_eq!(n.local_name(), "lang");
67    /// ```
68    pub fn prefixed(prefix: &str, local: &str) -> Self {
69        Self {
70            prefix: prefix.to_string(),
71            local: local.to_string(),
72        }
73    }
74
75    /// Parses `local` or `prefix:local`, checking both halves are `NCName`s.
76    ///
77    /// ```
78    /// use xsd_schema::compose::{ComposeError, Name};
79    ///
80    /// assert_eq!(Name::parse("bid-count")?.local_name(), "bid-count");
81    /// assert_eq!(Name::parse("p:bid")?.prefix(), "p");
82    /// assert!(matches!(Name::parse("a:b:c"), Err(ComposeError::InvalidName(_))));
83    /// assert!(matches!(Name::parse(""), Err(ComposeError::InvalidName(_))));
84    /// # Ok::<(), Box<dyn std::error::Error>>(())
85    /// ```
86    pub fn parse(text: &str) -> Result<Self, ComposeError> {
87        let invalid = || ComposeError::InvalidName(text.to_string());
88        match text.split_once(':') {
89            None => {
90                if is_ncname(text) {
91                    Ok(Self::local(text))
92                } else {
93                    Err(invalid())
94                }
95            }
96            Some((prefix, local)) => {
97                if is_ncname(prefix) && is_ncname(local) {
98                    Ok(Self::prefixed(prefix, local))
99                } else {
100                    Err(invalid())
101                }
102            }
103        }
104    }
105
106    /// The prefix, empty when there is none.
107    ///
108    /// ```
109    /// use xsd_schema::compose::Name;
110    ///
111    /// assert_eq!(Name::prefixed("p", "a").prefix(), "p");
112    /// assert_eq!(Name::local("a").prefix(), "");
113    /// ```
114    pub fn prefix(&self) -> &str {
115        &self.prefix
116    }
117
118    /// The local part.
119    ///
120    /// ```
121    /// use xsd_schema::compose::Name;
122    ///
123    /// assert_eq!(Name::prefixed("p", "a").local_name(), "a");
124    /// ```
125    pub fn local_name(&self) -> &str {
126        &self.local
127    }
128}
129
130impl fmt::Display for Name {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        if self.prefix.is_empty() {
133            f.write_str(&self.local)
134        } else {
135            write!(f, "{}:{}", self.prefix, self.local)
136        }
137    }
138}
139
140/// What an attribute's value is made of.
141///
142/// ```
143/// use xsd_schema::compose::AttrValue;
144///
145/// // A Rust value formatted with `Display` …
146/// let literal = AttrValue::text(42);
147/// assert!(matches!(literal, AttrValue::Text(ref s) if s == "42"));
148///
149/// // … or an XDM sequence, atomized and space-joined when the document is built.
150/// let computed: AttrValue<'_> = AttrValue::value("x");
151/// assert!(matches!(computed, AttrValue::Value(_)));
152/// ```
153#[derive(Clone)]
154pub enum AttrValue<'a> {
155    /// Literal text, written exactly as given.
156    Text(String),
157    /// A sequence: every item is atomized and their string values are joined
158    /// with single spaces (XQuery 1.0 §3.7.1.1).
159    Value(XPathValue<Nav<'a>>),
160}
161
162impl<'a> AttrValue<'a> {
163    /// An attribute value from anything that formats itself.
164    ///
165    /// ```
166    /// use xsd_schema::compose::AttrValue;
167    ///
168    /// assert!(matches!(AttrValue::text("b1"), AttrValue::Text(ref s) if s == "b1"));
169    /// ```
170    pub fn text(value: impl fmt::Display) -> Self {
171        Self::Text(value.to_string())
172    }
173
174    /// An attribute value from a query result or any bindable Rust value.
175    ///
176    /// ```
177    /// use bumpalo::Bump;
178    /// use xsd_schema::compose::{AttrValue, Composer};
179    /// use xsd_schema::namespace::NameTable;
180    ///
181    /// let arena = Bump::new();
182    /// let names = NameTable::new();
183    /// let c = Composer::new(&arena, &names);
184    ///
185    /// let ids = c.eval("(1, 2, 3)", &[], None, Vec::new())?;
186    /// let attr = AttrValue::value(ids);
187    /// assert!(matches!(attr, AttrValue::Value(_)));
188    /// # Ok::<(), Box<dyn std::error::Error>>(())
189    /// ```
190    pub fn value(value: impl IntoXPathValue<'a>) -> Self {
191        Self::Value(value.into_xpath_value())
192    }
193}
194
195/// One item of an element's content.
196///
197/// ```
198/// use xsd_schema::compose::{Content, Form, Name};
199///
200/// let mut form = Form::new(Name::local("p"));
201/// form.push(Content::Text("hello".to_string()));
202/// form.push(Content::Comment(" note ".to_string()));
203/// assert_eq!(form.content().len(), 2);
204/// ```
205#[derive(Clone)]
206pub enum Content<'a> {
207    /// Literal text. Two adjacent texts concatenate with no separator.
208    Text(String),
209    /// A sequence, emitted with the constructor content rules: atomic values
210    /// are space-separated from each other, nodes are copied.
211    Value(XPathValue<Nav<'a>>),
212    /// A child element.
213    Element(Form<'a>),
214    /// A comment.
215    Comment(String),
216    /// A processing instruction: target, then data.
217    Pi(String, String),
218}
219
220impl fmt::Debug for AttrValue<'_> {
221    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222        match self {
223            Self::Text(text) => f.debug_tuple("Text").field(text).finish(),
224            Self::Value(value) => f
225                .debug_tuple("Value")
226                .field(&describe_items(value))
227                .finish(),
228        }
229    }
230}
231
232impl fmt::Debug for Content<'_> {
233    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234        match self {
235            Self::Text(text) => f.debug_tuple("Text").field(text).finish(),
236            Self::Value(value) => f
237                .debug_tuple("Value")
238                .field(&describe_items(value))
239                .finish(),
240            Self::Element(form) => f.debug_tuple("Element").field(form).finish(),
241            Self::Comment(text) => f.debug_tuple("Comment").field(text).finish(),
242            Self::Pi(target, data) => f.debug_tuple("Pi").field(target).field(data).finish(),
243        }
244    }
245}
246
247/// A result element, described but not yet built.
248///
249/// ```
250/// use bumpalo::Bump;
251/// use xsd_schema::compose::{AttrValue, Composer, Content, Form, Name};
252/// use xsd_schema::document::SerializeOptions;
253/// use xsd_schema::namespace::NameTable;
254///
255/// let arena = Bump::new();
256/// let names = NameTable::new();
257/// let c = Composer::new(&arena, &names);
258///
259/// let mut title = Form::new(Name::local("title"));
260/// title.push(Content::Text("One".to_string()));
261///
262/// let mut book = Form::new(Name::local("book"));
263/// book.attr(Name::local("id"), AttrValue::text("b1"));
264/// book.push(Content::Element(title));
265///
266/// let doc = c.build(book)?;
267/// assert_eq!(
268///     doc.to_xml(&SerializeOptions::default())?,
269///     r#"<book id="b1"><title>One</title></book>"#,
270/// );
271/// # Ok::<(), Box<dyn std::error::Error>>(())
272/// ```
273#[derive(Debug, Clone)]
274pub struct Form<'a> {
275    name: Name,
276    decls: Vec<(String, String)>,
277    attrs: Vec<(Name, AttrValue<'a>)>,
278    content: Vec<Content<'a>>,
279}
280
281impl<'a> Form<'a> {
282    /// An element with no declarations, attributes or content.
283    ///
284    /// ```
285    /// use xsd_schema::compose::{Form, Name};
286    ///
287    /// let form = Form::new(Name::local("result"));
288    /// assert_eq!(form.name().local_name(), "result");
289    /// assert!(form.content().is_empty());
290    /// ```
291    pub fn new(name: Name) -> Self {
292        Self {
293            name,
294            decls: Vec::new(),
295            attrs: Vec::new(),
296            content: Vec::new(),
297        }
298    }
299
300    /// Declares a namespace on this element, in scope for it and its
301    /// descendants.
302    ///
303    /// An empty prefix declares the default namespace; an empty prefix with an
304    /// empty URI undeclares it. The declaration shadows the composer's
305    /// namespace table for this subtree, and is dropped from the output only
306    /// when it is redundant.
307    ///
308    /// ```
309    /// use bumpalo::Bump;
310    /// use xsd_schema::compose::{Composer, Form, Name};
311    /// use xsd_schema::document::SerializeOptions;
312    /// use xsd_schema::namespace::NameTable;
313    ///
314    /// let arena = Bump::new();
315    /// let names = NameTable::new();
316    /// let c = Composer::new(&arena, &names);
317    ///
318    /// let mut form = Form::new(Name::prefixed("p", "root"));
319    /// form.declare("p", "urn:x");
320    ///
321    /// assert_eq!(
322    ///     c.build(form)?.to_xml(&SerializeOptions::default())?,
323    ///     r#"<p:root xmlns:p="urn:x"/>"#,
324    /// );
325    /// # Ok::<(), Box<dyn std::error::Error>>(())
326    /// ```
327    pub fn declare(&mut self, prefix: &str, uri: &str) -> &mut Self {
328        self.decls.push((prefix.to_string(), uri.to_string()));
329        self
330    }
331
332    /// Adds an attribute.
333    ///
334    /// Attributes are written in the order they are added. Two attributes with
335    /// the same expanded name are a duplicate, and the later one wins.
336    ///
337    /// ```
338    /// use xsd_schema::compose::{AttrValue, Form, Name};
339    ///
340    /// let mut form = Form::new(Name::local("book"));
341    /// form.attr(Name::local("id"), AttrValue::text("b1"))
342    ///     .attr(Name::local("year"), AttrValue::text(1999));
343    /// assert_eq!(form.attributes().len(), 2);
344    /// ```
345    pub fn attr(&mut self, name: Name, value: AttrValue<'a>) -> &mut Self {
346        self.attrs.push((name, value));
347        self
348    }
349
350    /// Appends one content item.
351    ///
352    /// ```
353    /// use xsd_schema::compose::{Content, Form, IntoContent, Name};
354    ///
355    /// let mut form = Form::new(Name::local("p"));
356    /// form.push(Content::Text("a".to_string()))
357    ///     .push("b".into_content());
358    /// assert_eq!(form.content().len(), 2);
359    /// ```
360    pub fn push(&mut self, content: Content<'a>) -> &mut Self {
361        self.content.push(content);
362        self
363    }
364
365    /// The element's name.
366    ///
367    /// ```
368    /// use xsd_schema::compose::{Form, Name};
369    ///
370    /// let form = Form::new(Name::prefixed("p", "root"));
371    /// assert_eq!(form.name().to_string(), "p:root");
372    /// ```
373    pub fn name(&self) -> &Name {
374        &self.name
375    }
376
377    /// The namespace declarations the author asked for, in order.
378    ///
379    /// ```
380    /// use xsd_schema::compose::{Form, Name};
381    ///
382    /// let mut form = Form::new(Name::local("root"));
383    /// form.declare("p", "urn:x");
384    /// assert_eq!(form.declarations(), [("p".to_string(), "urn:x".to_string())]);
385    /// ```
386    pub fn declarations(&self) -> &[(String, String)] {
387        &self.decls
388    }
389
390    /// The attributes, in order.
391    ///
392    /// ```
393    /// use xsd_schema::compose::{AttrValue, Form, Name};
394    ///
395    /// let mut form = Form::new(Name::local("book"));
396    /// form.attr(Name::local("id"), AttrValue::text("b1"));
397    /// assert_eq!(form.attributes()[0].0.local_name(), "id");
398    /// ```
399    pub fn attributes(&self) -> &[(Name, AttrValue<'a>)] {
400        &self.attrs
401    }
402
403    /// The content items, in order.
404    ///
405    /// ```
406    /// use xsd_schema::compose::{Content, Form, Name};
407    ///
408    /// let mut form = Form::new(Name::local("p"));
409    /// form.push(Content::Text("hi".to_string()));
410    /// assert!(matches!(form.content()[0], Content::Text(ref t) if t == "hi"));
411    /// ```
412    pub fn content(&self) -> &[Content<'a>] {
413        &self.content
414    }
415
416    /// Takes the form apart for emission.
417    #[allow(clippy::type_complexity)]
418    pub(super) fn into_parts(
419        self,
420    ) -> (
421        Name,
422        Vec<(String, String)>,
423        Vec<(Name, AttrValue<'a>)>,
424        Vec<Content<'a>>,
425    ) {
426        (self.name, self.decls, self.attrs, self.content)
427    }
428}
429
430// ── IntoContent ───────────────────────────────────────────────────────
431
432/// A Rust value that can become element content.
433///
434/// The conversion never serializes an XDM value into text: a navigator stays a
435/// node and is copied when the document is built, an atomic value stays atomic
436/// and takes part in the space-separation rule, and only `Display` values
437/// become literal text.
438///
439/// There is deliberately no implementation for `Result`: turning a failure
440/// into missing content is exactly the mistake this layer is built to prevent.
441/// An `Option` *is* implemented, because "nothing" is a legitimate answer —
442/// `None` contributes the empty sequence, which adds no content and does not
443/// break the adjacency of what surrounds it.
444///
445/// ```
446/// use bumpalo::Bump;
447/// use xsd_schema::compose::{Composer, Content, Form, IntoContent, Name};
448/// use xsd_schema::document::SerializeOptions;
449/// use xsd_schema::namespace::NameTable;
450///
451/// let arena = Bump::new();
452/// let names = NameTable::new();
453/// let c = Composer::new(&arena, &names);
454///
455/// let mut form = Form::new(Name::local("p"));
456/// form.push("plain".into_content())
457///     .push(7.into_content())
458///     .push(Option::<&str>::None.into_content());
459///
460/// assert_eq!(
461///     c.build(form)?.to_xml(&SerializeOptions::default())?,
462///     "<p>plain7</p>",
463/// );
464/// # Ok::<(), Box<dyn std::error::Error>>(())
465/// ```
466pub trait IntoContent<'a> {
467    /// Converts `self` into one content item.
468    fn into_content(self) -> Content<'a>;
469}
470
471impl<'a> IntoContent<'a> for Content<'a> {
472    fn into_content(self) -> Content<'a> {
473        self
474    }
475}
476
477impl<'a> IntoContent<'a> for Form<'a> {
478    fn into_content(self) -> Content<'a> {
479        Content::Element(self)
480    }
481}
482
483impl<'a> IntoContent<'a> for Value<'a> {
484    fn into_content(self) -> Content<'a> {
485        Content::Value(self.into_inner())
486    }
487}
488
489impl<'a> IntoContent<'a> for &Value<'a> {
490    fn into_content(self) -> Content<'a> {
491        Content::Value(self.inner().clone())
492    }
493}
494
495impl<'a> IntoContent<'a> for XPathValue<Nav<'a>> {
496    fn into_content(self) -> Content<'a> {
497        Content::Value(self)
498    }
499}
500
501impl<'a> IntoContent<'a> for XmlItem<Nav<'a>> {
502    fn into_content(self) -> Content<'a> {
503        Content::Value(XPathValue::from_item(self))
504    }
505}
506
507impl<'a> IntoContent<'a> for Nav<'a> {
508    fn into_content(self) -> Content<'a> {
509        Content::Value(XPathValue::from_node(self))
510    }
511}
512
513impl<'a> IntoContent<'a> for &Nav<'a> {
514    fn into_content(self) -> Content<'a> {
515        Content::Value(XPathValue::from_node(self.clone()))
516    }
517}
518
519impl<'a> IntoContent<'a> for XmlValue {
520    fn into_content(self) -> Content<'a> {
521        Content::Value(XPathValue::from_atomic(self))
522    }
523}
524
525impl<'a> IntoContent<'a> for &XmlValue {
526    fn into_content(self) -> Content<'a> {
527        Content::Value(XPathValue::from_atomic(self.clone()))
528    }
529}
530
531impl<'a> IntoContent<'a> for String {
532    fn into_content(self) -> Content<'a> {
533        Content::Text(self)
534    }
535}
536
537impl<'a> IntoContent<'a> for &str {
538    fn into_content(self) -> Content<'a> {
539        Content::Text(self.to_string())
540    }
541}
542
543impl<'a, T: IntoContent<'a>> IntoContent<'a> for Option<T> {
544    fn into_content(self) -> Content<'a> {
545        match self {
546            Some(value) => value.into_content(),
547            // The empty sequence: no content, and no effect on the
548            // surrounding atomic-value adjacency.
549            None => Content::Value(XPathValue::Empty),
550        }
551    }
552}
553
554/// `Display` scalars become literal text.
555///
556/// Rust's own formatting is used, not the XDM canonical lexical form: `1.0f64`
557/// is `1` in XDM and `1` here only by coincidence. Bind the value into an
558/// expression, or build an [`XmlValue`], when the canonical form matters.
559macro_rules! into_content_via_display {
560    ($($t:ty),* $(,)?) => {
561        $(
562            impl<'a> IntoContent<'a> for $t {
563                fn into_content(self) -> Content<'a> {
564                    Content::Text(self.to_string())
565                }
566            }
567        )*
568    };
569}
570
571into_content_via_display!(
572    bool, char, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64,
573);
574
575// A `Vec` of convertible values flattens into one content sequence, so a
576// sequence built up in Rust splices exactly like one an expression returned.
577
578impl<'a> IntoContent<'a> for Vec<Value<'a>> {
579    fn into_content(self) -> Content<'a> {
580        let mut items: Vec<XmlItem<Nav<'a>>> = Vec::with_capacity(self.len());
581        for value in self {
582            items.extend(value.into_inner().into_vec());
583        }
584        Content::Value(XPathValue::from_sequence(items))
585    }
586}
587
588impl<'a> IntoContent<'a> for Vec<XPathValue<Nav<'a>>> {
589    fn into_content(self) -> Content<'a> {
590        let mut items: Vec<XmlItem<Nav<'a>>> = Vec::with_capacity(self.len());
591        for value in self {
592            items.extend(value.into_vec());
593        }
594        Content::Value(XPathValue::from_sequence(items))
595    }
596}
597
598impl<'a> IntoContent<'a> for Vec<XmlItem<Nav<'a>>> {
599    fn into_content(self) -> Content<'a> {
600        Content::Value(XPathValue::from_sequence(self))
601    }
602}
603
604impl<'a> IntoContent<'a> for Vec<Nav<'a>> {
605    fn into_content(self) -> Content<'a> {
606        Content::Value(XPathValue::from_sequence(
607            self.into_iter().map(XmlItem::Node).collect(),
608        ))
609    }
610}
611
612impl<'a> IntoContent<'a> for Vec<&Nav<'a>> {
613    fn into_content(self) -> Content<'a> {
614        Content::Value(XPathValue::from_sequence(
615            self.into_iter().map(|n| XmlItem::Node(n.clone())).collect(),
616        ))
617    }
618}
619
620impl<'a> IntoContent<'a> for Vec<XmlValue> {
621    fn into_content(self) -> Content<'a> {
622        Content::Value(XPathValue::from_sequence(
623            self.into_iter().map(XmlItem::Atomic).collect(),
624        ))
625    }
626}
627
628impl<'a> IntoContent<'a> for Vec<&XmlValue> {
629    fn into_content(self) -> Content<'a> {
630        Content::Value(XPathValue::from_sequence(
631            self.into_iter()
632                .map(|v| XmlItem::Atomic(v.clone()))
633                .collect(),
634        ))
635    }
636}
637
638// ── Macro support ─────────────────────────────────────────────────────
639//
640// The two functions below exist so the macros stay `macro_rules!` and expand
641// to ordinary calls. They are not part of the documented surface.
642
643/// The name a string literal in `form!` stands for.
644///
645/// The literal is split at its first colon, and the halves are *not* checked
646/// here: the emitter checks every name it writes, so a literal that is not an
647/// `NCName` or `prefix:NCName` is [`ComposeError::InvalidName`] at build time,
648/// where every other name rule is decided too.
649#[doc(hidden)]
650pub fn __name_from_literal(text: &str) -> Name {
651    match text.split_once(':') {
652        Some((prefix, local)) => Name::prefixed(prefix, local),
653        None => Name::local(text),
654    }
655}
656
657/// The content `form!`'s `@{…}` makes: a Rust value formatted with `Display`.
658#[doc(hidden)]
659pub fn __display_text<'a>(value: impl fmt::Display) -> Content<'a> {
660    Content::Text(value.to_string())
661}
662
663#[cfg(test)]
664mod tests {
665    use super::*;
666
667    #[test]
668    fn a_literal_name_splits_at_its_first_colon() {
669        assert_eq!(__name_from_literal("bid-count"), Name::local("bid-count"));
670        assert_eq!(__name_from_literal("p:bid"), Name::prefixed("p", "bid"));
671        // Unchecked here; the emitter refuses it.
672        assert_eq!(__name_from_literal("a:b:c"), Name::prefixed("a", "b:c"));
673    }
674
675    #[test]
676    fn a_display_value_becomes_text() {
677        let content: Content<'_> = __display_text(1.5f64);
678        assert!(matches!(content, Content::Text(ref t) if t == "1.5"));
679    }
680
681    #[test]
682    fn parse_accepts_local_and_prefixed_names() {
683        assert_eq!(Name::parse("item").unwrap(), Name::local("item"));
684        assert_eq!(Name::parse("p:item").unwrap(), Name::prefixed("p", "item"));
685        assert_eq!(Name::parse("bid-count").unwrap().local_name(), "bid-count");
686    }
687
688    #[test]
689    fn parse_refuses_non_names() {
690        for bad in ["", ":x", "x:", "a:b:c", "1a", "a b", "a/b"] {
691            assert!(
692                matches!(Name::parse(bad), Err(ComposeError::InvalidName(_))),
693                "{bad:?} should not parse"
694            );
695        }
696    }
697
698    #[test]
699    fn display_spells_the_qualified_name() {
700        assert_eq!(Name::local("a").to_string(), "a");
701        assert_eq!(Name::prefixed("p", "a").to_string(), "p:a");
702    }
703
704    #[test]
705    fn builders_are_chainable_and_ordered() {
706        let mut form = Form::new(Name::local("e"));
707        form.declare("p", "urn:x")
708            .attr(Name::local("k"), AttrValue::text("v"))
709            .push(Content::Text("t".to_string()));
710
711        assert_eq!(
712            form.declarations(),
713            [("p".to_string(), "urn:x".to_string())]
714        );
715        assert_eq!(form.attributes().len(), 1);
716        assert_eq!(form.content().len(), 1);
717    }
718
719    #[test]
720    fn display_impls_become_text() {
721        for content in [
722            true.into_content(),
723            'c'.into_content(),
724            1i8.into_content(),
725            2i16.into_content(),
726            3i32.into_content(),
727            4i64.into_content(),
728            5i128.into_content(),
729            6isize.into_content(),
730            7u8.into_content(),
731            8u16.into_content(),
732            9u32.into_content(),
733            10u64.into_content(),
734            11u128.into_content(),
735            12usize.into_content(),
736            1.5f32.into_content(),
737            2.5f64.into_content(),
738            "s".into_content(),
739            String::from("o").into_content(),
740        ] {
741            assert!(matches!(content, Content::Text(_)));
742        }
743    }
744
745    #[test]
746    fn xdm_impls_stay_sequences() {
747        let value = XmlValue::string("a");
748        for content in [
749            XPathValue::<Nav<'_>>::string("x").into_content(),
750            XmlItem::<Nav<'_>>::Atomic(XmlValue::string("y")).into_content(),
751            value.clone().into_content(),
752            (&value).into_content(),
753            vec![XmlValue::string("a"), XmlValue::string("b")].into_content(),
754            vec![XmlItem::<Nav<'_>>::Atomic(XmlValue::string("c"))].into_content(),
755            vec![XPathValue::<Nav<'_>>::string("d")].into_content(),
756            vec![&value].into_content(),
757            Some(XmlValue::string("e")).into_content(),
758            Option::<XmlValue>::None.into_content(),
759        ] {
760            assert!(matches!(content, Content::Value(_)));
761        }
762    }
763
764    #[test]
765    fn a_vec_of_values_flattens_into_one_sequence() {
766        let a: Value<'_> = XPathValue::from_sequence(vec![
767            XmlItem::Atomic(XmlValue::string("1")),
768            XmlItem::Atomic(XmlValue::string("2")),
769        ])
770        .into();
771        let b: Value<'_> = XPathValue::string("3").into();
772
773        match vec![a, b].into_content() {
774            Content::Value(v) => assert_eq!(v.len(), 3),
775            other => panic!("expected a sequence, got {other:?}"),
776        }
777    }
778
779    #[test]
780    fn none_contributes_the_empty_sequence() {
781        match Option::<&str>::None.into_content() {
782            Content::Value(v) => assert!(v.is_empty()),
783            other => panic!("expected the empty sequence, got {other:?}"),
784        }
785    }
786
787    #[test]
788    fn a_form_is_content() {
789        let form = Form::new(Name::local("child"));
790        assert!(matches!(form.into_content(), Content::Element(_)));
791    }
792}