Skip to main content

einvoice_xslt_exec/
sink.rs

1//! Where the result of a sequence constructor goes (XSLT 2.0 section 5.7).
2//!
3//! Instructions push events into a [`Sink`]; the instruction that owns the sequence
4//! constructor chooses the sink, which gives the result its meaning:
5//!
6//! - complex content (the final result, written straight to XML by [`XmlWriter`] or
7//!   built as a tree; a temporary tree, built by [`TreeSink`]): adjacent atomic values
8//!   are separated by a space, nodes are copied, a document node is replaced by its
9//!   children;
10//! - simple content (attribute values, comments, processing instructions,
11//!   `xsl:value-of`): [`TextSink`] concatenates the string values, adjacent text merged,
12//!   with a separator between the other items;
13//! - a sequence (`xsl:function` bodies, variables and parameters with `as`):
14//!   [`SequenceSink`] keeps the items, and each node an instruction constructs at its top
15//!   is a new parentless node (an element with its content, a document node with its
16//!   content, an attribute, a text node, even a zero-length one, a comment or a
17//!   processing instruction), as Saxon-HE 12.10 constructs them.
18
19use std::cmp::Ordering;
20use std::rc::Rc;
21use std::sync::Arc;
22
23use einvoice_xpath::{QName, XML_NAMESPACE};
24use einvoice_xpath_eval::tree::Axis;
25use einvoice_xpath_eval::{Document, Item, Node, NodeKind, TreeBuilder};
26use einvoice_xslt::NamespaceBinding;
27
28use crate::error::{Result, TransformError, err};
29use crate::output::{CompactBuilder, ResultObserver};
30
31/// The receiver of the events of a sequence constructor.
32pub(crate) trait Sink {
33    /// Opens an element with namespace nodes, besides those it inherits from its parent:
34    /// those of a literal result element, of `xsl:element`.
35    fn start_element(&mut self, name: &QName, namespaces: &Arc<[NamespaceBinding]>) -> Result<()>;
36    /// Opens a copy of an element (`xsl:copy`, `xsl:copy-of`, a node of `xsl:sequence`):
37    /// its namespace nodes are exactly `namespaces`, those it had, whatever its new parent
38    /// has (Saxon copies the namespaces of an element as they are). Only a tree tells the
39    /// two apart: written as XML, a binding of the parent that the copy lacks is not
40    /// undeclared, as Saxon's serializer does not undeclare it.
41    fn start_copied_element(
42        &mut self,
43        name: &QName,
44        namespaces: &Arc<[NamespaceBinding]>,
45    ) -> Result<()> {
46        self.start_element(name, namespaces)
47    }
48    /// Adds a namespace node to the element just opened (`xsl:namespace`): `prefix`
49    /// `None` for the default namespace.
50    fn namespace(&mut self, prefix: Option<&str>, uri: &str) -> Result<()>;
51    /// Adds an attribute to the element just opened.
52    fn attribute(&mut self, name: &QName, value: &str) -> Result<()>;
53    /// Closes the innermost open element.
54    fn end_element(&mut self) -> Result<()>;
55    /// A text node (possibly empty: it still separates atomic values).
56    fn text(&mut self, text: &str) -> Result<()>;
57    /// A comment.
58    fn comment(&mut self, text: &str) -> Result<()>;
59    /// A processing instruction.
60    fn processing_instruction(&mut self, target: &str, value: &str) -> Result<()>;
61    /// Opens a document node (a copied one, or `xsl:copy` of one): in complex content,
62    /// its children are added in its place.
63    fn start_document(&mut self) -> Result<()> {
64        Ok(())
65    }
66    /// Closes the document node opened last.
67    fn end_document(&mut self) -> Result<()> {
68        Ok(())
69    }
70    /// An item of `xsl:sequence`: an atomic value or an existing node.
71    fn item(&mut self, item: &Item) -> Result<()>;
72}
73
74/// Copies an existing node (deep copy, as XSLT 2.0 section 5.7.1 prescribes for nodes in
75/// a sequence constructor, and as `xsl:copy-of` copies), each element with its namespace
76/// nodes (`copy-namespaces="yes"`). The subtree is walked with an explicit stack, not a
77/// recursion: its depth is only bounded by the document's.
78pub(crate) fn copy_node(sink: &mut dyn Sink, node: &Node) -> Result<()> {
79    // The document node or elements being copied, innermost last, each with its children
80    // not copied yet, and for an element (to close) its namespaces in scope.
81    let mut open: Vec<(Axis, Option<Arc<[NamespaceBinding]>>)> = Vec::new();
82    let mut next = Some(node.clone());
83    loop {
84        if let Some(node) = next.take() {
85            match node.kind() {
86                NodeKind::Document => {
87                    sink.start_document()?;
88                    open.push((node.children(), None));
89                }
90                NodeKind::Element => {
91                    let Some(name) = node.name() else {
92                        return err("INTERNAL", "element without name");
93                    };
94                    // Those of the parent element, unless it has bindings of its own.
95                    let inherited = open
96                        .last()
97                        .and_then(|(_, parent)| parent.as_ref())
98                        .filter(|_| !node.has_own_namespaces());
99                    let namespaces: Arc<[NamespaceBinding]> = match inherited {
100                        Some(parent) => Arc::clone(parent),
101                        None => node.namespaces_in_scope().into(),
102                    };
103                    sink.start_copied_element(name, &namespaces)?;
104                    for attribute in node.attributes() {
105                        copy_attribute(sink, &attribute)?;
106                    }
107                    open.push((node.children(), Some(namespaces)));
108                }
109                NodeKind::Attribute => copy_attribute(sink, &node)?,
110                NodeKind::Text => sink.text(&node.string_value())?,
111                NodeKind::Comment => sink.comment(&node.string_value())?,
112                NodeKind::ProcessingInstruction => {
113                    let target = node.name().map_or("", |n| n.local.as_str());
114                    sink.processing_instruction(target, &node.string_value())?;
115                }
116            }
117        }
118        let Some((children, _)) = open.last_mut() else {
119            return Ok(());
120        };
121        match children.next() {
122            Some(child) => next = Some(child),
123            None => {
124                if let Some((_, element)) = open.pop() {
125                    if element.is_some() {
126                        sink.end_element()?;
127                    } else {
128                        sink.end_document()?;
129                    }
130                }
131            }
132        }
133    }
134}
135
136fn copy_attribute(sink: &mut dyn Sink, attribute: &Node) -> Result<()> {
137    let Some(name) = attribute.name() else {
138        return err("INTERNAL", "attribute without name");
139    };
140    sink.attribute(name, &attribute.string_value())
141}
142
143/// Serialization parameters of the XML output method (`xsl:output`), as Saxon-HE 12.10
144/// writes XML: UTF-8, namespace declarations before the attributes and sorted by prefix,
145/// `&lt;`, `&gt;` and `&amp;` escaped (and quotes, tabs, line ends and carriage returns
146/// in attribute values), carriage returns as `&#xD;`, U+007F to U+009F and U+2028 as
147/// character references, three spaces of indentation.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
149pub struct Serialization {
150    /// `indent="yes"`.
151    pub indent: bool,
152    /// `omit-xml-declaration="yes"`.
153    pub omit_xml_declaration: bool,
154    /// `Some(true)`: `standalone="yes"`, `Some(false)`: `"no"`, `None`: omitted.
155    pub standalone: Option<bool>,
156}
157
158/// A namespace binding: the prefix (`None` for the default namespace) and the URI (empty:
159/// the default namespace undeclared).
160type Binding = (Option<String>, String);
161
162/// A start tag once its namespaces are fixed up: the element's name, its attributes and
163/// its own namespace nodes.
164type FixedTag = (QName, Vec<(QName, String)>, Vec<Binding>);
165
166/// An element whose start tag is not complete yet: attributes and namespaces may still
167/// come.
168#[derive(Debug)]
169struct StartTag {
170    name: QName,
171    attributes: Vec<(QName, String)>,
172    /// The namespace nodes it was given: those of a literal result element, or all those
173    /// of a copied element.
174    given: Arc<[NamespaceBinding]>,
175    /// Those `xsl:namespace` added.
176    added: Vec<Binding>,
177}
178
179impl StartTag {
180    fn new(name: &QName, given: &Arc<[NamespaceBinding]>) -> Self {
181        Self {
182            name: name.clone(),
183            attributes: Vec::new(),
184            given: Arc::clone(given),
185            added: Vec::new(),
186        }
187    }
188
189    /// The URI the element's own namespace nodes bind `prefix` to.
190    fn own(&self, prefix: Option<&str>) -> Option<&str> {
191        self.added
192            .iter()
193            .find(|(p, _)| p.as_deref() == prefix)
194            .map(|(_, u)| u.as_str())
195            .or_else(|| {
196                self.given
197                    .iter()
198                    .find(|b| b.prefix.as_deref() == prefix)
199                    .map(|b| b.uri.as_str())
200            })
201    }
202
203    /// Adds a namespace node (`xsl:namespace`): an error when the element's own namespace
204    /// nodes bind the prefix to another URI (`XTDE0430`), or for a default namespace on
205    /// an element in no namespace (`XTDE0440`). The namespaces it inherits do not count.
206    fn namespace(&mut self, prefix: Option<&str>, uri: &str) -> Result<()> {
207        if prefix.is_none() && self.name.namespace.is_none() {
208            return err(
209                "XTDE0440",
210                format!(
211                    "a default namespace node ({uri:?}) on the element {}, which is in no namespace",
212                    self.name
213                ),
214            );
215        }
216        match self.own(prefix) {
217            Some(existing) if existing == uri => Ok(()),
218            Some(existing) => Err(namespace_conflict(prefix, uri, existing)),
219            None => {
220                self.added.push((prefix.map(str::to_owned), uri.to_owned()));
221                Ok(())
222            }
223        }
224    }
225
226    /// Adds an attribute, replacing one of the same expanded name.
227    fn attribute(&mut self, name: &QName, value: &str) {
228        if let Some(existing) = self
229            .attributes
230            .iter_mut()
231            .find(|(n, _)| n.same_expanded_name(name))
232        {
233            existing.0 = name.clone();
234            value.clone_into(&mut existing.1);
235        } else {
236            self.attributes.push((name.clone(), value.to_owned()));
237        }
238    }
239
240    /// The element's own namespace nodes when they are exactly those it was given: no
241    /// `xsl:namespace` added any, and namespace fixup ([`StartTag::fix`]) adds none and
242    /// renames nothing, as the namespace nodes given bind the prefix of the element and
243    /// that of each attribute in a namespace already. `None` otherwise. Allocates
244    /// nothing: the common case of a literal result element or a copy, whose names are
245    /// bound by its own namespace nodes.
246    fn given_unchanged(&self) -> Option<&Arc<[NamespaceBinding]>> {
247        if !self.added.is_empty() {
248            return None;
249        }
250        let bound = |prefix: Option<&str>| {
251            self.given
252                .iter()
253                .find(|b| b.prefix.as_deref() == prefix)
254                .map(|b| b.uri.as_str())
255        };
256        if self.name.prefix.as_deref() != Some("xml")
257            && bound(self.name.prefix.as_deref())
258                != Some(self.name.namespace.as_deref().unwrap_or(""))
259        {
260            return None;
261        }
262        for (attribute, _) in &self.attributes {
263            let Some(namespace) = attribute.namespace.as_deref() else {
264                continue;
265            };
266            match attribute.prefix.as_deref() {
267                Some("xml") => {}
268                Some(prefix) if bound(Some(prefix)) == Some(namespace) => {}
269                _ => return None,
270            }
271        }
272        Some(&self.given)
273    }
274
275    /// Namespace fixup, as Saxon-HE 12.10 does it when the start tag is complete: the
276    /// element's name, then each attribute's, gets a namespace node for its prefix unless
277    /// the element's own namespace nodes (those it was given, those added, those fixup
278    /// added) bind it already. A prefix they bind to another namespace is replaced: by the
279    /// prefix and `_0` for the element, by the prefix, `_` and the position of the
280    /// attribute (from 1) for an attribute. A namespace the element inherits is no
281    /// conflict: the new node overrides it. Returns the name, the attributes and the own
282    /// namespace nodes: those given, then those added, then those of fixup.
283    fn fix(self) -> Result<FixedTag> {
284        let Self {
285            mut name,
286            mut attributes,
287            given,
288            added,
289        } = self;
290        let mut own: Vec<Binding> = given
291            .iter()
292            .map(|b| (b.prefix.clone(), b.uri.clone()))
293            .filter(|(p, _)| !added.iter().any(|(q, _)| q == p))
294            .collect();
295        own.extend(added);
296        let lookup = |own: &[Binding], prefix: Option<&str>| {
297            own.iter()
298                .find(|(p, _)| p.as_deref() == prefix)
299                .map(|(_, u)| u.clone())
300        };
301        let uri = name.namespace.clone().unwrap_or_default();
302        if name.prefix.as_deref() != Some("xml") {
303            match lookup(&own, name.prefix.as_deref()) {
304                Some(bound) if bound == uri => {}
305                Some(_) => {
306                    let Some(prefix) = name.prefix.clone() else {
307                        return err(
308                            "UNSUPPORTED",
309                            format!(
310                                "the element {name} in a namespace other than its default namespace node"
311                            ),
312                        );
313                    };
314                    let renamed = format!("{prefix}_0");
315                    match lookup(&own, Some(&renamed)) {
316                        Some(bound) if bound == uri => {}
317                        Some(_) => {
318                            return err(
319                                "UNSUPPORTED",
320                                format!("the prefix Saxon gives the element {name}"),
321                            );
322                        }
323                        None => own.push((Some(renamed.clone()), uri.clone())),
324                    }
325                    name.prefix = Some(renamed);
326                }
327                None => own.push((name.prefix.clone(), uri)),
328            }
329        }
330        for (seq, (attribute, _)) in (1_usize..).zip(attributes.iter_mut()) {
331            let Some(namespace) = attribute.namespace.clone() else {
332                continue;
333            };
334            let Some(prefix) = attribute.prefix.clone() else {
335                return err(
336                    "UNSUPPORTED",
337                    format!("the prefix Saxon gives the attribute {attribute} in a namespace"),
338                );
339            };
340            if prefix == "xml" {
341                continue;
342            }
343            match lookup(&own, Some(&prefix)) {
344                Some(bound) if bound == namespace => {}
345                Some(_) => {
346                    let renamed = format!("{prefix}_{seq}");
347                    match lookup(&own, Some(&renamed)) {
348                        Some(bound) if bound == namespace => {}
349                        Some(_) => {
350                            return err(
351                                "UNSUPPORTED",
352                                format!("the prefix Saxon gives the attribute {attribute}"),
353                            );
354                        }
355                        None => own.push((Some(renamed.clone()), namespace)),
356                    }
357                    attribute.prefix = Some(renamed);
358                }
359                None => own.push((Some(prefix), namespace)),
360            }
361        }
362        Ok((name, attributes, own))
363    }
364}
365
366/// One open element of the result.
367#[derive(Debug)]
368struct Open {
369    /// The written qualified name, for the end tag.
370    tag: String,
371    /// How many entries of the namespace scope this element added.
372    bindings: usize,
373    /// The namespace nodes the element was given, when they are its own namespace nodes
374    /// ([`StartTag::given_unchanged`]): each is bound as it is in the scope after its
375    /// start tag, and so for a child given the same set.
376    given: Option<Arc<[NamespaceBinding]>>,
377    has_elements: bool,
378    has_text: bool,
379}
380
381/// Where [`XmlWriter`] puts the text it writes, and who reads the result as it is
382/// written.
383pub(crate) trait Target {
384    /// The text written since the previous call is a complete piece, to keep and clear
385    /// from `out`; or left in `out`, to which the writer appends.
386    fn commit(&mut self, out: &mut String) -> Result<()>;
387    /// Whether some text was taken from the writer.
388    fn has_taken(&self) -> bool;
389    /// The start of an element, its attributes as written.
390    fn start_element(&mut self, name: &QName, attributes: &[(QName, String)]);
391    /// The end of the innermost open element.
392    fn end_element(&mut self);
393    /// Character data inside the document element.
394    fn text(&mut self, text: &str);
395    /// A comment.
396    fn comment(&mut self, text: &str);
397    /// A processing instruction.
398    fn processing_instruction(&mut self, target: &str, data: &str);
399}
400
401/// The result as one string: the writer's own buffer.
402#[derive(Debug)]
403pub(crate) struct WholeText;
404
405impl Target for WholeText {
406    fn commit(&mut self, _out: &mut String) -> Result<()> {
407        Ok(())
408    }
409
410    fn has_taken(&self) -> bool {
411        false
412    }
413
414    fn start_element(&mut self, _name: &QName, _attributes: &[(QName, String)]) {}
415
416    fn end_element(&mut self) {}
417
418    fn text(&mut self, _text: &str) {}
419
420    fn comment(&mut self, _text: &str) {}
421
422    fn processing_instruction(&mut self, _target: &str, _data: &str) {}
423}
424
425/// The result kept as a [`CompactOutput`], read by an observer as it is written.
426pub(crate) struct Compact<'o> {
427    pub(crate) builder: CompactBuilder,
428    pub(crate) observer: &'o mut dyn ResultObserver,
429}
430
431impl std::fmt::Debug for Compact<'_> {
432    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
433        f.debug_struct("Compact")
434            .field("builder", &self.builder)
435            .finish_non_exhaustive()
436    }
437}
438
439impl Target for Compact<'_> {
440    fn commit(&mut self, out: &mut String) -> Result<()> {
441        self.builder.push(out)?;
442        out.clear();
443        Ok(())
444    }
445
446    fn has_taken(&self) -> bool {
447        !self.builder.is_empty()
448    }
449
450    fn start_element(&mut self, name: &QName, attributes: &[(QName, String)]) {
451        self.observer.start_element(name, attributes);
452    }
453
454    fn end_element(&mut self) {
455        self.observer.end_element();
456    }
457
458    fn text(&mut self, text: &str) {
459        self.observer.text(text);
460    }
461
462    fn comment(&mut self, text: &str) {
463        self.observer.comment(text);
464    }
465
466    fn processing_instruction(&mut self, target: &str, data: &str) {
467        self.observer.processing_instruction(target, data);
468    }
469}
470
471/// The order of namespace declarations in a start tag, as Saxon-HE 12.10 writes them
472/// (its `NamespaceMap` is sorted): by prefix, the default namespace first, prefixes
473/// compared as Java compares strings (UTF-16 code units).
474fn declaration_order(a: &(Option<String>, String), b: &(Option<String>, String)) -> Ordering {
475    let key = |p: &Option<String>| {
476        p.as_deref()
477            .unwrap_or("")
478            .encode_utf16()
479            .collect::<Vec<u16>>()
480    };
481    key(&a.0).cmp(&key(&b.0))
482}
483
484/// Writes the final result tree as XML text as it is produced, without building it,
485/// into its buffer, which the target keeps whole or takes a piece at a time: after an
486/// end tag or an empty element, and after a start tag that content follows.
487#[derive(Debug)]
488pub(crate) struct XmlWriter<T> {
489    out: String,
490    target: T,
491    settings: Serialization,
492    /// Whether the result may be a fragment rather than a document: text and several
493    /// elements at the top, as Saxon writes the content of `xsl:message`.
494    fragment: bool,
495    pending: Option<StartTag>,
496    open: Vec<Open>,
497    /// Namespace bindings in scope, innermost last: prefix (`None`: default) and URI.
498    scope: Vec<(Option<String>, String)>,
499    last_atomic: bool,
500}
501
502const INDENT: &str = "   ";
503
504impl<T: Target> XmlWriter<T> {
505    pub(crate) fn new(settings: Serialization, target: T) -> Self {
506        let mut out = String::new();
507        if !settings.omit_xml_declaration {
508            out.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"");
509            match settings.standalone {
510                Some(true) => out.push_str(" standalone=\"yes\""),
511                Some(false) => out.push_str(" standalone=\"no\""),
512                None => {}
513            }
514            out.push_str("?>");
515        }
516        Self {
517            out,
518            target,
519            settings,
520            fragment: false,
521            pending: None,
522            open: Vec::new(),
523            scope: Vec::new(),
524            last_atomic: false,
525        }
526    }
527
528    /// The text not taken by the target (all of it for [`WholeText`]), and the target.
529    pub(crate) fn finish(mut self) -> Result<(String, T)> {
530        self.flush()?;
531        if !self.open.is_empty() {
532            return err("INTERNAL", "unclosed element at the end of the result");
533        }
534        if self.settings.indent {
535            self.out.push('\n');
536        }
537        self.target.commit(&mut self.out)?;
538        Ok((self.out, self.target))
539    }
540
541    fn bound(&self, prefix: Option<&str>) -> Option<&str> {
542        self.scope
543            .iter()
544            .rev()
545            .find(|(p, _)| p.as_deref() == prefix)
546            .map(|(_, uri)| uri.as_str())
547    }
548
549    /// Whether each of the namespace nodes `given` is bound as it is in the scope, so
550    /// that a start tag with these as its own namespace nodes declares none. Without a
551    /// look at the scope when the parent element was given the same set.
552    fn all_bound(&self, given: &Arc<[NamespaceBinding]>) -> bool {
553        let parent_given = self.open.last().and_then(|o| o.given.as_ref());
554        if parent_given.is_some_and(|p| Arc::ptr_eq(p, given)) {
555            return true;
556        }
557        given.iter().all(|b| {
558            b.prefix.as_deref() == Some("xml")
559                || self.bound(b.prefix.as_deref()).unwrap_or("") == b.uri
560        })
561    }
562
563    /// Writes the pending start tag, its namespaces fixed up ([`StartTag::fix`]): the
564    /// declarations of the namespace nodes not in scope yet, sorted by prefix, then the
565    /// attributes. Bindings in scope that the element lacks are not undeclared (Saxon's
566    /// serializer does not), except the default namespace of an element in none.
567    fn flush(&mut self) -> Result<()> {
568        let Some(pending) = self.pending.take() else {
569            return Ok(());
570        };
571        let given = pending.given_unchanged().map(Arc::clone);
572        if given.as_ref().is_some_and(|g| self.all_bound(g)) {
573            // Fixup would change nothing, and each namespace node of the element is in
574            // scope already: no declaration, nothing to copy.
575            let StartTag {
576                name, attributes, ..
577            } = pending;
578            self.write_start_tag(&name, &attributes, &[], given);
579            return Ok(());
580        }
581        let (name, attributes, own) = pending.fix()?;
582        let mut declarations: Vec<Binding> = own
583            .into_iter()
584            .filter(|(prefix, uri)| {
585                prefix.as_deref() != Some("xml")
586                    && self.bound(prefix.as_deref()).unwrap_or("") != uri
587            })
588            .collect();
589        declarations.sort_by(declaration_order);
590        self.write_start_tag(&name, &attributes, &declarations, given);
591        Ok(())
592    }
593
594    /// Writes a start tag: its namespace declarations (added to the scope), then its
595    /// attributes; and opens the element. `given`: as [`Open::given`].
596    fn write_start_tag(
597        &mut self,
598        name: &QName,
599        attributes: &[(QName, String)],
600        declarations: &[Binding],
601        given: Option<Arc<[NamespaceBinding]>>,
602    ) {
603        let bindings_before = self.scope.len();
604        self.scope.extend(declarations.iter().cloned());
605        let mut tag = String::new();
606        if let Some(prefix) = &name.prefix {
607            tag.push_str(prefix);
608            tag.push(':');
609        }
610        tag.push_str(&name.local);
611        self.out.push('<');
612        self.out.push_str(&tag);
613        for (prefix, uri) in declarations {
614            self.out.push_str(" xmlns");
615            if let Some(prefix) = prefix {
616                self.out.push(':');
617                self.out.push_str(prefix);
618            }
619            self.out.push_str("=\"");
620            escape_attribute(&mut self.out, uri);
621            self.out.push('"');
622        }
623        for (name, value) in attributes {
624            self.out.push(' ');
625            if let Some(prefix) = &name.prefix {
626                self.out.push_str(prefix);
627                self.out.push(':');
628            }
629            self.out.push_str(&name.local);
630            self.out.push_str("=\"");
631            escape_attribute(&mut self.out, value);
632            self.out.push('"');
633        }
634        self.out.push('>');
635        self.target.start_element(name, attributes);
636        self.open.push(Open {
637            tag,
638            bindings: self.scope.len() - bindings_before,
639            given,
640            has_elements: false,
641            has_text: false,
642        });
643    }
644
645    /// Writes the pending start tag, if any, as a piece of its own: content follows, the
646    /// element is not empty.
647    fn flush_tag(&mut self) -> Result<()> {
648        if self.pending.is_some() {
649            self.flush()?;
650            self.target.commit(&mut self.out)?;
651        }
652        Ok(())
653    }
654
655    /// A line end and the indentation of the depth: whitespace in an element, the
656    /// innermost open one or the one just closed.
657    fn indent(&mut self) {
658        let start = self.out.len();
659        self.out.push('\n');
660        for _ in 0..self.open.len() {
661            self.out.push_str(INDENT);
662        }
663        self.target.text(&self.out[start..]);
664    }
665
666    /// Before an element, comment or processing instruction: indentation, unless in mixed
667    /// content.
668    fn before_markup(&mut self) {
669        if let Some(parent) = self.open.last_mut() {
670            parent.has_elements = true;
671            if !parent.has_text && self.settings.indent {
672                self.indent();
673            }
674        } else if self.settings.indent && (!self.out.is_empty() || self.target.has_taken()) {
675            self.out.push('\n');
676        }
677    }
678
679    fn write_text(&mut self, text: &str) -> Result<()> {
680        self.flush_tag()?;
681        if text.is_empty() {
682            return Ok(());
683        }
684        let Some(parent) = self.open.last_mut() else {
685            if self.fragment {
686                escape_text(&mut self.out, text);
687                return Ok(());
688            }
689            if !text.chars().all(|c| matches!(c, ' ' | '\t' | '\r' | '\n')) {
690                return err(
691                    "UNSUPPORTED",
692                    "text outside the document element of the result",
693                );
694            }
695            return Ok(());
696        };
697        parent.has_text = true;
698        escape_text(&mut self.out, text);
699        self.target.text(text);
700        Ok(())
701    }
702}
703
704/// The error for a namespace node whose prefix is already bound to another URI on its
705/// element.
706fn namespace_conflict(prefix: Option<&str>, uri: &str, other: &str) -> TransformError {
707    TransformError::new(
708        "XTDE0430",
709        format!(
710            "the namespace prefix {:?} is bound to {other:?} on the element, and a namespace node binds it to {uri:?}",
711            prefix.unwrap_or("")
712        ),
713    )
714}
715
716impl<T: Target> Sink for XmlWriter<T> {
717    fn start_element(&mut self, name: &QName, namespaces: &Arc<[NamespaceBinding]>) -> Result<()> {
718        self.flush_tag()?;
719        self.last_atomic = false;
720        self.before_markup();
721        self.pending = Some(StartTag::new(name, namespaces));
722        Ok(())
723    }
724
725    fn namespace(&mut self, prefix: Option<&str>, uri: &str) -> Result<()> {
726        self.last_atomic = false;
727        let Some(pending) = self.pending.as_mut() else {
728            return err(
729                "XTDE0410",
730                "a namespace node cannot be created after the children of the containing element",
731            );
732        };
733        pending.namespace(prefix, uri)
734    }
735
736    fn attribute(&mut self, name: &QName, value: &str) -> Result<()> {
737        self.last_atomic = false;
738        let Some(pending) = self.pending.as_mut() else {
739            return err(
740                "XTDE0410",
741                format!(
742                    "an attribute node ({name}) cannot be created after the children of the containing element"
743                ),
744            );
745        };
746        pending.attribute(name, value);
747        Ok(())
748    }
749
750    fn end_element(&mut self) -> Result<()> {
751        self.last_atomic = false;
752        if let Some(pending) = self.pending.take() {
753            // An empty element: written as `<name .../>`.
754            self.pending = Some(pending);
755            self.flush()?;
756            let Some(open) = self.open.pop() else {
757                return err("INTERNAL", "end of an element that is not open");
758            };
759            self.out.pop();
760            self.out.push_str("/>");
761            self.scope.truncate(self.scope.len() - open.bindings);
762            self.target.end_element();
763            return self.target.commit(&mut self.out);
764        }
765        let Some(open) = self.open.pop() else {
766            return err("INTERNAL", "end of an element that is not open");
767        };
768        if open.has_elements && !open.has_text && self.settings.indent {
769            self.indent();
770        }
771        self.out.push_str("</");
772        self.out.push_str(&open.tag);
773        self.out.push('>');
774        self.scope.truncate(self.scope.len() - open.bindings);
775        self.target.end_element();
776        self.target.commit(&mut self.out)
777    }
778
779    fn text(&mut self, text: &str) -> Result<()> {
780        self.last_atomic = false;
781        self.write_text(text)
782    }
783
784    fn comment(&mut self, text: &str) -> Result<()> {
785        self.flush_tag()?;
786        self.last_atomic = false;
787        self.before_markup();
788        self.out.push_str("<!--");
789        self.out.push_str(text);
790        self.out.push_str("-->");
791        self.target.comment(text);
792        Ok(())
793    }
794
795    fn processing_instruction(&mut self, target: &str, value: &str) -> Result<()> {
796        self.flush_tag()?;
797        self.last_atomic = false;
798        self.before_markup();
799        self.out.push_str("<?");
800        self.out.push_str(target);
801        if !value.is_empty() {
802            self.out.push(' ');
803            self.out.push_str(value);
804        }
805        self.out.push_str("?>");
806        self.target.processing_instruction(target, value);
807        Ok(())
808    }
809
810    fn item(&mut self, item: &Item) -> Result<()> {
811        match item {
812            Item::Atomic(_) => {
813                if self.last_atomic {
814                    self.write_text(" ")?;
815                }
816                self.write_text(&item.string_value())?;
817                self.last_atomic = true;
818                Ok(())
819            }
820            Item::Node(node) => {
821                self.last_atomic = false;
822                copy_node(self, node)
823            }
824        }
825    }
826}
827
828/// Whether Saxon's XML serializer writes a character as a character reference wherever it
829/// is: the C1 controls and DEL (U+007F to U+009F), and the line separator U+2028, which
830/// XML 1.1 normalizes as a line end. The reference is in lower-case hexadecimal.
831const fn written_as_reference(c: char) -> bool {
832    matches!(c, '\u{7f}'..='\u{9f}' | '\u{2028}')
833}
834
835fn push_reference(out: &mut String, c: char) {
836    use std::fmt::Write as _;
837    let _ = write!(out, "&#x{:x};", u32::from(c));
838}
839
840fn escape_text(out: &mut String, text: &str) {
841    for c in text.chars() {
842        match c {
843            '<' => out.push_str("&lt;"),
844            '>' => out.push_str("&gt;"),
845            '&' => out.push_str("&amp;"),
846            '\r' => out.push_str("&#xD;"),
847            c if written_as_reference(c) => push_reference(out, c),
848            c => out.push(c),
849        }
850    }
851}
852
853fn escape_attribute(out: &mut String, text: &str) {
854    for c in text.chars() {
855        match c {
856            '<' => out.push_str("&lt;"),
857            '>' => out.push_str("&gt;"),
858            '&' => out.push_str("&amp;"),
859            '"' => out.push_str("&#34;"),
860            '\t' => out.push_str("&#x9;"),
861            '\n' => out.push_str("&#xA;"),
862            '\r' => out.push_str("&#xD;"),
863            c if written_as_reference(c) => push_reference(out, c),
864            c => out.push(c),
865        }
866    }
867}
868
869/// Writes a tree as XML (`root` a document node or any node), with the serialization
870/// parameters `settings`; as a fragment (text and several elements at the top) with
871/// `fragment`.
872pub(crate) fn serialize(root: &Node, settings: Serialization, fragment: bool) -> Result<String> {
873    let mut writer = XmlWriter::new(settings, WholeText);
874    writer.fragment = fragment;
875    copy_node(&mut writer, root)?;
876    Ok(writer.finish()?.0)
877}
878
879/// Builds a tree: a temporary tree (a variable whose value is a sequence constructor,
880/// without `as`), a new document node; the final result tree; or the content of an
881/// element or a document node constructed in a sequence, a parentless element. The
882/// start tag of an element is kept until it is complete, then its namespaces fixed up as
883/// Saxon does ([`StartTag::fix`]): an element's namespace nodes are those it inherits
884/// from its parent and its own (a constructed element), or exactly its own (a copy).
885#[derive(Debug)]
886pub(crate) struct TreeSink {
887    builder: TreeBuilder,
888    last_atomic: bool,
889    /// The start tag not added yet, and whether it is a copy's.
890    pending: Option<(StartTag, bool)>,
891    /// The namespaces in scope on each open element, innermost last.
892    scopes: Vec<Scope>,
893    /// The namespaces of the start tags whose own namespace nodes were those given, as
894    /// worked out for the last of them (at most [`SCOPE_MEMO_SIZE`], the oldest dropped).
895    memo: Vec<ScopeMemo>,
896}
897
898/// The namespaces in scope on an element of a tree being built: shared by the elements
899/// of a tree that have the same, so that the scope of an element is known by its
900/// address.
901type Scope = Rc<[NamespaceBinding]>;
902
903/// The namespaces of an element ([`TreeSink::flush`]) whose own namespace nodes are the
904/// set `given` ([`StartTag::given_unchanged`]), copied or not, under a parent of scope
905/// `parent` (`None`: no parent element): its scope, and the namespace entries of its
906/// node. A function of these three alone, known by their addresses (kept alive here).
907#[derive(Debug)]
908struct ScopeMemo {
909    parent: Option<Scope>,
910    given: Arc<[NamespaceBinding]>,
911    copied: bool,
912    scope: Scope,
913    entries: Arc<[NamespaceBinding]>,
914}
915
916/// How many [`ScopeMemo`] a tree keeps: the few combinations of the literal result
917/// elements of a stylesheet that build it.
918const SCOPE_MEMO_SIZE: usize = 16;
919
920/// The namespaces in scope on an element, and the namespace entries of its node, from
921/// those of its parent and its own namespace nodes `own` once fixed up: a constructed
922/// element inherits its parent's (`copied` false), a copy has exactly its own. The
923/// entries are the bindings of its scope its parent's lacks, and the prefixes of its
924/// parent's it lacks undeclared (bound to the empty URI).
925fn child_scope<'a>(
926    parent: &[NamespaceBinding],
927    own: impl Iterator<Item = (Option<&'a str>, &'a str)>,
928    copied: bool,
929) -> (Vec<NamespaceBinding>, Vec<NamespaceBinding>) {
930    let mut scope: Vec<NamespaceBinding> = if copied { Vec::new() } else { parent.to_vec() };
931    for (prefix, uri) in own {
932        if prefix == Some("xml") {
933            continue;
934        }
935        scope.retain(|b| b.prefix.as_deref() != prefix);
936        scope.push(NamespaceBinding {
937            prefix: prefix.map(str::to_owned),
938            uri: uri.to_owned(),
939        });
940    }
941    scope.retain(|b| !b.uri.is_empty());
942    let mut entries: Vec<NamespaceBinding> = scope
943        .iter()
944        .filter(|b| !parent.contains(b))
945        .cloned()
946        .collect();
947    for binding in parent {
948        if !scope.iter().any(|b| b.prefix == binding.prefix) {
949            entries.push(NamespaceBinding {
950                prefix: binding.prefix.clone(),
951                uri: String::new(),
952            });
953        }
954    }
955    (scope, entries)
956}
957
958impl TreeSink {
959    /// A temporary tree: a document node.
960    pub(crate) fn new() -> Self {
961        Self::with(TreeBuilder::new())
962    }
963
964    /// A tree without document node, for one parentless node.
965    fn parentless() -> Self {
966        Self::with(TreeBuilder::parentless())
967    }
968
969    const fn with(builder: TreeBuilder) -> Self {
970        Self {
971            builder,
972            last_atomic: false,
973            pending: None,
974            scopes: Vec::new(),
975            memo: Vec::new(),
976        }
977    }
978
979    pub(crate) fn finish(self) -> Result<Rc<Document>> {
980        self.finish_with(None)
981    }
982
983    /// The finished tree, its nodes with the base URI `base_uri`.
984    pub(crate) fn finish_with(mut self, base_uri: Option<String>) -> Result<Rc<Document>> {
985        self.flush()?;
986        self.builder
987            .finish(None, base_uri)
988            .map_err(|e| TransformError::new("INTERNAL", e.message()))
989    }
990
991    /// Adds the pending start tag to the tree: the element, with its namespace entries
992    /// ([`child_scope`]); then its attributes.
993    fn flush(&mut self) -> Result<()> {
994        let Some((tag, copied)) = self.pending.take() else {
995            return Ok(());
996        };
997        let parent = self.scopes.last().cloned();
998        let (name, attributes, scope, entries) = if let Some(given) = tag.given_unchanged() {
999            let given = Arc::clone(given);
1000            let (scope, entries) = self.memoized_scope(parent, given, copied);
1001            let StartTag {
1002                name, attributes, ..
1003            } = tag;
1004            (name, attributes, scope, entries)
1005        } else {
1006            let (name, attributes, own) = tag.fix()?;
1007            let own = own.iter().map(|(p, u)| (p.as_deref(), u.as_str()));
1008            let parent = parent.as_deref().unwrap_or_default();
1009            let (scope, entries) = child_scope(parent, own, copied);
1010            (name, attributes, scope.into(), entries.into())
1011        };
1012        self.scopes.push(scope);
1013        self.builder
1014            .start_element_with_namespaces(name, entries)
1015            .map_err(|e| tree_error(&e))?;
1016        for (name, value) in attributes {
1017            self.builder
1018                .attribute(name, &value)
1019                .map_err(|e| tree_error(&e))?;
1020        }
1021        Ok(())
1022    }
1023
1024    /// The scope and the namespace entries of an element whose own namespace nodes are
1025    /// `given`, from [`TreeSink::memo`] or worked out ([`child_scope`]) and kept. A scope
1026    /// equal to the parent's is the parent's.
1027    fn memoized_scope(
1028        &mut self,
1029        parent: Option<Scope>,
1030        given: Arc<[NamespaceBinding]>,
1031        copied: bool,
1032    ) -> (Scope, Arc<[NamespaceBinding]>) {
1033        let found = self.memo.iter().find(|m| {
1034            m.copied == copied
1035                && Arc::ptr_eq(&m.given, &given)
1036                && match (&m.parent, &parent) {
1037                    (None, None) => true,
1038                    (Some(a), Some(b)) => Rc::ptr_eq(a, b),
1039                    _ => false,
1040                }
1041        });
1042        if let Some(m) = found {
1043            return (Rc::clone(&m.scope), Arc::clone(&m.entries));
1044        }
1045        let own = given.iter().map(|b| (b.prefix.as_deref(), b.uri.as_str()));
1046        let parent_bindings = parent.as_deref().unwrap_or_default();
1047        let (scope, entries) = child_scope(parent_bindings, own, copied);
1048        let scope: Scope = match &parent {
1049            Some(p) if **p == *scope => Rc::clone(p),
1050            _ => scope.into(),
1051        };
1052        let entries: Arc<[NamespaceBinding]> = entries.into();
1053        let memo = ScopeMemo {
1054            parent,
1055            given,
1056            copied,
1057            scope: Rc::clone(&scope),
1058            entries: Arc::clone(&entries),
1059        };
1060        if self.memo.len() == SCOPE_MEMO_SIZE {
1061            // The oldest goes.
1062            self.memo.remove(0);
1063        }
1064        self.memo.push(memo);
1065        (scope, entries)
1066    }
1067
1068    /// The start tag being built, or the error for an attribute or a namespace node that
1069    /// comes too late.
1070    fn start_tag(&mut self, what: &str) -> Result<&mut StartTag> {
1071        match self.pending.as_mut() {
1072            Some((tag, _)) => Ok(tag),
1073            None => err(
1074                "XTDE0410",
1075                format!(
1076                    "{what} cannot be created after the children of the containing element, or at the top of a temporary tree"
1077                ),
1078            ),
1079        }
1080    }
1081}
1082
1083fn tree_error(e: &einvoice_xpath_eval::DocumentError) -> TransformError {
1084    TransformError::new("INTERNAL", e.message())
1085}
1086
1087impl Sink for TreeSink {
1088    fn start_element(&mut self, name: &QName, namespaces: &Arc<[NamespaceBinding]>) -> Result<()> {
1089        self.flush()?;
1090        self.last_atomic = false;
1091        self.pending = Some((StartTag::new(name, namespaces), false));
1092        Ok(())
1093    }
1094
1095    fn start_copied_element(
1096        &mut self,
1097        name: &QName,
1098        namespaces: &Arc<[NamespaceBinding]>,
1099    ) -> Result<()> {
1100        self.flush()?;
1101        self.last_atomic = false;
1102        self.pending = Some((StartTag::new(name, namespaces), true));
1103        Ok(())
1104    }
1105
1106    fn namespace(&mut self, prefix: Option<&str>, uri: &str) -> Result<()> {
1107        self.last_atomic = false;
1108        self.start_tag("a namespace node")?.namespace(prefix, uri)
1109    }
1110
1111    fn attribute(&mut self, name: &QName, value: &str) -> Result<()> {
1112        self.last_atomic = false;
1113        if let Some((tag, _)) = self.pending.as_mut() {
1114            tag.attribute(name, value);
1115            return Ok(());
1116        }
1117        // The error, its message written only now.
1118        self.start_tag(&format!("an attribute node ({name})"))
1119            .map(|_| ())
1120    }
1121
1122    fn end_element(&mut self) -> Result<()> {
1123        self.flush()?;
1124        self.last_atomic = false;
1125        self.scopes.pop();
1126        self.builder.end_element().map_err(|e| tree_error(&e))
1127    }
1128
1129    fn text(&mut self, text: &str) -> Result<()> {
1130        self.flush()?;
1131        self.last_atomic = false;
1132        self.builder.text(text).map_err(|e| tree_error(&e))
1133    }
1134
1135    fn comment(&mut self, text: &str) -> Result<()> {
1136        self.flush()?;
1137        self.last_atomic = false;
1138        self.builder.comment(text).map_err(|e| tree_error(&e))
1139    }
1140
1141    fn processing_instruction(&mut self, target: &str, value: &str) -> Result<()> {
1142        self.flush()?;
1143        self.last_atomic = false;
1144        self.builder
1145            .processing_instruction(target, value)
1146            .map_err(|e| tree_error(&e))
1147    }
1148
1149    fn start_document(&mut self) -> Result<()> {
1150        self.flush()?;
1151        self.last_atomic = false;
1152        Ok(())
1153    }
1154
1155    fn end_document(&mut self) -> Result<()> {
1156        self.flush()?;
1157        self.last_atomic = false;
1158        Ok(())
1159    }
1160
1161    fn item(&mut self, item: &Item) -> Result<()> {
1162        match item {
1163            Item::Atomic(_) => {
1164                let was_atomic = self.last_atomic;
1165                if was_atomic {
1166                    self.text(" ")?;
1167                }
1168                self.text(&item.string_value())?;
1169                self.last_atomic = true;
1170                Ok(())
1171            }
1172            Item::Node(node) => {
1173                self.flush()?;
1174                self.last_atomic = false;
1175                copy_node(self, node)
1176            }
1177        }
1178    }
1179}
1180
1181/// Simple content (XSLT 2.0 section 5.7.2): zero-length text nodes dropped, adjacent
1182/// text nodes merged, every item atomized to a string, the strings joined with a
1183/// separator.
1184#[derive(Debug, Default)]
1185pub(crate) struct TextSink {
1186    parts: Vec<String>,
1187    /// Whether the last part is a text node that the next one can merge with.
1188    last_text: bool,
1189    /// Depth inside a constructed element or document node, whose string value is one
1190    /// part.
1191    depth: usize,
1192}
1193
1194impl TextSink {
1195    pub(crate) fn new() -> Self {
1196        Self::default()
1197    }
1198
1199    fn push_part(&mut self, value: &str, is_text: bool) {
1200        if is_text && self.last_text {
1201            if let Some(last) = self.parts.last_mut() {
1202                last.push_str(value);
1203            }
1204        } else {
1205            self.parts.push(value.to_owned());
1206        }
1207        self.last_text = is_text;
1208    }
1209
1210    /// The joined value.
1211    pub(crate) fn finish(self, separator: &str) -> String {
1212        if self.parts.len() == 1 {
1213            return self.parts.into_iter().next().unwrap_or_default();
1214        }
1215        self.parts.join(separator)
1216    }
1217
1218    fn open(&mut self) {
1219        if self.depth == 0 {
1220            self.parts.push(String::new());
1221            self.last_text = false;
1222        }
1223        self.depth += 1;
1224    }
1225}
1226
1227impl Sink for TextSink {
1228    fn start_element(
1229        &mut self,
1230        _name: &QName,
1231        _namespaces: &Arc<[NamespaceBinding]>,
1232    ) -> Result<()> {
1233        self.open();
1234        Ok(())
1235    }
1236
1237    fn namespace(&mut self, _prefix: Option<&str>, uri: &str) -> Result<()> {
1238        if self.depth == 0 {
1239            self.push_part(uri, false);
1240        }
1241        Ok(())
1242    }
1243
1244    fn attribute(&mut self, _name: &QName, value: &str) -> Result<()> {
1245        if self.depth == 0 {
1246            self.push_part(value, false);
1247        }
1248        Ok(())
1249    }
1250
1251    fn end_element(&mut self) -> Result<()> {
1252        self.depth = self.depth.saturating_sub(1);
1253        Ok(())
1254    }
1255
1256    fn text(&mut self, text: &str) -> Result<()> {
1257        if self.depth > 0 {
1258            if let Some(last) = self.parts.last_mut() {
1259                last.push_str(text);
1260            }
1261        } else if !text.is_empty() {
1262            self.push_part(text, true);
1263        }
1264        Ok(())
1265    }
1266
1267    fn comment(&mut self, text: &str) -> Result<()> {
1268        if self.depth == 0 {
1269            self.push_part(text, false);
1270        }
1271        Ok(())
1272    }
1273
1274    fn processing_instruction(&mut self, _target: &str, value: &str) -> Result<()> {
1275        if self.depth == 0 {
1276            self.push_part(value, false);
1277        }
1278        Ok(())
1279    }
1280
1281    fn start_document(&mut self) -> Result<()> {
1282        self.open();
1283        Ok(())
1284    }
1285
1286    fn end_document(&mut self) -> Result<()> {
1287        self.depth = self.depth.saturating_sub(1);
1288        Ok(())
1289    }
1290
1291    fn item(&mut self, item: &Item) -> Result<()> {
1292        if self.depth > 0 {
1293            return err(
1294                "INTERNAL",
1295                "an item inside an element constructed in simple content",
1296            );
1297        }
1298        let is_text = matches!(item, Item::Node(n) if n.kind() == NodeKind::Text);
1299        let value = item.string_value();
1300        if is_text && value.is_empty() {
1301            return Ok(());
1302        }
1303        self.push_part(&value, is_text);
1304        Ok(())
1305    }
1306}
1307
1308/// A sequence of items (function bodies, variables and parameters with `as`). A node
1309/// constructed at the top of the sequence is a new parentless node: an element or a
1310/// document node is built with its content, as complex content; each attribute, text
1311/// (each instruction's, not merged with the next, and kept when of zero length, as Saxon
1312/// does), comment and processing instruction is a node of its own. Items of
1313/// `xsl:sequence` are kept as they are (nodes are not copied).
1314#[derive(Debug, Default)]
1315pub(crate) struct SequenceSink {
1316    pub(crate) items: Vec<Item>,
1317    /// The element or document node being constructed at the top, and how many
1318    /// elements and document nodes are open in it (boxed: a function call holds a sink
1319    /// on the stack of each level of recursion).
1320    open: Option<Box<(TreeSink, usize)>>,
1321}
1322
1323impl SequenceSink {
1324    /// The tree being constructed, if any.
1325    fn tree(&mut self) -> Option<&mut TreeSink> {
1326        self.open.as_mut().map(|e| &mut e.0)
1327    }
1328
1329    /// A parentless node built by `build`.
1330    fn push_parentless(
1331        &mut self,
1332        build: impl FnOnce(
1333            &mut TreeBuilder,
1334        ) -> std::result::Result<(), einvoice_xpath_eval::DocumentError>,
1335    ) -> Result<()> {
1336        let mut builder = TreeBuilder::parentless();
1337        build(&mut builder).map_err(|e| tree_error(&e))?;
1338        let tree = builder
1339            .finish(None, None)
1340            .map_err(|e| TransformError::new("INTERNAL", e.message()))?;
1341        self.items.push(Item::Node(tree.root()));
1342        Ok(())
1343    }
1344
1345    /// One construction closed: the tree is an item once the outermost one is.
1346    fn close(&mut self) -> Result<()> {
1347        let Some(open) = self.open.as_mut() else {
1348            return err("INTERNAL", "end of a node that is not open");
1349        };
1350        open.1 -= 1;
1351        if open.1 == 0
1352            && let Some(open) = self.open.take()
1353        {
1354            self.items.push(Item::Node(open.0.finish()?.root()));
1355        }
1356        Ok(())
1357    }
1358}
1359
1360impl Sink for SequenceSink {
1361    fn start_element(&mut self, name: &QName, namespaces: &Arc<[NamespaceBinding]>) -> Result<()> {
1362        let open = self
1363            .open
1364            .get_or_insert_with(|| Box::new((TreeSink::parentless(), 0)));
1365        open.1 += 1;
1366        open.0.start_element(name, namespaces)
1367    }
1368
1369    fn start_copied_element(
1370        &mut self,
1371        name: &QName,
1372        namespaces: &Arc<[NamespaceBinding]>,
1373    ) -> Result<()> {
1374        let open = self
1375            .open
1376            .get_or_insert_with(|| Box::new((TreeSink::parentless(), 0)));
1377        open.1 += 1;
1378        open.0.start_copied_element(name, namespaces)
1379    }
1380
1381    fn namespace(&mut self, prefix: Option<&str>, uri: &str) -> Result<()> {
1382        if let Some(tree) = self.tree() {
1383            return tree.namespace(prefix, uri);
1384        }
1385        err(
1386            "UNSUPPORTED",
1387            "a parentless namespace node constructed in a sequence is not supported",
1388        )
1389    }
1390
1391    fn attribute(&mut self, name: &QName, value: &str) -> Result<()> {
1392        if let Some(tree) = self.tree() {
1393            return tree.attribute(name, value);
1394        }
1395        self.push_parentless(|b| b.attribute(name.clone(), value))
1396    }
1397
1398    fn end_element(&mut self) -> Result<()> {
1399        let Some(open) = self.open.as_mut() else {
1400            return err("INTERNAL", "end of an element that is not open");
1401        };
1402        open.0.end_element()?;
1403        self.close()
1404    }
1405
1406    fn text(&mut self, text: &str) -> Result<()> {
1407        if let Some(tree) = self.tree() {
1408            return tree.text(text);
1409        }
1410        self.push_parentless(|b| b.text(text))
1411    }
1412
1413    fn comment(&mut self, text: &str) -> Result<()> {
1414        if let Some(tree) = self.tree() {
1415            return tree.comment(text);
1416        }
1417        self.push_parentless(|b| b.comment(text))
1418    }
1419
1420    fn processing_instruction(&mut self, target: &str, value: &str) -> Result<()> {
1421        if let Some(tree) = self.tree() {
1422            return tree.processing_instruction(target, value);
1423        }
1424        self.push_parentless(|b| b.processing_instruction(target, value))
1425    }
1426
1427    fn start_document(&mut self) -> Result<()> {
1428        let open = self
1429            .open
1430            .get_or_insert_with(|| Box::new((TreeSink::new(), 0)));
1431        open.1 += 1;
1432        open.0.start_document()
1433    }
1434
1435    fn end_document(&mut self) -> Result<()> {
1436        let Some(open) = self.open.as_mut() else {
1437            return err("INTERNAL", "end of a document node that is not open");
1438        };
1439        open.0.end_document()?;
1440        self.close()
1441    }
1442
1443    fn item(&mut self, item: &Item) -> Result<()> {
1444        if let Some(tree) = self.tree() {
1445            return tree.item(item);
1446        }
1447        self.items.push(item.clone());
1448        Ok(())
1449    }
1450}
1451
1452/// Whether the name of a computed attribute or element is a lexical `QName`: its prefix
1453/// and local part.
1454fn lexical_qname(text: &str) -> Option<(Option<&str>, &str)> {
1455    let text = text.trim_matches(einvoice_xpath::is_xml_whitespace);
1456    let (prefix, local) = match text.split_once(':') {
1457        Some((p, l)) => (Some(p), l),
1458        None => (None, text),
1459    };
1460    (einvoice_xpath::is_ncname(local) && prefix.is_none_or(einvoice_xpath::is_ncname))
1461        .then_some((prefix, local))
1462}
1463
1464/// The name of a computed attribute (`xsl:attribute`): a lexical `QName`, in the namespace
1465/// of `namespace` when given (a prefix of the name is kept; an empty namespace means no
1466/// namespace and no prefix), else in the namespace its prefix has among the namespaces
1467/// in scope on the instruction (no namespace without prefix).
1468pub(crate) fn attribute_name(
1469    text: &str,
1470    namespace: Option<&str>,
1471    namespaces: &[NamespaceBinding],
1472) -> Result<QName> {
1473    let Some((prefix, local)) = lexical_qname(text) else {
1474        return err(
1475            "XTDE0850",
1476            format!("invalid attribute name {text:?} in xsl:attribute"),
1477        );
1478    };
1479    if prefix.is_none() && local == "xmlns" {
1480        return err("XTDE0855", "an attribute cannot be named xmlns");
1481    }
1482    if let Some(uri) = namespace {
1483        if uri.is_empty() {
1484            return Ok(QName::local(local));
1485        }
1486        let Some(prefix) = prefix else {
1487            return err(
1488                "UNSUPPORTED",
1489                format!(
1490                    "the prefix Saxon chooses for an attribute {local:?} in the namespace {uri:?} given without one"
1491                ),
1492            );
1493        };
1494        return Ok(QName {
1495            prefix: Some(prefix.to_owned()),
1496            namespace: Some(uri.to_owned()),
1497            local: local.to_owned(),
1498        });
1499    }
1500    let namespace = match prefix {
1501        None => None,
1502        Some("xml") => Some(XML_NAMESPACE.to_owned()),
1503        Some(p) => Some(
1504            namespaces
1505                .iter()
1506                .find(|ns| ns.prefix.as_deref() == Some(p))
1507                .map(|ns| ns.uri.clone())
1508                .ok_or_else(|| {
1509                    TransformError::new(
1510                        "XTDE0860",
1511                        format!("prefix {p:?} of attribute name {text:?} is not declared"),
1512                    )
1513                })?,
1514        ),
1515    };
1516    Ok(QName {
1517        prefix: prefix.map(str::to_owned),
1518        namespace,
1519        local: local.to_owned(),
1520    })
1521}
1522
1523/// The name of a computed element (`xsl:element`): a lexical `QName`, in the namespace of
1524/// `namespace` when given (a prefix of the name is kept; an empty namespace means no
1525/// namespace and no prefix), else in the namespace its prefix, or the default namespace
1526/// without one, has among the namespaces in scope on the instruction.
1527pub(crate) fn element_name(
1528    text: &str,
1529    namespace: Option<&str>,
1530    namespaces: &[NamespaceBinding],
1531) -> Result<QName> {
1532    let Some((prefix, local)) = lexical_qname(text) else {
1533        return err(
1534            "XTDE0820",
1535            format!("invalid element name {text:?} in xsl:element"),
1536        );
1537    };
1538    if let Some(uri) = namespace {
1539        return Ok(QName {
1540            prefix: prefix.filter(|_| !uri.is_empty()).map(str::to_owned),
1541            namespace: (!uri.is_empty()).then(|| uri.to_owned()),
1542            local: local.to_owned(),
1543        });
1544    }
1545    let namespace = match prefix {
1546        Some("xml") => Some(XML_NAMESPACE.to_owned()),
1547        _ => namespaces
1548            .iter()
1549            .find(|ns| ns.prefix.as_deref() == prefix)
1550            .map(|ns| ns.uri.clone())
1551            .filter(|uri| !uri.is_empty()),
1552    };
1553    if prefix.is_some() && namespace.is_none() {
1554        return err(
1555            "XTDE0830",
1556            format!("the prefix of element name {text:?} is not declared"),
1557        );
1558    }
1559    Ok(QName {
1560        prefix: prefix.map(str::to_owned),
1561        namespace,
1562        local: local.to_owned(),
1563    })
1564}