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
//! Integration tests for the XPath 2.0 phase-1 subset.
//!
//! Two properties matter here, and they pull in opposite directions.
//!
//! The additions must **work** under an XPath 2.0 query binding: regular
//! expressions, conditionals, and the string and numeric functions that
//! schemas declaring `xslt2` actually reach for.
//!
//! And everything outside the subset must be a **hard error naming the
//! construct** — never a wrong answer. That is what makes a partial
//! implementation of a different language honest rather than dangerous. See
//! `spec/xpath2/`.

use assertables::*;
use schematron::{Document, Schema};

/// Wraps a body in a schema with the given query binding.
fn schema_with(binding: &str, body: &str) -> String {
    format!(
        r#"<schema xmlns="http://purl.oclc.org/dsdl/schematron" queryBinding="{binding}">{body}</schema>"#
    )
}

/// Compiles an `xslt2` schema with one assertion, and validates `document`.
fn check(test: &str, document: &str) -> bool {
    let source = schema_with(
        "xslt2",
        &format!(r#"<pattern><rule context="a"><assert test="{test}">failed</assert></rule></pattern>"#),
    );
    let schema = Schema::from_str(&source)
        .unwrap_or_else(|e| panic!("schema with test {test:?} should compile: {e}"));
    let document = Document::from_str(document).expect("document should parse");
    schema.validate(&document).expect("validation should run").is_valid()
}

/// The compile error for a test under a binding, if it does not compile.
fn compile_error(binding: &str, test: &str) -> String {
    let source = schema_with(
        binding,
        &format!(r#"<pattern><rule context="a"><assert test="{test}">m</assert></rule></pattern>"#),
    );
    Schema::from_str(&source).map_or_else(
        |error| error.to_string(),
        |_| panic!("test {test:?} unexpectedly compiled under {binding}"),
    )
}

#[test]
fn matches_tests_a_regular_expression() {
    assert!(check("matches(@x, '^[0-9]+$')", r#"<a x="123"/>"#));
    assert!(!check("matches(@x, '^[0-9]+$')", r#"<a x="12a"/>"#));
    // Unanchored by default, as XPath 2.0 specifies.
    assert!(check("matches(@x, '[0-9]')", r#"<a x="ab1cd"/>"#));
}

#[test]
fn matches_honours_the_flags_argument() {
    assert!(!check("matches(@x, '^abc$')", r#"<a x="ABC"/>"#));
    assert!(check("matches(@x, '^abc$', 'i')", r#"<a x="ABC"/>"#));
}

#[test]
fn replace_rewrites_with_group_references() {
    assert!(check(
        "replace(@x, '([0-9]+)-([0-9]+)', '$2-$1') = '34-12'",
        r#"<a x="12-34"/>"#
    ));
}

#[test]
fn a_conditional_chooses_a_branch() {
    let test = "if (@type = 'credit') then number(@total) &lt; 0 else number(@total) &gt;= 0";
    assert!(check(test, r#"<a type="credit" total="-5"/>"#));
    assert!(!check(test, r#"<a type="credit" total="5"/>"#));
    assert!(check(test, r#"<a type="debit" total="5"/>"#));
    assert!(!check(test, r#"<a type="debit" total="-5"/>"#));
}

#[test]
fn a_conditional_evaluates_only_the_taken_branch() {
    // The untaken branch is a union of two numbers, which is a type error if
    // it is evaluated — and is not caught at compile time, because operand
    // types are not known until there is a document.
    assert!(check("if (true()) then true() else boolean(1 | 2)", "<a/>"));
    assert!(check("if (false()) then boolean(1 | 2) else true()", "<a/>"));
}

#[test]
fn string_functions() {
    assert!(check("upper-case(@x) = 'ABC'", r#"<a x="abc"/>"#));
    assert!(check("lower-case(@x) = 'abc'", r#"<a x="ABC"/>"#));
    assert!(check("ends-with(@x, '.pdf')", r#"<a x="doc.pdf"/>"#));
    assert!(!check("ends-with(@x, '.pdf')", r#"<a x="doc.txt"/>"#));
}

#[test]
fn string_join_concatenates_a_node_set_in_document_order() {
    assert!(check(
        "string-join(b, ',') = 'x,y,z'",
        "<a><b>x</b><b>y</b><b>z</b></a>"
    ));
}

#[test]
fn numeric_functions() {
    assert!(check("abs(number(@x)) = 5", r#"<a x="-5"/>"#));
    assert!(check("min(b) = 1", "<a><b>3</b><b>1</b><b>2</b></a>"));
    assert!(check("max(b) = 3", "<a><b>3</b><b>1</b><b>2</b></a>"));
    assert!(check("avg(b) = 2", "<a><b>3</b><b>1</b><b>2</b></a>"));
}

#[test]
fn exists_and_empty_are_opposites() {
    assert!(check("exists(b)", "<a><b/></a>"));
    assert!(!check("exists(b)", "<a/>"));
    assert!(check("empty(b)", "<a/>"));
    assert!(!check("empty(b)", "<a><b/></a>"));
}

#[test]
fn two_point_zero_functions_are_refused_under_a_one_point_zero_binding() {
    for binding in ["xslt", "xpath"] {
        let message = compile_error(binding, "matches(@x, 'y')");
        assert_contains!(message, "matches()");
        assert_contains!(message, "XPath 2.0");
        // The message must say what to do about it.
        assert_contains!(message, "xslt2");
    }
}

#[test]
fn a_conditional_is_refused_under_a_one_point_zero_binding() {
    let message = compile_error("xslt", "if (b) then 1 else 2");
    assert_contains!(message, "XPath 2.0 syntax");
    assert_contains!(message, "xslt2");
}

#[test]
fn a_conditional_requires_both_branches() {
    let message = compile_error("xslt2", "if (b) then 1");
    assert_contains!(message, "else");
}

#[test]
fn constructs_still_needing_phase_two_b_say_so() {
    // What no phase has added yet still names itself rather than
    // misbehaving. `for-each` looks like its neighbour `subsequence` (now
    // implemented, phase 5) but needs function items, an XPath 3.0 feature.
    for (test, expected) in [
        ("count(for-each(b, 1))", "does not implement"),
        ("trace(b, 'x')", "does not implement"),
        ("resolve-uri('a', 'b')", "does not implement"),
    ] {
        let message = compile_error("xslt2", test);
        assert_contains!(message, expected);
        assert_contains!(message, "spec/xpath2/");
    }
}

#[test]
fn constructs_still_needing_the_type_system_say_so() {
    // What the subset does not reach still names itself rather than
    // misbehaving.
    let message = compile_error("xslt2", "adjust-date-to-timezone(@d, @z)");
    assert_contains!(message, "date and time");
    assert_contains!(message, "spec/xpath2/");
}

#[test]
fn a_malformed_regular_expression_fails_when_the_schema_loads() {
    // Not part-way through validating somebody's document.
    let message = compile_error("xslt2", "matches(@x, '[unclosed')");
    assert_contains!(message, "did not compile");
    assert_contains!(message, "[unclosed");
}

#[test]
fn an_unknown_regular_expression_flag_fails_when_the_schema_loads() {
    let message = compile_error("xslt2", "matches(@x, 'y', 'q')");
    assert_contains!(message, "flag");
}

#[test]
fn a_computed_regular_expression_is_checked_at_evaluation_time() {
    // It cannot be checked earlier, so it must still be an error rather than
    // a silently false test.
    let source = schema_with(
        "xslt2",
        r#"<pattern><rule context="a"><assert test="matches('x', @pattern)">m</assert></rule></pattern>"#,
    );
    let schema = Schema::from_str(&source).expect("schema should compile");
    let document = Document::from_str(r#"<a pattern="[unclosed"/>"#).unwrap();

    let error = schema.validate(&document).unwrap_err();
    assert_contains!(error.to_string(), "did not compile");
}

#[test]
fn xpath_one_point_zero_still_works_under_a_two_point_zero_binding() {
    // The 2.0 binding adds to the language; it does not remove anything.
    assert!(check("count(b) = 2", "<a><b/><b/></a>"));
    assert!(check("b/@x = '1'", r#"<a><b x="1"/></a>"#));
    assert!(check("normalize-space(@x) = 'a b'", r#"<a x="  a   b "/>"#));
    assert!(check("substring(@x, 2, 3) = 'bcd'", r#"<a x="abcde"/>"#));
}

#[test]
fn bindings_above_two_point_zero_are_still_refused() {
    for binding in ["xslt3", "xpath3", "xpath31"] {
        let message = compile_error(binding, "true()");
        assert_contains!(message, "unsupported query binding");
    }
}

#[test]
fn the_documented_divergence_from_real_xpath_two_holds() {
    // spec/xpath2/ states that where XPath 2.0 raises a type error, this
    // crate produces NaN and the test is simply false. Asserting it here
    // means the documentation cannot drift away from the behaviour.
    assert!(!check("number(@x) + 1 &gt; 0", r#"<a x="not-a-number"/>"#));
    assert!(!check("'x' &gt; 0", "<a/>"));
}

// ---------------------------------------------------------------------------
// Phase 2a: the sequence type.
// ---------------------------------------------------------------------------

#[test]
fn a_sequence_can_be_constructed_and_counted() {
    assert!(check("count((1, 2, 3)) = 3", "<a/>"));
    assert!(check("count(()) = 0", "<a/>"));
    // Sequences do not nest: building one from others flattens them.
    assert!(check("count((1, (2, 3), 4)) = 4", "<a/>"));
}

#[test]
fn a_sequence_can_mix_nodes_and_atomic_values() {
    assert!(check("count((b, 'x', 1)) = 4", "<a><b/><b/></a>"));
}

#[test]
fn a_range_counts_up_and_is_empty_when_descending() {
    assert!(check("count(1 to 5) = 5", "<a/>"));
    assert!(check("count(5 to 1) = 0", "<a/>"));
    assert!(check("count(3 to 3) = 1", "<a/>"));
}

#[test]
fn an_absurd_range_is_an_error_rather_than_an_allocation() {
    let source = schema_with(
        "xslt2",
        r#"<pattern><rule context="a"><assert test="count(1 to 100000000) > 0">m</assert></rule></pattern>"#,
    );
    let schema = Schema::from_str(&source).expect("schema should compile");
    let document = Document::from_str("<a/>").unwrap();
    let error = schema.validate(&document).unwrap_err();
    assert_contains!(error.to_string(), "exceeds the limit");
}

#[test]
fn for_iterates_and_concatenates() {
    assert!(check("count(for $b in b return $b) = 3", "<a><b/><b/><b/></a>"));
    // The bound variable is a node, so a path can continue from it.
    assert!(check(
        "count(for $b in b return $b/c) = 2",
        "<a><b><c/></b><b><c/></b><b/></a>"
    ));
    // Each iteration may yield several items; the results concatenate.
    assert!(check("count(for $n in (1, 2) return (1 to 3)) = 6", "<a/>"));
}

#[test]
fn some_and_every_quantify_over_a_sequence() {
    let doc = r#"<a><b n="1"/><b n="2"/><b n="3"/></a>"#;
    assert!(check("some $b in b satisfies number($b/@n) = 2", doc));
    assert!(!check("some $b in b satisfies number($b/@n) = 9", doc));
    assert!(check("every $b in b satisfies number($b/@n) > 0", doc));
    assert!(!check("every $b in b satisfies number($b/@n) > 1", doc));
}

#[test]
fn every_is_true_for_an_empty_input_and_some_is_false() {
    // Vacuous truth, as XPath 2.0 specifies.
    assert!(check("every $b in nothing satisfies false()", "<a/>"));
    assert!(!check("some $b in nothing satisfies true()", "<a/>"));
}

#[test]
fn quantifiers_work_over_a_constructed_sequence() {
    assert!(check("some $n in (1 to 10) satisfies $n = 7", "<a/>"));
    assert!(check("every $n in (2, 4, 6) satisfies $n mod 2 = 0", "<a/>"));
}

#[test]
fn a_bound_variable_does_not_escape_its_expression() {
    // `$b` is bound only inside the quantified expression. Referencing it
    // outside is an unbound variable, and since no `let` binds that name the
    // schema does not even compile.
    let message = compile_error(
        "xslt2",
        "(every $b in b satisfies true()) and $b",
    );
    assert_contains!(message, "$b");
}

#[test]
fn a_variable_bound_by_a_quantifier_is_in_scope_inside_it() {
    // The other half: the binding must be visible where it should be, or the
    // compile-time check would reject every quantified expression.
    assert!(check("every $n in (1, 2) satisfies $n > 0", "<a/>"));
    assert!(check("count(for $n in (1, 2) return $n) = 2", "<a/>"));
    assert!(check("some $n in (1 to 3) satisfies $n = 2", "<a/>"));
}

#[test]
fn tokenize_splits_into_a_sequence() {
    assert!(check("count(tokenize(@x, ',')) = 3", r#"<a x="p,q,r"/>"#));
    assert!(check(
        "string-join(tokenize(@x, ',\\s*'), '-') = 'p-q-r'",
        r#"<a x="p, q,  r"/>"#
    ));
}

#[test]
fn distinct_values_removes_duplicates_keeping_order() {
    assert!(check(
        "string-join(distinct-values((1, 2, 1, 3, 2)), ',') = '1,2,3'",
        "<a/>"
    ));
    assert!(check("count(distinct-values(b)) = 2", "<a><b>x</b><b>y</b><b>x</b></a>"));
}

#[test]
fn index_of_reports_one_based_positions() {
    assert!(check("index-of(('a', 'b', 'c'), 'b') = 2", "<a/>"));
    assert!(check("count(index-of(('a', 'b', 'a'), 'a')) = 2", "<a/>"));
    assert!(check("count(index-of(('a', 'b'), 'z')) = 0", "<a/>"));
}

#[test]
fn reverse_reverses_a_sequence() {
    assert!(check("string-join(reverse((1, 2, 3)), ',') = '3,2,1'", "<a/>"));
    assert!(check("count(reverse(())) = 0", "<a/>"));
}

#[test]
fn unordered_returns_every_item_unchanged() {
    // The result order is implementation-defined; this crate's choice is to
    // leave it as-is, so the count and membership are what's guaranteed.
    assert!(check("count(unordered((3, 1, 2))) = 3", "<a/>"));
    assert!(check("string-join(unordered((3, 1, 2)), ',') = '3,1,2'", "<a/>"));
}

#[test]
fn subsequence_selects_by_one_based_position() {
    assert!(check(
        "string-join(subsequence(('a', 'b', 'c', 'd', 'e'), 3), ',') = 'c,d,e'",
        "<a/>"
    ));
    assert!(check(
        "string-join(subsequence(('a', 'b', 'c', 'd', 'e'), 2, 3), ',') = 'b,c,d'",
        "<a/>"
    ));
    // A fractional start rounds like `round()` does: halves go up.
    assert!(check(
        "string-join(subsequence(('a', 'b', 'c', 'd', 'e'), 1.5), ',') = 'b,c,d,e'",
        "<a/>"
    ));
    assert!(check("count(subsequence(('a', 'b'), 5)) = 0", "<a/>"));
}

#[test]
fn insert_before_splices_in_a_sequence() {
    assert!(check(
        "string-join(insert-before(('a', 'b', 'c'), 2, ('x', 'y')), ',') = 'a,x,y,b,c'",
        "<a/>"
    ));
    // A position before the start clamps to the front.
    assert!(check(
        "string-join(insert-before(('a', 'b'), -3, 'x'), ',') = 'x,a,b'",
        "<a/>"
    ));
    // A position past the end appends.
    assert!(check(
        "string-join(insert-before(('a', 'b'), 99, 'x'), ',') = 'a,b,x'",
        "<a/>"
    ));
}

#[test]
fn remove_drops_one_item_by_position() {
    assert!(check(
        "string-join(remove(('a', 'b', 'c'), 2), ',') = 'a,c'",
        "<a/>"
    ));
    // Out of range leaves the sequence unchanged.
    assert!(check(
        "string-join(remove(('a', 'b', 'c'), 99), ',') = 'a,b,c'",
        "<a/>"
    ));
    assert!(check("count(remove((), 1)) = 0", "<a/>"));
}

#[test]
fn cardinality_checks_pass_through_a_matching_sequence() {
    assert!(check("count(zero-or-one(())) = 0", "<a/>"));
    assert!(check("zero-or-one((1)) = 1", "<a/>"));
    assert!(check("string-join(one-or-more((1, 2)), ',') = '1,2'", "<a/>"));
    assert!(check("exactly-one((1)) = 1", "<a/>"));
}

#[test]
fn cardinality_checks_raise_on_a_mismatch() {
    let too_many = eval_error("zero-or-one((1, 2))", "<a/>");
    assert_contains!(too_many, "zero-or-one()");
    assert_contains!(too_many, "2 items");

    let empty = eval_error("one-or-more(())", "<a/>");
    assert_contains!(empty, "one-or-more()");

    let two = eval_error("exactly-one((1, 2))", "<a/>");
    assert_contains!(two, "exactly-one()");
    assert_contains!(two, "2 items");

    let zero = eval_error("exactly-one(())", "<a/>");
    assert_contains!(zero, "exactly-one()");
}

#[test]
fn data_atomizes_nodes_and_passes_atomic_values_through() {
    assert!(check("data(@x) eq 'open'", r#"<a x="open"/>"#));
    assert!(check("data(1) = 1", "<a/>"));
    assert!(check("string-join(data((@x, 'y')), ',') = 'open,y'", r#"<a x="open"/>"#));
}

#[test]
fn deep_equal_compares_atomic_sequences_by_value_and_length() {
    assert!(check("deep-equal((1, 2, 'x'), (1, 2, 'x'))", "<a/>"));
    assert!(!check("deep-equal((1, 2), (1, 2, 3))", "<a/>"));
    assert!(!check("deep-equal((1, 2), (1, 9))", "<a/>"));
    // Unlike `eq`, mismatched types are simply unequal, not an error.
    assert!(!check("deep-equal(1, 'a')", "<a/>"));
    // Unlike `eq`, NaN deep-equals NaN.
    assert!(check("deep-equal(avg(()), avg(()))", "<a/>"));
}

#[test]
fn deep_equal_compares_elements_structurally() {
    // Each comparison is between two `<b>` elements — deep-equal requires
    // the same expanded *name* too, so the two sides of a comparison must
    // share a tag; wrapper elements (`p`, `q`, ...) distinguish the pairs.
    let doc = r#"<a>
        <p><b x="1"><i>t</i></b></p>
        <q><b x="1"><i>t</i></b></q>
        <r><b x="2"><i>t</i></b></r>
        <s><b x="1" y="2"><i>t</i></b></s>
        <t><b y="2" x="1"><i>t</i></b></t>
        <u><b><i>t</i><j>u</j></b></u>
        <v><b><j>u</j><i>t</i></b></v>
    </a>"#;
    // Same name, same attribute, same single child: equal.
    assert!(check("deep-equal(p/b, q/b)", doc));
    // Different attribute value: not equal.
    assert!(!check("deep-equal(p/b, r/b)", doc));
    // Attribute order is not significant.
    assert!(check("deep-equal(s/b, t/b)", doc));
    // Child order is significant.
    assert!(!check("deep-equal(u/b, v/b)", doc));
    // A node never deep-equals an atomic value, even with the same string
    // value — this crate does not atomize for `deep-equal`.
    assert!(!check("deep-equal(p/b/i, 't')", doc));
}

#[test]
fn aggregates_accept_sequences_as_well_as_node_sets() {
    assert!(check("sum((1, 2, 3)) = 6", "<a/>"));
    assert!(check("min((3, 1, 2)) = 1", "<a/>"));
    assert!(check("max((3, 1, 2)) = 3", "<a/>"));
    assert!(check("avg((2, 4)) = 3", "<a/>"));
    assert!(check("exists((1))", "<a/>"));
    assert!(check("empty(())", "<a/>"));
}

#[test]
fn a_sequence_compares_existentially_like_a_node_set() {
    assert!(check("(1, 2, 3) = 2", "<a/>"));
    assert!(!check("(1, 2, 3) = 9", "<a/>"));
    assert!(check("(1, 2, 3) > 2", "<a/>"));
    // Both can be true at once, as for node-sets.
    assert!(check("((1, 2) = 1) and ((1, 2) != 1)", "<a/>"));
}

#[test]
fn a_multi_item_sequence_has_no_effective_boolean_value() {
    // XPath 2.0 makes this a type error; guessing a branch would be worse.
    let source = schema_with(
        "xslt2",
        r#"<pattern><rule context="a"><assert test="if ((1, 2)) then true() else false()">m</assert></rule></pattern>"#,
    );
    let schema = Schema::from_str(&source).expect("schema should compile");
    let document = Document::from_str("<a/>").unwrap();
    let error = schema.validate(&document).unwrap_err();
    assert_contains!(error.to_string(), "effective boolean value");
}

#[test]
fn sequence_syntax_is_refused_under_a_one_point_zero_binding() {
    for (test, fragment) in [
        ("count((1, 2))", "sequence"),
        ("count(1 to 3)", "`to` range"),
        ("count(for $b in b return $b)", "for"),
        ("some $b in b satisfies true()", "some"),
        ("every $b in b satisfies true()", "every"),
    ] {
        let message = compile_error("xslt", test);
        assert_contains!(message, fragment);
        assert_contains!(message, "xslt2");
    }
}

#[test]
fn keywords_are_not_reserved_words() {
    // `in`, `to`, `return` and the rest are ordinary names in XPath, so a
    // document may legitimately use them as element names.
    assert!(check("count(to) = 1", "<a><to/></a>"));
    assert!(check("count(for) = 1", "<a><for/></a>"));
    assert!(check("count(some) = 1", "<a><some/></a>"));
    // And a keyword directly followed by `(` is still the keyword.
    assert!(check("some $n in (1 to 3) satisfies $n = 2", "<a/>"));
    assert!(check("count(for $n in (1, 2) return ($n)) = 2", "<a/>"));
}

// ---------------------------------------------------------------------------
// Phase 2b: dates and times.
// ---------------------------------------------------------------------------

/// A fixed instant, so every date test below is reproducible: the seconds
/// from the Unix epoch to 2026-08-21T12:00:00Z.
const FIXED_NOW: f64 = 1_787_313_600.0;

/// As `check`, but with the clock pinned to [`FIXED_NOW`].
fn check_at_fixed_time(test: &str, document: &str) -> bool {
    use schematron::validate::ValidateOptions;

    let source = schema_with(
        "xslt2",
        &format!(
            r#"<ns prefix="xs" uri="http://www.w3.org/2001/XMLSchema"/>
               <pattern><rule context="a"><assert test="{test}">failed</assert></rule></pattern>"#
        ),
    );
    let schema = Schema::from_str(&source)
        .unwrap_or_else(|e| panic!("schema with test {test:?} should compile: {e}"));
    let document = Document::from_str(document).expect("document should parse");
    let options = ValidateOptions::new().with_current_time(FIXED_NOW);
    schema
        .validate_with(&document, &options)
        .expect("validation should run")
        .is_valid()
}

#[test]
fn the_clock_reports_the_supplied_instant() {
    assert!(check_at_fixed_time("current-date() = xs:date('2026-08-21Z')", "<a/>"));
    assert!(check_at_fixed_time(
        "current-dateTime() = xs:dateTime('2026-08-21T12:00:00Z')",
        "<a/>"
    ));
    assert!(check_at_fixed_time("year-from-date(current-date()) = 2026", "<a/>"));
}

#[test]
fn the_canonical_schematron_example_now_runs() {
    // "ContractDate should be in the past, because future contracts are not
    // allowed" — the example Schematron is most often quoted with, and which
    // this crate could not run until dates existed.
    let test = "@ContractDate &lt; current-date()";
    assert!(check_at_fixed_time(test, r#"<a ContractDate="2020-01-01"/>"#));
    assert!(!check_at_fixed_time(test, r#"<a ContractDate="2099-12-31"/>"#));
}

#[test]
fn an_untyped_value_is_cast_to_the_other_operands_type() {
    // The attribute is untyped, so the comparison casts it to a date rather
    // than comparing strings.
    assert!(check_at_fixed_time(
        "@d = xs:date('2026-08-21')",
        r#"<a d="2026-08-21"/>"#
    ));
    assert!(check_at_fixed_time(
        "@d &gt; xs:date('2020-01-01')",
        r#"<a d="2026-08-21"/>"#
    ));
}

#[test]
fn a_timezone_offset_is_honoured_rather_than_compared_as_text() {
    // Lexically `00:00:00+01:00` sorts after `00:00:00Z`, but as an instant
    // it is an hour earlier. Comparing as text would get this backwards.
    assert!(check_at_fixed_time(
        "xs:dateTime('2026-08-21T00:00:00+01:00') &lt; xs:dateTime('2026-08-21T00:00:00Z')",
        "<a/>"
    ));
}

#[test]
fn date_components_can_be_read() {
    let doc = r#"<a d="2026-08-21" t="10:30:05" dt="2026-08-21T10:30:05"/>"#;
    assert!(check_at_fixed_time("year-from-date(@d) = 2026", doc));
    assert!(check_at_fixed_time("month-from-date(@d) = 8", doc));
    assert!(check_at_fixed_time("day-from-date(@d) = 21", doc));
    assert!(check_at_fixed_time("hours-from-time(@t) = 10", doc));
    assert!(check_at_fixed_time("minutes-from-time(@t) = 30", doc));
    assert!(check_at_fixed_time("seconds-from-time(@t) = 5", doc));
    assert!(check_at_fixed_time("hours-from-dateTime(@dt) = 10", doc));
}

#[test]
fn a_malformed_date_is_an_error_not_a_false_test() {
    // A date typo must fail loudly. A quietly false assertion would report
    // the document as broken for the wrong reason, or pass it for one.
    use schematron::validate::ValidateOptions;

    let source = schema_with(
        "xslt2",
        r#"<pattern><rule context="a">
             <assert test="@d &lt; current-date()">m</assert>
           </rule></pattern>"#,
    );
    let schema = Schema::from_str(&source).expect("schema should compile");
    let document = Document::from_str(r#"<a d="2026-02-30"/>"#).unwrap();
    let options = ValidateOptions::new().with_current_time(FIXED_NOW);

    let error = schema.validate_with(&document, &options).unwrap_err();
    assert_contains!(error.to_string(), "2026-02-30");
    assert_contains!(error.to_string(), "xs:date");
}

#[test]
fn the_constructors_reject_impossible_values_when_the_schema_loads() {
    // A literal argument is checked at evaluation, not compile, time — but it
    // must still be an error.
    use schematron::validate::ValidateOptions;

    let source = schema_with(
        "xslt2",
        r#"<ns prefix="xs" uri="http://www.w3.org/2001/XMLSchema"/>
           <pattern><rule context="a">
             <assert test="xs:date('2026-13-01') &lt; current-date()">m</assert>
           </rule></pattern>"#,
    );
    let schema = Schema::from_str(&source).expect("schema should compile");
    let document = Document::from_str("<a/>").unwrap();
    let options = ValidateOptions::new().with_current_time(FIXED_NOW);
    let error = schema.validate_with(&document, &options).unwrap_err();
    assert_contains!(error.to_string(), "2026-13-01");
}

#[test]
fn the_clock_is_stable_across_a_whole_run() {
    // Every call must agree, or one rule could contradict another halfway
    // down a document.
    assert!(check_at_fixed_time(
        "current-date() = current-date() and current-dateTime() = current-dateTime()",
        "<a/>"
    ));
}

#[test]
fn a_run_without_a_supplied_instant_still_works() {
    // The system clock is read once, so this must not error — only be
    // non-reproducible, which is why the tests above pin it.
    assert!(check("year-from-date(current-date()) > 2000", "<a/>"));
}

#[test]
fn date_functions_are_refused_under_a_one_point_zero_binding() {
    let message = compile_error("xslt", "current-date()");
    assert_contains!(message, "XPath 2.0");
    assert_contains!(message, "xslt2");
}

#[test]
fn calling_the_clock_without_a_run_instant_is_an_error() {
    // Evaluating XPath directly has no run, so an arbitrary instant would be
    // silently non-reproducible.
    use schematron::xpath::{evaluate, parse, EvalContext, Namespaces, Variables, XPathVersion};

    let document = Document::from_str("<a/>").unwrap();
    let expr = parse("current-date()").unwrap();
    let variables = Variables::new();
    let namespaces = Namespaces::new();
    let context = EvalContext::new(&document, document.root(), &variables, &namespaces)
        .with_version(XPathVersion::V2);

    let error = evaluate(&expr, &context).unwrap_err();
    assert_contains!(error.message, "instant");
}

// ---------------------------------------------------------------------------
// Phase 2c: value comparisons.
// ---------------------------------------------------------------------------

/// The evaluation error for a test under `xslt2`, if it produces one.
fn eval_error(test: &str, document: &str) -> String {
    let source = schema_with(
        "xslt2",
        &format!(
            r#"<ns prefix="xs" uri="http://www.w3.org/2001/XMLSchema"/>
               <pattern><rule context="a"><assert test="{test}">m</assert></rule></pattern>"#
        ),
    );
    let schema = Schema::from_str(&source)
        .unwrap_or_else(|e| panic!("schema with test {test:?} should compile: {e}"));
    let document = Document::from_str(document).expect("document should parse");
    schema.validate(&document).map_or_else(
        |error| error.to_string(),
        |_| panic!("test {test:?} unexpectedly evaluated without error"),
    )
}

#[test]
fn value_comparisons_compare_two_values() {
    assert!(check("'a' eq 'a'", "<a/>"));
    assert!(!check("'a' eq 'b'", "<a/>"));
    assert!(check("'a' ne 'b'", "<a/>"));
    assert!(check("1 lt 2", "<a/>"));
    assert!(check("2 le 2", "<a/>"));
    assert!(check("3 gt 2", "<a/>"));
    assert!(check("2 ge 2", "<a/>"));
}

#[test]
fn a_node_atomizes_to_its_string_value() {
    assert!(check("@x eq 'open'", r#"<a x="open"/>"#));
    assert!(check("b eq 'text'", "<a><b>text</b></a>"));
    // Strings order lexically.
    assert!(check("@x lt 'M'", r#"<a x="ABC"/>"#));
}

#[test]
fn more_than_one_item_is_an_error_where_a_general_comparison_is_not() {
    // The whole reason to reach for `eq`: `=` would quietly pick whichever
    // pair happened to match.
    let doc = r#"<a><b q="1"/><b q="2"/></a>"#;
    assert!(check("b/@q = 1", doc));

    let message = eval_error("b/@q eq '1'", doc);
    assert_contains!(message, "2 items");
    assert_contains!(message, "exactly one");
    // And it points at the operator that would have worked.
    assert_contains!(message, "=");
}

#[test]
fn mismatched_types_are_an_error() {
    // Everything in an XML document is untyped, so it counts as a string.
    let message = eval_error("@n eq 1", r#"<a n="1"/>"#);
    assert_contains!(message, "string");
    assert_contains!(message, "number");

    // Which the schema author fixes by saying what they meant.
    assert!(check("number(@n) eq 1", r#"<a n="1"/>"#));
    assert!(check("@n eq '1'", r#"<a n="1"/>"#));
}

#[test]
fn an_untyped_value_is_not_coerced_to_a_date() {
    // A general comparison would cast it; a value comparison will not.
    let message = eval_error("@d eq xs:date('2020-01-01')", r#"<a d="2020-01-01"/>"#);
    assert_contains!(message, "xs:date");

    // Cast it explicitly and the comparison is fine.
    assert!(check(
        "xs:date(@d) eq xs:date('2020-01-01')",
        r#"<a d="2020-01-01"/>"#
    ));
}

#[test]
fn dates_compare_by_instant() {
    assert!(check(
        "xs:date('2020-01-01') lt xs:date('2026-08-21')",
        "<a/>"
    ));
    assert!(check(
        "xs:dateTime('2026-08-21T00:00:00+01:00') lt xs:dateTime('2026-08-21T00:00:00Z')",
        "<a/>"
    ));
}

#[test]
fn an_empty_operand_yields_the_empty_sequence() {
    // Nothing to compare, so nothing is claimed — false in a boolean
    // position, and not an error.
    assert!(!check("missing eq 'x'", "<a/>"));
    assert!(!check("missing ne 'x'", "<a/>"));
    assert!(!check("'x' eq missing", "<a/>"));
    assert!(!check("missing lt 1", "<a/>"));
}

#[test]
fn value_comparisons_are_refused_under_a_one_point_zero_binding() {
    for op in ["eq", "ne", "lt", "le", "gt", "ge"] {
        let message = compile_error("xslt", &format!("'a' {op} 'b'"));
        assert_contains!(message, "value comparison");
        assert_contains!(message, "xslt2");
    }
}

#[test]
fn the_operator_names_are_still_element_names_in_name_position() {
    // `eq`, `lt` and the rest are not reserved words, so a document may use
    // them as element names.
    assert!(check("count(eq) = 1", "<a><eq/></a>"));
    assert!(check("count(lt) = 1", "<a><lt/></a>"));
    assert!(check("count(a/ge) = 0", "<a/>"));
}

#[test]
fn booleans_compare_with_false_below_true() {
    assert!(check("false() lt true()", "<a/>"));
    assert!(check("true() eq true()", "<a/>"));
    assert!(check("false() ne true()", "<a/>"));
}

#[test]
fn nan_is_never_equal_and_never_ordered() {
    // Consistent with IEEE 754, and with the rest of the engine.
    assert!(!check("number('x') eq number('x')", "<a/>"));
    assert!(!check("number('x') lt 1", "<a/>"));
    assert!(!check("number('x') ge 1", "<a/>"));
    assert!(check("number('x') ne number('x')", "<a/>"));
}

// ---------------------------------------------------------------------------
// Phase 2d: durations and date arithmetic.
// ---------------------------------------------------------------------------

#[test]
fn subtracting_two_dates_measures_the_distance() {
    assert!(check(
        "xs:date('2026-08-21') - xs:date('2026-01-01') eq xs:dayTimeDuration('P232D')",
        "<a/>"
    ));
    assert!(check(
        "days-from-duration(xs:date('2026-08-21') - xs:date('2026-01-01')) = 232",
        "<a/>"
    ));
}

#[test]
fn the_constraint_a_schema_actually_wants_to_write() {
    let test = "xs:date(@end) - xs:date(@start) le xs:dayTimeDuration('P90D')";
    assert!(check(test, r#"<a start="2026-01-01" end="2026-03-01"/>"#));
    assert!(!check(test, r#"<a start="2026-01-01" end="2026-08-21"/>"#));
}

#[test]
fn a_duration_moves_a_date() {
    assert!(check(
        "xs:date('2026-01-01') + xs:dayTimeDuration('P90D') eq xs:date('2026-04-01')",
        "<a/>"
    ));
    assert!(check(
        "xs:date('2026-04-01') - xs:dayTimeDuration('P90D') eq xs:date('2026-01-01')",
        "<a/>"
    ));
    assert!(check(
        "xs:date('2026-01-01') + xs:yearMonthDuration('P1Y6M') eq xs:date('2027-07-01')",
        "<a/>"
    ));
}

#[test]
fn adding_months_clamps_the_day_rather_than_overflowing() {
    // XML Schema requires 31 January plus one month to be 28 February.
    assert!(check(
        "xs:date('2026-01-31') + xs:yearMonthDuration('P1M') eq xs:date('2026-02-28')",
        "<a/>"
    ));
    // And 29 February in a leap year.
    assert!(check(
        "xs:date('2024-01-31') + xs:yearMonthDuration('P1M') eq xs:date('2024-02-29')",
        "<a/>"
    ));
}

#[test]
fn durations_add_and_subtract_within_a_subtype() {
    assert!(check(
        "xs:dayTimeDuration('P1D') + xs:dayTimeDuration('P2D') eq xs:dayTimeDuration('P3D')",
        "<a/>"
    ));
    assert!(check(
        "xs:yearMonthDuration('P1Y') - xs:yearMonthDuration('P6M') eq xs:yearMonthDuration('P6M')",
        "<a/>"
    ));
}

#[test]
fn mixing_the_two_duration_subtypes_is_an_error() {
    // Whether a month exceeds thirty days has no answer, which is why the
    // subtypes are separate in the first place.
    let message = eval_error(
        "xs:yearMonthDuration('P1M') + xs:dayTimeDuration('P30D') eq xs:dayTimeDuration('P30D')",
        "<a/>",
    );
    assert_contains!(message, "xs:yearMonthDuration");
    assert_contains!(message, "xs:dayTimeDuration");
}

#[test]
fn durations_of_different_subtypes_do_not_compare() {
    let message = eval_error(
        "xs:yearMonthDuration('P1M') lt xs:dayTimeDuration('P30D')",
        "<a/>",
    );
    assert_contains!(message, "same type");
}

#[test]
fn duration_components_can_be_read() {
    assert!(check(
        "days-from-duration(xs:dayTimeDuration('P1DT2H30M15S')) = 1",
        "<a/>"
    ));
    assert!(check(
        "hours-from-duration(xs:dayTimeDuration('P1DT2H30M15S')) = 2",
        "<a/>"
    ));
    assert!(check(
        "minutes-from-duration(xs:dayTimeDuration('P1DT2H30M15S')) = 30",
        "<a/>"
    ));
    assert!(check(
        "seconds-from-duration(xs:dayTimeDuration('P1DT2H30M15S')) = 15",
        "<a/>"
    ));
    assert!(check("years-from-duration(xs:yearMonthDuration('P1Y6M')) = 1", "<a/>"));
    assert!(check("months-from-duration(xs:yearMonthDuration('P1Y6M')) = 6", "<a/>"));
}

#[test]
fn a_negative_duration_signs_every_component() {
    assert!(check(
        "days-from-duration(xs:dayTimeDuration('-P3D')) = -3",
        "<a/>"
    ));
    assert!(check(
        "xs:date('2026-01-01') - xs:date('2026-01-04') eq xs:dayTimeDuration('-P3D')",
        "<a/>"
    ));
}

#[test]
fn a_component_accessor_refuses_the_wrong_subtype() {
    let message = eval_error("days-from-duration(xs:yearMonthDuration('P1M')) = 0", "<a/>");
    assert_contains!(message, "xs:dayTimeDuration");
}

#[test]
fn adding_two_dates_is_an_error() {
    // XPath 2.0 gives it no meaning, and inventing one would hide a mistake.
    let message = eval_error(
        "xs:date('2026-01-01') + xs:date('2026-01-02') eq xs:date('2026-01-01')",
        "<a/>",
    );
    assert_contains!(message, "cannot be added");
}

#[test]
fn a_malformed_duration_is_an_error() {
    let message = eval_error("xs:dayTimeDuration('P1X') eq xs:dayTimeDuration('P1D')", "<a/>");
    assert_contains!(message, "P1X");

    // A month field in a dayTimeDuration is not a dayTimeDuration.
    let message = eval_error("xs:dayTimeDuration('P1M') eq xs:dayTimeDuration('P1D')", "<a/>");
    assert_contains!(message, "P1M");
}

#[test]
fn duration_constructors_are_refused_under_a_one_point_zero_binding() {
    let message = compile_error("xslt", "xs:dayTimeDuration('P1D')");
    assert_contains!(message, "XPath 2.0");
}

// ---------------------------------------------------------------------------
// Phase 2e: node comparisons, duration scaling, implicit timezone.
// ---------------------------------------------------------------------------

#[test]
fn is_asks_about_identity_not_content() {
    // Two elements with the same content are equal, and are not the same node.
    let doc = "<a><b>x</b><c>x</c></a>";
    assert!(check("b = c", doc));
    assert!(!check("b is c", doc));
    assert!(check("b is b", doc));
    assert!(check("b[1] is b[1]", doc));
}

#[test]
fn document_order_operators() {
    let doc = "<a><b/><c/></a>";
    assert!(check("b << c", doc));
    assert!(!check("c << b", doc));
    assert!(check("c >> b", doc));
    assert!(!check("b >> c", doc));
    // A node neither precedes nor follows itself.
    assert!(!check("b << b", doc));
    assert!(!check("b >> b", doc));
}

#[test]
fn a_node_comparison_takes_exactly_one_node() {
    let doc = "<a><b/><b/></a>";
    let message = eval_error("b is b", doc);
    assert_contains!(message, "2 nodes");
    assert_contains!(message, "exactly one");

    // An atomic operand is a type error, not a coercion.
    let message = eval_error("'x' is 'x'", "<a/>");
    assert_contains!(message, "node comparison");
}

#[test]
fn an_empty_node_operand_yields_the_empty_sequence() {
    assert!(!check("missing is missing", "<a/>"));
    assert!(!check("missing << b", "<a><b/></a>"));
}

#[test]
fn node_comparisons_are_refused_under_a_one_point_zero_binding() {
    for test in ["b is c", "b << c", "b >> c"] {
        let message = compile_error("xslt", test);
        assert_contains!(message, "node comparison");
        assert_contains!(message, "xslt2");
    }
}

#[test]
fn is_is_still_an_element_name_in_name_position() {
    assert!(check("count(is) = 1", "<a><is/></a>"));
}

#[test]
fn a_duration_scales_by_a_number() {
    assert!(check(
        "xs:dayTimeDuration('P1D') * 3 eq xs:dayTimeDuration('P3D')",
        "<a/>"
    ));
    assert!(check(
        "3 * xs:dayTimeDuration('P1D') eq xs:dayTimeDuration('P3D')",
        "<a/>"
    ));
    assert!(check(
        "xs:dayTimeDuration('P6D') div 2 eq xs:dayTimeDuration('P3D')",
        "<a/>"
    ));
    assert!(check(
        "xs:yearMonthDuration('P1Y') * 2 eq xs:yearMonthDuration('P2Y')",
        "<a/>"
    ));
}

#[test]
fn dividing_two_durations_gives_a_number() {
    assert!(check(
        "xs:dayTimeDuration('P90D') div xs:dayTimeDuration('P30D') = 3",
        "<a/>"
    ));
    assert!(check(
        "xs:yearMonthDuration('P1Y') div xs:yearMonthDuration('P3M') = 4",
        "<a/>"
    ));
}

#[test]
fn multiplying_two_durations_is_an_error() {
    let message = eval_error(
        "xs:dayTimeDuration('P1D') * xs:dayTimeDuration('P1D') eq xs:dayTimeDuration('P1D')",
        "<a/>",
    );
    assert_contains!(message, "cannot be multiplied");
}

#[test]
fn months_scale_as_whole_months() {
    // There is no such thing as half a month, so the result rounds.
    assert!(check(
        "xs:yearMonthDuration('P1M') * 1.5 eq xs:yearMonthDuration('P2M')",
        "<a/>"
    ));
}

#[test]
fn the_implicit_timezone_defaults_to_utc() {
    // A value with no offset reads as UTC, so it equals the same value
    // written with Z.
    assert!(check(
        "xs:dateTime('2026-08-21T00:00:00') eq xs:dateTime('2026-08-21T00:00:00Z')",
        "<a/>"
    ));
}

#[test]
fn the_implicit_timezone_can_be_set() {
    use schematron::validate::ValidateOptions;

    let source = schema_with(
        "xslt2",
        r#"<ns prefix="xs" uri="http://www.w3.org/2001/XMLSchema"/>
           <pattern><rule context="a">
             <assert test="xs:dateTime('2026-08-21T00:00:00') eq xs:dateTime('2026-08-21T05:00:00Z')">m</assert>
           </rule></pattern>"#,
    );
    let schema = Schema::from_str(&source).expect("schema should compile");
    let document = Document::from_str("<a/>").unwrap();

    // Under UTC the two are five hours apart.
    assert!(!schema.validate(&document).unwrap().is_valid());

    // Read as UTC-5, the offsetless value is the same instant.
    let options = ValidateOptions::new().with_implicit_timezone(-5 * 60);
    assert!(schema.validate_with(&document, &options).unwrap().is_valid());
}

#[test]
fn timezone_from_a_value_reports_its_own_offset() {
    assert!(check(
        "timezone-from-dateTime(xs:dateTime('2026-08-21T00:00:00+01:00')) eq xs:dayTimeDuration('PT1H')",
        "<a/>"
    ));
    assert!(check(
        "timezone-from-date(xs:date('2026-08-21Z')) eq xs:dayTimeDuration('PT0S')",
        "<a/>"
    ));
    // A value with no offset has no timezone, which is the empty sequence.
    assert!(check(
        "empty(timezone-from-date(xs:date('2026-08-21')))",
        "<a/>"
    ));
}

#[test]
fn implicit_timezone_reports_the_runs_setting() {
    assert!(check("implicit-timezone() eq xs:dayTimeDuration('PT0S')", "<a/>"));
}

// ---------------------------------------------------------------------------
// Phase 3: the type operators.
// ---------------------------------------------------------------------------

#[test]
fn castable_as_reports_instead_of_aborting() {
    // The whole point of the operator. Before it, asking whether an attribute
    // held a date meant calling xs:date(), which raises an error and stops the
    // run — so a schema could not report a bad date as a finding.
    assert!(check("@d castable as xs:date", r#"<a d="2026-08-21"/>"#));
    assert!(!check("@d castable as xs:date", r#"<a d="2026-02-30"/>"#));
    assert!(!check("@d castable as xs:date", r#"<a d="not-a-date"/>"#));

    // And the guarded form a schema actually writes.
    let guarded = "not(@d castable as xs:date) or xs:date(@d) lt xs:date('2030-01-01')";
    assert!(check(guarded, r#"<a d="2026-08-21"/>"#));
    assert!(check(guarded, r#"<a d="rubbish"/>"#));
}

#[test]
fn castable_as_checks_the_lexical_form() {
    assert!(check("'12' castable as xs:integer", "<a/>"));
    assert!(!check("'12.5' castable as xs:integer", "<a/>"));
    assert!(check("'12.5' castable as xs:decimal", "<a/>"));
    assert!(!check("'x' castable as xs:double", "<a/>"));
    assert!(check("'true' castable as xs:boolean", "<a/>"));
    assert!(!check("'yes' castable as xs:boolean", "<a/>"));
    assert!(check("'P90D' castable as xs:dayTimeDuration", "<a/>"));
    assert!(!check("'P90D' castable as xs:yearMonthDuration", "<a/>"));
}

#[test]
fn cast_as_converts_and_the_result_is_usable() {
    assert!(check("'2026-08-21' cast as xs:date eq xs:date('2026-08-21')", "<a/>"));
    assert!(check("'12' cast as xs:integer = 12", "<a/>"));
    assert!(check("@n cast as xs:double + 1 = 3", r#"<a n="2"/>"#));
    assert!(check("'true' cast as xs:boolean", "<a/>"));
}

#[test]
fn cast_as_errors_where_castable_as_reports_false() {
    // The two are the same test; only the failure mode differs.
    assert!(!check("'x' castable as xs:date", "<a/>"));
    let message = eval_error("'x' cast as xs:date eq xs:date('2026-08-21')", "<a/>");
    assert_contains!(message, "cannot be cast");
}

#[test]
fn an_empty_operand_needs_the_optional_marker() {
    assert!(!check("missing castable as xs:date", "<a/>"));
    assert!(check("missing castable as xs:date?", "<a/>"));

    let message = eval_error("(missing cast as xs:date) eq xs:date('2026-08-21')", "<a/>");
    assert_contains!(message, "nothing to cast");
}

#[test]
fn instance_of_matches_node_kinds() {
    let doc = "<a><b/>text<!--c--></a>";
    assert!(check(". instance of element()", doc));
    assert!(check(". instance of node()", doc));
    assert!(check(". instance of item()", doc));
    assert!(check("b instance of element()", doc));
    assert!(check("text() instance of text()", doc));
    assert!(check("comment() instance of comment()", doc));
    assert!(!check("b instance of attribute()", doc));
}

#[test]
fn instance_of_matches_a_named_element() {
    let doc = "<a><b/></a>";
    assert!(check("b instance of element(b)", doc));
    assert!(!check("b instance of element(c)", doc));
}

#[test]
fn instance_of_matches_atomic_types() {
    assert!(check("'x' instance of xs:string", "<a/>"));
    assert!(check("true() instance of xs:boolean", "<a/>"));
    assert!(check("xs:date('2026-08-21') instance of xs:date", "<a/>"));
    assert!(check(
        "xs:dayTimeDuration('P1D') instance of xs:dayTimeDuration",
        "<a/>"
    ));
    assert!(check("'x' instance of xs:anyAtomicType", "<a/>"));
    // A node is not an atomic value; `instance of` does not atomize.
    assert!(!check("@n instance of xs:string", r#"<a n="1"/>"#));
}

// ---------------------------------------------------------------------------
// Phase 4: the numeric hierarchy.
// ---------------------------------------------------------------------------

#[test]
fn a_literal_carries_the_type_it_is_written_as() {
    // XPath 2.0 assigns these types lexically, not by value: `1.0` is a
    // decimal even though it equals the integer `1`. Documented in
    // spec/xpath2/.
    assert!(check("1 instance of xs:integer", "<a/>"));
    assert!(!check("1.0 instance of xs:integer", "<a/>"));
    assert!(check("1.0 instance of xs:decimal", "<a/>"));
    assert!(check("1.5 instance of xs:decimal", "<a/>"));
    assert!(!check("1.5 instance of xs:integer", "<a/>"));
}

#[test]
fn an_integer_is_also_a_decimal_but_not_a_double() {
    // `xs:integer` derives from `xs:decimal` by restriction in XML Schema,
    // so an integer matches `instance of xs:decimal` too. `xs:float` and
    // `xs:double` are unrelated primitive types, so an integer matches
    // neither — this corrects a divergence the crate previously had from
    // real XPath 2.0, back when every number reported as `xs:double`.
    assert!(check("1 instance of xs:decimal", "<a/>"));
    assert!(!check("1 instance of xs:double", "<a/>"));
    assert!(!check("1 instance of xs:float", "<a/>"));
    assert!(check("1 instance of xs:anyAtomicType", "<a/>"));
}

#[test]
fn cast_as_tags_the_result_with_the_type_named() {
    assert!(check("'1' cast as xs:integer instance of xs:integer", "<a/>"));
    assert!(check("'1.5' cast as xs:decimal instance of xs:decimal", "<a/>"));
    assert!(check("'1.5' cast as xs:float instance of xs:float", "<a/>"));
    assert!(check("'1.5' cast as xs:double instance of xs:double", "<a/>"));
    // Casting itself is still lexical, unaffected by this: `'1'` is castable
    // as `xs:integer` whether or not the source text looks like one.
    assert!(check("'1' castable as xs:integer", "<a/>"));
}

#[test]
fn a_for_bound_item_keeps_its_tag() {
    // Binding a sequence item to a variable does not launder its type.
    assert!(check("some $x in (1, 2) satisfies $x instance of xs:integer", "<a/>"));
    assert!(check(
        "(for $x in (1.5) return $x) instance of xs:decimal",
        "<a/>"
    ));
}

#[test]
fn computed_numbers_are_still_double() {
    // Deliberately out of scope: this crate tracks a numeric type only for
    // literals and explicit casts. Arithmetic, every function in the
    // library, and `to` ranges always produce `xs:double`, exactly as
    // before this hierarchy existed. Documented in spec/xpath2/.
    assert!(check("(1 + 1) instance of xs:double", "<a/>"));
    assert!(!check("(1 + 1) instance of xs:integer", "<a/>"));
    assert!(check("count((1, 2)) instance of xs:double", "<a/>"));
    assert!(check("every $x in (1 to 3) satisfies $x instance of xs:double", "<a/>"));
}

#[test]
fn occurrence_indicators_bound_the_length() {
    let doc = "<a><b/><b/></a>";
    assert!(check("b instance of element()*", doc));
    assert!(check("b instance of element()+", doc));
    assert!(!check("b instance of element()", doc));
    assert!(!check("b instance of element()?", doc));

    assert!(check("missing instance of element()*", doc));
    assert!(check("missing instance of element()?", doc));
    assert!(!check("missing instance of element()+", doc));
}

#[test]
fn empty_sequence_matches_only_nothing() {
    assert!(check("missing instance of empty-sequence()", "<a/>"));
    assert!(!check("b instance of empty-sequence()", "<a><b/></a>"));
}

#[test]
fn treat_as_passes_through_or_errors() {
    assert!(check("(b treat as element()) instance of element()", "<a><b/></a>"));

    let message = eval_error("(b treat as attribute()) instance of node()", "<a><b/></a>");
    assert_contains!(message, "treat as");
}

#[test]
fn cast_as_refuses_a_node_or_sequence_type() {
    // Casting a node has no meaning, so it is a syntax error rather than a
    // silently odd result.
    let message = compile_error("xslt2", "@d cast as element()");
    assert_contains!(message, "atomic type");
}

#[test]
fn type_operators_bind_tighter_than_comparison() {
    // `x cast as xs:integer = 12` must group as `(x cast as xs:integer) = 12`.
    assert!(check("'12' cast as xs:integer = 12", "<a/>"));
    assert!(check("'12' castable as xs:integer = true()", "<a/>"));
}

#[test]
fn type_operators_are_refused_under_a_one_point_zero_binding() {
    for (test, fragment) in [
        ("@d castable as xs:date", "castable as"),
        ("@d cast as xs:date", "cast as"),
        (". instance of element()", "instance of"),
        (". treat as element()", "treat as"),
    ] {
        let message = compile_error("xslt", test);
        assert_contains!(message, fragment);
        assert_contains!(message, "xslt2");
    }
}

#[test]
fn the_keywords_are_still_element_names_in_name_position() {
    // `cast`, `instance` and the rest are not reserved words. They are only
    // operators when their partner word follows.
    assert!(check("count(cast) = 1", "<a><cast/></a>"));
    assert!(check("count(instance) = 1", "<a><instance/></a>"));
    assert!(check("count(treat) = 1", "<a><treat/></a>"));
}

#[test]
fn kind_tests_work_as_path_node_tests() {
    const DOC: &str = r#"<a>text<b id="1"/><c/><b id="2"/><!--note--><?pi data?></a>"#;

    // `element()` names the kind outright, so it selects elements whatever
    // the axis — unlike `*`, which selects the axis's principal node type.
    assert!(check("count(element()) = 3", DOC));
    assert!(check("count(element(b)) = 2", DOC));
    assert!(check("count(element(*)) = 3", DOC));
    assert!(check("count(self::element(a)) = 1", DOC));

    // A step whose test is an attribute kind test defaults to the attribute
    // axis, per XPath 2.0 section 3.2.1.1. Without that rule it could never
    // match: the child axis yields no attributes.
    assert!(check("count(b/attribute()) = 2", DOC));
    assert!(check("count(b/attribute(id)) = 2", DOC));
    assert!(check("count(b/attribute(absent)) = 0", DOC));

    // An axis written out is respected, and the child axis has no attributes.
    assert!(check("count(b/child::attribute()) = 0", DOC));

    // `document-node()` matches the root, which is the parent of the
    // document element rather than one of its children.
    assert!(check("count(/self::document-node()) = 1", DOC));
    assert!(check("count(ancestor-or-self::document-node()) = 1", DOC));
    assert!(check("count(/document-node()) = 0", DOC));

    // The XPath 1.0 node tests keep working and keep their meaning.
    assert!(check("count(node()) = 6", DOC));
    assert!(check("count(text()) = 1", DOC));
    assert!(check("count(comment()) = 1", DOC));
    assert!(check("count(processing-instruction()) = 1", DOC));
}

#[test]
fn kind_tests_as_node_tests_are_refused_under_a_one_point_zero_binding() {
    // Being told `element` is an unknown function would send the reader
    // hunting for a typo. The message names the construct and the binding
    // that enables it.
    for (test, written) in [
        ("count(element())", "element()"),
        ("count(element(b))", "element()"),
        ("count(b/attribute())", "attribute()"),
        ("count(self::document-node())", "document-node()"),
    ] {
        let message = compile_error("xslt", test);
        assert_contains!(message, written);
        assert_contains!(message, "kind test");
        assert_contains!(message, "xslt2");
    }
}

#[test]
fn an_element_named_like_a_kind_test_is_still_a_name_test() {
    // `element` is only a kind test when followed by `(`. As a bare name it
    // is an ordinary element name, under either binding.
    const DOC: &str = "<a><element/><attribute/></a>";
    assert!(check("count(element) = 1", DOC));
    assert!(check("count(attribute) = 1", DOC));
    assert!(check("name(element) = 'element'", DOC));
}

#[test]
fn nested_ranges_and_loops_are_bounded_together() {
    // A limit on one range cannot see this: each of the three below is well
    // under it, and the product is close to a billion items. libFuzzer found
    // the shape as a slow unit; the budget is shared across nested
    // constructs so that the product is what is bounded.
    const DOC: &str = "<a/>";

    // Each of these is legitimate and must keep working.
    assert!(check("count(1 to 999999) = 999999", DOC));
    assert!(check("count(for $i in 1 to 999 return for $j in 1 to 999 return $j) = 998001", DOC));
    assert!(check("count(for $i in 1 to 10 return $i * 2) = 10", DOC));
    assert!(check("some $i in 1 to 10 satisfies $i = 5", DOC));

    // And each of these asks for more than the budget allows.
    for test in [
        "count(for $i in 1 to 999 return for $j in 1 to 999 return for $k in 1 to 999 return $k)",
        // Both ranges are under the single-range limit; their product is not.
        "count(for $i in 1 to 4000 return for $j in 1 to 4000 return $j)",
    ] {
        let source = schema_with(
            "xslt2",
            &format!(r#"<pattern><rule context="a"><assert test="{test}">m</assert></rule></pattern>"#),
        );
        let schema = Schema::from_str(&source).expect("it compiles; the cost is at evaluation");
        let document = Document::from_str(DOC).unwrap();
        let error = schema
            .validate(&document)
            .expect_err("an expression this large must be refused, not run");
        assert_contains!(error.to_string(), "items");
    }
}

#[test]
fn the_budget_does_not_leak_between_expressions() {
    // The budget is thread-local, so a large-but-legal expression must not
    // leave a later one short. Two rules, each asking for most of it.
    let source = schema_with(
        "xslt2",
        r#"<pattern>
             <rule context="a">
               <assert test="count(1 to 900000) = 900000">first</assert>
               <assert test="count(1 to 900000) = 900000">second</assert>
             </rule>
           </pattern>"#,
    );
    let schema = Schema::from_str(&source).unwrap();
    let document = Document::from_str("<a/>").unwrap();
    let report = schema.validate(&document).expect("both must run");
    assert!(report.is_valid(), "{}", report.to_text());
}