schematron 0.8.0

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 subset, 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
1591
1592
1593
1594
1595
1596
1597
1598
1599
//! The XPath 1.0 core function library.
//!
//! All twenty-seven functions of XPath 1.0 section 4, plus `current()` from
//! the XSLT library, which Schematron's `xslt` query binding makes available
//! and which schemas genuinely use inside predicates.
//!
//! Arity is checked when the schema is compiled, not when a document is
//! validated, so `contains(@x)` is an error the moment the schema loads.

use super::context::EvalContext;
use super::eval::EvalError;
use super::temporal::{from_unix_seconds, Duration, DurationKind, Temporal, TemporalKind};
use super::value::{parse_number, Item, NumericType, Value};
use super::version::XPathVersion;
use crate::xml::{Document, NodeId, NodeKind, QName};

/// The name and permitted argument count of every supported function.
///
/// `None` as the maximum means unbounded, which only `concat` uses.
const SIGNATURES: &[(&str, usize, Option<usize>)] = &[
    ("last", 0, Some(0)),
    ("position", 0, Some(0)),
    ("count", 1, Some(1)),
    ("id", 1, Some(1)),
    ("local-name", 0, Some(1)),
    ("namespace-uri", 0, Some(1)),
    ("name", 0, Some(1)),
    ("string", 0, Some(1)),
    ("concat", 2, None),
    ("starts-with", 2, Some(2)),
    ("contains", 2, Some(2)),
    ("substring-before", 2, Some(2)),
    ("substring-after", 2, Some(2)),
    ("substring", 2, Some(3)),
    ("string-length", 0, Some(1)),
    ("normalize-space", 0, Some(1)),
    ("translate", 3, Some(3)),
    ("boolean", 1, Some(1)),
    ("not", 1, Some(1)),
    ("true", 0, Some(0)),
    ("false", 0, Some(0)),
    ("lang", 1, Some(1)),
    ("number", 0, Some(1)),
    ("sum", 1, Some(1)),
    ("floor", 1, Some(1)),
    ("ceiling", 1, Some(1)),
    ("round", 1, Some(1)),
    ("current", 0, Some(0)),
    ("document", 1, Some(2)),
    ("key", 2, Some(2)),
];

/// The XPath 2.0 functions this crate implements, with their arities.
///
/// Available only under an XPath 2.0 query binding. The set is deliberately
/// the one that needs no sequence type; see `spec/xpath2/`.
const SIGNATURES_V2: &[(&str, usize, Option<usize>)] = &[
    ("matches", 2, Some(3)),
    ("replace", 3, Some(4)),
    ("upper-case", 1, Some(1)),
    ("lower-case", 1, Some(1)),
    ("ends-with", 2, Some(2)),
    ("abs", 1, Some(1)),
    ("min", 1, Some(1)),
    ("max", 1, Some(1)),
    ("avg", 1, Some(1)),
    ("exists", 1, Some(1)),
    ("empty", 1, Some(1)),
    ("string-join", 2, Some(2)),
    ("tokenize", 2, Some(3)),
    ("distinct-values", 1, Some(1)),
    ("index-of", 2, Some(2)),
    ("reverse", 1, Some(1)),
    ("subsequence", 2, Some(3)),
    ("insert-before", 3, Some(3)),
    ("remove", 2, Some(2)),
    ("unordered", 1, Some(1)),
    ("zero-or-one", 1, Some(1)),
    ("one-or-more", 1, Some(1)),
    ("exactly-one", 1, Some(1)),
    ("data", 1, Some(1)),
    ("deep-equal", 2, Some(2)),
    ("current-date", 0, Some(0)),
    ("current-dateTime", 0, Some(0)),
    ("current-time", 0, Some(0)),
    ("year-from-date", 1, Some(1)),
    ("month-from-date", 1, Some(1)),
    ("day-from-date", 1, Some(1)),
    ("year-from-dateTime", 1, Some(1)),
    ("month-from-dateTime", 1, Some(1)),
    ("day-from-dateTime", 1, Some(1)),
    ("hours-from-dateTime", 1, Some(1)),
    ("minutes-from-dateTime", 1, Some(1)),
    ("seconds-from-dateTime", 1, Some(1)),
    ("hours-from-time", 1, Some(1)),
    ("minutes-from-time", 1, Some(1)),
    ("seconds-from-time", 1, Some(1)),
    ("xs:date", 1, Some(1)),
    ("xs:dateTime", 1, Some(1)),
    ("xs:time", 1, Some(1)),
    ("xs:dayTimeDuration", 1, Some(1)),
    ("xs:yearMonthDuration", 1, Some(1)),
    ("days-from-duration", 1, Some(1)),
    ("hours-from-duration", 1, Some(1)),
    ("minutes-from-duration", 1, Some(1)),
    ("seconds-from-duration", 1, Some(1)),
    ("years-from-duration", 1, Some(1)),
    ("months-from-duration", 1, Some(1)),
    ("timezone-from-date", 1, Some(1)),
    ("timezone-from-dateTime", 1, Some(1)),
    ("timezone-from-time", 1, Some(1)),
    ("implicit-timezone", 0, Some(0)),
];

/// XPath 2.0 date/time-related functions this crate does not implement yet.
///
/// Not blocked on the date and time types, which shipped in phase 2b:
/// `duration()` needs the general `xs:duration` type, which
/// `spec/xpath2/` documents as a deliberate omission (only the two ordered
/// subtypes are implemented); the `adjust-*-to-timezone()` functions need a
/// timezone-bearing cast, which nothing in the crate currently produces.
const V2_FUNCTIONS_NEEDING_DATES: &[&str] = &[
    "duration",
    "adjust-date-to-timezone",
    "adjust-dateTime-to-timezone",
    "adjust-time-to-timezone",
];

/// Other XPath 2.0 functions that are simply not implemented yet.
///
/// `for-each` looks like a sequence function and was filed as one until this
/// list was audited: it is not part of XPath 2.0 at all. `fn:for-each` takes
/// a **function item** as its second argument, and function items — inline
/// function expressions, named function references, dynamic calls — are an
/// XPath 3.0 feature this crate does not have. Its neighbours here
/// (`subsequence`, `insert-before`, `remove`, `reverse`, `unordered`) needed
/// only the sequence type, which phase 2a already shipped, and are
/// implemented; `for-each` needs a type this crate has no representation
/// for.
const V2_FUNCTIONS_NOT_IMPLEMENTED: &[&str] = &["trace", "resolve-uri", "for-each"];

/// Checks that a function exists and accepts this many arguments.
///
/// Called while compiling a schema, so that a typo or an XPath 2.0 function
/// is reported against the schema rather than against a document.
///
/// # Errors
///
/// Returns a message naming the function and, where it can, why it is absent.
///
/// # Examples
///
/// ```
/// use schematron::xpath::{check_function, XPathVersion};
///
/// assert!(check_function("contains", 2, XPathVersion::V1).is_ok());
/// assert!(check_function("contains", 1, XPathVersion::V1).is_err());
///
/// // An XPath 2.0 function needs an XPath 2.0 query binding.
/// assert!(check_function("matches", 2, XPathVersion::V1).is_err());
/// assert!(check_function("matches", 2, XPathVersion::V2).is_ok());
/// ```
pub fn check_function(name: &str, arity: usize, version: XPathVersion) -> Result<(), String> {
    let tables: &[&[(&str, usize, Option<usize>)]] = if version.is_v2() {
        &[SIGNATURES, SIGNATURES_V2]
    } else {
        &[SIGNATURES]
    };

    for (function, minimum, maximum) in tables.iter().copied().flatten() {
        if *function != name {
            continue;
        }
        if arity < *minimum {
            return Err(format!(
                "{name}() takes at least {minimum} argument(s), but {arity} were given"
            ));
        }
        if let Some(maximum) = maximum {
            if arity > *maximum {
                return Err(format!(
                    "{name}() takes at most {maximum} argument(s), but {arity} were given"
                ));
            }
        }
        return Ok(());
    }

    // A 2.0 function used under a 1.0 binding: say which binding it needs.
    if !version.is_v2() && SIGNATURES_V2.iter().any(|(f, _, _)| *f == name) {
        return Err(format!(
            "{name}() is an XPath 2.0 function, and this schema's query binding is \
             XPath 1.0. Set queryBinding=\"xslt2\" to use it; see spec/xpath2/."
        ));
    }
    if V2_FUNCTIONS_NEEDING_DATES.contains(&name) {
        return Err(format!(
            "{name}() is an XPath 2.0 date and time function this crate \
             does not implement yet; see spec/xpath2/"
        ));
    }
    if V2_FUNCTIONS_NOT_IMPLEMENTED.contains(&name) {
        return Err(format!(
            "{name}() is an XPath 2.0 function this crate does not implement; \
             see spec/xpath2/"
        ));
    }
    Err(format!("unknown function {name}()"))
}

/// The names of every function this crate implements, sorted.
///
/// Useful for building a "did you mean" list, and for documentation tests
/// that assert the library has not silently shrunk.
#[must_use]
pub fn function_names() -> Vec<&'static str> {
    let mut names: Vec<&'static str> = SIGNATURES.iter().map(|(name, _, _)| *name).collect();
    names.sort_unstable();
    names
}

/// Checks a regular expression literal and its flags, without a document.
///
/// Called while compiling a schema, 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.
///
/// # Errors
///
/// Returns a message naming the pattern and what is wrong with it.
///
/// # Examples
///
/// ```
/// use schematron::xpath::check_regex;
///
/// assert!(check_regex("^[0-9]+$", None).is_ok());
/// assert!(check_regex("^[0-9]+$", Some("i")).is_ok());
/// assert!(check_regex("[unclosed", None).is_err());
/// assert!(check_regex(".", Some("q")).is_err());
/// ```
pub fn check_regex(pattern: &str, flags: Option<&str>) -> Result<(), String> {
    build_regex(pattern, flags.unwrap_or_default()).map(|_| ())
}

/// The names of the XPath 2.0 functions this crate implements, sorted.
#[must_use]
pub fn function_names_v2() -> Vec<&'static str> {
    let mut names: Vec<&'static str> = SIGNATURES_V2.iter().map(|(name, _, _)| *name).collect();
    names.sort_unstable();
    names
}

/// Calls a function with already-evaluated arguments.
///
/// Re-checks arity here rather than trusting that [`check_function`] ran.
/// Schema compilation does call it, but [`evaluate`] is public and can be
/// handed an expression that never went through a schema — and the arms below
/// index into `args` directly, so an unchecked call would panic rather than
/// return an error.
///
/// [`evaluate`]: super::evaluate
pub(crate) fn call(
    name: &str,
    args: &[Value],
    context: &EvalContext<'_>,
) -> Result<Value, EvalError> {
    check_function(name, args.len(), context.version).map_err(EvalError::new)?;
    let document = context.document;
    match name {
        "last" => Ok(double(as_f64(context.size))),
        "position" => Ok(double(as_f64(context.position))),
        "count" => Ok(double(as_f64(
            items_of(name, args, 0, context.version)?.len(),
        ))),
        "id" => Ok(Value::NodeSet(id_function(args, context))),

        "local-name" => Ok(Value::String(
            node_argument(name, args, context)?
                .and_then(|n| document.name(n).map(|q| q.local.clone()))
                .unwrap_or_default(),
        )),
        "namespace-uri" => Ok(Value::String(
            node_argument(name, args, context)?
                .and_then(|n| document.name(n).and_then(|q| q.uri.clone()))
                .unwrap_or_default(),
        )),
        "name" => Ok(Value::String(
            node_argument(name, args, context)?
                .and_then(|n| document.name(n).map(crate::xml::QName::display_name))
                .unwrap_or_default(),
        )),

        "string" => Ok(Value::String(match args.first() {
            Some(value) => value.to_xpath_string(document),
            None => document.string_value(context.node),
        })),
        "concat" => Ok(Value::String(
            args.iter()
                .map(|a| a.to_xpath_string(document))
                .collect::<String>(),
        )),
        "starts-with" => {
            let (haystack, needle) = two_strings(args, document);
            Ok(Value::Boolean(haystack.starts_with(&needle)))
        }
        "contains" => {
            let (haystack, needle) = two_strings(args, document);
            Ok(Value::Boolean(haystack.contains(&needle)))
        }
        "substring-before" => {
            let (haystack, needle) = two_strings(args, document);
            Ok(Value::String(
                haystack
                    .find(&needle)
                    .map(|i| haystack[..i].to_string())
                    .unwrap_or_default(),
            ))
        }
        "substring-after" => {
            let (haystack, needle) = two_strings(args, document);
            Ok(Value::String(
                haystack
                    .find(&needle)
                    .map(|i| haystack[i + needle.len()..].to_string())
                    .unwrap_or_default(),
            ))
        }
        "substring" => Ok(Value::String(substring(args, document))),
        "string-length" => Ok(double(as_f64(
            string_argument(args, context).chars().count(),
        ))),
        "normalize-space" => Ok(Value::String(normalize_space(&string_argument(
            args, context,
        )))),
        "translate" => Ok(Value::String(translate(
            &args[0].to_xpath_string(document),
            &args[1].to_xpath_string(document),
            &args[2].to_xpath_string(document),
        ))),

        "boolean" => Ok(Value::Boolean(args[0].to_boolean())),
        "not" => Ok(Value::Boolean(!args[0].to_boolean())),
        "true" => Ok(Value::Boolean(true)),
        "false" => Ok(Value::Boolean(false)),
        "lang" => Ok(Value::Boolean(lang(
            &args[0].to_xpath_string(document),
            document,
            context.node,
        ))),

        "number" => Ok(double(match args.first() {
            Some(value) => value.to_number(document),
            None => parse_number(&document.string_value(context.node)),
        })),
        // Folded from `0.0` rather than `.sum()`: Rust's `Sum` for `f64` starts
        // from `-0.0`, which is the true additive identity — `-0.0 + x == x`
        // for every `x`, including `-0.0` itself, which `0.0` does not manage.
        // Correct for Rust, wrong here: `sum()` over an empty node-set must be
        // positive zero, as every other XPath processor gives. The sign is
        // invisible until something divides by it, and then `1 div sum(none)`
        // is -Infinity instead of Infinity.
        "sum" => {
            let items = items_of(name, args, 0, context.version)?;
            Ok(double(
                items.iter().map(|item| item.to_number(document)).fold(0.0, |a, b| a + b),
            ))
        }
        "floor" => Ok(double(args[0].to_number(document).floor())),
        "ceiling" => Ok(double(args[0].to_number(document).ceil())),
        "round" => Ok(double(round_half_up(args[0].to_number(document)))),

        "current" => Ok(Value::NodeSet(vec![context.current])),

        "document" => document_function(args, context),
        "key" => key_function(args, context),

        // XPath 2.0, phase 1. Reachable only under a 2.0 query binding,
        // because `check_function` above gates on the version.
        _ if context.version.is_v2() => call_v2(name, args, context),

        _ => Err(EvalError::new(format!("unknown function {name}()"))),
    }
}

/// The XPath 2.0 additions, split out so each dispatch stays readable and
/// mirrors its own signature table.
fn call_v2(name: &str, args: &[Value], context: &EvalContext<'_>) -> Result<Value, EvalError> {
    let document = context.document;
    match name {        "matches" => {
            let regex = compile_regex(&args[1].to_xpath_string(document), args.get(2), document)?;
            Ok(Value::Boolean(
                regex.is_match(&args[0].to_xpath_string(document)),
            ))
        }
        "replace" => {
            let regex = compile_regex(&args[1].to_xpath_string(document), args.get(3), document)?;
            let input = args[0].to_xpath_string(document);
            let replacement = translate_replacement(&args[2].to_xpath_string(document));
            Ok(Value::String(
                regex.replace_all(&input, replacement.as_str()).into_owned(),
            ))
        }
        "upper-case" => Ok(Value::String(args[0].to_xpath_string(document).to_uppercase())),
        "lower-case" => Ok(Value::String(args[0].to_xpath_string(document).to_lowercase())),
        "ends-with" => {
            let (haystack, needle) = two_strings(args, document);
            Ok(Value::Boolean(haystack.ends_with(&needle)))
        }
        "abs" => Ok(double(args[0].to_number(document).abs())),
        "min" => Ok(double(extreme(args, document, f64::min))),
        "max" => Ok(double(extreme(args, document, f64::max))),
        "avg" => {
            let numbers = numbers_of(args, document);
            if numbers.is_empty() {
                // XPath 2.0's avg() of an empty sequence is the empty
                // sequence; without sequences, NaN is the honest analogue and
                // behaves the same way in every comparison.
                return Ok(double(f64::NAN));
            }
            // Folded from `0.0` for the same reason as `sum()` above.
            let total: f64 = numbers.iter().fold(0.0, |a, b| a + b);
            #[allow(clippy::cast_precision_loss)]
            let count = numbers.len() as f64;
            Ok(double(total / count))
        }
        "exists" => Ok(Value::Boolean(!items_of(name, args, 0, context.version)?.is_empty())),
        "empty" => Ok(Value::Boolean(items_of(name, args, 0, context.version)?.is_empty())),
        "string-join" => {
            let items = items_of(name, args, 0, context.version)?;
            let separator = args[1].to_xpath_string(document);
            let parts: Vec<String> = items
                .iter()
                .map(|item| item.to_xpath_string(document))
                .collect();
            Ok(Value::String(parts.join(&separator)))
        }

        "tokenize" => {
            let regex = compile_regex(&args[1].to_xpath_string(document), args.get(2), document)?;
            let input = args[0].to_xpath_string(document);
            Ok(Value::Sequence(
                regex
                    .split(&input)
                    .map(|part| Item::String(part.to_string()))
                    .collect(),
            ))
        }

        "distinct-values" => {
            let items = items_of(name, args, 0, context.version)?;
            // Compared by string value, and first-seen order is kept, which
            // is what makes the result predictable. XPath 2.0 leaves the
            // order implementation-defined.
            let mut seen: Vec<String> = Vec::new();
            let mut out = Vec::new();
            for item in items {
                let key = item.to_xpath_string(document);
                if seen.iter().any(|existing| existing == &key) {
                    continue;
                }
                seen.push(key.clone());
                out.push(Item::String(key));
            }
            Ok(Value::Sequence(out))
        }

        _ => call_v2_temporal(name, args, context),
    }
}

/// The XPath 2.0 date, time and duration functions, split out so that each
/// dispatch stays readable.
fn call_v2_temporal(
    name: &str,
    args: &[Value],
    context: &EvalContext<'_>,
) -> Result<Value, EvalError> {
    let document = context.document;
    match name {
        "current-date" => clock(TemporalKind::Date, context),
        "current-dateTime" => clock(TemporalKind::DateTime, context),
        "current-time" => clock(TemporalKind::Time, context),

        "xs:date" => cast_temporal(args, TemporalKind::Date, document),
        "xs:dateTime" => cast_temporal(args, TemporalKind::DateTime, document),
        "xs:time" => cast_temporal(args, TemporalKind::Time, document),

        "xs:dayTimeDuration" => cast_duration(args, DurationKind::DayTime, document),
        "xs:yearMonthDuration" => cast_duration(args, DurationKind::YearMonth, document),

        _ if name.ends_with("-from-duration") => duration_component(name, args, document),

        "implicit-timezone" => Ok(Value::Sequence(vec![Item::Duration(
            Duration::from_seconds(f64::from(context.implicit_timezone) * 60.0),
        )])),

        _ if name.starts_with("timezone-from-") => timezone_of(name, args, document),

        _ if name.ends_with("-from-date")
            || name.ends_with("-from-dateTime")
            || name.ends_with("-from-time") =>
        {
            component_of(name, args, document)
        }

        _ => call_v2_rest(name, args, context),
    }
}

/// The remaining XPath 2.0 functions.
fn call_v2_rest(name: &str, args: &[Value], context: &EvalContext<'_>) -> Result<Value, EvalError> {
    let document = context.document;
    match name {
        "index-of" => {
            let items = items_of(name, args, 0, context.version)?;
            let wanted = args[1].to_xpath_string(document);
            let positions = items
                .iter()
                .enumerate()
                .filter(|(_, item)| item.to_xpath_string(document) == wanted)
                // XPath positions are one-based.
                .map(|(index, _)| Item::Number(as_f64(index + 1), NumericType::Double))
                .collect();
            Ok(Value::Sequence(positions))
        }

        "reverse" => {
            let mut items = items_of(name, args, 0, context.version)?;
            items.reverse();
            Ok(Value::Sequence(items))
        }

        // The result order is implementation-defined by the spec — the
        // point of the name is that a caller may not rely on it. Returning
        // the input unchanged is a conformant choice, and a deterministic
        // one is easier to write a test against than any other.
        "unordered" => Ok(Value::Sequence(items_of(name, args, 0, context.version)?)),

        "subsequence" => Ok(Value::Sequence(subsequence(name, args, context)?)),

        "insert-before" => {
            let mut items = items_of(name, args, 0, context.version)?;
            let inserts = items_of(name, args, 2, context.version)?;
            // Per the F&O definition: a position before the start clamps to
            // the front, and one past the end appends. `round_half_up`
            // mirrors `fn:round`'s own tie-breaking, so this agrees with
            // `subsequence()` on where a fractional position lands.
            let position = round_half_up(args[1].to_number(document));
            #[allow(
                clippy::cast_precision_loss,
                clippy::cast_sign_loss,
                clippy::cast_possible_truncation
            )]
            let index = if position < 1.0 {
                0
            } else if position > items.len() as f64 {
                items.len()
            } else {
                (position - 1.0) as usize
            };
            items.splice(index..index, inserts);
            Ok(Value::Sequence(items))
        }

        "remove" => {
            let mut items = items_of(name, args, 0, context.version)?;
            let position = round_half_up(args[1].to_number(document));
            // Out of range — including NaN, for which every comparison
            // below is false — leaves the sequence unchanged, per the F&O
            // definition, rather than an error.
            #[allow(clippy::cast_precision_loss)]
            if position >= 1.0 && position <= items.len() as f64 {
                #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
                items.remove(position as usize - 1);
            }
            Ok(Value::Sequence(items))
        }

        // The three cardinality assertions. Each passes its argument through
        // unchanged when the cardinality holds, and raises rather than
        // silently truncating or padding otherwise — the same choice
        // `eq`/`ne`/… make for "more than one item", and for the same
        // reason: guessing which item to keep would be a wrong answer
        // wearing the shape of a right one.
        "zero-or-one" => {
            let items = items_of(name, args, 0, context.version)?;
            if items.len() > 1 {
                return Err(EvalError::new(format!(
                    "zero-or-one() requires a sequence of at most one item, but got {} items",
                    items.len()
                )));
            }
            Ok(Value::Sequence(items))
        }
        "one-or-more" => {
            let items = items_of(name, args, 0, context.version)?;
            if items.is_empty() {
                return Err(EvalError::new(
                    "one-or-more() requires a sequence of at least one item, but got 0",
                ));
            }
            Ok(Value::Sequence(items))
        }
        "exactly-one" => {
            let items = items_of(name, args, 0, context.version)?;
            if items.len() != 1 {
                return Err(EvalError::new(format!(
                    "exactly-one() requires a sequence of exactly one item, but got {} items",
                    items.len()
                )));
            }
            Ok(Value::Sequence(items))
        }

        // Atomizes: a node becomes its typed value, everything else passes
        // through. This crate does no schema-aware processing, so a node's
        // typed value is always untyped atomic — which, like every untyped
        // value elsewhere in this engine (see the divergences table in
        // spec/xpath2/), is represented as a plain string.
        "data" => {
            let items = items_of(name, args, 0, context.version)?;
            Ok(Value::Sequence(
                items
                    .iter()
                    .map(|item| match item {
                        Item::Node(_) => Item::String(item.to_xpath_string(document)),
                        _ => item.clone(),
                    })
                    .collect(),
            ))
        }

        // Structural equality: same length, and each pair of items
        // deep-equal — never an error, unlike `eq`, because mismatched
        // types or counts are simply not equal rather than a type error.
        "deep-equal" => deep_equal_call(name, args, context),

        _ => Err(EvalError::new(format!("unknown function {name}()"))),
    }
}

/// `deep-equal($sequence, $sequence)`, split out to keep `call_v2_rest`
/// short.
fn deep_equal_call(
    name: &str,
    args: &[Value],
    context: &EvalContext<'_>,
) -> Result<Value, EvalError> {
    let a = items_of(name, args, 0, context.version)?;
    let b = items_of(name, args, 1, context.version)?;
    Ok(Value::Boolean(
        a.len() == b.len()
            && a.iter()
                .zip(b.iter())
                .all(|(x, y)| deep_equal_item(x, y, context.document)),
    ))
}

/// Whether two items are deep-equal, per `fn:deep-equal`.
///
/// Unlike `eq`, mismatched atomic types compare unequal rather than erroring
/// — that is the whole difference between the two functions — and `NaN`
/// deep-equals `NaN`, also unlike `eq`. A node compares structurally via
/// [`deep_equal_node`], never against an atomic value.
fn deep_equal_item(a: &Item, b: &Item, document: &Document) -> bool {
    match (a, b) {
        (Item::Node(x), Item::Node(y)) => deep_equal_node(*x, *y, document),
        (Item::String(x), Item::String(y)) => x == y,
        (Item::Number(x, _), Item::Number(y, _)) => (x.is_nan() && y.is_nan()) || x == y,
        (Item::Boolean(x), Item::Boolean(y)) => x == y,
        (Item::Temporal(x), Item::Temporal(y)) => x.kind() == y.kind() && x == y,
        (Item::Duration(x), Item::Duration(y)) => x == y,
        _ => false,
    }
}

/// Whether two nodes are deep-equal: same kind, and then recursively —
/// same expanded name where the kind has one, the same attribute set
/// (compared as a set, not in document order — attribute order is not
/// significant in XML), and the same children in the same order.
///
/// This crate does no schema-aware processing, so there is no typed value
/// to compare beyond the string value every kind already carries.
fn deep_equal_node(a: NodeId, b: NodeId, document: &Document) -> bool {
    let kind = document.kind(a);
    if kind != document.kind(b) {
        return false;
    }

    let names_match = || match (document.name(a), document.name(b)) {
        (Some(x), Some(y)) => x.matches(y),
        (None, None) => true,
        _ => false,
    };

    match kind {
        NodeKind::Element => {
            if !names_match() {
                return false;
            }
            let attrs_of = |id: NodeId| -> Vec<(&QName, String)> {
                document
                    .attributes(id)
                    .iter()
                    .map(|&attr| (document.name(attr).expect("attributes are named"), document.string_value(attr)))
                    .collect()
            };
            let (attrs_a, attrs_b) = (attrs_of(a), attrs_of(b));
            if attrs_a.len() != attrs_b.len() {
                return false;
            }
            if !attrs_a.iter().all(|(name_a, value_a)| {
                attrs_b
                    .iter()
                    .any(|(name_b, value_b)| name_a.matches(name_b) && value_a == value_b)
            }) {
                return false;
            }
            let (children_a, children_b) = (document.children(a), document.children(b));
            children_a.len() == children_b.len()
                && children_a
                    .iter()
                    .zip(children_b.iter())
                    .all(|(&x, &y)| deep_equal_node(x, y, document))
        }
        NodeKind::Root => {
            let (children_a, children_b) = (document.children(a), document.children(b));
            children_a.len() == children_b.len()
                && children_a
                    .iter()
                    .zip(children_b.iter())
                    .all(|(&x, &y)| deep_equal_node(x, y, document))
        }
        NodeKind::Text | NodeKind::Comment => document.string_value(a) == document.string_value(b),
        NodeKind::Attribute | NodeKind::Namespace | NodeKind::ProcessingInstruction => {
            names_match() && document.string_value(a) == document.string_value(b)
        }
    }
}

/// `subsequence($sequence, $start)` and `subsequence($sequence, $start,
/// $length)`.
///
/// Both position arguments are rounded with `fn:round`'s own rule
/// (`round_half_up`) before use, exactly as the F&O definition specifies, so
/// `subsequence($s, 1.5)` starts at position 2. Comparing the unrounded
/// arithmetic directly against each item's plain `f64` position — rather
/// than building an explicit range — gets the edge cases right for free: a
/// `NaN` start or length excludes every item, because every comparison
/// against `NaN` is false, and a `-INF` start includes everything from
/// position 1, because every finite position is greater.
fn subsequence(
    name: &str,
    args: &[Value],
    context: &EvalContext<'_>,
) -> Result<Vec<Item>, EvalError> {
    let document = context.document;
    let items = items_of(name, args, 0, context.version)?;
    let start = round_half_up(args[1].to_number(document));
    let end = match args.get(2) {
        Some(length) => start + round_half_up(length.to_number(document)),
        None => f64::INFINITY,
    };
    Ok(items
        .into_iter()
        .enumerate()
        .filter(|(index, _)| {
            #[allow(clippy::cast_precision_loss)]
            let position = (*index + 1) as f64;
            position >= start && position < end
        })
        .map(|(_, item)| item)
        .collect())
}

/// Converts a count to `f64` for XPath, which has only one numeric type.
///
/// A document large enough to lose precision here would need more than 2^53
/// nodes, which is far beyond what fits in memory.
#[allow(clippy::cast_precision_loss)]
fn as_f64(value: usize) -> f64 {
    value as f64
}

/// Wraps a computed number as `xs:double` — every function result is one,
/// never a more specific tracked type. See [`NumericType`].
fn double(value: f64) -> Value {
    Value::Number(value, NumericType::Double)
}

/// The items of an argument that may be a node-set or an XPath 2.0 sequence.
///
/// Under XPath 2.0 every value *is* a sequence, so a scalar counts as a
/// one-item one and `exists(1)` is true. Under XPath 1.0 a sequence is
/// unreachable and a scalar is an error, exactly as the node-set accessor
/// this replaced behaved — so the 1.0 functions are unaffected.
fn items_of(
    name: &str,
    args: &[Value],
    index: usize,
    version: XPathVersion,
) -> Result<Vec<Item>, EvalError> {
    match args.get(index) {
        Some(Value::NodeSet(nodes)) => Ok(nodes.iter().copied().map(Item::Node).collect()),
        Some(Value::Sequence(items)) => Ok(items.clone()),
        Some(other) if version.is_v2() => Ok(match other {
            Value::String(text) => vec![Item::String(text.clone())],
            // Preserves the tag: an untagged scalar argument keeps whatever
            // numeric type it already carried.
            Value::Number(number, ty) => vec![Item::Number(*number, *ty)],
            Value::Boolean(boolean) => vec![Item::Boolean(*boolean)],
            Value::NodeSet(_) | Value::Sequence(_) => unreachable!("matched above"),
        }),
        _ => Err(EvalError::new(format!(
            "{name}() requires a node-set argument"
        ))),
    }
}

/// The node an optional-node-set function operates on: the first node of the
/// argument, or the context node when there is no argument.
fn node_argument(
    name: &str,
    args: &[Value],
    context: &EvalContext<'_>,
) -> Result<Option<NodeId>, EvalError> {
    match args.first() {
        None => Ok(Some(context.node)),
        Some(Value::NodeSet(nodes)) => Ok(nodes.first().copied()),
        Some(other) => Err(EvalError::new(format!(
            "{name}() requires a node-set argument, but was given a {}",
            other.type_name()
        ))),
    }
}

fn string_argument(args: &[Value], context: &EvalContext<'_>) -> String {
    match args.first() {
        Some(value) => value.to_xpath_string(context.document),
        None => context.document.string_value(context.node),
    }
}

fn two_strings(args: &[Value], document: &Document) -> (String, String) {
    (
        args[0].to_xpath_string(document),
        args[1].to_xpath_string(document),
    )
}

/// `current-date()` and its companions.
///
/// The instant comes from the run, not from the clock, so every call in a
/// validation agrees — which XPath 2.0 requires. With no instant supplied the
/// function is an error rather than an arbitrary time, so a caller evaluating
/// XPath directly cannot get a silently non-reproducible answer.
fn clock(kind: TemporalKind, context: &EvalContext<'_>) -> Result<Value, EvalError> {
    let Some(seconds) = context.current_time else {
        return Err(EvalError::new(
            "current-date() and its companions need the run's instant, which \
             the validator supplies and a direct call to evaluate() does not; \
             see EvalContext::with_current_time",
        ));
    };
    Ok(Value::Sequence(vec![Item::Temporal(from_unix_seconds(
        kind, seconds,
    ))]))
}

/// `xs:date()`, `xs:dateTime()`, `xs:time()`.
fn cast_temporal(
    args: &[Value],
    kind: TemporalKind,
    document: &Document,
) -> Result<Value, EvalError> {
    // An argument that is already this type passes through unchanged.
    if let Some([Item::Temporal(temporal)]) = args[0].as_sequence() {
        if temporal.kind() == kind {
            return Ok(args[0].clone());
        }
    }
    let text = args[0].to_xpath_string(document);
    let parsed = Temporal::parse(&text, kind).map_err(EvalError::new)?;
    Ok(Value::Sequence(vec![Item::Temporal(parsed)]))
}

/// `xs:dayTimeDuration()` and `xs:yearMonthDuration()`.
fn cast_duration(
    args: &[Value],
    kind: DurationKind,
    document: &Document,
) -> Result<Value, EvalError> {
    if let Some([Item::Duration(duration)]) = args[0].as_sequence() {
        if duration.kind() == kind {
            return Ok(args[0].clone());
        }
    }
    let text = args[0].to_xpath_string(document);
    let parsed = Duration::parse(&text, kind).map_err(EvalError::new)?;
    Ok(Value::Sequence(vec![Item::Duration(parsed)]))
}

/// The `*-from-duration` accessors.
///
/// XPath 2.0 defines each as the component it would occupy in the normalised
/// lexical form, so the days of `P1DT36H` are two, not one.
fn duration_component(
    name: &str,
    args: &[Value],
    document: &Document,
) -> Result<Value, EvalError> {
    let component = name
        .strip_suffix("-from-duration")
        .ok_or_else(|| EvalError::new(format!("unknown function {name}()")))?;

    // Years and months belong to one subtype, the rest to the other.
    let kind = match component {
        "years" | "months" => DurationKind::YearMonth,
        _ => DurationKind::DayTime,
    };
    let duration = match args[0].as_sequence().and_then(|items| match items {
        [Item::Duration(duration)] => Some(*duration),
        _ => None,
    }) {
        Some(duration) => duration,
        None => Duration::parse(&args[0].to_xpath_string(document), kind)
            .map_err(EvalError::new)?,
    };

    if duration.kind() != kind {
        return Err(EvalError::new(format!(
            "{name}() takes a {}, not a {}",
            kind.as_str(),
            duration.kind().as_str()
        )));
    }

    // Each component is signed the same way as the duration as a whole.
    let sign = if duration.is_negative() { -1.0 } else { 1.0 };
    let value = match kind {
        DurationKind::YearMonth => {
            let months = duration.to_months().abs();
            match component {
                "years" => as_f64_signed(months / 12),
                _ => as_f64_signed(months % 12),
            }
        }
        DurationKind::DayTime => {
            let total = duration.to_seconds().abs();
            match component {
                "days" => (total / 86_400.0).floor(),
                "hours" => ((total % 86_400.0) / 3_600.0).floor(),
                "minutes" => ((total % 3_600.0) / 60.0).floor(),
                _ => total % 60.0,
            }
        }
    };
    Ok(double(value * sign))
}

/// `timezone-from-date()` and its companions.
///
/// Returns the value's **own** timezone as a dayTimeDuration, or the empty
/// sequence when it carries none — not the implicit timezone, which is a
/// property of the evaluation rather than of the value.
fn timezone_of(name: &str, args: &[Value], document: &Document) -> Result<Value, EvalError> {
    let type_name = name
        .strip_prefix("timezone-from-")
        .ok_or_else(|| EvalError::new(format!("unknown function {name}()")))?;
    let kind = match type_name {
        "date" => TemporalKind::Date,
        "dateTime" => TemporalKind::DateTime,
        "time" => TemporalKind::Time,
        other => return Err(EvalError::new(format!("unknown type {other:?}"))),
    };

    let temporal = match args[0].as_sequence().and_then(|items| match items {
        [Item::Temporal(temporal)] => Some(*temporal),
        _ => None,
    }) {
        Some(temporal) => temporal,
        None => Temporal::parse(&args[0].to_xpath_string(document), kind)
            .map_err(EvalError::new)?,
    };

    Ok(match temporal.offset_minutes() {
        None => Value::Sequence(Vec::new()),
        Some(minutes) => Value::Sequence(vec![Item::Duration(Duration::from_seconds(
            f64::from(minutes) * 60.0,
        ))]),
    })
}

/// The `*-from-date`, `*-from-dateTime` and `*-from-time` accessors.
fn component_of(
    name: &str,
    args: &[Value],
    document: &Document,
) -> Result<Value, EvalError> {
    let (component, type_name) = name
        .split_once("-from-")
        .ok_or_else(|| EvalError::new(format!("unknown function {name}()")))?;
    let kind = match type_name {
        "date" => TemporalKind::Date,
        "dateTime" => TemporalKind::DateTime,
        "time" => TemporalKind::Time,
        other => return Err(EvalError::new(format!("unknown component type {other:?}"))),
    };

    // The argument may already be typed, or be an untyped value to cast.
    let temporal = match args[0].as_sequence().and_then(|items| match items {
        [Item::Temporal(temporal)] => Some(*temporal),
        _ => None,
    }) {
        Some(temporal) => temporal,
        None => Temporal::parse(&args[0].to_xpath_string(document), kind)
            .map_err(EvalError::new)?,
    };

    let value = match component {
        "year" => as_f64_signed(temporal.year()),
        "month" => f64::from(temporal.month()),
        "day" => f64::from(temporal.day()),
        "hours" => f64::from(temporal.hour()),
        "minutes" => f64::from(temporal.minute()),
        "seconds" => temporal.second(),
        other => {
            return Err(EvalError::new(format!(
                "{other:?} is not a component of {}",
                kind.as_str()
            )))
        }
    };
    Ok(double(value))
}

/// Converts a year to `f64`; years are far below the precision limit.
#[allow(clippy::cast_precision_loss)]
fn as_f64_signed(value: i64) -> f64 {
    value as f64
}

/// The numeric values of a node-set argument, for `min`, `max`, and `avg`.
fn numbers_of(args: &[Value], document: &Document) -> Vec<f64> {
    match &args[0] {
        Value::NodeSet(nodes) => nodes
            .iter()
            .map(|&node| parse_number(&document.string_value(node)))
            .collect(),
        Value::Sequence(items) => items.iter().map(|item| item.to_number(document)).collect(),
        // A single scalar is a one-item sequence in XPath 2.0 terms.
        other => vec![other.to_number(document)],
    }
}

/// `min()` and `max()`, which differ only in the comparison.
fn extreme(args: &[Value], document: &Document, pick: fn(f64, f64) -> f64) -> f64 {
    let numbers = numbers_of(args, document);
    // A NaN anywhere makes the result NaN, matching XPath 2.0, where a
    // non-numeric value makes the whole call a type error and so never
    // yields a usable answer either.
    if numbers.is_empty() || numbers.iter().any(|n| n.is_nan()) {
        return f64::NAN;
    }
    numbers.into_iter().fold(f64::NAN, |accumulated, next| {
        if accumulated.is_nan() {
            next
        } else {
            pick(accumulated, next)
        }
    })
}

/// Compiles a regular expression, honouring XPath 2.0's flag argument.
///
/// The `regex` crate's syntax is close to the XML Schema regular expressions
/// XPath 2.0 specifies, but not identical; `spec/xpath2/` lists the
/// differences. A pattern that does not compile is an error naming the
/// pattern, never a silently false test.
fn compile_regex(
    pattern: &str,
    flags: Option<&Value>,
    document: &Document,
) -> Result<regex::Regex, EvalError> {
    let flags = flags
        .map(|value| value.to_xpath_string(document))
        .unwrap_or_default();
    build_regex(pattern, &flags).map_err(EvalError::new)
}

/// Builds a regular expression from an XPath 2.0 pattern and flag string.
fn build_regex(pattern: &str, flags: &str) -> Result<regex::Regex, String> {
    let mut builder = regex::RegexBuilder::new(pattern);
    for flag in flags.chars() {
        match flag {
            'i' => {
                builder.case_insensitive(true);
            }
            'm' => {
                builder.multi_line(true);
            }
            's' => {
                builder.dot_matches_new_line(true);
            }
            'x' => {
                builder.ignore_whitespace(true);
            }
            other => {
                return Err(format!(
                    "unknown regular expression flag {other:?}; XPath 2.0 defines \
                     i, m, s and x"
                ))
            }
        }
    }

    builder
        .build()
        .map_err(|error| format!("the regular expression {pattern:?} did not compile: {error}"))
}

/// Rewrites XPath 2.0's `$1` group references into the `regex` crate's form.
///
/// The two agree on `$1`, but XPath escapes a literal dollar as `\$` while
/// the crate uses `$$`.
fn translate_replacement(replacement: &str) -> String {
    replacement.replace("\\$", "$$$$")
}

/// `document()`: the root nodes of external documents, by URI.
///
/// The argument is converted the way XSLT converts it: a node-set yields one
/// URI per node, from each node's string value, so `document(ref/@href)`
/// loads every referenced document at once. Anything else yields a single URI
/// from its string value.
///
/// A URI that is not in the registry contributes no node and is recorded as a
/// miss, which is how the validator discovers what to load for the next pass.
/// A caller evaluating XPath directly, with no registry, gets an error —
/// silently returning an empty node-set would turn a broken lookup into a
/// passing assertion.
fn document_function(args: &[Value], context: &EvalContext<'_>) -> Result<Value, EvalError> {
    let Some(registry) = context.documents else {
        return Err(EvalError::new(
            "document() needs a document registry, which the validator supplies \
             and a direct call to evaluate() does not; see EvalContext::with_documents",
        ));
    };

    let uris: Vec<String> = match &args[0] {
        Value::NodeSet(nodes) => nodes
            .iter()
            .map(|&node| context.document.string_value(node))
            .collect(),
        other => vec![other.to_xpath_string(context.document)],
    };

    // XSLT 1.0 section 12.1: with a second argument, a relative URI resolves
    // against the base URI of the *first node* of that node-set, rather than
    // against the instance. That is how a document loaded by an earlier
    // `document()` call can name its own neighbours.
    let base: Option<String> = match args.get(1) {
        None => None,
        Some(Value::NodeSet(nodes)) => {
            let first = nodes
                .iter()
                .copied()
                .min_by_key(|&node| context.document.order(node));
            match first {
                // An empty node-set names no base, so there is nothing to
                // resolve and nothing to load.
                //
                // This must not be an error. Loading runs in passes, and on
                // the first pass every `document()` call returns empty — so
                // `document(x, document(y))` has an empty second argument
                // until the pass that loads `y` has run. Erroring here would
                // abort the validation before the retry that makes it work.
                None => return Ok(Value::NodeSet(Vec::new())),
                Some(node) => {
                    let root = context.document.root_of(node);
                    registry
                        .origin_of(root)
                        .map(ToString::to_string)
                        .or_else(|| context.document.base_uri().map(ToString::to_string))
                }
            }
        }
        Some(other) => {
            return Err(EvalError::new(format!(
                "document(): the second argument must be a node-set, not {}",
                other.type_name()
            )))
        }
    };

    let mut roots: Vec<NodeId> = uris
        .iter()
        .filter_map(|uri| registry.lookup(uri, base.as_deref()))
        .collect();
    // A node-set is sorted and deduplicated; two references to one URI are
    // one node.
    roots.sort_unstable_by_key(|&root| context.document.order(root));
    roots.dedup();
    Ok(Value::NodeSet(roots))
}

/// `key(name, value)`: the nodes a named index holds under a value.
///
/// A node-set second argument looks up **each** of its string values, which
/// is the existential behaviour the rest of XPath uses — so
/// `key('parts', line/@ref)` finds every referenced part at once.
fn key_function(args: &[Value], context: &EvalContext<'_>) -> Result<Value, EvalError> {
    let Some(keys) = context.keys else {
        return Err(EvalError::new(
            "key() needs the run's key indexes, which the validator supplies and \
             a direct call to evaluate() does not; see EvalContext::with_keys",
        ));
    };

    let name = args[0].to_xpath_string(context.document);
    if !keys.is_declared(&name) {
        // A missing declaration is a mistake in the schema, not an empty
        // result: returning nothing would make the assertion quietly pass.
        return Err(EvalError::new(format!(
            "no key named {name:?} is declared; add <key name=\"{name}\" \
             match=\"…\" use=\"…\"/> to the schema"
        )));
    }

    let wanted: Vec<String> = match &args[1] {
        Value::NodeSet(nodes) => nodes
            .iter()
            .map(|&node| context.document.string_value(node))
            .collect(),
        other => vec![other.to_xpath_string(context.document)],
    };

    let mut found: Vec<NodeId> = wanted
        .iter()
        .flat_map(|value| keys.lookup(&name, value))
        .collect();
    found.sort_unstable_by_key(|&node| context.document.order(node));
    found.dedup();
    Ok(Value::NodeSet(found))
}

/// `id()` without a DTD.
///
/// Nothing tells the crate which attributes have type ID, because DTDs are not
/// processed, so `xml:id` and any attribute named `id` are treated as
/// identifiers. Every DTD-less processor does something equivalent.
fn id_function(args: &[Value], context: &EvalContext<'_>) -> Vec<NodeId> {
    let document = context.document;
    let wanted: Vec<String> = match args.first() {
        Some(Value::NodeSet(nodes)) => nodes
            .iter()
            .flat_map(|&n| {
                document
                    .string_value(n)
                    .split_whitespace()
                    .map(ToString::to_string)
                    .collect::<Vec<_>>()
            })
            .collect(),
        Some(value) => value
            .to_xpath_string(document)
            .split_whitespace()
            .map(ToString::to_string)
            .collect(),
        None => Vec::new(),
    };

    let mut found = Vec::new();
    // Scoped to the document the context node belongs to: `id()` must not
    // reach into a document merged in by `document()`.
    for node in document.descendants_or_self(document.root_of(context.node)) {
        if document.kind(node) != NodeKind::Element {
            continue;
        }
        for &attribute in document.attributes(node) {
            let Some(name) = document.name(attribute) else {
                continue;
            };
            // With no DTD there is no attribute typed ID, so `id` and
            // `xml:id` are what every DTD-less processor treats as one.
            let is_id = name.local == "id"
                && matches!(name.uri.as_deref(), None | Some(crate::xml::XML_NAMESPACE));
            if is_id && wanted.iter().any(|w| w == document.value(attribute)) {
                found.push(node);
                break;
            }
        }
    }
    found
}

/// `substring()`, with XPath 1.0's one-based, rounding, NaN-tolerant indexing.
///
/// The specification defines it in terms of `round()` and inequalities rather
/// than integer slicing, which is why `substring('12345', 1.5, 2.6)` is `'234'`
/// and why a NaN start yields the empty string instead of an error.
fn substring(args: &[Value], document: &Document) -> String {
    let text: Vec<char> = args[0].to_xpath_string(document).chars().collect();
    let start = round_half_up(args[1].to_number(document));
    let end = match args.get(2) {
        Some(length) => {
            let length = round_half_up(length.to_number(document));
            if length.is_nan() {
                return String::new();
            }
            start + length
        }
        None => f64::INFINITY,
    };
    if start.is_nan() {
        return String::new();
    }

    let mut out = String::new();
    for (index, c) in text.iter().enumerate() {
        // XPath positions are one-based.
        let position = as_f64(index + 1);
        if position >= start && position < end {
            out.push(*c);
        }
    }
    out
}

/// XPath's `round()`: halfway cases go towards positive infinity, so
/// `round(-0.5)` is `0`, not `-1`.
fn round_half_up(value: f64) -> f64 {
    if value.is_nan() || value.is_infinite() {
        return value;
    }
    (value + 0.5).floor()
}

/// Collapses internal whitespace runs and trims the ends.
fn normalize_space(input: &str) -> String {
    input.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// `translate()`: character-wise mapping, with characters beyond the end of
/// the replacement string removed rather than replaced.
fn translate(text: &str, from: &str, to: &str) -> String {
    let from: Vec<char> = from.chars().collect();
    let to: Vec<char> = to.chars().collect();
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        match from.iter().position(|&f| f == c) {
            // First occurrence wins, and a character past the end of `to` is
            // deleted.
            Some(index) => {
                if let Some(&replacement) = to.get(index) {
                    out.push(replacement);
                }
            }
            None => out.push(c),
        }
    }
    out
}

/// `lang()`: walks up for the nearest `xml:lang`, then matches the language
/// tag case-insensitively, allowing a suffix after a hyphen.
fn lang(wanted: &str, document: &Document, node: NodeId) -> bool {
    let mut current = Some(node);
    while let Some(id) = current {
        for &attribute in document.attributes(id) {
            if let Some(name) = document.name(attribute) {
                if name.local == "lang" && name.uri.as_deref() == Some(crate::xml::XML_NAMESPACE) {
                    let actual = document.value(attribute).to_lowercase();
                    let wanted = wanted.to_lowercase();
                    return actual == wanted
                        || actual.strip_prefix(&wanted).is_some_and(|r| r.starts_with('-'));
                }
            }
        }
        current = document.parent(id);
    }
    false
}

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

    #[test]
    fn arity_is_checked() {
        assert!(check_function("contains", 2, XPathVersion::V1).is_ok());
        assert!(check_function("contains", 1, XPathVersion::V1).is_err());
        assert!(check_function("concat", 5, XPathVersion::V1).is_ok());
        assert!(check_function("concat", 1, XPathVersion::V1).is_err());
        assert!(check_function("true", 1, XPathVersion::V1).is_err());
        assert!(check_function("string", 0, XPathVersion::V1).is_ok());
        assert!(check_function("string", 1, XPathVersion::V1).is_ok());
        assert!(check_function("string", 2, XPathVersion::V1).is_err());
    }

    #[test]
    fn xpath_two_functions_are_refused_under_a_one_point_zero_binding() {
        let message = check_function("matches", 2, XPathVersion::V1).unwrap_err();
        assert!(message.contains("XPath 2.0"), "{message}");
        assert!(message.contains("xslt2"), "{message}");
    }

    #[test]
    fn xpath_two_functions_are_accepted_under_a_two_point_zero_binding() {
        assert!(check_function("matches", 2, XPathVersion::V2).is_ok());
        assert!(check_function("matches", 3, XPathVersion::V2).is_ok());
        assert!(check_function("matches", 1, XPathVersion::V2).is_err());
        assert!(check_function("string-join", 2, XPathVersion::V2).is_ok());
    }

    #[test]
    fn unimplemented_two_point_zero_functions_say_what_they_need() {
        let dates = check_function("adjust-date-to-timezone", 2, XPathVersion::V2).unwrap_err();
        assert!(dates.contains("date and time"), "{dates}");

        // Looks like a sequence function, but needs function items instead
        // (see the comment on `V2_FUNCTIONS_NOT_IMPLEMENTED`).
        let for_each = check_function("for-each", 2, XPathVersion::V2).unwrap_err();
        assert!(for_each.contains("does not implement"), "{for_each}");
    }

    #[test]
    fn the_date_functions_are_available_now_that_dates_exist() {
        for (name, arity) in [
            ("current-date", 0),
            ("current-dateTime", 0),
            ("year-from-date", 1),
            ("hours-from-time", 1),
            ("xs:date", 1),
        ] {
            assert!(
                check_function(name, arity, XPathVersion::V2).is_ok(),
                "{name}() should be available"
            );
        }
        // Still an XPath 2.0 function, so an XPath 1.0 binding refuses it.
        assert!(check_function("current-date", 0, XPathVersion::V1).is_err());
    }

    #[test]
    fn the_duration_functions_are_available_now_that_durations_exist() {
        for (name, arity) in [
            ("xs:dayTimeDuration", 1),
            ("xs:yearMonthDuration", 1),
            ("days-from-duration", 1),
            ("months-from-duration", 1),
        ] {
            assert!(
                check_function(name, arity, XPathVersion::V2).is_ok(),
                "{name}() should be available"
            );
        }
        assert!(check_function("xs:dayTimeDuration", 1, XPathVersion::V1).is_err());
    }

    #[test]
    fn the_sequence_functions_are_available_now_that_sequences_exist() {
        // These moved out of the "needs sequences" list in phase 2a.
        for (name, arity) in [("tokenize", 2), ("distinct-values", 1), ("index-of", 2)] {
            assert!(
                check_function(name, arity, XPathVersion::V2).is_ok(),
                "{name}() should be available"
            );
        }
        // These moved out of it in phase 5.
        for (name, arity) in [
            ("reverse", 1),
            ("subsequence", 2),
            ("insert-before", 3),
            ("remove", 2),
            ("unordered", 1),
        ] {
            assert!(
                check_function(name, arity, XPathVersion::V2).is_ok(),
                "{name}() should be available"
            );
        }
    }

    #[test]
    fn the_cardinality_and_atomization_functions_are_available() {
        for name in ["zero-or-one", "one-or-more", "exactly-one", "data"] {
            assert!(
                check_function(name, 1, XPathVersion::V2).is_ok(),
                "{name}() should be available"
            );
        }
    }

    #[test]
    fn deep_equal_is_available() {
        assert!(check_function("deep-equal", 2, XPathVersion::V2).is_ok());
        assert!(check_function("deep-equal", 1, XPathVersion::V2).is_err());
        assert!(check_function("deep-equal", 2, XPathVersion::V1).is_err());
    }

    #[test]
    fn the_two_point_zero_library_has_the_documented_names() {
        let names = function_names_v2();
        // Growing this number is expected; the point of the check is that the
        // list and the documentation move together, which
        // `tests/docs.rs::the_xpath_two_function_list_in_the_spec_matches_the_engine`
        // enforces.
        assert_eq!(names.len(), 55, "{names:?}");
        for expected in [
            "matches",
            "replace",
            "abs",
            "exists",
            "string-join",
            "tokenize",
            "distinct-values",
            "index-of",
            "reverse",
            "deep-equal",
            "zero-or-one",
            "one-or-more",
            "exactly-one",
            "data",
            "subsequence",
            "insert-before",
            "remove",
            "unordered",
            "current-date",
            "year-from-date",
            "xs:date",
            "xs:dayTimeDuration",
            "xs:yearMonthDuration",
            "days-from-duration",
            "years-from-duration",
            "timezone-from-date",
            "implicit-timezone",
        ] {
            assert!(names.contains(&expected), "{expected} is missing");
        }
    }

    #[test]
    fn unknown_functions_are_rejected() {
        assert!(check_function("nonsense", 0, XPathVersion::V1).is_err());
    }

    #[test]
    fn library_has_every_expected_name() {
        // The 27 core XPath 1.0 functions, plus the three from the XSLT
        // library that the `xslt` query binding makes available.
        let names = function_names();
        assert_eq!(names.len(), 30, "{names:?}");
        for from_xslt in ["current", "document", "key"] {
            assert!(names.contains(&from_xslt), "{from_xslt}() is missing");
        }
    }

    #[test]
    fn document_without_a_registry_is_an_error() {
        // Returning an empty node-set instead would turn a misconfigured
        // lookup into a quietly passing assertion.
        assert!(check_function("document", 1, XPathVersion::V1).is_ok());
        // XSLT 1.0 section 12.1 gives `document()` a second, optional
        // argument: the node-set whose first node supplies the base URI.
        assert!(check_function("document", 2, XPathVersion::V1).is_ok());
        assert!(check_function("document", 0, XPathVersion::V1).is_err());
        assert!(check_function("document", 3, XPathVersion::V1).is_err());
    }

    #[test]
    fn round_sends_halves_upwards() {
        assert_eq!(round_half_up(0.5), 1.0);
        assert_eq!(round_half_up(-0.5), 0.0);
        assert_eq!(round_half_up(1.5), 2.0);
        assert_eq!(round_half_up(-1.5), -1.0);
    }

    #[test]
    fn normalize_space_collapses_runs() {
        assert_eq!(normalize_space("  a   b \n c "), "a b c");
        assert_eq!(normalize_space("   "), "");
    }

    #[test]
    fn translate_deletes_unmapped_characters() {
        assert_eq!(translate("bar", "abc", "ABC"), "BAr");
        assert_eq!(translate("--aaa--", "abc-", "ABC"), "AAA");
        assert_eq!(translate("abc", "aa", "XY"), "Xbc");
    }

    #[test]
    fn substring_follows_the_specification_not_integer_slicing() {
        assert_eq!(round_half_up(1.5), 2.0);
        assert_eq!(normalize_space(" a "), "a");
    }
}