use std::cmp::Ordering;
use std::rc::Rc;
use std::sync::Arc;
use einvoice_xpath::{QName, XML_NAMESPACE};
use einvoice_xpath_eval::tree::Axis;
use einvoice_xpath_eval::{Document, Item, Node, NodeKind, TreeBuilder};
use einvoice_xslt::NamespaceBinding;
use crate::error::{Result, TransformError, err};
use crate::output::{CompactBuilder, ResultObserver};
pub(crate) trait Sink {
fn start_element(&mut self, name: &QName, namespaces: &Arc<[NamespaceBinding]>) -> Result<()>;
fn start_copied_element(
&mut self,
name: &QName,
namespaces: &Arc<[NamespaceBinding]>,
) -> Result<()> {
self.start_element(name, namespaces)
}
fn namespace(&mut self, prefix: Option<&str>, uri: &str) -> Result<()>;
fn attribute(&mut self, name: &QName, value: &str) -> Result<()>;
fn end_element(&mut self) -> Result<()>;
fn text(&mut self, text: &str) -> Result<()>;
fn comment(&mut self, text: &str) -> Result<()>;
fn processing_instruction(&mut self, target: &str, value: &str) -> Result<()>;
fn start_document(&mut self) -> Result<()> {
Ok(())
}
fn end_document(&mut self) -> Result<()> {
Ok(())
}
fn item(&mut self, item: &Item) -> Result<()>;
}
pub(crate) fn copy_node(sink: &mut dyn Sink, node: &Node) -> Result<()> {
let mut open: Vec<(Axis, bool)> = Vec::new();
let mut next = Some(node.clone());
loop {
if let Some(node) = next.take() {
match node.kind() {
NodeKind::Document => {
sink.start_document()?;
open.push((node.children(), false));
}
NodeKind::Element => {
let Some(name) = node.name() else {
return err("INTERNAL", "element without name");
};
let namespaces: Arc<[NamespaceBinding]> = node.namespaces_in_scope().into();
sink.start_copied_element(name, &namespaces)?;
for attribute in node.attributes() {
copy_attribute(sink, &attribute)?;
}
open.push((node.children(), true));
}
NodeKind::Attribute => copy_attribute(sink, &node)?,
NodeKind::Text => sink.text(&node.string_value())?,
NodeKind::Comment => sink.comment(&node.string_value())?,
NodeKind::ProcessingInstruction => {
let target = node.name().map_or("", |n| n.local.as_str());
sink.processing_instruction(target, &node.string_value())?;
}
}
}
let Some((children, _)) = open.last_mut() else {
return Ok(());
};
match children.next() {
Some(child) => next = Some(child),
None => {
if let Some((_, element)) = open.pop() {
if element {
sink.end_element()?;
} else {
sink.end_document()?;
}
}
}
}
}
}
fn copy_attribute(sink: &mut dyn Sink, attribute: &Node) -> Result<()> {
let Some(name) = attribute.name() else {
return err("INTERNAL", "attribute without name");
};
sink.attribute(name, &attribute.string_value())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Serialization {
pub indent: bool,
pub omit_xml_declaration: bool,
pub standalone: Option<bool>,
}
type Binding = (Option<String>, String);
type FixedTag = (QName, Vec<(QName, String)>, Vec<Binding>);
#[derive(Debug)]
struct StartTag {
name: QName,
attributes: Vec<(QName, String)>,
given: Arc<[NamespaceBinding]>,
added: Vec<Binding>,
}
impl StartTag {
fn new(name: &QName, given: &Arc<[NamespaceBinding]>) -> Self {
Self {
name: name.clone(),
attributes: Vec::new(),
given: Arc::clone(given),
added: Vec::new(),
}
}
fn own(&self, prefix: Option<&str>) -> Option<&str> {
self.added
.iter()
.find(|(p, _)| p.as_deref() == prefix)
.map(|(_, u)| u.as_str())
.or_else(|| {
self.given
.iter()
.find(|b| b.prefix.as_deref() == prefix)
.map(|b| b.uri.as_str())
})
}
fn namespace(&mut self, prefix: Option<&str>, uri: &str) -> Result<()> {
if prefix.is_none() && self.name.namespace.is_none() {
return err(
"XTDE0440",
format!(
"a default namespace node ({uri:?}) on the element {}, which is in no namespace",
self.name
),
);
}
match self.own(prefix) {
Some(existing) if existing == uri => Ok(()),
Some(existing) => Err(namespace_conflict(prefix, uri, existing)),
None => {
self.added.push((prefix.map(str::to_owned), uri.to_owned()));
Ok(())
}
}
}
fn attribute(&mut self, name: &QName, value: &str) {
if let Some(existing) = self
.attributes
.iter_mut()
.find(|(n, _)| n.same_expanded_name(name))
{
existing.0 = name.clone();
value.clone_into(&mut existing.1);
} else {
self.attributes.push((name.clone(), value.to_owned()));
}
}
fn fix(self) -> Result<FixedTag> {
let Self {
mut name,
mut attributes,
given,
added,
} = self;
let mut own: Vec<Binding> = given
.iter()
.map(|b| (b.prefix.clone(), b.uri.clone()))
.filter(|(p, _)| !added.iter().any(|(q, _)| q == p))
.collect();
own.extend(added);
let lookup = |own: &[Binding], prefix: Option<&str>| {
own.iter()
.find(|(p, _)| p.as_deref() == prefix)
.map(|(_, u)| u.clone())
};
let uri = name.namespace.clone().unwrap_or_default();
if name.prefix.as_deref() != Some("xml") {
match lookup(&own, name.prefix.as_deref()) {
Some(bound) if bound == uri => {}
Some(_) => {
let Some(prefix) = name.prefix.clone() else {
return err(
"UNSUPPORTED",
format!(
"the element {name} in a namespace other than its default namespace node"
),
);
};
let renamed = format!("{prefix}_0");
match lookup(&own, Some(&renamed)) {
Some(bound) if bound == uri => {}
Some(_) => {
return err(
"UNSUPPORTED",
format!("the prefix Saxon gives the element {name}"),
);
}
None => own.push((Some(renamed.clone()), uri.clone())),
}
name.prefix = Some(renamed);
}
None => own.push((name.prefix.clone(), uri)),
}
}
for (seq, (attribute, _)) in (1_usize..).zip(attributes.iter_mut()) {
let Some(namespace) = attribute.namespace.clone() else {
continue;
};
let Some(prefix) = attribute.prefix.clone() else {
return err(
"UNSUPPORTED",
format!("the prefix Saxon gives the attribute {attribute} in a namespace"),
);
};
if prefix == "xml" {
continue;
}
match lookup(&own, Some(&prefix)) {
Some(bound) if bound == namespace => {}
Some(_) => {
let renamed = format!("{prefix}_{seq}");
match lookup(&own, Some(&renamed)) {
Some(bound) if bound == namespace => {}
Some(_) => {
return err(
"UNSUPPORTED",
format!("the prefix Saxon gives the attribute {attribute}"),
);
}
None => own.push((Some(renamed.clone()), namespace)),
}
attribute.prefix = Some(renamed);
}
None => own.push((Some(prefix), namespace)),
}
}
Ok((name, attributes, own))
}
}
#[derive(Debug)]
struct Open {
tag: String,
bindings: usize,
has_elements: bool,
has_text: bool,
}
pub(crate) trait Target {
fn commit(&mut self, out: &mut String) -> Result<()>;
fn has_taken(&self) -> bool;
fn start_element(&mut self, name: &QName, attributes: &[(QName, String)]);
fn end_element(&mut self);
fn text(&mut self, text: &str);
fn comment(&mut self, text: &str);
fn processing_instruction(&mut self, target: &str, data: &str);
}
#[derive(Debug)]
pub(crate) struct WholeText;
impl Target for WholeText {
fn commit(&mut self, _out: &mut String) -> Result<()> {
Ok(())
}
fn has_taken(&self) -> bool {
false
}
fn start_element(&mut self, _name: &QName, _attributes: &[(QName, String)]) {}
fn end_element(&mut self) {}
fn text(&mut self, _text: &str) {}
fn comment(&mut self, _text: &str) {}
fn processing_instruction(&mut self, _target: &str, _data: &str) {}
}
pub(crate) struct Compact<'o> {
pub(crate) builder: CompactBuilder,
pub(crate) observer: &'o mut dyn ResultObserver,
}
impl std::fmt::Debug for Compact<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Compact")
.field("builder", &self.builder)
.finish_non_exhaustive()
}
}
impl Target for Compact<'_> {
fn commit(&mut self, out: &mut String) -> Result<()> {
self.builder.push(out)?;
out.clear();
Ok(())
}
fn has_taken(&self) -> bool {
!self.builder.is_empty()
}
fn start_element(&mut self, name: &QName, attributes: &[(QName, String)]) {
self.observer.start_element(name, attributes);
}
fn end_element(&mut self) {
self.observer.end_element();
}
fn text(&mut self, text: &str) {
self.observer.text(text);
}
fn comment(&mut self, text: &str) {
self.observer.comment(text);
}
fn processing_instruction(&mut self, target: &str, data: &str) {
self.observer.processing_instruction(target, data);
}
}
fn declaration_order(a: &(Option<String>, String), b: &(Option<String>, String)) -> Ordering {
let key = |p: &Option<String>| {
p.as_deref()
.unwrap_or("")
.encode_utf16()
.collect::<Vec<u16>>()
};
key(&a.0).cmp(&key(&b.0))
}
#[derive(Debug)]
pub(crate) struct XmlWriter<T> {
out: String,
target: T,
settings: Serialization,
fragment: bool,
pending: Option<StartTag>,
open: Vec<Open>,
scope: Vec<(Option<String>, String)>,
last_atomic: bool,
}
const INDENT: &str = " ";
impl<T: Target> XmlWriter<T> {
pub(crate) fn new(settings: Serialization, target: T) -> Self {
let mut out = String::new();
if !settings.omit_xml_declaration {
out.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"");
match settings.standalone {
Some(true) => out.push_str(" standalone=\"yes\""),
Some(false) => out.push_str(" standalone=\"no\""),
None => {}
}
out.push_str("?>");
}
Self {
out,
target,
settings,
fragment: false,
pending: None,
open: Vec::new(),
scope: Vec::new(),
last_atomic: false,
}
}
pub(crate) fn finish(mut self) -> Result<(String, T)> {
self.flush()?;
if !self.open.is_empty() {
return err("INTERNAL", "unclosed element at the end of the result");
}
if self.settings.indent {
self.out.push('\n');
}
self.target.commit(&mut self.out)?;
Ok((self.out, self.target))
}
fn bound(&self, prefix: Option<&str>) -> Option<&str> {
self.scope
.iter()
.rev()
.find(|(p, _)| p.as_deref() == prefix)
.map(|(_, uri)| uri.as_str())
}
fn flush(&mut self) -> Result<()> {
let Some(pending) = self.pending.take() else {
return Ok(());
};
let (name, attributes, own) = pending.fix()?;
let mut declarations: Vec<Binding> = own
.into_iter()
.filter(|(prefix, uri)| {
prefix.as_deref() != Some("xml")
&& self.bound(prefix.as_deref()).unwrap_or("") != uri
})
.collect();
declarations.sort_by(declaration_order);
let bindings_before = self.scope.len();
self.scope.extend(declarations.iter().cloned());
let mut tag = String::new();
if let Some(prefix) = &name.prefix {
tag.push_str(prefix);
tag.push(':');
}
tag.push_str(&name.local);
self.out.push('<');
self.out.push_str(&tag);
for (prefix, uri) in &declarations {
self.out.push_str(" xmlns");
if let Some(prefix) = prefix {
self.out.push(':');
self.out.push_str(prefix);
}
self.out.push_str("=\"");
escape_attribute(&mut self.out, uri);
self.out.push('"');
}
for (name, value) in &attributes {
self.out.push(' ');
if let Some(prefix) = &name.prefix {
self.out.push_str(prefix);
self.out.push(':');
}
self.out.push_str(&name.local);
self.out.push_str("=\"");
escape_attribute(&mut self.out, value);
self.out.push('"');
}
self.out.push('>');
self.target.start_element(&name, &attributes);
self.open.push(Open {
tag,
bindings: self.scope.len() - bindings_before,
has_elements: false,
has_text: false,
});
Ok(())
}
fn flush_tag(&mut self) -> Result<()> {
if self.pending.is_some() {
self.flush()?;
self.target.commit(&mut self.out)?;
}
Ok(())
}
fn indent(&mut self) {
let start = self.out.len();
self.out.push('\n');
for _ in 0..self.open.len() {
self.out.push_str(INDENT);
}
self.target.text(&self.out[start..]);
}
fn before_markup(&mut self) {
if let Some(parent) = self.open.last_mut() {
parent.has_elements = true;
if !parent.has_text && self.settings.indent {
self.indent();
}
} else if self.settings.indent && (!self.out.is_empty() || self.target.has_taken()) {
self.out.push('\n');
}
}
fn write_text(&mut self, text: &str) -> Result<()> {
self.flush_tag()?;
if text.is_empty() {
return Ok(());
}
let Some(parent) = self.open.last_mut() else {
if self.fragment {
escape_text(&mut self.out, text);
return Ok(());
}
if !text.chars().all(|c| matches!(c, ' ' | '\t' | '\r' | '\n')) {
return err(
"UNSUPPORTED",
"text outside the document element of the result",
);
}
return Ok(());
};
parent.has_text = true;
escape_text(&mut self.out, text);
self.target.text(text);
Ok(())
}
}
fn namespace_conflict(prefix: Option<&str>, uri: &str, other: &str) -> TransformError {
TransformError::new(
"XTDE0430",
format!(
"the namespace prefix {:?} is bound to {other:?} on the element, and a namespace node binds it to {uri:?}",
prefix.unwrap_or("")
),
)
}
impl<T: Target> Sink for XmlWriter<T> {
fn start_element(&mut self, name: &QName, namespaces: &Arc<[NamespaceBinding]>) -> Result<()> {
self.flush_tag()?;
self.last_atomic = false;
self.before_markup();
self.pending = Some(StartTag::new(name, namespaces));
Ok(())
}
fn namespace(&mut self, prefix: Option<&str>, uri: &str) -> Result<()> {
self.last_atomic = false;
let Some(pending) = self.pending.as_mut() else {
return err(
"XTDE0410",
"a namespace node cannot be created after the children of the containing element",
);
};
pending.namespace(prefix, uri)
}
fn attribute(&mut self, name: &QName, value: &str) -> Result<()> {
self.last_atomic = false;
let Some(pending) = self.pending.as_mut() else {
return err(
"XTDE0410",
format!(
"an attribute node ({name}) cannot be created after the children of the containing element"
),
);
};
pending.attribute(name, value);
Ok(())
}
fn end_element(&mut self) -> Result<()> {
self.last_atomic = false;
if let Some(pending) = self.pending.take() {
self.pending = Some(pending);
self.flush()?;
let Some(open) = self.open.pop() else {
return err("INTERNAL", "end of an element that is not open");
};
self.out.pop();
self.out.push_str("/>");
self.scope.truncate(self.scope.len() - open.bindings);
self.target.end_element();
return self.target.commit(&mut self.out);
}
let Some(open) = self.open.pop() else {
return err("INTERNAL", "end of an element that is not open");
};
if open.has_elements && !open.has_text && self.settings.indent {
self.indent();
}
self.out.push_str("</");
self.out.push_str(&open.tag);
self.out.push('>');
self.scope.truncate(self.scope.len() - open.bindings);
self.target.end_element();
self.target.commit(&mut self.out)
}
fn text(&mut self, text: &str) -> Result<()> {
self.last_atomic = false;
self.write_text(text)
}
fn comment(&mut self, text: &str) -> Result<()> {
self.flush_tag()?;
self.last_atomic = false;
self.before_markup();
self.out.push_str("<!--");
self.out.push_str(text);
self.out.push_str("-->");
self.target.comment(text);
Ok(())
}
fn processing_instruction(&mut self, target: &str, value: &str) -> Result<()> {
self.flush_tag()?;
self.last_atomic = false;
self.before_markup();
self.out.push_str("<?");
self.out.push_str(target);
if !value.is_empty() {
self.out.push(' ');
self.out.push_str(value);
}
self.out.push_str("?>");
self.target.processing_instruction(target, value);
Ok(())
}
fn item(&mut self, item: &Item) -> Result<()> {
match item {
Item::Atomic(_) => {
if self.last_atomic {
self.write_text(" ")?;
}
self.write_text(&item.string_value())?;
self.last_atomic = true;
Ok(())
}
Item::Node(node) => {
self.last_atomic = false;
copy_node(self, node)
}
}
}
}
const fn written_as_reference(c: char) -> bool {
matches!(c, '\u{7f}'..='\u{9f}' | '\u{2028}')
}
fn push_reference(out: &mut String, c: char) {
use std::fmt::Write as _;
let _ = write!(out, "&#x{:x};", u32::from(c));
}
fn escape_text(out: &mut String, text: &str) {
for c in text.chars() {
match c {
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'&' => out.push_str("&"),
'\r' => out.push_str("
"),
c if written_as_reference(c) => push_reference(out, c),
c => out.push(c),
}
}
}
fn escape_attribute(out: &mut String, text: &str) {
for c in text.chars() {
match c {
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'&' => out.push_str("&"),
'"' => out.push_str("""),
'\t' => out.push_str("	"),
'\n' => out.push_str("
"),
'\r' => out.push_str("
"),
c if written_as_reference(c) => push_reference(out, c),
c => out.push(c),
}
}
}
pub(crate) fn serialize(root: &Node, settings: Serialization, fragment: bool) -> Result<String> {
let mut writer = XmlWriter::new(settings, WholeText);
writer.fragment = fragment;
copy_node(&mut writer, root)?;
Ok(writer.finish()?.0)
}
#[derive(Debug)]
pub(crate) struct TreeSink {
builder: TreeBuilder,
last_atomic: bool,
pending: Option<(StartTag, bool)>,
scopes: Vec<Vec<NamespaceBinding>>,
}
impl TreeSink {
pub(crate) fn new() -> Self {
Self::with(TreeBuilder::new())
}
fn parentless() -> Self {
Self::with(TreeBuilder::parentless())
}
const fn with(builder: TreeBuilder) -> Self {
Self {
builder,
last_atomic: false,
pending: None,
scopes: Vec::new(),
}
}
pub(crate) fn finish(self) -> Result<Rc<Document>> {
self.finish_with(None)
}
pub(crate) fn finish_with(mut self, base_uri: Option<String>) -> Result<Rc<Document>> {
self.flush()?;
self.builder
.finish(None, base_uri)
.map_err(|e| TransformError::new("INTERNAL", e.message()))
}
fn flush(&mut self) -> Result<()> {
let Some((tag, copied)) = self.pending.take() else {
return Ok(());
};
let (name, attributes, own) = tag.fix()?;
let parent: Vec<NamespaceBinding> = self.scopes.last().cloned().unwrap_or_default();
let mut scope: Vec<NamespaceBinding> = if copied { Vec::new() } else { parent.clone() };
for (prefix, uri) in own {
if prefix.as_deref() == Some("xml") {
continue;
}
scope.retain(|b| b.prefix != prefix);
scope.push(NamespaceBinding { prefix, uri });
}
scope.retain(|b| !b.uri.is_empty());
let mut entries: Vec<NamespaceBinding> = scope
.iter()
.filter(|b| !parent.contains(b))
.cloned()
.collect();
for binding in &parent {
if !scope.iter().any(|b| b.prefix == binding.prefix) {
entries.push(NamespaceBinding {
prefix: binding.prefix.clone(),
uri: String::new(),
});
}
}
self.scopes.push(scope);
self.builder
.start_element_with_namespaces(name, entries.into())
.map_err(|e| tree_error(&e))?;
for (name, value) in attributes {
self.builder
.attribute(name, &value)
.map_err(|e| tree_error(&e))?;
}
Ok(())
}
fn start_tag(&mut self, what: &str) -> Result<&mut StartTag> {
match self.pending.as_mut() {
Some((tag, _)) => Ok(tag),
None => err(
"XTDE0410",
format!(
"{what} cannot be created after the children of the containing element, or at the top of a temporary tree"
),
),
}
}
}
fn tree_error(e: &einvoice_xpath_eval::DocumentError) -> TransformError {
TransformError::new("INTERNAL", e.message())
}
impl Sink for TreeSink {
fn start_element(&mut self, name: &QName, namespaces: &Arc<[NamespaceBinding]>) -> Result<()> {
self.flush()?;
self.last_atomic = false;
self.pending = Some((StartTag::new(name, namespaces), false));
Ok(())
}
fn start_copied_element(
&mut self,
name: &QName,
namespaces: &Arc<[NamespaceBinding]>,
) -> Result<()> {
self.flush()?;
self.last_atomic = false;
self.pending = Some((StartTag::new(name, namespaces), true));
Ok(())
}
fn namespace(&mut self, prefix: Option<&str>, uri: &str) -> Result<()> {
self.last_atomic = false;
self.start_tag("a namespace node")?.namespace(prefix, uri)
}
fn attribute(&mut self, name: &QName, value: &str) -> Result<()> {
self.last_atomic = false;
let what = format!("an attribute node ({name})");
self.start_tag(&what)?.attribute(name, value);
Ok(())
}
fn end_element(&mut self) -> Result<()> {
self.flush()?;
self.last_atomic = false;
self.scopes.pop();
self.builder.end_element().map_err(|e| tree_error(&e))
}
fn text(&mut self, text: &str) -> Result<()> {
self.flush()?;
self.last_atomic = false;
self.builder.text(text).map_err(|e| tree_error(&e))
}
fn comment(&mut self, text: &str) -> Result<()> {
self.flush()?;
self.last_atomic = false;
self.builder.comment(text).map_err(|e| tree_error(&e))
}
fn processing_instruction(&mut self, target: &str, value: &str) -> Result<()> {
self.flush()?;
self.last_atomic = false;
self.builder
.processing_instruction(target, value)
.map_err(|e| tree_error(&e))
}
fn start_document(&mut self) -> Result<()> {
self.flush()?;
self.last_atomic = false;
Ok(())
}
fn end_document(&mut self) -> Result<()> {
self.flush()?;
self.last_atomic = false;
Ok(())
}
fn item(&mut self, item: &Item) -> Result<()> {
match item {
Item::Atomic(_) => {
let was_atomic = self.last_atomic;
if was_atomic {
self.text(" ")?;
}
self.text(&item.string_value())?;
self.last_atomic = true;
Ok(())
}
Item::Node(node) => {
self.flush()?;
self.last_atomic = false;
copy_node(self, node)
}
}
}
}
#[derive(Debug, Default)]
pub(crate) struct TextSink {
parts: Vec<String>,
last_text: bool,
depth: usize,
}
impl TextSink {
pub(crate) fn new() -> Self {
Self::default()
}
fn push_part(&mut self, value: &str, is_text: bool) {
if is_text && self.last_text {
if let Some(last) = self.parts.last_mut() {
last.push_str(value);
}
} else {
self.parts.push(value.to_owned());
}
self.last_text = is_text;
}
pub(crate) fn finish(self, separator: &str) -> String {
if self.parts.len() == 1 {
return self.parts.into_iter().next().unwrap_or_default();
}
self.parts.join(separator)
}
fn open(&mut self) {
if self.depth == 0 {
self.parts.push(String::new());
self.last_text = false;
}
self.depth += 1;
}
}
impl Sink for TextSink {
fn start_element(
&mut self,
_name: &QName,
_namespaces: &Arc<[NamespaceBinding]>,
) -> Result<()> {
self.open();
Ok(())
}
fn namespace(&mut self, _prefix: Option<&str>, uri: &str) -> Result<()> {
if self.depth == 0 {
self.push_part(uri, false);
}
Ok(())
}
fn attribute(&mut self, _name: &QName, value: &str) -> Result<()> {
if self.depth == 0 {
self.push_part(value, false);
}
Ok(())
}
fn end_element(&mut self) -> Result<()> {
self.depth = self.depth.saturating_sub(1);
Ok(())
}
fn text(&mut self, text: &str) -> Result<()> {
if self.depth > 0 {
if let Some(last) = self.parts.last_mut() {
last.push_str(text);
}
} else if !text.is_empty() {
self.push_part(text, true);
}
Ok(())
}
fn comment(&mut self, text: &str) -> Result<()> {
if self.depth == 0 {
self.push_part(text, false);
}
Ok(())
}
fn processing_instruction(&mut self, _target: &str, value: &str) -> Result<()> {
if self.depth == 0 {
self.push_part(value, false);
}
Ok(())
}
fn start_document(&mut self) -> Result<()> {
self.open();
Ok(())
}
fn end_document(&mut self) -> Result<()> {
self.depth = self.depth.saturating_sub(1);
Ok(())
}
fn item(&mut self, item: &Item) -> Result<()> {
if self.depth > 0 {
return err(
"INTERNAL",
"an item inside an element constructed in simple content",
);
}
let is_text = matches!(item, Item::Node(n) if n.kind() == NodeKind::Text);
let value = item.string_value();
if is_text && value.is_empty() {
return Ok(());
}
self.push_part(&value, is_text);
Ok(())
}
}
#[derive(Debug, Default)]
pub(crate) struct SequenceSink {
pub(crate) items: Vec<Item>,
open: Option<Box<(TreeSink, usize)>>,
}
impl SequenceSink {
fn tree(&mut self) -> Option<&mut TreeSink> {
self.open.as_mut().map(|e| &mut e.0)
}
fn push_parentless(
&mut self,
build: impl FnOnce(
&mut TreeBuilder,
) -> std::result::Result<(), einvoice_xpath_eval::DocumentError>,
) -> Result<()> {
let mut builder = TreeBuilder::parentless();
build(&mut builder).map_err(|e| tree_error(&e))?;
let tree = builder
.finish(None, None)
.map_err(|e| TransformError::new("INTERNAL", e.message()))?;
self.items.push(Item::Node(tree.root()));
Ok(())
}
fn close(&mut self) -> Result<()> {
let Some(open) = self.open.as_mut() else {
return err("INTERNAL", "end of a node that is not open");
};
open.1 -= 1;
if open.1 == 0
&& let Some(open) = self.open.take()
{
self.items.push(Item::Node(open.0.finish()?.root()));
}
Ok(())
}
}
impl Sink for SequenceSink {
fn start_element(&mut self, name: &QName, namespaces: &Arc<[NamespaceBinding]>) -> Result<()> {
let open = self
.open
.get_or_insert_with(|| Box::new((TreeSink::parentless(), 0)));
open.1 += 1;
open.0.start_element(name, namespaces)
}
fn start_copied_element(
&mut self,
name: &QName,
namespaces: &Arc<[NamespaceBinding]>,
) -> Result<()> {
let open = self
.open
.get_or_insert_with(|| Box::new((TreeSink::parentless(), 0)));
open.1 += 1;
open.0.start_copied_element(name, namespaces)
}
fn namespace(&mut self, prefix: Option<&str>, uri: &str) -> Result<()> {
if let Some(tree) = self.tree() {
return tree.namespace(prefix, uri);
}
err(
"UNSUPPORTED",
"a parentless namespace node constructed in a sequence is not supported",
)
}
fn attribute(&mut self, name: &QName, value: &str) -> Result<()> {
if let Some(tree) = self.tree() {
return tree.attribute(name, value);
}
self.push_parentless(|b| b.attribute(name.clone(), value))
}
fn end_element(&mut self) -> Result<()> {
let Some(open) = self.open.as_mut() else {
return err("INTERNAL", "end of an element that is not open");
};
open.0.end_element()?;
self.close()
}
fn text(&mut self, text: &str) -> Result<()> {
if let Some(tree) = self.tree() {
return tree.text(text);
}
self.push_parentless(|b| b.text(text))
}
fn comment(&mut self, text: &str) -> Result<()> {
if let Some(tree) = self.tree() {
return tree.comment(text);
}
self.push_parentless(|b| b.comment(text))
}
fn processing_instruction(&mut self, target: &str, value: &str) -> Result<()> {
if let Some(tree) = self.tree() {
return tree.processing_instruction(target, value);
}
self.push_parentless(|b| b.processing_instruction(target, value))
}
fn start_document(&mut self) -> Result<()> {
let open = self
.open
.get_or_insert_with(|| Box::new((TreeSink::new(), 0)));
open.1 += 1;
open.0.start_document()
}
fn end_document(&mut self) -> Result<()> {
let Some(open) = self.open.as_mut() else {
return err("INTERNAL", "end of a document node that is not open");
};
open.0.end_document()?;
self.close()
}
fn item(&mut self, item: &Item) -> Result<()> {
if let Some(tree) = self.tree() {
return tree.item(item);
}
self.items.push(item.clone());
Ok(())
}
}
fn lexical_qname(text: &str) -> Option<(Option<&str>, &str)> {
let text = text.trim_matches(einvoice_xpath::is_xml_whitespace);
let (prefix, local) = match text.split_once(':') {
Some((p, l)) => (Some(p), l),
None => (None, text),
};
(einvoice_xpath::is_ncname(local) && prefix.is_none_or(einvoice_xpath::is_ncname))
.then_some((prefix, local))
}
pub(crate) fn attribute_name(
text: &str,
namespace: Option<&str>,
namespaces: &[NamespaceBinding],
) -> Result<QName> {
let Some((prefix, local)) = lexical_qname(text) else {
return err(
"XTDE0850",
format!("invalid attribute name {text:?} in xsl:attribute"),
);
};
if prefix.is_none() && local == "xmlns" {
return err("XTDE0855", "an attribute cannot be named xmlns");
}
if let Some(uri) = namespace {
if uri.is_empty() {
return Ok(QName::local(local));
}
let Some(prefix) = prefix else {
return err(
"UNSUPPORTED",
format!(
"the prefix Saxon chooses for an attribute {local:?} in the namespace {uri:?} given without one"
),
);
};
return Ok(QName {
prefix: Some(prefix.to_owned()),
namespace: Some(uri.to_owned()),
local: local.to_owned(),
});
}
let namespace = match prefix {
None => None,
Some("xml") => Some(XML_NAMESPACE.to_owned()),
Some(p) => Some(
namespaces
.iter()
.find(|ns| ns.prefix.as_deref() == Some(p))
.map(|ns| ns.uri.clone())
.ok_or_else(|| {
TransformError::new(
"XTDE0860",
format!("prefix {p:?} of attribute name {text:?} is not declared"),
)
})?,
),
};
Ok(QName {
prefix: prefix.map(str::to_owned),
namespace,
local: local.to_owned(),
})
}
pub(crate) fn element_name(
text: &str,
namespace: Option<&str>,
namespaces: &[NamespaceBinding],
) -> Result<QName> {
let Some((prefix, local)) = lexical_qname(text) else {
return err(
"XTDE0820",
format!("invalid element name {text:?} in xsl:element"),
);
};
if let Some(uri) = namespace {
return Ok(QName {
prefix: prefix.filter(|_| !uri.is_empty()).map(str::to_owned),
namespace: (!uri.is_empty()).then(|| uri.to_owned()),
local: local.to_owned(),
});
}
let namespace = match prefix {
Some("xml") => Some(XML_NAMESPACE.to_owned()),
_ => namespaces
.iter()
.find(|ns| ns.prefix.as_deref() == prefix)
.map(|ns| ns.uri.clone())
.filter(|uri| !uri.is_empty()),
};
if prefix.is_some() && namespace.is_none() {
return err(
"XTDE0830",
format!("the prefix of element name {text:?} is not declared"),
);
}
Ok(QName {
prefix: prefix.map(str::to_owned),
namespace,
local: local.to_owned(),
})
}