einvoice-xslt-exec 0.1.0

Executor of the XSLT 2.0 subset used by the official e-invoicing validation stylesheets: runs the compiled Schematron and writes SVRL, with the behaviour of Saxon-HE
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
//! Running an [`Executable`] on a document.
//!
//! Template rules are chosen as Saxon-HE chooses them: highest priority first, the last
//! declared on a tie (an ambiguity is reported as a warning, as Saxon does), then the
//! built-in rules of XSLT 2.0 section 6.6. A dynamic error while matching a pattern is
//! recovered as Saxon recovers it: a warning, and the rule does not match. Variables live in frames, one per template,
//! function or global variable invocation; the XPath evaluator reads them through the
//! [`Host`] interface, and calls stylesheet functions through it too.
//!
//! Evaluation order follows Saxon where it is observable (which dynamic errors are
//! raised): global variables are evaluated when first referenced; a local variable or
//! parameter that nothing refers to is never evaluated; one whose `select` may return
//! several items is evaluated when first referenced; any other is evaluated where it is
//! declared.

use std::borrow::Cow;
use std::cell::{Cell, OnceCell, RefCell};
use std::collections::HashSet;
use std::rc::{Rc, Weak};

use einvoice_xdm::{AtomicType, AtomicValue, DateTime};
use einvoice_xpath::{AtomicKind, ItemType, Occurrence, QName, SequenceType};
use einvoice_xpath_eval::{
    Clock, CompiledExpr, Context, Document, DynamicContext, ErrorCode, FunctionId, Host, Item,
    Node, NodeAxis, NodeKind, VariableId,
};
use einvoice_xslt::NumberLevel;

use crate::error::{Result, TransformError, err};
use crate::pattern::{self, Matcher};
use crate::prepare::{
    AvtItem, Binding, CompiledAvt, CountPattern, Executable, Inst, ModeRef, Value, WithParam,
};
use crate::sink::{SequenceSink, Sink, TextSink, TreeSink, XmlWriter, attribute_name};

/// Fetches the documents that `document()` asks for, by absolute URI. The engine never
/// reads files or the network itself.
pub trait DocumentResolver {
    /// The text of the document at `uri`, or `None` when it cannot be retrieved.
    fn resolve(&self, uri: &str) -> Option<String>;
}

/// Options of a transformation.
#[derive(Default)]
pub struct TransformOptions<'r> {
    /// The implicit timezone in minutes east of UTC (Saxon takes the JVM's). Default: UTC.
    pub implicit_timezone: Option<i16>,
    /// The value of `fn:current-dateTime()`, with a timezone. Default: the system clock,
    /// read once per transformation; required on targets without one
    /// (`wasm32-unknown-unknown`).
    pub current_date_time: Option<DateTime>,
    /// Values of the global parameters (`xsl:param`), by name.
    pub parameters: Vec<(QName, Vec<Item>)>,
    /// Where `document()` gets documents other than the source document.
    pub resolver: Option<&'r dyn DocumentResolver>,
}

impl std::fmt::Debug for TransformOptions<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TransformOptions")
            .field("implicit_timezone", &self.implicit_timezone)
            .field("current_date_time", &self.current_date_time)
            .field("parameters", &self.parameters)
            .field("resolver", &self.resolver.map(|_| "..."))
            .finish()
    }
}

/// The result of a transformation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Transformation {
    /// The result document, serialized as `xsl:output` asks.
    pub output: String,
    /// Recoverable conditions reported as warnings, as Saxon reports them, each
    /// distinct message once in the order first reported, as Saxon's standard error
    /// reporter prints them: ambiguous template rule matches (`XTDE0540: ...`), and
    /// dynamic errors raised while matching a pattern, after which the node is taken
    /// not to match (`line <L>: <CODE>: An error occurred matching pattern {...}:
    /// <message>`, `L` the line of the `xsl:template` or `xsl:number`).
    pub warnings: Vec<String>,
}

impl Executable {
    /// Runs the stylesheet on a document: `xsl:apply-templates` on its document node in
    /// the default mode, the result serialized. `base_uri` is the URI of the document:
    /// the base URI of its nodes, and the URI under which `document()` loads it again. As
    /// in Saxon-HE 12.10, it is not its document URI: `document-uri(/)` is empty.
    ///
    /// The source text can be borrowed (`&str`, `&String`) or given (`String`), as for
    /// [`Document::parse`]: borrowed, the texts of its nodes are copied into the tree;
    /// given, the tree keeps the text and refers to it, so that the document is in memory
    /// once. A given text is kept as a copy only for a stylesheet that calls
    /// `document()` and a document with a `base_uri`, where `document()` may load the
    /// document again from its text.
    ///
    /// # Errors
    ///
    /// The document is not well-formed (or has a document type declaration), or the
    /// transformation raised a dynamic error.
    pub fn transform<'s>(
        &self,
        source: impl Into<Cow<'s, str>>,
        base_uri: Option<&str>,
    ) -> std::result::Result<Transformation, TransformError> {
        self.transform_with(source, base_uri, &TransformOptions::default())
    }

    /// [`Executable::transform`] with options.
    ///
    /// # Errors
    ///
    /// As [`Executable::transform`], and an invalid timezone or current date and time
    /// (or none given on a target without a system clock).
    pub fn transform_with<'s>(
        &self,
        source: impl Into<Cow<'s, str>>,
        base_uri: Option<&str>,
        options: &TransformOptions<'_>,
    ) -> std::result::Result<Transformation, TransformError> {
        let source = source.into();
        // The text `document()` parses again when asked for the source document.
        let source_text = match &source {
            Cow::Borrowed(text) => Some(Cow::Borrowed(*text)),
            Cow::Owned(text) if self.calls_document && base_uri.is_some() => {
                Some(Cow::Owned(text.clone()))
            }
            Cow::Owned(_) => None,
        };
        let document = Document::parse(source, base_uri)
            .map_err(|e| TransformError::new("SXXP0003", e.message()))?;
        let root = document.root();
        let runtime = Runtime {
            exe: self,
            source_root: root.clone(),
            source_text: RefCell::new(source_text),
            source_uri: base_uri,
            options,
            dc: Cell::new(None),
            globals: (0..self.globals.len())
                .map(|_| RefCell::new(GlobalState::Pending))
                .collect(),
            frames: RefCell::new(Vec::new()),
            documents: RefCell::new(Vec::new()),
            warnings: RefCell::new(Vec::new()),
            warned: RefCell::new(HashSet::new()),
            stashed: RefCell::new(None),
        };
        let timezone = options.implicit_timezone.unwrap_or(0);
        let clock = match options.current_date_time {
            Some(now) => Clock::new(timezone, now)?,
            None => system_clock(timezone)?,
        };
        let dc = DynamicContext::new(&runtime, clock);
        runtime.dc.set(Some(&dc));
        let mut writer = XmlWriter::new(self.serialization);
        runtime.apply_rule(&root, 1, 1, self.default_mode, None, &[], &mut writer)?;
        let output = writer.finish()?;
        let warnings = runtime.warnings.take();
        Ok(Transformation { output, warnings })
    }
}

/// The system clock, in the implicit timezone.
#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
fn system_clock(timezone: i16) -> Result<Clock> {
    Ok(Clock::system(timezone)?)
}

/// No system clock on this target: the caller must give the current date and time.
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
fn system_clock(_timezone: i16) -> Result<Clock> {
    Err(einvoice_xpath_eval::Error::new(
        ErrorCode::Unsupported,
        "no system clock on this target: give TransformOptions::current_date_time",
    )
    .into())
}

#[derive(Debug)]
enum GlobalState {
    Pending,
    Evaluating,
    Done(Rc<[Item]>),
}

/// A value computed when first read.
struct Thunk<'e> {
    expr: &'e CompiledExpr,
    as_type: Option<&'e SequenceType>,
    code: &'static str,
    context: Context,
    /// The frame the expression's variables are read from.
    frame: Option<Weak<Frame<'e>>>,
    memo: OnceCell<Rc<[Item]>>,
}

#[derive(Clone)]
enum Slot<'e> {
    Unset,
    Value(Rc<[Item]>),
    Lazy(Rc<Thunk<'e>>),
}

/// The variables of one invocation.
struct Frame<'e> {
    slots: RefCell<Vec<Slot<'e>>>,
}

impl Frame<'_> {
    fn new(slots: usize) -> Rc<Self> {
        Rc::new(Self {
            slots: RefCell::new(vec![Slot::Unset; slots]),
        })
    }
}

/// The XSLT part of the dynamic context of an instruction.
struct State<'c> {
    context: &'c Context,
    mode: usize,
    /// The rank of the current template rule in `mode`, if any.
    rule: Option<u32>,
}

type Params<'e> = Vec<(&'e QName, Slot<'e>)>;

struct Runtime<'e, 'a> {
    exe: &'e Executable,
    source_root: Node,
    /// The text of the source document, until `document()` loads it again (absent when
    /// the stylesheet never calls `document()` and the text was given to the tree).
    source_text: RefCell<Option<Cow<'a, str>>>,
    source_uri: Option<&'a str>,
    options: &'a TransformOptions<'a>,
    dc: Cell<Option<&'a DynamicContext<'a>>>,
    globals: Vec<RefCell<GlobalState>>,
    frames: RefCell<Vec<Rc<Frame<'e>>>>,
    /// Documents loaded by `document()`, by absolute URI.
    documents: RefCell<Vec<(String, Node)>>,
    /// The warnings, each distinct one once, in the order first reported.
    warnings: RefCell<Vec<String>>,
    warned: RefCell<HashSet<String>>,
    /// The error a host callback raised, given back when the evaluator returns it.
    stashed: RefCell<Option<TransformError>>,
}

/// Sets the line of an error.
trait At<T> {
    fn at(self, line: u32) -> Result<T>;
}

impl<T> At<T> for Result<T> {
    fn at(self, line: u32) -> Result<T> {
        self.map_err(|e| e.at(line))
    }
}

/// XPath type names, for messages.
fn type_name(t: &SequenceType) -> String {
    let item = match &t.item {
        ItemType::Atomic(a) => a.name.to_string(),
        ItemType::Kind(k) => format!("{k:?}"),
    };
    let occurrence = match t.occurrence {
        Occurrence::One => "",
        Occurrence::ZeroOrOne => "?",
        Occurrence::ZeroOrMore => "*",
        Occurrence::OneOrMore => "+",
    };
    format!("{item}{occurrence}")
}

const fn atomic_type(kind: AtomicKind) -> AtomicType {
    match kind {
        AtomicKind::String => AtomicType::String,
        AtomicKind::AnyUri => AtomicType::AnyUri,
        AtomicKind::Boolean => AtomicType::Boolean,
        AtomicKind::Integer => AtomicType::Integer,
        AtomicKind::Decimal => AtomicType::Decimal,
        AtomicKind::Date => AtomicType::Date,
    }
}

/// Converts a value to a sequence type with the function conversion rules (XPath 2.0
/// section 3.1.5): atomization, `xs:untypedAtomic` cast to the expected type, URI
/// promotion to `xs:string`, then the item type and cardinality checks.
fn convert(items: Vec<Item>, t: &SequenceType, code: &str) -> Result<Vec<Item>> {
    let count = items.len();
    let cardinality_ok = match t.occurrence {
        Occurrence::One => count == 1,
        Occurrence::ZeroOrOne => count <= 1,
        Occurrence::ZeroOrMore => true,
        Occurrence::OneOrMore => count >= 1,
    };
    if !cardinality_ok {
        return err(
            code,
            format!(
                "Required cardinality of value is {}; supplied value has {count} items",
                type_name(t)
            ),
        );
    }
    match &t.item {
        ItemType::Atomic(a) => {
            let target = atomic_type(a.kind);
            items
                .into_iter()
                .map(|item| {
                    let value = item.atomize();
                    let value = match value {
                        AtomicValue::UntypedAtomic(_) => value.cast(target)?,
                        AtomicValue::AnyUri(s) if target == AtomicType::String => {
                            AtomicValue::String(s)
                        }
                        v if v.is_instance_of(target) => v,
                        v => {
                            return err(
                                code,
                                format!(
                                    "Required item type of value is {}; supplied value has item type {}",
                                    a.name,
                                    v.atomic_type()
                                ),
                            );
                        }
                    };
                    Ok(Item::Atomic(value))
                })
                .collect()
        }
        ItemType::Kind(kind) => {
            let test = pattern::step_test(
                match kind {
                    einvoice_xpath::KindTest::Attribute(_) => {
                        einvoice_xpath::PatternAxis::Attribute
                    }
                    _ => einvoice_xpath::PatternAxis::Child,
                },
                &einvoice_xpath::NodeTest::Kind(kind.clone()),
            );
            for item in &items {
                let ok = match item {
                    Item::Node(n) => {
                        matches!(kind, einvoice_xpath::KindTest::AnyKind) || test.matches(n)
                    }
                    Item::Atomic(_) => false,
                };
                if !ok {
                    return err(
                        code,
                        format!("Required item type of value is {}", type_name(t)),
                    );
                }
            }
            Ok(items)
        }
    }
}

/// Inserts a space where a comment's text would contain `--` or end with `-` (XSLT 2.0
/// section 11.6).
fn comment_text(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut previous_dash = false;
    for c in text.chars() {
        if c == '-' && previous_dash {
            out.push(' ');
        }
        previous_dash = c == '-';
        out.push(c);
    }
    if previous_dash {
        out.push(' ');
    }
    out
}

/// Resolves a URI reference against a base URI (RFC 3986 section 5.2, without the
/// query and fragment cases the rule sets never produce).
fn resolve_uri(reference: &str, base: Option<&str>) -> String {
    let has_scheme = reference.split_once(':').is_some_and(|(scheme, _)| {
        let mut chars = scheme.chars();
        chars.next().is_some_and(|c| c.is_ascii_alphabetic())
            && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
    });
    let Some(base) = base.filter(|_| !has_scheme) else {
        return reference.to_owned();
    };
    if reference.is_empty() {
        return base.to_owned();
    }
    let joined = if reference.starts_with('/') {
        match base.split_once(':') {
            Some((scheme, _)) => format!("{scheme}:{reference}"),
            None => reference.to_owned(),
        }
    } else {
        let directory = base.rfind('/').map_or("", |i| &base[..=i]);
        format!("{directory}{reference}")
    };
    // Remove `.` and `..` segments.
    let (prefix, path) = joined.split_once(':').unwrap_or(("", &joined));
    let mut segments: Vec<&str> = Vec::new();
    for segment in path.split('/') {
        match segment {
            "." => {}
            ".." => {
                if segments.len() > 1 {
                    segments.pop();
                }
            }
            s => segments.push(s),
        }
    }
    let path = segments.join("/");
    if prefix.is_empty() {
        path
    } else {
        format!("{prefix}:{path}")
    }
}

impl<'e, 'a> Runtime<'e, 'a> {
    fn dc(&self) -> Result<&'a DynamicContext<'a>> {
        self.dc
            .get()
            .ok_or_else(|| TransformError::new("INTERNAL", "no dynamic context"))
    }

    /// Converts an evaluator error, giving back the error a host callback raised.
    fn xerr(&self, e: einvoice_xpath_eval::Error) -> TransformError {
        if e.code() == ErrorCode::Host
            && let Some(stashed) = self.stashed.borrow_mut().take()
        {
            return stashed;
        }
        e.into()
    }

    /// Keeps an error for [`Runtime::xerr`] and gives the evaluator a placeholder.
    fn stash(&self, e: TransformError) -> einvoice_xpath_eval::Error {
        let message = e.to_string();
        *self.stashed.borrow_mut() = Some(e);
        einvoice_xpath_eval::Error::new(ErrorCode::Host, message)
    }

    fn evaluate(&self, expr: &CompiledExpr, context: &Context) -> Result<Vec<Item>> {
        expr.evaluate(self.dc()?, context).map_err(|e| self.xerr(e))
    }

    fn test(&self, expr: &CompiledExpr, context: &Context) -> Result<bool> {
        expr.effective_boolean_value(self.dc()?, context)
            .map_err(|e| self.xerr(e))
    }

    /// Runs `f` with `frame` as the frame variables are read from.
    fn in_frame<T>(
        &self,
        frame: Option<Rc<Frame<'e>>>,
        f: impl FnOnce() -> Result<T>,
    ) -> Result<T> {
        let Some(frame) = frame else {
            return f();
        };
        self.frames.borrow_mut().push(frame);
        let result = f();
        self.frames.borrow_mut().pop();
        result
    }

    fn top_frame(&self) -> Option<Rc<Frame<'e>>> {
        self.frames.borrow().last().cloned()
    }

    fn set_slot(&self, slot: usize, value: Slot<'e>) -> Result<()> {
        let frames = self.frames.borrow();
        let Some(frame) = frames.last() else {
            return err("INTERNAL", "no frame for a local variable");
        };
        let mut slots = frame.slots.borrow_mut();
        let Some(s) = slots.get_mut(slot) else {
            return err("INTERNAL", "variable slot out of range");
        };
        *s = value;
        Ok(())
    }

    fn force(&self, thunk: &Thunk<'e>) -> Result<Rc<[Item]>> {
        if let Some(value) = thunk.memo.get() {
            return Ok(Rc::clone(value));
        }
        let frame = match &thunk.frame {
            None => None,
            Some(weak) => Some(
                weak.upgrade()
                    .ok_or_else(|| TransformError::new("INTERNAL", "variable frame is gone"))?,
            ),
        };
        let items = self.in_frame(frame, || self.evaluate(thunk.expr, &thunk.context))?;
        let items = match thunk.as_type {
            Some(t) => convert(items, t, thunk.code)?,
            None => items,
        };
        let value: Rc<[Item]> = items.into();
        let _ = thunk.memo.set(Rc::clone(&value));
        Ok(value)
    }

    fn slot_value(&self, slot: &Slot<'e>) -> Result<Rc<[Item]>> {
        match slot {
            Slot::Value(v) => Ok(Rc::clone(v)),
            Slot::Lazy(thunk) => self.force(thunk),
            Slot::Unset => err("INTERNAL", "variable read before it is bound"),
        }
    }

    fn variable(&self, id: VariableId) -> Result<Rc<[Item]>> {
        let index = id.0 as usize;
        let globals = self.exe.globals.len();
        if index < globals {
            return self.global(index);
        }
        let slot = {
            let frames = self.frames.borrow();
            let Some(frame) = frames.last() else {
                return err("INTERNAL", "no frame for a local variable");
            };
            let slots = frame.slots.borrow();
            slots
                .get(index - globals)
                .cloned()
                .ok_or_else(|| TransformError::new("INTERNAL", "variable slot out of range"))?
        };
        self.slot_value(&slot)
    }

    fn global(&self, index: usize) -> Result<Rc<[Item]>> {
        let g = &self.exe.globals[index];
        {
            let mut state = self.globals[index].borrow_mut();
            match &*state {
                GlobalState::Done(v) => return Ok(Rc::clone(v)),
                GlobalState::Evaluating => {
                    return err(
                        "XTDE0640",
                        format!("Circular definition of global variable ${}", g.name),
                    )
                    .at(g.line);
                }
                GlobalState::Pending => *state = GlobalState::Evaluating,
            }
        }
        let supplied = if g.is_param {
            self.options
                .parameters
                .iter()
                .find(|(n, _)| n.same_expanded_name(&g.name))
        } else {
            None
        };
        let value = if let Some((_, items)) = supplied {
            match &g.as_type {
                Some(t) => convert(items.clone(), t, "XTTE0590"),
                None => Ok(items.clone()),
            }
            .map(Rc::from)
        } else {
            let context = Context::for_item(Item::Node(self.source_root.clone()));
            let state = State {
                context: &context,
                mode: self.exe.default_mode,
                rule: None,
            };
            let frame = (g.slots > 0).then(|| Frame::new(g.slots));
            let code = if g.is_param { "XTTE0590" } else { "XTTE0570" };
            self.in_frame(frame, || {
                self.value(&g.value, g.as_type.as_ref(), &state, code)
            })
        };
        let value = match value {
            Ok(v) => v,
            Err(e) => {
                *self.globals[index].borrow_mut() = GlobalState::Pending;
                return Err(e.at(g.line));
            }
        };
        *self.globals[index].borrow_mut() = GlobalState::Done(Rc::clone(&value));
        Ok(value)
    }

    /// The value of a binding, computed now.
    fn value(
        &self,
        value: &'e Value,
        as_type: Option<&'e SequenceType>,
        state: &State<'_>,
        code: &str,
    ) -> Result<Rc<[Item]>> {
        let items = match value {
            Value::Select(expr) => self.evaluate(expr, state.context)?,
            Value::Content(body) => {
                if as_type.is_some() {
                    let mut sink = SequenceSink::default();
                    self.exec(body, state, &mut sink)?;
                    sink.items
                } else {
                    let mut sink = TreeSink::new();
                    self.exec(body, state, &mut sink)?;
                    vec![Item::Node(sink.finish()?.root())]
                }
            }
            Value::Absent => {
                if as_type.is_some() {
                    Vec::new()
                } else {
                    vec![Item::Atomic(AtomicValue::String(String::new()))]
                }
            }
        };
        let items = match as_type {
            Some(t) => convert(items, t, code)?,
            None => items,
        };
        Ok(items.into())
    }

    /// A binding's slot: computed now, or later when it may be a sequence.
    fn bind(
        &self,
        value: &'e Value,
        as_type: Option<&'e SequenceType>,
        lazy: bool,
        state: &State<'_>,
        code: &'static str,
    ) -> Result<Slot<'e>> {
        if lazy && let Value::Select(expr) = value {
            return Ok(Slot::Lazy(Rc::new(Thunk {
                expr,
                as_type,
                code,
                context: state.context.clone(),
                frame: self.top_frame().map(|f| Rc::downgrade(&f)),
                memo: OnceCell::new(),
            })));
        }
        Ok(Slot::Value(self.value(value, as_type, state, code)?))
    }

    fn with_params(&self, params: &'e [WithParam], state: &State<'_>) -> Result<Params<'e>> {
        params
            .iter()
            .map(|p| {
                Ok((
                    &p.name,
                    self.bind(&p.value, p.as_type.as_ref(), p.lazy, state, "XTTE0590")?,
                ))
            })
            .collect()
    }

    fn exec(&self, body: &'e [Inst], state: &State<'_>, sink: &mut dyn Sink) -> Result<()> {
        for inst in body {
            self.instruction(inst, state, sink)?;
        }
        Ok(())
    }

    #[expect(
        clippy::too_many_lines,
        reason = "one arm per instruction of the supported subset"
    )]
    fn instruction(&self, inst: &'e Inst, state: &State<'_>, sink: &mut dyn Sink) -> Result<()> {
        match inst {
            Inst::ApplyTemplates {
                line,
                select,
                mode,
                params,
            } => {
                let items = self.evaluate(select, state.context).at(*line)?;
                let mode = match mode {
                    ModeRef::Mode(m) => *m,
                    ModeRef::Current => state.mode,
                };
                let params = self.with_params(params, state).at(*line)?;
                let size = items.len();
                for (i, item) in items.iter().enumerate() {
                    match item {
                        Item::Node(node) => self
                            .apply_rule(node, i + 1, size, mode, None, &params, sink)
                            .at(*line)?,
                        // As Saxon, an XSLT 3.0 processor: no pattern of the subset
                        // matches an atomic value, whose built-in rule writes it as text.
                        Item::Atomic(_) => sink.text(&item.string_value()).at(*line)?,
                    }
                }
                Ok(())
            }
            Inst::NextMatch { line, params } => {
                let Some(rank) = state.rule else {
                    return err("XTDE0560", "xsl:next-match without a current template rule")
                        .at(*line);
                };
                let Some(focus) = &state.context.focus else {
                    return err("XTDE0560", "xsl:next-match without a context item").at(*line);
                };
                let Item::Node(node) = &focus.item else {
                    return err("XTDE0560", "xsl:next-match on an atomic value").at(*line);
                };
                let params = self.with_params(params, state).at(*line)?;
                self.apply_rule(
                    node,
                    focus.position,
                    focus.size,
                    state.mode,
                    Some(rank),
                    &params,
                    sink,
                )
                .at(*line)
            }
            Inst::CallTemplate {
                line,
                template,
                params,
            } => {
                let params = self.with_params(params, state).at(*line)?;
                self.invoke(
                    *template,
                    state.context,
                    state.mode,
                    state.rule,
                    &params,
                    sink,
                )
                .at(*line)
            }
            Inst::Choose { whens, otherwise } => {
                for when in whens {
                    if self.test(&when.test, state.context).at(when.line)? {
                        return self.exec(&when.body, state, sink);
                    }
                }
                self.exec(otherwise, state, sink)
            }
            Inst::ForEach { line, select, body } => {
                let items = self.evaluate(select, state.context).at(*line)?;
                let size = items.len();
                for (i, item) in items.into_iter().enumerate() {
                    let context = Context::at(item, i + 1, size);
                    let inner = State {
                        context: &context,
                        mode: state.mode,
                        rule: None,
                    };
                    self.exec(body, &inner, sink)?;
                }
                Ok(())
            }
            Inst::Variable(binding) => self.variable_instruction(binding, state),
            Inst::Sequence { line, select } => {
                for item in self.evaluate(select, state.context).at(*line)? {
                    sink.item(&item).at(*line)?;
                }
                Ok(())
            }
            Inst::ValueOf {
                line,
                select,
                separator,
                body,
            } => {
                let separator = match separator {
                    Some(avt) => Some(self.avt(avt, state).at(*line)?),
                    None => None,
                };
                let mut parts = TextSink::new();
                let text = if let Some(expr) = select {
                    for item in self.evaluate(expr, state.context).at(*line)? {
                        parts.item(&item)?;
                    }
                    parts.finish(separator.as_deref().unwrap_or(" "))
                } else {
                    self.exec(body, state, &mut parts)?;
                    parts.finish(separator.as_deref().unwrap_or(""))
                };
                sink.text(&text).at(*line)
            }
            Inst::Attribute {
                line,
                name,
                namespaces,
                select,
                body,
            } => {
                let name = self.avt(name, state).at(*line)?;
                let name = attribute_name(&name, namespaces).at(*line)?;
                let value = self
                    .simple_content(select.as_deref(), body, state)
                    .at(*line)?;
                sink.attribute(&name, &value).at(*line)
            }
            Inst::Comment { line, body } => {
                let mut parts = TextSink::new();
                self.exec(body, state, &mut parts)?;
                sink.comment(&comment_text(&parts.finish(""))).at(*line)
            }
            Inst::Text(text) => sink.text(text),
            Inst::Number { line, level, count } => {
                let text = self
                    .number(*line, *level, count.as_ref(), state)
                    .at(*line)?;
                sink.text(&text).at(*line)
            }
            Inst::Element {
                line,
                name,
                namespaces,
                attributes,
                body,
            } => {
                sink.start_element(name, namespaces).at(*line)?;
                for (attribute, value) in attributes {
                    let value = self.avt(value, state).at(*line)?;
                    sink.attribute(attribute, &value).at(*line)?;
                }
                self.exec(body, state, sink)?;
                sink.end_element().at(*line)
            }
        }
    }

    fn variable_instruction(&self, binding: &'e Binding, state: &State<'_>) -> Result<()> {
        if !binding.used {
            return Ok(());
        }
        let slot = self
            .bind(
                &binding.value,
                binding.as_type.as_ref(),
                binding.lazy,
                state,
                "XTTE0570",
            )
            .at(binding.line)?;
        self.set_slot(binding.slot, slot).at(binding.line)
    }

    /// The value of `xsl:attribute`: `select` joined with spaces, or the content.
    fn simple_content(
        &self,
        select: Option<&'e CompiledExpr>,
        body: &'e [Inst],
        state: &State<'_>,
    ) -> Result<String> {
        let mut parts = TextSink::new();
        if let Some(expr) = select {
            for item in self.evaluate(expr, state.context)? {
                parts.item(&item)?;
            }
            Ok(parts.finish(" "))
        } else {
            self.exec(body, state, &mut parts)?;
            Ok(parts.finish(""))
        }
    }

    fn avt(&self, avt: &'e CompiledAvt, state: &State<'_>) -> Result<String> {
        if let [AvtItem::Text(text)] = avt.0.as_slice() {
            return Ok(text.to_string());
        }
        let mut out = String::new();
        for item in &avt.0 {
            match item {
                AvtItem::Text(text) => out.push_str(text),
                AvtItem::Expr(expr) => {
                    for (i, value) in self.evaluate(expr, state.context)?.iter().enumerate() {
                        if i > 0 {
                            out.push(' ');
                        }
                        out.push_str(&value.atomize().to_string());
                    }
                }
            }
        }
        Ok(out)
    }

    /// Finds the best rule for `node` in `mode` (ranked after `after`, for
    /// `xsl:next-match`) and runs it, or the built-in rule.
    #[expect(
        clippy::too_many_arguments,
        reason = "the focus, the mode, the rule and the parameters of the invocation"
    )]
    fn apply_rule(
        &self,
        node: &Node,
        position: usize,
        size: usize,
        mode: usize,
        after: Option<u32>,
        params: &[(&'e QName, Slot<'e>)],
        sink: &mut dyn Sink,
    ) -> Result<()> {
        match self.find_rule(mode, node, after)? {
            Some(rank) => {
                let template = self.exe.modes[mode].rules[rank as usize].template;
                let context = Context::at(Item::Node(node.clone()), position, size);
                self.invoke(template, &context, mode, Some(rank), params, sink)
            }
            None => self.builtin(node, mode, params, sink),
        }
    }

    /// Whether `node` matches the pattern of a rule. A dynamic error while matching is
    /// recovered as Saxon recovers it (see [`Runtime::pattern_error`]).
    fn rule_matches(&self, rank: u32, mode: usize, node: &Node) -> Result<bool> {
        let rule = &self.exe.modes[mode].rules[rank as usize];
        let template = &self.exe.templates[rule.template];
        let matcher = Matcher { dc: self.dc()? };
        // A union pattern with an explicit priority is one rule: its alternatives in
        // order, the first error ending the match.
        let (alternatives, text) = match rule.alternative {
            Some(index) => (
                template.pattern.get(index..=index).unwrap_or_default(),
                template
                    .alternative_texts
                    .get(index)
                    .map_or("", String::as_str),
            ),
            None => (template.pattern.as_slice(), template.pattern_text.as_str()),
        };
        let outcome = alternatives
            .iter()
            .try_fold(false, |found, a| Ok(found || matcher.matches(a, node)?));
        outcome.or_else(|e| self.pattern_error(e, template.line, text))
    }

    /// A dynamic error raised while matching a pattern (of a template rule, or the
    /// `count` pattern of `xsl:number`), as Saxon-HE 12.10 handles it
    /// (`Pattern.matchesItem`): the node does not match, and the error is reported as
    /// a warning, whatever its code, except a circularity (`XTDE0640`), which ends the
    /// transformation. A global variable whose evaluation failed is not kept in error:
    /// the next reference evaluates it again (`GlobalVariable.actuallyEvaluate`), in a
    /// pattern or elsewhere. The refusals and bugs of this crate (`UNSUPPORTED`,
    /// `INTERNAL`) are never recovered: Saxon would not have raised them.
    fn pattern_error(
        &self,
        e: einvoice_xpath_eval::Error,
        line: u32,
        pattern: &str,
    ) -> Result<bool> {
        let e = self.xerr(e);
        if matches!(e.code(), "XTDE0640" | "UNSUPPORTED" | "INTERNAL" | "HOST") {
            return Err(e.at(line));
        }
        self.warn(format!(
            "line {line}: {}: An error occurred matching pattern {{{pattern}}}: {}",
            e.code(),
            e.message()
        ));
        Ok(false)
    }

    /// Reports a warning, once: Saxon's standard error reporter prints each distinct
    /// warning once.
    fn warn(&self, message: String) {
        if self.warned.borrow_mut().insert(message.clone()) {
            self.warnings.borrow_mut().push(message);
        }
    }

    /// The rule for `node` in `mode`, chosen exactly as Saxon-HE 12.10 chooses it
    /// (`SimpleMode.getRule` and `searchRuleChain`): the chains of the node's name, of
    /// its kind, then the generic chain, each in rank order; a rule of higher priority
    /// replaces the best so far; on a tie the later declared rule wins and the ambiguity
    /// is reported as an XTDE0540 warning. For `xsl:next-match` (`after` is the current
    /// rule) only the rules ranked below the current one are candidates (lower
    /// priority, or same priority and declared before it, or an earlier part of the
    /// same template), and a tie between two parts of one template goes to the part
    /// found last.
    fn find_rule(&self, mode: usize, node: &Node, after: Option<u32>) -> Result<Option<u32>> {
        let compiled = &self.exe.modes[mode];
        let rules = &compiled.rules;
        let below_current = |rank: u32| -> bool {
            let Some(current) = after else {
                return true;
            };
            let (r, c) = (&rules[rank as usize], &rules[current as usize]);
            match r.priority.total_cmp(&c.priority) {
                std::cmp::Ordering::Less => true,
                std::cmp::Ordering::Greater => false,
                std::cmp::Ordering::Equal => {
                    r.sequence < c.sequence || (r.sequence == c.sequence && r.part < c.part)
                }
            }
        };
        let mut best: Option<u32> = None;
        for chain in compiled.chains(node.kind(), node.name()) {
            for &rank in chain {
                if !below_current(rank) {
                    continue;
                }
                let Some(chosen) = best else {
                    if self.rule_matches(rank, mode, node)? {
                        best = Some(rank);
                    }
                    continue;
                };
                let (head, b) = (&rules[rank as usize], &rules[chosen as usize]);
                match head.priority.total_cmp(&b.priority) {
                    std::cmp::Ordering::Less => break,
                    std::cmp::Ordering::Greater => {
                        if self.rule_matches(rank, mode, node)? {
                            best = Some(rank);
                        }
                    }
                    std::cmp::Ordering::Equal => {
                        if !self.rule_matches(rank, mode, node)? {
                            continue;
                        }
                        if head.template != b.template {
                            self.ambiguity(node, compiled, b, head);
                        }
                        // The later declared rule; between two parts of one template,
                        // the higher part, or for xsl:next-match the one found last.
                        let keep = b.sequence > head.sequence
                            || (b.sequence == head.sequence
                                && after.is_none()
                                && b.part > head.part);
                        best = Some(if keep { chosen } else { rank });
                        break;
                    }
                }
            }
        }
        Ok(best)
    }

    /// Reports a tie between `a`, the best rule so far, and `b`, as Saxon's
    /// `reportAmbiguity` does, naming them in that order.
    fn ambiguity(
        &self,
        node: &Node,
        mode: &crate::prepare::CompiledMode,
        a: &crate::prepare::Rule,
        b: &crate::prepare::Rule,
    ) {
        let (ta, tb) = (
            &self.exe.templates[a.template],
            &self.exe.templates[b.template],
        );
        let later = if a.sequence > b.sequence { ta } else { tb };
        self.warn(format!(
            "XTDE0540: Ambiguous rule match for {} in mode {}: matches the template rules on line {} and line {}; the one on line {} is used",
            describe(node),
            mode.name,
            ta.line,
            tb.line,
            later.line
        ));
    }

    fn builtin(
        &self,
        node: &Node,
        mode: usize,
        params: &[(&'e QName, Slot<'e>)],
        sink: &mut dyn Sink,
    ) -> Result<()> {
        match node.kind() {
            NodeKind::Document | NodeKind::Element => {
                let children: Vec<Node> = node.children().collect();
                let size = children.len();
                for (i, child) in children.iter().enumerate() {
                    self.apply_rule(child, i + 1, size, mode, None, params, sink)?;
                }
                Ok(())
            }
            NodeKind::Text | NodeKind::Attribute => sink.text(&node.string_value()),
            NodeKind::Comment | NodeKind::ProcessingInstruction => Ok(()),
        }
    }

    /// Runs a template: its parameters bound from `params` or their default values,
    /// then its body.
    fn invoke(
        &self,
        index: usize,
        context: &Context,
        mode: usize,
        rule: Option<u32>,
        params: &[(&'e QName, Slot<'e>)],
        sink: &mut dyn Sink,
    ) -> Result<()> {
        let template = &self.exe.templates[index];
        let frame = (template.slots > 0).then(|| Frame::new(template.slots));
        let state = State {
            context,
            mode,
            rule,
        };
        self.in_frame(frame, || {
            for param in &template.params {
                let passed = params
                    .iter()
                    .find(|(name, _)| name.same_expanded_name(&param.name));
                let slot = match (passed, &param.as_type) {
                    (Some((_, slot)), None) => slot.clone(),
                    (Some((_, slot)), Some(t)) => {
                        let items = self.slot_value(slot)?.to_vec();
                        Slot::Value(convert(items, t, "XTTE0590").at(param.line)?.into())
                    }
                    (None, as_type) => self
                        .bind(
                            &param.value,
                            as_type.as_ref(),
                            param.lazy,
                            &state,
                            "XTTE0590",
                        )
                        .at(param.line)?,
                };
                self.set_slot(param.slot, slot)?;
            }
            self.exec(&template.body, &state, sink)
        })
        .at(template.line)
    }

    fn call(&self, id: FunctionId, args: Vec<Vec<Item>>) -> Result<Vec<Item>> {
        let function = &self.exe.functions[id.0 as usize];
        let frame = Frame::new(function.slots);
        for (param, arg) in function.params.iter().zip(args) {
            let value = match &param.as_type {
                Some(t) => convert(arg, t, "XPTY0004").map_err(|e| {
                    TransformError::new(
                        e.code(),
                        format!(
                            "{} (argument ${} of {}())",
                            e.message(),
                            param.name,
                            function.name
                        ),
                    )
                })?,
                None => arg,
            };
            frame.slots.borrow_mut()[param.slot] = Slot::Value(value.into());
        }
        // A stylesheet function has no focus and no current template rule.
        let context = Context::new();
        let state = State {
            context: &context,
            mode: self.exe.default_mode,
            rule: None,
        };
        let mut sink = SequenceSink::default();
        self.in_frame(Some(frame), || self.exec(&function.body, &state, &mut sink))
            .at(function.line)?;
        match &function.as_type {
            Some(t) => convert(sink.items, t, "XTTE0780").at(function.line),
            None => Ok(sink.items),
        }
    }

    fn number(
        &self,
        line: u32,
        level: NumberLevel,
        count: Option<&'e CountPattern>,
        state: &State<'_>,
    ) -> Result<String> {
        let Some(Item::Node(node)) = state.context.focus.as_ref().map(|f| &f.item) else {
            return err("XTTE0990", "xsl:number needs a node as context item");
        };
        let matcher = Matcher { dc: self.dc()? };
        let counted = |n: &Node| -> Result<bool> {
            match count {
                // As a template rule's pattern, an error is recovered (Saxon's
                // `Navigator` matches the count pattern with `matchesItem`).
                Some(pattern) => pattern
                    .alternatives
                    .iter()
                    .try_fold(false, |found, a| Ok(found || matcher.matches(a, n)?))
                    .or_else(|e| self.pattern_error(e, line, &pattern.text)),
                None => Ok(n.kind() == node.kind()
                    && match (n.name(), node.name()) {
                        (Some(a), Some(b)) => a.same_expanded_name(b),
                        (None, None) => true,
                        _ => false,
                    }),
            }
        };
        let position = |n: &Node| -> Result<usize> {
            let mut p = 1;
            for sibling in n.axis(NodeAxis::PrecedingSibling) {
                if counted(&sibling)? {
                    p += 1;
                }
            }
            Ok(p)
        };
        let mut numbers = Vec::new();
        for ancestor in node.axis(NodeAxis::AncestorOrSelf) {
            if counted(&ancestor)? {
                numbers.push(position(&ancestor)?);
                if level == NumberLevel::Single {
                    break;
                }
            }
        }
        numbers.reverse();
        Ok(numbers
            .iter()
            .map(usize::to_string)
            .collect::<Vec<_>>()
            .join("."))
    }

    fn load_document(&self, uri: &str, base: Option<&str>) -> Result<Node> {
        let absolute = resolve_uri(uri, base.or(self.exe.base_uri.as_deref()));
        if let Some((_, node)) = self.documents.borrow().iter().find(|(u, _)| *u == absolute) {
            return Ok(node.clone());
        }
        // As Saxon: the source document, asked for by its base URI, is parsed again and
        // is a different tree. Loaded once: the tree is kept under its URI above.
        let text: Cow<'_, str> = if self.source_uri == Some(absolute.as_str()) {
            self.source_text.take().ok_or_else(|| {
                TransformError::new(
                    "INTERNAL",
                    "document() loads the source document, whose text was not kept",
                )
            })?
        } else {
            // The resolver's text is given to the tree, not copied.
            Cow::Owned(
                self.options
                    .resolver
                    .and_then(|r| r.resolve(&absolute))
                    .ok_or_else(|| {
                        TransformError::new(
                            "FODC0002",
                            format!("cannot retrieve the document at {absolute}"),
                        )
                    })?,
            )
        };
        // A loaded document has a document URI, as one in Saxon's document pool.
        let node = Document::parse_loaded(text, &absolute)
            .map_err(|e| TransformError::new("FODC0002", format!("{absolute}: {}", e.message())))?
            .root();
        self.documents.borrow_mut().push((absolute, node.clone()));
        Ok(node)
    }
}

/// A node, for messages: its path from the root, written as Saxon-HE 12.10 writes it
/// (`Navigator.getPath`): `/r/x[2]/@a`, `/r/text()[1]`, the outermost element without
/// position. Saxon's error reporter prints each distinct warning once, so the path tells
/// apart exactly the nodes Saxon's tells apart.
fn describe(node: &Node) -> String {
    let name = |n: &Node| n.name().map(ToString::to_string).unwrap_or_default();
    // The position among the preceding siblings of the same kind and, for a node with a
    // name, the same name (`Navigator.getNumberSimple`).
    let number = |n: &Node| {
        1 + n
            .axis(NodeAxis::PrecedingSibling)
            .filter(|s| {
                s.kind() == n.kind()
                    && match (s.name(), n.name()) {
                        (Some(a), Some(b)) => a.same_expanded_name(b),
                        (None, None) => true,
                        _ => false,
                    }
            })
            .count()
    };
    let parent = node.parent();
    let parent_path = || parent.as_ref().map(describe).unwrap_or_default();
    // A step under the parent, which is "/" for the document node.
    let under_parent = |step: String| {
        let path = parent_path();
        format!("{}/{step}", if path == "/" { "" } else { path.as_str() })
    };
    match node.kind() {
        NodeKind::Document => "/".to_owned(),
        NodeKind::Element => match &parent {
            None => name(node),
            Some(p) if p.kind() == NodeKind::Document => format!("/{}", name(node)),
            Some(_) => format!("{}/{}[{}]", parent_path(), name(node), number(node)),
        },
        NodeKind::Attribute => format!("{}/@{}", parent_path(), name(node)),
        NodeKind::Text => under_parent(format!("text()[{}]", number(node))),
        NodeKind::Comment => under_parent(format!("comment()[{}]", number(node))),
        NodeKind::ProcessingInstruction => {
            under_parent(format!("processing-instruction()[{}]", number(node)))
        }
    }
}

impl Host for Runtime<'_, '_> {
    fn variable(&self, id: VariableId) -> einvoice_xpath_eval::Result<Rc<[Item]>> {
        Runtime::variable(self, id).map_err(|e| self.stash(e))
    }

    fn call_function(
        &self,
        id: FunctionId,
        args: Vec<Vec<Item>>,
    ) -> einvoice_xpath_eval::Result<Vec<Item>> {
        self.call(id, args).map_err(|e| self.stash(e))
    }

    fn document(&self, uri: &str, base: Option<&str>) -> einvoice_xpath_eval::Result<Node> {
        self.load_document(uri, base).map_err(|e| self.stash(e))
    }

    fn system_property(&self, name: &QName) -> String {
        // Saxon-HE 12.10's values.
        if name.namespace.as_deref() != Some(einvoice_xslt::XSLT_NAMESPACE) {
            return String::new();
        }
        match name.local.as_str() {
            "version" => "3.0",
            "vendor" => "Saxonica",
            "vendor-url" => "http://www.saxonica.com/",
            "product-name" => "SAXON",
            "product-version" => "HE 12.10",
            _ => "",
        }
        .to_owned()
    }
}

#[cfg(test)]
mod tests {
    use super::{comment_text, resolve_uri};

    #[test]
    fn comments_never_hold_double_dashes() {
        assert_eq!(comment_text("a--b-"), "a- -b- ");
        assert_eq!(comment_text("-x"), "-x");
        assert_eq!(comment_text("---"), "- - - ");
    }

    #[test]
    fn uris_resolve_against_the_base() {
        assert_eq!(resolve_uri("b.xml", Some("file:/d/a.xml")), "file:/d/b.xml");
        assert_eq!(
            resolve_uri("../c/b.xml", Some("file:/d/e/a.xml")),
            "file:/d/c/b.xml"
        );
        assert_eq!(
            resolve_uri("file:/x.xml", Some("file:/d/a.xml")),
            "file:/x.xml"
        );
        assert_eq!(resolve_uri("/x.xml", Some("file:/d/a.xml")), "file:/x.xml");
        assert_eq!(resolve_uri("x.xml", None), "x.xml");
        assert_eq!(resolve_uri("", Some("file:/d/a.xml")), "file:/d/a.xml");
    }
}