einvoice-xslt-exec 0.2.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
//! Preparation: a loaded [`Stylesheet`] becomes an [`Executable`], once, to be run on any
//! number of documents. Every XPath expression is compiled against its static context
//! (global variables, the local variables in scope, the stylesheet functions), every
//! variable gets a slot in the frame of its template, function or global variable,
//! named templates and modes are resolved, and the template rules of each mode are
//! ranked and indexed by the kind and name of the nodes they can match.

use std::cell::{Cell, RefCell};
use std::collections::{BTreeSet, HashMap};
use std::sync::Arc;

use einvoice_xpath::{
    self as ast, Avt, AvtPart, Expr, NamespaceMap, Occurrence, QName, SequenceType, parse_expr,
};
use einvoice_xpath_eval::{
    BindingValue, Cardinality, CompiledExpr, FunctionId, StaticContext, ValueType, VariableId,
    VariableInfo, compile,
};
use einvoice_xslt::{
    ApplyMode, GlobalKind, Instruction, Mode, NamespaceBinding, NumberLevel, Priority, Standalone,
    Stylesheet, Template, TemplateModes, Variable, VariableValue,
};

use crate::error::{PrepareError, PrepareErrors};
use crate::pattern::{self, Alternative, Key};
use crate::sink::Serialization;

/// A stylesheet ready to run: prepared once, run on any number of documents with
/// [`Executable::transform`](crate::Executable::transform).
#[derive(Debug)]
pub struct Executable {
    pub(crate) globals: Vec<Global>,
    pub(crate) templates: Vec<CompiledTemplate>,
    pub(crate) functions: Vec<CompiledFunction>,
    pub(crate) modes: Vec<CompiledMode>,
    pub(crate) default_mode: usize,
    pub(crate) serialization: Serialization,
    /// The static base URI, against which `document()` resolves relative URIs given as
    /// strings.
    pub(crate) base_uri: Option<String>,
    /// Whether some expression calls `document()`, which may load the source document
    /// again from its text: a transformation given its source as an owned `String` then
    /// keeps the text (see [`Executable::transform`](crate::Executable::transform)).
    pub(crate) calls_document: bool,
}

/// A global variable or parameter.
#[derive(Debug)]
pub(crate) struct Global {
    pub(crate) name: QName,
    pub(crate) is_param: bool,
    pub(crate) line: u32,
    pub(crate) value: Value,
    pub(crate) as_type: Option<SequenceType>,
    /// Slots of the variables local to its sequence constructor.
    pub(crate) slots: usize,
}

/// How the value of a binding is computed.
#[derive(Debug)]
pub(crate) enum Value {
    Select(Box<CompiledExpr>),
    Content(Vec<Inst>),
    Absent,
}

/// A local variable, a template or function parameter: a slot of the frame.
#[derive(Debug)]
pub(crate) struct Binding {
    pub(crate) line: u32,
    pub(crate) name: QName,
    pub(crate) slot: usize,
    pub(crate) as_type: Option<SequenceType>,
    pub(crate) value: Value,
    /// Evaluated when first referenced rather than where it is declared: a `select`
    /// that may return more than one item (Saxon evaluates the others eagerly).
    pub(crate) lazy: bool,
    /// Whether some expression in its scope refers to it (an unused variable is never
    /// evaluated, as Saxon removes it).
    pub(crate) used: bool,
}

/// `xsl:with-param`.
#[derive(Debug)]
pub(crate) struct WithParam {
    pub(crate) name: QName,
    pub(crate) as_type: Option<SequenceType>,
    pub(crate) value: Value,
    pub(crate) lazy: bool,
}

#[derive(Debug)]
pub(crate) struct CompiledTemplate {
    pub(crate) line: u32,
    pub(crate) params: Vec<Binding>,
    pub(crate) body: Vec<Inst>,
    pub(crate) slots: usize,
    /// The compiled alternatives of the match pattern (empty without one).
    pub(crate) pattern: Vec<Alternative>,
    /// The match pattern as written, and each of its alternatives, for warnings.
    pub(crate) pattern_text: String,
    pub(crate) alternative_texts: Vec<String>,
}

#[derive(Debug)]
pub(crate) struct CompiledFunction {
    pub(crate) line: u32,
    pub(crate) name: QName,
    pub(crate) params: Vec<Binding>,
    pub(crate) as_type: Option<SequenceType>,
    pub(crate) body: Vec<Inst>,
    pub(crate) slots: usize,
}

/// The mode of `xsl:apply-templates`.
#[derive(Debug, Clone, Copy)]
pub(crate) enum ModeRef {
    Mode(usize),
    Current,
}

/// An attribute value template.
#[derive(Debug)]
pub(crate) struct CompiledAvt(pub(crate) Vec<AvtItem>);

#[derive(Debug)]
pub(crate) enum AvtItem {
    Text(Box<str>),
    Expr(Box<CompiledExpr>),
}

/// An instruction of a sequence constructor.
#[derive(Debug)]
pub(crate) enum Inst {
    ApplyTemplates {
        line: u32,
        select: Box<CompiledExpr>,
        mode: ModeRef,
        params: Vec<WithParam>,
    },
    NextMatch {
        line: u32,
        params: Vec<WithParam>,
    },
    CallTemplate {
        line: u32,
        template: usize,
        params: Vec<WithParam>,
    },
    /// `xsl:choose`, and `xsl:if` as a choose with one branch.
    Choose {
        whens: Vec<When>,
        otherwise: Vec<Inst>,
    },
    ForEach {
        line: u32,
        select: Box<CompiledExpr>,
        body: Vec<Inst>,
    },
    Variable(Box<Binding>),
    Sequence {
        line: u32,
        select: Box<CompiledExpr>,
    },
    ValueOf {
        line: u32,
        select: Option<Box<CompiledExpr>>,
        separator: Option<CompiledAvt>,
        body: Vec<Inst>,
    },
    Attribute {
        line: u32,
        name: CompiledAvt,
        namespaces: Arc<[NamespaceBinding]>,
        select: Option<Box<CompiledExpr>>,
        body: Vec<Inst>,
    },
    Comment {
        line: u32,
        body: Vec<Inst>,
    },
    Text(Box<str>),
    Number {
        line: u32,
        level: NumberLevel,
        /// `None`: nodes of the context node's kind and name.
        count: Option<CountPattern>,
    },
    Element {
        line: u32,
        name: Arc<QName>,
        namespaces: Arc<[NamespaceBinding]>,
        attributes: Vec<(Arc<QName>, CompiledAvt)>,
        body: Vec<Inst>,
    },
}

/// A branch of `xsl:choose` (`xsl:when`), or `xsl:if`: an error in its test is
/// attributed to its own line, as Saxon attributes it.
#[derive(Debug)]
pub(crate) struct When {
    pub(crate) line: u32,
    pub(crate) test: Box<CompiledExpr>,
    pub(crate) body: Vec<Inst>,
}

/// The `count` pattern of `xsl:number`, and its text for warnings.
#[derive(Debug)]
pub(crate) struct CountPattern {
    pub(crate) alternatives: Vec<Alternative>,
    pub(crate) text: String,
}

/// A template rule as Saxon-HE 12.10 registers it: one per alternative of a match
/// pattern without explicit priority (`A | B` is split into rules, XSLT 2.0 section
/// 6.4), one for the whole pattern with an explicit priority.
#[derive(Debug)]
pub(crate) struct Rule {
    pub(crate) template: usize,
    /// The alternative of the template's pattern; `None` for the whole pattern.
    pub(crate) alternative: Option<usize>,
    /// The priority, compared as Saxon compares it: as a double.
    pub(crate) priority: f64,
    /// Declaration order: the template's position.
    pub(crate) sequence: usize,
    /// The position of the alternative among the rules split from the same template
    /// without explicit priority; 0 for a pattern with an explicit priority (Saxon's
    /// `part`, which keeps `xsl:next-match` from running the same template twice).
    pub(crate) part: usize,
}

/// Rule ranks of elements or attributes by local name, then namespace.
type ByName = HashMap<String, Vec<(Option<String>, Vec<u32>)>>;

/// The rules of a mode and Saxon's rule chains: the ranks of the rules that can match
/// nodes of one name (elements, attributes), of one kind, or of any kind, each chain in
/// rank order.
#[derive(Debug, Default)]
pub(crate) struct CompiledMode {
    pub(crate) name: String,
    /// In rank order: priority descending, then declaration order descending, then part
    /// descending (Saxon puts a rule added later before the earlier ones of the same
    /// priority).
    pub(crate) rules: Vec<Rule>,
    elements: ByName,
    attributes: ByName,
    any_element: Vec<u32>,
    any_attribute: Vec<u32>,
    text: Vec<u32>,
    comment: Vec<u32>,
    processing_instruction: Vec<u32>,
    document: Vec<u32>,
    generic: Vec<u32>,
}

const EMPTY: &[u32] = &[];

impl CompiledMode {
    fn named<'a>(map: &'a ByName, name: Option<&QName>) -> &'a [u32] {
        let Some(name) = name else {
            return EMPTY;
        };
        map.get(name.local.as_str())
            .and_then(|by_ns| {
                by_ns
                    .iter()
                    .find(|(ns, _)| ns.as_deref() == name.namespace.as_deref())
            })
            .map_or(EMPTY, |(_, ranks)| ranks.as_slice())
    }

    /// The chains Saxon searches for a node of that kind and name, in its order: the
    /// chain of the name, the chain of the kind, the generic chain.
    pub(crate) fn chains(
        &self,
        kind: einvoice_xpath_eval::NodeKind,
        name: Option<&QName>,
    ) -> [&[u32]; 3] {
        use einvoice_xpath_eval::NodeKind as K;
        let kind_chain: (&[u32], &[u32]) = match kind {
            K::Element => (Self::named(&self.elements, name), &self.any_element),
            K::Attribute => (Self::named(&self.attributes, name), &self.any_attribute),
            K::Text => (EMPTY, &self.text),
            K::Comment => (EMPTY, &self.comment),
            K::ProcessingInstruction => (EMPTY, &self.processing_instruction),
            K::Document => (EMPTY, &self.document),
        };
        [kind_chain.0, kind_chain.1, &self.generic]
    }

    fn index(&mut self, rank: u32, key: &Key) {
        let push_named = |map: &mut ByName, ns: &Option<String>, local: &str| {
            let by_ns = map.entry(local.to_owned()).or_default();
            match by_ns.iter_mut().find(|(n, _)| n == ns) {
                Some((_, ranks)) => ranks.push(rank),
                None => by_ns.push((ns.clone(), vec![rank])),
            }
        };
        match key {
            Key::Document => self.document.push(rank),
            Key::Element(ns, local) => push_named(&mut self.elements, ns, local),
            Key::Attribute(ns, local) => push_named(&mut self.attributes, ns, local),
            Key::AnyElement => self.any_element.push(rank),
            Key::AnyAttribute => self.any_attribute.push(rank),
            Key::AnyChild => {
                self.any_element.push(rank);
                self.text.push(rank);
                self.comment.push(rank);
                self.processing_instruction.push(rank);
            }
            Key::Text => self.text.push(rank),
            Key::Comment => self.comment.push(rank),
            Key::ProcessingInstruction => self.processing_instruction.push(rank),
            Key::Generic => self.generic.push(rank),
        }
    }
}

/// The local variables of one frame (a template, a function or a global variable)
/// during compilation.
#[derive(Debug, Default)]
struct Frame {
    slots: usize,
    /// In scope, innermost last.
    locals: Vec<(QName, VariableInfo)>,
    /// References seen, per slot.
    uses: RefCell<Vec<u32>>,
}

impl Frame {
    fn declare(
        &mut self,
        name: QName,
        cardinality: Cardinality,
        value_type: ValueType,
        globals: usize,
    ) -> usize {
        let slot = self.slots;
        self.slots += 1;
        self.uses.borrow_mut().push(0);
        let id = VariableId(u32::try_from(globals + slot).unwrap_or(u32::MAX));
        self.locals.push((
            name,
            VariableInfo {
                id,
                cardinality,
                value_type,
            },
        ));
        slot
    }
}

/// The static context of an expression.
struct Scope<'a> {
    globals: &'a [(QName, VariableInfo)],
    /// How many globals Saxon has typed before the declaration being compiled (those
    /// declared before it): a reference to a later one is of unknown type for the type
    /// inference of the variables declared here.
    typed_globals: usize,
    functions: &'a [(QName, usize)],
    /// The declared result types of the functions.
    function_types: &'a [ValueType],
    frame: Option<&'a Frame>,
    /// Set when the compiler asked for a namespace prefix (only `system-property()`
    /// does), which this crate cannot resolve.
    asked_prefix: Cell<bool>,
}

impl StaticContext for Scope<'_> {
    fn variable(&self, name: &QName) -> Option<VariableInfo> {
        if let Some(frame) = self.frame
            && let Some((_, info)) = frame
                .locals
                .iter()
                .rev()
                .find(|(n, _)| n.same_expanded_name(name))
        {
            let globals = self.globals.len();
            let slot = (info.id.0 as usize).saturating_sub(globals);
            if let Some(count) = frame.uses.borrow_mut().get_mut(slot) {
                *count += 1;
            }
            return Some(info.clone());
        }
        let (index, (_, info)) = self
            .globals
            .iter()
            .enumerate()
            .find(|(_, (n, _))| n.same_expanded_name(name))?;
        Some(if index < self.typed_globals {
            info.clone()
        } else {
            VariableInfo {
                value_type: info.value_type.declared_later(),
                ..info.clone()
            }
        })
    }

    fn function(&self, name: &QName, arity: usize) -> Option<FunctionId> {
        self.functions
            .iter()
            .position(|(n, a)| *a == arity && n.same_expanded_name(name))
            .map(|i| FunctionId(u32::try_from(i).unwrap_or(u32::MAX)))
    }

    fn function_type(&self, id: FunctionId) -> ValueType {
        self.function_types
            .get(id.0 as usize)
            .cloned()
            .unwrap_or_default()
    }

    fn xslt_functions(&self) -> bool {
        true
    }

    fn namespace_uri(&self, _prefix: &str) -> Option<String> {
        self.asked_prefix.set(true);
        None
    }
}

/// Whether an expression calls `fn:document` anywhere.
fn calls_document(expr: &Expr) -> bool {
    let any = |exprs: &[Expr]| exprs.iter().any(calls_document);
    let bindings = |bindings: &[ast::Binding]| bindings.iter().any(|b| calls_document(&b.sequence));
    match expr {
        Expr::FunctionCall { name, args } => {
            (name.namespace.as_deref() == Some(ast::FN_NAMESPACE) && name.local == "document")
                || any(args)
        }
        Expr::Literal(_) | Expr::VarRef(_) | Expr::ContextItem => false,
        Expr::Sequence(items) => any(items),
        Expr::Filter { base, predicates } => calls_document(base) || any(predicates),
        Expr::Path(path) => path.steps.iter().any(|step| match step {
            ast::Step::Axis(axis_step) => any(&axis_step.predicates),
            ast::Step::Expr(e) => calls_document(e),
        }),
        Expr::Negate(e)
        | Expr::Castable { operand: e, .. }
        | Expr::Cast { operand: e, .. }
        | Expr::InstanceOf { operand: e, .. } => calls_document(e),
        Expr::Union(lhs, rhs)
        | Expr::Range(lhs, rhs)
        | Expr::And(lhs, rhs)
        | Expr::Or(lhs, rhs)
        | Expr::Arithmetic { lhs, rhs, .. }
        | Expr::Comparison { lhs, rhs, .. } => calls_document(lhs) || calls_document(rhs),
        Expr::If {
            condition,
            then,
            otherwise,
        } => calls_document(condition) || calls_document(then) || calls_document(otherwise),
        Expr::For { bindings: b, body } => bindings(b) || calls_document(body),
        Expr::Quantified {
            bindings: b,
            satisfies,
            ..
        } => bindings(b) || calls_document(satisfies),
    }
}

/// Whether the predicates of a pattern alternative call `fn:document` anywhere.
fn pattern_calls_document(alternative: &ast::PatternAlternative) -> bool {
    let any = |exprs: &[Expr]| exprs.iter().any(calls_document);
    match alternative {
        ast::PatternAlternative::DocumentRoot | ast::PatternAlternative::RootFunction => false,
        ast::PatternAlternative::Path(path) => {
            any(&path.first.predicates) || path.rest.iter().any(|(_, step)| any(&step.predicates))
        }
        ast::PatternAlternative::Parenthesized { inner, predicates } => {
            inner.alternatives.iter().any(pattern_calls_document) || any(predicates)
        }
    }
}

fn cardinality_of(occurrence: Occurrence) -> Cardinality {
    match occurrence {
        Occurrence::One | Occurrence::ZeroOrOne => Cardinality::AtMostOne,
        Occurrence::ZeroOrMore | Occurrence::OneOrMore => Cardinality::Any,
    }
}

/// What a binding's value is, for the inference of its static type.
fn binding_value(value: &Value) -> BindingValue<'_> {
    match value {
        Value::Select(expr) => BindingValue::Select(expr),
        Value::Content(_) => BindingValue::Content,
        Value::Absent => BindingValue::Absent,
    }
}

/// What is statically known of the number of items of a binding's value.
fn binding_cardinality(as_type: Option<&SequenceType>, value: &Value) -> Cardinality {
    if let Some(t) = as_type {
        return cardinality_of(t.occurrence);
    }
    match value {
        Value::Select(expr) if !expr.is_at_most_one() => Cardinality::Any,
        Value::Select(_) | Value::Content(_) | Value::Absent => Cardinality::AtMostOne,
    }
}

struct Compiler<'s> {
    sheet: &'s Stylesheet,
    /// Names of literal result elements and their attributes, shared.
    names: Vec<Arc<QName>>,
    errors: Vec<PrepareError>,
    globals: Vec<(QName, VariableInfo)>,
    /// How many globals are declared before the declaration being compiled.
    typed_globals: usize,
    functions: Vec<(QName, usize)>,
    /// The declared result types of the functions, by identity.
    function_types: Vec<ValueType>,
    modes: Vec<Mode>,
    /// Whether some expression compiled so far calls `document()`.
    calls_document: bool,
}

/// Collects the modes named by templates and by `xsl:apply-templates`.
fn collect_modes(instructions: &[Instruction], modes: &mut BTreeSet<Mode>) {
    for instruction in instructions {
        match instruction {
            Instruction::ApplyTemplates(apply) => {
                if let ApplyMode::Mode(mode) = &apply.mode {
                    modes.insert(mode.clone());
                }
                collect_params(&apply.params, modes);
            }
            Instruction::NextMatch(n) => collect_params(&n.params, modes),
            Instruction::CallTemplate(c) => collect_params(&c.params, modes),
            Instruction::Choose(choose) => {
                for when in &choose.whens {
                    collect_modes(&when.body, modes);
                }
                if let Some(otherwise) = &choose.otherwise {
                    collect_modes(otherwise, modes);
                }
            }
            Instruction::If(i) => collect_modes(&i.body, modes),
            Instruction::ForEach(f) => collect_modes(&f.body, modes),
            Instruction::Variable(v) => collect_value(&v.value, modes),
            Instruction::ValueOf(v) => collect_modes(&v.body, modes),
            Instruction::Attribute(a) => collect_modes(&a.body, modes),
            Instruction::Comment(c) => collect_modes(&c.body, modes),
            Instruction::LiteralElement(e) => collect_modes(&e.body, modes),
            Instruction::Sequence(_) | Instruction::Text(_) | Instruction::Number(_) => {}
        }
    }
}

fn collect_params(params: &[Variable], modes: &mut BTreeSet<Mode>) {
    for p in params {
        collect_value(&p.value, modes);
    }
}

fn collect_value(value: &VariableValue, modes: &mut BTreeSet<Mode>) {
    if let VariableValue::Content(body) = value {
        collect_modes(body, modes);
    }
}

/// Where a sequence constructor's result goes, for the refusals.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Content {
    /// Nodes may be constructed.
    Nodes,
    /// A sequence: only `xsl:sequence`, variables and control flow (the body of an
    /// `xsl:function`, a variable with `as`).
    Sequence,
}

impl Compiler<'_> {
    fn error(&mut self, line: u32, message: impl Into<String>) {
        self.errors.push(PrepareError {
            line,
            message: message.into(),
        });
    }

    fn scope<'a>(&'a self, frame: Option<&'a Frame>) -> Scope<'a> {
        Scope {
            globals: &self.globals,
            typed_globals: self.typed_globals,
            functions: &self.functions,
            function_types: &self.function_types,
            frame,
            asked_prefix: Cell::new(false),
        }
    }

    fn expr(&mut self, line: u32, expr: &Expr, frame: Option<&Frame>) -> Option<Box<CompiledExpr>> {
        self.calls_document |= calls_document(expr);
        let scope = self.scope(frame);
        match compile(expr, &scope) {
            Ok(compiled) => Some(Box::new(compiled)),
            Err(e) => {
                let message = if scope.asked_prefix.get() {
                    format!(
                        "{expr}: system-property() with a prefixed name is not supported (the in-scope namespaces of instructions are not kept)"
                    )
                } else {
                    format!("{expr}: {e}")
                };
                self.error(line, message);
                None
            }
        }
    }

    fn avt(&mut self, line: u32, avt: &Avt, frame: Option<&Frame>) -> Option<CompiledAvt> {
        let mut items = Vec::with_capacity(avt.parts.len());
        let mut ok = true;
        for part in &avt.parts {
            match part {
                AvtPart::Text(text) => items.push(AvtItem::Text(text.as_str().into())),
                AvtPart::Expr(e) => match self.expr(line, e, frame) {
                    Some(c) => items.push(AvtItem::Expr(c)),
                    None => ok = false,
                },
            }
        }
        ok.then_some(CompiledAvt(items))
    }

    /// A shared copy of `name` (the prefix counts: it is serialized).
    fn intern(&mut self, name: &QName) -> Arc<QName> {
        if let Some(shared) = self.names.iter().find(|n| ***n == *name) {
            return Arc::clone(shared);
        }
        let shared = Arc::new(name.clone());
        self.names.push(Arc::clone(&shared));
        shared
    }

    fn mode_index(&self, mode: &Mode) -> usize {
        self.modes.iter().position(|m| m == mode).unwrap_or(0)
    }

    /// The value of a binding. Its content is a sequence when it has `as`.
    fn value(
        &mut self,
        line: u32,
        value: &VariableValue,
        as_type: Option<&SequenceType>,
        frame: &mut Frame,
    ) -> Value {
        match value {
            VariableValue::Select(expr) => self
                .expr(line, expr, Some(frame))
                .map_or(Value::Absent, Value::Select),
            VariableValue::Content(body) => {
                let content = if as_type.is_some() {
                    Content::Sequence
                } else {
                    Content::Nodes
                };
                Value::Content(self.sequence_constructor(body, frame, content))
            }
            VariableValue::Absent => Value::Absent,
        }
    }

    fn with_params(&mut self, params: &[Variable], frame: &mut Frame) -> Vec<WithParam> {
        params
            .iter()
            .map(|p| {
                let value = self.value(p.line, &p.value, p.as_type.as_ref(), frame);
                let lazy = matches!(&value, Value::Select(e) if !e.is_at_most_one());
                WithParam {
                    name: p.name.clone(),
                    as_type: p.as_type.clone(),
                    value,
                    lazy,
                }
            })
            .collect()
    }

    /// Compiles a sequence constructor. Local variables are in scope for their
    /// following siblings and their descendants.
    fn sequence_constructor(
        &mut self,
        instructions: &[Instruction],
        frame: &mut Frame,
        content: Content,
    ) -> Vec<Inst> {
        let scope_depth = frame.locals.len();
        let mut out = Vec::with_capacity(instructions.len());
        for instruction in instructions {
            if let Some(inst) = self.instruction(instruction, frame, content) {
                out.push(inst);
            }
        }
        frame.locals.truncate(scope_depth);
        let uses = frame.uses.borrow();
        for inst in &mut out {
            if let Inst::Variable(binding) = inst {
                binding.used = uses.get(binding.slot).is_some_and(|&n| n > 0);
            }
        }
        out
    }

    fn refuse_in_sequence(&mut self, line: u32, what: &str, content: Content) -> bool {
        if content == Content::Sequence {
            self.error(
                line,
                format!(
                    "{what} in a sequence (an xsl:function body or a variable with `as`) is not supported"
                ),
            );
            return true;
        }
        false
    }

    #[expect(
        clippy::too_many_lines,
        reason = "one arm per instruction of the supported subset"
    )]
    fn instruction(
        &mut self,
        instruction: &Instruction,
        frame: &mut Frame,
        content: Content,
    ) -> Option<Inst> {
        Some(match instruction {
            Instruction::ApplyTemplates(apply) => {
                if self.refuse_in_sequence(apply.line, "xsl:apply-templates", content) {
                    return None;
                }
                let select = if let Some(e) = &apply.select {
                    self.expr(apply.line, e, Some(frame))
                } else {
                    let children = parse_expr("child::node()", &NamespaceMap::new()).ok()?;
                    self.expr(apply.line, &children, Some(frame))
                };
                let mode = match &apply.mode {
                    ApplyMode::Current => ModeRef::Current,
                    ApplyMode::Mode(m) => ModeRef::Mode(self.mode_index(m)),
                };
                let params = self.with_params(&apply.params, frame);
                Inst::ApplyTemplates {
                    line: apply.line,
                    select: select?,
                    mode,
                    params,
                }
            }
            Instruction::NextMatch(next) => {
                if self.refuse_in_sequence(next.line, "xsl:next-match", content) {
                    return None;
                }
                Inst::NextMatch {
                    line: next.line,
                    params: self.with_params(&next.params, frame),
                }
            }
            Instruction::CallTemplate(call) => {
                if self.refuse_in_sequence(call.line, "xsl:call-template", content) {
                    return None;
                }
                let Some(template) = self.sheet.templates.iter().position(|t| {
                    t.name
                        .as_ref()
                        .is_some_and(|n| n.same_expanded_name(&call.name))
                }) else {
                    self.error(
                        call.line,
                        format!("no template named {} (XTSE0650)", call.name),
                    );
                    return None;
                };
                let declared = &self.sheet.templates[template].params;
                if let Some(p) = call
                    .params
                    .iter()
                    .find(|p| !declared.iter().any(|d| d.name.same_expanded_name(&p.name)))
                {
                    let message = format!(
                        "parameter {} is not declared by template {} (XTSE0680)",
                        p.name, call.name
                    );
                    self.error(call.line, message);
                    return None;
                }
                Inst::CallTemplate {
                    line: call.line,
                    template,
                    params: self.with_params(&call.params, frame),
                }
            }
            Instruction::Choose(choose) => {
                let mut whens = Vec::with_capacity(choose.whens.len());
                for when in &choose.whens {
                    let test = self.expr(when.line, &when.test, Some(frame));
                    let body = self.sequence_constructor(&when.body, frame, content);
                    whens.push(When {
                        line: when.line,
                        test: test?,
                        body,
                    });
                }
                let otherwise = choose
                    .otherwise
                    .as_ref()
                    .map(|body| self.sequence_constructor(body, frame, content))
                    .unwrap_or_default();
                Inst::Choose { whens, otherwise }
            }
            Instruction::If(i) => {
                let test = self.expr(i.line, &i.test, Some(frame));
                let body = self.sequence_constructor(&i.body, frame, content);
                Inst::Choose {
                    whens: vec![When {
                        line: i.line,
                        test: test?,
                        body,
                    }],
                    otherwise: Vec::new(),
                }
            }
            Instruction::ForEach(f) => {
                let select = self.expr(f.line, &f.select, Some(frame));
                let body = self.sequence_constructor(&f.body, frame, content);
                Inst::ForEach {
                    line: f.line,
                    select: select?,
                    body,
                }
            }
            Instruction::Variable(v) => {
                let value = self.value(v.line, &v.value, v.as_type.as_ref(), frame);
                let cardinality = binding_cardinality(v.as_type.as_ref(), &value);
                let value_type =
                    ValueType::local_variable(binding_value(&value), v.as_type.as_ref());
                let lazy = matches!(&value, Value::Select(e) if !e.is_at_most_one());
                let slot =
                    frame.declare(v.name.clone(), cardinality, value_type, self.globals.len());
                Inst::Variable(Box::new(Binding {
                    line: v.line,
                    name: v.name.clone(),
                    slot,
                    as_type: v.as_type.clone(),
                    value,
                    lazy,
                    used: false,
                }))
            }
            Instruction::Sequence(s) => Inst::Sequence {
                line: s.line,
                select: self.expr(s.line, &s.select, Some(frame))?,
            },
            Instruction::ValueOf(v) => {
                if self.refuse_in_sequence(v.line, "xsl:value-of", content) {
                    return None;
                }
                let select = v.select.as_ref().map(|e| self.expr(v.line, e, Some(frame)));
                let separator = v
                    .separator
                    .as_ref()
                    .map(|s| self.avt(v.line, s, Some(frame)));
                let body = self.sequence_constructor(&v.body, frame, Content::Nodes);
                Inst::ValueOf {
                    line: v.line,
                    select: select.map_or(Some(None), |s| s.map(Some))?,
                    separator: separator.map_or(Some(None), |s| s.map(Some))?,
                    body,
                }
            }
            Instruction::Attribute(a) => {
                if self.refuse_in_sequence(a.line, "xsl:attribute", content) {
                    return None;
                }
                let name = self.avt(a.line, &a.name, Some(frame));
                let select = a.select.as_ref().map(|e| self.expr(a.line, e, Some(frame)));
                let body = self.sequence_constructor(&a.body, frame, Content::Nodes);
                Inst::Attribute {
                    line: a.line,
                    name: name?,
                    namespaces: Arc::clone(&a.namespaces),
                    select: select.map_or(Some(None), |s| s.map(Some))?,
                    body,
                }
            }
            Instruction::Comment(c) => {
                if self.refuse_in_sequence(c.line, "xsl:comment", content) {
                    return None;
                }
                Inst::Comment {
                    line: c.line,
                    body: self.sequence_constructor(&c.body, frame, Content::Nodes),
                }
            }
            Instruction::Text(t) => {
                if self.refuse_in_sequence(t.line, "text", content) {
                    return None;
                }
                Inst::Text(t.value.as_str().into())
            }
            Instruction::Number(n) => {
                if self.refuse_in_sequence(n.line, "xsl:number", content) {
                    return None;
                }
                let count = match &n.count {
                    None => None,
                    Some(p) => Some(CountPattern {
                        alternatives: self.pattern(n.line, p)?,
                        text: p.to_string(),
                    }),
                };
                Inst::Number {
                    line: n.line,
                    level: n.level,
                    count,
                }
            }
            Instruction::LiteralElement(e) => {
                if self.refuse_in_sequence(e.line, "a literal result element", content) {
                    return None;
                }
                let mut attributes = Vec::with_capacity(e.attributes.len());
                let mut ok = true;
                for attribute in &e.attributes {
                    match self.avt(e.line, &attribute.value, Some(frame)) {
                        Some(value) => attributes.push((self.intern(&attribute.name), value)),
                        None => ok = false,
                    }
                }
                let body = self.sequence_constructor(&e.body, frame, Content::Nodes);
                if !ok {
                    return None;
                }
                Inst::Element {
                    line: e.line,
                    name: self.intern(&e.name),
                    namespaces: Arc::clone(&e.namespaces),
                    attributes,
                    body,
                }
            }
        })
    }

    /// A pattern (template `match`, `xsl:number/@count`): global variables only.
    fn pattern(&mut self, line: u32, pattern: &ast::Pattern) -> Option<Vec<Alternative>> {
        let mut out = Vec::with_capacity(pattern.alternatives.len());
        for alternative in &pattern.alternatives {
            self.calls_document |= pattern_calls_document(alternative);
            let scope = self.scope(None);
            match pattern::compile_alternative(alternative, &scope) {
                Ok(a) => out.push(a),
                Err(message) => {
                    self.error(line, format!("pattern {alternative}: {message}"));
                    return None;
                }
            }
        }
        Some(out)
    }

    /// Template and function parameters, declared in order in `frame`.
    fn params(&mut self, params: &[Variable], frame: &mut Frame) -> Vec<Binding> {
        let mut out = Vec::with_capacity(params.len());
        for p in params {
            let value = self.value(p.line, &p.value, p.as_type.as_ref(), frame);
            let cardinality = p
                .as_type
                .as_ref()
                .map_or(Cardinality::Any, |t| cardinality_of(t.occurrence));
            let lazy = matches!(&value, Value::Select(e) if !e.is_at_most_one());
            let slot = frame.declare(
                p.name.clone(),
                cardinality,
                ValueType::declared(p.as_type.as_ref()),
                self.globals.len(),
            );
            out.push(Binding {
                line: p.line,
                name: p.name.clone(),
                slot,
                as_type: p.as_type.clone(),
                value,
                lazy,
                used: true,
            });
        }
        out
    }

    fn template(&mut self, template: &Template) -> CompiledTemplate {
        self.typed_globals = self.globals_before(template.line);
        let mut frame = Frame::default();
        let params = self.params(&template.params, &mut frame);
        let body = self.sequence_constructor(&template.body, &mut frame, Content::Nodes);
        let (pattern, pattern_text, alternative_texts) = match &template.pattern {
            Some(p) => (
                self.pattern(template.line, p).unwrap_or_default(),
                p.to_string(),
                p.alternatives.iter().map(ToString::to_string).collect(),
            ),
            None => (Vec::new(), String::new(), Vec::new()),
        };
        CompiledTemplate {
            line: template.line,
            params,
            body,
            slots: frame.slots,
            pattern,
            pattern_text,
            alternative_texts,
        }
    }
}

impl Executable {
    /// Prepares a loaded stylesheet.
    ///
    /// # Errors
    ///
    /// Every problem found: XPath expressions that do not compile in their static
    /// context (unknown variables or functions), calls of undeclared templates, and the
    /// constructs refused because their result would differ from the reference engine's
    /// (instructions that construct nodes inside an `xsl:function` or a variable with
    /// `as`, a positional predicate in a parenthesized pattern, `system-property()` with
    /// a prefixed name).
    pub fn new(sheet: &Stylesheet) -> Result<Self, PrepareErrors> {
        let mut modes = BTreeSet::new();
        modes.insert(Mode::Default);
        for template in &sheet.templates {
            if template.pattern.is_some()
                && let TemplateModes::Listed(listed) = &template.modes
            {
                modes.extend(listed.iter().cloned());
            }
            collect_modes(&template.body, &mut modes);
            collect_params(&template.params, &mut modes);
        }
        for function in &sheet.functions {
            collect_modes(&function.body, &mut modes);
        }
        for global in &sheet.globals {
            collect_value(&global.variable.value, &mut modes);
        }
        let mut compiler = Compiler {
            sheet,
            names: Vec::new(),
            errors: Vec::new(),
            globals: Vec::new(),
            typed_globals: 0,
            functions: sheet
                .functions
                .iter()
                .map(|f| (f.name.clone(), f.params.len()))
                .collect(),
            function_types: sheet
                .functions
                .iter()
                .map(|f| ValueType::declared(f.as_type.as_ref()))
                .collect(),
            modes: modes.into_iter().collect(),
            calls_document: false,
        };
        let globals = compiler.globals(sheet);
        let templates: Vec<CompiledTemplate> = sheet
            .templates
            .iter()
            .map(|t| compiler.template(t))
            .collect();
        let functions = sheet
            .functions
            .iter()
            .map(|f| {
                compiler.typed_globals = compiler.globals_before(f.line);
                let mut frame = Frame::default();
                let params = compiler.params(&f.params, &mut frame);
                let body = compiler.sequence_constructor(&f.body, &mut frame, Content::Sequence);
                CompiledFunction {
                    line: f.line,
                    name: f.name.clone(),
                    params,
                    as_type: f.as_type.clone(),
                    body,
                    slots: frame.slots,
                }
            })
            .collect();
        let compiled_modes = compiler
            .modes
            .iter()
            .map(|mode| rank_rules(sheet, &templates, mode))
            .collect();
        if !compiler.errors.is_empty() {
            compiler.errors.sort_by_key(|e| e.line);
            return Err(PrepareErrors(compiler.errors));
        }
        let default_mode = compiler.mode_index(&Mode::Default);
        let serialization = sheet
            .output
            .map_or_else(Serialization::default, |o| Serialization {
                indent: o.indent == Some(true),
                omit_xml_declaration: o.omit_xml_declaration == Some(true),
                standalone: match o.standalone {
                    Some(Standalone::Yes) => Some(true),
                    Some(Standalone::No) => Some(false),
                    Some(Standalone::Omit) | None => None,
                },
            });
        Ok(Self {
            globals,
            templates,
            functions,
            modes: compiled_modes,
            default_mode,
            serialization,
            base_uri: None,
            calls_document: compiler.calls_document,
        })
    }

    /// Sets the static base URI of the stylesheet (its location), against which
    /// `document()` resolves relative URIs given as strings.
    #[must_use]
    pub fn with_base_uri(mut self, uri: impl Into<String>) -> Self {
        self.base_uri = Some(uri.into());
        self
    }
}

impl Compiler<'_> {
    /// How many global variables and parameters are declared before `line`: Saxon types
    /// the declarations in document order.
    fn globals_before(&self, line: u32) -> usize {
        self.sheet
            .globals
            .iter()
            .take_while(|g| g.variable.line < line)
            .count()
    }

    /// The global variables. Their static cardinality comes from their compiled value,
    /// which may refer to other globals: compiled again until it is stable. Their static
    /// type is inferred in declaration order from the types of the globals declared
    /// before them, and used from the second compilation on.
    fn globals(&mut self, sheet: &Stylesheet) -> Vec<Global> {
        self.globals = sheet
            .globals
            .iter()
            .enumerate()
            .map(|(i, g)| {
                (
                    g.variable.name.clone(),
                    VariableInfo {
                        id: VariableId(u32::try_from(i).unwrap_or(u32::MAX)),
                        cardinality: g
                            .variable
                            .as_type
                            .as_ref()
                            .map_or(Cardinality::Any, |t| cardinality_of(t.occurrence)),
                        value_type: ValueType::unknown(),
                    },
                )
            })
            .collect();
        let errors_before = self.errors.len();
        let mut compiled: Vec<Global> = Vec::new();
        for pass in 0..=sheet.globals.len() + 1 {
            self.errors.truncate(errors_before);
            compiled = Vec::with_capacity(sheet.globals.len());
            for (index, g) in sheet.globals.iter().enumerate() {
                let v = &g.variable;
                self.typed_globals = index;
                let mut frame = Frame::default();
                let value = self.value(v.line, &v.value, v.as_type.as_ref(), &mut frame);
                let value_type = if g.kind == GlobalKind::Param {
                    ValueType::declared(v.as_type.as_ref())
                } else {
                    ValueType::global_variable(binding_value(&value), v.as_type.as_ref())
                };
                if let Some((_, info)) = self.globals.get_mut(index) {
                    info.value_type = value_type;
                }
                compiled.push(Global {
                    name: v.name.clone(),
                    is_param: g.kind == GlobalKind::Param,
                    line: v.line,
                    value,
                    as_type: v.as_type.clone(),
                    slots: frame.slots,
                });
            }
            // The types are final after the first compilation (each depends on the
            // globals declared before it only), which saw the later ones untyped.
            let mut changed = pass == 0;
            for (info, global) in self.globals.iter_mut().zip(&compiled) {
                let cardinality = binding_cardinality(global.as_type.as_ref(), &global.value);
                if info.1.cardinality != cardinality {
                    info.1.cardinality = cardinality;
                    changed = true;
                }
            }
            if !changed {
                break;
            }
        }
        compiled
    }
}

/// The priority as Saxon compares priorities: a double.
fn as_double(priority: Priority) -> f64 {
    priority.to_string().parse().unwrap_or(f64::NAN)
}

/// The rules of `mode`, ranked and indexed.
fn rank_rules(sheet: &Stylesheet, templates: &[CompiledTemplate], mode: &Mode) -> CompiledMode {
    let mut rules = Vec::new();
    for (index, template) in sheet.templates.iter().enumerate() {
        if template.pattern.is_none() {
            continue;
        }
        let in_mode = match &template.modes {
            TemplateModes::All => true,
            TemplateModes::Listed(modes) => modes.contains(mode),
        };
        if !in_mode {
            continue;
        }
        // Saxon-HE 12.10 keeps a union pattern with an explicit priority as one rule
        // (Saxon-HE 9.9 split it like a pattern without one).
        let whole = template.rules.len() > 1 && template.rules.iter().all(|r| !r.is_default);
        for rule in &template.rules {
            rules.push(Rule {
                template: index,
                alternative: (!whole).then_some(rule.alternative),
                priority: as_double(rule.priority),
                sequence: index,
                part: if rule.is_default { rule.alternative } else { 0 },
            });
            if whole {
                break;
            }
        }
    }
    rules.sort_by(|a, b| {
        b.priority
            .total_cmp(&a.priority)
            .then(b.sequence.cmp(&a.sequence))
            .then(b.part.cmp(&a.part))
    });
    let mut compiled = CompiledMode {
        name: match mode {
            Mode::Default => "#default".to_owned(),
            Mode::Named(q) => q.to_string(),
        },
        ..CompiledMode::default()
    };
    for (rank, rule) in rules.iter().enumerate() {
        let rank = u32::try_from(rank).unwrap_or(u32::MAX);
        let pattern = &templates[rule.template].pattern;
        match rule.alternative {
            Some(alternative) => {
                if let Some(alternative) = pattern.get(alternative) {
                    for key in alternative.chain_keys() {
                        compiled.index(rank, &key);
                    }
                }
            }
            None => {
                if let Some(key) = pattern::union_chain_key(pattern) {
                    compiled.index(rank, &key);
                }
            }
        }
    }
    compiled.rules = rules;
    compiled
}