rsconstruct 0.9.122

Rust based fast build system
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
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
//! XSD validation, as `xmllint --schema` does it, for the schema constructs
//! in use: global and local elements, named and anonymous complex types with
//! `sequence`/`choice`/`all` content models, `any`, mixed and simple content,
//! attributes with `use`/`fixed`, `anyAttribute`, simple types restricted by
//! facets, lists and unions, `extension` of simple and complex types, and
//! `include`. A schema using anything else (`group`, `attributeGroup`,
//! `import`, `redefine`, identity constraints, substitution groups, complex
//! `restriction`) is rejected with an error naming the construct: a schema
//! that is only half enforced would pass files xmllint rejects.
//!
//! Messages follow xmllint's wording so a file's report reads the same from
//! either tool.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::Path;
use std::sync::LazyLock;

use anyhow::{Context, Result, bail};
use regex::Regex;

use super::{Child, Element, Kind, Problem, expanded_name};

const XSD_NS: &str = "http://www.w3.org/2001/XMLSchema";
const XSI_NS: &str = "http://www.w3.org/2001/XMLSchema-instance";

/// Type references nested deeper than this are a cycle in the schema.
const MAX_TYPE_DEPTH: usize = 64;

/// A namespace-qualified name.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct QName {
    pub namespace: Option<String>,
    pub local: String,
}

impl QName {
    fn of(element: &Element) -> Self {
        Self {
            namespace: element.namespace.clone(),
            local: element.local.clone(),
        }
    }

    fn expanded(&self) -> String {
        expanded_name(self.namespace.as_deref(), &self.local)
    }
}

/// A compiled schema: the global declarations, by name.
#[derive(Debug, Default)]
pub struct Schema {
    target_namespace: Option<String>,
    elements: HashMap<QName, ElementDecl>,
    attributes: HashMap<QName, AttributeDecl>,
    types: HashMap<QName, Type>,
}

#[derive(Debug, Clone)]
enum Type {
    Simple(SimpleType),
    Complex(ComplexType),
}

#[derive(Debug, Clone)]
enum TypeRef {
    /// `xs:anyType`, and an element with neither a type nor a type child.
    AnyType,
    Named(QName),
    Simple(Box<SimpleType>),
    Complex(Box<ComplexType>),
}

#[derive(Debug, Clone)]
struct ElementDecl {
    name: QName,
    type_ref: TypeRef,
    nillable: bool,
    fixed: Option<String>,
}

#[derive(Debug, Clone)]
struct AttributeDecl {
    name: QName,
    type_ref: SimpleRef,
    fixed: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Use {
    Optional,
    Required,
    Prohibited,
}

#[derive(Debug, Clone)]
enum AttributeSource {
    Local(AttributeDecl),
    Ref(QName),
}

#[derive(Debug, Clone)]
struct AttributeUse {
    source: AttributeSource,
    use_: Use,
}

#[derive(Debug, Clone)]
struct ComplexType {
    mixed: bool,
    content: Content,
    attributes: Vec<AttributeUse>,
    any_attribute: bool,
    /// `complexContent/extension base`: the base's content precedes this
    /// type's, and its attributes are inherited.
    extends: Option<QName>,
}

#[derive(Debug, Clone)]
enum Content {
    Empty,
    Simple(SimpleRef),
    Particle(Particle),
}

#[derive(Debug, Clone)]
struct Particle {
    min: u32,
    /// `None` is `unbounded`.
    max: Option<u32>,
    term: Term,
}

#[derive(Debug, Clone)]
enum Term {
    Element(ElementDecl),
    ElementRef(QName),
    Sequence(Vec<Particle>),
    Choice(Vec<Particle>),
    All(Vec<Particle>),
    Any(Wildcard),
}

#[derive(Debug, Clone)]
struct Wildcard {
    namespace: WildcardNamespace,
    process: ProcessContents,
}

#[derive(Debug, Clone)]
enum WildcardNamespace {
    Any,
    /// `##other`: any namespace but the target one (and not absent).
    Other,
    /// A list of namespaces (`None` is `##local`).
    List(Vec<Option<String>>),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProcessContents {
    Strict,
    Lax,
    Skip,
}

#[derive(Debug, Clone)]
enum SimpleRef {
    Builtin(Builtin),
    Named(QName),
    Inline(Box<SimpleType>),
}

#[derive(Debug, Clone)]
struct SimpleType {
    variety: Variety,
    facets: Facets,
}

#[derive(Debug, Clone)]
enum Variety {
    Restriction(SimpleRef),
    List(SimpleRef),
    Union(Vec<SimpleRef>),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WhiteSpace {
    Preserve,
    Replace,
    Collapse,
}

#[derive(Debug, Clone, Default)]
struct Facets {
    enumeration: Vec<String>,
    /// `(source, compiled)`: the source is for the message.
    patterns: Vec<(String, Regex)>,
    length: Option<usize>,
    min_length: Option<usize>,
    max_length: Option<usize>,
    min_inclusive: Option<f64>,
    max_inclusive: Option<f64>,
    min_exclusive: Option<f64>,
    max_exclusive: Option<f64>,
    total_digits: Option<usize>,
    fraction_digits: Option<usize>,
    white_space: Option<WhiteSpace>,
}

impl Facets {
    /// The facets of a type derived from one with `base` facets: a derived
    /// enumeration or bound replaces the base's, patterns accumulate.
    fn on_top_of(&self, base: &Self) -> Self {
        let mut merged = base.clone();
        if !self.enumeration.is_empty() {
            merged.enumeration.clone_from(&self.enumeration);
        }
        merged.patterns.extend(self.patterns.iter().cloned());
        merged.length = self.length.or(base.length);
        merged.min_length = self.min_length.or(base.min_length);
        merged.max_length = self.max_length.or(base.max_length);
        merged.min_inclusive = self.min_inclusive.or(base.min_inclusive);
        merged.max_inclusive = self.max_inclusive.or(base.max_inclusive);
        merged.min_exclusive = self.min_exclusive.or(base.min_exclusive);
        merged.max_exclusive = self.max_exclusive.or(base.max_exclusive);
        merged.total_digits = self.total_digits.or(base.total_digits);
        merged.fraction_digits = self.fraction_digits.or(base.fraction_digits);
        merged.white_space = self.white_space.or(base.white_space);
        merged
    }
}

/// A simple type with every derivation step folded in.
#[derive(Debug, Clone)]
struct Flat {
    kind: FlatKind,
    facets: Facets,
}

#[derive(Debug, Clone)]
enum FlatKind {
    Atomic(Builtin),
    List(Box<Flat>),
    Union(Vec<Flat>),
}

// ---------------------------------------------------------------------------
// Built-in simple types
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Builtin {
    AnySimpleType,
    String,
    NormalizedString,
    Token,
    Language,
    Name,
    NcName,
    Id,
    IdRef,
    IdRefs,
    Entity,
    Entities,
    NmToken,
    NmTokens,
    Boolean,
    Decimal,
    Integer,
    NonNegativeInteger,
    PositiveInteger,
    NonPositiveInteger,
    NegativeInteger,
    Long,
    Int,
    Short,
    Byte,
    UnsignedLong,
    UnsignedInt,
    UnsignedShort,
    UnsignedByte,
    Float,
    Double,
    AnyUri,
    QName,
    Duration,
    DateTime,
    Date,
    Time,
    GYear,
    GYearMonth,
    GMonth,
    GMonthDay,
    GDay,
    HexBinary,
    Base64Binary,
}

impl Builtin {
    fn from_local(local: &str) -> Option<Self> {
        Some(match local {
            "anySimpleType" => Self::AnySimpleType,
            "string" => Self::String,
            "normalizedString" => Self::NormalizedString,
            "token" => Self::Token,
            "language" => Self::Language,
            "Name" => Self::Name,
            "NCName" => Self::NcName,
            "ID" => Self::Id,
            "IDREF" => Self::IdRef,
            "IDREFS" => Self::IdRefs,
            "ENTITY" => Self::Entity,
            "ENTITIES" => Self::Entities,
            "NMTOKEN" => Self::NmToken,
            "NMTOKENS" => Self::NmTokens,
            "boolean" => Self::Boolean,
            "decimal" => Self::Decimal,
            "integer" => Self::Integer,
            "nonNegativeInteger" => Self::NonNegativeInteger,
            "positiveInteger" => Self::PositiveInteger,
            "nonPositiveInteger" => Self::NonPositiveInteger,
            "negativeInteger" => Self::NegativeInteger,
            "long" => Self::Long,
            "int" => Self::Int,
            "short" => Self::Short,
            "byte" => Self::Byte,
            "unsignedLong" => Self::UnsignedLong,
            "unsignedInt" => Self::UnsignedInt,
            "unsignedShort" => Self::UnsignedShort,
            "unsignedByte" => Self::UnsignedByte,
            "float" => Self::Float,
            "double" => Self::Double,
            "anyURI" => Self::AnyUri,
            "QName" => Self::QName,
            "duration" => Self::Duration,
            "dateTime" => Self::DateTime,
            "date" => Self::Date,
            "time" => Self::Time,
            "gYear" => Self::GYear,
            "gYearMonth" => Self::GYearMonth,
            "gMonth" => Self::GMonth,
            "gMonthDay" => Self::GMonthDay,
            "gDay" => Self::GDay,
            "hexBinary" => Self::HexBinary,
            "base64Binary" => Self::Base64Binary,
            _ => return None,
        })
    }

    /// The type's name as xmllint prints it.
    const fn xs_name(self) -> &'static str {
        match self {
            Self::AnySimpleType => "xs:anySimpleType",
            Self::String => "xs:string",
            Self::NormalizedString => "xs:normalizedString",
            Self::Token => "xs:token",
            Self::Language => "xs:language",
            Self::Name => "xs:Name",
            Self::NcName => "xs:NCName",
            Self::Id => "xs:ID",
            Self::IdRef => "xs:IDREF",
            Self::IdRefs => "xs:IDREFS",
            Self::Entity => "xs:ENTITY",
            Self::Entities => "xs:ENTITIES",
            Self::NmToken => "xs:NMTOKEN",
            Self::NmTokens => "xs:NMTOKENS",
            Self::Boolean => "xs:boolean",
            Self::Decimal => "xs:decimal",
            Self::Integer => "xs:integer",
            Self::NonNegativeInteger => "xs:nonNegativeInteger",
            Self::PositiveInteger => "xs:positiveInteger",
            Self::NonPositiveInteger => "xs:nonPositiveInteger",
            Self::NegativeInteger => "xs:negativeInteger",
            Self::Long => "xs:long",
            Self::Int => "xs:int",
            Self::Short => "xs:short",
            Self::Byte => "xs:byte",
            Self::UnsignedLong => "xs:unsignedLong",
            Self::UnsignedInt => "xs:unsignedInt",
            Self::UnsignedShort => "xs:unsignedShort",
            Self::UnsignedByte => "xs:unsignedByte",
            Self::Float => "xs:float",
            Self::Double => "xs:double",
            Self::AnyUri => "xs:anyURI",
            Self::QName => "xs:QName",
            Self::Duration => "xs:duration",
            Self::DateTime => "xs:dateTime",
            Self::Date => "xs:date",
            Self::Time => "xs:time",
            Self::GYear => "xs:gYear",
            Self::GYearMonth => "xs:gYearMonth",
            Self::GMonth => "xs:gMonth",
            Self::GMonthDay => "xs:gMonthDay",
            Self::GDay => "xs:gDay",
            Self::HexBinary => "xs:hexBinary",
            Self::Base64Binary => "xs:base64Binary",
        }
    }

    const fn white_space(self) -> WhiteSpace {
        match self {
            Self::String | Self::AnySimpleType => WhiteSpace::Preserve,
            Self::NormalizedString => WhiteSpace::Replace,
            _ => WhiteSpace::Collapse,
        }
    }

    /// Whether `value` (already whitespace-normalized) is in the type's
    /// lexical space. `scope` resolves `QName` prefixes.
    fn accepts(self, value: &str, scope: &Element) -> bool {
        match self {
            Self::AnySimpleType
            | Self::String
            | Self::NormalizedString
            | Self::Token
            | Self::AnyUri => true,
            Self::Language => LANGUAGE.is_match(value),
            Self::Name => is_name(value),
            Self::NcName | Self::Id | Self::IdRef | Self::Entity => is_ncname(value),
            Self::IdRefs | Self::Entities => !value.is_empty() && value.split(' ').all(is_ncname),
            Self::NmToken => is_nmtoken(value),
            Self::NmTokens => !value.is_empty() && value.split(' ').all(is_nmtoken),
            Self::Boolean => matches!(value, "true" | "false" | "1" | "0"),
            Self::Decimal => DECIMAL.is_match(value),
            Self::Integer => INTEGER.is_match(value),
            Self::NonNegativeInteger => integer_in(value, 0, i128::MAX),
            Self::PositiveInteger => integer_in(value, 1, i128::MAX),
            Self::NonPositiveInteger => integer_in(value, i128::MIN, 0),
            Self::NegativeInteger => integer_in(value, i128::MIN, -1),
            Self::Long => integer_in(value, i128::from(i64::MIN), i128::from(i64::MAX)),
            Self::Int => integer_in(value, i128::from(i32::MIN), i128::from(i32::MAX)),
            Self::Short => integer_in(value, i128::from(i16::MIN), i128::from(i16::MAX)),
            Self::Byte => integer_in(value, i128::from(i8::MIN), i128::from(i8::MAX)),
            Self::UnsignedLong => integer_in(value, 0, i128::from(u64::MAX)),
            Self::UnsignedInt => integer_in(value, 0, i128::from(u32::MAX)),
            Self::UnsignedShort => integer_in(value, 0, i128::from(u16::MAX)),
            Self::UnsignedByte => integer_in(value, 0, i128::from(u8::MAX)),
            Self::Float | Self::Double => FLOAT.is_match(value),
            Self::QName => match value.split_once(':') {
                Some((prefix, local)) => {
                    is_ncname(prefix) && is_ncname(local) && scope.lookup_prefix(prefix).is_some()
                }
                None => is_ncname(value),
            },
            Self::Duration => {
                DURATION.is_match(value) && value.trim_end_matches('T') != "P" && value != "-P"
            }
            Self::DateTime => DATE_TIME.is_match(value),
            Self::Date => DATE.is_match(value),
            Self::Time => TIME.is_match(value),
            Self::GYear => G_YEAR.is_match(value),
            Self::GYearMonth => G_YEAR_MONTH.is_match(value),
            Self::GMonth => G_MONTH.is_match(value),
            Self::GMonthDay => G_MONTH_DAY.is_match(value),
            Self::GDay => G_DAY.is_match(value),
            Self::HexBinary => HEX_BINARY.is_match(value),
            Self::Base64Binary => {
                let compact: String = value.chars().filter(|c| *c != ' ').collect();
                BASE64.is_match(&compact) && compact.len().is_multiple_of(4)
            }
        }
    }
}

fn integer_in(value: &str, min: i128, max: i128) -> bool {
    INTEGER.is_match(value)
        && value
            .trim_start_matches('+')
            .parse::<i128>()
            .is_ok_and(|n| n >= min && n <= max)
}

fn is_name(value: &str) -> bool {
    use xmlparser::XmlCharExt;
    let mut chars = value.chars();
    chars.next().is_some_and(|c| c.is_xml_name_start()) && chars.all(|c| c.is_xml_name())
}

fn is_ncname(value: &str) -> bool {
    is_name(value) && !value.contains(':')
}

fn is_nmtoken(value: &str) -> bool {
    use xmlparser::XmlCharExt;
    !value.is_empty() && value.chars().all(|c| c.is_xml_name())
}

const TZ: &str = r"(Z|[+-]\d{2}:\d{2})?";

fn anchored(pattern: &str) -> Regex {
    Regex::new(&format!("^(?:{pattern})$")).expect("built-in XSD type regex is valid")
}

static LANGUAGE: LazyLock<Regex> = LazyLock::new(|| anchored(r"[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*"));
static DECIMAL: LazyLock<Regex> = LazyLock::new(|| anchored(r"[+-]?(\d+(\.\d*)?|\.\d+)"));
static INTEGER: LazyLock<Regex> = LazyLock::new(|| anchored(r"[+-]?\d+"));
static FLOAT: LazyLock<Regex> =
    LazyLock::new(|| anchored(r"[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?|[+-]?INF|NaN"));
static DURATION: LazyLock<Regex> =
    LazyLock::new(|| anchored(r"-?P(\d+Y)?(\d+M)?(\d+D)?(T(\d+H)?(\d+M)?(\d+(\.\d+)?S)?)?"));
static DATE_TIME: LazyLock<Regex> = LazyLock::new(|| {
    anchored(&format!(
        r"-?\d{{4,}}-\d{{2}}-\d{{2}}T\d{{2}}:\d{{2}}:\d{{2}}(\.\d+)?{TZ}"
    ))
});
static DATE: LazyLock<Regex> =
    LazyLock::new(|| anchored(&format!(r"-?\d{{4,}}-\d{{2}}-\d{{2}}{TZ}")));
static TIME: LazyLock<Regex> =
    LazyLock::new(|| anchored(&format!(r"\d{{2}}:\d{{2}}:\d{{2}}(\.\d+)?{TZ}")));
static G_YEAR: LazyLock<Regex> = LazyLock::new(|| anchored(&format!(r"-?\d{{4,}}{TZ}")));
static G_YEAR_MONTH: LazyLock<Regex> =
    LazyLock::new(|| anchored(&format!(r"-?\d{{4,}}-\d{{2}}{TZ}")));
static G_MONTH: LazyLock<Regex> = LazyLock::new(|| anchored(&format!(r"--\d{{2}}{TZ}")));
static G_MONTH_DAY: LazyLock<Regex> =
    LazyLock::new(|| anchored(&format!(r"--\d{{2}}-\d{{2}}{TZ}")));
static G_DAY: LazyLock<Regex> = LazyLock::new(|| anchored(&format!(r"---\d{{2}}{TZ}")));
static HEX_BINARY: LazyLock<Regex> = LazyLock::new(|| anchored(r"([0-9a-fA-F]{2})*"));
static BASE64: LazyLock<Regex> = LazyLock::new(|| anchored(r"[A-Za-z0-9+/]*={0,2}"));

// ---------------------------------------------------------------------------
// Loading a schema
// ---------------------------------------------------------------------------

/// Reads schema documents: the one named plus whatever it `include`s.
struct Loader<'a> {
    schema: &'a mut Schema,
    /// The file being read, for messages.
    path: String,
    element_form_qualified: bool,
    attribute_form_qualified: bool,
}

impl Schema {
    /// Compiles the schema in `path`, a well-formed XSD document.
    pub fn from_file(path: &Path) -> Result<Self> {
        let mut schema = Self::default();
        schema.load(path, true)?;
        Ok(schema)
    }

    fn load(&mut self, path: &Path, first: bool) -> Result<()> {
        let bytes = std::fs::read(path)
            .with_context(|| format!("Failed to read XSD schema {}", path.display()))?;
        let document = super::parse(&bytes);
        if let Some(problem) = document.problems.iter().find(|p| p.kind.is_fatal()) {
            bail!("{}:{problem}", path.display());
        }
        let Some(root) = document.root else {
            bail!("{}: no root element", path.display());
        };
        if root.namespace.as_deref() != Some(XSD_NS) || root.local != "schema" {
            bail!(
                "{}: not an XML Schema: the root element is '{}', not '{{{XSD_NS}}}schema'",
                path.display(),
                root.expanded_name()
            );
        }
        let target = attr(&root, "targetNamespace").map(str::to_string);
        if first {
            self.target_namespace = target;
        } else if target.is_some() && target != self.target_namespace {
            bail!(
                "{}: included schema has target namespace {:?}, the including one {:?}",
                path.display(),
                target,
                self.target_namespace
            );
        }
        let mut loader = Loader {
            schema: self,
            path: path.display().to_string(),
            element_form_qualified: attr(&root, "elementFormDefault") == Some("qualified"),
            attribute_form_qualified: attr(&root, "attributeFormDefault") == Some("qualified"),
        };
        let includes = loader.schema_children(&root)?;
        for include in includes {
            let include_path = path.parent().map_or_else(
                || Path::new(&include).to_path_buf(),
                |dir| dir.join(&include),
            );
            self.load(&include_path, false)?;
        }
        Ok(())
    }
}

/// The value of an unqualified attribute.
fn attr<'e>(element: &'e Element, local: &str) -> Option<&'e str> {
    element.attribute(None, local).map(|a| a.value.as_str())
}

impl Loader<'_> {
    fn unsupported(&self, element: &Element, what: &str) -> anyhow::Error {
        anyhow::anyhow!(
            "{}:{}: unsupported XSD construct: {what}. ixmllint implements the schema \
             constructs in use across the fleet; keep this file on xmllint or extend \
             src/engines/xmllint/xsd.rs",
            self.path,
            element.line
        )
    }

    fn xsd_children<'e>(&self, element: &'e Element) -> Vec<&'e Element> {
        element
            .child_elements()
            .filter(|c| c.namespace.as_deref() == Some(XSD_NS) && c.local != "annotation")
            .collect()
    }

    /// Resolves a `QName` written in an attribute value, in the element's
    /// namespace scope. An unprefixed name is in the default namespace,
    /// which for schema documents is usually the target namespace or none.
    fn qname(&self, element: &Element, value: &str) -> Result<QName> {
        let (prefix, local) = value.split_once(':').unwrap_or(("", value));
        let namespace = match element.lookup_prefix(prefix) {
            Some(uri) => Some(uri.to_string()),
            None if prefix.is_empty() => None,
            None => bail!(
                "{}:{}: undeclared namespace prefix in '{value}'",
                self.path,
                element.line
            ),
        };
        Ok(QName {
            namespace,
            local: local.to_string(),
        })
    }

    /// The `xs:schema` children; returns the `include`d schema locations.
    fn schema_children(&mut self, root: &Element) -> Result<Vec<String>> {
        let mut includes = Vec::new();
        for child in self.xsd_children(root) {
            match child.local.as_str() {
                "element" => {
                    let decl = self.element_decl(child, true)?;
                    self.schema.elements.insert(decl.name.clone(), decl);
                }
                "attribute" => {
                    let decl = self.attribute_decl(child, true)?;
                    self.schema.attributes.insert(decl.name.clone(), decl);
                }
                "complexType" => {
                    let name = self.required(child, "name")?;
                    let ty = self.complex_type(child)?;
                    self.schema
                        .types
                        .insert(self.target_qname(name), Type::Complex(ty));
                }
                "simpleType" => {
                    let name = self.required(child, "name")?;
                    let ty = self.simple_type(child)?;
                    self.schema
                        .types
                        .insert(self.target_qname(name), Type::Simple(ty));
                }
                "include" => includes.push(self.required(child, "schemaLocation")?.to_string()),
                "import" => return Err(self.unsupported(child, "xs:import")),
                other => return Err(self.unsupported(child, &format!("xs:{other}"))),
            }
        }
        Ok(includes)
    }

    fn required<'e>(&self, element: &'e Element, name: &str) -> Result<&'e str> {
        attr(element, name).ok_or_else(|| {
            anyhow::anyhow!(
                "{}:{}: xs:{} lacks the '{name}' attribute",
                self.path,
                element.line,
                element.local
            )
        })
    }

    fn target_qname(&self, local: &str) -> QName {
        QName {
            namespace: self.schema.target_namespace.clone(),
            local: local.to_string(),
        }
    }

    fn occurs(&self, element: &Element) -> Result<(u32, Option<u32>)> {
        let min = match attr(element, "minOccurs") {
            None => 1,
            Some(v) => v
                .parse()
                .with_context(|| format!("{}:{}: bad minOccurs {v:?}", self.path, element.line))?,
        };
        let max =
            match attr(element, "maxOccurs") {
                None => Some(1),
                Some("unbounded") => None,
                Some(v) => Some(v.parse().with_context(|| {
                    format!("{}:{}: bad maxOccurs {v:?}", self.path, element.line)
                })?),
            };
        Ok((min, max))
    }

    fn element_decl(&self, element: &Element, global: bool) -> Result<ElementDecl> {
        for forbidden in ["abstract", "substitutionGroup"] {
            if attr(element, forbidden).is_some() {
                return Err(self.unsupported(element, &format!("xs:element {forbidden}")));
            }
        }
        let name = self.required(element, "name")?;
        let qualified = global
            || match attr(element, "form") {
                Some(form) => form == "qualified",
                None => self.element_form_qualified,
            };
        let name = QName {
            namespace: if qualified {
                self.schema.target_namespace.clone()
            } else {
                None
            },
            local: name.to_string(),
        };
        let mut type_ref = match attr(element, "type") {
            Some(type_name) => self.type_ref(element, type_name)?,
            None => TypeRef::AnyType,
        };
        for child in self.xsd_children(element) {
            match child.local.as_str() {
                "complexType" => type_ref = TypeRef::Complex(Box::new(self.complex_type(child)?)),
                "simpleType" => type_ref = TypeRef::Simple(Box::new(self.simple_type(child)?)),
                other => return Err(self.unsupported(child, &format!("xs:{other} in xs:element"))),
            }
        }
        Ok(ElementDecl {
            name,
            type_ref,
            nillable: matches!(attr(element, "nillable"), Some("true" | "1")),
            fixed: attr(element, "fixed").map(str::to_string),
        })
    }

    fn type_ref(&self, element: &Element, type_name: &str) -> Result<TypeRef> {
        let qname = self.qname(element, type_name)?;
        if qname.namespace.as_deref() == Some(XSD_NS) {
            if qname.local == "anyType" {
                return Ok(TypeRef::AnyType);
            }
            return match Builtin::from_local(&qname.local) {
                Some(builtin) => Ok(TypeRef::Simple(Box::new(SimpleType {
                    variety: Variety::Restriction(SimpleRef::Builtin(builtin)),
                    facets: Facets::default(),
                }))),
                None => {
                    Err(self.unsupported(element, &format!("built-in type xs:{}", qname.local)))
                }
            };
        }
        Ok(TypeRef::Named(qname))
    }

    fn simple_ref(&self, element: &Element, type_name: &str) -> Result<SimpleRef> {
        let qname = self.qname(element, type_name)?;
        if qname.namespace.as_deref() == Some(XSD_NS) {
            return match Builtin::from_local(&qname.local) {
                Some(builtin) => Ok(SimpleRef::Builtin(builtin)),
                None => {
                    Err(self.unsupported(element, &format!("built-in type xs:{}", qname.local)))
                }
            };
        }
        Ok(SimpleRef::Named(qname))
    }

    fn attribute_decl(&self, element: &Element, global: bool) -> Result<AttributeDecl> {
        let name = self.required(element, "name")?;
        let qualified = global
            || match attr(element, "form") {
                Some(form) => form == "qualified",
                None => self.attribute_form_qualified,
            };
        let mut type_ref = match attr(element, "type") {
            Some(type_name) => self.simple_ref(element, type_name)?,
            None => SimpleRef::Builtin(Builtin::AnySimpleType),
        };
        for child in self.xsd_children(element) {
            match child.local.as_str() {
                "simpleType" => type_ref = SimpleRef::Inline(Box::new(self.simple_type(child)?)),
                other => {
                    return Err(self.unsupported(child, &format!("xs:{other} in xs:attribute")));
                }
            }
        }
        Ok(AttributeDecl {
            name: QName {
                namespace: if qualified {
                    self.schema.target_namespace.clone()
                } else {
                    None
                },
                local: name.to_string(),
            },
            type_ref,
            fixed: attr(element, "fixed").map(str::to_string),
        })
    }

    fn attribute_use(&self, element: &Element) -> Result<AttributeUse> {
        let use_ = match attr(element, "use") {
            None | Some("optional") => Use::Optional,
            Some("required") => Use::Required,
            Some("prohibited") => Use::Prohibited,
            Some(other) => bail!(
                "{}:{}: bad attribute use {other:?}",
                self.path,
                element.line
            ),
        };
        let source = match attr(element, "ref") {
            Some(reference) => AttributeSource::Ref(self.qname(element, reference)?),
            None => AttributeSource::Local(self.attribute_decl(element, false)?),
        };
        Ok(AttributeUse { source, use_ })
    }

    fn complex_type(&self, element: &Element) -> Result<ComplexType> {
        if attr(element, "abstract") == Some("true") {
            return Err(self.unsupported(element, "xs:complexType abstract"));
        }
        let mut ty = ComplexType {
            mixed: matches!(attr(element, "mixed"), Some("true" | "1")),
            content: Content::Empty,
            attributes: Vec::new(),
            any_attribute: false,
            extends: None,
        };
        for child in self.xsd_children(element) {
            match child.local.as_str() {
                "sequence" | "choice" | "all" => {
                    ty.content = Content::Particle(self.particle(child)?);
                }
                "attribute" => ty.attributes.push(self.attribute_use(child)?),
                "anyAttribute" => ty.any_attribute = true,
                "simpleContent" => self.simple_content(child, &mut ty)?,
                "complexContent" => self.complex_content(child, &mut ty)?,
                other => {
                    return Err(self.unsupported(child, &format!("xs:{other} in xs:complexType")));
                }
            }
        }
        Ok(ty)
    }

    fn simple_content(&self, element: &Element, ty: &mut ComplexType) -> Result<()> {
        for child in self.xsd_children(element) {
            match child.local.as_str() {
                "extension" => {
                    let base = self.required(child, "base")?;
                    ty.content = Content::Simple(self.simple_ref(child, base)?);
                    self.attributes_of(child, ty)?;
                }
                other => {
                    return Err(self.unsupported(child, &format!("xs:{other} in xs:simpleContent")));
                }
            }
        }
        Ok(())
    }

    fn complex_content(&self, element: &Element, ty: &mut ComplexType) -> Result<()> {
        if matches!(attr(element, "mixed"), Some("true" | "1")) {
            ty.mixed = true;
        }
        for child in self.xsd_children(element) {
            match child.local.as_str() {
                "extension" => {
                    let base = self.required(child, "base")?;
                    let base = self.qname(child, base)?;
                    if base.namespace.as_deref() == Some(XSD_NS) {
                        if base.local != "anyType" {
                            return Err(
                                self.unsupported(child, &format!("extension of xs:{}", base.local))
                            );
                        }
                    } else {
                        ty.extends = Some(base);
                    }
                    for part in self.xsd_children(child) {
                        match part.local.as_str() {
                            "sequence" | "choice" | "all" => {
                                ty.content = Content::Particle(self.particle(part)?);
                            }
                            "attribute" => ty.attributes.push(self.attribute_use(part)?),
                            "anyAttribute" => ty.any_attribute = true,
                            other => {
                                return Err(
                                    self.unsupported(part, &format!("xs:{other} in xs:extension"))
                                );
                            }
                        }
                    }
                }
                other => {
                    return Err(
                        self.unsupported(child, &format!("xs:{other} in xs:complexContent"))
                    );
                }
            }
        }
        Ok(())
    }

    /// `attribute`/`anyAttribute` children of an extension.
    fn attributes_of(&self, element: &Element, ty: &mut ComplexType) -> Result<()> {
        for child in self.xsd_children(element) {
            match child.local.as_str() {
                "attribute" => ty.attributes.push(self.attribute_use(child)?),
                "anyAttribute" => ty.any_attribute = true,
                other => {
                    return Err(self.unsupported(child, &format!("xs:{other} in xs:extension")));
                }
            }
        }
        Ok(())
    }

    /// A `sequence`, `choice`, `all`, `element` or `any` as a particle.
    fn particle(&self, element: &Element) -> Result<Particle> {
        let (min, max) = self.occurs(element)?;
        let term = match element.local.as_str() {
            "sequence" => Term::Sequence(self.particles(element)?),
            "choice" => Term::Choice(self.particles(element)?),
            "all" => Term::All(self.particles(element)?),
            "element" => match attr(element, "ref") {
                Some(reference) => Term::ElementRef(self.qname(element, reference)?),
                None => Term::Element(self.element_decl(element, false)?),
            },
            "any" => Term::Any(self.wildcard(element)?),
            other => return Err(self.unsupported(element, &format!("xs:{other} as a particle"))),
        };
        Ok(Particle { min, max, term })
    }

    fn particles(&self, element: &Element) -> Result<Vec<Particle>> {
        self.xsd_children(element)
            .into_iter()
            .map(|child| self.particle(child))
            .collect()
    }

    fn wildcard(&self, element: &Element) -> Result<Wildcard> {
        let namespace = match attr(element, "namespace") {
            None | Some("##any") => WildcardNamespace::Any,
            Some("##other") => WildcardNamespace::Other,
            Some(list) => WildcardNamespace::List(
                list.split_whitespace()
                    .map(|item| match item {
                        "##local" => None,
                        "##targetNamespace" => self.schema.target_namespace.clone(),
                        uri => Some(uri.to_string()),
                    })
                    .collect(),
            ),
        };
        let process = match attr(element, "processContents") {
            None | Some("strict") => ProcessContents::Strict,
            Some("lax") => ProcessContents::Lax,
            Some("skip") => ProcessContents::Skip,
            Some(other) => bail!(
                "{}:{}: bad processContents {other:?}",
                self.path,
                element.line
            ),
        };
        Ok(Wildcard { namespace, process })
    }

    fn simple_type(&self, element: &Element) -> Result<SimpleType> {
        let children = self.xsd_children(element);
        let [derivation] = children.as_slice() else {
            bail!(
                "{}:{}: xs:simpleType needs exactly one of restriction, list or union",
                self.path,
                element.line
            );
        };
        match derivation.local.as_str() {
            "restriction" => {
                let mut facets = Facets::default();
                let mut base = match attr(derivation, "base") {
                    Some(base) => Some(self.simple_ref(derivation, base)?),
                    None => None,
                };
                for facet in self.xsd_children(derivation) {
                    if facet.local == "simpleType" {
                        base = Some(SimpleRef::Inline(Box::new(self.simple_type(facet)?)));
                    } else {
                        self.facet(facet, &mut facets)?;
                    }
                }
                let Some(base) = base else {
                    bail!(
                        "{}:{}: xs:restriction without a base",
                        self.path,
                        derivation.line
                    );
                };
                Ok(SimpleType {
                    variety: Variety::Restriction(base),
                    facets,
                })
            }
            "list" => {
                let item = match attr(derivation, "itemType") {
                    Some(item) => self.simple_ref(derivation, item)?,
                    None => match self.xsd_children(derivation).as_slice() {
                        [inline] if inline.local == "simpleType" => {
                            SimpleRef::Inline(Box::new(self.simple_type(inline)?))
                        }
                        _ => bail!(
                            "{}:{}: xs:list without an item type",
                            self.path,
                            derivation.line
                        ),
                    },
                };
                Ok(SimpleType {
                    variety: Variety::List(item),
                    facets: Facets::default(),
                })
            }
            "union" => {
                let mut members = Vec::new();
                if let Some(names) = attr(derivation, "memberTypes") {
                    for name in names.split_whitespace() {
                        members.push(self.simple_ref(derivation, name)?);
                    }
                }
                for inline in self.xsd_children(derivation) {
                    if inline.local != "simpleType" {
                        return Err(
                            self.unsupported(inline, &format!("xs:{} in xs:union", inline.local))
                        );
                    }
                    members.push(SimpleRef::Inline(Box::new(self.simple_type(inline)?)));
                }
                if members.is_empty() {
                    bail!(
                        "{}:{}: xs:union without member types",
                        self.path,
                        derivation.line
                    );
                }
                Ok(SimpleType {
                    variety: Variety::Union(members),
                    facets: Facets::default(),
                })
            }
            other => Err(self.unsupported(derivation, &format!("xs:{other} in xs:simpleType"))),
        }
    }

    fn facet(&self, facet: &Element, facets: &mut Facets) -> Result<()> {
        let value = self.required(facet, "value")?;
        let number = |what: &str| -> Result<usize> {
            value.parse().with_context(|| {
                format!("{}:{}: bad {what} value {value:?}", self.path, facet.line)
            })
        };
        let float = |what: &str| -> Result<f64> {
            value.parse().with_context(|| {
                format!("{}:{}: bad {what} value {value:?}", self.path, facet.line)
            })
        };
        match facet.local.as_str() {
            "enumeration" => facets.enumeration.push(value.to_string()),
            "pattern" => {
                let regex = Regex::new(&format!("^(?:{value})$")).with_context(|| {
                    format!(
                        "{}:{}: pattern {value:?} is not a supported regex",
                        self.path, facet.line
                    )
                })?;
                facets.patterns.push((value.to_string(), regex));
            }
            "length" => facets.length = Some(number("length")?),
            "minLength" => facets.min_length = Some(number("minLength")?),
            "maxLength" => facets.max_length = Some(number("maxLength")?),
            "minInclusive" => facets.min_inclusive = Some(float("minInclusive")?),
            "maxInclusive" => facets.max_inclusive = Some(float("maxInclusive")?),
            "minExclusive" => facets.min_exclusive = Some(float("minExclusive")?),
            "maxExclusive" => facets.max_exclusive = Some(float("maxExclusive")?),
            "totalDigits" => facets.total_digits = Some(number("totalDigits")?),
            "fractionDigits" => facets.fraction_digits = Some(number("fractionDigits")?),
            "whiteSpace" => {
                facets.white_space = Some(match value {
                    "preserve" => WhiteSpace::Preserve,
                    "replace" => WhiteSpace::Replace,
                    "collapse" => WhiteSpace::Collapse,
                    other => bail!(
                        "{}:{}: bad whiteSpace value {other:?}",
                        self.path,
                        facet.line
                    ),
                });
            }
            other => return Err(self.unsupported(facet, &format!("facet xs:{other}"))),
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------

/// What the content-model matcher saw: how far into the children it got and
/// which element names it was prepared to accept at each position, in the
/// order they were tried (the schema's order, which is how xmllint lists
/// them). That is what the "not expected / expected is" message is built
/// from.
#[derive(Default)]
struct Trace {
    furthest: usize,
    expected: BTreeMap<usize, Vec<String>>,
}

impl Trace {
    fn expect(&mut self, position: usize, name: String) {
        let names = self.expected.entry(position).or_default();
        if !names.contains(&name) {
            names.push(name);
        }
    }
}

struct Validator<'s> {
    schema: &'s Schema,
    problems: Vec<Problem>,
}

pub(super) fn validate(root: &Element, schema: &Schema) -> Result<Vec<Problem>> {
    let mut validator = Validator {
        schema,
        problems: Vec::new(),
    };
    match schema.elements.get(&QName::of(root)) {
        Some(decl) => validator.element(root, decl)?,
        None => validator.problem(
            root,
            format!(
                "Element '{}': No matching global declaration available for the validation root.",
                root.expanded_name()
            ),
        ),
    }
    Ok(validator.problems)
}

impl Validator<'_> {
    fn problem(&mut self, element: &Element, message: String) {
        self.problems.push(Problem {
            line: element.end_line,
            kind: Kind::SchemaError,
            message,
        });
    }

    fn named_type(&self, name: &QName) -> Result<&Type> {
        self.schema.types.get(name).ok_or_else(|| {
            anyhow::anyhow!("schema refers to the undefined type '{}'", name.expanded())
        })
    }

    fn element(&mut self, element: &Element, decl: &ElementDecl) -> Result<()> {
        let shown = element.expanded_name();
        if element.attribute(Some(XSI_NS), "type").is_some() {
            self.problem(
                element,
                format!("Element '{shown}': xsi:type is not supported by ixmllint."),
            );
            return Ok(());
        }
        if let Some(nil) = element.attribute(Some(XSI_NS), "nil") {
            if !decl.nillable {
                self.problem(
                    element,
                    format!(
                        "Element '{shown}', attribute '{{{XSI_NS}}}nil': The element is not 'nillable'."
                    ),
                );
            } else if matches!(nil.value.as_str(), "true" | "1") {
                if !element
                    .children
                    .iter()
                    .all(|c| matches!(c, Child::Text(t) if t.trim().is_empty()))
                {
                    self.problem(
                        element,
                        format!("Element '{shown}': The content must be empty since it's nilled."),
                    );
                }
                return Ok(());
            }
        }
        let fixed = decl.fixed.as_deref();
        match &decl.type_ref {
            TypeRef::AnyType => self.lax_children(element),
            TypeRef::Named(name) => match self.named_type(name)?.clone() {
                Type::Simple(simple) => self.simple_element(element, &simple, fixed),
                Type::Complex(complex) => self.complex_element(element, &complex, fixed),
            },
            TypeRef::Simple(simple) => self.simple_element(element, simple, fixed),
            TypeRef::Complex(complex) => self.complex_element(element, complex, fixed),
        }
    }

    /// Children of an `anyType` element or a lax wildcard: validated when a
    /// global declaration exists, accepted otherwise.
    fn lax_children(&mut self, element: &Element) -> Result<()> {
        for child in element.child_elements() {
            if let Some(decl) = self.schema.elements.get(&QName::of(child)) {
                self.element(child, decl)?;
            } else {
                self.lax_children(child)?;
            }
        }
        Ok(())
    }

    fn simple_element(
        &mut self,
        element: &Element,
        simple: &SimpleType,
        fixed: Option<&str>,
    ) -> Result<()> {
        let shown = element.expanded_name();
        if let Some(child) = element.child_elements().next() {
            self.problem(
                child,
                format!(
                    "Element '{shown}': Element content is not allowed, because the content type is a simple type definition."
                ),
            );
        }
        for attribute in &element.attributes {
            if attribute.namespace.as_deref() != Some(XSI_NS) {
                let name = expanded_name(attribute.namespace.as_deref(), &attribute.local);
                self.problem(
                    element,
                    format!("Element '{shown}', attribute '{name}': The attribute '{name}' is not allowed."),
                );
            }
        }
        let flat = self.flatten(&SimpleRef::Inline(Box::new(simple.clone())), 0)?;
        self.text_value(element, &flat, fixed);
        Ok(())
    }

    /// Checks an element's text against a simple type.
    fn text_value(&mut self, element: &Element, flat: &Flat, fixed: Option<&str>) {
        let shown = element.expanded_name();
        let text = element.text();
        match check_value(flat, &text, element) {
            Ok(normalized) => {
                if let Some(fixed) = fixed
                    && normalized != fixed
                {
                    self.problem(
                        element,
                        format!(
                            "Element '{shown}': The value '{normalized}' does not match the fixed value constraint '{fixed}'."
                        ),
                    );
                }
            }
            Err(message) => self.problem(element, format!("Element '{shown}': {message}")),
        }
    }

    fn complex_element(
        &mut self,
        element: &Element,
        complex: &ComplexType,
        fixed: Option<&str>,
    ) -> Result<()> {
        let complex = self.effective(complex, 0)?;
        self.attributes(element, &complex)?;
        let shown = element.expanded_name();
        let has_text = element
            .children
            .iter()
            .any(|c| matches!(c, Child::Text(t) if !t.trim().is_empty()));
        match &complex.content {
            Content::Empty => {
                if let Some(child) = element.child_elements().next() {
                    self.problem(
                        child,
                        format!(
                            "Element '{shown}': Element content is not allowed, because the content type is empty."
                        ),
                    );
                }
                if has_text {
                    self.problem(
                        element,
                        format!(
                            "Element '{shown}': Character content is not allowed, because the content type is empty."
                        ),
                    );
                }
            }
            Content::Simple(simple) => {
                if let Some(child) = element.child_elements().next() {
                    self.problem(
                        child,
                        format!(
                            "Element '{shown}': Element content is not allowed, because the content type is a simple type definition."
                        ),
                    );
                }
                let flat = self.flatten(simple, 0)?;
                self.text_value(element, &flat, fixed);
            }
            Content::Particle(particle) => {
                if has_text && !complex.mixed {
                    self.problem(
                        element,
                        format!(
                            "Element '{shown}': Character content other than whitespace is not allowed because the content type is 'element-only'."
                        ),
                    );
                }
                self.content_model(element, particle)?;
            }
        }
        Ok(())
    }

    /// A complex type with its `extension` bases folded in: base content
    /// first, then its own; attributes of both.
    fn effective(&self, complex: &ComplexType, depth: usize) -> Result<ComplexType> {
        let Some(base_name) = &complex.extends else {
            return Ok(complex.clone());
        };
        if depth > MAX_TYPE_DEPTH {
            bail!("schema type '{}' extends itself", base_name.expanded());
        }
        let Type::Complex(base) = self.named_type(base_name)? else {
            bail!(
                "schema type '{}' is extended as a complex type but is a simple type",
                base_name.expanded()
            );
        };
        let base = self.effective(base, depth + 1)?;
        let content = match (base.content, complex.content.clone()) {
            (Content::Particle(b), Content::Particle(own)) => Content::Particle(Particle {
                min: 1,
                max: Some(1),
                term: Term::Sequence(vec![b, own]),
            }),
            (Content::Empty, own) | (own, Content::Empty) => own,
            (Content::Simple(_), own @ Content::Simple(_)) => own,
            (Content::Simple(_), Content::Particle(_))
            | (Content::Particle(_), Content::Simple(_)) => {
                bail!(
                    "schema type extending '{}' mixes simple and element content",
                    base_name.expanded()
                )
            }
        };
        let mut attributes = base.attributes;
        attributes.extend(complex.attributes.iter().cloned());
        Ok(ComplexType {
            mixed: complex.mixed || base.mixed,
            content,
            attributes,
            any_attribute: complex.any_attribute || base.any_attribute,
            extends: None,
        })
    }

    fn attributes(&mut self, element: &Element, complex: &ComplexType) -> Result<()> {
        let shown = element.expanded_name();
        let mut uses: Vec<(AttributeDecl, Use)> = Vec::new();
        for use_ in &complex.attributes {
            let decl = match &use_.source {
                AttributeSource::Local(decl) => decl.clone(),
                AttributeSource::Ref(name) => {
                    self.schema.attributes.get(name).cloned().ok_or_else(|| {
                        anyhow::anyhow!(
                            "schema refers to the undefined attribute '{}'",
                            name.expanded()
                        )
                    })?
                }
            };
            uses.push((decl, use_.use_));
        }
        for attribute in &element.attributes {
            if attribute.namespace.as_deref() == Some(XSI_NS) {
                continue;
            }
            let name = QName {
                namespace: attribute.namespace.clone(),
                local: attribute.local.clone(),
            };
            let shown_attr = name.expanded();
            match uses.iter().find(|(decl, _)| decl.name == name) {
                None if complex.any_attribute => {}
                None | Some((_, Use::Prohibited)) => self.problem(
                    element,
                    format!(
                        "Element '{shown}', attribute '{shown_attr}': The attribute '{shown_attr}' is not allowed."
                    ),
                ),
                Some((decl, _)) => {
                    let flat = self.flatten(&decl.type_ref, 0)?;
                    match check_value(&flat, &attribute.value, element) {
                        Ok(normalized) => {
                            if let Some(fixed) = &decl.fixed
                                && &normalized != fixed
                            {
                                self.problem(
                                    element,
                                    format!(
                                        "Element '{shown}', attribute '{shown_attr}': The value '{normalized}' does not match the fixed value constraint '{fixed}'."
                                    ),
                                );
                            }
                        }
                        Err(message) => self.problem(
                            element,
                            format!("Element '{shown}', attribute '{shown_attr}': {message}"),
                        ),
                    }
                }
            }
        }
        for (decl, use_) in &uses {
            if *use_ == Use::Required
                && element
                    .attribute(decl.name.namespace.as_deref(), &decl.name.local)
                    .is_none()
            {
                self.problem(
                    element,
                    format!(
                        "Element '{shown}': The attribute '{}' is required but missing.",
                        decl.name.expanded()
                    ),
                );
            }
        }
        Ok(())
    }

    /// Matches the child elements against the content model, reports the
    /// first child that does not fit (or what is missing), then validates
    /// each child against the declaration the model gives its name.
    fn content_model(&mut self, element: &Element, particle: &Particle) -> Result<()> {
        let children: Vec<&Element> = element.child_elements().collect();
        let names: Vec<QName> = children.iter().map(|c| QName::of(c)).collect();
        let mut trace = Trace::default();
        let ends = self.particle_ends(particle, &names, 0, &mut trace)?;
        if !ends.contains(&names.len()) {
            let expected = trace
                .expected
                .get(&trace.furthest)
                .cloned()
                .unwrap_or_default();
            let expected_text = match expected.len() {
                0 => String::new(),
                1 => format!(" Expected is ( {} ).", expected[0]),
                _ => format!(" Expected is one of ( {} ).", expected.join(", ")),
            };
            match children.get(trace.furthest) {
                Some(child) => self.problem(
                    child,
                    format!(
                        "Element '{}': This element is not expected.{expected_text}",
                        child.expanded_name()
                    ),
                ),
                None => self.problem(
                    element,
                    format!(
                        "Element '{}': Missing child element(s).{expected_text}",
                        element.expanded_name()
                    ),
                ),
            }
        }
        let mut decls: HashMap<QName, ElementDecl> = HashMap::new();
        let mut wildcards: Vec<Wildcard> = Vec::new();
        self.collect_decls(&particle.term, &mut decls, &mut wildcards)?;
        for child in children {
            let name = QName::of(child);
            if let Some(decl) = decls.get(&name) {
                self.element(child, decl)?;
                continue;
            }
            let Some(wildcard) = wildcards.iter().find(|w| w.admits(&name, self.schema)) else {
                continue; // already reported as not expected
            };
            match wildcard.process {
                ProcessContents::Skip => {}
                ProcessContents::Lax => self.lax_children_or_self(child)?,
                ProcessContents::Strict => match self.schema.elements.get(&name) {
                    Some(decl) => self.element(child, decl)?,
                    None => self.problem(
                        child,
                        format!(
                            "Element '{}': No matching global element declaration available, but demanded by the strict wildcard.",
                            child.expanded_name()
                        ),
                    ),
                },
            }
        }
        Ok(())
    }

    fn lax_children_or_self(&mut self, element: &Element) -> Result<()> {
        match self.schema.elements.get(&QName::of(element)) {
            Some(decl) => self.element(element, decl),
            None => self.lax_children(element),
        }
    }

    /// Every element declaration a content model can match, by name. XSD's
    /// "element declarations consistent" rule makes the name decisive.
    fn collect_decls(
        &self,
        term: &Term,
        decls: &mut HashMap<QName, ElementDecl>,
        wildcards: &mut Vec<Wildcard>,
    ) -> Result<()> {
        match term {
            Term::Element(decl) => {
                decls
                    .entry(decl.name.clone())
                    .or_insert_with(|| decl.clone());
            }
            Term::ElementRef(name) => {
                let decl = self.global_element(name)?;
                decls
                    .entry(decl.name.clone())
                    .or_insert_with(|| decl.clone());
            }
            Term::Sequence(parts) | Term::Choice(parts) | Term::All(parts) => {
                for part in parts {
                    self.collect_decls(&part.term, decls, wildcards)?;
                }
            }
            Term::Any(wildcard) => wildcards.push(wildcard.clone()),
        }
        Ok(())
    }

    fn global_element(&self, name: &QName) -> Result<&ElementDecl> {
        self.schema.elements.get(name).ok_or_else(|| {
            anyhow::anyhow!(
                "schema refers to the undefined element '{}'",
                name.expanded()
            )
        })
    }

    /// The positions a particle can end at when it starts matching `names`
    /// at `start`.
    fn particle_ends(
        &self,
        particle: &Particle,
        names: &[QName],
        start: usize,
        trace: &mut Trace,
    ) -> Result<BTreeSet<usize>> {
        let mut results = BTreeSet::new();
        let mut frontier: BTreeSet<usize> = BTreeSet::from([start]);
        let mut count: u32 = 0;
        loop {
            if count >= particle.min {
                results.extend(frontier.iter().copied());
            }
            if particle.max.is_some_and(|max| count >= max) {
                break;
            }
            let mut next = BTreeSet::new();
            for &position in &frontier {
                next.extend(self.term_ends(&particle.term, names, position, trace)?);
            }
            if next.is_empty() {
                break;
            }
            count += 1;
            if next.is_subset(&frontier) {
                // Only empty matches are left; they can repeat to any
                // minimum, so these positions are final.
                results.extend(next.iter().copied());
                break;
            }
            frontier = next;
        }
        Ok(results)
    }

    fn term_ends(
        &self,
        term: &Term,
        names: &[QName],
        position: usize,
        trace: &mut Trace,
    ) -> Result<BTreeSet<usize>> {
        Ok(match term {
            Term::Element(decl) => self.element_step(&decl.name, names, position, trace),
            Term::ElementRef(name) => {
                let decl = self.global_element(name)?;
                self.element_step(&decl.name, names, position, trace)
            }
            Term::Any(wildcard) => {
                trace.expect(position, "##any".to_string());
                match names.get(position) {
                    Some(name) if wildcard.admits(name, self.schema) => {
                        trace.furthest = trace.furthest.max(position + 1);
                        BTreeSet::from([position + 1])
                    }
                    _ => BTreeSet::new(),
                }
            }
            Term::Sequence(parts) => {
                let mut frontier = BTreeSet::from([position]);
                for part in parts {
                    let mut next = BTreeSet::new();
                    for &p in &frontier {
                        next.extend(self.particle_ends(part, names, p, trace)?);
                    }
                    if next.is_empty() {
                        return Ok(next);
                    }
                    frontier = next;
                }
                frontier
            }
            Term::Choice(parts) => {
                let mut ends = BTreeSet::new();
                for part in parts {
                    ends.extend(self.particle_ends(part, names, position, trace)?);
                }
                ends
            }
            Term::All(parts) => {
                let mut used = vec![false; parts.len()];
                let mut ends = BTreeSet::new();
                self.all_ends(parts, &mut used, names, position, trace, &mut ends)?;
                ends
            }
        })
    }

    fn element_step(
        &self,
        expected: &QName,
        names: &[QName],
        position: usize,
        trace: &mut Trace,
    ) -> BTreeSet<usize> {
        trace.expect(position, expected.expanded());
        if names.get(position) == Some(expected) {
            trace.furthest = trace.furthest.max(position + 1);
            BTreeSet::from([position + 1])
        } else {
            BTreeSet::new()
        }
    }

    /// `xs:all`: each particle at most once, in any order.
    fn all_ends(
        &self,
        parts: &[Particle],
        used: &mut Vec<bool>,
        names: &[QName],
        position: usize,
        trace: &mut Trace,
        ends: &mut BTreeSet<usize>,
    ) -> Result<()> {
        if parts.iter().zip(used.iter()).all(|(p, &u)| u || p.min == 0) {
            ends.insert(position);
        }
        for i in 0..parts.len() {
            if used[i] {
                continue;
            }
            let steps = self.particle_ends(&parts[i], names, position, trace)?;
            for end in steps {
                if end == position {
                    continue;
                }
                used[i] = true;
                self.all_ends(parts, used, names, end, trace, ends)?;
                used[i] = false;
            }
        }
        Ok(())
    }

    /// A simple type with every derivation folded in.
    fn flatten(&self, reference: &SimpleRef, depth: usize) -> Result<Flat> {
        if depth > MAX_TYPE_DEPTH {
            bail!("schema simple type derivation is circular");
        }
        let simple = match reference {
            SimpleRef::Builtin(builtin) => {
                return Ok(Flat {
                    kind: FlatKind::Atomic(*builtin),
                    facets: Facets::default(),
                });
            }
            SimpleRef::Named(name) => match self.named_type(name)? {
                Type::Simple(simple) => simple,
                Type::Complex(_) => bail!(
                    "schema type '{}' is used as a simple type but is a complex type",
                    name.expanded()
                ),
            },
            SimpleRef::Inline(simple) => simple,
        };
        Ok(match &simple.variety {
            Variety::Restriction(base) => {
                let base = self.flatten(base, depth + 1)?;
                Flat {
                    kind: base.kind,
                    facets: simple.facets.on_top_of(&base.facets),
                }
            }
            Variety::List(item) => Flat {
                kind: FlatKind::List(Box::new(self.flatten(item, depth + 1)?)),
                facets: simple.facets.clone(),
            },
            Variety::Union(members) => Flat {
                kind: FlatKind::Union(
                    members
                        .iter()
                        .map(|m| self.flatten(m, depth + 1))
                        .collect::<Result<Vec<_>>>()?,
                ),
                facets: simple.facets.clone(),
            },
        })
    }
}

impl Wildcard {
    fn admits(&self, name: &QName, schema: &Schema) -> bool {
        match &self.namespace {
            WildcardNamespace::Any => true,
            WildcardNamespace::Other => {
                name.namespace.is_some() && name.namespace != schema.target_namespace
            }
            WildcardNamespace::List(list) => list.contains(&name.namespace),
        }
    }
}

fn normalize_whitespace(value: &str, mode: WhiteSpace) -> String {
    match mode {
        WhiteSpace::Preserve => value.to_string(),
        WhiteSpace::Replace => value
            .chars()
            .map(|c| {
                if matches!(c, '\t' | '\n' | '\r') {
                    ' '
                } else {
                    c
                }
            })
            .collect(),
        WhiteSpace::Collapse => value.split_whitespace().collect::<Vec<_>>().join(" "),
    }
}

/// Checks a value against a flattened simple type. `Ok` carries the
/// whitespace-normalized value (what a `fixed` constraint compares with);
/// `Err` carries xmllint's message tail, after `Element 'x': `.
fn check_value(flat: &Flat, raw: &str, scope: &Element) -> Result<String, String> {
    let mode = flat.facets.white_space.unwrap_or_else(|| match &flat.kind {
        FlatKind::Atomic(builtin) => builtin.white_space(),
        FlatKind::List(_) => WhiteSpace::Collapse,
        FlatKind::Union(_) => WhiteSpace::Preserve,
    });
    let value = normalize_whitespace(raw, mode);
    let length = match &flat.kind {
        FlatKind::Atomic(builtin) => {
            if !builtin.accepts(&value, scope) {
                return Err(format!(
                    "'{value}' is not a valid value of the atomic type '{}'.",
                    builtin.xs_name()
                ));
            }
            value.chars().count()
        }
        FlatKind::List(item) => {
            let items: Vec<&str> = value.split(' ').filter(|s| !s.is_empty()).collect();
            for element in &items {
                check_value(item, element, scope).map_err(|message| {
                    format!("'{value}' is not a valid value of the list type: {message}")
                })?;
            }
            items.len()
        }
        FlatKind::Union(members) => {
            if !members
                .iter()
                .any(|m| check_value(m, &value, scope).is_ok())
            {
                return Err(format!("'{value}' is not a valid value of the union type."));
            }
            value.chars().count()
        }
    };
    check_facets(&flat.facets, &value, length)?;
    Ok(value)
}

fn check_facets(facets: &Facets, value: &str, length: usize) -> Result<(), String> {
    if !facets.enumeration.is_empty() && !facets.enumeration.iter().any(|e| e == value) {
        let set = facets
            .enumeration
            .iter()
            .map(|e| format!("'{e}'"))
            .collect::<Vec<_>>()
            .join(", ");
        return Err(format!(
            "[facet 'enumeration'] The value '{value}' is not an element of the set {{{set}}}."
        ));
    }
    for (source, regex) in &facets.patterns {
        if !regex.is_match(value) {
            return Err(format!(
                "[facet 'pattern'] The value '{value}' is not accepted by the pattern '{source}'."
            ));
        }
    }
    if let Some(expected) = facets.length
        && length != expected
    {
        return Err(format!(
            "[facet 'length'] The value has a length of '{length}'; this differs from the allowed length of '{expected}'."
        ));
    }
    if let Some(min) = facets.min_length
        && length < min
    {
        return Err(format!(
            "[facet 'minLength'] The value has a length of '{length}'; this underruns the allowed minimum length of '{min}'."
        ));
    }
    if let Some(max) = facets.max_length
        && length > max
    {
        return Err(format!(
            "[facet 'maxLength'] The value has a length of '{length}'; this exceeds the allowed maximum length of '{max}'."
        ));
    }
    let number = value.parse::<f64>().ok();
    if let (Some(min), Some(n)) = (facets.min_inclusive, number)
        && n < min
    {
        return Err(format!(
            "[facet 'minInclusive'] The value '{value}' is less than the minimum value allowed ('{min}')."
        ));
    }
    if let (Some(max), Some(n)) = (facets.max_inclusive, number)
        && n > max
    {
        return Err(format!(
            "[facet 'maxInclusive'] The value '{value}' is greater than the maximum value allowed ('{max}')."
        ));
    }
    if let (Some(min), Some(n)) = (facets.min_exclusive, number)
        && n <= min
    {
        return Err(format!(
            "[facet 'minExclusive'] The value '{value}' must be greater than '{min}'."
        ));
    }
    if let (Some(max), Some(n)) = (facets.max_exclusive, number)
        && n >= max
    {
        return Err(format!(
            "[facet 'maxExclusive'] The value '{value}' must be less than '{max}'."
        ));
    }
    if let Some(total) = facets.total_digits {
        let digits = value.chars().filter(char::is_ascii_digit).count();
        if digits > total {
            return Err(format!(
                "[facet 'totalDigits'] The value '{value}' has more digits than are allowed ('{total}')."
            ));
        }
    }
    if let Some(fraction) = facets.fraction_digits {
        let digits = value
            .split_once('.')
            .map_or(0, |(_, f)| f.chars().filter(char::is_ascii_digit).count());
        if digits > fraction {
            return Err(format!(
                "[facet 'fractionDigits'] The value '{value}' has more fractional digits than are allowed ('{fraction}')."
            ));
        }
    }
    Ok(())
}