Skip to main content

xsd_schema/document/
copy.rs

1//! Copying nodes into a document under construction, with constructor
2//! semantics.
3//!
4//! [`BufferDocumentBuilder`] can build a tree
5//! from scratch, and [`serialize`](super::serialize) can write one out. This
6//! module adds the step in between: taking nodes that already exist — in
7//! another `BufferDocument`, in a `roxmltree` document, in any navigator a host
8//! supplies — and appending them to the document being built, as a *new* node
9//! with a new identity rather than a reference to the old one.
10//!
11//! ```
12//! use bumpalo::Bump;
13//! use xsd_schema::document::{serialize, BufferDocument, BufferDocumentBuilder};
14//! use xsd_schema::document::{BufferDocumentOptions, CopyOptions};
15//! use xsd_schema::namespace::NameTable;
16//! use xsd_schema::navigator::DomNavigator;
17//!
18//! let arena = Bump::new();
19//! let names = NameTable::new();
20//! let source = BufferDocument::from_reader_default(
21//!     r#"<doc xmlns:p="urn:x"><p:keep k="1">text</p:keep></doc>"#.as_bytes(),
22//!     &arena,
23//!     &names,
24//! )?;
25//!
26//! // The node to copy: the one child of the document element.
27//! let mut keep = source.create_navigator();
28//! keep.move_to_first_child();
29//! keep.move_to_first_child();
30//!
31//! let target_arena = Bump::new();
32//! let mut builder =
33//!     BufferDocumentBuilder::new(&target_arena, &names, None, BufferDocumentOptions::default())?;
34//! builder.start_element("wrapper", "", "", &[])?;
35//! builder.end_of_attributes();
36//! builder.copy_subtree(&keep, CopyOptions::default())?;
37//! builder.end_element()?;
38//! let target = builder.finalize()?;
39//!
40//! // The prefix `p` was declared on an ancestor in the source; the copy
41//! // carries the declaration it needs itself.
42//! assert_eq!(
43//!     serialize::to_string(&target.create_navigator(), &Default::default())?,
44//!     r#"<wrapper><p:keep xmlns:p="urn:x" k="1">text</p:keep></wrapper>"#,
45//! );
46//! # Ok::<(), Box<dyn std::error::Error>>(())
47//! ```
48//!
49//! # What "constructor semantics" means here
50//!
51//! The rules are the ones an XQuery element constructor applies to its content
52//! sequence — the constructor content rules (XQuery 1.0 §3.7.1.3), quoted
53//! here as the design states them:
54//!
55//! > Any atomic value in the sequence is cast to a string. […] Any consecutive
56//! > sequence of strings within the result sequence is converted to a single
57//! > text node, whose string value contains the content of each of the strings
58//! > in turn, with a single space (#x20) used as a separator between successive
59//! > strings. Any document node within the result sequence is replaced by a
60//! > sequence containing each of its children, in document order. Zero-length
61//! > text nodes within the result sequence are removed. Adjacent text nodes
62//! > within the result sequence are merged into a single text node.
63//!
64//! [`append_content`](BufferDocumentBuilder::append_content) implements that
65//! table item by item, and two further rules of XQuery 1.0 §3.7.1:
66//!
67//! * an attribute that follows a child in the sequence is an error
68//!   ([`CopyError::AttributeAfterContent`], XQuery XQTY0024), as is an
69//!   attribute with no element to attach it to
70//!   ([`CopyError::AttributeOutsideElement`]);
71//! * two attributes with the same expanded name cannot both survive. XQuery
72//!   raises XQDY0025; this builder keeps the **later** value, which needs no
73//!   lookahead over the sequence. Refusing the duplicate instead is future
74//!   work.
75//!
76//! # Namespaces
77//!
78//! A copied element's names have to keep resolving in their new home, where
79//! the ancestors are different ones. [`NamespaceFixup`] works out, for each
80//! element, the declarations it must carry — XQuery 1.0 §3.7.4 calls this
81//! namespace fixup — and generates prefixes (`ns0`, `ns1`, …) where a prefix
82//! the source used is already bound to something else. This is what lets
83//! [`serialize`](super::serialize) be strict: it refuses to write a name whose
84//! prefix is unbound, and a tree built through this module never contains one.
85//!
86//! [`CopyOptions::namespaces`] and [`CopyOptions::inherit`] are the two words
87//! of XQuery's `copy-namespaces` declaration: whether declarations that the
88//! source element carried but does not need are preserved, and whether the
89//! copy inherits the declarations in force at the insertion point.
90//!
91//! # Type annotations
92//!
93//! By default a copy is untyped: the new nodes have no schema binding, so they
94//! atomize as `xs:untypedAtomic`, whatever the source was.
95//! [`Annotations::Preserve`] carries the source's bindings over, but only when
96//! source and target are bound to the *same* [`SchemaSet`] — a type key means
97//! nothing in another set, so that case is
98//! [`CopyError::SchemaMismatch`] rather than a
99//! silently wrong annotation.
100
101use std::ptr;
102
103use crate::namespace::XML_NAMESPACE;
104use crate::navigator::{DomNavigator, DomNodeType, NamespaceAxisScope, TypedValue};
105use crate::schema::SchemaSet;
106use crate::types::value::XmlValue;
107use crate::xpath::{XPathError, XmlItem};
108
109use super::navigator::BufferDocNavigator;
110use super::{BufferDocumentBuilder, BufferDocumentError, NodeSchemaBinding};
111
112/// The one prefix that is bound without a declaration and can never be
113/// declared (Namespaces in XML 1.0 §3).
114const XML_PREFIX: &str = "xml";
115
116// ── Options ───────────────────────────────────────────────────────────
117
118/// Whether a copied element keeps the namespace declarations it carried.
119///
120/// This is the first word of XQuery's `copy-namespaces` declaration. It is
121/// only ever visible for a declaration the subtree does not *need*: one it
122/// needs is added by the fixup either way.
123///
124/// ```
125/// use xsd_schema::document::CopyNamespaces;
126///
127/// assert_eq!(CopyNamespaces::default(), CopyNamespaces::Preserve);
128/// ```
129#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
130pub enum CopyNamespaces {
131    /// Carry over the declarations the source element made itself, used or not.
132    #[default]
133    Preserve,
134    /// Declare only what the copied names actually need.
135    NoPreserve,
136}
137
138/// Whether a copy carries the source's schema type annotations.
139///
140/// ```
141/// use xsd_schema::document::Annotations;
142///
143/// assert_eq!(Annotations::default(), Annotations::Strip);
144/// ```
145#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
146pub enum Annotations {
147    /// Copy nodes untyped, whatever the source was: no binding, no nil flag.
148    #[default]
149    Strip,
150    /// Replay the source's bindings and nil flags, when both documents share a
151    /// [`SchemaSet`].
152    Preserve,
153}
154
155/// How a subtree, an attribute or a content sequence is copied.
156///
157/// The default is XQuery's own default construction mode: declarations
158/// preserved, the insertion point's namespaces inherited, annotations
159/// stripped.
160///
161/// ```
162/// use xsd_schema::document::{Annotations, CopyNamespaces, CopyOptions};
163///
164/// let opts = CopyOptions::default();
165/// assert_eq!(opts.namespaces, CopyNamespaces::Preserve);
166/// assert!(opts.inherit);
167/// assert_eq!(opts.annotations, Annotations::Strip);
168///
169/// // A subtree that should stand entirely on its own:
170/// let standalone = CopyOptions {
171///     namespaces: CopyNamespaces::NoPreserve,
172///     inherit: false,
173///     ..CopyOptions::default()
174/// };
175/// assert!(!standalone.inherit);
176/// ```
177#[derive(Clone, Copy, Debug, PartialEq, Eq)]
178pub struct CopyOptions {
179    /// Whether an element keeps declarations it does not need.
180    pub namespaces: CopyNamespaces,
181    /// Whether the copy inherits the namespaces in scope at the insertion
182    /// point (`true`, the default) or re-declares what it needs on its own top
183    /// element (`false`).
184    pub inherit: bool,
185    /// Whether schema type annotations are carried over.
186    pub annotations: Annotations,
187}
188
189impl Default for CopyOptions {
190    fn default() -> Self {
191        Self {
192            namespaces: CopyNamespaces::default(),
193            inherit: true,
194            annotations: Annotations::default(),
195        }
196    }
197}
198
199// ── Errors ────────────────────────────────────────────────────────────
200
201/// Why a node could not be copied.
202///
203/// ```
204/// use bumpalo::Bump;
205/// use xsd_schema::document::{BufferDocument, BufferDocumentBuilder};
206/// use xsd_schema::document::{BufferDocumentOptions, CopyError, CopyOptions};
207/// use xsd_schema::namespace::NameTable;
208/// use xsd_schema::navigator::DomNavigator;
209///
210/// let arena = Bump::new();
211/// let names = NameTable::new();
212/// let source = BufferDocument::from_reader_default(r#"<a k="v"/>"#.as_bytes(), &arena, &names)?;
213/// let mut attr = source.create_navigator();
214/// attr.move_to_first_child();
215/// attr.move_to_first_attribute();
216///
217/// // Nothing is open, so there is no element to put the attribute on.
218/// let mut builder =
219///     BufferDocumentBuilder::new(&arena, &names, None, BufferDocumentOptions::default())?;
220/// match builder.copy_attribute(&attr, CopyOptions::default()) {
221///     Err(CopyError::AttributeOutsideElement { name }) => assert_eq!(name, "k"),
222///     other => panic!("expected a refusal, got {other:?}"),
223/// }
224/// # Ok::<(), Box<dyn std::error::Error>>(())
225/// ```
226#[derive(Debug, thiserror::Error)]
227pub enum CopyError {
228    /// An attribute was appended to an element that already has a child
229    /// (XQuery XQTY0024).
230    #[error("attribute {name:?} cannot be added after the element already has content")]
231    AttributeAfterContent {
232        /// The attribute's qualified name, as the source spells it.
233        name: String,
234    },
235
236    /// An attribute was appended with no element open, i.e. at document level
237    /// (XQuery XQTY0024).
238    #[error("attribute {name:?} cannot be added outside an element")]
239    AttributeOutsideElement {
240        /// The attribute's qualified name, as the source spells it.
241        name: String,
242    },
243
244    /// [`Annotations::Preserve`] was asked for, but the source document is
245    /// bound to a different [`SchemaSet`] than the document being built, so
246    /// its type keys mean nothing here.
247    #[error("type annotations cannot be preserved across two different schema sets")]
248    SchemaMismatch,
249
250    /// A node kind this copy cannot represent: a namespace node used as
251    /// content, or a node that is not an attribute passed to
252    /// [`copy_attribute`](BufferDocumentBuilder::copy_attribute).
253    #[error("{0}")]
254    Unsupported(&'static str),
255
256    /// The builder refused the node (the document is full, or an element was
257    /// closed that was never opened).
258    #[error("the document builder failed: {0}")]
259    Document(#[from] BufferDocumentError),
260
261    /// An atomic item could not be atomized to a string value.
262    #[error("an atomic value could not be atomized: {0}")]
263    Atomize(#[from] XPathError),
264}
265
266// ── CopySource ────────────────────────────────────────────────────────
267
268/// A navigator that can also report the PSVI facts a copy may carry over.
269///
270/// Every [`DomNavigator`] is a `CopySource`: the default bodies say "nothing to
271/// preserve", which is the right answer for a navigator over a document that
272/// was never validated. A schema-aware navigator overrides them, and then
273/// [`Annotations::Preserve`] has something to replay.
274///
275/// ```
276/// use xsd_schema::document::CopySource;
277/// use xsd_schema::navigator::RoXmlNavigator;
278///
279/// let doc = roxmltree::Document::parse("<a/>")?;
280/// let nav = RoXmlNavigator::new(&doc);
281///
282/// // An untyped source: a copy from it is untyped whatever the options say.
283/// assert!(nav.schema_binding().is_none());
284/// assert!(CopySource::schema_set(&nav).is_none());
285/// # Ok::<(), Box<dyn std::error::Error>>(())
286/// ```
287pub trait CopySource: DomNavigator {
288    /// The schema binding of the node at the cursor, if it carries one.
289    fn schema_binding(&self) -> Option<NodeSchemaBinding> {
290        None
291    }
292
293    /// The schema set the node's document is bound to, if any.
294    ///
295    /// A copy preserves annotations only when this is the very same set the
296    /// target document is bound to, compared by address.
297    fn schema_set(&self) -> Option<&SchemaSet> {
298        None
299    }
300}
301
302impl CopySource for BufferDocNavigator<'_> {
303    fn schema_binding(&self) -> Option<NodeSchemaBinding> {
304        // The inherent accessor borrows out of the remap table; a binding is
305        // `Copy`, and the copy has to outlive the navigator's borrow anyway.
306        BufferDocNavigator::schema_binding(self).copied()
307    }
308
309    fn schema_set(&self) -> Option<&SchemaSet> {
310        self.document().schema_set()
311    }
312}
313
314impl CopySource for crate::navigator::RoXmlNavigator<'_> {}
315
316// ── NamespaceFixup ────────────────────────────────────────────────────
317
318/// The namespace declarations a constructed element has to carry.
319///
320/// A `NamespaceFixup` mirrors the open elements of the document being built:
321/// one scope per element, innermost last. For each element it answers the only
322/// question namespace fixup (XQuery 1.0 §3.7.4) asks — which declarations does
323/// this element need so that its own name and its attributes' names resolve? —
324/// and rewrites an attribute's prefix when the one it came with is taken.
325///
326/// [`declarations_for`](Self::declarations_for) **pushes** the scope it
327/// computes, so the caller mirrors the element's end with
328/// [`pop_scope`](Self::pop_scope):
329///
330/// ```
331/// use xsd_schema::document::NamespaceFixup;
332///
333/// let mut fixup = NamespaceFixup::new();
334/// fixup.push_scope(&[("p".to_string(), "urn:outer".to_string())]);
335/// assert_eq!(fixup.in_scope("p"), Some("urn:outer"));
336///
337/// // An element in urn:inner with a `p:k` attribute in urn:other: the
338/// // element declares its own prefix, and the attribute cannot borrow the
339/// // conflicting `p`, so it gets a generated one.
340/// let (decls, attrs) =
341///     fixup.declarations_for(("q", "urn:inner"), &[("p", "urn:other")], &[]);
342/// assert_eq!(
343///     decls,
344///     vec![
345///         ("q".to_string(), "urn:inner".to_string()),
346///         ("ns0".to_string(), "urn:other".to_string()),
347///     ],
348/// );
349/// assert_eq!(attrs, vec![("ns0".to_string(), "urn:other".to_string())]);
350///
351/// fixup.pop_scope();
352/// assert_eq!(fixup.in_scope("q"), None);
353/// ```
354#[derive(Clone, Debug, Default)]
355pub struct NamespaceFixup {
356    /// Every binding of every open scope, innermost last. An entry with an
357    /// empty prefix and an empty URI is an undeclared default namespace.
358    bindings: Vec<(String, String)>,
359    /// Where each open scope starts in `bindings`.
360    marks: Vec<usize>,
361}
362
363impl NamespaceFixup {
364    /// A fixup with nothing in scope.
365    ///
366    /// ```
367    /// use xsd_schema::document::NamespaceFixup;
368    ///
369    /// let fixup = NamespaceFixup::new();
370    /// assert_eq!(fixup.in_scope("p"), None);
371    /// // The empty prefix always resolves: to no namespace.
372    /// assert_eq!(fixup.in_scope(""), Some(""));
373    /// ```
374    pub fn new() -> Self {
375        Self::default()
376    }
377
378    /// Opens a scope holding `decls`, as an element start does.
379    ///
380    /// ```
381    /// use xsd_schema::document::NamespaceFixup;
382    ///
383    /// let mut fixup = NamespaceFixup::new();
384    /// fixup.push_scope(&[(String::new(), "urn:d".to_string())]);
385    /// assert_eq!(fixup.in_scope(""), Some("urn:d"));
386    /// ```
387    pub fn push_scope(&mut self, decls: &[(String, String)]) {
388        self.marks.push(self.bindings.len());
389        self.bindings.extend_from_slice(decls);
390    }
391
392    /// Closes the innermost scope, as an element end does. A no-op when no
393    /// scope is open.
394    ///
395    /// ```
396    /// use xsd_schema::document::NamespaceFixup;
397    ///
398    /// let mut fixup = NamespaceFixup::new();
399    /// fixup.push_scope(&[("p".to_string(), "urn:x".to_string())]);
400    /// fixup.pop_scope();
401    /// assert_eq!(fixup.in_scope("p"), None);
402    /// fixup.pop_scope(); // harmless
403    /// ```
404    pub fn pop_scope(&mut self) {
405        if let Some(mark) = self.marks.pop() {
406            self.bindings.truncate(mark);
407        }
408    }
409
410    /// The namespace URI `prefix` resolves to here, or `None` when the prefix
411    /// is not usable.
412    ///
413    /// The empty prefix always resolves — to the empty URI when no default
414    /// namespace is in scope — and `xml` resolves without a declaration. A
415    /// prefix bound to the empty URI is an XML 1.1 undeclaration, which XML
416    /// 1.0 cannot write, so it reads as unusable rather than as "no
417    /// namespace".
418    ///
419    /// ```
420    /// use xsd_schema::document::NamespaceFixup;
421    ///
422    /// let mut fixup = NamespaceFixup::new();
423    /// fixup.push_scope(&[("p".to_string(), "urn:x".to_string())]);
424    /// assert_eq!(fixup.in_scope("p"), Some("urn:x"));
425    /// assert_eq!(fixup.in_scope("q"), None);
426    /// assert_eq!(fixup.in_scope("xml"), Some("http://www.w3.org/XML/1998/namespace"));
427    /// ```
428    pub fn in_scope(&self, prefix: &str) -> Option<&str> {
429        if prefix == XML_PREFIX {
430            return Some(XML_NAMESPACE);
431        }
432        match self
433            .bindings
434            .iter()
435            .rev()
436            .find(|(p, _)| p == prefix)
437            .map(|(_, u)| u.as_str())
438        {
439            Some("") if !prefix.is_empty() => None,
440            Some(uri) => Some(uri),
441            None if prefix.is_empty() => Some(""),
442            None => None,
443        }
444    }
445
446    /// The declarations an element must carry so that its own name and every
447    /// attribute name resolves, plus the — possibly re-prefixed — attribute
448    /// names to store.
449    ///
450    /// `elem` and the entries of `attrs` are `(prefix, namespace_uri)` pairs;
451    /// `keep` holds declarations to carry over from a copied source element
452    /// (its local namespace axis under [`CopyNamespaces::Preserve`], nothing
453    /// under [`CopyNamespaces::NoPreserve`]). The returned attribute names come
454    /// back in the order they were given, so a caller pairs them with its own
455    /// local names and values by index.
456    ///
457    /// The rules, in the order they are applied:
458    ///
459    /// 1. The element's own name is declared unless it already resolves. An
460    ///    unprefixed name in no namespace declares `xmlns=""` when a default
461    ///    namespace would otherwise apply to it.
462    /// 2. `keep` follows, minus anything that already resolves identically and
463    ///    minus any entry that would rebind the element's own prefix: the
464    ///    element's binding wins.
465    /// 3. An attribute in a namespace keeps its prefix when that prefix
466    ///    resolves to the same URI, and gets the prefix declared when it is
467    ///    free. An empty prefix (which cannot carry a namespaced attribute —
468    ///    Namespaces in XML 1.0 §6.2) and a prefix bound to another URI both
469    ///    get a generated prefix, `ns0`, `ns1`, … — the first that is neither
470    ///    in scope nor already declared on this element.
471    ///
472    /// The resulting scope is pushed before returning; call
473    /// [`pop_scope`](Self::pop_scope) when the element ends.
474    ///
475    /// ```
476    /// use xsd_schema::document::NamespaceFixup;
477    ///
478    /// let mut fixup = NamespaceFixup::new();
479    ///
480    /// // A prefixed element with an unprefixed attribute in no namespace:
481    /// // one declaration, and the attribute name is unchanged.
482    /// let (decls, attrs) = fixup.declarations_for(("p", "urn:x"), &[("", "")], &[]);
483    /// assert_eq!(decls, vec![("p".to_string(), "urn:x".to_string())]);
484    /// assert_eq!(attrs, vec![(String::new(), String::new())]);
485    ///
486    /// // Nested inside it, an unused declaration carried over by `keep`.
487    /// let (inner, _) = fixup.declarations_for(
488    ///     ("p", "urn:x"),
489    ///     &[],
490    ///     &[("unused".to_string(), "urn:u".to_string())]
491    ///         .iter()
492    ///         .map(|(p, u)| (p.as_str(), u.as_str()))
493    ///         .collect::<Vec<_>>(),
494    /// );
495    /// // `p` already resolves, so only the carried declaration is new.
496    /// assert_eq!(inner, vec![("unused".to_string(), "urn:u".to_string())]);
497    /// ```
498    // The tuple of two `(prefix, uri)` lists *is* the documented shape of the
499    // answer — declarations to write, names to store — and naming either half
500    // would hide which is which at the call site.
501    #[allow(clippy::type_complexity)]
502    pub fn declarations_for(
503        &mut self,
504        elem: (&str, &str),
505        attrs: &[(&str, &str)],
506        keep: &[(&str, &str)],
507    ) -> (Vec<(String, String)>, Vec<(String, String)>) {
508        let (elem_prefix, elem_uri) = elem;
509        let mut decls: Vec<(String, String)> = Vec::new();
510
511        // Rule 1 — the element's own name, first, so it wins every conflict.
512        // A prefixed name in no namespace cannot be written in XML 1.0 at all;
513        // nothing is declared for it and the serializer reports it.
514        if elem_prefix != XML_PREFIX
515            && (!elem_uri.is_empty() || elem_prefix.is_empty())
516            && self.in_scope(elem_prefix) != Some(elem_uri)
517        {
518            decls.push((elem_prefix.to_string(), elem_uri.to_string()));
519        }
520
521        // Rule 2 — declarations carried over from the source element.
522        for &(prefix, uri) in keep {
523            if prefix == XML_PREFIX
524                || (prefix == elem_prefix && uri != elem_uri)
525                || (uri.is_empty() && !prefix.is_empty())
526            {
527                continue;
528            }
529            if resolve(self, &decls, prefix) != Some(uri) {
530                decls.push((prefix.to_string(), uri.to_string()));
531            }
532        }
533
534        // Rule 3 — attribute names.
535        let mut names = Vec::with_capacity(attrs.len());
536        for &(prefix, uri) in attrs {
537            names.push(self.attribute_name(prefix, uri, &mut decls));
538        }
539
540        self.push_scope(&decls);
541        (decls, names)
542    }
543
544    /// The prefix an attribute in `uri` is stored with, declaring one in
545    /// `decls` when it needs declaring.
546    fn attribute_name(
547        &self,
548        prefix: &str,
549        uri: &str,
550        decls: &mut Vec<(String, String)>,
551    ) -> (String, String) {
552        // In no namespace: unprefixed, whatever the source called it. The
553        // default namespace never applies to an attribute (Namespaces in XML
554        // 1.0 §6.2), so this needs no declaration and can never conflict.
555        if uri.is_empty() {
556            return (String::new(), String::new());
557        }
558        if uri == XML_NAMESPACE {
559            return (XML_PREFIX.to_string(), uri.to_string());
560        }
561        if !prefix.is_empty() {
562            match resolve(self, decls, prefix) {
563                Some(bound) if bound == uri => return (prefix.to_string(), uri.to_string()),
564                Some(_) => {} // taken by another URI — generate one below
565                None => {
566                    decls.push((prefix.to_string(), uri.to_string()));
567                    return (prefix.to_string(), uri.to_string());
568                }
569            }
570        }
571        let generated = self.generated_prefix(decls);
572        decls.push((generated.clone(), uri.to_string()));
573        (generated, uri.to_string())
574    }
575
576    /// The first `ns{k}` that is neither in scope nor already declared here.
577    fn generated_prefix(&self, decls: &[(String, String)]) -> String {
578        let mut k = 0u32;
579        loop {
580            let candidate = format!("ns{k}");
581            if resolve(self, decls, &candidate).is_none() {
582                return candidate;
583            }
584            k += 1;
585        }
586    }
587}
588
589/// [`NamespaceFixup::in_scope`] extended with the declarations collected for
590/// an element that has not been pushed yet.
591fn resolve<'r>(
592    fixup: &'r NamespaceFixup,
593    pending: &'r [(String, String)],
594    prefix: &str,
595) -> Option<&'r str> {
596    if prefix == XML_PREFIX {
597        return Some(XML_NAMESPACE);
598    }
599    match pending.iter().rev().find(|(p, _)| p == prefix) {
600        Some((_, uri)) if uri.is_empty() && !prefix.is_empty() => None,
601        Some((_, uri)) => Some(uri.as_str()),
602        None => fixup.in_scope(prefix),
603    }
604}
605
606// ── Internals shared by the copy methods ──────────────────────────────
607
608/// What to do with the source's type annotations, once the schema sets have
609/// been compared.
610#[derive(Clone, Copy, Debug, PartialEq, Eq)]
611enum Annotate {
612    Strip,
613    Preserve,
614}
615
616/// One source attribute, read off before the target element is opened.
617struct CopiedAttribute {
618    local_name: String,
619    namespace_uri: String,
620    prefix: String,
621    value: String,
622    binding: Option<NodeSchemaBinding>,
623}
624
625/// The declarations the source element made itself, `xml` excluded.
626fn local_declarations<N: DomNavigator>(nav: &N) -> Vec<(String, String)> {
627    let mut decls = Vec::new();
628    let mut ns = nav.clone();
629    if ns.move_to_first_namespace(NamespaceAxisScope::Local) {
630        loop {
631            let prefix = ns.local_name();
632            if prefix != XML_PREFIX {
633                decls.push((prefix.to_string(), ns.value_ref().into_owned()));
634            }
635            if !ns.move_to_next_namespace(NamespaceAxisScope::Local) {
636                break;
637            }
638        }
639    }
640    decls
641}
642
643/// The string an atomic item contributes to the content.
644///
645/// XDM sequences hold atomic values, so the value is atomized first: that is
646/// the identity for an atomic value and unwraps a union. A list value is a
647/// *sequence* of atomic values, and the constructor content rules join such a
648/// run with a single space — exactly what its string value already is.
649fn atomic_text(value: &XmlValue) -> Result<String, XPathError> {
650    if value.is_atomic() || value.is_list() {
651        Ok(value.to_string_value())
652    } else {
653        Ok(crate::xpath::atomize::atomize(value)?.to_string_value())
654    }
655}
656
657/// The name to report in an attribute error, as the source spells it.
658fn qualified_name<N: DomNavigator>(nav: &N) -> String {
659    nav.name().to_string()
660}
661
662// ── Builder methods ───────────────────────────────────────────────────
663
664impl<'a> BufferDocumentBuilder<'a> {
665    /// Copies the node at the cursor, and everything below it, as the next
666    /// child of the open element — or as a top-level node when no element is
667    /// open.
668    ///
669    /// | Node kind | What is copied |
670    /// |---|---|
671    /// | element | the subtree: the element with its attributes, the declarations it needs, then its children |
672    /// | text, comment, processing instruction | that one node |
673    /// | document (`Root`) | its children, in document order — the node itself has no counterpart inside an element |
674    /// | attribute | as [`copy_attribute`](Self::copy_attribute) |
675    /// | namespace | [`CopyError::Unsupported`]: a namespace node is a property of an element, not content |
676    ///
677    /// The result is a new subtree with new node identities; nothing is shared
678    /// with the source, which may live in another document, another arena or
679    /// another navigator implementation entirely.
680    ///
681    /// ```
682    /// use bumpalo::Bump;
683    /// use xsd_schema::document::{serialize, BufferDocumentBuilder};
684    /// use xsd_schema::document::{BufferDocumentOptions, CopyOptions};
685    /// use xsd_schema::namespace::NameTable;
686    /// use xsd_schema::navigator::{DomNavigator, RoXmlNavigator};
687    ///
688    /// // The source need not be a BufferDocument.
689    /// let source = roxmltree::Document::parse("<doc><a>1</a><b/></doc>")?;
690    /// let mut nav = RoXmlNavigator::new(&source);
691    /// nav.move_to_first_child(); // <doc>
692    /// nav.move_to_first_child(); // <a>
693    ///
694    /// let arena = Bump::new();
695    /// let names = NameTable::new();
696    /// let mut builder =
697    ///     BufferDocumentBuilder::new(&arena, &names, None, BufferDocumentOptions::default())?;
698    /// builder.start_element("out", "", "", &[])?;
699    /// builder.end_of_attributes();
700    /// builder.copy_subtree(&nav, CopyOptions::default())?;
701    /// nav.move_to_next_sibling(); // <b/>
702    /// builder.copy_subtree(&nav, CopyOptions::default())?;
703    /// builder.end_element()?;
704    /// let doc = builder.finalize()?;
705    ///
706    /// assert_eq!(
707    ///     serialize::to_string(&doc.create_navigator(), &Default::default())?,
708    ///     "<out><a>1</a><b/></out>",
709    /// );
710    /// # Ok::<(), Box<dyn std::error::Error>>(())
711    /// ```
712    pub fn copy_subtree<N: CopySource>(
713        &mut self,
714        node: &N,
715        opts: CopyOptions,
716    ) -> Result<(), CopyError> {
717        match node.node_type() {
718            DomNodeType::Element => {
719                let mode = self.annotate_mode(node, opts)?;
720                let mut fixup = self.seeded_fixup(opts.inherit);
721                self.copy_element_tree(node, opts, mode, &mut fixup)
722            }
723            DomNodeType::Root => {
724                let mut child = node.clone();
725                if child.move_to_first_child() {
726                    loop {
727                        self.copy_subtree(&child, opts)?;
728                        if !child.move_to_next_sibling() {
729                            break;
730                        }
731                    }
732                }
733                Ok(())
734            }
735            DomNodeType::Attribute => self.copy_attribute(node, opts),
736            kind => self.copy_leaf(node, kind),
737        }
738    }
739
740    /// Copies an attribute node onto the open element.
741    ///
742    /// The attribute is stored with a prefix that resolves where it lands: the
743    /// source's prefix when that is free or already bound to the same URI, a
744    /// generated one otherwise, with the declaration added to the open element.
745    /// This is the one point where a declaration can appear after
746    /// [`start_element`](Self::start_element) has returned, and it is sound
747    /// because an attribute may only be added before the element has children.
748    ///
749    /// Errors when the element already has a child
750    /// ([`CopyError::AttributeAfterContent`]) or when no element is open
751    /// ([`CopyError::AttributeOutsideElement`]). An attribute whose expanded
752    /// name the element already carries replaces that one's value and type
753    /// annotation — the later of two duplicates wins, and keeps the earlier
754    /// one's prefix. What the earlier one made its element answer to in
755    /// `fn:id` goes with it.
756    ///
757    /// ```
758    /// use bumpalo::Bump;
759    /// use xsd_schema::document::{serialize, BufferDocument, BufferDocumentBuilder};
760    /// use xsd_schema::document::{BufferDocumentOptions, CopyOptions};
761    /// use xsd_schema::namespace::NameTable;
762    /// use xsd_schema::navigator::DomNavigator;
763    ///
764    /// let arena = Bump::new();
765    /// let names = NameTable::new();
766    /// let source = BufferDocument::from_reader_default(
767    ///     r#"<a xmlns:p="urn:x" p:k="v"/>"#.as_bytes(),
768    ///     &arena,
769    ///     &names,
770    /// )?;
771    /// let mut attr = source.create_navigator();
772    /// attr.move_to_first_child();
773    /// attr.move_to_first_attribute();
774    ///
775    /// let mut builder =
776    ///     BufferDocumentBuilder::new(&arena, &names, None, BufferDocumentOptions::default())?;
777    /// builder.start_element("out", "", "", &[])?;
778    /// builder.copy_attribute(&attr, CopyOptions::default())?;
779    /// builder.end_of_attributes();
780    /// builder.end_element()?;
781    /// let doc = builder.finalize()?;
782    ///
783    /// assert_eq!(
784    ///     serialize::to_string(&doc.create_navigator(), &Default::default())?,
785    ///     r#"<out xmlns:p="urn:x" p:k="v"/>"#,
786    /// );
787    /// # Ok::<(), Box<dyn std::error::Error>>(())
788    /// ```
789    pub fn copy_attribute<N: CopySource>(
790        &mut self,
791        attr: &N,
792        opts: CopyOptions,
793    ) -> Result<(), CopyError> {
794        if attr.node_type() != DomNodeType::Attribute {
795            return Err(CopyError::Unsupported(
796                "copy_attribute needs an attribute node",
797            ));
798        }
799        if !self.has_open_element() {
800            return Err(CopyError::AttributeOutsideElement {
801                name: qualified_name(attr),
802            });
803        }
804        if self.content_state().children_started {
805            return Err(CopyError::AttributeAfterContent {
806                name: qualified_name(attr),
807            });
808        }
809
810        let mode = self.annotate_mode(attr, opts)?;
811        let binding = if mode == Annotate::Preserve {
812            attr.schema_binding()
813        } else {
814            None
815        };
816        let local_name = attr.local_name();
817        let namespace_uri = attr.namespace_uri();
818        let value = attr.value_ref();
819
820        // A duplicate keeps its place and its prefix; its value and its
821        // annotation are the later one's — including the lack of one: an
822        // unannotated attribute must not inherit the earlier one's type.
823        if let Some(existing) = self.find_attribute(local_name, namespace_uri) {
824            self.set_attribute_value(existing, &value);
825            match binding {
826                Some(binding) => {
827                    self.set_node_binding(existing, binding)?;
828                }
829                None => self.clear_node_binding(existing),
830            }
831            return Ok(());
832        }
833
834        // Fixup against the scope actually in force at the insertion point:
835        // a lone attribute has no subtree to re-declare anything for.
836        let fixup = self.seeded_fixup(true);
837        let mut decls = Vec::new();
838        let (prefix, _) = fixup.attribute_name(attr.prefix(), namespace_uri, &mut decls);
839        for (decl_prefix, decl_uri) in &decls {
840            self.declare_namespace_on_open_element(decl_prefix, decl_uri)?;
841        }
842
843        self.sync_last_attribute();
844        let attr_ref = self.attribute(local_name, namespace_uri, &prefix, &value)?;
845        if let Some(binding) = binding {
846            self.set_node_binding(attr_ref, binding)?;
847        }
848        Ok(())
849    }
850
851    /// Appends a sequence of items as content, with the constructor content
852    /// rules (XQuery 1.0 §3.7.1.3).
853    ///
854    /// Each item is handled by its kind: an atomic value becomes text —
855    /// separated from a preceding atomic value by a single space, and from a
856    /// node by nothing at all — a document node contributes its children, an
857    /// attribute goes onto the open element, and anything else is copied as a
858    /// subtree. The "previous item was atomic" state belongs to the open
859    /// element, not to the call, so splitting a sequence across two calls makes
860    /// no difference to the output.
861    ///
862    /// ```
863    /// use bumpalo::Bump;
864    /// use xsd_schema::document::{serialize, BufferDocument, BufferDocumentBuilder};
865    /// use xsd_schema::document::{BufferDocumentOptions, CopyOptions};
866    /// use xsd_schema::namespace::NameTable;
867    /// use xsd_schema::navigator::DomNavigator;
868    /// use xsd_schema::types::value::XmlValue;
869    /// use xsd_schema::xpath::XmlItem;
870    ///
871    /// let arena = Bump::new();
872    /// let names = NameTable::new();
873    /// let source =
874    ///     BufferDocument::from_reader_default("<x><em>b</em></x>".as_bytes(), &arena, &names)?;
875    /// let mut em = source.create_navigator();
876    /// em.move_to_first_child();
877    /// em.move_to_first_child();
878    ///
879    /// let items = vec![
880    ///     XmlItem::Atomic(XmlValue::string("a")),
881    ///     XmlItem::Node(em),
882    ///     XmlItem::Atomic(XmlValue::string("c")),
883    ///     XmlItem::Atomic(XmlValue::string("d")),
884    /// ];
885    ///
886    /// let mut builder =
887    ///     BufferDocumentBuilder::new(&arena, &names, None, BufferDocumentOptions::default())?;
888    /// builder.start_element("p", "", "", &[])?;
889    /// builder.end_of_attributes();
890    /// builder.append_content(&items, CopyOptions::default())?;
891    /// builder.end_element()?;
892    /// let doc = builder.finalize()?;
893    ///
894    /// // No separator next to a node, one space between two atomic values.
895    /// assert_eq!(
896    ///     serialize::to_string(&doc.create_navigator(), &Default::default())?,
897    ///     "<p>a<em>b</em>c d</p>",
898    /// );
899    /// # Ok::<(), Box<dyn std::error::Error>>(())
900    /// ```
901    pub fn append_content<N: CopySource>(
902        &mut self,
903        items: &[XmlItem<N>],
904        opts: CopyOptions,
905    ) -> Result<(), CopyError> {
906        for item in items {
907            match item {
908                XmlItem::Atomic(value) => self.append_atomic(value)?,
909                XmlItem::Node(node) => self.copy_subtree(node, opts)?,
910            }
911        }
912        Ok(())
913    }
914
915    /// Appends one atomic value as text, with the separator rule of
916    /// [`append_content`](Self::append_content).
917    ///
918    /// A single space goes in first when the item appended last to this
919    /// element was also an atomic value. An explicit [`text`](Self::text) call
920    /// is not an atomic item and breaks that run, so text and an atomic value
921    /// meet without a separator.
922    ///
923    /// ```
924    /// use bumpalo::Bump;
925    /// use xsd_schema::document::{serialize, BufferDocumentBuilder, BufferDocumentOptions};
926    /// use xsd_schema::namespace::NameTable;
927    /// use xsd_schema::types::value::XmlValue;
928    ///
929    /// let arena = Bump::new();
930    /// let names = NameTable::new();
931    /// let mut builder =
932    ///     BufferDocumentBuilder::new(&arena, &names, None, BufferDocumentOptions::default())?;
933    /// builder.start_element("p", "", "", &[])?;
934    /// builder.end_of_attributes();
935    /// builder.append_atomic(&XmlValue::string("a"))?;
936    /// builder.append_atomic(&XmlValue::boolean(true))?;
937    /// builder.end_element()?;
938    /// let doc = builder.finalize()?;
939    ///
940    /// assert_eq!(
941    ///     serialize::to_string(&doc.create_navigator(), &Default::default())?,
942    ///     "<p>a true</p>",
943    /// );
944    /// # Ok::<(), Box<dyn std::error::Error>>(())
945    /// ```
946    pub fn append_atomic(&mut self, value: &XmlValue) -> Result<(), CopyError> {
947        let text = atomic_text(value)?;
948        if self.content_state().last_atomic {
949            self.text(" ");
950        }
951        self.text(&text);
952        let state = self.content_state_mut();
953        state.children_started = true;
954        state.last_atomic = true;
955        Ok(())
956    }
957
958    // ── Internals ─────────────────────────────────────────────────────
959
960    /// Copies a text, comment or processing-instruction node.
961    fn copy_leaf<N: DomNavigator>(&mut self, node: &N, kind: DomNodeType) -> Result<(), CopyError> {
962        match kind {
963            DomNodeType::Text | DomNodeType::Whitespace | DomNodeType::SignificantWhitespace => {
964                self.text(&node.value_ref());
965                Ok(())
966            }
967            DomNodeType::Comment => {
968                self.comment(&node.value_ref())?;
969                Ok(())
970            }
971            DomNodeType::ProcessingInstruction => {
972                self.processing_instruction(node.local_name(), &node.value_ref())?;
973                Ok(())
974            }
975            DomNodeType::Namespace => Err(CopyError::Unsupported(
976                "a namespace node is a property of an element and cannot be copied as content",
977            )),
978            _ => Err(CopyError::Unsupported(
979                "DomNodeType::All is a wildcard, not a node kind that can be copied",
980            )),
981        }
982    }
983
984    /// Walks the source subtree iteratively — one explicit level of `depth`
985    /// per open element, so a deep document cannot overflow the Rust stack —
986    /// opening, filling and closing the copy as it goes.
987    fn copy_element_tree<N: CopySource>(
988        &mut self,
989        start: &N,
990        opts: CopyOptions,
991        mode: Annotate,
992        fixup: &mut NamespaceFixup,
993    ) -> Result<(), CopyError> {
994        let mut nav = start.clone();
995        let mut depth = 0usize;
996        loop {
997            let mut descended = false;
998            match nav.node_type() {
999                DomNodeType::Element => {
1000                    self.start_copied_element(&nav, opts, mode, fixup)?;
1001                    let mut child = nav.clone();
1002                    if child.move_to_first_child() {
1003                        nav = child;
1004                        depth += 1;
1005                        descended = true;
1006                    } else {
1007                        self.end_element()?;
1008                        fixup.pop_scope();
1009                    }
1010                }
1011                // An element's children are elements, text, comments and PIs;
1012                // its attributes are copied with it, above.
1013                kind => self.copy_leaf(&nav, kind)?,
1014            }
1015            if descended {
1016                continue;
1017            }
1018            // Up and on, closing every element whose children are exhausted.
1019            loop {
1020                if depth == 0 {
1021                    return Ok(());
1022                }
1023                if nav.move_to_next_sibling() {
1024                    break;
1025                }
1026                nav.move_to_parent();
1027                depth -= 1;
1028                self.end_element()?;
1029                fixup.pop_scope();
1030            }
1031        }
1032    }
1033
1034    /// Opens the copy of one element: its declarations and attributes are read
1035    /// off the source *before* `start_element`, because that is where the
1036    /// builder takes an element's declarations.
1037    fn start_copied_element<N: CopySource>(
1038        &mut self,
1039        nav: &N,
1040        opts: CopyOptions,
1041        mode: Annotate,
1042        fixup: &mut NamespaceFixup,
1043    ) -> Result<(), CopyError> {
1044        let mut attributes: Vec<CopiedAttribute> = Vec::new();
1045        let mut attr = nav.clone();
1046        if attr.move_to_first_attribute() {
1047            loop {
1048                attributes.push(CopiedAttribute {
1049                    local_name: attr.local_name().to_string(),
1050                    namespace_uri: attr.namespace_uri().to_string(),
1051                    prefix: attr.prefix().to_string(),
1052                    value: attr.value_ref().into_owned(),
1053                    binding: if mode == Annotate::Preserve {
1054                        attr.schema_binding()
1055                    } else {
1056                        None
1057                    },
1058                });
1059                if !attr.move_to_next_attribute() {
1060                    break;
1061                }
1062            }
1063        }
1064
1065        let keep = if opts.namespaces == CopyNamespaces::Preserve {
1066            local_declarations(nav)
1067        } else {
1068            Vec::new()
1069        };
1070        let keep_refs: Vec<(&str, &str)> =
1071            keep.iter().map(|(p, u)| (p.as_str(), u.as_str())).collect();
1072        let attr_refs: Vec<(&str, &str)> = attributes
1073            .iter()
1074            .map(|a| (a.prefix.as_str(), a.namespace_uri.as_str()))
1075            .collect();
1076        let (decls, names) =
1077            fixup.declarations_for((nav.prefix(), nav.namespace_uri()), &attr_refs, &keep_refs);
1078        let decl_refs: Vec<(&str, &str)> = decls
1079            .iter()
1080            .map(|(p, u)| (p.as_str(), u.as_str()))
1081            .collect();
1082
1083        let elem_ref = self.start_element(
1084            nav.local_name(),
1085            nav.namespace_uri(),
1086            nav.prefix(),
1087            &decl_refs,
1088        )?;
1089        for (attribute, (prefix, _)) in attributes.iter().zip(names.iter()) {
1090            let attr_ref = self.attribute(
1091                &attribute.local_name,
1092                &attribute.namespace_uri,
1093                prefix,
1094                &attribute.value,
1095            )?;
1096            if let Some(binding) = attribute.binding {
1097                self.set_node_binding(attr_ref, binding)?;
1098            }
1099        }
1100        if mode == Annotate::Preserve {
1101            if let Some(binding) = nav.schema_binding() {
1102                self.set_node_binding(elem_ref, binding)?;
1103            }
1104            if nav.typed_value() == TypedValue::Nilled {
1105                self.set_nil(elem_ref);
1106            }
1107        }
1108        self.end_of_attributes();
1109        Ok(())
1110    }
1111
1112    /// Whether the source's annotations can be replayed here, per
1113    /// [`CopyOptions::annotations`].
1114    fn annotate_mode<N: CopySource>(
1115        &self,
1116        node: &N,
1117        opts: CopyOptions,
1118    ) -> Result<Annotate, CopyError> {
1119        if opts.annotations == Annotations::Strip {
1120            return Ok(Annotate::Strip);
1121        }
1122        match (node.schema_set(), self.schema_set()) {
1123            // Nothing to preserve: an untyped source copies untyped, as
1124            // `Strip` would.
1125            (None, _) => Ok(Annotate::Strip),
1126            (Some(source), Some(target)) if ptr::eq(source, target) => Ok(Annotate::Preserve),
1127            (Some(_), _) => Err(CopyError::SchemaMismatch),
1128        }
1129    }
1130
1131    /// A fixup seeded with the scope a copy starts from.
1132    ///
1133    /// With `inherit` the copy sees the namespaces in force at the insertion
1134    /// point and re-declares nothing they already provide. Without it the copy
1135    /// starts from an empty scope, so its top element re-declares everything
1136    /// its names need — except that an inherited **default** namespace stays
1137    /// visible: XML 1.0 cannot undeclare a prefix, but an unprefixed name in no
1138    /// namespace does need `xmlns=""` under one, and leaving that out would
1139    /// change the copied element's name.
1140    fn seeded_fixup(&self, inherit: bool) -> NamespaceFixup {
1141        let mut fixup = NamespaceFixup::new();
1142        let bindings = self.in_scope_bindings();
1143        if inherit {
1144            fixup.push_scope(&bindings);
1145        } else if let Some(default) = bindings.iter().find(|(p, u)| p.is_empty() && !u.is_empty()) {
1146            fixup.push_scope(std::slice::from_ref(default));
1147        }
1148        fixup
1149    }
1150}
1151
1152// ── Tests ─────────────────────────────────────────────────────────────
1153
1154#[cfg(test)]
1155mod tests {
1156    use super::*;
1157    use crate::document::{serialize, BufferDocument, BufferDocumentOptions};
1158    use crate::namespace::NameTable;
1159    use crate::navigator::RoXmlNavigator;
1160    use crate::xpath::TreeComparer;
1161    use bumpalo::Bump;
1162
1163    // ── Fixtures ──────────────────────────────────────────────────────
1164
1165    fn parse<'a>(xml: &str, arena: &'a Bump, names: &'a NameTable) -> BufferDocument<'a> {
1166        BufferDocument::from_reader_default(xml.as_bytes(), arena, names)
1167            .expect("the fixture parses")
1168    }
1169
1170    fn new_builder<'a>(arena: &'a Bump, names: &'a NameTable) -> BufferDocumentBuilder<'a> {
1171        BufferDocumentBuilder::new(arena, names, None, BufferDocumentOptions::default())
1172            .expect("a builder")
1173    }
1174
1175    /// The element reached from the document root by following `path` as child
1176    /// indices (`[0]` is the document element).
1177    fn element_at<'d>(doc: &'d BufferDocument<'d>, path: &[usize]) -> BufferDocNavigator<'d> {
1178        let mut nav = doc.create_navigator();
1179        for &index in path {
1180            assert!(nav.move_to_first_child(), "no children at {path:?}");
1181            for _ in 0..index {
1182                assert!(nav.move_to_next_sibling(), "no sibling at {path:?}");
1183            }
1184        }
1185        nav
1186    }
1187
1188    fn xml_of(doc: &BufferDocument<'_>) -> String {
1189        serialize::to_string(&doc.create_navigator(), &Default::default()).expect("serializes")
1190    }
1191
1192    /// Copies `path` out of `source` into a target element opened with
1193    /// `target_declarations`, and returns the serialized result.
1194    fn copy_into(
1195        source: &str,
1196        path: &[usize],
1197        target_declarations: &[(&str, &str)],
1198        target_uri: &str,
1199        opts: CopyOptions,
1200    ) -> String {
1201        let arena = Bump::new();
1202        let names = NameTable::new();
1203        let doc = parse(source, &arena, &names);
1204        let node = element_at(&doc, path);
1205
1206        let mut builder = new_builder(&arena, &names);
1207        builder
1208            .start_element("out", target_uri, "", target_declarations)
1209            .expect("starts");
1210        builder.end_of_attributes();
1211        builder.copy_subtree(&node, opts).expect("copies");
1212        builder.end_element().expect("ends");
1213        xml_of(&builder.finalize().expect("finalizes"))
1214    }
1215
1216    // ── Identity ──────────────────────────────────────────────────────
1217
1218    #[test]
1219    fn a_copy_is_a_new_node_with_the_same_content() {
1220        let arena = Bump::new();
1221        let names = NameTable::new();
1222        let doc = parse(r#"<r><a k="1">t<b/></a></r>"#, &arena, &names);
1223        let source = element_at(&doc, &[0, 0]);
1224
1225        let mut builder = new_builder(&arena, &names);
1226        builder
1227            .copy_subtree(&source, CopyOptions::default())
1228            .unwrap();
1229        let copied = builder.finalize().unwrap();
1230        let copy = element_at(&copied, &[0]);
1231
1232        assert!(!source.is_same_position(&copy), "the copy is a new node");
1233        assert_eq!(source.local_name(), copy.local_name());
1234        assert!(
1235            TreeComparer::new().deep_equal(&source, &copy),
1236            "the copy has the same content",
1237        );
1238        assert_eq!(xml_of(&copied), r#"<a k="1">t<b/></a>"#);
1239    }
1240
1241    /// A copied subtree is a new tree, and it carries its `xml:id`s: the copy
1242    /// goes through `BufferDocumentBuilder::attribute`, which is the one place
1243    /// an id is registered.
1244    #[test]
1245    fn a_copied_subtree_carries_its_ids() {
1246        let arena = Bump::new();
1247        let names = NameTable::new();
1248        let doc = parse(r#"<r><d xml:id="keep"><t>x</t></d></r>"#, &arena, &names);
1249        let source = element_at(&doc, &[0, 0]);
1250        assert_eq!(source.local_name(), "d");
1251
1252        let mut builder = new_builder(&arena, &names);
1253        builder
1254            .copy_subtree(&source, CopyOptions::default())
1255            .unwrap();
1256        let copied = builder.finalize().unwrap();
1257
1258        let found = copied
1259            .get_element_by_id("keep")
1260            .expect("the copy has the id");
1261        let mut nav = copied.create_navigator();
1262        assert!(nav.move_to_first_child());
1263        assert_eq!(nav.current_ref(), found, "the id points at the copy's root");
1264    }
1265
1266    // ── Content rules ─────────────────────────────────────────────────
1267
1268    /// Appends `items` to a `<p>` element and returns the serialized result.
1269    fn content_of(items: &[XmlItem<BufferDocNavigator<'_>>]) -> String {
1270        let arena = Bump::new();
1271        let names = NameTable::new();
1272        let mut builder = new_builder(&arena, &names);
1273        builder.start_element("p", "", "", &[]).unwrap();
1274        builder.end_of_attributes();
1275        builder
1276            .append_content(items, CopyOptions::default())
1277            .unwrap();
1278        builder.end_element().unwrap();
1279        xml_of(&builder.finalize().unwrap())
1280    }
1281
1282    #[test]
1283    fn two_atomic_values_are_joined_with_one_space() {
1284        let items = vec![
1285            XmlItem::Atomic(XmlValue::string("a")),
1286            XmlItem::Atomic(XmlValue::string("b")),
1287        ];
1288        assert_eq!(content_of(&items), "<p>a b</p>");
1289    }
1290
1291    #[test]
1292    fn an_atomic_value_next_to_a_node_gets_no_separator() {
1293        let arena = Bump::new();
1294        let names = NameTable::new();
1295        let doc = parse("<r><x/></r>", &arena, &names);
1296        let items = vec![
1297            XmlItem::Atomic(XmlValue::string("a")),
1298            XmlItem::Node(element_at(&doc, &[0, 0])),
1299            XmlItem::Atomic(XmlValue::string("b")),
1300        ];
1301        assert_eq!(content_of(&items), "<p>a<x/>b</p>");
1302    }
1303
1304    #[test]
1305    fn the_atomic_run_survives_across_two_calls() {
1306        let arena = Bump::new();
1307        let names = NameTable::new();
1308        let mut builder = new_builder(&arena, &names);
1309        builder.start_element("p", "", "", &[]).unwrap();
1310        builder.end_of_attributes();
1311        let first: Vec<XmlItem<BufferDocNavigator<'_>>> =
1312            vec![XmlItem::Atomic(XmlValue::string("a"))];
1313        let second: Vec<XmlItem<BufferDocNavigator<'_>>> =
1314            vec![XmlItem::Atomic(XmlValue::string("b"))];
1315        builder
1316            .append_content(&first, CopyOptions::default())
1317            .unwrap();
1318        builder
1319            .append_content(&second, CopyOptions::default())
1320            .unwrap();
1321        builder.end_element().unwrap();
1322        assert_eq!(xml_of(&builder.finalize().unwrap()), "<p>a b</p>");
1323    }
1324
1325    #[test]
1326    fn explicit_text_is_not_an_atomic_item() {
1327        let arena = Bump::new();
1328        let names = NameTable::new();
1329        let mut builder = new_builder(&arena, &names);
1330        builder.start_element("p", "", "", &[]).unwrap();
1331        builder.end_of_attributes();
1332        builder.text("a");
1333        builder.append_atomic(&XmlValue::string("b")).unwrap();
1334        builder.end_element().unwrap();
1335        assert_eq!(xml_of(&builder.finalize().unwrap()), "<p>ab</p>");
1336    }
1337
1338    #[test]
1339    fn a_text_node_in_the_sequence_breaks_the_atomic_run() {
1340        let arena = Bump::new();
1341        let names = NameTable::new();
1342        let doc = parse("<r>t</r>", &arena, &names);
1343        let mut text = doc.create_navigator();
1344        assert!(text.move_to_first_child());
1345        assert!(text.move_to_first_child());
1346        assert_eq!(text.node_type(), DomNodeType::Text);
1347        let items = vec![
1348            XmlItem::Atomic(XmlValue::string("a")),
1349            XmlItem::Node(text),
1350            XmlItem::Atomic(XmlValue::string("b")),
1351        ];
1352        assert_eq!(content_of(&items), "<p>atb</p>");
1353    }
1354
1355    #[test]
1356    fn a_document_node_contributes_its_children() {
1357        let arena = Bump::new();
1358        let names = NameTable::new();
1359        let doc = parse("<?work now?><r><a/></r><!--c-->", &arena, &names);
1360        let items = vec![XmlItem::Node(doc.create_navigator())];
1361        assert_eq!(content_of(&items), "<p><?work now?><r><a/></r><!--c--></p>",);
1362    }
1363
1364    #[test]
1365    fn an_attribute_after_a_child_is_refused() {
1366        let arena = Bump::new();
1367        let names = NameTable::new();
1368        let doc = parse(r#"<r k="v"/>"#, &arena, &names);
1369        let mut attr = element_at(&doc, &[0]);
1370        assert!(attr.move_to_first_attribute());
1371
1372        let mut builder = new_builder(&arena, &names);
1373        builder.start_element("out", "", "", &[]).unwrap();
1374        builder.end_of_attributes();
1375        builder.text("already here");
1376        let items = vec![XmlItem::Node(attr)];
1377        match builder.append_content(&items, CopyOptions::default()) {
1378            Err(CopyError::AttributeAfterContent { name }) => assert_eq!(name, "k"),
1379            other => panic!("expected a refusal, got {other:?}"),
1380        }
1381    }
1382
1383    #[test]
1384    fn an_attribute_at_document_level_is_refused() {
1385        let arena = Bump::new();
1386        let names = NameTable::new();
1387        let doc = parse(r#"<r p:k="v" xmlns:p="urn:x"/>"#, &arena, &names);
1388        let mut attr = element_at(&doc, &[0]);
1389        assert!(attr.move_to_first_attribute());
1390
1391        let mut builder = new_builder(&arena, &names);
1392        match builder.copy_attribute(&attr, CopyOptions::default()) {
1393            Err(CopyError::AttributeOutsideElement { name }) => assert_eq!(name, "p:k"),
1394            other => panic!("expected a refusal, got {other:?}"),
1395        }
1396    }
1397
1398    #[test]
1399    fn the_later_of_two_duplicate_attributes_wins() {
1400        let arena = Bump::new();
1401        let names = NameTable::new();
1402        let doc = parse(r#"<r><a k="1"/><b k="2"/></r>"#, &arena, &names);
1403        let mut first = element_at(&doc, &[0, 0]);
1404        assert!(first.move_to_first_attribute());
1405        let mut second = element_at(&doc, &[0, 1]);
1406        assert!(second.move_to_first_attribute());
1407
1408        let mut builder = new_builder(&arena, &names);
1409        builder.start_element("out", "", "", &[]).unwrap();
1410        builder
1411            .copy_attribute(&first, CopyOptions::default())
1412            .unwrap();
1413        builder
1414            .copy_attribute(&second, CopyOptions::default())
1415            .unwrap();
1416        builder.end_of_attributes();
1417        builder.end_element().unwrap();
1418        assert_eq!(xml_of(&builder.finalize().unwrap()), r#"<out k="2"/>"#);
1419    }
1420
1421    #[test]
1422    fn an_attribute_can_follow_end_of_attributes() {
1423        let arena = Bump::new();
1424        let names = NameTable::new();
1425        let doc = parse(r#"<r a="1" b="2"/>"#, &arena, &names);
1426        let mut attr = element_at(&doc, &[0]);
1427        assert!(attr.move_to_first_attribute());
1428        assert!(attr.move_to_next_attribute());
1429
1430        let mut builder = new_builder(&arena, &names);
1431        builder.start_element("out", "", "", &[]).unwrap();
1432        builder.attribute("a", "", "", "1").unwrap();
1433        builder.end_of_attributes();
1434        // Still legal: no child has been added yet.
1435        builder
1436            .copy_attribute(&attr, CopyOptions::default())
1437            .unwrap();
1438        builder.end_element().unwrap();
1439        assert_eq!(
1440            xml_of(&builder.finalize().unwrap()),
1441            r#"<out a="1" b="2"/>"#
1442        );
1443    }
1444
1445    // ── Namespaces ────────────────────────────────────────────────────
1446
1447    #[test]
1448    fn a_copy_carries_a_declaration_it_inherited() {
1449        // `p` is declared on the source's document element, not on the copied
1450        // node — the copy has to carry it, or the serializer would refuse the
1451        // name (`SerializeError::UnboundName`).
1452        assert_eq!(
1453            copy_into(
1454                r#"<r xmlns:p="urn:x"><p:a k="1"/></r>"#,
1455                &[0, 0],
1456                &[],
1457                "",
1458                CopyOptions::default(),
1459            ),
1460            r#"<out><p:a xmlns:p="urn:x" k="1"/></out>"#,
1461        );
1462    }
1463
1464    #[test]
1465    fn preserve_keeps_an_unused_declaration() {
1466        assert_eq!(
1467            copy_into(
1468                r#"<r xmlns:p="urn:x" xmlns:unused="urn:u"><p:a/></r>"#,
1469                &[0],
1470                &[],
1471                "",
1472                CopyOptions::default(),
1473            ),
1474            r#"<out><r xmlns:p="urn:x" xmlns:unused="urn:u"><p:a/></r></out>"#,
1475        );
1476    }
1477
1478    #[test]
1479    fn no_preserve_declares_only_what_is_needed() {
1480        let opts = CopyOptions {
1481            namespaces: CopyNamespaces::NoPreserve,
1482            ..CopyOptions::default()
1483        };
1484        assert_eq!(
1485            copy_into(
1486                r#"<r xmlns:p="urn:x" xmlns:unused="urn:u"><p:a/></r>"#,
1487                &[0],
1488                &[],
1489                "",
1490                opts,
1491            ),
1492            r#"<out><r><p:a xmlns:p="urn:x"/></r></out>"#,
1493        );
1494    }
1495
1496    #[test]
1497    fn without_inherit_the_copy_redeclares_what_it_needs() {
1498        let arena = Bump::new();
1499        let names = NameTable::new();
1500        let doc = parse(r#"<r xmlns:p="urn:x"><p:a/></r>"#, &arena, &names);
1501        let node = element_at(&doc, &[0, 0]);
1502
1503        // The target already binds `p` to the same URI, so an inheriting copy
1504        // needs no declaration of its own.
1505        let mut inheriting = new_builder(&arena, &names);
1506        inheriting
1507            .start_element("out", "", "", &[("p", "urn:x")])
1508            .unwrap();
1509        inheriting.end_of_attributes();
1510        inheriting
1511            .copy_subtree(&node, CopyOptions::default())
1512            .unwrap();
1513        inheriting.end_element().unwrap();
1514        let inherited = inheriting.finalize().unwrap();
1515        assert!(
1516            local_declarations(&element_at(&inherited, &[0, 0])).is_empty(),
1517            "an inheriting copy leans on the scope it landed in",
1518        );
1519
1520        let opts = CopyOptions {
1521            inherit: false,
1522            ..CopyOptions::default()
1523        };
1524        let mut standalone = new_builder(&arena, &names);
1525        standalone
1526            .start_element("out", "", "", &[("p", "urn:x")])
1527            .unwrap();
1528        standalone.end_of_attributes();
1529        standalone.copy_subtree(&node, opts).unwrap();
1530        standalone.end_element().unwrap();
1531        let alone = standalone.finalize().unwrap();
1532        assert_eq!(
1533            local_declarations(&element_at(&alone, &[0, 0])),
1534            vec![("p".to_string(), "urn:x".to_string())],
1535            "without inherit the declaration is re-emitted on the copy",
1536        );
1537
1538        // Either way the names resolve, so the output is the same: a
1539        // re-declaration of what is already in scope is redundant.
1540        assert_eq!(xml_of(&inherited), xml_of(&alone));
1541        assert_eq!(xml_of(&alone), r#"<out xmlns:p="urn:x"><p:a/></out>"#);
1542    }
1543
1544    #[test]
1545    fn a_conflicting_attribute_prefix_is_generated() {
1546        let opts = CopyOptions {
1547            namespaces: CopyNamespaces::NoPreserve,
1548            ..CopyOptions::default()
1549        };
1550        assert_eq!(
1551            copy_into(
1552                r#"<r xmlns:p="urn:x"><a p:k="v"/></r>"#,
1553                &[0, 0],
1554                &[("p", "urn:other")],
1555                "",
1556                opts,
1557            ),
1558            r#"<out xmlns:p="urn:other"><a xmlns:ns0="urn:x" ns0:k="v"/></out>"#,
1559        );
1560    }
1561
1562    #[test]
1563    fn a_namespaced_attribute_without_a_prefix_gets_one() {
1564        let arena = Bump::new();
1565        let names = NameTable::new();
1566
1567        // A parser cannot produce this — an unprefixed attribute is in no
1568        // namespace — so the source is built by hand.
1569        let mut source = new_builder(&arena, &names);
1570        source.start_element("a", "", "", &[]).unwrap();
1571        source.attribute("k", "urn:a", "", "v").unwrap();
1572        source.end_of_attributes();
1573        source.end_element().unwrap();
1574        let doc = source.finalize().unwrap();
1575
1576        let mut builder = new_builder(&arena, &names);
1577        builder.start_element("out", "", "", &[]).unwrap();
1578        builder.end_of_attributes();
1579        builder
1580            .copy_subtree(&element_at(&doc, &[0]), CopyOptions::default())
1581            .unwrap();
1582        builder.end_element().unwrap();
1583        assert_eq!(
1584            xml_of(&builder.finalize().unwrap()),
1585            r#"<out><a xmlns:ns0="urn:a" ns0:k="v"/></out>"#,
1586        );
1587    }
1588
1589    #[test]
1590    fn a_copied_attribute_brings_its_declaration_along() {
1591        let arena = Bump::new();
1592        let names = NameTable::new();
1593        let doc = parse(r#"<r xmlns:p="urn:x" p:k="v"/>"#, &arena, &names);
1594        let mut attr = element_at(&doc, &[0]);
1595        assert!(attr.move_to_first_attribute());
1596
1597        // The open element binds `p` elsewhere, so the copied attribute takes
1598        // a generated prefix, declared on the element it lands on.
1599        let mut builder = new_builder(&arena, &names);
1600        builder
1601            .start_element("out", "", "", &[("p", "urn:other")])
1602            .unwrap();
1603        builder
1604            .copy_attribute(&attr, CopyOptions::default())
1605            .unwrap();
1606        builder.end_of_attributes();
1607        builder.end_element().unwrap();
1608        assert_eq!(
1609            xml_of(&builder.finalize().unwrap()),
1610            r#"<out xmlns:ns0="urn:x" xmlns:p="urn:other" ns0:k="v"/>"#,
1611        );
1612    }
1613
1614    #[test]
1615    fn an_unprefixed_element_undeclares_an_inherited_default_namespace() {
1616        assert_eq!(
1617            copy_into(
1618                "<r><a/></r>",
1619                &[0, 0],
1620                &[("", "urn:d")],
1621                "urn:d",
1622                CopyOptions::default(),
1623            ),
1624            r#"<out xmlns="urn:d"><a xmlns=""/></out>"#,
1625        );
1626    }
1627
1628    #[test]
1629    fn a_default_namespace_is_carried_over_as_a_default() {
1630        assert_eq!(
1631            copy_into(
1632                r#"<r xmlns="urn:d"><a/></r>"#,
1633                &[0, 0],
1634                &[],
1635                "",
1636                CopyOptions::default(),
1637            ),
1638            r#"<out><a xmlns="urn:d"/></out>"#,
1639        );
1640    }
1641
1642    #[test]
1643    fn the_xml_prefix_is_never_declared() {
1644        assert_eq!(
1645            copy_into(
1646                r#"<r><a xml:lang="en"/></r>"#,
1647                &[0, 0],
1648                &[],
1649                "",
1650                CopyOptions::default(),
1651            ),
1652            r#"<out><a xml:lang="en"/></out>"#,
1653        );
1654    }
1655
1656    #[test]
1657    fn both_navigator_backends_copy_alike() {
1658        let xml = r#"<r xmlns:p="urn:x" xmlns="urn:d"><p:a k="1">t<!--c--><?pi d?></p:a></r>"#;
1659
1660        let arena = Bump::new();
1661        let names = NameTable::new();
1662        let doc = parse(xml, &arena, &names);
1663        let mut builder = new_builder(&arena, &names);
1664        builder
1665            .copy_subtree(&element_at(&doc, &[0, 0]), CopyOptions::default())
1666            .unwrap();
1667        let from_buffer = xml_of(&builder.finalize().unwrap());
1668
1669        let ro_doc = roxmltree::Document::parse(xml).expect("the fixture parses");
1670        let mut ro_nav = RoXmlNavigator::new(&ro_doc);
1671        assert!(ro_nav.move_to_first_child());
1672        assert!(ro_nav.move_to_first_child());
1673        let mut ro_builder = new_builder(&arena, &names);
1674        ro_builder
1675            .copy_subtree(&ro_nav, CopyOptions::default())
1676            .unwrap();
1677        let from_roxmltree = xml_of(&ro_builder.finalize().unwrap());
1678
1679        assert_eq!(from_buffer, from_roxmltree);
1680        assert_eq!(
1681            from_buffer,
1682            r#"<p:a xmlns:p="urn:x" k="1">t<!--c--><?pi d?></p:a>"#,
1683        );
1684    }
1685
1686    #[test]
1687    fn a_namespace_node_is_not_content() {
1688        let arena = Bump::new();
1689        let names = NameTable::new();
1690        let doc = parse(r#"<r xmlns:p="urn:x"/>"#, &arena, &names);
1691        let mut ns = element_at(&doc, &[0]);
1692        assert!(ns.move_to_first_namespace(NamespaceAxisScope::Local));
1693
1694        let mut builder = new_builder(&arena, &names);
1695        match builder.copy_subtree(&ns, CopyOptions::default()) {
1696            Err(CopyError::Unsupported(_)) => {}
1697            other => panic!("expected a refusal, got {other:?}"),
1698        }
1699    }
1700
1701    // ── Annotations ───────────────────────────────────────────────────
1702
1703    const NILLABLE_SCHEMA: &str = r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
1704        <xs:element name="r">
1705          <xs:complexType>
1706            <xs:sequence>
1707              <xs:element name="v" type="xs:int" nillable="true"/>
1708            </xs:sequence>
1709            <xs:attribute name="k" type="xs:int"/>
1710          </xs:complexType>
1711        </xs:element>
1712      </xs:schema>"#;
1713
1714    const NILLABLE_INSTANCE: &str =
1715        r#"<r k="7"><v xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/></r>"#;
1716
1717    fn load_schema() -> SchemaSet {
1718        let mut schema_set = SchemaSet::xsd11();
1719        crate::pipeline::load_and_process_schema(
1720            NILLABLE_SCHEMA.as_bytes(),
1721            "test.xsd",
1722            &mut schema_set,
1723            None,
1724        )
1725        .expect("the schema loads");
1726        schema_set
1727    }
1728
1729    fn preserving() -> CopyOptions {
1730        CopyOptions {
1731            annotations: Annotations::Preserve,
1732            ..CopyOptions::default()
1733        }
1734    }
1735
1736    #[test]
1737    fn annotations_are_preserved_within_one_schema_set() {
1738        let schema_set = load_schema();
1739        let arena = Bump::new();
1740        let names = NameTable::new();
1741        let source = crate::document::build_typed_document(
1742            NILLABLE_INSTANCE.as_bytes(),
1743            &arena,
1744            &schema_set,
1745            BufferDocumentOptions::default(),
1746        )
1747        .expect("the instance builds");
1748
1749        // The source really is typed, or the test would prove nothing.
1750        let root = element_at(&source, &[0]);
1751        assert!(root.schema_binding().is_some(), "the source is typed");
1752
1753        let mut builder = BufferDocumentBuilder::new(
1754            &arena,
1755            &names,
1756            Some(&schema_set),
1757            BufferDocumentOptions::default(),
1758        )
1759        .expect("a builder");
1760        builder.copy_subtree(&root, preserving()).unwrap();
1761        let copied = builder.finalize().unwrap();
1762
1763        let copy = element_at(&copied, &[0]);
1764        assert_eq!(
1765            copy.element_type_key(),
1766            root.element_type_key(),
1767            "the element keeps its type annotation",
1768        );
1769        let mut attr = copy.clone();
1770        assert!(attr.move_to_first_attribute());
1771        assert_eq!(attr.local_name(), "k");
1772        assert!(attr.schema_type().is_some(), "the attribute stays typed");
1773        let child = element_at(&copied, &[0, 0]);
1774        assert_eq!(child.typed_value(), TypedValue::Nilled, "nil is replayed");
1775    }
1776
1777    #[test]
1778    fn annotations_are_stripped_by_default() {
1779        let schema_set = load_schema();
1780        let arena = Bump::new();
1781        let names = NameTable::new();
1782        let source = crate::document::build_typed_document(
1783            NILLABLE_INSTANCE.as_bytes(),
1784            &arena,
1785            &schema_set,
1786            BufferDocumentOptions::default(),
1787        )
1788        .expect("the instance builds");
1789
1790        let mut builder = BufferDocumentBuilder::new(
1791            &arena,
1792            &names,
1793            Some(&schema_set),
1794            BufferDocumentOptions::default(),
1795        )
1796        .expect("a builder");
1797        builder
1798            .copy_subtree(&element_at(&source, &[0]), CopyOptions::default())
1799            .unwrap();
1800        let copied = builder.finalize().unwrap();
1801
1802        let copy = element_at(&copied, &[0]);
1803        assert!(copy.schema_binding().is_none(), "no annotation is carried");
1804        assert_eq!(
1805            element_at(&copied, &[0, 0]).typed_value(),
1806            TypedValue::Untyped,
1807            "and no nil flag either",
1808        );
1809    }
1810
1811    #[test]
1812    fn annotations_from_another_schema_set_are_refused() {
1813        let source_set = load_schema();
1814        let target_set = load_schema();
1815        let arena = Bump::new();
1816        let names = NameTable::new();
1817        let source = crate::document::build_typed_document(
1818            NILLABLE_INSTANCE.as_bytes(),
1819            &arena,
1820            &source_set,
1821            BufferDocumentOptions::default(),
1822        )
1823        .expect("the instance builds");
1824
1825        let mut builder = BufferDocumentBuilder::new(
1826            &arena,
1827            &names,
1828            Some(&target_set),
1829            BufferDocumentOptions::default(),
1830        )
1831        .expect("a builder");
1832        match builder.copy_subtree(&element_at(&source, &[0]), preserving()) {
1833            Err(CopyError::SchemaMismatch) => {}
1834            other => panic!("expected a refusal, got {other:?}"),
1835        }
1836    }
1837
1838    #[test]
1839    fn an_untyped_source_copies_untyped_even_with_preserve() {
1840        let schema_set = load_schema();
1841        let arena = Bump::new();
1842        let names = NameTable::new();
1843        // Parsed without a schema set: there is nothing to preserve, so this
1844        // is not a mismatch.
1845        let source = parse(r#"<r k="7"/>"#, &arena, &names);
1846
1847        let mut builder = BufferDocumentBuilder::new(
1848            &arena,
1849            &names,
1850            Some(&schema_set),
1851            BufferDocumentOptions::default(),
1852        )
1853        .expect("a builder");
1854        builder
1855            .copy_subtree(&element_at(&source, &[0]), preserving())
1856            .unwrap();
1857        let copied = builder.finalize().unwrap();
1858        assert!(element_at(&copied, &[0]).schema_binding().is_none());
1859        assert_eq!(xml_of(&copied), r#"<r k="7"/>"#);
1860    }
1861
1862    // ── NamespaceFixup on its own ─────────────────────────────────────
1863
1864    #[test]
1865    fn in_scope_reads_the_empty_prefix_and_xml_specially() {
1866        let mut fixup = NamespaceFixup::new();
1867        assert_eq!(fixup.in_scope(""), Some(""));
1868        assert_eq!(fixup.in_scope("xml"), Some(XML_NAMESPACE));
1869        assert_eq!(fixup.in_scope("p"), None);
1870
1871        fixup.push_scope(&[
1872            (String::new(), "urn:d".to_string()),
1873            ("p".to_string(), "urn:x".to_string()),
1874        ]);
1875        assert_eq!(fixup.in_scope(""), Some("urn:d"));
1876        assert_eq!(fixup.in_scope("p"), Some("urn:x"));
1877
1878        // An inner scope shadows, and popping restores.
1879        fixup.push_scope(&[("p".to_string(), "urn:y".to_string())]);
1880        assert_eq!(fixup.in_scope("p"), Some("urn:y"));
1881        fixup.pop_scope();
1882        assert_eq!(fixup.in_scope("p"), Some("urn:x"));
1883    }
1884
1885    #[test]
1886    fn generated_prefixes_skip_the_ones_already_taken() {
1887        let mut fixup = NamespaceFixup::new();
1888        fixup.push_scope(&[
1889            ("ns0".to_string(), "urn:zero".to_string()),
1890            ("p".to_string(), "urn:taken".to_string()),
1891        ]);
1892
1893        // Two attributes needing a prefix: `p` is taken by another URI, and
1894        // `ns0` is in scope, so the generated names start at `ns1`.
1895        let (decls, attrs) =
1896            fixup.declarations_for(("", ""), &[("p", "urn:a"), ("", "urn:b")], &[]);
1897        assert_eq!(
1898            decls,
1899            vec![
1900                ("ns1".to_string(), "urn:a".to_string()),
1901                ("ns2".to_string(), "urn:b".to_string()),
1902            ],
1903        );
1904        assert_eq!(
1905            attrs,
1906            vec![
1907                ("ns1".to_string(), "urn:a".to_string()),
1908                ("ns2".to_string(), "urn:b".to_string()),
1909            ],
1910        );
1911    }
1912
1913    #[test]
1914    fn the_elements_own_binding_wins_over_a_carried_one() {
1915        let mut fixup = NamespaceFixup::new();
1916        let (decls, _) = fixup.declarations_for(
1917            ("p", "urn:element"),
1918            &[],
1919            &[("p", "urn:carried"), ("q", "urn:kept")],
1920        );
1921        assert_eq!(
1922            decls,
1923            vec![
1924                ("p".to_string(), "urn:element".to_string()),
1925                ("q".to_string(), "urn:kept".to_string()),
1926            ],
1927        );
1928    }
1929}