1use 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
31pub(crate) trait Sink {
33 fn start_element(&mut self, name: &QName, namespaces: &Arc<[NamespaceBinding]>) -> Result<()>;
36 fn start_copied_element(
42 &mut self,
43 name: &QName,
44 namespaces: &Arc<[NamespaceBinding]>,
45 ) -> Result<()> {
46 self.start_element(name, namespaces)
47 }
48 fn namespace(&mut self, prefix: Option<&str>, uri: &str) -> Result<()>;
51 fn attribute(&mut self, name: &QName, value: &str) -> Result<()>;
53 fn end_element(&mut self) -> Result<()>;
55 fn text(&mut self, text: &str) -> Result<()>;
57 fn comment(&mut self, text: &str) -> Result<()>;
59 fn processing_instruction(&mut self, target: &str, value: &str) -> Result<()>;
61 fn start_document(&mut self) -> Result<()> {
64 Ok(())
65 }
66 fn end_document(&mut self) -> Result<()> {
68 Ok(())
69 }
70 fn item(&mut self, item: &Item) -> Result<()>;
72}
73
74pub(crate) fn copy_node(sink: &mut dyn Sink, node: &Node) -> Result<()> {
79 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
149pub struct Serialization {
150 pub indent: bool,
152 pub omit_xml_declaration: bool,
154 pub standalone: Option<bool>,
156}
157
158type Binding = (Option<String>, String);
161
162type FixedTag = (QName, Vec<(QName, String)>, Vec<Binding>);
165
166#[derive(Debug)]
169struct StartTag {
170 name: QName,
171 attributes: Vec<(QName, String)>,
172 given: Arc<[NamespaceBinding]>,
175 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 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 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 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 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 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#[derive(Debug)]
368struct Open {
369 tag: String,
371 bindings: usize,
373 given: Option<Arc<[NamespaceBinding]>>,
377 has_elements: bool,
378 has_text: bool,
379}
380
381pub(crate) trait Target {
384 fn commit(&mut self, out: &mut String) -> Result<()>;
387 fn has_taken(&self) -> bool;
389 fn start_element(&mut self, name: &QName, attributes: &[(QName, String)]);
391 fn end_element(&mut self);
393 fn text(&mut self, text: &str);
395 fn comment(&mut self, text: &str);
397 fn processing_instruction(&mut self, target: &str, data: &str);
399}
400
401#[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
425pub(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
471fn 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#[derive(Debug)]
488pub(crate) struct XmlWriter<T> {
489 out: String,
490 target: T,
491 settings: Serialization,
492 fragment: bool,
495 pending: Option<StartTag>,
496 open: Vec<Open>,
497 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 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 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 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 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 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 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 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 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
704fn 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 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
828const 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("<"),
844 '>' => out.push_str(">"),
845 '&' => out.push_str("&"),
846 '\r' => out.push_str("
"),
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("<"),
857 '>' => out.push_str(">"),
858 '&' => out.push_str("&"),
859 '"' => out.push_str("""),
860 '\t' => out.push_str("	"),
861 '\n' => out.push_str("
"),
862 '\r' => out.push_str("
"),
863 c if written_as_reference(c) => push_reference(out, c),
864 c => out.push(c),
865 }
866 }
867}
868
869pub(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#[derive(Debug)]
886pub(crate) struct TreeSink {
887 builder: TreeBuilder,
888 last_atomic: bool,
889 pending: Option<(StartTag, bool)>,
891 scopes: Vec<Scope>,
893 memo: Vec<ScopeMemo>,
896}
897
898type Scope = Rc<[NamespaceBinding]>;
902
903#[derive(Debug)]
908struct ScopeMemo {
909 parent: Option<Scope>,
910 given: Arc<[NamespaceBinding]>,
911 copied: bool,
912 scope: Scope,
913 entries: Arc<[NamespaceBinding]>,
914}
915
916const SCOPE_MEMO_SIZE: usize = 16;
919
920fn 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 pub(crate) fn new() -> Self {
961 Self::with(TreeBuilder::new())
962 }
963
964 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 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 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 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 self.memo.remove(0);
1063 }
1064 self.memo.push(memo);
1065 (scope, entries)
1066 }
1067
1068 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 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#[derive(Debug, Default)]
1185pub(crate) struct TextSink {
1186 parts: Vec<String>,
1187 last_text: bool,
1189 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 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#[derive(Debug, Default)]
1315pub(crate) struct SequenceSink {
1316 pub(crate) items: Vec<Item>,
1317 open: Option<Box<(TreeSink, usize)>>,
1321}
1322
1323impl SequenceSink {
1324 fn tree(&mut self) -> Option<&mut TreeSink> {
1326 self.open.as_mut().map(|e| &mut e.0)
1327 }
1328
1329 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 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
1452fn 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
1464pub(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
1523pub(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}