1use std::borrow::Cow;
17use std::cell::{Cell, OnceCell, RefCell};
18use std::collections::HashSet;
19use std::rc::{Rc, Weak};
20use std::sync::Arc;
21
22use einvoice_xdm::{AtomicType, AtomicValue, DateTime};
23use einvoice_xpath::{AtomicKind, ItemType, Occurrence, QName, SequenceType};
24use einvoice_xpath_eval::{
25 Clock, CompiledExpr, Context, DEFAULT_MAX_DEPTH, Document, DocumentError, DynamicContext,
26 ErrorCode, FunctionId, Host, Item, LimitExceeded, Node, NodeAxis, NodeKind, VariableId,
27};
28use einvoice_xslt::{NamespaceBinding, NumberLevel};
29
30use crate::error::{LIMIT, Result, TransformError, err};
31use crate::pattern::{self, Matcher};
32use crate::prepare::{
33 AvtItem, Binding, CompiledAvt, CompiledTemplate, CountPattern, Executable, Inst, ModeRef,
34 Value, When, WithParam,
35};
36use crate::sink::{SequenceSink, Sink, TextSink, TreeSink, XmlWriter, attribute_name};
37
38pub trait DocumentResolver {
41 fn resolve(&self, uri: &str) -> Option<String>;
43}
44
45pub const DEFAULT_MAX_NESTING: u32 = max_nesting_for_depth(DEFAULT_MAX_DEPTH);
50
51#[must_use]
63pub const fn max_nesting_for_depth(max_depth: u32) -> u32 {
64 max_depth.saturating_mul(2).saturating_add(64)
65}
66
67pub struct TransformOptions<'r> {
69 pub implicit_timezone: Option<i16>,
71 pub current_date_time: Option<DateTime>,
75 pub parameters: Vec<(QName, Vec<Item>)>,
77 pub resolver: Option<&'r dyn DocumentResolver>,
79 pub max_depth: u32,
84 pub max_nesting: u32,
89 pub max_stack: u32,
98}
99
100#[cfg(not(target_family = "wasm"))]
106pub const DEFAULT_MAX_STACK: u32 = 3 << 19;
107
108#[cfg(target_family = "wasm")]
110pub const DEFAULT_MAX_STACK: u32 = 640 << 10;
111
112impl Default for TransformOptions<'_> {
113 fn default() -> Self {
114 Self {
115 implicit_timezone: None,
116 current_date_time: None,
117 parameters: Vec::new(),
118 resolver: None,
119 max_depth: DEFAULT_MAX_DEPTH,
120 max_nesting: DEFAULT_MAX_NESTING,
121 max_stack: DEFAULT_MAX_STACK,
122 }
123 }
124}
125
126impl std::fmt::Debug for TransformOptions<'_> {
127 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128 f.debug_struct("TransformOptions")
129 .field("implicit_timezone", &self.implicit_timezone)
130 .field("current_date_time", &self.current_date_time)
131 .field("parameters", &self.parameters)
132 .field("resolver", &self.resolver.map(|_| "..."))
133 .field("max_depth", &self.max_depth)
134 .field("max_nesting", &self.max_nesting)
135 .field("max_stack", &self.max_stack)
136 .finish()
137 }
138}
139
140#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct Transformation {
143 pub output: String,
145 pub warnings: Vec<String>,
152}
153
154impl Executable {
155 pub fn transform<'s>(
172 &self,
173 source: impl Into<Cow<'s, str>>,
174 base_uri: Option<&str>,
175 ) -> std::result::Result<Transformation, TransformError> {
176 self.transform_with(source, base_uri, &TransformOptions::default())
177 }
178
179 pub fn transform_with<'s>(
186 &self,
187 source: impl Into<Cow<'s, str>>,
188 base_uri: Option<&str>,
189 options: &TransformOptions<'_>,
190 ) -> std::result::Result<Transformation, TransformError> {
191 let source = source.into();
192 let source_text = match &source {
194 Cow::Borrowed(text) => Some(Cow::Borrowed(*text)),
195 Cow::Owned(text) if self.calls_document && base_uri.is_some() => {
196 Some(Cow::Owned(text.clone()))
197 }
198 Cow::Owned(_) => None,
199 };
200 let document = Document::parse_with_max_depth(source, base_uri, options.max_depth)
201 .map_err(|e| match e.limit() {
202 Some(limit) => TransformError::limit_exceeded(limit),
203 None => TransformError::new("SXXP0003", e.message()),
204 })?;
205 let root = document.root();
206 let runtime = Runtime {
207 exe: self,
208 source_root: root.clone(),
209 source_text: RefCell::new(source_text),
210 source_uri: base_uri,
211 options,
212 dc: Cell::new(None),
213 globals: (0..self.globals.len())
214 .map(|_| RefCell::new(GlobalState::Pending))
215 .collect(),
216 frames: RefCell::new(Vec::new()),
217 documents: RefCell::new(Vec::new()),
218 warnings: RefCell::new(Vec::new()),
219 warned: RefCell::new(HashSet::new()),
220 stashed: RefCell::new(None),
221 nesting: Cell::new(0),
222 stack_base: stack_position(),
223 };
224 let timezone = options.implicit_timezone.unwrap_or(0);
225 let clock = match options.current_date_time {
226 Some(now) => Clock::new(timezone, now)?,
227 None => system_clock(timezone)?,
228 };
229 let dc = DynamicContext::new(&runtime, clock);
230 runtime.dc.set(Some(&dc));
231 let mut writer = XmlWriter::new(self.serialization);
232 runtime.apply_rule(&root, 1, 1, self.default_mode, None, &[], &mut writer)?;
233 let output = writer.finish()?;
234 let warnings = runtime.warnings.take();
235 Ok(Transformation { output, warnings })
236 }
237}
238
239#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
241fn system_clock(timezone: i16) -> Result<Clock> {
242 Ok(Clock::system(timezone)?)
243}
244
245#[cfg(all(target_family = "wasm", target_os = "unknown"))]
247fn system_clock(_timezone: i16) -> Result<Clock> {
248 Err(einvoice_xpath_eval::Error::new(
249 ErrorCode::Unsupported,
250 "no system clock on this target: give TransformOptions::current_date_time",
251 )
252 .into())
253}
254
255#[derive(Debug)]
256enum GlobalState {
257 Pending,
258 Evaluating,
259 Done(Rc<[Item]>),
260}
261
262struct Thunk<'e> {
264 expr: &'e CompiledExpr,
265 as_type: Option<&'e SequenceType>,
266 code: &'static str,
267 context: Context,
268 frame: Option<Weak<Frame<'e>>>,
270 memo: OnceCell<Rc<[Item]>>,
271}
272
273#[derive(Clone)]
274enum Slot<'e> {
275 Unset,
276 Value(Rc<[Item]>),
277 Lazy(Rc<Thunk<'e>>),
278}
279
280struct Frame<'e> {
282 slots: RefCell<Vec<Slot<'e>>>,
283}
284
285impl Frame<'_> {
286 fn new(slots: usize) -> Rc<Self> {
287 Rc::new(Self {
288 slots: RefCell::new(vec![Slot::Unset; slots]),
289 })
290 }
291}
292
293struct State<'c> {
295 context: &'c Context,
296 mode: usize,
297 rule: Option<u32>,
299}
300
301type Params<'e> = Vec<(&'e QName, Slot<'e>)>;
302
303struct Runtime<'e, 'a> {
304 exe: &'e Executable,
305 source_root: Node,
306 source_text: RefCell<Option<Cow<'a, str>>>,
309 source_uri: Option<&'a str>,
310 options: &'a TransformOptions<'a>,
311 dc: Cell<Option<&'a DynamicContext<'a>>>,
312 globals: Vec<RefCell<GlobalState>>,
313 frames: RefCell<Vec<Rc<Frame<'e>>>>,
314 documents: RefCell<Vec<(String, Node)>>,
316 warnings: RefCell<Vec<String>>,
318 warned: RefCell<HashSet<String>>,
319 stashed: RefCell<Option<TransformError>>,
321 nesting: Cell<u32>,
324 stack_base: usize,
327}
328
329#[inline(never)]
333fn stack_position() -> usize {
334 let marker = 0_u8;
335 std::hint::black_box(std::ptr::addr_of!(marker)).addr()
336}
337
338struct Nested<'n>(&'n Cell<u32>);
340
341impl Drop for Nested<'_> {
342 fn drop(&mut self) {
343 self.0.set(self.0.get().saturating_sub(1));
344 }
345}
346
347trait At<T> {
349 fn at(self, line: u32) -> Result<T>;
350}
351
352impl<T> At<T> for Result<T> {
353 fn at(self, line: u32) -> Result<T> {
354 self.map_err(|e| e.at(line))
355 }
356}
357
358fn type_name(t: &SequenceType) -> String {
360 let item = match &t.item {
361 ItemType::Atomic(a) => a.name.to_string(),
362 ItemType::Kind(k) => format!("{k:?}"),
363 };
364 let occurrence = match t.occurrence {
365 Occurrence::One => "",
366 Occurrence::ZeroOrOne => "?",
367 Occurrence::ZeroOrMore => "*",
368 Occurrence::OneOrMore => "+",
369 };
370 format!("{item}{occurrence}")
371}
372
373const fn atomic_type(kind: AtomicKind) -> AtomicType {
374 match kind {
375 AtomicKind::String => AtomicType::String,
376 AtomicKind::AnyUri => AtomicType::AnyUri,
377 AtomicKind::Boolean => AtomicType::Boolean,
378 AtomicKind::Integer => AtomicType::Integer,
379 AtomicKind::Decimal => AtomicType::Decimal,
380 AtomicKind::Date => AtomicType::Date,
381 }
382}
383
384fn convert(items: Vec<Item>, t: &SequenceType, code: &str) -> Result<Vec<Item>> {
388 let count = items.len();
389 let cardinality_ok = match t.occurrence {
390 Occurrence::One => count == 1,
391 Occurrence::ZeroOrOne => count <= 1,
392 Occurrence::ZeroOrMore => true,
393 Occurrence::OneOrMore => count >= 1,
394 };
395 if !cardinality_ok {
396 return err(
397 code,
398 format!(
399 "Required cardinality of value is {}; supplied value has {count} items",
400 type_name(t)
401 ),
402 );
403 }
404 match &t.item {
405 ItemType::Atomic(a) => {
406 let target = atomic_type(a.kind);
407 items
408 .into_iter()
409 .map(|item| {
410 let value = item.atomize();
411 let value = match value {
412 AtomicValue::UntypedAtomic(_) => value.cast(target)?,
413 AtomicValue::AnyUri(s) if target == AtomicType::String => {
414 AtomicValue::String(s)
415 }
416 v if v.is_instance_of(target) => v,
417 v => {
418 return err(
419 code,
420 format!(
421 "Required item type of value is {}; supplied value has item type {}",
422 a.name,
423 v.atomic_type()
424 ),
425 );
426 }
427 };
428 Ok(Item::Atomic(value))
429 })
430 .collect()
431 }
432 ItemType::Kind(kind) => {
433 let test = pattern::step_test(
434 match kind {
435 einvoice_xpath::KindTest::Attribute(_) => {
436 einvoice_xpath::PatternAxis::Attribute
437 }
438 _ => einvoice_xpath::PatternAxis::Child,
439 },
440 &einvoice_xpath::NodeTest::Kind(kind.clone()),
441 );
442 for item in &items {
443 let ok = match item {
444 Item::Node(n) => {
445 matches!(kind, einvoice_xpath::KindTest::AnyKind) || test.matches(n)
446 }
447 Item::Atomic(_) => false,
448 };
449 if !ok {
450 return err(
451 code,
452 format!("Required item type of value is {}", type_name(t)),
453 );
454 }
455 }
456 Ok(items)
457 }
458 }
459}
460
461fn comment_text(text: &str) -> String {
464 let mut out = String::with_capacity(text.len());
465 let mut previous_dash = false;
466 for c in text.chars() {
467 if c == '-' && previous_dash {
468 out.push(' ');
469 }
470 previous_dash = c == '-';
471 out.push(c);
472 }
473 if previous_dash {
474 out.push(' ');
475 }
476 out
477}
478
479fn resolve_uri(reference: &str, base: Option<&str>) -> String {
482 let has_scheme = reference.split_once(':').is_some_and(|(scheme, _)| {
483 let mut chars = scheme.chars();
484 chars.next().is_some_and(|c| c.is_ascii_alphabetic())
485 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
486 });
487 let Some(base) = base.filter(|_| !has_scheme) else {
488 return reference.to_owned();
489 };
490 if reference.is_empty() {
491 return base.to_owned();
492 }
493 let joined = if reference.starts_with('/') {
494 match base.split_once(':') {
495 Some((scheme, _)) => format!("{scheme}:{reference}"),
496 None => reference.to_owned(),
497 }
498 } else {
499 let directory = base.rfind('/').map_or("", |i| &base[..=i]);
500 format!("{directory}{reference}")
501 };
502 let (prefix, path) = joined.split_once(':').unwrap_or(("", &joined));
504 let mut segments: Vec<&str> = Vec::new();
505 for segment in path.split('/') {
506 match segment {
507 "." => {}
508 ".." => {
509 if segments.len() > 1 {
510 segments.pop();
511 }
512 }
513 s => segments.push(s),
514 }
515 }
516 let path = segments.join("/");
517 if prefix.is_empty() {
518 path
519 } else {
520 format!("{prefix}:{path}")
521 }
522}
523
524impl<'e, 'a> Runtime<'e, 'a> {
525 fn dc(&self) -> Result<&'a DynamicContext<'a>> {
526 self.dc
527 .get()
528 .ok_or_else(|| TransformError::new("INTERNAL", "no dynamic context"))
529 }
530
531 fn xerr(&self, e: einvoice_xpath_eval::Error) -> TransformError {
533 if e.code() == ErrorCode::Host
534 && let Some(stashed) = self.stashed.borrow_mut().take()
535 {
536 return stashed;
537 }
538 e.into()
539 }
540
541 fn nested(&self) -> Result<Nested<'_>> {
548 let depth = self.nesting.get();
549 if depth >= self.options.max_nesting {
550 return Err(TransformError::limit_exceeded(LimitExceeded::Nesting {
551 max: self.options.max_nesting,
552 }));
553 }
554 let used = self.stack_base.abs_diff(stack_position());
555 if u32::try_from(used).map_or(true, |used| used > self.options.max_stack) {
556 return Err(TransformError::limit_exceeded(LimitExceeded::Stack {
557 max: self.options.max_stack,
558 }));
559 }
560 self.nesting.set(depth + 1);
561 Ok(Nested(&self.nesting))
562 }
563
564 fn stash(&self, e: TransformError) -> einvoice_xpath_eval::Error {
566 let message = e.to_string();
567 *self.stashed.borrow_mut() = Some(e);
568 einvoice_xpath_eval::Error::new(ErrorCode::Host, message)
569 }
570
571 fn evaluate(&self, expr: &CompiledExpr, context: &Context) -> Result<Vec<Item>> {
572 expr.evaluate(self.dc()?, context).map_err(|e| self.xerr(e))
573 }
574
575 fn test(&self, expr: &CompiledExpr, context: &Context) -> Result<bool> {
576 expr.effective_boolean_value(self.dc()?, context)
577 .map_err(|e| self.xerr(e))
578 }
579
580 fn in_frame<T>(
582 &self,
583 frame: Option<Rc<Frame<'e>>>,
584 f: impl FnOnce() -> Result<T>,
585 ) -> Result<T> {
586 let Some(frame) = frame else {
587 return f();
588 };
589 self.frames.borrow_mut().push(frame);
590 let result = f();
591 self.frames.borrow_mut().pop();
592 result
593 }
594
595 fn top_frame(&self) -> Option<Rc<Frame<'e>>> {
596 self.frames.borrow().last().cloned()
597 }
598
599 fn set_slot(&self, slot: usize, value: Slot<'e>) -> Result<()> {
600 let frames = self.frames.borrow();
601 let Some(frame) = frames.last() else {
602 return err("INTERNAL", "no frame for a local variable");
603 };
604 let mut slots = frame.slots.borrow_mut();
605 let Some(s) = slots.get_mut(slot) else {
606 return err("INTERNAL", "variable slot out of range");
607 };
608 *s = value;
609 Ok(())
610 }
611
612 fn force(&self, thunk: &Thunk<'e>) -> Result<Rc<[Item]>> {
613 if let Some(value) = thunk.memo.get() {
614 return Ok(Rc::clone(value));
615 }
616 let frame = match &thunk.frame {
617 None => None,
618 Some(weak) => Some(
619 weak.upgrade()
620 .ok_or_else(|| TransformError::new("INTERNAL", "variable frame is gone"))?,
621 ),
622 };
623 let items = self.in_frame(frame, || self.evaluate(thunk.expr, &thunk.context))?;
624 let items = match thunk.as_type {
625 Some(t) => convert(items, t, thunk.code)?,
626 None => items,
627 };
628 let value: Rc<[Item]> = items.into();
629 let _ = thunk.memo.set(Rc::clone(&value));
630 Ok(value)
631 }
632
633 fn slot_value(&self, slot: &Slot<'e>) -> Result<Rc<[Item]>> {
634 match slot {
635 Slot::Value(v) => Ok(Rc::clone(v)),
636 Slot::Lazy(thunk) => self.force(thunk),
637 Slot::Unset => err("INTERNAL", "variable read before it is bound"),
638 }
639 }
640
641 fn variable(&self, id: VariableId) -> Result<Rc<[Item]>> {
642 let index = id.0 as usize;
643 let globals = self.exe.globals.len();
644 if index < globals {
645 return self.global(index);
646 }
647 let slot = {
648 let frames = self.frames.borrow();
649 let Some(frame) = frames.last() else {
650 return err("INTERNAL", "no frame for a local variable");
651 };
652 let slots = frame.slots.borrow();
653 slots
654 .get(index - globals)
655 .cloned()
656 .ok_or_else(|| TransformError::new("INTERNAL", "variable slot out of range"))?
657 };
658 self.slot_value(&slot)
659 }
660
661 fn global(&self, index: usize) -> Result<Rc<[Item]>> {
662 let g = &self.exe.globals[index];
663 {
664 let mut state = self.globals[index].borrow_mut();
665 match &*state {
666 GlobalState::Done(v) => return Ok(Rc::clone(v)),
667 GlobalState::Evaluating => {
668 return err(
669 "XTDE0640",
670 format!("Circular definition of global variable ${}", g.name),
671 )
672 .at(g.line);
673 }
674 GlobalState::Pending => *state = GlobalState::Evaluating,
675 }
676 }
677 let supplied = if g.is_param {
678 self.options
679 .parameters
680 .iter()
681 .find(|(n, _)| n.same_expanded_name(&g.name))
682 } else {
683 None
684 };
685 let value = if let Some((_, items)) = supplied {
686 match &g.as_type {
687 Some(t) => convert(items.clone(), t, "XTTE0590"),
688 None => Ok(items.clone()),
689 }
690 .map(Rc::from)
691 } else {
692 let context = Context::for_item(Item::Node(self.source_root.clone()));
693 let state = State {
694 context: &context,
695 mode: self.exe.default_mode,
696 rule: None,
697 };
698 let frame = (g.slots > 0).then(|| Frame::new(g.slots));
699 let code = if g.is_param { "XTTE0590" } else { "XTTE0570" };
700 self.in_frame(frame, || {
701 self.value(&g.value, g.as_type.as_ref(), &state, code)
702 })
703 };
704 let value = match value {
705 Ok(v) => v,
706 Err(e) => {
707 *self.globals[index].borrow_mut() = GlobalState::Pending;
708 return Err(e.at(g.line));
709 }
710 };
711 *self.globals[index].borrow_mut() = GlobalState::Done(Rc::clone(&value));
712 Ok(value)
713 }
714
715 fn value(
717 &self,
718 value: &'e Value,
719 as_type: Option<&'e SequenceType>,
720 state: &State<'_>,
721 code: &str,
722 ) -> Result<Rc<[Item]>> {
723 let items = match value {
724 Value::Select(expr) => self.evaluate(expr, state.context)?,
725 Value::Content(body) => {
726 if as_type.is_some() {
727 let mut sink = SequenceSink::default();
728 self.exec(body, state, &mut sink)?;
729 sink.items
730 } else {
731 let mut sink = TreeSink::new();
732 self.exec(body, state, &mut sink)?;
733 vec![Item::Node(sink.finish()?.root())]
734 }
735 }
736 Value::Absent => {
737 if as_type.is_some() {
738 Vec::new()
739 } else {
740 vec![Item::Atomic(AtomicValue::String(String::new()))]
741 }
742 }
743 };
744 let items = match as_type {
745 Some(t) => convert(items, t, code)?,
746 None => items,
747 };
748 Ok(items.into())
749 }
750
751 fn bind(
753 &self,
754 value: &'e Value,
755 as_type: Option<&'e SequenceType>,
756 lazy: bool,
757 state: &State<'_>,
758 code: &'static str,
759 ) -> Result<Slot<'e>> {
760 if lazy && let Value::Select(expr) = value {
761 return Ok(Slot::Lazy(Rc::new(Thunk {
762 expr,
763 as_type,
764 code,
765 context: state.context.clone(),
766 frame: self.top_frame().map(|f| Rc::downgrade(&f)),
767 memo: OnceCell::new(),
768 })));
769 }
770 Ok(Slot::Value(self.value(value, as_type, state, code)?))
771 }
772
773 fn with_params(&self, params: &'e [WithParam], state: &State<'_>) -> Result<Params<'e>> {
774 params
775 .iter()
776 .map(|p| {
777 Ok((
778 &p.name,
779 self.bind(&p.value, p.as_type.as_ref(), p.lazy, state, "XTTE0590")?,
780 ))
781 })
782 .collect()
783 }
784
785 fn exec(&self, body: &'e [Inst], state: &State<'_>, sink: &mut dyn Sink) -> Result<()> {
786 for inst in body {
787 self.instruction(inst, state, sink)?;
788 }
789 Ok(())
790 }
791
792 fn instruction(&self, inst: &'e Inst, state: &State<'_>, sink: &mut dyn Sink) -> Result<()> {
798 match inst {
799 Inst::ApplyTemplates {
800 line,
801 select,
802 mode,
803 params,
804 } => self.apply_templates(*line, select, mode, params, state, sink),
805 Inst::NextMatch { line, params } => self.next_match(*line, params, state, sink),
806 Inst::CallTemplate {
807 line,
808 template,
809 params,
810 } => self.call_template(*line, *template, params, state, sink),
811 Inst::Choose { whens, otherwise } => self.choose(whens, otherwise, state, sink),
812 Inst::ForEach { line, select, body } => self.for_each(*line, select, body, state, sink),
813 Inst::Element {
814 line,
815 name,
816 namespaces,
817 attributes,
818 body,
819 } => self.element(*line, name, namespaces, attributes, body, state, sink),
820 _ => self.other_instruction(inst, state, sink),
821 }
822 }
823
824 #[inline(never)]
826 fn other_instruction(
827 &self,
828 inst: &'e Inst,
829 state: &State<'_>,
830 sink: &mut dyn Sink,
831 ) -> Result<()> {
832 match inst {
833 Inst::Variable(binding) => self.variable_instruction(binding, state),
834 Inst::Sequence { line, select } => self.sequence(*line, select, state, sink),
835 Inst::ValueOf {
836 line,
837 select,
838 separator,
839 body,
840 } => self.value_of(
841 *line,
842 select.as_deref(),
843 separator.as_ref(),
844 body,
845 state,
846 sink,
847 ),
848 Inst::Attribute {
849 line,
850 name,
851 namespaces,
852 select,
853 body,
854 } => self.attribute(
855 *line,
856 name,
857 namespaces,
858 select.as_deref(),
859 body,
860 state,
861 sink,
862 ),
863 Inst::Comment { line, body } => self.comment(*line, body, state, sink),
864 Inst::Text(text) => sink.text(text),
865 Inst::Number { line, level, count } => {
866 self.number_instruction(*line, *level, count.as_ref(), state, sink)
867 }
868 Inst::ApplyTemplates { .. }
869 | Inst::NextMatch { .. }
870 | Inst::CallTemplate { .. }
871 | Inst::Choose { .. }
872 | Inst::ForEach { .. }
873 | Inst::Element { .. } => self.instruction(inst, state, sink),
874 }
875 }
876
877 fn apply_templates(
878 &self,
879 line: u32,
880 select: &'e CompiledExpr,
881 mode: &ModeRef,
882 params: &'e [WithParam],
883 state: &State<'_>,
884 sink: &mut dyn Sink,
885 ) -> Result<()> {
886 let items = self.evaluate(select, state.context).at(line)?;
887 let mode = match mode {
888 ModeRef::Mode(m) => *m,
889 ModeRef::Current => state.mode,
890 };
891 let params = self.with_params(params, state).at(line)?;
892 let size = items.len();
893 for (i, item) in items.iter().enumerate() {
894 match item {
895 Item::Node(node) => self
896 .apply_rule(node, i + 1, size, mode, None, ¶ms, sink)
897 .at(line)?,
898 Item::Atomic(_) => sink.text(&item.string_value()).at(line)?,
901 }
902 }
903 Ok(())
904 }
905
906 fn next_match(
907 &self,
908 line: u32,
909 params: &'e [WithParam],
910 state: &State<'_>,
911 sink: &mut dyn Sink,
912 ) -> Result<()> {
913 let Some(rank) = state.rule else {
914 return err("XTDE0560", "xsl:next-match without a current template rule").at(line);
915 };
916 let Some(focus) = &state.context.focus else {
917 return err("XTDE0560", "xsl:next-match without a context item").at(line);
918 };
919 let Item::Node(node) = &focus.item else {
920 return err("XTDE0560", "xsl:next-match on an atomic value").at(line);
921 };
922 let params = self.with_params(params, state).at(line)?;
923 self.apply_rule(
924 node,
925 focus.position,
926 focus.size,
927 state.mode,
928 Some(rank),
929 ¶ms,
930 sink,
931 )
932 .at(line)
933 }
934
935 fn call_template(
936 &self,
937 line: u32,
938 template: usize,
939 params: &'e [WithParam],
940 state: &State<'_>,
941 sink: &mut dyn Sink,
942 ) -> Result<()> {
943 let params = self.with_params(params, state).at(line)?;
944 self.invoke(
945 template,
946 state.context,
947 state.mode,
948 state.rule,
949 ¶ms,
950 sink,
951 )
952 .at(line)
953 }
954
955 fn choose(
956 &self,
957 whens: &'e [When],
958 otherwise: &'e [Inst],
959 state: &State<'_>,
960 sink: &mut dyn Sink,
961 ) -> Result<()> {
962 for when in whens {
963 if self.test(&when.test, state.context).at(when.line)? {
964 return self.exec(&when.body, state, sink);
965 }
966 }
967 self.exec(otherwise, state, sink)
968 }
969
970 fn for_each(
971 &self,
972 line: u32,
973 select: &'e CompiledExpr,
974 body: &'e [Inst],
975 state: &State<'_>,
976 sink: &mut dyn Sink,
977 ) -> Result<()> {
978 let items = self.evaluate(select, state.context).at(line)?;
979 let size = items.len();
980 for (i, item) in items.into_iter().enumerate() {
981 let context = Context::at(item, i + 1, size);
982 let inner = State {
983 context: &context,
984 mode: state.mode,
985 rule: None,
986 };
987 self.exec(body, &inner, sink)?;
988 }
989 Ok(())
990 }
991
992 #[inline(never)]
993 fn sequence(
994 &self,
995 line: u32,
996 select: &'e CompiledExpr,
997 state: &State<'_>,
998 sink: &mut dyn Sink,
999 ) -> Result<()> {
1000 for item in self.evaluate(select, state.context).at(line)? {
1001 sink.item(&item).at(line)?;
1002 }
1003 Ok(())
1004 }
1005
1006 #[inline(never)]
1007 fn value_of(
1008 &self,
1009 line: u32,
1010 select: Option<&'e CompiledExpr>,
1011 separator: Option<&'e CompiledAvt>,
1012 body: &'e [Inst],
1013 state: &State<'_>,
1014 sink: &mut dyn Sink,
1015 ) -> Result<()> {
1016 let separator = match separator {
1017 Some(avt) => Some(self.avt(avt, state).at(line)?),
1018 None => None,
1019 };
1020 let mut parts = TextSink::new();
1021 let text = if let Some(expr) = select {
1022 for item in self.evaluate(expr, state.context).at(line)? {
1023 parts.item(&item)?;
1024 }
1025 parts.finish(separator.as_deref().unwrap_or(" "))
1026 } else {
1027 self.exec(body, state, &mut parts)?;
1028 parts.finish(separator.as_deref().unwrap_or(""))
1029 };
1030 sink.text(&text).at(line)
1031 }
1032
1033 #[inline(never)]
1034 #[expect(
1035 clippy::too_many_arguments,
1036 reason = "the parts of the instruction, its dynamic context and its sink"
1037 )]
1038 fn attribute(
1039 &self,
1040 line: u32,
1041 name: &'e CompiledAvt,
1042 namespaces: &[NamespaceBinding],
1043 select: Option<&'e CompiledExpr>,
1044 body: &'e [Inst],
1045 state: &State<'_>,
1046 sink: &mut dyn Sink,
1047 ) -> Result<()> {
1048 let name = self.avt(name, state).at(line)?;
1049 let name = attribute_name(&name, namespaces).at(line)?;
1050 let value = self.simple_content(select, body, state).at(line)?;
1051 sink.attribute(&name, &value).at(line)
1052 }
1053
1054 #[inline(never)]
1055 fn comment(
1056 &self,
1057 line: u32,
1058 body: &'e [Inst],
1059 state: &State<'_>,
1060 sink: &mut dyn Sink,
1061 ) -> Result<()> {
1062 let mut parts = TextSink::new();
1063 self.exec(body, state, &mut parts)?;
1064 sink.comment(&comment_text(&parts.finish(""))).at(line)
1065 }
1066
1067 #[inline(never)]
1068 fn number_instruction(
1069 &self,
1070 line: u32,
1071 level: NumberLevel,
1072 count: Option<&'e CountPattern>,
1073 state: &State<'_>,
1074 sink: &mut dyn Sink,
1075 ) -> Result<()> {
1076 let text = self.number(line, level, count, state).at(line)?;
1077 sink.text(&text).at(line)
1078 }
1079
1080 #[expect(
1081 clippy::too_many_arguments,
1082 reason = "the parts of the instruction, its dynamic context and its sink"
1083 )]
1084 fn element(
1085 &self,
1086 line: u32,
1087 name: &QName,
1088 namespaces: &[NamespaceBinding],
1089 attributes: &'e [(Arc<QName>, CompiledAvt)],
1090 body: &'e [Inst],
1091 state: &State<'_>,
1092 sink: &mut dyn Sink,
1093 ) -> Result<()> {
1094 sink.start_element(name, namespaces).at(line)?;
1095 for (attribute, value) in attributes {
1096 self.attribute_value(line, attribute, value, state, sink)?;
1097 }
1098 self.exec(body, state, sink)?;
1099 sink.end_element().at(line)
1100 }
1101
1102 #[inline(never)]
1104 fn attribute_value(
1105 &self,
1106 line: u32,
1107 name: &QName,
1108 value: &'e CompiledAvt,
1109 state: &State<'_>,
1110 sink: &mut dyn Sink,
1111 ) -> Result<()> {
1112 let value = self.avt(value, state).at(line)?;
1113 sink.attribute(name, &value).at(line)
1114 }
1115
1116 fn variable_instruction(&self, binding: &'e Binding, state: &State<'_>) -> Result<()> {
1117 if !binding.used {
1118 return Ok(());
1119 }
1120 let slot = self
1121 .bind(
1122 &binding.value,
1123 binding.as_type.as_ref(),
1124 binding.lazy,
1125 state,
1126 "XTTE0570",
1127 )
1128 .at(binding.line)?;
1129 self.set_slot(binding.slot, slot).at(binding.line)
1130 }
1131
1132 fn simple_content(
1134 &self,
1135 select: Option<&'e CompiledExpr>,
1136 body: &'e [Inst],
1137 state: &State<'_>,
1138 ) -> Result<String> {
1139 let mut parts = TextSink::new();
1140 if let Some(expr) = select {
1141 for item in self.evaluate(expr, state.context)? {
1142 parts.item(&item)?;
1143 }
1144 Ok(parts.finish(" "))
1145 } else {
1146 self.exec(body, state, &mut parts)?;
1147 Ok(parts.finish(""))
1148 }
1149 }
1150
1151 fn avt(&self, avt: &'e CompiledAvt, state: &State<'_>) -> Result<String> {
1152 if let [AvtItem::Text(text)] = avt.0.as_slice() {
1153 return Ok(text.to_string());
1154 }
1155 let mut out = String::new();
1156 for item in &avt.0 {
1157 match item {
1158 AvtItem::Text(text) => out.push_str(text),
1159 AvtItem::Expr(expr) => {
1160 for (i, value) in self.evaluate(expr, state.context)?.iter().enumerate() {
1161 if i > 0 {
1162 out.push(' ');
1163 }
1164 out.push_str(&value.atomize().to_string());
1165 }
1166 }
1167 }
1168 }
1169 Ok(out)
1170 }
1171
1172 #[expect(
1175 clippy::too_many_arguments,
1176 reason = "the focus, the mode, the rule and the parameters of the invocation"
1177 )]
1178 fn apply_rule(
1179 &self,
1180 node: &Node,
1181 position: usize,
1182 size: usize,
1183 mode: usize,
1184 after: Option<u32>,
1185 params: &[(&'e QName, Slot<'e>)],
1186 sink: &mut dyn Sink,
1187 ) -> Result<()> {
1188 match self.find_rule(mode, node, after)? {
1189 Some(rank) => {
1190 let template = self.exe.modes[mode].rules[rank as usize].template;
1191 let context = Context::at(Item::Node(node.clone()), position, size);
1192 self.invoke(template, &context, mode, Some(rank), params, sink)
1193 }
1194 None => self.builtin(node, mode, params, sink),
1195 }
1196 }
1197
1198 fn rule_matches(&self, rank: u32, mode: usize, node: &Node) -> Result<bool> {
1201 let rule = &self.exe.modes[mode].rules[rank as usize];
1202 let template = &self.exe.templates[rule.template];
1203 let matcher = Matcher { dc: self.dc()? };
1204 let (alternatives, text) = match rule.alternative {
1207 Some(index) => (
1208 template.pattern.get(index..=index).unwrap_or_default(),
1209 template
1210 .alternative_texts
1211 .get(index)
1212 .map_or("", String::as_str),
1213 ),
1214 None => (template.pattern.as_slice(), template.pattern_text.as_str()),
1215 };
1216 let outcome = alternatives
1217 .iter()
1218 .try_fold(false, |found, a| Ok(found || matcher.matches(a, node)?));
1219 outcome.or_else(|e| self.pattern_error(e, template.line, text))
1220 }
1221
1222 fn pattern_error(
1231 &self,
1232 e: einvoice_xpath_eval::Error,
1233 line: u32,
1234 pattern: &str,
1235 ) -> Result<bool> {
1236 let e = self.xerr(e);
1237 if matches!(
1238 e.code(),
1239 "XTDE0640" | "UNSUPPORTED" | LIMIT | "INTERNAL" | "HOST"
1240 ) {
1241 return Err(e.at(line));
1242 }
1243 self.warn(format!(
1244 "line {line}: {}: An error occurred matching pattern {{{pattern}}}: {}",
1245 e.code(),
1246 e.message()
1247 ));
1248 Ok(false)
1249 }
1250
1251 fn warn(&self, message: String) {
1254 if self.warned.borrow_mut().insert(message.clone()) {
1255 self.warnings.borrow_mut().push(message);
1256 }
1257 }
1258
1259 fn find_rule(&self, mode: usize, node: &Node, after: Option<u32>) -> Result<Option<u32>> {
1269 let compiled = &self.exe.modes[mode];
1270 let rules = &compiled.rules;
1271 let below_current = |rank: u32| -> bool {
1272 let Some(current) = after else {
1273 return true;
1274 };
1275 let (r, c) = (&rules[rank as usize], &rules[current as usize]);
1276 match r.priority.total_cmp(&c.priority) {
1277 std::cmp::Ordering::Less => true,
1278 std::cmp::Ordering::Greater => false,
1279 std::cmp::Ordering::Equal => {
1280 r.sequence < c.sequence || (r.sequence == c.sequence && r.part < c.part)
1281 }
1282 }
1283 };
1284 let mut best: Option<u32> = None;
1285 for chain in compiled.chains(node.kind(), node.name()) {
1286 for &rank in chain {
1287 if !below_current(rank) {
1288 continue;
1289 }
1290 let Some(chosen) = best else {
1291 if self.rule_matches(rank, mode, node)? {
1292 best = Some(rank);
1293 }
1294 continue;
1295 };
1296 let (head, b) = (&rules[rank as usize], &rules[chosen as usize]);
1297 match head.priority.total_cmp(&b.priority) {
1298 std::cmp::Ordering::Less => break,
1299 std::cmp::Ordering::Greater => {
1300 if self.rule_matches(rank, mode, node)? {
1301 best = Some(rank);
1302 }
1303 }
1304 std::cmp::Ordering::Equal => {
1305 if !self.rule_matches(rank, mode, node)? {
1306 continue;
1307 }
1308 if head.template != b.template {
1309 self.ambiguity(node, compiled, b, head);
1310 }
1311 let keep = b.sequence > head.sequence
1314 || (b.sequence == head.sequence
1315 && after.is_none()
1316 && b.part > head.part);
1317 best = Some(if keep { chosen } else { rank });
1318 break;
1319 }
1320 }
1321 }
1322 }
1323 Ok(best)
1324 }
1325
1326 fn ambiguity(
1329 &self,
1330 node: &Node,
1331 mode: &crate::prepare::CompiledMode,
1332 a: &crate::prepare::Rule,
1333 b: &crate::prepare::Rule,
1334 ) {
1335 let (ta, tb) = (
1336 &self.exe.templates[a.template],
1337 &self.exe.templates[b.template],
1338 );
1339 let later = if a.sequence > b.sequence { ta } else { tb };
1340 self.warn(format!(
1341 "XTDE0540: Ambiguous rule match for {} in mode {}: matches the template rules on line {} and line {}; the one on line {} is used",
1342 describe(node),
1343 mode.name,
1344 ta.line,
1345 tb.line,
1346 later.line
1347 ));
1348 }
1349
1350 fn builtin(
1354 &self,
1355 node: &Node,
1356 mode: usize,
1357 params: &[(&'e QName, Slot<'e>)],
1358 sink: &mut dyn Sink,
1359 ) -> Result<()> {
1360 match node.kind() {
1361 NodeKind::Document | NodeKind::Element => {
1362 let _nested = self.nested()?;
1363 let children: Vec<Node> = node.children().collect();
1364 let size = children.len();
1365 for (i, child) in children.iter().enumerate() {
1366 self.apply_rule(child, i + 1, size, mode, None, params, sink)?;
1367 }
1368 Ok(())
1369 }
1370 NodeKind::Text | NodeKind::Attribute => sink.text(&node.string_value()),
1371 NodeKind::Comment | NodeKind::ProcessingInstruction => Ok(()),
1372 }
1373 }
1374
1375 fn invoke(
1378 &self,
1379 index: usize,
1380 context: &Context,
1381 mode: usize,
1382 rule: Option<u32>,
1383 params: &[(&'e QName, Slot<'e>)],
1384 sink: &mut dyn Sink,
1385 ) -> Result<()> {
1386 let template = &self.exe.templates[index];
1387 let _nested = self.nested().at(template.line)?;
1388 let frame = (template.slots > 0).then(|| Frame::new(template.slots));
1389 let state = State {
1390 context,
1391 mode,
1392 rule,
1393 };
1394 self.in_frame(frame, || {
1395 self.bind_params(template, params, &state)?;
1396 self.exec(&template.body, &state, sink)
1397 })
1398 .at(template.line)
1399 }
1400
1401 #[inline(never)]
1405 fn bind_params(
1406 &self,
1407 template: &'e CompiledTemplate,
1408 params: &[(&'e QName, Slot<'e>)],
1409 state: &State<'_>,
1410 ) -> Result<()> {
1411 for param in &template.params {
1412 let passed = params
1413 .iter()
1414 .find(|(name, _)| name.same_expanded_name(¶m.name));
1415 let slot = match (passed, ¶m.as_type) {
1416 (Some((_, slot)), None) => slot.clone(),
1417 (Some((_, slot)), Some(t)) => {
1418 let items = self.slot_value(slot)?.to_vec();
1419 Slot::Value(convert(items, t, "XTTE0590").at(param.line)?.into())
1420 }
1421 (None, as_type) => self
1422 .bind(
1423 ¶m.value,
1424 as_type.as_ref(),
1425 param.lazy,
1426 state,
1427 "XTTE0590",
1428 )
1429 .at(param.line)?,
1430 };
1431 self.set_slot(param.slot, slot)?;
1432 }
1433 Ok(())
1434 }
1435
1436 fn call(&self, id: FunctionId, args: Vec<Vec<Item>>) -> Result<Vec<Item>> {
1438 let function = &self.exe.functions[id.0 as usize];
1439 let _nested = self.nested().at(function.line)?;
1440 let frame = Frame::new(function.slots);
1441 for (param, arg) in function.params.iter().zip(args) {
1442 let value = match ¶m.as_type {
1443 Some(t) => convert(arg, t, "XPTY0004").map_err(|e| {
1444 TransformError::new(
1445 e.code(),
1446 format!(
1447 "{} (argument ${} of {}())",
1448 e.message(),
1449 param.name,
1450 function.name
1451 ),
1452 )
1453 })?,
1454 None => arg,
1455 };
1456 frame.slots.borrow_mut()[param.slot] = Slot::Value(value.into());
1457 }
1458 let context = Context::new();
1460 let state = State {
1461 context: &context,
1462 mode: self.exe.default_mode,
1463 rule: None,
1464 };
1465 let mut sink = SequenceSink::default();
1466 self.in_frame(Some(frame), || self.exec(&function.body, &state, &mut sink))
1467 .at(function.line)?;
1468 match &function.as_type {
1469 Some(t) => convert(sink.items, t, "XTTE0780").at(function.line),
1470 None => Ok(sink.items),
1471 }
1472 }
1473
1474 fn number(
1475 &self,
1476 line: u32,
1477 level: NumberLevel,
1478 count: Option<&'e CountPattern>,
1479 state: &State<'_>,
1480 ) -> Result<String> {
1481 let Some(Item::Node(node)) = state.context.focus.as_ref().map(|f| &f.item) else {
1482 return err("XTTE0990", "xsl:number needs a node as context item");
1483 };
1484 let matcher = Matcher { dc: self.dc()? };
1485 let counted = |n: &Node| -> Result<bool> {
1486 match count {
1487 Some(pattern) => pattern
1490 .alternatives
1491 .iter()
1492 .try_fold(false, |found, a| Ok(found || matcher.matches(a, n)?))
1493 .or_else(|e| self.pattern_error(e, line, &pattern.text)),
1494 None => Ok(n.kind() == node.kind()
1495 && match (n.name(), node.name()) {
1496 (Some(a), Some(b)) => a.same_expanded_name(b),
1497 (None, None) => true,
1498 _ => false,
1499 }),
1500 }
1501 };
1502 let position = |n: &Node| -> Result<usize> {
1503 let mut p = 1;
1504 for sibling in n.axis(NodeAxis::PrecedingSibling) {
1505 if counted(&sibling)? {
1506 p += 1;
1507 }
1508 }
1509 Ok(p)
1510 };
1511 let mut numbers = Vec::new();
1512 for ancestor in node.axis(NodeAxis::AncestorOrSelf) {
1513 if counted(&ancestor)? {
1514 numbers.push(position(&ancestor)?);
1515 if level == NumberLevel::Single {
1516 break;
1517 }
1518 }
1519 }
1520 numbers.reverse();
1521 Ok(numbers
1522 .iter()
1523 .map(usize::to_string)
1524 .collect::<Vec<_>>()
1525 .join("."))
1526 }
1527
1528 fn load_document(&self, uri: &str, base: Option<&str>) -> Result<Node> {
1529 let absolute = resolve_uri(uri, base.or(self.exe.base_uri.as_deref()));
1530 if let Some((_, node)) = self.documents.borrow().iter().find(|(u, _)| *u == absolute) {
1531 return Ok(node.clone());
1532 }
1533 let text: Cow<'_, str> = if self.source_uri == Some(absolute.as_str()) {
1536 self.source_text.take().ok_or_else(|| {
1537 TransformError::new(
1538 "INTERNAL",
1539 "document() loads the source document, whose text was not kept",
1540 )
1541 })?
1542 } else {
1543 Cow::Owned(
1545 self.options
1546 .resolver
1547 .and_then(|r| r.resolve(&absolute))
1548 .ok_or_else(|| {
1549 TransformError::new(
1550 "FODC0002",
1551 format!("cannot retrieve the document at {absolute}"),
1552 )
1553 })?,
1554 )
1555 };
1556 let node = Document::parse_loaded_with_max_depth(text, &absolute, self.options.max_depth)
1558 .map_err(|e| loaded_document_error(&absolute, &e))?
1559 .root();
1560 self.documents.borrow_mut().push((absolute, node.clone()));
1561 Ok(node)
1562 }
1563}
1564
1565fn describe(node: &Node) -> String {
1570 let name = |n: &Node| n.name().map(ToString::to_string).unwrap_or_default();
1571 let number = |n: &Node| {
1574 1 + n
1575 .axis(NodeAxis::PrecedingSibling)
1576 .filter(|s| {
1577 s.kind() == n.kind()
1578 && match (s.name(), n.name()) {
1579 (Some(a), Some(b)) => a.same_expanded_name(b),
1580 (None, None) => true,
1581 _ => false,
1582 }
1583 })
1584 .count()
1585 };
1586 let lineage: Vec<Node> = node.axis(NodeAxis::AncestorOrSelf).collect();
1589 let mut path = String::new();
1590 let mut parent_kind: Option<NodeKind> = None;
1591 for n in lineage.iter().rev() {
1592 let parent_path = std::mem::take(&mut path);
1593 let under_parent = |step: String| {
1595 format!(
1596 "{}/{step}",
1597 if parent_path == "/" {
1598 ""
1599 } else {
1600 parent_path.as_str()
1601 }
1602 )
1603 };
1604 path = match n.kind() {
1605 NodeKind::Document => "/".to_owned(),
1606 NodeKind::Element => match parent_kind {
1607 None => name(n),
1608 Some(NodeKind::Document) => format!("/{}", name(n)),
1609 Some(_) => format!("{parent_path}/{}[{}]", name(n), number(n)),
1610 },
1611 NodeKind::Attribute => format!("{parent_path}/@{}", name(n)),
1612 NodeKind::Text => under_parent(format!("text()[{}]", number(n))),
1613 NodeKind::Comment => under_parent(format!("comment()[{}]", number(n))),
1614 NodeKind::ProcessingInstruction => {
1615 under_parent(format!("processing-instruction()[{}]", number(n)))
1616 }
1617 };
1618 parent_kind = Some(n.kind());
1619 }
1620 path
1621}
1622
1623fn loaded_document_error(uri: &str, e: &DocumentError) -> TransformError {
1626 match e.limit() {
1627 Some(limit) => TransformError::limit_exceeded(limit).in_document(uri),
1628 None => TransformError::new("FODC0002", format!("{uri}: {}", e.message())),
1629 }
1630}
1631
1632impl Host for Runtime<'_, '_> {
1633 fn variable(&self, id: VariableId) -> einvoice_xpath_eval::Result<Rc<[Item]>> {
1634 Runtime::variable(self, id).map_err(|e| self.stash(e))
1635 }
1636
1637 fn call_function(
1638 &self,
1639 id: FunctionId,
1640 args: Vec<Vec<Item>>,
1641 ) -> einvoice_xpath_eval::Result<Vec<Item>> {
1642 self.call(id, args).map_err(|e| self.stash(e))
1643 }
1644
1645 fn document(&self, uri: &str, base: Option<&str>) -> einvoice_xpath_eval::Result<Node> {
1646 self.load_document(uri, base).map_err(|e| self.stash(e))
1647 }
1648
1649 fn system_property(&self, name: &QName) -> String {
1650 if name.namespace.as_deref() != Some(einvoice_xslt::XSLT_NAMESPACE) {
1652 return String::new();
1653 }
1654 match name.local.as_str() {
1655 "version" => "3.0",
1656 "vendor" => "Saxonica",
1657 "vendor-url" => "http://www.saxonica.com/",
1658 "product-name" => "SAXON",
1659 "product-version" => "HE 12.10",
1660 _ => "",
1661 }
1662 .to_owned()
1663 }
1664}
1665
1666#[cfg(test)]
1667mod tests {
1668 use super::{comment_text, resolve_uri};
1669
1670 #[test]
1671 fn comments_never_hold_double_dashes() {
1672 assert_eq!(comment_text("a--b-"), "a- -b- ");
1673 assert_eq!(comment_text("-x"), "-x");
1674 assert_eq!(comment_text("---"), "- - - ");
1675 }
1676
1677 #[test]
1678 fn uris_resolve_against_the_base() {
1679 assert_eq!(resolve_uri("b.xml", Some("file:/d/a.xml")), "file:/d/b.xml");
1680 assert_eq!(
1681 resolve_uri("../c/b.xml", Some("file:/d/e/a.xml")),
1682 "file:/d/c/b.xml"
1683 );
1684 assert_eq!(
1685 resolve_uri("file:/x.xml", Some("file:/d/a.xml")),
1686 "file:/x.xml"
1687 );
1688 assert_eq!(resolve_uri("/x.xml", Some("file:/d/a.xml")), "file:/x.xml");
1689 assert_eq!(resolve_uri("x.xml", None), "x.xml");
1690 assert_eq!(resolve_uri("", Some("file:/d/a.xml")), "file:/d/a.xml");
1691 }
1692}