xsd_schema/compose/macros.rs
1//! The two macros: [`xpath!`](crate::xpath!) and [`form!`](crate::form!).
2//!
3//! Everything in this module is `macro_rules!`, and every expansion goes
4//! through `$crate::compose::…` paths, so the macros need nothing that a host
5//! crate cannot reach itself.
6//!
7//! # Importing them
8//!
9//! Both macros live at the crate root:
10//!
11//! ```
12//! use xsd_schema::{form, xpath};
13//! ```
14//!
15//! That is the canonical import, and the one every example here uses. The
16//! macros are *not* re-exported from `compose`: `compose::form` is already the
17//! module holding [`Form`](crate::compose::Form), and `xsd_schema::xpath` is
18//! already the XPath engine's module, so re-exporting the macros there would
19//! put two different things behind one path for no gain. Names in the macro
20//! namespace and names in the type namespace never collide, which is why
21//! `use xsd_schema::xpath;` brings in both the module and the macro and both
22//! keep working.
23//!
24//! # What they expand to
25//!
26//! [`xpath!`](crate::xpath!) is one call to the composer's cached evaluator:
27//! the expression text and the variable names are `'static` literals, so a
28//! call site inside a loop compiles its expression once and then only
29//! evaluates.
30//!
31//! [`form!`](crate::form!) is a token-tree muncher over the form grammar; it
32//! builds an owned [`Form`](crate::compose::Form) eagerly, evaluating every
33//! escape exactly once, left to right, as the form is constructed. No closure
34//! and no iterator survives into the form, which is why a `?` inside an
35//! escape returns from the enclosing function and why the finished form can
36//! be stored, returned and spliced later.
37//!
38//! In a form, a prefixed name is written `p::local`: one colon after the
39//! element name is always the attribute marker, so `(p:title "One")` is the
40//! element `p` with `title="One"`, and `(p::title "One")` is the element
41//! `p:title`.
42//!
43//! # Expansion depth
44//!
45//! Both the nesting depth of a form and the number of items in one form cost
46//! macro expansion steps, which `recursion_limit` (128 by default) bounds. A
47//! form nested more than about thirty levels deep, or one with more than about
48//! a hundred items, needs `#![recursion_limit = "256"]` in the consuming
49//! crate. Neither is close for the compositions this layer is built for.
50
51/// Evaluates an XPath expression on a [`Composer`](crate::compose::Composer).
52///
53/// ```text
54/// xpath!(c, "expr") // no context item, no variables
55/// xpath!(c, "expr", node) // a context item
56/// xpath!(c, "expr", i = &item, b = &bids) // the external variables $i and $b
57/// xpath!(c, "expr", items, i = &item) // a context item, then variables
58/// ```
59///
60/// The result is `Result<`[`Value`](crate::compose::Value)`,
61/// `[`ComposeError`](crate::compose::ComposeError)`>`, so a call site ends in
62/// `?` and then asks the value for what it wants — `nodes`, `atomics`,
63/// `boolean`, `string`, `number`, `key`.
64///
65/// # The argument order, and why it is a rule
66///
67/// The expression is always a string literal. A context item, when there is
68/// one, is always the **third** argument, directly after it; everything after
69/// that is a `name = value` binding, and an optional trailing comma is
70/// accepted everywhere.
71///
72/// `name = value` is also Rust's assignment expression, so the bindings-only
73/// shape is matched *before* the context shape: `xpath!(c, "$node", node =
74/// value)` binds `$node` and leaves the context item empty. A named binding
75/// never implies a context item, and `xpath!(c, "expr", node)` never binds
76/// anything. A context item after a binding, or two of them, is a compile
77/// error naming the expected order; for preparatory work, use a block that
78/// ends in the node — `xpath!(c, "expr", { prepare(); doc.root() })`.
79///
80/// # What may be a context item
81///
82/// [`Nav`](crate::compose::Nav), `&Nav`, [`Doc`](crate::compose::Doc) or
83/// `&Doc` — anything [`IntoContextNode`](crate::compose::IntoContextNode)
84/// accepts. A document supplies its document node, a borrowed navigator is
85/// cloned. Binding values are anything
86/// [`IntoXPathValue`](crate::compose::IntoXPathValue) accepts, which is every
87/// atomic Rust scalar, every XDM value, a node, a document, a sequence, and
88/// `Option` of any of those. Variable names are Rust identifiers; a prefixed
89/// external variable needs
90/// [`Composer::eval`](crate::compose::Composer::eval) directly.
91///
92/// # Evaluation
93///
94/// Each supplied expression is evaluated exactly once, in the order written:
95/// the composer, then the context item, then the binding values from left to
96/// right. Every one of them appears exactly once in the expansion, with the
97/// composer and the context item held in temporaries of the macro's own, so
98/// no conversion can repeat an evaluation or reorder a side effect.
99///
100/// # Examples
101///
102/// All four call forms:
103///
104/// ```
105/// use bumpalo::Bump;
106/// use xsd_schema::compose::{ComposeError, Composer};
107/// use xsd_schema::namespace::NameTable;
108/// use xsd_schema::xpath;
109///
110/// let arena = Bump::new();
111/// let names = NameTable::new();
112/// let c = Composer::new(&arena, &names);
113/// let items = c.load_str("<items><item n='1'/><item n='2'/></items>")?;
114///
115/// assert_eq!(xpath!(c, "1 + 1")?.string()?, "2");
116/// assert_eq!(xpath!(c, "count(//item)", items)?.string()?, "2");
117/// assert_eq!(xpath!(c, "$n * 2", n = 21)?.string()?, "42");
118/// assert_eq!(
119/// xpath!(c, "count(//item[@n = $n])", items, n = "2")?.string()?,
120/// "1",
121/// );
122/// # Ok::<(), ComposeError>(())
123/// ```
124///
125/// A binding is not a context item:
126///
127/// ```
128/// use bumpalo::Bump;
129/// use xsd_schema::compose::{ComposeError, Composer};
130/// use xsd_schema::namespace::NameTable;
131/// use xsd_schema::xpath;
132///
133/// let arena = Bump::new();
134/// let names = NameTable::new();
135/// let c = Composer::new(&arena, &names);
136/// let doc = c.load_str("<items><item/></items>")?;
137/// let node = doc.document_element().expect("a document element");
138///
139/// // `node = …` binds $node …
140/// assert_eq!(xpath!(c, "name($node)", node = &node)?.string()?, "items");
141/// // … and the same value as the context item needs no name.
142/// assert_eq!(xpath!(c, "name()", &node)?.string()?, "items");
143/// # Ok::<(), ComposeError>(())
144/// ```
145///
146/// Inside a pipeline closure, where most real call sites are:
147///
148/// ```
149/// use xsd_schema::compose::{pipe, ComposeError, Composer};
150/// use xsd_schema::document::SerializeOptions;
151/// use xsd_schema::namespace::NameTable;
152/// use xsd_schema::{form, xpath};
153/// use bumpalo::Bump;
154///
155/// let arena = Bump::new();
156/// let names = NameTable::new();
157/// let c = Composer::new(&arena, &names);
158/// let stock = c.load_str("<stock><part qty='7'>bolt</part><part qty='0'>nut</part></stock>")?;
159///
160/// let rows = pipe::nodes(xpath!(c, "//part", stock)?)
161/// .try_filter(|p| xpath!(c, "@qty > 0", p)?.boolean())
162/// .try_map(|p| Ok(form! { (part ^{ xpath!(c, "string()", &p)? }) }));
163///
164/// assert_eq!(
165/// c.build(form! { (in_stock ..?^{ rows }) })?.to_xml(&SerializeOptions::default())?,
166/// "<in_stock><part>bolt</part></in_stock>",
167/// );
168/// # Ok::<(), ComposeError>(())
169/// ```
170///
171/// A context item after a binding does not compile:
172///
173/// ```compile_fail
174/// use bumpalo::Bump;
175/// use xsd_schema::compose::{ComposeError, Composer};
176/// use xsd_schema::namespace::NameTable;
177/// use xsd_schema::xpath;
178///
179/// let arena = Bump::new();
180/// let names = NameTable::new();
181/// let c = Composer::new(&arena, &names);
182/// let doc = c.load_str("<a><b/></a>")?;
183/// let node = doc.root();
184///
185/// // The context item belongs before the bindings.
186/// let wrong = xpath!(c, "name($x)", x = &node, node)?;
187/// # Ok::<(), ComposeError>(())
188/// ```
189///
190/// Neither does a second context item:
191///
192/// ```compile_fail
193/// use bumpalo::Bump;
194/// use xsd_schema::compose::{ComposeError, Composer};
195/// use xsd_schema::namespace::NameTable;
196/// use xsd_schema::xpath;
197///
198/// let arena = Bump::new();
199/// let names = NameTable::new();
200/// let c = Composer::new(&arena, &names);
201/// let doc = c.load_str("<a><b/></a>")?;
202///
203/// // One context item only; bind the other value by name.
204/// let wrong = xpath!(c, "name()", doc.root(), doc.root())?;
205/// # Ok::<(), ComposeError>(())
206/// ```
207#[macro_export]
208macro_rules! xpath {
209 // The plain form and the bindings. This arm comes first so that
210 // `name = value` is always a binding and never Rust's assignment
211 // expression in the context-item position.
212 ($c:expr, $src:literal $(, $name:ident = $val:expr)* $(,)?) => {{
213 // Borrowed once, so the composer expression cannot run twice; the
214 // method call derefs whatever `&$c` turns out to be, which is how a
215 // `Composer`, a `&Composer` and a guard all work here.
216 #[allow(clippy::needless_borrow)]
217 let __xpath_composer = &$c;
218 __xpath_composer.eval(
219 $src,
220 &[$(::core::stringify!($name)),*],
221 ::core::option::Option::None,
222 ::std::vec![$((
223 ::core::stringify!($name),
224 $crate::compose::IntoXPathValue::into_xpath_value($val),
225 )),*],
226 )
227 }};
228
229 // A context item, then bindings.
230 ($c:expr, $src:literal, $ctx:expr $(, $name:ident = $val:expr)* $(,)?) => {{
231 // Borrowed once, so the composer expression cannot run twice; the
232 // method call derefs whatever `&$c` turns out to be, which is how a
233 // `Composer`, a `&Composer` and a guard all work here.
234 #[allow(clippy::needless_borrow)]
235 let __xpath_composer = &$c;
236 let __xpath_context = $crate::compose::IntoContextNode::into_context_node($ctx);
237 __xpath_composer.eval(
238 $src,
239 &[$(::core::stringify!($name)),*],
240 ::core::option::Option::Some(__xpath_context),
241 ::std::vec![$((
242 ::core::stringify!($name),
243 $crate::compose::IntoXPathValue::into_xpath_value($val),
244 )),*],
245 )
246 }};
247
248 // ── Diagnostics ───────────────────────────────────────────────────
249 //
250 // These arms match the two orders that read as if they should work. They
251 // come after the two real arms, so they only ever see calls the real arms
252 // refused.
253
254 // A binding first and then something that is not another binding: the
255 // context item, written too late. Matched with one binding and a token
256 // muncher rather than a repetition followed by `$ctx:expr`, because two
257 // fragment options at one position are a `macro_rules!` local ambiguity
258 // and would replace this message with one about the matcher.
259 ($c:expr, $src:literal, $name:ident = $val:expr, $($rest:tt)*) => {
260 ::core::compile_error!(
261 "xpath!: the context item comes before the `name = value` bindings — \
262 write xpath!(c, \"expr\", node, name = value)"
263 )
264 };
265
266 ($c:expr, $src:literal, $ctx:expr, $second:expr $(, $name:ident = $val:expr)* $(,)?) => {
267 ::core::compile_error!(
268 "xpath!: only one context item is allowed, and it is the third argument — \
269 write xpath!(c, \"expr\", node, name = value), and bind any further value by name"
270 )
271 };
272
273 ($($rest:tt)*) => {
274 ::core::compile_error!(
275 "xpath!: expected xpath!(composer, \"expr\") with an optional context item as the \
276 third argument and `name = value` bindings after it"
277 )
278 };
279}
280
281/// Describes a result element: a [`Form`](crate::compose::Form), built eagerly
282/// and emitted later by [`Composer::build`](crate::compose::Composer::build).
283///
284/// ```text
285/// form ::= '(' name item* ')'
286/// name ::= ident | ident '::' ident | string-literal
287/// -- one colon after the name is an attribute
288/// item ::= ':' attr-name attr-value -- an attribute
289/// | ':' 'xmlns' string-literal -- a default namespace declaration
290/// | ':' 'xmlns' '::' ident string-literal
291/// | ':' 'xmlns' ':' ident string-literal
292/// | string-literal -- literal text
293/// | '@' '{' rust-expr '}' -- text from a Display value
294/// | '^' '{' rust-expr '}' -- one content value
295/// | '..' '^' '{' rust-expr '}' -- a spliced sequence
296/// | '..' '?' '^' '{' rust-expr '}' -- a spliced fallible sequence
297/// | '#' 'comment' string-literal
298/// | '#' 'pi' string-literal string-literal
299/// | form -- a child element
300/// attr-name ::= ident | ident '::' ident | ident ':' ident | string-literal
301/// attr-value::= string-literal | '@' '{' rust-expr '}' | '^' '{' rust-expr '}'
302/// ```
303///
304/// # The escapes
305///
306/// | Written | Means |
307/// |---|---|
308/// | `"text"` | literal text; two adjacent texts concatenate with nothing between them |
309/// | `@{ e }` | `e` formatted with `Display`, captured now — Rust's formatting, not XDM's canonical lexical form |
310/// | `^{ e }` | one content value: anything [`IntoContent`](crate::compose::IntoContent) accepts — a query result, a node, an atomic value, a nested [`Form`](crate::compose::Form), an `Option` of any of those |
311/// | `..^{ e }` | an `IntoIterator` of those, spliced in order; an empty iterator adds nothing |
312/// | `..?^{ e }` | an `IntoIterator<Item = Result<T, ComposeError>>`; the first failure returns from the enclosing function |
313/// | `:name "v"`, `:name @{ e }`, `:name ^{ e }` | an attribute — literal, `Display`, or a sequence atomized and joined with single spaces |
314///
315/// `Result` deliberately has no [`IntoContent`](crate::compose::IntoContent)
316/// implementation, so `..^{}` cannot quietly turn a failure into missing
317/// content; `..?^{}` is the spelling that propagates it.
318///
319/// # Write the invocation with braces
320///
321/// **`form! { ( … ) }` is the spelling to use**, and it is what every example
322/// here and in the guide uses. All three delimiters expand identically —
323/// `macro_rules!` does not care which one an invocation carries — but a form's
324/// tokens also happen to parse as a Rust expression: `(a ^{ x } (b))` is a
325/// bit-xor and a call. rustfmt reads a parenthesized invocation as arguments
326/// and reflows them into that shape, so `form!((a ^{ x } (b)))` comes back as
327/// `form!((a ^ { x }(b)))` and the element structure stops being visible. A
328/// brace-delimited invocation is left alone, which is all it takes: the form
329/// keeps the layout you gave it, with no `#[rustfmt::skip]` anywhere.
330///
331/// # Names
332///
333/// Prefixes are resolved when the document is built — against the form's own
334/// `:xmlns` declarations, innermost first, then the composer's
335/// [`with_namespace`](crate::compose::Composer::with_namespace) table.
336/// An unprefixed element name takes the default element namespace; an
337/// unprefixed attribute is in no namespace. `xml` is always bound.
338///
339/// **A prefixed element name is written with two colons** — `(p::title
340/// "One")` — or as a string literal — `("p:title" "One")`, which is also how
341/// a name that is not a Rust identifier is written: `("bid-count" "7")`.
342///
343/// One colon is the attribute marker, always. Rust's tokens carry no
344/// whitespace, so `(book :id "b1")` and `(p:title "One")` are the same shape,
345/// and rather than guess, the macro reads a single colon after the element
346/// name as the start of an attribute in every case: `(p:title "One")` and
347/// `(p :title "One")` are both the element `p` with `title="One"`, and
348/// `(p:root (child))` — where no attribute value follows — does not compile,
349/// with a message naming the `p::root` spelling. Nothing is ever reinterpreted
350/// silently.
351///
352/// After that marker the ambiguity is gone, so an attribute name and a
353/// declaration take either spelling: `:xml::lang "en"` and `:xml:lang "en"`
354/// are the same attribute, `:xmlns::p "urn:x"` and `:xmlns:p "urn:x"` the same
355/// declaration.
356///
357/// A literal name that is not an `NCName` or `prefix:NCName` is
358/// [`ComposeError::InvalidName`](crate::compose::ComposeError::InvalidName)
359/// at build time, and a prefix nothing binds is
360/// [`ComposeError::UnboundPrefix`](crate::compose::ComposeError::UnboundPrefix).
361///
362/// # Order
363///
364/// Attributes and declarations belong before content. The macro does not
365/// enforce that — a [`Form`](crate::compose::Form) keeps its attributes and
366/// its content apart — but the emitter does enforce it for a *spliced*
367/// attribute node, which is
368/// [`ComposeError::Copy`](crate::compose::ComposeError::Copy) when content has
369/// already been written.
370///
371/// Items and escapes are processed left to right, each Rust expression
372/// evaluated exactly once, as the form is built.
373///
374/// # Expansion depth
375///
376/// The macro is a token-tree muncher, so both the nesting depth of a form and
377/// the number of items in one form cost macro expansion steps, which
378/// `recursion_limit` (128 by default) bounds. A form nested more than about
379/// thirty levels deep, or one carrying more than about a hundred items, needs
380/// `#![recursion_limit = "256"]` in the crate that writes it. The compositions
381/// this layer is built for are nowhere near either bound.
382///
383/// # Examples
384///
385/// Every escape at once:
386///
387/// ```
388/// use bumpalo::Bump;
389/// use xsd_schema::compose::{ComposeError, Composer};
390/// use xsd_schema::document::SerializeOptions;
391/// use xsd_schema::namespace::NameTable;
392/// use xsd_schema::{form, xpath};
393///
394/// let arena = Bump::new();
395/// let names = NameTable::new();
396/// let c = Composer::new(&arena, &names);
397/// let stock = c.load_str("<stock><part>bolt</part><part>nut</part></stock>")?;
398///
399/// let count = 4;
400/// let parts = xpath!(c, "//part", stock)?;
401/// let extra = ["washer", "screw"];
402///
403/// let doc = c.build(form! {
404/// (inventory
405/// :kind "hardware" // a literal attribute
406/// :count @{ count } // an attribute from a Rust value
407/// :first ^{ xpath!(c, "//part[1]", stock)? } // an attribute from a query
408/// "in stock: " // literal text
409/// @{ count } // text from a Rust value
410/// ^{ parts } // two copied elements
411/// ..^{ extra.iter().map(|n| form! { (part ^{ *n }) }) } // a spliced sequence
412/// (note :kind "generated" "written by form!") // a child element
413/// #comment " counted " // a comment
414/// #pi "sort" "by name" // a processing instruction
415/// )
416/// })?;
417///
418/// assert_eq!(
419/// doc.to_xml(&SerializeOptions::default())?,
420/// concat!(
421/// r#"<inventory kind="hardware" count="4" first="bolt">"#,
422/// "in stock: 4<part>bolt</part><part>nut</part>",
423/// "<part>washer</part><part>screw</part>",
424/// r#"<note kind="generated">written by form!</note>"#,
425/// "<!-- counted --><?sort by name?></inventory>",
426/// ),
427/// );
428/// # Ok::<(), ComposeError>(())
429/// ```
430///
431/// Namespaces, declared on the form or by the composer:
432///
433/// ```
434/// use bumpalo::Bump;
435/// use xsd_schema::compose::{ComposeError, Composer};
436/// use xsd_schema::document::SerializeOptions;
437/// use xsd_schema::form;
438/// use xsd_schema::namespace::NameTable;
439///
440/// let arena = Bump::new();
441/// let names = NameTable::new();
442/// let c = Composer::new(&arena, &names).with_namespace("q", "urn:q");
443///
444/// let doc = c.build(form! {
445/// (e::root :xmlns::e "urn:e" :xml::lang "en"
446/// (q::child :xmlns "urn:d" (leaf "text"))
447/// )
448/// })?;
449///
450/// assert_eq!(
451/// doc.to_xml(&SerializeOptions::default())?,
452/// concat!(
453/// r#"<e:root xmlns:e="urn:e" xml:lang="en">"#,
454/// r#"<q:child xmlns="urn:d" xmlns:q="urn:q"><leaf>text</leaf></q:child>"#,
455/// "</e:root>",
456/// ),
457/// );
458/// # Ok::<(), ComposeError>(())
459/// ```
460///
461/// A fallible splice, with the `?` returning from the enclosing function:
462///
463/// ```
464/// use bumpalo::Bump;
465/// use xsd_schema::compose::{pipe, ComposeError, Composer, Doc};
466/// use xsd_schema::document::SerializeOptions;
467/// use xsd_schema::namespace::NameTable;
468/// use xsd_schema::{form, xpath};
469///
470/// fn loud<'a>(c: &Composer<'a>, stock: Doc<'a>) -> Result<Doc<'a>, ComposeError> {
471/// let rows = pipe::nodes(xpath!(c, "//part", stock)?)
472/// .try_map(|p| Ok(form! { (part ^{ xpath!(c, "upper-case(string())", &p)? }) }));
473/// // A failure anywhere in `rows` leaves this function instead of
474/// // becoming missing content, and `build` is never reached.
475/// c.build(form! { (parts ..?^{ rows }) })
476/// }
477///
478/// let arena = Bump::new();
479/// let names = NameTable::new();
480/// let c = Composer::new(&arena, &names);
481/// let stock = c.load_str("<stock><part>bolt</part></stock>")?;
482///
483/// assert_eq!(
484/// loud(&c, stock)?.to_xml(&SerializeOptions::default())?,
485/// "<parts><part>BOLT</part></parts>",
486/// );
487/// # Ok::<(), ComposeError>(())
488/// ```
489///
490/// A single colon after the element name is an attribute, so a prefixed
491/// element name written with one does not compile:
492///
493/// ```compile_fail
494/// use bumpalo::Bump;
495/// use xsd_schema::compose::{ComposeError, Composer};
496/// use xsd_schema::form;
497/// use xsd_schema::namespace::NameTable;
498///
499/// let arena = Bump::new();
500/// let names = NameTable::new();
501/// let c = Composer::new(&arena, &names).with_namespace("p", "urn:p");
502///
503/// // `:root` starts an attribute, and `(child)` is not an attribute value.
504/// // Write form! { (p::root (child)) } for the element `p:root`.
505/// let refused = form! { (p:root (child)) };
506/// # Ok::<(), ComposeError>(())
507/// ```
508///
509/// `..^{}` refuses an iterator of results:
510///
511/// ```compile_fail
512/// use bumpalo::Bump;
513/// use xsd_schema::compose::{ComposeError, Composer};
514/// use xsd_schema::form;
515/// use xsd_schema::namespace::NameTable;
516///
517/// let arena = Bump::new();
518/// let names = NameTable::new();
519/// let c = Composer::new(&arena, &names);
520///
521/// let rows: Vec<Result<&str, ComposeError>> = vec![Ok("a")];
522/// // `Result` is not content: write `..?^{ rows }` to propagate the failure.
523/// let refused = form! { (result ..^{ rows }) };
524/// # Ok::<(), ComposeError>(())
525/// ```
526///
527/// … and `..?^{}` needs a function that can carry the failure:
528///
529/// ```compile_fail
530/// use xsd_schema::compose::ComposeError;
531/// use xsd_schema::form;
532///
533/// fn how_many() -> usize {
534/// let rows: Vec<Result<&'static str, ComposeError>> = vec![Ok("a")];
535/// // There is nothing here for the `?` to return to.
536/// let refused = form! { (result ..?^{ rows }) };
537/// refused.content().len()
538/// }
539/// ```
540#[macro_export]
541macro_rules! form {
542 // ── The element name ──────────────────────────────────────────────
543 //
544 // `p::local` is the prefixed spelling, and it is decided first. A single
545 // colon is always the attribute marker: `(book :id "b1")` and
546 // `(p:title "One")` are the same token shape, so the arms below look ahead
547 // for a complete attribute — a name and a value — and hand everything
548 // else to the plain-name arm, where an attribute without a value is
549 // refused by name.
550
551 (($prefix:ident :: $local:ident $($items:tt)*)) => {
552 $crate::__form_build!(
553 $crate::compose::Name::prefixed(
554 ::core::stringify!($prefix),
555 ::core::stringify!($local),
556 ),
557 $($items)*
558 )
559 };
560
561 // An unprefixed name whose first item is an attribute with a plain name.
562 (($name:ident : $a:ident $v:literal $($items:tt)*)) => {
563 $crate::__form_build!(
564 $crate::compose::Name::local(::core::stringify!($name)),
565 : $a $v $($items)*
566 )
567 };
568 (($name:ident : $a:ident @ { $e:expr } $($items:tt)*)) => {
569 $crate::__form_build!(
570 $crate::compose::Name::local(::core::stringify!($name)),
571 : $a @ { $e } $($items)*
572 )
573 };
574 (($name:ident : $a:ident ^ { $e:expr } $($items:tt)*)) => {
575 $crate::__form_build!(
576 $crate::compose::Name::local(::core::stringify!($name)),
577 : $a ^ { $e } $($items)*
578 )
579 };
580
581 // … or with a prefixed one, in either spelling (`:xml::lang`, `:xml:lang`).
582 (($name:ident : $ap:ident :: $al:ident $v:literal $($items:tt)*)) => {
583 $crate::__form_build!(
584 $crate::compose::Name::local(::core::stringify!($name)),
585 : $ap :: $al $v $($items)*
586 )
587 };
588 (($name:ident : $ap:ident :: $al:ident @ { $e:expr } $($items:tt)*)) => {
589 $crate::__form_build!(
590 $crate::compose::Name::local(::core::stringify!($name)),
591 : $ap :: $al @ { $e } $($items)*
592 )
593 };
594 (($name:ident : $ap:ident :: $al:ident ^ { $e:expr } $($items:tt)*)) => {
595 $crate::__form_build!(
596 $crate::compose::Name::local(::core::stringify!($name)),
597 : $ap :: $al ^ { $e } $($items)*
598 )
599 };
600 (($name:ident : $ap:ident : $al:ident $v:literal $($items:tt)*)) => {
601 $crate::__form_build!(
602 $crate::compose::Name::local(::core::stringify!($name)),
603 : $ap : $al $v $($items)*
604 )
605 };
606 (($name:ident : $ap:ident : $al:ident @ { $e:expr } $($items:tt)*)) => {
607 $crate::__form_build!(
608 $crate::compose::Name::local(::core::stringify!($name)),
609 : $ap : $al @ { $e } $($items)*
610 )
611 };
612 (($name:ident : $ap:ident : $al:ident ^ { $e:expr } $($items:tt)*)) => {
613 $crate::__form_build!(
614 $crate::compose::Name::local(::core::stringify!($name)),
615 : $ap : $al ^ { $e } $($items)*
616 )
617 };
618
619 // There is deliberately no `ident : ident` element-name arm: a single
620 // colon after the name always starts an attribute, so `(p:root (child))`
621 // reaches the attribute arms and is refused there by name, rather than
622 // quietly meaning something else than `(p::root (child))`.
623
624 // A name that is not a Rust identifier.
625 (($name:literal $($items:tt)*)) => {
626 $crate::__form_build!($crate::compose::__name_from_literal($name), $($items)*)
627 };
628
629 // The plain case.
630 (($name:ident $($items:tt)*)) => {
631 $crate::__form_build!(
632 $crate::compose::Name::local(::core::stringify!($name)),
633 $($items)*
634 )
635 };
636
637 ($($rest:tt)*) => {
638 ::core::compile_error!(
639 "form!: expected one parenthesized form — form! { (name item…) }, whose name \
640 is `local`, `prefix::local` or a string literal"
641 )
642 };
643}
644
645/// Builds the form once its name is known.
646#[doc(hidden)]
647#[macro_export]
648macro_rules! __form_build {
649 ($name:expr, $($items:tt)*) => {{
650 let mut __form = $crate::compose::Form::new($name);
651 $crate::__form_items!(__form, $($items)*);
652 __form
653 }};
654}
655
656/// Munches a form's items, one statement at a time, left to right.
657#[doc(hidden)]
658#[macro_export]
659macro_rules! __form_items {
660 ($f:ident) => {};
661 ($f:ident,) => {};
662
663 // ── Namespace declarations ────────────────────────────────────────
664 //
665 // Before the attribute arms, because `xmlns` is an identifier like any
666 // other.
667
668 ($f:ident, : xmlns :: $prefix:ident $uri:literal $($rest:tt)*) => {
669 $f.declare(::core::stringify!($prefix), $uri);
670 $crate::__form_items!($f, $($rest)*);
671 };
672 ($f:ident, : xmlns : $prefix:ident $uri:literal $($rest:tt)*) => {
673 $f.declare(::core::stringify!($prefix), $uri);
674 $crate::__form_items!($f, $($rest)*);
675 };
676 ($f:ident, : xmlns $uri:literal $($rest:tt)*) => {
677 $f.declare("", $uri);
678 $crate::__form_items!($f, $($rest)*);
679 };
680 ($f:ident, : xmlns $($rest:tt)*) => {
681 ::core::compile_error!(
682 "form!: a namespace declaration takes a string-literal URI — \
683 :xmlns \"urn:x\" or :xmlns::p \"urn:x\""
684 )
685 };
686
687 // ── Attributes ───────────────────────────────────────────────────
688
689 ($f:ident, : $prefix:ident :: $local:ident $($rest:tt)*) => {
690 $crate::__form_attr!(
691 $f,
692 $crate::compose::Name::prefixed(
693 ::core::stringify!($prefix),
694 ::core::stringify!($local),
695 ),
696 $($rest)*
697 );
698 };
699 ($f:ident, : $prefix:ident : $local:ident $($rest:tt)*) => {
700 $crate::__form_attr!(
701 $f,
702 $crate::compose::Name::prefixed(
703 ::core::stringify!($prefix),
704 ::core::stringify!($local),
705 ),
706 $($rest)*
707 );
708 };
709 ($f:ident, : $name:ident $($rest:tt)*) => {
710 $crate::__form_attr!(
711 $f,
712 $crate::compose::Name::local(::core::stringify!($name)),
713 $($rest)*
714 );
715 };
716 ($f:ident, : $name:literal $($rest:tt)*) => {
717 $crate::__form_attr!($f, $crate::compose::__name_from_literal($name), $($rest)*);
718 };
719 ($f:ident, : $($rest:tt)*) => {
720 ::core::compile_error!(
721 "form!: an attribute name is `local`, `prefix::local` or a string literal — \
722 :id \"b1\", :xml::lang \"en\", :\"bid-count\" @{ n }"
723 )
724 };
725
726 // ── Content ──────────────────────────────────────────────────────
727
728 ($f:ident, $text:literal $($rest:tt)*) => {
729 $f.push($crate::compose::Content::Text(::std::string::String::from($text)));
730 $crate::__form_items!($f, $($rest)*);
731 };
732 ($f:ident, @ { $e:expr } $($rest:tt)*) => {
733 $f.push($crate::compose::__display_text($e));
734 $crate::__form_items!($f, $($rest)*);
735 };
736 ($f:ident, ^ { $e:expr } $($rest:tt)*) => {
737 $f.push($crate::compose::IntoContent::into_content($e));
738 $crate::__form_items!($f, $($rest)*);
739 };
740 ($f:ident, .. ? ^ { $e:expr } $($rest:tt)*) => {
741 // The escape expression runs once; the `?` returns from the enclosing
742 // function or closure, so a failure skips every later escape and the
743 // half-built form is abandoned.
744 for __entry in $e {
745 let __item = __entry?;
746 $f.push($crate::compose::IntoContent::into_content(__item));
747 }
748 $crate::__form_items!($f, $($rest)*);
749 };
750 ($f:ident, .. ^ { $e:expr } $($rest:tt)*) => {
751 for __item in $e {
752 $f.push($crate::compose::IntoContent::into_content(__item));
753 }
754 $crate::__form_items!($f, $($rest)*);
755 };
756 ($f:ident, # comment $text:literal $($rest:tt)*) => {
757 $f.push($crate::compose::Content::Comment(::std::string::String::from($text)));
758 $crate::__form_items!($f, $($rest)*);
759 };
760 ($f:ident, # pi $target:literal $data:literal $($rest:tt)*) => {
761 $f.push($crate::compose::Content::Pi(
762 ::std::string::String::from($target),
763 ::std::string::String::from($data),
764 ));
765 $crate::__form_items!($f, $($rest)*);
766 };
767 ($f:ident, ( $($nested:tt)* ) $($rest:tt)*) => {
768 $f.push($crate::compose::Content::Element($crate::form!(($($nested)*))));
769 $crate::__form_items!($f, $($rest)*);
770 };
771
772 ($f:ident, $($rest:tt)*) => {
773 ::core::compile_error!(
774 "form!: expected a form item — an attribute (:name value), a namespace \
775 declaration (:xmlns \"urn:x\"), text (\"literal\" or @{ e }), content (^{ e }, \
776 ..^{ e }, ..?^{ e }), #comment \"…\", #pi \"…\" \"…\", or a nested (form …)"
777 )
778 };
779}
780
781/// Munches one attribute value, then hands the rest back to
782/// [`__form_items!`](crate::__form_items).
783#[doc(hidden)]
784#[macro_export]
785macro_rules! __form_attr {
786 ($f:ident, $name:expr, $v:literal $($rest:tt)*) => {
787 $f.attr(
788 $name,
789 $crate::compose::AttrValue::Text(::std::string::String::from($v)),
790 );
791 $crate::__form_items!($f, $($rest)*);
792 };
793 ($f:ident, $name:expr, @ { $e:expr } $($rest:tt)*) => {
794 $f.attr($name, $crate::compose::AttrValue::text($e));
795 $crate::__form_items!($f, $($rest)*);
796 };
797 ($f:ident, $name:expr, ^ { $e:expr } $($rest:tt)*) => {
798 $f.attr($name, $crate::compose::AttrValue::value($e));
799 $crate::__form_items!($f, $($rest)*);
800 };
801 ($f:ident, $name:expr, $($rest:tt)*) => {
802 ::core::compile_error!(
803 "form!: an attribute needs a value — a string literal, @{ e } for a Display \
804 value, or ^{ e } for a sequence. A single colon always starts an attribute, so \
805 a prefixed element name is written with two — form! { (p::local …) } — or as \
806 a string literal — form! { (\"p:local\" …) }"
807 )
808 };
809}
810
811#[cfg(test)]
812mod tests {
813 use std::cell::{Cell, RefCell};
814 use std::fmt;
815
816 use bumpalo::Bump;
817
818 use crate::compose::{ComposeError, Composer, Form};
819 use crate::document::SerializeOptions;
820 use crate::namespace::NameTable;
821 use crate::types::value::XmlValue;
822
823 /// The compact XML of a form, built by `c`.
824 fn xml<'a>(c: &Composer<'a>, form: Form<'a>) -> String {
825 c.build(form)
826 .expect("the form builds")
827 .to_xml(&SerializeOptions::default())
828 .expect("the document serializes")
829 }
830
831 /// Records that an expression ran, and hands its value straight back.
832 fn note<T>(log: &RefCell<Vec<&'static str>>, tag: &'static str, value: T) -> T {
833 log.borrow_mut().push(tag);
834 value
835 }
836
837 /// A value that is neither a string nor a number: `@{}` only needs
838 /// `Display`.
839 struct Bicycle;
840
841 impl fmt::Display for Bicycle {
842 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
843 f.write_str("Red Bicycle")
844 }
845 }
846
847 // ── xpath! ────────────────────────────────────────────────────────
848
849 #[test]
850 fn all_four_call_forms_work_with_and_without_a_trailing_comma() -> Result<(), ComposeError> {
851 let arena = Bump::new();
852 let names = NameTable::new();
853 let c = Composer::new(&arena, &names);
854 let items = c.load_str("<items><item n='1'/><item n='2'/></items>")?;
855
856 assert_eq!(xpath!(c, "1 + 1")?.string()?, "2");
857 assert_eq!(xpath!(c, "count(//item)", items)?.string()?, "2");
858 assert_eq!(xpath!(c, "$n * 2", n = 21)?.string()?, "42");
859 assert_eq!(
860 xpath!(c, "count(//item[@n = $n])", items, n = "2")?.string()?,
861 "1"
862 );
863
864 assert_eq!(xpath!(c, "1 + 1",)?.string()?, "2");
865 assert_eq!(xpath!(c, "count(//item)", items,)?.string()?, "2");
866 assert_eq!(xpath!(c, "$n * 2", n = 21,)?.string()?, "42");
867 assert_eq!(
868 xpath!(c, "count(//item[@n = $n])", items, n = "2",)?.string()?,
869 "1"
870 );
871 Ok(())
872 }
873
874 #[test]
875 fn a_context_item_can_be_written_in_any_shape() -> Result<(), ComposeError> {
876 let arena = Bump::new();
877 let names = NameTable::new();
878 let c = Composer::new(&arena, &names);
879 let doc = c.load_str("<a><b>deep</b></a>")?;
880 let node = doc.document_element().expect("a document element");
881 let prepared = Cell::new(0);
882
883 // Borrowed …
884 assert_eq!(xpath!(c, "name()", &node)?.string()?, "a");
885 // … a method call …
886 assert_eq!(xpath!(c, "name(*)", doc.root())?.string()?, "a");
887 // … a block that does some work first …
888 assert_eq!(
889 xpath!(c, "string(a/b)", {
890 prepared.set(prepared.get() + 1);
891 doc.root()
892 })?
893 .string()?,
894 "deep"
895 );
896 assert_eq!(prepared.get(), 1);
897 // … an expression that can itself fail …
898 assert_eq!(
899 xpath!(c, "name(*)", c.load_str("<z/>")?.root())?.string()?,
900 "z"
901 );
902 // … and a bare identifier, which the context item takes by value.
903 assert_eq!(xpath!(c, "name()", node)?.string()?, "a");
904 Ok(())
905 }
906
907 #[test]
908 fn a_named_binding_is_not_a_context_item() -> Result<(), ComposeError> {
909 let arena = Bump::new();
910 let names = NameTable::new();
911 let c = Composer::new(&arena, &names);
912 let doc = c.load_str("<a><b/></a>")?;
913 let node = doc.document_element().expect("a document element");
914
915 // The bindings arm is matched first, so this binds `$node` …
916 assert_eq!(xpath!(c, "name($node)", node = &node)?.string()?, "a");
917 // … and leaves the context item absent, which `name()` needs.
918 assert!(matches!(
919 xpath!(c, "name()", node = &node),
920 Err(ComposeError::XPath { .. })
921 ));
922 Ok(())
923 }
924
925 #[test]
926 fn every_expression_is_evaluated_once_and_in_order() -> Result<(), ComposeError> {
927 let arena = Bump::new();
928 let names = NameTable::new();
929 let c = Composer::new(&arena, &names);
930 let doc = c.load_str("<a><b/></a>")?;
931 let log = RefCell::new(Vec::new());
932
933 let value = xpath!(
934 note(&log, "composer", &c),
935 "concat(name(), $one, $two)",
936 note(&log, "context", doc.document_element().unwrap()),
937 one = note(&log, "one", "1"),
938 two = note(&log, "two", "2"),
939 )?;
940
941 assert_eq!(value.string()?, "a12");
942 assert_eq!(*log.borrow(), ["composer", "context", "one", "two"]);
943 Ok(())
944 }
945
946 #[test]
947 fn one_call_site_compiles_one_expression() -> Result<(), ComposeError> {
948 let arena = Bump::new();
949 let names = NameTable::new();
950 let c = Composer::new(&arena, &names);
951
952 for _ in 0..2 {
953 assert_eq!(xpath!(c, "$n + 1", n = 1)?.string()?, "2");
954 }
955 assert_eq!(c.cached_expressions(), 1);
956 Ok(())
957 }
958
959 #[test]
960 fn an_expression_error_names_the_expression() {
961 let arena = Bump::new();
962 let names = NameTable::new();
963 let c = Composer::new(&arena, &names);
964
965 match xpath!(c, "$undeclared + 1") {
966 Err(ComposeError::XPath { expr, .. }) => assert_eq!(expr, "$undeclared + 1"),
967 other => panic!("expected a refusal, got {other:?}"),
968 }
969 }
970
971 // ── form!: the invocation itself ──────────────────────────────────
972
973 #[test]
974 fn every_invocation_delimiter_expands_the_same() {
975 let arena = Bump::new();
976 let names = NameTable::new();
977 let c = Composer::new(&arena, &names);
978
979 // `form! { ( … ) }` is the documented spelling because rustfmt leaves
980 // it alone; the other two must keep working all the same.
981 let braces = xml(&c, form! { (part :qty "7" "bolt" (tag "new")) });
982 let parens = xml(&c, form!((part :qty "7" "bolt" (tag "new"))));
983 let brackets = xml(&c, form![(part :qty "7" "bolt" (tag "new"))]);
984
985 assert_eq!(braces, r#"<part qty="7">bolt<tag>new</tag></part>"#);
986 assert_eq!(parens, braces);
987 assert_eq!(brackets, braces);
988 }
989
990 // ── form!: names ──────────────────────────────────────────────────
991
992 #[test]
993 fn a_name_is_an_identifier_a_prefixed_pair_or_a_literal() -> Result<(), ComposeError> {
994 let arena = Bump::new();
995 let names = NameTable::new();
996 let c = Composer::new(&arena, &names).with_namespace("p", "urn:p");
997
998 assert_eq!(xml(&c, form! { (item_tuple) }), "<item_tuple/>");
999 assert_eq!(
1000 xml(&c, form! { (p::bid "55") }),
1001 r#"<p:bid xmlns:p="urn:p">55</p:bid>"#
1002 );
1003 // A name that is not a Rust identifier, and a prefixed one.
1004 assert_eq!(
1005 xml(&c, form! { ("bid-count" :"low-bid" "3" "7") }),
1006 r#"<bid-count low-bid="3">7</bid-count>"#
1007 );
1008 assert_eq!(
1009 xml(&c, form! { ("p:bid" "55") }),
1010 r#"<p:bid xmlns:p="urn:p">55</p:bid>"#
1011 );
1012 Ok(())
1013 }
1014
1015 #[test]
1016 fn a_single_colon_after_the_name_starts_an_attribute() {
1017 let arena = Bump::new();
1018 let names = NameTable::new();
1019 let c = Composer::new(&arena, &names).with_namespace("p", "urn:p");
1020
1021 // `(p:title "One")` and `(book :id "b1")` are the same token shape —
1022 // whitespace is not in the token stream — so one colon after the
1023 // element name is the attribute marker in both, and in either spacing.
1024 assert_eq!(xml(&c, form! { (p:title "One") }), r#"<p title="One"/>"#);
1025 assert_eq!(xml(&c, form! { (p :title "One") }), r#"<p title="One"/>"#);
1026 // A prefixed element name written with one colon does not compile at
1027 // all; the doc tests pin that. Nothing here is reinterpreted.
1028 }
1029
1030 #[test]
1031 fn a_prefixed_element_name_is_written_with_two_colons_or_a_literal() {
1032 let arena = Bump::new();
1033 let names = NameTable::new();
1034 let c = Composer::new(&arena, &names).with_namespace("p", "urn:p");
1035
1036 assert_eq!(
1037 xml(&c, form! { (p::title "One") }),
1038 r#"<p:title xmlns:p="urn:p">One</p:title>"#
1039 );
1040 assert_eq!(
1041 xml(&c, form! { ("p:title" "One") }),
1042 r#"<p:title xmlns:p="urn:p">One</p:title>"#
1043 );
1044 // An attribute after either spelling is unambiguous.
1045 assert_eq!(
1046 xml(&c, form! { (p::title :id "b1" "One") }),
1047 r#"<p:title xmlns:p="urn:p" id="b1">One</p:title>"#
1048 );
1049 assert_eq!(
1050 xml(&c, form! { (p::title (leaf)) }),
1051 r#"<p:title xmlns:p="urn:p"><leaf/></p:title>"#
1052 );
1053 }
1054
1055 #[test]
1056 fn an_unbound_prefix_is_refused_when_the_document_is_built() {
1057 let arena = Bump::new();
1058 let names = NameTable::new();
1059 let c = Composer::new(&arena, &names);
1060
1061 match c.build(form! { (p::x) }) {
1062 Err(ComposeError::UnboundPrefix { prefix, at }) => {
1063 assert_eq!(prefix, "p");
1064 assert_eq!(at, "p:x");
1065 }
1066 other => panic!("expected an unbound prefix, got {other:?}"),
1067 }
1068 }
1069
1070 #[test]
1071 fn a_literal_name_that_is_no_name_is_refused_when_the_document_is_built() {
1072 let arena = Bump::new();
1073 let names = NameTable::new();
1074 let c = Composer::new(&arena, &names);
1075
1076 match c.build(form! { ("not a name") }) {
1077 Err(ComposeError::InvalidName(name)) => assert_eq!(name, "not a name"),
1078 other => panic!("expected an invalid name, got {other:?}"),
1079 }
1080 match c.build(form! { (e :"not a name" "v") }) {
1081 Err(ComposeError::InvalidName(name)) => assert_eq!(name, "not a name"),
1082 other => panic!("expected an invalid name, got {other:?}"),
1083 }
1084 }
1085
1086 // ── form!: attributes and declarations ────────────────────────────
1087
1088 #[test]
1089 fn attributes_come_from_literals_display_values_and_sequences() -> Result<(), ComposeError> {
1090 let arena = Bump::new();
1091 let names = NameTable::new();
1092 let c = Composer::new(&arena, &names);
1093 let ids = xpath!(c, "(1, 2, 3)")?;
1094
1095 assert_eq!(
1096 xml(
1097 &c,
1098 form! { (item :kind "bike" :count @{ 7 } :what @{ Bicycle } :ids ^{ ids }) }
1099 ),
1100 r#"<item kind="bike" count="7" what="Red Bicycle" ids="1 2 3"/>"#
1101 );
1102 Ok(())
1103 }
1104
1105 #[test]
1106 fn the_xml_prefix_needs_no_declaration_in_either_spelling() {
1107 let arena = Bump::new();
1108 let names = NameTable::new();
1109 let c = Composer::new(&arena, &names);
1110
1111 assert_eq!(
1112 xml(&c, form! { (p :xml::lang "en" "text") }),
1113 r#"<p xml:lang="en">text</p>"#
1114 );
1115 assert_eq!(
1116 xml(&c, form! { (p :xml:space "preserve" "text") }),
1117 r#"<p xml:space="preserve">text</p>"#
1118 );
1119 }
1120
1121 #[test]
1122 fn namespace_declarations_apply_at_two_levels_and_shadow() {
1123 let arena = Bump::new();
1124 let names = NameTable::new();
1125 let c = Composer::new(&arena, &names);
1126
1127 assert_eq!(
1128 xml(
1129 &c,
1130 form! {
1131 (outer :xmlns "urn:one"
1132 (inner :xmlns "urn:two" (leaf))
1133 (sibling))
1134 }
1135 ),
1136 concat!(
1137 r#"<outer xmlns="urn:one">"#,
1138 r#"<inner xmlns="urn:two"><leaf/></inner>"#,
1139 "<sibling/></outer>",
1140 )
1141 );
1142 assert_eq!(
1143 xml(
1144 &c,
1145 form! { (e::root :xmlns::e "urn:e" (e::child :xmlns:e "urn:f" (e::leaf))) }
1146 ),
1147 concat!(
1148 r#"<e:root xmlns:e="urn:e">"#,
1149 r#"<e:child xmlns:e="urn:f"><e:leaf/></e:child>"#,
1150 "</e:root>",
1151 )
1152 );
1153 }
1154
1155 #[test]
1156 fn a_conflicting_attribute_prefix_gets_a_generated_one() -> Result<(), ComposeError> {
1157 let arena = Bump::new();
1158 let names = NameTable::new();
1159 let c = Composer::new(&arena, &names)
1160 .with_namespace("p", "urn:a")
1161 .with_namespace("q", "urn:b");
1162
1163 // The source binds `p` to a different namespace, so the copied
1164 // attribute cannot keep that prefix in a `p:out` element.
1165 let source = c.load_str(r#"<s xmlns:p="urn:b" p:k="v"/>"#)?;
1166 let attr = xpath!(c, "//@q:k", source)?;
1167
1168 let written = xml(&c, form! { (p::out ^{ attr }) });
1169 assert!(written.contains(r#"ns0:k="v""#), "{written}");
1170 assert!(written.contains(r#"xmlns:ns0="urn:b""#), "{written}");
1171 assert!(written.contains(r#"xmlns:p="urn:a""#), "{written}");
1172 Ok(())
1173 }
1174
1175 #[test]
1176 fn a_spliced_attribute_after_content_is_refused_with_the_form_path() -> Result<(), ComposeError>
1177 {
1178 let arena = Bump::new();
1179 let names = NameTable::new();
1180 let c = Composer::new(&arena, &names);
1181 let source = c.load_str(r#"<s k="v"/>"#)?;
1182 let attr = xpath!(c, "//@k", source)?;
1183
1184 match c.build(form! { (result (item "text first" ^{ attr })) }) {
1185 Err(ComposeError::Copy { source, at }) => {
1186 assert_eq!(at, "result/item");
1187 assert!(source.to_string().contains("content"), "{source}");
1188 }
1189 other => panic!("expected a copy refusal, got {other:?}"),
1190 }
1191 Ok(())
1192 }
1193
1194 // ── form!: content ────────────────────────────────────────────────
1195
1196 #[test]
1197 fn text_comes_from_literals_and_from_display_values() {
1198 let arena = Bump::new();
1199 let names = NameTable::new();
1200 let c = Composer::new(&arena, &names);
1201
1202 // Two adjacent texts concatenate with nothing between them.
1203 assert_eq!(
1204 xml(&c, form! { (p "in stock: " @{ 4 } " of " @{ Bicycle }) }),
1205 "<p>in stock: 4 of Red Bicycle</p>"
1206 );
1207 }
1208
1209 #[test]
1210 fn one_content_value_copies_a_node_or_takes_a_form() -> Result<(), ComposeError> {
1211 let arena = Bump::new();
1212 let names = NameTable::new();
1213 let c = Composer::new(&arena, &names);
1214 let source = c.load_str("<a><b k='v'>text</b></a>")?;
1215 let b = xpath!(c, "//b", source)?;
1216
1217 assert_eq!(
1218 xml(&c, form! { (out ^{ b } ^{ form! { (child "x") } }) }),
1219 r#"<out><b k="v">text</b><child>x</child></out>"#
1220 );
1221 Ok(())
1222 }
1223
1224 #[test]
1225 fn an_optional_content_value_is_present_or_absent() {
1226 let arena = Bump::new();
1227 let names = NameTable::new();
1228 let c = Composer::new(&arena, &names);
1229 let present: Option<Form<'_>> = Some(form! { (here) });
1230 let absent: Option<Form<'_>> = None;
1231
1232 assert_eq!(
1233 xml(&c, form! { (root ^{ present } ^{ absent }) }),
1234 "<root><here/></root>"
1235 );
1236 }
1237
1238 #[test]
1239 fn a_splice_over_an_empty_iterator_adds_nothing() {
1240 let arena = Bump::new();
1241 let names = NameTable::new();
1242 let c = Composer::new(&arena, &names);
1243 let empty: Vec<&str> = Vec::new();
1244
1245 assert_eq!(xml(&c, form! { (e "a" ..^{ empty } "b") }), "<e>ab</e>");
1246 }
1247
1248 #[test]
1249 fn separate_splices_keep_the_atomic_adjacency() {
1250 let arena = Bump::new();
1251 let names = NameTable::new();
1252 let c = Composer::new(&arena, &names);
1253 let empty: Vec<XmlValue> = Vec::new();
1254
1255 // One space between successive atomic values, across the splice
1256 // boundary, and an empty splice does not break it.
1257 assert_eq!(
1258 xml(
1259 &c,
1260 form! {
1261 (e
1262 ..^{ [XmlValue::string("a")] }
1263 ..^{ empty }
1264 ..^{ [XmlValue::string("b")] })
1265 }
1266 ),
1267 "<e>a b</e>"
1268 );
1269 }
1270
1271 #[test]
1272 fn a_splice_pushes_every_item_in_order() {
1273 let arena = Bump::new();
1274 let names = NameTable::new();
1275 let c = Composer::new(&arena, &names);
1276 let extra = ["washer", "screw"];
1277
1278 assert_eq!(
1279 xml(
1280 &c,
1281 form! { (parts ..^{ extra.iter().map(|n| form! { (part ^{ *n }) }) }) }
1282 ),
1283 "<parts><part>washer</part><part>screw</part></parts>"
1284 );
1285 }
1286
1287 #[test]
1288 fn comments_and_processing_instructions_are_items() {
1289 let arena = Bump::new();
1290 let names = NameTable::new();
1291 let c = Composer::new(&arena, &names);
1292
1293 assert_eq!(
1294 xml(&c, form! { (root #comment " note " #pi "work" "now") }),
1295 "<root><!-- note --><?work now?></root>"
1296 );
1297 }
1298
1299 #[test]
1300 fn a_nested_form_is_a_child_element() {
1301 let arena = Bump::new();
1302 let names = NameTable::new();
1303 let c = Composer::new(&arena, &names);
1304
1305 assert_eq!(
1306 xml(&c, form! { (a (b (c "deep")) (b)) }),
1307 "<a><b><c>deep</c></b><b/></a>"
1308 );
1309 }
1310
1311 #[test]
1312 fn items_are_evaluated_once_and_in_order() {
1313 let arena = Bump::new();
1314 let names = NameTable::new();
1315 let c = Composer::new(&arena, &names);
1316 let log = RefCell::new(Vec::new());
1317
1318 let form = form! {
1319 (e
1320 :first @{ note(&log, "attribute", 1) }
1321 @{ note(&log, "text", 2) }
1322 ^{ note(&log, "value", "three") }
1323 ..^{ note(&log, "splice", vec!["four"]) }
1324 )
1325 };
1326
1327 assert_eq!(*log.borrow(), ["attribute", "text", "value", "splice"]);
1328 assert_eq!(xml(&c, form), r#"<e first="1">2threefour</e>"#);
1329 }
1330
1331 // ── form!: the fallible splice ────────────────────────────────────
1332
1333 #[test]
1334 fn a_fallible_splice_carries_the_rows_through() -> Result<(), ComposeError> {
1335 let arena = Bump::new();
1336 let names = NameTable::new();
1337 let c = Composer::new(&arena, &names);
1338 let rows: Vec<Result<&str, ComposeError>> = vec![Ok("a"), Ok("b")];
1339
1340 assert_eq!(xml(&c, form! { (e ..?^{ rows }) }), "<e>ab</e>");
1341 Ok(())
1342 }
1343
1344 #[test]
1345 fn a_fallible_splice_stops_at_the_first_failure() {
1346 let arena = Bump::new();
1347 let names = NameTable::new();
1348 let c = Composer::new(&arena, &names);
1349
1350 let pulled = Cell::new(0);
1351 let later = Cell::new(0);
1352 let built = Cell::new(0);
1353
1354 let rows: Vec<Result<&str, ComposeError>> = vec![
1355 Ok("a"),
1356 Ok("b"),
1357 Err(ComposeError::NotANode),
1358 Ok("never reached"),
1359 ];
1360
1361 let outcome = (|| -> Result<String, ComposeError> {
1362 let form = form! {
1363 (result
1364 ..?^{ rows.into_iter().inspect(|_| pulled.set(pulled.get() + 1)) }
1365 ^{ { later.set(later.get() + 1); "after" } }
1366 )
1367 };
1368 built.set(built.get() + 1);
1369 c.build(form)?.to_xml(&SerializeOptions::default())
1370 })();
1371
1372 assert!(
1373 matches!(outcome, Err(ComposeError::NotANode)),
1374 "the failure leaves the closure, got {outcome:?}"
1375 );
1376 assert_eq!(pulled.get(), 3, "the row after the failure is never pulled");
1377 assert_eq!(later.get(), 0, "the escape after the splice is skipped");
1378 assert_eq!(built.get(), 0, "the build is never reached");
1379 }
1380
1381 // ── The documented example ────────────────────────────────────────
1382
1383 #[test]
1384 fn the_catalog_example_is_the_same_document_in_both_modes() -> Result<(), ComposeError> {
1385 let arena = Bump::new();
1386 let names = NameTable::new();
1387 let c = Composer::new(&arena, &names);
1388
1389 let doc = c.build(form! {
1390 (catalog
1391 (book :id "b1" (title "One"))
1392 (book :id "b2" (title "Two"))
1393 )
1394 })?;
1395
1396 assert_eq!(
1397 doc.to_xml(&SerializeOptions::default())?,
1398 concat!(
1399 r#"<catalog><book id="b1"><title>One</title></book>"#,
1400 r#"<book id="b2"><title>Two</title></book></catalog>"#,
1401 )
1402 );
1403
1404 let formatted = SerializeOptions {
1405 indent: Some(2),
1406 ..SerializeOptions::default()
1407 };
1408 assert_eq!(
1409 doc.to_xml(&formatted)?,
1410 concat!(
1411 "<catalog>\n",
1412 " <book id=\"b1\">\n <title>One</title>\n </book>\n",
1413 " <book id=\"b2\">\n <title>Two</title>\n </book>\n",
1414 "</catalog>",
1415 )
1416 );
1417 Ok(())
1418 }
1419}