schematron 0.16.1

Schematron: pure Rust implementation of ISO/IEC 19757-3 rule-based XML validation, with its own XML parser, XPath 1.0 engine, XPath 2.0 and 3.0 subsets, schema linting, and SVRL reporting. By SixArm.com.
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
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
//! Pass 5 of schema compilation, and the public [`Schema`] type.
//!
//! Every XPath expression in the schema is parsed **once**, here, and cached.
//! Two things follow. A syntax error, an unknown function, or an undeclared
//! namespace prefix is reported when the schema loads, naming the element it
//! is in — not silently at validation time on somebody else's document. And
//! validating a thousand documents parses each expression once, not a
//! thousand times.

use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;

use super::expand::expand;
use super::include::resolve_includes;
use super::model::{
    Assertion, Content, Let, LetValue, Pattern, QueryBinding, Rule, SchemaModel,
};
use super::parse::parse_schema;
use super::resolver::{FileResolver, SharedResolver};
use crate::error::{Error, Result};
use crate::xml::Document;
use crate::xpath::{
    check_function, Axis, BinaryOp, Expr, NameTest, Namespaces, NodeTest, PathStart, XPathVersion,
};

/// How to load a schema.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// use schematron::schema::{MemoryResolver, SchemaOptions};
///
/// let options = SchemaOptions::new()
///     .with_resolver(Arc::new(MemoryResolver::new().with("common.sch", "<p/>")))
///     .with_max_include_depth(8);
/// assert_eq!(options.max_include_depth, 8);
/// ```
#[derive(Clone)]
pub struct SchemaOptions {
    /// The base URI that relative `include` hrefs resolve against.
    pub base_uri: Option<String>,
    /// How `include` and `extends href` fetch their targets.
    pub resolver: SharedResolver,
    /// How deeply includes may nest before it is treated as a runaway.
    pub max_include_depth: usize,
    /// Compile a schema whose `queryBinding` this crate does not implement.
    ///
    /// Off by default: running an `xslt2` schema through an XPath 1.0 engine
    /// gives wrong answers quietly. Turn it on for the common case of a
    /// schema that declares `xslt2` but only uses XPath 1.0 constructs — any
    /// construct that really is XPath 2.0 will still fail to compile, with a
    /// message naming it.
    pub allow_unknown_query_binding: bool,
}

impl std::fmt::Debug for SchemaOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SchemaOptions")
            .field("base_uri", &self.base_uri)
            .field("max_include_depth", &self.max_include_depth)
            .field(
                "allow_unknown_query_binding",
                &self.allow_unknown_query_binding,
            )
            .finish_non_exhaustive()
    }
}

impl Default for SchemaOptions {
    fn default() -> Self {
        Self {
            base_uri: None,
            resolver: Arc::new(FileResolver::new()),
            max_include_depth: 64,
            allow_unknown_query_binding: false,
        }
    }
}

impl SchemaOptions {
    /// Default options: filesystem resolution, strict query binding.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the base URI for relative includes.
    #[must_use]
    pub fn with_base_uri(mut self, uri: impl Into<String>) -> Self {
        self.base_uri = Some(uri.into());
        self
    }

    /// Sets the resolver.
    #[must_use]
    pub fn with_resolver(mut self, resolver: SharedResolver) -> Self {
        self.resolver = resolver;
        self
    }

    /// Sets the include depth limit.
    #[must_use]
    pub fn with_max_include_depth(mut self, depth: usize) -> Self {
        self.max_include_depth = depth;
        self
    }

    /// Allows an unsupported `queryBinding` to compile anyway.
    #[must_use]
    pub fn with_allow_unknown_query_binding(mut self, allow: bool) -> Self {
        self.allow_unknown_query_binding = allow;
        self
    }
}

/// A compiled Schematron schema, ready to validate documents.
///
/// Compiling is the expensive part; validating is not. Compile once and reuse.
/// `Schema` is immutable and `Send + Sync`, so one schema can validate
/// documents on many threads at the same time.
///
/// # Examples
///
/// ```
/// use schematron::{Document, Schema};
///
/// let schema = Schema::from_str(r#"
///     <schema xmlns="http://purl.oclc.org/dsdl/schematron">
///       <pattern>
///         <rule context="line">
///           <assert test="number(@qty) &gt; 0">Quantity must be positive.</assert>
///         </rule>
///       </pattern>
///     </schema>
/// "#)?;
///
/// let document = Document::from_str("<order><line qty='-1'/></order>")?;
/// let report = schema.validate(&document)?;
/// assert_eq!(report.count_failures(), 1);
/// # Ok::<(), schematron::Error>(())
/// ```
#[derive(Debug, Clone)]
pub struct Schema {
    pub(crate) model: SchemaModel,
    pub(crate) expressions: HashMap<String, Expr>,
    pub(crate) namespaces: Namespaces,
    /// Kept for `pattern/@documents` and XPath `document()`, both of which
    /// fetch documents at validation time rather than at compile time.
    pub(crate) resolver: SharedResolver,
    /// The XPath version every expression in this schema is compiled and
    /// evaluated as, taken from the query binding.
    pub(crate) version: XPathVersion,
    /// Whether any expression calls XPath `document()`.
    ///
    /// Recorded at compile time so that the overwhelmingly common case — a
    /// schema that does not — pays nothing for the machinery that supports
    /// it. See `spec/xpath/`.
    pub(crate) uses_document_function: bool,
    /// Why streaming validation refuses this schema, or `None` when it
    /// qualifies. Computed once at compile time — same reasoning as
    /// `uses_document_function` — so `--stream`/`validate_streaming` can
    /// fail immediately, naming the reason, rather than partway through a
    /// large document. See `spec/streaming/`.
    pub(crate) streaming_ineligible_reason: Option<String>,
}

impl Schema {
    /// Compiles a schema from source text.
    ///
    /// Named `from_str` rather than implementing [`std::str::FromStr`]
    /// deliberately: the trait's signature has no room for
    /// [`SchemaOptions`], and a schema that cannot resolve its includes is
    /// not much use.
    ///
    /// # Errors
    ///
    /// Returns [`Error::XmlParse`] if the schema is not well-formed XML,
    /// [`Error::Schema`] if it is not a valid Schematron schema, and
    /// [`Error::XPathSyntax`] if any expression in it does not compile.
    #[allow(clippy::should_implement_trait)] // See the note above.
    pub fn from_str(source: &str) -> Result<Schema> {
        Schema::from_str_with(source, &SchemaOptions::default())
    }

    /// Compiles a schema from source text, with options.
    ///
    /// # Errors
    ///
    /// As [`Schema::from_str`], plus [`Error::Resolve`],
    /// [`Error::IncludeCycle`], and [`Error::IncludeDepth`] from include
    /// resolution.
    pub fn from_str_with(source: &str, options: &SchemaOptions) -> Result<Schema> {
        let mut document = Document::from_str(source)?;
        if let Some(base) = &options.base_uri {
            document.set_base_uri(base.clone());
        }
        Schema::from_document(&document, options)
    }

    /// Reads and compiles a schema from a file.
    ///
    /// The file's path becomes the base URI, so relative includes resolve
    /// against the directory the schema lives in.
    ///
    /// # Errors
    ///
    /// As [`Schema::from_str_with`], plus [`Error::Io`] if the file cannot be
    /// read.
    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Schema> {
        let path = path.as_ref();
        let source = std::fs::read_to_string(path).map_err(|source| Error::Io {
            path: path.display().to_string(),
            source,
        })?;
        let options = SchemaOptions::new().with_base_uri(path.display().to_string());
        Schema::from_str_with(&source, &options)
    }

    /// Compiles a schema from an already-parsed XML document.
    ///
    /// # Errors
    ///
    /// As [`Schema::from_str_with`].
    pub fn from_document(document: &Document, options: &SchemaOptions) -> Result<Schema> {
        let resolved = resolve_includes(
            document,
            options.resolver.as_ref(),
            options.max_include_depth,
        )?;
        let mut model = parse_schema(&resolved)?;

        if !model.query_binding.is_supported() && !options.allow_unknown_query_binding {
            return Err(Error::UnsupportedQueryBinding {
                binding: model
                    .query_binding
                    .as_str()
                    .unwrap_or_default()
                    .to_string(),
            });
        }

        let version = model.query_binding.version();
        expand(&mut model)?;

        let mut namespaces = Namespaces::new();
        for ns in &model.namespaces {
            namespaces.insert(ns.prefix.clone(), ns.uri.clone());
        }

        let mut schema = Schema {
            model,
            expressions: HashMap::new(),
            namespaces,
            resolver: Arc::clone(&options.resolver),
            version,
            uses_document_function: false,
            streaming_ineligible_reason: None,
        };
        schema.compile_expressions()?;
        schema.check_references()?;
        schema.uses_document_function = schema
            .expressions
            .values()
            .any(calls_document_function);
        schema.streaming_ineligible_reason = streaming_ineligibility_reason(&schema);
        Ok(schema)
    }

    /// Parses every expression in the schema, once.
    fn compile_expressions(&mut self) -> Result<()> {
        let mut work: Vec<(String, String, bool)> = Vec::new();

        for binding in &self.model.lets {
            collect_let(binding, "schema", &mut work);
        }
        for phase in &self.model.phases {
            let location = format!("phase[@id='{}']", phase.id);
            for binding in &phase.lets {
                collect_let(binding, &location, &mut work);
            }
        }
        for (index, pattern) in self.model.patterns.iter().enumerate() {
            collect_pattern(pattern, index, &mut work);
        }
        for key in &self.model.keys {
            let location = format!("key[@name='{}']", key.name);
            work.push((
                key.match_pattern.clone(),
                format!("{location}/@match"),
                true,
            ));
            work.push((
                key.use_expression.clone(),
                format!("{location}/@use"),
                false,
            ));
        }
        for diagnostic in &self.model.diagnostics {
            let location = format!("diagnostic[@id='{}']", diagnostic.id);
            collect_content(&diagnostic.content, &location, &mut work);
        }
        for property in &self.model.properties {
            let location = format!("property[@id='{}']", property.id);
            collect_content(&property.content, &location, &mut work);
        }

        // Every name any `let` binds, at any scope. Checking against the
        // union rather than the exact scope keeps the check free of false
        // positives; see `spec/parsing/`.
        let bindable = self.bindable_names();

        for (source, location, is_pattern) in work {
            let expr = self.compile_one(&source, &location)?;
            Schema::check_variables(&expr, &source, &location, &bindable, &mut Vec::new())?;
            if is_pattern {
                check_match_pattern(&expr, &source, &location)?;
            }
            self.expressions.insert(source, expr);
        }
        Ok(())
    }

    /// Every name a `let` binds anywhere in the schema, at any scope.
    fn bindable_names(&self) -> std::collections::HashSet<String> {
        let model = &self.model;
        let mut names: std::collections::HashSet<String> = std::collections::HashSet::new();

        let mut add = |lets: &[Let]| {
            for binding in lets {
                names.insert(binding.name.clone());
            }
        };
        add(&model.lets);
        for phase in &model.phases {
            add(&phase.lets);
        }
        for pattern in &model.patterns {
            add(&pattern.lets);
            for rule in &pattern.rules {
                add(&rule.lets);
            }
        }
        names
    }

    /// Reports a `$name` that nothing anywhere could bind.
    ///
    /// `enclosing` carries the variables an XPath 2.0 `for`, `some` or
    /// `every` binds around this point, which are scoped to the expression
    /// rather than to the schema.
    fn check_variables(
        expr: &Expr,
        source: &str,
        location: &str,
        bindable: &std::collections::HashSet<String>,
        enclosing: &mut Vec<String>,
    ) -> Result<()> {
        match expr {
            Expr::Literal(_) | Expr::Number(_, _) | Expr::NamedFunctionRef { .. } => {}

            Expr::Variable(name) => {
                let name = name.to_string();
                if bindable.contains(&name) || enclosing.contains(&name) {
                    return Ok(());
                }
                let mut known: Vec<&str> =
                    bindable.iter().map(String::as_str).collect();
                known.extend(enclosing.iter().map(String::as_str));
                known.sort_unstable();
                return Err(Error::xpath_syntax(
                    location,
                    source,
                    0,
                    format!(
                        "no <let> anywhere in this schema binds ${name}{}",
                        if known.is_empty() {
                            "; the schema declares no variables".to_string()
                        } else {
                            format!("; it declares: {}", known.join(", "))
                        }
                    ),
                ));
            }

            Expr::Negate(inner) => {
                Schema::check_variables(inner, source, location, bindable, enclosing)?;
            }
            Expr::Binary(_, left, right) => {
                Schema::check_variables(left, source, location, bindable, enclosing)?;
                Schema::check_variables(right, source, location, bindable, enclosing)?;
            }
            Expr::Function { args, .. } => {
                for arg in args {
                    Schema::check_variables(arg, source, location, bindable, enclosing)?;
                }
            }
            Expr::TypeOp { value, .. } => {
                Schema::check_variables(value, source, location, bindable, enclosing)?;
            }
            Expr::Sequence(members) => {
                for member in members {
                    Schema::check_variables(member, source, location, bindable, enclosing)?;
                }
            }
            Expr::Range(from, to) => {
                Schema::check_variables(from, source, location, bindable, enclosing)?;
                Schema::check_variables(to, source, location, bindable, enclosing)?;
            }
            Expr::If {
                condition,
                then_branch,
                else_branch,
            } => {
                Schema::check_variables(condition, source, location, bindable, enclosing)?;
                Schema::check_variables(then_branch, source, location, bindable, enclosing)?;
                Schema::check_variables(else_branch, source, location, bindable, enclosing)?;
            }

            // These each bind one variable for part of themselves — `for`'s
            // `body`, `let`'s `body`, a quantifier's `test` — so share the
            // push/check/pop shape via `check_binding`.
            Expr::For {
                variable,
                input,
                body,
            } => {
                Schema::check_binding(input, variable, body, source, location, bindable, enclosing)?;
            }
            Expr::Let {
                variable,
                value,
                body,
            } => {
                Schema::check_binding(value, variable, body, source, location, bindable, enclosing)?;
            }
            Expr::Quantified {
                variable,
                input,
                test,
                ..
            } => {
                Schema::check_binding(input, variable, test, source, location, bindable, enclosing)?;
            }

            Expr::InlineFunction { .. } | Expr::DynamicCall { .. } | Expr::Arrow(_) => {
                Schema::check_variables_v3(expr, source, location, bindable, enclosing)?;
            }

            Expr::Path(path) => {
                if let PathStart::Expr(start, predicates) = &path.start {
                    Schema::check_variables(start, source, location, bindable, enclosing)?;
                    for predicate in predicates {
                        Schema::check_variables(predicate, source, location, bindable, enclosing)?;
                    }
                }
                for step in &path.steps {
                    for predicate in &step.predicates {
                        Schema::check_variables(predicate, source, location, bindable, enclosing)?;
                    }
                }
            }
        }
        Ok(())
    }

    /// `Expr::InlineFunction` and `Expr::DynamicCall`'s own check, split out
    /// of `check_variables` to keep that function under the line-count
    /// lint. An inline function's parameters bind new variables for its
    /// body, same as `for`'s and the quantifiers' bound variable above; a
    /// dynamic call's target and arguments are ordinary sub-expressions.
    fn check_variables_v3(
        expr: &Expr,
        source: &str,
        location: &str,
        bindable: &std::collections::HashSet<String>,
        enclosing: &mut Vec<String>,
    ) -> Result<()> {
        match expr {
            Expr::InlineFunction { params, body } => {
                let pushed = params.len();
                enclosing.extend(params.iter().cloned());
                let checked = Schema::check_variables(body, source, location, bindable, enclosing);
                enclosing.truncate(enclosing.len() - pushed);
                checked
            }
            Expr::DynamicCall { function, args } => {
                Schema::check_variables(function, source, location, bindable, enclosing)?;
                for arg in args {
                    Schema::check_variables(arg, source, location, bindable, enclosing)?;
                }
                Ok(())
            }
            // Pure sugar around the `Function` or `DynamicCall` above that
            // the parser already built — see `Expr::Arrow`'s doc comment —
            // so checking its variables is exactly checking the call it
            // holds.
            Expr::Arrow(called) => {
                Schema::check_variables(called, source, location, bindable, enclosing)
            }
            _ => unreachable!("caller matches only these three XPath 3.0 variants"),
        }
    }

    /// Checks a construct that binds one variable for part of itself:
    /// `for`'s `body`, `let`'s `body`, and a quantifier's `test` — `outer`
    /// is checked without the binding in scope, `inner` with `variable`
    /// pushed onto `enclosing`, popped again whatever `inner`'s check
    /// returns. Split out of `check_variables` to keep it under the
    /// line-count lint; three call sites share it instead of each
    /// duplicating the push/check/pop.
    fn check_binding(
        outer: &Expr,
        variable: &NameTest,
        inner: &Expr,
        source: &str,
        location: &str,
        bindable: &std::collections::HashSet<String>,
        enclosing: &mut Vec<String>,
    ) -> Result<()> {
        Schema::check_variables(outer, source, location, bindable, enclosing)?;
        enclosing.push(variable.to_string());
        let checked = Schema::check_variables(inner, source, location, bindable, enclosing);
        enclosing.pop();
        checked
    }

    fn compile_one(&self, source: &str, location: &str) -> Result<Expr> {
        let expr = crate::xpath::parse(source).map_err(|error| {
            Error::xpath_syntax(location, source, error.position, error.message)
        })?;
        self.check_expression(&expr, source, location)?;
        Ok(expr)
    }

    /// Walks an expression, checking what can be checked without a document:
    /// function names and arities, and namespace prefixes.
    fn check_expression(&self, expr: &Expr, source: &str, location: &str) -> Result<()> {
        match expr {
            // Literals need no checking. Variable references are checked
            // separately, by `check_variables`, which needs the set of names
            // the schema binds.
            Expr::Literal(_) | Expr::Number(_, _) | Expr::Variable(_) => {}
            Expr::Negate(inner) => self.check_expression(inner, source, location)?,
            Expr::Binary(op, left, right) => {
                self.check_binary_op_version(*op, source, location)?;
                self.check_expression(left, source, location)?;
                self.check_expression(right, source, location)?;
            }
            Expr::Function { name, args } => {
                check_function(name, args.len(), self.version).map_err(|message| {
                    Error::xpath_syntax(location, source, 0, message)
                })?;
                check_literal_regex(name, args, source, location)?;
                for arg in args {
                    self.check_expression(arg, source, location)?;
                }
            }
            Expr::If {
                condition,
                then_branch,
                else_branch,
            } => {
                self.require_v2("`if (…) then … else …`", source, location)?;
                self.check_expression(condition, source, location)?;
                self.check_expression(then_branch, source, location)?;
                self.check_expression(else_branch, source, location)?;
            }
            Expr::TypeOp { op, value, .. } => {
                self.require_v2(&format!("`{}`", op.as_str()), source, location)?;
                self.check_expression(value, source, location)?;
            }
            Expr::Sequence(members) => {
                self.require_v2("a sequence written with `,`", source, location)?;
                for member in members {
                    self.check_expression(member, source, location)?;
                }
            }
            Expr::Range(from, to) => {
                self.require_v2("the `to` range operator", source, location)?;
                self.check_expression(from, source, location)?;
                self.check_expression(to, source, location)?;
            }
            Expr::For { input, body, .. } => {
                self.require_v2("`for … in … return …`", source, location)?;
                self.check_expression(input, source, location)?;
                self.check_expression(body, source, location)?;
            }
            Expr::Let { value, body, .. } => {
                self.require_v3("`let $v := … return …`", source, location)?;
                self.check_expression(value, source, location)?;
                self.check_expression(body, source, location)?;
            }
            Expr::Quantified {
                quantifier,
                input,
                test,
                ..
            } => {
                self.require_v2(
                    &format!("`{} … in … satisfies …`", quantifier.as_str()),
                    source,
                    location,
                )?;
                self.check_expression(input, source, location)?;
                self.check_expression(test, source, location)?;
            }
            Expr::InlineFunction { .. } | Expr::NamedFunctionRef { .. } | Expr::DynamicCall { .. } => {
                self.check_v3_expression(expr, source, location)?;
            }
            // The wrapper's own gate, checked before recursing into the
            // `Function` or `DynamicCall` it holds — so `X => f()` under a
            // 1.0/2.0 binding is refused as the arrow operator, not
            // whatever `f()` on its own would have been.
            Expr::Arrow(called) => {
                self.require_v3("the arrow operator `=>`", source, location)?;
                self.check_expression(called, source, location)?;
            }

            Expr::Path(path) => {
                if let PathStart::Expr(start, predicates) = &path.start {
                    self.check_expression(start, source, location)?;
                    for predicate in predicates {
                        self.check_expression(predicate, source, location)?;
                    }
                }
                for step in &path.steps {
                    self.check_node_test(&step.node_test, source, location)?;
                    for predicate in &step.predicates {
                        self.check_expression(predicate, source, location)?;
                    }
                }
            }
        }
        Ok(())
    }

    /// The XPath 3.0 constructs' own check, split out of `check_expression`
    /// to keep that function under the line-count lint — each still needs a
    /// 3.0 binding, and a named function reference additionally needs to
    /// name a real function at the arity written.
    fn check_v3_expression(&self, expr: &Expr, source: &str, location: &str) -> Result<()> {
        match expr {
            Expr::InlineFunction { body, .. } => {
                self.require_v3("an inline function expression", source, location)?;
                self.check_expression(body, source, location)?;
            }
            Expr::NamedFunctionRef { name, arity } => {
                self.require_v3("a named function reference", source, location)?;
                check_function(name, *arity, self.version)
                    .map_err(|message| Error::xpath_syntax(location, source, 0, message))?;
            }
            Expr::DynamicCall { function, args } => {
                self.require_v3("a dynamic function call", source, location)?;
                self.check_expression(function, source, location)?;
                for arg in args {
                    self.check_expression(arg, source, location)?;
                }
            }
            _ => unreachable!("caller matches only the three XPath 3.0 variants"),
        }
        Ok(())
    }

    /// Checks one step's node test: prefixes must be declared, and a kind
    /// test needs an XPath 2.0 binding.
    fn check_node_test(&self, test: &NodeTest, source: &str, location: &str) -> Result<()> {
        match test {
            // An EQName carries its namespace URI outright — nothing to
            // resolve, so no `check_prefix` call, only the version gate.
            NodeTest::Name(NameTest { uri: Some(_), .. }) => {
                self.require_v3("an EQName (Q{uri}local)", source, location)
            }
            NodeTest::Name(NameTest {
                prefix: Some(prefix),
                ..
            })
            | NodeTest::NamespaceWildcard(prefix) => self.check_prefix(prefix, source, location),
            // A kind test as a node test is XPath 2.0. The lexer recognises
            // it whatever the binding, so that a 1.0 schema is told what it
            // wrote rather than being told `element` is an unknown function.
            NodeTest::Kind { kind, name } => {
                let written = match kind {
                    crate::xml::NodeKind::Element => "element",
                    crate::xml::NodeKind::Attribute => "attribute",
                    _ => "document-node",
                };
                self.require_v2(&format!("the {written}() kind test"), source, location)?;
                if let Some(NameTest {
                    prefix: Some(prefix),
                    ..
                }) = name
                {
                    self.check_prefix(prefix, source, location)?;
                }
                Ok(())
            }
            _ => Ok(()),
        }
    }

    /// Rejects an XPath 2.0 construct under an XPath 1.0 query binding.
    ///
    /// Keeping this in one place means every 2.0 construct refuses the same
    /// way and says the same thing about how to enable it.
    fn require_v2(&self, construct: &str, source: &str, location: &str) -> Result<()> {
        if self.version.is_v2() {
            return Ok(());
        }
        Err(Error::xpath_syntax(
            location,
            source,
            0,
            format!(
                "{construct} is XPath 2.0 syntax; this schema's query binding is \
                 XPath 1.0. Set queryBinding=\"xslt2\" to use it, and see \
                 spec/xpath2/ for what that enables."
            ),
        ))
    }

    /// Rejects an XPath 3.0 construct under an XPath 1.0 or 2.0 query
    /// binding. See [`Schema::require_v2`], which this mirrors.
    fn require_v3(&self, construct: &str, source: &str, location: &str) -> Result<()> {
        if self.version.is_v3() {
            return Ok(());
        }
        Err(Error::xpath_syntax(
            location,
            source,
            0,
            format!(
                "{construct} is XPath 3.0 syntax; this schema's query binding is \
                 {}. Set queryBinding=\"xslt3\" to use it, and see spec/xpath3/ \
                 for what that enables.",
                self.version.as_str()
            ),
        ))
    }

    /// The version gate for one [`Expr::Binary`] operator, split out of
    /// `check_expression` to keep that function under the line-count lint.
    /// Every operator with a version requirement is a single `require_v2`
    /// or `require_v3` call; the ordinary 1.0 operators (`+`, `=`, `|`, …)
    /// need none and fall through.
    fn check_binary_op_version(&self, op: BinaryOp, source: &str, location: &str) -> Result<()> {
        if op.is_value_comparison() {
            self.require_v2(
                &format!("the `{}` value comparison", op.as_str()),
                source,
                location,
            )?;
        }
        if op.is_node_comparison() {
            self.require_v2(
                &format!("the `{}` node comparison", op.as_str()),
                source,
                location,
            )?;
        }
        if op.is_string_concat() {
            self.require_v3("the `||` string concatenation operator", source, location)?;
        }
        if op.is_simple_map() {
            self.require_v3("the `!` simple map operator", source, location)?;
        }
        Ok(())
    }

    fn check_prefix(&self, prefix: &str, source: &str, location: &str) -> Result<()> {
        if self.namespaces.resolve(prefix).is_some() {
            return Ok(());
        }
        let declared: Vec<&str> = self.model.namespaces.iter().map(|n| n.prefix.as_str()).collect();
        Err(Error::xpath_syntax(
            location,
            source,
            0,
            format!(
                "namespace prefix {prefix:?} is not declared; add <ns prefix=\"{prefix}\" uri=\"…\"/> \
                 to the schema{}",
                if declared.is_empty() {
                    ", which currently declares none".to_string()
                } else {
                    format!(", which declares: {}", declared.join(", "))
                }
            ),
        ))
    }

    /// Checks that every id an assertion references actually exists.
    fn check_references(&self) -> Result<()> {
        for pattern in &self.model.patterns {
            for rule in &pattern.rules {
                for assertion in rule.assertions() {
                    for id in &assertion.diagnostics {
                        if self.model.diagnostic(id).is_none() {
                            return Err(Error::schema(
                                assertion.kind.as_str(),
                                pattern.id.clone(),
                                format!("no <diagnostic> with @id={id:?}"),
                            ));
                        }
                    }
                    for id in &assertion.properties {
                        if self.model.property(id).is_none() {
                            return Err(Error::schema(
                                assertion.kind.as_str(),
                                pattern.id.clone(),
                                format!("no <property> with @id={id:?}"),
                            ));
                        }
                    }
                }
            }
        }
        for phase in &self.model.phases {
            for active in &phase.actives {
                if self.model.pattern(active).is_none() {
                    return Err(Error::schema(
                        "active",
                        Some(format!("phase[@id='{}']", phase.id)),
                        format!(
                            "no <pattern> with @id={active:?}; an abstract pattern \
                             cannot be activated either, since it never runs"
                        ),
                    ));
                }
            }
        }
        // Key names must be unique, or a lookup would be ambiguous.
        for (index, key) in self.model.keys.iter().enumerate() {
            if self.model.keys[..index].iter().any(|earlier| earlier.name == key.name) {
                return Err(Error::schema(
                    "key",
                    Some(format!("key[@name='{}']", key.name)),
                    "two keys share this name; a lookup would be ambiguous",
                ));
            }
        }
        if let Some(default) = &self.model.default_phase {
            if self.model.phase(default).is_none() {
                return Err(Error::schema(
                    "schema",
                    None,
                    format!("@defaultPhase names {default:?}, which is not a declared <phase>"),
                ));
            }
        }
        Ok(())
    }

    /// Validates a document against this schema, using default options.
    ///
    /// # Errors
    ///
    /// Returns [`Error::XPathEval`] if an expression fails at runtime, and
    /// [`Error::UnknownPhase`] if a phase was named that does not exist. A
    /// document that simply breaks the rules is *not* an error: that is a
    /// [`Report`](crate::Report) with failures in it.
    pub fn validate(&self, document: &Document) -> Result<crate::Report> {
        self.validate_with(document, &crate::ValidateOptions::new())
    }

    /// Validates a document against this schema, with options.
    ///
    /// # Errors
    ///
    /// As [`Schema::validate`].
    pub fn validate_with(
        &self,
        document: &Document,
        options: &crate::ValidateOptions,
    ) -> Result<crate::Report> {
        crate::validate::validate(self, document, options)
    }

    /// Validates a document read from `source` one record at a time, never
    /// materialising the whole document in memory.
    ///
    /// Only for schemas whose active patterns are provably local to one
    /// record's own subtree — most real schemas are not, and
    /// [`Schema::streaming_eligible`] says why not for one that isn't,
    /// before any of `source` is even read. See `spec/streaming/` for
    /// exactly what qualifies and what the "record" boundary is.
    ///
    /// Deliberately a hard error rather than a silent fallback to
    /// [`Schema::validate_with`] when a schema does not qualify: someone
    /// reaching for this specifically needed bounded memory, and a silent
    /// fallback could exhaust it instead of failing cleanly.
    ///
    /// # Errors
    ///
    /// [`Error::Streaming`] if this schema is not streaming-eligible, or if
    /// `options` asks for parallel pattern evaluation (the arena streaming
    /// reuses across records is not safe to share across threads). As
    /// [`Schema::validate_with`] otherwise, plus [`Error::XmlParse`] and
    /// [`Error::Io`] from reading `source`.
    pub fn validate_streaming<R: std::io::Read>(
        &self,
        source: R,
        options: &crate::ValidateOptions,
    ) -> Result<crate::Report> {
        crate::validate::validate_streaming(self, source, options)
    }

    /// Whether [`Schema::validate_streaming`] can validate a document
    /// against this schema at all, and why not when it can't.
    ///
    /// Checked once at compile time, not per call — see `spec/streaming/`
    /// for the exact list of disqualifying constructs.
    ///
    /// # Errors
    ///
    /// The reason streaming is refused, as plain text naming the construct
    /// or declaration responsible.
    pub fn streaming_eligible(&self) -> std::result::Result<(), &str> {
        match &self.streaming_ineligible_reason {
            None => Ok(()),
            Some(reason) => Err(reason.as_str()),
        }
    }

    /// The resolver used for `pattern/@documents`.
    pub(crate) fn resolver(&self) -> &dyn super::resolver::Resolver {
        self.resolver.as_ref()
    }

    /// A compiled expression, by its source text.
    pub(crate) fn expression(&self, source: &str) -> Result<&Expr> {
        self.expressions.get(source).ok_or_else(|| {
            Error::xpath_eval(
                source,
                "this expression was not compiled; this is a bug in the crate",
            )
        })
    }

    /// Whether any expression in this schema calls XPath `document()`.
    ///
    /// A schema that does not is validated against the caller's document
    /// directly; one that does needs a working copy of the tree that loaded
    /// documents can be merged into.
    #[must_use]
    pub fn uses_document_function(&self) -> bool {
        self.uses_document_function
    }

    /// The parsed model, after includes and abstractions are expanded.
    #[must_use]
    pub fn model(&self) -> &SchemaModel {
        &self.model
    }

    /// The namespace bindings every expression is evaluated against.
    #[must_use]
    pub fn namespaces(&self) -> &Namespaces {
        &self.namespaces
    }

    /// The schema's `@id`.
    #[must_use]
    pub fn id(&self) -> Option<&str> {
        self.model.id.as_deref()
    }

    /// The schema's title.
    #[must_use]
    pub fn title(&self) -> Option<&str> {
        self.model.title.as_deref()
    }

    /// The schema's `@schemaVersion`.
    #[must_use]
    pub fn schema_version(&self) -> Option<&str> {
        self.model.schema_version.as_deref()
    }

    /// The XPath version this schema's expressions use.
    #[must_use]
    pub fn version(&self) -> XPathVersion {
        self.version
    }

    /// The query language binding the schema declares.
    #[must_use]
    pub fn query_binding(&self) -> &QueryBinding {
        &self.model.query_binding
    }

    /// The identifiers of the schema's phases, in document order.
    pub fn phases(&self) -> impl Iterator<Item = &str> {
        self.model.phases.iter().map(|p| p.id.as_str())
    }

    /// The schema's `@defaultPhase`.
    #[must_use]
    pub fn default_phase(&self) -> Option<&str> {
        self.model.default_phase.as_deref()
    }

    /// The keys, indexed before any pattern runs.
    #[must_use]
    pub fn keys(&self) -> &[crate::schema::Key] {
        &self.model.keys
    }

    /// The patterns that will run, in order.
    #[must_use]
    pub fn patterns(&self) -> &[Pattern] {
        &self.model.patterns
    }
}

fn collect_let(binding: &Let, location: &str, work: &mut Vec<(String, String, bool)>) {
    match &binding.value {
        LetValue::Expression(expression) => work.push((
            expression.clone(),
            format!("{location}/let[@name='{}']", binding.name),
            false,
        )),
        LetValue::Content(content) => collect_content(
            content,
            &format!("{location}/let[@name='{}']", binding.name),
            work,
        ),
    }
}

fn collect_pattern(pattern: &Pattern, index: usize, work: &mut Vec<(String, String, bool)>) {
    let location = pattern.id.as_ref().map_or_else(
        || format!("pattern[{}]", index + 1),
        |id| format!("pattern[@id='{id}']"),
    );
    if let Some(documents) = &pattern.documents {
        work.push((documents.clone(), format!("{location}/@documents"), false));
    }
    for binding in &pattern.lets {
        collect_let(binding, &location, work);
    }
    for rule in &pattern.rules {
        collect_rule(rule, &location, work);
    }
}

fn collect_rule(rule: &Rule, pattern_location: &str, work: &mut Vec<(String, String, bool)>) {
    let location = match &rule.context {
        Some(context) => format!("{pattern_location}/rule[@context='{context}']"),
        None => format!("{pattern_location}/rule"),
    };
    if let Some(context) = &rule.context {
        work.push((context.clone(), format!("{location}/@context"), true));
    }
    if let Some(subject) = &rule.subject {
        work.push((subject.clone(), format!("{location}/@subject"), false));
    }
    for binding in &rule.lets {
        collect_let(binding, &location, work);
    }
    for (index, assertion) in rule.assertions().enumerate() {
        collect_assertion(assertion, &location, index, work);
    }
}

fn collect_assertion(
    assertion: &Assertion,
    rule_location: &str,
    index: usize,
    work: &mut Vec<(String, String, bool)>,
) {
    let location = format!("{rule_location}/{}[{}]", assertion.kind.as_str(), index + 1);
    work.push((assertion.test.clone(), format!("{location}/@test"), false));
    if let Some(subject) = &assertion.subject {
        work.push((subject.clone(), format!("{location}/@subject"), false));
    }
    collect_content(&assertion.content, &location, work);
}

fn collect_content(content: &[Content], location: &str, work: &mut Vec<(String, String, bool)>) {
    for fragment in content {
        match fragment {
            // Literal text and a bare `<name/>` hold no expression to compile.
            Content::Text(_) | Content::Name { path: None } => {}
            Content::ValueOf { select } => {
                work.push((select.clone(), format!("{location}/value-of/@select"), false));
            }
            Content::Name { path: Some(path) } => {
                work.push((path.clone(), format!("{location}/name/@path"), false));
            }
            Content::Emph(inner)
            | Content::Span { content: inner, .. }
            | Content::Dir { content: inner, .. } => collect_content(inner, location, work),
        }
    }
}

/// Compiles a literal regular expression argument, so that a malformed
/// pattern written into the schema fails when the schema loads rather than
/// part-way through validating somebody's document.
///
/// A pattern computed at runtime cannot be checked here, and is validated
/// when it is evaluated.
fn check_literal_regex(
    name: &str,
    args: &[Expr],
    source: &str,
    location: &str,
) -> Result<()> {
    // `matches(input, pattern, flags?)` and `replace(input, pattern, replacement, flags?)`.
    let (pattern_index, flags_index) = match name {
        "matches" => (1, 2),
        "replace" => (1, 3),
        _ => return Ok(()),
    };

    let Some(Expr::Literal(pattern)) = args.get(pattern_index) else {
        return Ok(());
    };
    // Only check flags that are literal too; a computed flag string is left
    // to evaluation time.
    let flags = match args.get(flags_index) {
        Some(Expr::Literal(flags)) => Some(flags.as_str()),
        Some(_) => return Ok(()),
        None => None,
    };

    crate::xpath::check_regex(pattern, flags)
        .map_err(|message| Error::xpath_syntax(location, source, 0, message))
}

/// Whether an expression calls `document()` anywhere inside it.
fn calls_document_function(expr: &Expr) -> bool {
    match expr {
        Expr::Literal(_) | Expr::Number(_, _) | Expr::Variable(_) => false,
        Expr::Negate(inner) => calls_document_function(inner),
        Expr::Binary(_, left, right) => {
            calls_document_function(left) || calls_document_function(right)
        }
        Expr::Function { name, args } => {
            name == "document" || args.iter().any(calls_document_function)
        }
        Expr::If {
            condition,
            then_branch,
            else_branch,
        } => {
            calls_document_function(condition)
                || calls_document_function(then_branch)
                || calls_document_function(else_branch)
        }
        Expr::TypeOp { value, .. } => calls_document_function(value),
        Expr::Sequence(members) => members.iter().any(calls_document_function),
        Expr::Range(from, to) => {
            calls_document_function(from) || calls_document_function(to)
        }
        Expr::For { input, body, .. } => {
            calls_document_function(input) || calls_document_function(body)
        }
        Expr::Let { value, body, .. } => {
            calls_document_function(value) || calls_document_function(body)
        }
        Expr::Quantified { input, test, .. } => {
            calls_document_function(input) || calls_document_function(test)
        }
        Expr::InlineFunction { body, .. } => calls_document_function(body),
        Expr::NamedFunctionRef { name, .. } => name == "document",
        Expr::DynamicCall { function, args } => {
            calls_document_function(function) || args.iter().any(calls_document_function)
        }
        Expr::Arrow(called) => calls_document_function(called),
        Expr::Path(path) => {
            let start = match &path.start {
                PathStart::Expr(expr, predicates) => {
                    calls_document_function(expr)
                        || predicates.iter().any(calls_document_function)
                }
                PathStart::Root | PathStart::Context => false,
            };
            start
                || path
                    .steps
                    .iter()
                    .any(|step| step.predicates.iter().any(calls_document_function))
        }
    }
}

/// Whether streaming validation can validate documents against this
/// schema, and why not when it can't. See [`Schema::validate_streaming`]
/// and `spec/streaming/`.
///
/// Deliberately schema-wide, not scoped to one phase's active patterns —
/// the same choice `uses_document_function` already made: simpler, and
/// conservative in the direction that never lets an unsound schema
/// through, at the cost of occasionally refusing one whose only
/// disqualifying construct sits in a pattern that would never actually
/// run.
fn streaming_ineligibility_reason(schema: &Schema) -> Option<String> {
    if !schema.model.keys.is_empty() {
        return Some(
            "the schema declares <key>; a key indexes the whole document, and a \
             per-record index would silently answer key() differently than a real \
             one would"
                .to_string(),
        );
    }
    if !schema.model.lets.is_empty() {
        return Some(
            "the schema declares a schema-scoped <let>, which is evaluated once \
             against the document root before any record has been parsed"
                .to_string(),
        );
    }
    if let Some(phase) = schema.model.phases.iter().find(|p| !p.lets.is_empty()) {
        return Some(format!(
            "phase {:?} declares a phase-scoped <let>, which is evaluated once \
             against the document root before any record has been parsed",
            phase.id
        ));
    }
    for pattern in &schema.model.patterns {
        if pattern.documents.is_some() {
            return Some(format!(
                "pattern {} declares @documents, which validates other whole \
                 documents against the same pattern rather than the streamed one",
                pattern_label(pattern)
            ));
        }
        if !pattern.lets.is_empty() {
            return Some(format!(
                "pattern {} declares a pattern-scoped <let>, which is evaluated \
                 once against the document root before any record has been parsed",
                pattern_label(pattern)
            ));
        }
    }
    for expr in schema.expressions.values() {
        if let Some(what) = streaming_unsafe_construct(expr) {
            return Some(format!(
                "an expression uses {what}, which needs more of the document than \
                 one record's own subtree"
            ));
        }
    }
    None
}

fn pattern_label(pattern: &Pattern) -> String {
    match &pattern.id {
        Some(id) => format!("{id:?}"),
        None => "(unnamed)".to_string(),
    }
}

/// The first construct anywhere in `expr` that needs more of the document
/// than one record's own subtree, if any — see
/// [`streaming_ineligibility_reason`].
///
/// `following::`, `preceding::`, and `following-sibling::` each need
/// either the whole document or a record's *parent's* full child list
/// (`collect_axis`, `src/xpath/eval.rs`); `document()`, `id()`, and
/// `key()` each need the whole document too, the same reasoning
/// [`calls_document_function`] already applies to `document()` alone.
/// Every other axis and function reads only a node's already-parsed
/// ancestor chain plus its own subtree, which streaming always has.
fn streaming_unsafe_construct(expr: &Expr) -> Option<&'static str> {
    const UNSAFE_FUNCTIONS: [&str; 3] = ["document", "id", "key"];

    match expr {
        Expr::Literal(_) | Expr::Number(_, _) | Expr::Variable(_) => None,
        Expr::Negate(inner) => streaming_unsafe_construct(inner),
        Expr::Binary(_, left, right) => {
            streaming_unsafe_construct(left).or_else(|| streaming_unsafe_construct(right))
        }
        Expr::Function { name, args } => UNSAFE_FUNCTIONS
            .iter()
            .find(|&&f| f == name)
            .map(|&f| function_reason(f))
            .or_else(|| args.iter().find_map(streaming_unsafe_construct)),
        Expr::If {
            condition,
            then_branch,
            else_branch,
        } => streaming_unsafe_construct(condition)
            .or_else(|| streaming_unsafe_construct(then_branch))
            .or_else(|| streaming_unsafe_construct(else_branch)),
        Expr::TypeOp { value, .. } => streaming_unsafe_construct(value),
        Expr::Sequence(members) => members.iter().find_map(streaming_unsafe_construct),
        Expr::Range(from, to) => {
            streaming_unsafe_construct(from).or_else(|| streaming_unsafe_construct(to))
        }
        Expr::For { input, body, .. } => {
            streaming_unsafe_construct(input).or_else(|| streaming_unsafe_construct(body))
        }
        Expr::Let { value, body, .. } => {
            streaming_unsafe_construct(value).or_else(|| streaming_unsafe_construct(body))
        }
        Expr::Quantified { input, test, .. } => {
            streaming_unsafe_construct(input).or_else(|| streaming_unsafe_construct(test))
        }
        Expr::InlineFunction { body, .. } => streaming_unsafe_construct(body),
        Expr::NamedFunctionRef { name, .. } => UNSAFE_FUNCTIONS
            .iter()
            .find(|&&f| f == name)
            .map(|&f| function_reason(f)),
        Expr::DynamicCall { function, args } => streaming_unsafe_construct(function)
            .or_else(|| args.iter().find_map(streaming_unsafe_construct)),
        Expr::Arrow(called) => streaming_unsafe_construct(called),
        Expr::Path(path) => {
            let start = match &path.start {
                PathStart::Expr(expr, predicates) => streaming_unsafe_construct(expr)
                    .or_else(|| predicates.iter().find_map(streaming_unsafe_construct)),
                PathStart::Root | PathStart::Context => None,
            };
            start.or_else(|| path.steps.iter().find_map(|step| {
                axis_reason(step.axis)
                    .or_else(|| step.predicates.iter().find_map(streaming_unsafe_construct))
            }))
        }
    }
}

fn axis_reason(axis: Axis) -> Option<&'static str> {
    match axis {
        Axis::Following => Some("the following:: axis"),
        Axis::Preceding => Some("the preceding:: axis"),
        Axis::FollowingSibling => Some("the following-sibling:: axis"),
        _ => None,
    }
}

fn function_reason(name: &'static str) -> &'static str {
    match name {
        "document" => "document()",
        "id" => "id()",
        "key" => "key()",
        _ => unreachable!("only called with a name from UNSAFE_FUNCTIONS"),
    }
}

/// Rejects a `rule/@context` that is not a legal XSLT match pattern.
///
/// A match pattern selects downwards from an ancestor; a leading reverse axis
/// has no meaning in that reduction. Rejecting it beats guessing, because a
/// guess would produce a rule that silently never fires.
fn check_match_pattern(expr: &Expr, source: &str, location: &str) -> Result<()> {
    match expr {
        Expr::Binary(crate::xpath::BinaryOp::Union, left, right) => {
            check_match_pattern(left, source, location)?;
            check_match_pattern(right, source, location)
        }
        Expr::Path(path) => {
            for step in &path.steps {
                let allowed = matches!(
                    step.axis,
                    Axis::Child | Axis::Attribute | Axis::DescendantOrSelf | Axis::SelfAxis
                );
                if !allowed {
                    return Err(Error::xpath_syntax(
                        location,
                        source,
                        0,
                        format!(
                            "the {}:: axis is not allowed in a rule context, which must be an \
                             XSLT match pattern; express the constraint as a predicate instead, \
                             such as `a[ancestor::b]`",
                            step.axis.as_str()
                        ),
                    ));
                }
            }
            Ok(())
        }
        _ => Err(Error::xpath_syntax(
            location,
            source,
            0,
            "a rule context must be a location path or a union of location paths",
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const MINIMAL: &str = r#"
        <schema xmlns="http://purl.oclc.org/dsdl/schematron">
          <pattern><rule context="a"><assert test="b">m</assert></rule></pattern>
        </schema>
    "#;

    fn error(source: &str) -> String {
        Schema::from_str(source).unwrap_err().to_string()
    }

    #[test]
    fn compiles_a_minimal_schema() {
        let schema = Schema::from_str(MINIMAL).unwrap();
        assert_eq!(schema.patterns().len(), 1);
        assert!(schema.expression("a").is_ok());
        assert!(schema.expression("b").is_ok());
    }

    #[test]
    fn reports_syntax_errors_at_compile_time_with_a_location() {
        let message = error(
            r#"<schema xmlns="http://purl.oclc.org/dsdl/schematron">
                 <pattern><rule context="a"><assert test="count(b">m</assert></rule></pattern>
               </schema>"#,
        );
        assert!(message.contains("XPath syntax error"), "{message}");
        assert!(message.contains("@test"), "{message}");
    }

    #[test]
    fn reports_unknown_functions_at_compile_time() {
        let message = error(
            r#"<schema xmlns="http://purl.oclc.org/dsdl/schematron">
                 <pattern><rule context="a"><assert test="nonsense()">m</assert></rule></pattern>
               </schema>"#,
        );
        assert!(message.contains("unknown function"), "{message}");
    }

    #[test]
    fn names_xpath_two_functions_as_such() {
        let message = error(
            r#"<schema xmlns="http://purl.oclc.org/dsdl/schematron">
                 <pattern><rule context="a">
                   <assert test="matches(., 'x')">m</assert>
                 </rule></pattern>
               </schema>"#,
        );
        assert!(message.contains("XPath 2.0"), "{message}");
    }

    #[test]
    fn reports_undeclared_prefixes_at_compile_time() {
        let message = error(
            r#"<schema xmlns="http://purl.oclc.org/dsdl/schematron">
                 <pattern><rule context="p:a"><assert test="b">m</assert></rule></pattern>
               </schema>"#,
        );
        assert!(message.contains("is not declared"), "{message}");
    }

    #[test]
    fn accepts_declared_prefixes() {
        let schema = Schema::from_str(
            r#"<schema xmlns="http://purl.oclc.org/dsdl/schematron">
                 <ns prefix="p" uri="urn:p"/>
                 <pattern><rule context="p:a"><assert test="p:b">m</assert></rule></pattern>
               </schema>"#,
        )
        .unwrap();
        assert_eq!(schema.namespaces().resolve("p"), Some("urn:p"));
    }

    #[test]
    fn rejects_query_bindings_above_xpath_three() {
        let source = r#"<schema xmlns="http://purl.oclc.org/dsdl/schematron" queryBinding="xpath31">
                          <pattern><rule context="a"><assert test="b">m</assert></rule></pattern>
                        </schema>"#;
        assert!(matches!(
            Schema::from_str(source).unwrap_err(),
            Error::UnsupportedQueryBinding { .. }
        ));

        let options = SchemaOptions::new().with_allow_unknown_query_binding(true);
        assert!(Schema::from_str_with(source, &options).is_ok());
    }

    #[test]
    fn accepts_the_xpath_two_bindings() {
        for binding in ["xslt2", "xpath2"] {
            let source = format!(
                r#"<schema xmlns="http://purl.oclc.org/dsdl/schematron" queryBinding="{binding}">
                     <pattern><rule context="a"><assert test="b">m</assert></rule></pattern>
                   </schema>"#
            );
            let schema = Schema::from_str(&source)
                .unwrap_or_else(|e| panic!("{binding} should compile: {e}"));
            assert_eq!(schema.version(), crate::xpath::XPathVersion::V2);
        }
    }

    #[test]
    fn accepts_the_xpath_three_bindings() {
        for binding in ["xslt3", "xpath3"] {
            let source = format!(
                r#"<schema xmlns="http://purl.oclc.org/dsdl/schematron" queryBinding="{binding}">
                     <pattern><rule context="a"><assert test="b">m</assert></rule></pattern>
                   </schema>"#
            );
            let schema = Schema::from_str(&source)
                .unwrap_or_else(|e| panic!("{binding} should compile: {e}"));
            assert_eq!(schema.version(), crate::xpath::XPathVersion::V3);
        }
    }

    #[test]
    fn a_forced_unknown_binding_is_treated_as_xpath_one() {
        // `allow_unknown_query_binding` must not quietly grant later-version
        // features.
        let source = r#"<schema xmlns="http://purl.oclc.org/dsdl/schematron" queryBinding="xpath31">
                          <pattern><rule context="a"><assert test="b">m</assert></rule></pattern>
                        </schema>"#;
        let options = SchemaOptions::new().with_allow_unknown_query_binding(true);
        let schema = Schema::from_str_with(source, &options).unwrap();
        assert_eq!(schema.version(), crate::xpath::XPathVersion::V1);
    }

    #[test]
    fn rejects_reverse_axes_in_a_rule_context() {
        let message = error(
            r#"<schema xmlns="http://purl.oclc.org/dsdl/schematron">
                 <pattern><rule context="ancestor::a"><assert test="b">m</assert></rule></pattern>
               </schema>"#,
        );
        assert!(message.contains("not allowed in a rule context"), "{message}");
    }

    #[test]
    fn accepts_the_usual_match_pattern_shapes() {
        for context in ["a", "a/b", "//a", "/a", "@x", "a[@x]", "a | b", "*", "text()"] {
            let source = format!(
                r#"<schema xmlns="http://purl.oclc.org/dsdl/schematron">
                     <pattern><rule context="{context}"><assert test="true()">m</assert></rule></pattern>
                   </schema>"#
            );
            assert!(Schema::from_str(&source).is_ok(), "rejected context {context:?}");
        }
    }

    #[test]
    fn rejects_references_to_missing_diagnostics() {
        let message = error(
            r#"<schema xmlns="http://purl.oclc.org/dsdl/schematron">
                 <pattern><rule context="a">
                   <assert test="b" diagnostics="nope">m</assert>
                 </rule></pattern>
               </schema>"#,
        );
        assert!(message.contains("no <diagnostic>"), "{message}");
    }

    #[test]
    fn rejects_phases_that_activate_missing_patterns() {
        let message = error(
            r#"<schema xmlns="http://purl.oclc.org/dsdl/schematron">
                 <phase id="p"><active pattern="nope"/></phase>
                 <pattern id="q"><rule context="a"><assert test="b">m</assert></rule></pattern>
               </schema>"#,
        );
        assert!(message.contains("no <pattern>"), "{message}");
    }

    #[test]
    fn rejects_a_default_phase_that_does_not_exist() {
        let message = error(
            r#"<schema xmlns="http://purl.oclc.org/dsdl/schematron" defaultPhase="nope">
                 <pattern><rule context="a"><assert test="b">m</assert></rule></pattern>
               </schema>"#,
        );
        assert!(message.contains("defaultPhase"), "{message}");
    }

    #[test]
    fn identical_expressions_compile_once() {
        let schema = Schema::from_str(
            r#"<schema xmlns="http://purl.oclc.org/dsdl/schematron">
                 <pattern>
                   <rule context="a"><assert test="b">one</assert></rule>
                   <rule context="c"><assert test="b">two</assert></rule>
                 </pattern>
               </schema>"#,
        )
        .unwrap();
        // "a", "b", "c" — three distinct sources, not four expressions.
        assert_eq!(schema.expressions.len(), 3);
    }

    #[test]
    fn schema_is_send_and_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<Schema>();
    }
}