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
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
//! XSD validation logic for element and content model validation.
//!
//! This module contains the core validation methods on `XsdValidator`:
//! - `validate()` — entry point: validates an entire document against the schema
//! - `validate_element()` — validates a single element against its declaration
//! - `validate_complex_content()` — validates attributes and content model of complex types
//! - `validate_sequence()` / `validate_choice()` / `validate_all()` — content model validators
//! - `validate_simple_content()` — validates text content against a simple type
//! - `validate_attribute_value()` — validates an attribute value against its declared type
//! - xsi:type resolution and type substitution blocking checks
//! - Substitution group matching for element declarations
use crate::dom::{Document, NodeId, NodeKind};
use crate::error::ValidationError;
use crate::namespace::build_resolver_for_node;
use super::builtins::{
apply_whitespace_normalization, validate_builtin_value, validate_facet, validate_list_facet,
whitespace_for_type,
};
use super::parser::parse_builtin_type;
use super::types::*;
use super::wildcard::wildcard_allows_namespace;
use super::{XSI_NAMESPACE, XS_NAMESPACE};
/// Result of resolving an `xsi:type` attribute on an element.
///
/// When an instance element carries `xsi:type`, the validator resolves it to one of:
/// - A built-in XSD type (e.g. `xs:int`)
/// - A named schema type (simple or complex)
/// - Not found (error case)
enum XsiTypeResult {
/// A built-in XSD type like xs:string, xs:int, etc.
BuiltIn(BuiltInType),
/// A named type definition from the schema.
Named(Box<TypeDef>),
/// The xsi:type QName could not be resolved.
NotFound(String),
}
impl XsdValidator {
/// Validate a document against this schema.
///
/// Finds the root element, looks up its global element declaration, and
/// delegates to `validate_element()`. Returns a (possibly empty) list of
/// validation errors.
pub fn validate(&self, doc: &Document) -> Vec<ValidationError> {
let mut errors = Vec::new();
let doc_elem = match doc.document_element() {
Some(e) => e,
None => {
errors.push(ValidationError {
message: "Document has no root element".to_string(),
line: None,
column: None,
});
return errors;
}
};
let elem = match doc.element(doc_elem) {
Some(e) => e,
None => return errors,
};
// Find matching top-level element declaration
let key_with_ns = (
elem.name.namespace_uri.as_deref().map(|s| s.to_string()),
elem.name.local_name.to_string(),
);
let key_no_ns = (None, elem.name.local_name.to_string());
let decl = self
.elements
.get(&key_with_ns)
.or_else(|| self.elements.get(&key_no_ns));
match decl {
Some(decl) => {
self.validate_element(doc, doc_elem, decl, &mut errors);
}
None => {
errors.push(ValidationError {
message: format!(
"No element declaration found for '{}'",
elem.name.local_name
),
line: Some(doc.node_line(doc_elem)),
column: Some(doc.node_column(doc_elem)),
});
}
}
errors
}
/// Check if an element has any child elements (not just text nodes).
fn element_has_child_elements(&self, doc: &Document, node: NodeId) -> bool {
for child in doc.children(node) {
if let Some(NodeKind::Element(_)) = doc.node_kind(child) {
return true;
}
}
false
}
/// Get a display name for a built-in type (e.g. "xs:string").
fn builtin_type_name(&self, bt: &BuiltInType) -> &'static str {
match bt {
BuiltInType::String => "xs:string",
BuiltInType::Boolean => "xs:boolean",
BuiltInType::Decimal => "xs:decimal",
BuiltInType::Float => "xs:float",
BuiltInType::Double => "xs:double",
BuiltInType::Integer => "xs:integer",
BuiltInType::Long => "xs:long",
BuiltInType::Int => "xs:int",
BuiltInType::Short => "xs:short",
BuiltInType::Byte => "xs:byte",
BuiltInType::NonNegativeInteger => "xs:nonNegativeInteger",
BuiltInType::PositiveInteger => "xs:positiveInteger",
BuiltInType::NonPositiveInteger => "xs:nonPositiveInteger",
BuiltInType::NegativeInteger => "xs:negativeInteger",
BuiltInType::UnsignedLong => "xs:unsignedLong",
BuiltInType::UnsignedInt => "xs:unsignedInt",
BuiltInType::UnsignedShort => "xs:unsignedShort",
BuiltInType::UnsignedByte => "xs:unsignedByte",
BuiltInType::DateTime => "xs:dateTime",
BuiltInType::Date => "xs:date",
BuiltInType::Time => "xs:time",
BuiltInType::Duration => "xs:duration",
BuiltInType::GYear => "xs:gYear",
BuiltInType::GYearMonth => "xs:gYearMonth",
BuiltInType::GMonth => "xs:gMonth",
BuiltInType::GMonthDay => "xs:gMonthDay",
BuiltInType::GDay => "xs:gDay",
BuiltInType::HexBinary => "xs:hexBinary",
BuiltInType::Base64Binary => "xs:base64Binary",
BuiltInType::AnyURI => "xs:anyURI",
BuiltInType::QName => "xs:QName",
BuiltInType::NormalizedString => "xs:normalizedString",
BuiltInType::Token => "xs:token",
BuiltInType::Language => "xs:language",
BuiltInType::Name => "xs:Name",
BuiltInType::NCName => "xs:NCName",
BuiltInType::ID => "xs:ID",
BuiltInType::IDREF => "xs:IDREF",
BuiltInType::IDREFS => "xs:IDREFS",
BuiltInType::NMTOKEN => "xs:NMTOKEN",
BuiltInType::NMTOKENS => "xs:NMTOKENS",
BuiltInType::NOTATION => "xs:NOTATION",
BuiltInType::ENTITY => "xs:ENTITY",
BuiltInType::ENTITIES => "xs:ENTITIES",
BuiltInType::AnyType => "xs:anyType",
BuiltInType::AnySimpleType => "xs:anySimpleType",
}
}
/// Resolve an `xsi:type` attribute on an element.
///
/// Looks for `xsi:type` in the element's attributes, parses the QName value,
/// resolves the prefix to a namespace URI, and looks up the type in the schema
/// or built-in type registry.
///
/// Returns `None` if no `xsi:type` is present.
fn resolve_xsi_type(&self, doc: &Document, node: NodeId) -> Option<XsiTypeResult> {
let elem = doc.element(node)?;
// Look for xsi:type attribute
let xsi_type_value = elem.get_attribute_ns(XSI_NAMESPACE, "type").or_else(|| {
// Also try by prefix match for elements where namespace resolution
// hasn't been applied to attributes
elem.attributes
.iter()
.find(|a| a.name.local_name == "type" && a.name.prefix.as_deref() == Some("xsi"))
.map(|a| &*a.value)
})?;
// Parse the QName value (may be prefixed like "xs:int")
let (prefix, local_name) = if let Some(colon_pos) = xsi_type_value.find(':') {
(
Some(&xsi_type_value[..colon_pos]),
&xsi_type_value[colon_pos + 1..],
)
} else {
(None, xsi_type_value)
};
// Resolve prefix to namespace URI
let type_ns = if let Some(pfx) = prefix {
// Look up prefix in namespace declarations
let resolver = build_resolver_for_node(doc, node);
resolver.resolve(pfx).map(|s| s.to_string())
} else {
// No prefix — use default namespace if present
// Per XSD spec, an unprefixed QName in xsi:type uses the default namespace
let resolver = build_resolver_for_node(doc, node);
resolver.resolve_default().map(|s| s.to_string())
};
// Check if it's a built-in XSD type
if type_ns.as_deref() == Some(XS_NAMESPACE) {
if let Some(bt) = parse_builtin_type(local_name) {
return Some(XsiTypeResult::BuiltIn(bt));
}
}
// Try looking up in schema types
let key = (type_ns.clone(), local_name.to_string());
if let Some(td) = self.types.get(&key) {
return Some(XsiTypeResult::Named(Box::new(td.clone())));
}
// Also try without namespace
let key_no_ns = (None, local_name.to_string());
if let Some(td) = self.types.get(&key_no_ns) {
return Some(XsiTypeResult::Named(Box::new(td.clone())));
}
Some(XsiTypeResult::NotFound(xsi_type_value.to_string()))
}
/// Check if xsi:type substitution is blocked by element or type block constraints.
///
/// Per XSD §3.4.4.2 "Type Derivation OK (Complex)", blocking is checked against:
/// 1. The element declaration's block (`decl_block_ext`/`decl_block_rst`) — blocks any
/// derivation step in the entire chain that uses the blocked method.
/// 2. The declared type's block (`decl_type_block_ext`/`decl_type_block_rst`) — same rule,
/// applied to the type that the element declaration refers to.
///
/// Intermediate types' block constraints do NOT affect xsi:type substitution checking.
///
/// Returns `Some(error_message)` if blocked, `None` if allowed.
fn check_type_substitution_blocked(
&self,
xsi_type: &TypeDef,
decl_block_ext: bool,
decl_block_rst: bool,
decl_type_block_ext: bool,
decl_type_block_rst: bool,
) -> Option<String> {
// Walk up the derivation chain of the xsi:type type.
// Track which derivation methods appear in the chain.
let mut has_extension_in_chain = false;
let mut has_restriction_in_chain = false;
let mut current = xsi_type;
while let TypeDef::Complex(ct) = current {
let is_extension = match ct.derived_by_extension {
Some(true) => true,
Some(false) => false,
None => break, // Not derived, we're at a root type
};
if is_extension {
has_extension_in_chain = true;
} else {
has_restriction_in_chain = true;
}
// Check element-level block against accumulated chain
if has_extension_in_chain && decl_block_ext {
return Some(
"Type substitution blocked: derivation chain includes extension, which is blocked by element declaration".to_string(),
);
}
if has_restriction_in_chain && decl_block_rst {
return Some(
"Type substitution blocked: derivation chain includes restriction, which is blocked by element declaration".to_string(),
);
}
// Check the declared type's block against accumulated chain
if has_extension_in_chain && decl_type_block_ext {
return Some(
"Type substitution blocked: derivation chain includes extension, which is blocked by the declared type".to_string(),
);
}
if has_restriction_in_chain && decl_type_block_rst {
return Some(
"Type substitution blocked: derivation chain includes restriction, which is blocked by the declared type".to_string(),
);
}
// Move up to base type
if let Some(ref base_key) = ct.base_type {
if let Some(base_td) = self.types.get(base_key) {
current = base_td;
} else {
break;
}
} else {
break;
}
}
None
}
/// Check if `xsi_type` is the declared type or derived from it.
///
/// The declared element type is given as a `TypeRef`. Returns `true` if the
/// xsi:type is valid for substitution (ignoring block constraints).
fn is_type_derived_from_decl(&self, xsi_type: &TypeDef, decl_type_ref: &TypeRef) -> bool {
// Get the declared type's key (namespace, local_name)
let decl_key = match decl_type_ref {
TypeRef::Named(ns, name) => (ns.clone(), name.clone()),
TypeRef::BuiltIn(bt) => {
// xsi:type is always a named type here, AnyType allows everything
if *bt == BuiltInType::AnyType {
return true;
}
// For other built-in types, the xsi:type must match exactly
// (named schema types can't derive from built-in complex types normally)
return false;
}
TypeRef::Inline(_) => {
// Inline (anonymous) type — xsi:type substitution is not meaningful
// since you can't name the declared type. Allow it.
return true;
}
};
// Check if xsi:type IS the declared type
let xsi_key = match xsi_type {
TypeDef::Complex(ct) => {
if let Some(ref name) = ct.name {
// Try to match: check if namespace+name matches decl_key
// We need the type's namespace. Walk through the types map to find it.
if let Some(found_key) = self.find_type_key_by_typedef(xsi_type) {
if found_key == decl_key {
return true;
}
found_key
} else {
// Anonymous type — can't be the same as a named declared type
(None, name.clone())
}
} else {
return false; // anonymous type, can't match
}
}
TypeDef::Simple(st) => {
if let Some(ref name) = st.name {
if let Some(found_key) = self.find_type_key_by_typedef(xsi_type) {
if found_key == decl_key {
return true;
}
found_key
} else {
(None, name.clone())
}
} else {
return false;
}
}
};
// Walk the derivation chain of xsi:type to see if it eventually derives from decl_key
self.is_derived_from(&xsi_key, &decl_key)
}
/// Find the key in `self.types` that corresponds to a given `TypeDef`.
///
/// Searches the types map by matching the type's name field against the map's
/// local name component. Returns the full `(Option<namespace>, name)` key.
fn find_type_key_by_typedef(&self, td: &TypeDef) -> Option<(Option<String>, String)> {
let name = match td {
TypeDef::Complex(ct) => ct.name.as_ref()?,
TypeDef::Simple(st) => st.name.as_ref()?,
};
// Look for it in the types map
for key in self.types.keys() {
if &key.1 == name {
return Some(key.clone());
}
}
None
}
/// Check if a type identified by `type_key` is derived (directly or transitively)
/// from a type identified by `ancestor_key`.
///
/// Walks up the derivation chain (via `base_type` links on complex types) up to
/// 50 levels deep to prevent infinite loops.
fn is_derived_from(
&self,
type_key: &(Option<String>, String),
ancestor_key: &(Option<String>, String),
) -> bool {
let mut current_key = type_key.clone();
// Walk up to 50 levels to avoid infinite loops
for _ in 0..50 {
if let Some(td) = self.types.get(¤t_key) {
match td {
TypeDef::Complex(ct) => {
if let Some(ref base_key) = ct.base_type {
if base_key == ancestor_key {
return true;
}
current_key = base_key.clone();
} else {
return false; // no base type
}
}
TypeDef::Simple(_st) => {
// Simple types derive from their base built-in type
// For now, we can't easily walk the chain for simple types
// since base is a BuiltInType, not a key
return false;
}
}
} else {
return false;
}
}
false
}
/// Compute the effective attribute wildcard for a complex type.
///
/// For types derived by extension, this is the union of the base type's
/// effective wildcard and the derived type's own wildcard.
/// For restriction types or types not derived, this is just the type's own wildcard.
fn compute_effective_wildcard(&self, ct: &ComplexTypeDef) -> Option<AttributeWildcard> {
if ct.derived_by_extension == Some(true) {
// Get the base type's effective wildcard (recursively)
let base_wildcard = if let Some(ref base_key) = ct.base_type {
if let Some(TypeDef::Complex(base_ct)) = self.types.get(base_key) {
self.compute_effective_wildcard(base_ct)
} else {
None
}
} else {
None
};
// Union of base wildcard and derived wildcard
match (&base_wildcard, &ct.attribute_wildcard) {
(Some(base_wc), Some(derived_wc)) => Some(base_wc.union(derived_wc)),
(Some(base_wc), None) => Some(base_wc.clone()),
(None, Some(derived_wc)) => Some(derived_wc.clone()),
(None, None) => None,
}
} else {
// Restriction or not derived: use the type's own wildcard
ct.attribute_wildcard.clone()
}
}
/// Compute effective attributes for a complex type, including inherited attributes
/// from the base type chain.
///
/// - **Extension**: base attributes + derived attributes (derived can add new ones)
/// - **Restriction**: derived attributes override base; attributes not mentioned in
/// the restriction are inherited; prohibited attributes are removed
/// - **Not derived**: just the type's own attributes
fn compute_effective_attributes(&self, ct: &ComplexTypeDef) -> Vec<AttributeDecl> {
// Get base type's effective attributes
let base_attrs = if let Some(ref base_key) = ct.base_type {
if let Some(TypeDef::Complex(base_ct)) = self.types.get(base_key) {
self.compute_effective_attributes(base_ct)
} else {
Vec::new()
}
} else {
Vec::new()
};
if base_attrs.is_empty() {
return ct.attributes.clone();
}
match ct.derived_by_extension {
Some(true) => {
// Extension: base attributes + derived attributes
let mut result = base_attrs;
for attr in &ct.attributes {
if !result.iter().any(|a| a.name == attr.name) {
result.push(attr.clone());
}
}
result
}
Some(false) => {
// Restriction: start with base attributes, then apply overrides
// Attributes explicitly declared in restriction replace base attrs.
// Attributes with use="prohibited" remove the attribute.
let mut result = Vec::new();
for base_attr in &base_attrs {
// Check if the restriction overrides or prohibits this attribute
let override_attr = ct.attributes.iter().find(|a| a.name == base_attr.name);
if let Some(oa) = override_attr {
// Use the overridden version (but check if prohibited)
if !oa.prohibited {
result.push(oa.clone());
}
// If prohibited, skip it (don't add to result)
} else {
// Not mentioned in restriction: inherit from base
result.push(base_attr.clone());
}
}
// Also add any new attributes from restriction that aren't in base
// (unusual but technically possible)
for attr in &ct.attributes {
if !attr.prohibited && !result.iter().any(|a| a.name == attr.name) {
result.push(attr.clone());
}
}
result
}
None => {
// Not derived
ct.attributes.clone()
}
}
}
/// Compute the effective content model for a complex type, merging base type
/// particles for extension types.
///
/// For a type derived by extension from another complex type with a sequence
/// content model, the effective content is the base type's particles followed
/// by the extension's particles. This recursively walks the extension chain.
///
/// Returns `None` if the type is not an extension or cannot be merged.
fn compute_effective_particles(&self, ct: &ComplexTypeDef) -> Option<Vec<Particle>> {
if ct.derived_by_extension != Some(true) {
return None;
}
let (base_ns, base_name) = ct.base_type.as_ref()?;
let key = (base_ns.clone(), base_name.clone());
let base_type = self.types.get(&key)?;
if let TypeDef::Complex(base_ct) = base_type {
// Recursively get the base type's effective particles
let base_particles = if let Some(recursive) = self.compute_effective_particles(base_ct)
{
recursive
} else {
// No further merging needed, just get the base type's own particles
match &base_ct.content {
ContentModel::Sequence(particles, _, _) => particles.clone(),
ContentModel::Empty => Vec::new(),
_ => return None, // Can't merge non-sequence base content
}
};
// Get the extension's own particles
let ext_particles = match &ct.content {
ContentModel::Sequence(particles, _, _) => particles.clone(),
ContentModel::Empty => Vec::new(),
_ => return None,
};
// Merge: base particles followed by extension particles
let mut merged = base_particles;
merged.extend(ext_particles);
Some(merged)
} else {
None
}
}
/// Validate a single element against its element declaration.
///
/// This is the main per-element validation entry point. It handles:
/// 1. Element reference resolution (is_ref → look up global declaration)
/// 2. Abstract element rejection
/// 3. `xsi:nil` processing (nillable elements with nil=true must be empty)
/// 4. `xsi:type` override resolution and type substitution blocking
/// 5. Type resolution and dispatch to complex/simple content validation
/// 6. Identity constraint evaluation (key/unique/keyref)
fn validate_element(
&self,
doc: &Document,
node: NodeId,
decl: &ElementDecl,
errors: &mut Vec<ValidationError>,
) {
// If this is an element reference, resolve the actual declaration from the
// global elements map to get the real type_ref, nillable, block constraints, etc.
if decl.is_ref {
let key = (decl.namespace.clone(), decl.name.clone());
if let Some(global_decl) = self.elements.get(&key) {
let resolved = global_decl.clone();
self.validate_element(doc, node, &resolved, errors);
return;
}
// Fall through with the ref decl's AnyType if global not found
}
// Reject abstract elements: they cannot appear directly in instances
if decl.is_abstract {
errors.push(ValidationError {
message: format!(
"Element '{}' is abstract and cannot appear in an instance document",
decl.name
),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
return;
}
// Check for xsi:nil="true"
if let Some(elem) = doc.element(node) {
let xsi_nil_value = elem.get_attribute_ns(XSI_NAMESPACE, "nil").or_else(|| {
elem.attributes
.iter()
.find(|a| a.name.local_name == "nil" && a.name.prefix.as_deref() == Some("xsi"))
.map(|a| &*a.value)
});
if xsi_nil_value == Some("true") || xsi_nil_value == Some("1") {
if !decl.nillable {
errors.push(ValidationError {
message: "xsi:nil='true' on non-nillable element".to_string(),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
return;
}
// Nillable element with xsi:nil="true": must be empty
// (no child elements and no non-whitespace text content)
let has_children = self.element_has_child_elements(doc, node);
let text = doc.text_content_deep(node);
let has_text = !text.trim().is_empty();
if has_children || has_text {
errors.push(ValidationError {
message: "Element with xsi:nil='true' must have no content".to_string(),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
}
// Skip all further content validation — nilled element is valid if empty
return;
}
}
// Check for xsi:type override
if let Some(xsi_type_ref) = self.resolve_xsi_type(doc, node) {
match xsi_type_ref {
XsiTypeResult::BuiltIn(bt) => {
// NOTATION cannot be used as the {type definition} of an element
if bt == BuiltInType::NOTATION {
errors.push(ValidationError {
message: "xs:NOTATION cannot be used as the type of an element"
.to_string(),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
return;
}
if bt == BuiltInType::AnyType {
self.validate_children_against_global_decls(doc, node, errors);
} else {
// Simple built-in type: element must not have child elements
if self.element_has_child_elements(doc, node) {
errors.push(ValidationError {
message: format!(
"Element with xsi:type '{}' must not have child elements",
self.builtin_type_name(&bt)
),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
return;
}
let text = doc.text_content_deep(node);
validate_builtin_value(&text, &bt, doc, node, errors);
}
return;
}
XsiTypeResult::Named(td) => {
// Check that xsi:type is the declared type or derived from it
if !self.is_type_derived_from_decl(&td, &decl.type_ref) {
let type_name = match td.as_ref() {
TypeDef::Complex(ct) => ct.name.as_deref().unwrap_or("anonymous"),
TypeDef::Simple(st) => st.name.as_deref().unwrap_or("anonymous"),
};
errors.push(ValidationError {
message: format!(
"xsi:type '{}' is not derived from the declared element type",
type_name,
),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
return;
}
// Check block constraints
// Get the declared type's block constraints
let (decl_type_block_ext, decl_type_block_rst) = match &decl.type_ref {
TypeRef::Named(ns, name) => {
let key = (ns.clone(), name.clone());
if let Some(TypeDef::Complex(ct)) = self.types.get(&key) {
(ct.block_extension, ct.block_restriction)
} else {
(false, false)
}
}
_ => (false, false),
};
if let Some(block_msg) = self.check_type_substitution_blocked(
&td,
decl.block_extension,
decl.block_restriction,
decl_type_block_ext,
decl_type_block_rst,
) {
errors.push(ValidationError {
message: block_msg,
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
return;
}
match *td {
TypeDef::Complex(ct) => {
self.validate_complex_content(doc, node, &ct, errors);
}
TypeDef::Simple(st) => {
// Simple type: element must not have child elements
if self.element_has_child_elements(doc, node) {
errors.push(ValidationError {
message:
"Element with simple xsi:type must not have child elements"
.to_string(),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
return;
}
self.validate_simple_content(doc, node, &st, errors);
}
}
return;
}
XsiTypeResult::NotFound(type_name) => {
errors.push(ValidationError {
message: format!("xsi:type '{}' not found", type_name),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
return;
}
}
}
let type_def = self.resolve_type(&decl.type_ref);
match type_def {
Some(TypeDef::Complex(ct)) => {
self.validate_complex_content(doc, node, ct, errors);
}
Some(TypeDef::Simple(st)) => {
// Simple types cannot have child elements
if self.element_has_child_elements(doc, node) {
let elem_name = doc
.element(node)
.map(|e| &*e.name.local_name)
.unwrap_or("?");
errors.push(ValidationError {
message: format!(
"Element '{}' has simple type but contains child elements",
elem_name
),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
}
self.validate_simple_content(doc, node, st, errors);
}
None => {
// If type can't be resolved, check if it's a built-in
if let TypeRef::BuiltIn(bt) = &decl.type_ref {
match bt {
BuiltInType::AnyType => {
// AnyType allows any content, but we should still
// validate child elements against their own declarations.
self.validate_children_against_global_decls(doc, node, errors);
}
_ => {
// Built-in simple types cannot have child elements
if self.element_has_child_elements(doc, node) {
let elem_name = doc
.element(node)
.map(|e| &*e.name.local_name)
.unwrap_or("?");
errors.push(ValidationError {
message: format!(
"Element '{}' has simple type '{:?}' but contains child elements",
elem_name, bt
),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
}
let text = doc.text_content_deep(node);
validate_builtin_value(&text, bt, doc, node, errors);
}
}
}
// Otherwise, no validation possible (unknown type)
}
}
// Check fixed-value constraint (raw lexical comparison, no whitespace normalization)
if let Some(ref fixed_value) = decl.fixed {
let text = doc.text_content_deep(node);
if text != *fixed_value {
errors.push(ValidationError {
message: format!(
"Element '{}' has fixed value '{}' but content is '{}'",
decl.name, fixed_value, text
),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
}
}
// Evaluate identity constraints declared on this element
if !decl.identity_constraints.is_empty() {
self.evaluate_identity_constraints(doc, node, &decl.identity_constraints, errors);
}
}
/// Resolve a type reference to a `TypeDef`.
///
/// - `TypeRef::Named` → look up in `self.types` by (namespace, name) key
/// - `TypeRef::Inline` → return the inline type definition directly
/// - `TypeRef::BuiltIn` → return `None` (built-in types are handled separately)
fn resolve_type<'a>(&'a self, type_ref: &'a TypeRef) -> Option<&'a TypeDef> {
match type_ref {
TypeRef::Named(ns, name) => {
let key = (ns.clone(), name.clone());
self.types.get(&key)
}
TypeRef::Inline(td) => Some(td.as_ref()),
TypeRef::BuiltIn(_) => None,
}
}
/// Recursively validate child elements of an AnyType element against
/// their global element declarations.
///
/// For elements typed as `xs:anyType`, any content is allowed, but child
/// elements that have matching global declarations are still validated
/// against those declarations.
fn validate_children_against_global_decls(
&self,
doc: &Document,
node: NodeId,
errors: &mut Vec<ValidationError>,
) {
for child in doc.children(node) {
if let Some(NodeKind::Element(child_elem)) = doc.node_kind(child) {
// Look up child element in global declarations
let key_with_ns = (
child_elem
.name
.namespace_uri
.as_deref()
.map(|s| s.to_string()),
child_elem.name.local_name.to_string(),
);
let key_no_ns = (None, child_elem.name.local_name.to_string());
let child_decl = self
.elements
.get(&key_with_ns)
.or_else(|| self.elements.get(&key_no_ns));
if let Some(decl) = child_decl {
self.validate_element(doc, child, decl, errors);
} else {
// No declaration found — for AnyType, that's OK.
// Still recurse to validate deeper children.
self.validate_children_against_global_decls(doc, child, errors);
}
}
}
}
/// Validate the complex content of an element against a complex type definition.
///
/// This handles:
/// - Required/optional attribute checking
/// - Attribute value validation against declared types
/// - Attribute wildcard processing (processContents=skip/lax/strict)
/// - Rejecting undeclared attributes when no wildcard is present
/// - Element-only text content rejection (non-mixed types)
/// - Content model validation (sequence/choice/all/empty/simpleContent/any)
/// - Extension type particle merging
fn validate_complex_content(
&self,
doc: &Document,
node: NodeId,
ct: &ComplexTypeDef,
errors: &mut Vec<ValidationError>,
) {
// Compute effective attributes (including inherited from base types)
let effective_attrs = self.compute_effective_attributes(ct);
// Validate attributes
if let Some(elem) = doc.element(node) {
for attr_decl in &effective_attrs {
if attr_decl.required {
let found = elem
.attributes
.iter()
.any(|a| a.name.local_name == attr_decl.name);
if !found {
errors.push(ValidationError {
message: format!("Required attribute '{}' is missing", attr_decl.name),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
}
}
}
// Validate attribute values against their declared types
for attr_decl in &effective_attrs {
debug_log!(
"effective_attr name={} type_ref={:?}",
attr_decl.name,
attr_decl.type_ref
);
if let Some(attr) = elem
.attributes
.iter()
.find(|a| a.name.local_name == attr_decl.name)
{
let value = &attr.value;
debug_log!(
"validating attr {}={} against {:?}",
attr_decl.name,
value,
attr_decl.type_ref
);
self.validate_attribute_value(value, &attr_decl.type_ref, doc, node, errors);
}
}
// Compute the effective wildcard: for types derived by extension,
// merge the base type's wildcard with the derived type's wildcard (union).
let effective_wildcard = self.compute_effective_wildcard(ct);
// Validate unmatched attributes against wildcard or reject if no wildcard
if let Some(ref wildcard) = effective_wildcard {
for attr in &elem.attributes {
// Skip namespace declarations
if attr.name.local_name == "xmlns"
|| attr.name.prefix.as_deref() == Some("xmlns")
{
continue;
}
// Skip xsi:* attributes
if attr.name.prefix.as_deref() == Some("xsi")
|| attr.name.namespace_uri.as_deref()
== Some("http://www.w3.org/2001/XMLSchema-instance")
{
continue;
}
// Skip if already matched by an explicit attribute declaration
let already_declared = effective_attrs
.iter()
.any(|ad| ad.name == attr.name.local_name);
if already_declared {
continue;
}
let attr_ns_str = attr.name.namespace_uri.as_deref().map(|s| s.to_string());
// Check namespace constraint
if !wildcard.allows_namespace(attr_ns_str.as_deref()) {
errors.push(ValidationError {
message: format!(
"Attribute '{}' in namespace '{}' is not allowed by wildcard constraint",
attr.name.local_name,
attr_ns_str.as_deref().unwrap_or("(no namespace)")
),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
continue;
}
// processContents validation
match wildcard.process_contents {
ProcessContents::Skip => {
// No validation needed
}
ProcessContents::Lax | ProcessContents::Strict => {
// Look up in global attribute declarations
let key = (attr_ns_str.clone(), attr.name.local_name.to_string());
let global_decl = self.global_attributes.get(&key).or_else(|| {
let key2 = (
self.target_namespace.clone(),
attr.name.local_name.to_string(),
);
self.global_attributes.get(&key2)
});
match global_decl {
Some(decl) => {
// Validate attribute value against its declared type
self.validate_attribute_value(
&attr.value,
&decl.type_ref,
doc,
node,
errors,
);
}
None => {
// For strict: must find a declaration
if wildcard.process_contents == ProcessContents::Strict {
errors.push(ValidationError {
message: format!(
"Attribute '{}' in namespace '{}' has no global declaration (strict processContents)",
attr.name.local_name,
attr_ns_str.as_deref().unwrap_or("(no namespace)")
),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
}
// For lax: no declaration is OK
}
}
}
}
}
} else {
// No wildcard: reject any undeclared attributes
for attr in &elem.attributes {
// Skip namespace declarations
if attr.name.local_name == "xmlns"
|| attr.name.prefix.as_deref() == Some("xmlns")
{
continue;
}
// Skip xsi:* attributes
if attr.name.prefix.as_deref() == Some("xsi")
|| attr.name.namespace_uri.as_deref()
== Some("http://www.w3.org/2001/XMLSchema-instance")
{
continue;
}
// Check if declared
let already_declared = effective_attrs
.iter()
.any(|ad| ad.name == attr.name.local_name);
if !already_declared {
errors.push(ValidationError {
message: format!(
"Attribute '{}' is not allowed (no wildcard permits additional attributes)",
attr.name.local_name,
),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
}
}
}
}
// Validate content model
let child_elements: Vec<NodeId> = doc
.children(node)
.into_iter()
.filter(|&c| matches!(doc.node_kind(c), Some(NodeKind::Element(_))))
.collect();
// For non-mixed element-only content models, reject non-whitespace text
if !ct.mixed {
let is_element_only = matches!(
ct.content,
ContentModel::Sequence(..) | ContentModel::Choice(..) | ContentModel::All(..)
);
if is_element_only {
for child in doc.children(node) {
if let Some(text) = doc.text_content(child) {
if !text.trim().is_empty() {
errors.push(ValidationError {
message:
"Non-whitespace text content is not allowed in element-only content"
.to_string(),
line: Some(doc.node_line(child)),
column: Some(doc.node_column(child)),
});
break; // report once
}
}
}
}
}
// For extension types, merge base type's particles with extension's particles
if let Some(merged_particles) = self.compute_effective_particles(ct) {
let consumed = self.validate_sequence(
doc,
&child_elements,
&merged_particles,
1,
&MaxOccurs::Bounded(1),
node,
errors,
);
// Report remaining children as unexpected
for &remaining in &child_elements[consumed..] {
if let Some(elem) = doc.element(remaining) {
errors.push(ValidationError {
message: format!(
"Unexpected element '{}' in sequence",
elem.name.local_name
),
line: Some(doc.node_line(remaining)),
column: Some(doc.node_column(remaining)),
});
}
}
return;
}
match &ct.content {
ContentModel::Empty => {
if !child_elements.is_empty() {
errors.push(ValidationError {
message: "Element should have empty content".to_string(),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
}
// Check no text content (unless mixed)
if !ct.mixed {
let text = doc.text_content_deep(node);
let trimmed = text.trim();
if !trimmed.is_empty() {
errors.push(ValidationError {
message: "Element should have empty content but contains text"
.to_string(),
line: Some(doc.node_line(node)),
column: Some(doc.node_column(node)),
});
}
}
}
ContentModel::Sequence(particles, min_occurs, max_occurs) => {
let consumed = self.validate_sequence(
doc,
&child_elements,
particles,
*min_occurs,
max_occurs,
node,
errors,
);
// Report remaining children as unexpected
for &remaining in &child_elements[consumed..] {
if let Some(elem) = doc.element(remaining) {
errors.push(ValidationError {
message: format!(
"Unexpected element '{}' in sequence",
elem.name.local_name
),
line: Some(doc.node_line(remaining)),
column: Some(doc.node_column(remaining)),
});
}
}
}
ContentModel::Choice(particles, min_occurs, max_occurs) => {
let consumed = self.validate_choice(
doc,
&child_elements,
particles,
*min_occurs,
max_occurs,
node,
errors,
);
// Report remaining children as unexpected
for &remaining in &child_elements[consumed..] {
if let Some(elem) = doc.element(remaining) {
errors.push(ValidationError {
message: format!(
"Unexpected element '{}' after choice",
elem.name.local_name
),
line: Some(doc.node_line(remaining)),
column: Some(doc.node_column(remaining)),
});
}
}
}
ContentModel::All(particles) => {
self.validate_all(doc, &child_elements, particles, node, errors);
}
ContentModel::SimpleContent(type_ref) => {
match type_ref.as_ref() {
TypeRef::BuiltIn(bt) => {
let text = doc.text_content_deep(node);
validate_builtin_value(&text, bt, doc, node, errors);
}
TypeRef::Named(ns, local_name) => {
let key = (ns.clone(), local_name.clone());
if let Some(type_def) = self.types.get(&key) {
match type_def {
TypeDef::Simple(st) => {
self.validate_simple_content(doc, node, st, errors);
}
TypeDef::Complex(_) => {
// Complex base type for simpleContent — text validated against
// the complex type's own simpleContent base (recursively)
}
}
}
}
TypeRef::Inline(inner_type_def) => {
if let TypeDef::Simple(st) = inner_type_def.as_ref() {
self.validate_simple_content(doc, node, st, errors);
}
}
}
}
ContentModel::Any => {
// Any content is valid
}
}
}
/// Find a global element declaration by local name and namespace.
fn find_global_element(&self, name: &str, ns: Option<&str>) -> Option<ElementDecl> {
let key = (ns.map(|s| s.to_string()), name.to_string());
self.elements.get(&key).cloned()
}
/// Check if an instance element matches a declared element or is a member of
/// its substitution group.
///
/// Returns `Some(global_decl)` if the element is a substitution group member
/// that should be validated against its own declaration.
/// Returns `None` if it's a direct match (caller handles validation) or no match.
fn element_matches_with_substitution(
&self,
elem_name: &str,
elem_ns: Option<&str>,
decl: &ElementDecl,
) -> Option<ElementDecl> {
// Check if the instance element is a member of the substitution group
// headed by decl.
let head_key = (decl.namespace.clone(), decl.name.clone());
if let Some(members) = self.substitution_groups.get(&head_key) {
let elem_key = (elem_ns.map(|s| s.to_string()), elem_name.to_string());
if members.contains(&elem_key) {
// Found: the instance element substitutes for the declared element.
// Return the member's own global declaration for type validation.
return self.find_global_element(elem_name, elem_ns);
}
}
None
}
/// Validate a sequence content model.
///
/// Iterates through the sequence's particles in order, matching child elements.
/// The sequence can repeat between `compositor_min` and `compositor_max` times.
/// Each particle within the sequence has its own min/max occurs constraints.
///
/// Returns the number of child elements consumed.
#[allow(clippy::too_many_arguments)]
fn validate_sequence(
&self,
doc: &Document,
children: &[NodeId],
particles: &[Particle],
compositor_min: u64,
compositor_max: &MaxOccurs,
parent: NodeId,
errors: &mut Vec<ValidationError>,
) -> usize {
let max_reps = match compositor_max {
MaxOccurs::Bounded(n) => *n,
MaxOccurs::Unbounded => u64::MAX,
};
let mut child_idx = 0;
let mut seq_reps = 0u64;
// Outer loop: repeat the entire sequence up to max_reps times
'outer: while seq_reps < max_reps {
let start_idx = child_idx;
for particle in particles {
let mut count = 0u64;
let max = match particle.max_occurs {
MaxOccurs::Bounded(n) => n,
MaxOccurs::Unbounded => u64::MAX,
};
match &particle.kind {
ParticleKind::Element(decl) => {
while child_idx < children.len() && count < max {
let child = children[child_idx];
if let Some(elem) = doc.element(child) {
let name_matches = elem.name.local_name == decl.name;
let ns_matches = match (&elem.name.namespace_uri, &decl.namespace) {
(Some(a), Some(b)) => a == b,
(None, None) => true,
(Some(_), None) => false,
(None, Some(_)) => false,
};
if name_matches && ns_matches {
self.validate_element(doc, child, decl, errors);
count += 1;
child_idx += 1;
} else if let Some(subst_decl) = self
.element_matches_with_substitution(
&elem.name.local_name,
elem.name.namespace_uri.as_deref(),
decl,
)
{
// Element is a substitution group member;
// validate against its own declaration.
self.validate_element(doc, child, &subst_decl, errors);
count += 1;
child_idx += 1;
} else {
break;
}
} else {
break;
}
}
if count < particle.min_occurs {
if seq_reps >= compositor_min {
// We've already met the minimum repetitions,
// so this is just the sequence not starting another rep.
// Roll back to start_idx for this failed rep.
child_idx = start_idx;
break 'outer;
}
errors.push(ValidationError {
message: format!(
"Expected at least {} occurrence(s) of element '{}', found {}",
particle.min_occurs, decl.name, count
),
line: Some(doc.node_line(parent)),
column: Some(doc.node_column(parent)),
});
break 'outer;
}
}
ParticleKind::Sequence(sub_particles) => {
let sub_min = particle.min_occurs;
let sub_max = &particle.max_occurs;
let before = errors.len();
let consumed = self.validate_sequence(
doc,
&children[child_idx..],
sub_particles,
sub_min,
sub_max,
parent,
errors,
);
child_idx += consumed;
if errors.len() > before {
break 'outer;
}
}
ParticleKind::Choice(sub_particles) => {
let sub_min = particle.min_occurs;
let sub_max = &particle.max_occurs;
let consumed = self.validate_choice(
doc,
&children[child_idx..],
sub_particles,
sub_min,
sub_max,
parent,
errors,
);
child_idx += consumed;
}
ParticleKind::Any {
namespace_constraint,
process_contents,
} => {
// xs:any element wildcard: consume matching children
while child_idx < children.len() && count < max {
let child = children[child_idx];
if let Some(elem) = doc.element(child) {
if wildcard_allows_namespace(
namespace_constraint,
elem.name.namespace_uri.as_deref(),
) {
// Namespace matches; apply processContents
match process_contents {
ProcessContents::Skip => {
// Accept unconditionally
}
ProcessContents::Lax => {
// Try to find global element declaration; validate if found
if let Some(global_decl) = self.find_global_element(
&elem.name.local_name,
elem.name.namespace_uri.as_deref(),
) {
self.validate_element(
doc,
child,
&global_decl,
errors,
);
}
}
ProcessContents::Strict => {
// Must find global element declaration
if let Some(global_decl) = self.find_global_element(
&elem.name.local_name,
elem.name.namespace_uri.as_deref(),
) {
self.validate_element(
doc,
child,
&global_decl,
errors,
);
} else {
errors.push(ValidationError {
message: format!(
"No global element declaration found for '{}' (strict wildcard)",
elem.name.local_name
),
line: Some(doc.node_line(child)),
column: Some(doc.node_column(child)),
});
}
}
}
count += 1;
child_idx += 1;
} else {
break; // namespace doesn't match
}
} else {
break;
}
}
if count < particle.min_occurs {
if seq_reps >= compositor_min {
child_idx = start_idx;
break 'outer;
}
errors.push(ValidationError {
message: format!(
"Expected at least {} element(s) matching wildcard, found {}",
particle.min_occurs, count
),
line: Some(doc.node_line(parent)),
column: Some(doc.node_column(parent)),
});
break 'outer;
}
}
}
}
seq_reps += 1;
// If no progress was made, stop looping
if child_idx == start_idx {
break;
}
// If all children consumed, stop
if child_idx >= children.len() {
break;
}
}
if seq_reps < compositor_min {
errors.push(ValidationError {
message: format!(
"Sequence must occur at least {} time(s), found {}",
compositor_min, seq_reps
),
line: Some(doc.node_line(parent)),
column: Some(doc.node_column(parent)),
});
}
child_idx
}
/// Validate a choice content model.
///
/// Tries to match the current child element against one of the choice alternatives.
/// The choice can repeat between `compositor_min` and `compositor_max` times.
/// Each repetition picks one matching alternative and consumes its elements.
///
/// Returns the number of child elements consumed.
#[allow(clippy::too_many_arguments)]
fn validate_choice(
&self,
doc: &Document,
children: &[NodeId],
particles: &[Particle],
compositor_min: u64,
compositor_max: &MaxOccurs,
parent: NodeId,
errors: &mut Vec<ValidationError>,
) -> usize {
let max_reps = match compositor_max {
MaxOccurs::Bounded(n) => *n,
MaxOccurs::Unbounded => u64::MAX,
};
if children.is_empty() {
if compositor_min > 0 {
// Check if any particle allows 0 occurrences
let any_optional = particles.iter().any(|p| p.min_occurs == 0);
if !any_optional && !particles.is_empty() {
errors.push(ValidationError {
message: "Expected one of the choice alternatives".to_string(),
line: Some(doc.node_line(parent)),
column: Some(doc.node_column(parent)),
});
}
}
return 0;
}
let mut child_idx = 0;
let mut choice_reps = 0u64;
// Outer loop: repeat the choice up to max_reps times.
// Each iteration picks one alternative and consumes matching children for it.
while choice_reps < max_reps && child_idx < children.len() {
let current_child = children[child_idx];
let elem = match doc.element(current_child) {
Some(e) => e,
None => break,
};
// Try to match the current child against one of the choice alternatives
let mut matched_any = false;
for p in particles {
match &p.kind {
ParticleKind::Element(decl) => {
let name_matches = decl.name == elem.name.local_name;
let ns_matches = match (&elem.name.namespace_uri, &decl.namespace) {
(Some(a), Some(b)) => a == b,
(None, None) => true,
(Some(_), None) => false,
(None, Some(_)) => false,
};
// Check for direct match or substitution group match
let subst_decl = if !(name_matches && ns_matches) {
self.element_matches_with_substitution(
&elem.name.local_name,
elem.name.namespace_uri.as_deref(),
decl,
)
} else {
None
};
if (name_matches && ns_matches) || subst_decl.is_some() {
// Consume as many consecutive elements as allowed by max_occurs
// (matching either the declared element or substitution group members)
let max = match p.max_occurs {
MaxOccurs::Bounded(n) => n as usize,
MaxOccurs::Unbounded => usize::MAX,
};
let mut count = 0usize;
while child_idx < children.len() && count < max {
let child = children[child_idx];
if let Some(child_elem) = doc.element(child) {
let cn_matches = child_elem.name.local_name == decl.name;
let cns_matches =
match (&child_elem.name.namespace_uri, &decl.namespace) {
(Some(a), Some(b)) => a == b,
(None, None) => true,
_ => false,
};
if cn_matches && cns_matches {
self.validate_element(doc, child, decl, errors);
child_idx += 1;
count += 1;
} else if let Some(child_subst) = self
.element_matches_with_substitution(
&child_elem.name.local_name,
child_elem.name.namespace_uri.as_deref(),
decl,
)
{
self.validate_element(doc, child, &child_subst, errors);
child_idx += 1;
count += 1;
} else {
break;
}
} else {
break;
}
}
if count < p.min_occurs as usize {
errors.push(ValidationError {
message: format!(
"Expected at least {} occurrence(s) of element '{}' in choice, found {}",
p.min_occurs, decl.name, count
),
line: Some(doc.node_line(current_child)),
column: Some(doc.node_column(current_child)),
});
}
matched_any = true;
break;
}
}
ParticleKind::Sequence(sub_particles) => {
let sub_min = p.min_occurs;
let sub_max = &p.max_occurs;
let before_errors = errors.len();
let consumed = self.validate_sequence(
doc,
&children[child_idx..],
sub_particles,
sub_min,
sub_max,
parent,
errors,
);
if consumed > 0 {
child_idx += consumed;
matched_any = true;
// If the nested sequence produced errors, we still consumed
// elements — but we should stop the choice loop
if errors.len() > before_errors {
choice_reps += 1;
break;
}
break;
} else if errors.len() > before_errors {
// Sequence matched nothing but produced errors — try next alternative
// Roll back errors from this failed attempt
errors.truncate(before_errors);
}
// If consumed == 0 and no errors, this alternative didn't match; try next
}
ParticleKind::Choice(sub_particles) => {
let sub_min = p.min_occurs;
let sub_max = &p.max_occurs;
let before_errors = errors.len();
let consumed = self.validate_choice(
doc,
&children[child_idx..],
sub_particles,
sub_min,
sub_max,
parent,
errors,
);
if consumed > 0 {
child_idx += consumed;
matched_any = true;
break;
} else if errors.len() > before_errors {
// Sub-choice matched nothing but produced errors — try next alternative
errors.truncate(before_errors);
}
}
ParticleKind::Any {
namespace_constraint,
process_contents,
} => {
if wildcard_allows_namespace(
namespace_constraint,
elem.name.namespace_uri.as_deref(),
) {
// Consume as many wildcard-matching elements as allowed
let max = match p.max_occurs {
MaxOccurs::Bounded(n) => n as usize,
MaxOccurs::Unbounded => usize::MAX,
};
let mut count = 0usize;
while child_idx < children.len() && count < max {
let child = children[child_idx];
if let Some(child_elem) = doc.element(child) {
if wildcard_allows_namespace(
namespace_constraint,
child_elem.name.namespace_uri.as_deref(),
) {
match process_contents {
ProcessContents::Skip => {}
ProcessContents::Lax => {
if let Some(global_decl) = self.find_global_element(
&child_elem.name.local_name,
child_elem.name.namespace_uri.as_deref(),
) {
self.validate_element(
doc,
child,
&global_decl,
errors,
);
}
}
ProcessContents::Strict => {
if let Some(global_decl) = self.find_global_element(
&child_elem.name.local_name,
child_elem.name.namespace_uri.as_deref(),
) {
self.validate_element(
doc,
child,
&global_decl,
errors,
);
} else {
errors.push(ValidationError {
message: format!(
"No global element declaration found for '{}' (strict wildcard)",
child_elem.name.local_name
),
line: Some(doc.node_line(child)),
column: Some(doc.node_column(child)),
});
}
}
}
child_idx += 1;
count += 1;
} else {
break;
}
} else {
break;
}
}
matched_any = count > 0;
if matched_any {
break;
}
}
}
}
}
if !matched_any {
// Current child doesn't match any alternative
if choice_reps < compositor_min {
errors.push(ValidationError {
message: format!(
"Element '{}' does not match any choice alternative",
elem.name.local_name
),
line: Some(doc.node_line(current_child)),
column: Some(doc.node_column(current_child)),
});
}
break;
}
choice_reps += 1;
}
if choice_reps < compositor_min && child_idx == 0 && errors.is_empty() {
// No children matched and no error was emitted yet
let any_optional = particles.iter().any(|p| p.min_occurs == 0);
if !any_optional && !particles.is_empty() {
errors.push(ValidationError {
message: "Expected one of the choice alternatives".to_string(),
line: Some(doc.node_line(parent)),
column: Some(doc.node_column(parent)),
});
}
}
child_idx
}
/// Validate an `xs:all` content model.
///
/// In an all group, each particle can appear at most once, and order doesn't matter.
/// Required particles (min_occurs > 0) must all be present.
/// Supports both element particles and wildcard particles.
fn validate_all(
&self,
doc: &Document,
children: &[NodeId],
particles: &[Particle],
parent: NodeId,
errors: &mut Vec<ValidationError>,
) {
let mut matched = vec![false; particles.len()];
for &child in children {
if let Some(elem) = doc.element(child) {
let mut found = false;
for (i, particle) in particles.iter().enumerate() {
match &particle.kind {
ParticleKind::Element(decl) => {
let name_matches = decl.name == elem.name.local_name;
let ns_matches = match (&elem.name.namespace_uri, &decl.namespace) {
(Some(a), Some(b)) => a == b,
(None, None) => true,
(Some(_), None) => false,
(None, Some(_)) => false,
};
let subst_decl = if !(name_matches && ns_matches) {
self.element_matches_with_substitution(
&elem.name.local_name,
elem.name.namespace_uri.as_deref(),
decl,
)
} else {
None
};
if (name_matches && ns_matches) || subst_decl.is_some() {
if matched[i] {
errors.push(ValidationError {
message: format!(
"Duplicate element '{}' in all group",
elem.name.local_name
),
line: Some(doc.node_line(child)),
column: Some(doc.node_column(child)),
});
} else {
matched[i] = true;
if let Some(ref sd) = subst_decl {
self.validate_element(doc, child, sd, errors);
} else {
self.validate_element(doc, child, decl, errors);
}
}
found = true;
break;
}
}
ParticleKind::Any {
namespace_constraint,
process_contents,
} => {
if wildcard_allows_namespace(
namespace_constraint,
elem.name.namespace_uri.as_deref(),
) {
matched[i] = true;
match process_contents {
ProcessContents::Skip => {}
ProcessContents::Lax => {
if let Some(global_decl) = self.find_global_element(
&elem.name.local_name,
elem.name.namespace_uri.as_deref(),
) {
self.validate_element(doc, child, &global_decl, errors);
}
}
ProcessContents::Strict => {
if let Some(global_decl) = self.find_global_element(
&elem.name.local_name,
elem.name.namespace_uri.as_deref(),
) {
self.validate_element(doc, child, &global_decl, errors);
} else {
errors.push(ValidationError {
message: format!(
"No global element declaration found for '{}' (strict wildcard)",
elem.name.local_name
),
line: Some(doc.node_line(child)),
column: Some(doc.node_column(child)),
});
}
}
}
found = true;
break;
}
}
_ => {}
}
}
if !found {
errors.push(ValidationError {
message: format!(
"Unexpected element '{}' in all group",
elem.name.local_name
),
line: Some(doc.node_line(child)),
column: Some(doc.node_column(child)),
});
}
}
}
// Check required elements
for (i, particle) in particles.iter().enumerate() {
if particle.min_occurs > 0 && !matched[i] {
if let ParticleKind::Element(decl) = &particle.kind {
errors.push(ValidationError {
message: format!(
"Required element '{}' is missing in all group",
decl.name
),
line: Some(doc.node_line(parent)),
column: Some(doc.node_column(parent)),
});
}
}
}
}
/// Validate simple (text) content of an element against a simple type definition.
///
/// Handles both list types (whitespace-separated items validated individually)
/// and atomic types. Applies XSD whiteSpace normalization before validation.
fn validate_simple_content(
&self,
doc: &Document,
node: NodeId,
st: &SimpleTypeDef,
errors: &mut Vec<ValidationError>,
) {
let raw_text = doc.text_content_deep(node);
// Apply XSD whiteSpace normalization before any validation.
let ws_mode = whitespace_for_type(&st.base);
let text = apply_whitespace_normalization(&raw_text, &ws_mode);
if st.is_list {
// List type: value is whitespace-separated items
let items: Vec<&str> = text.split_whitespace().collect();
// Validate each item against the item type
if let Some(ref item_bt) = st.item_type {
for item in &items {
validate_builtin_value(item, item_bt, doc, node, errors);
// Also validate item-level facets (from user-defined item types)
for facet in &st.item_facets {
validate_facet(
item,
facet,
item_bt,
doc,
node,
errors,
self.enforce_qname_length_facets,
);
}
}
}
// Validate list-level facets (length counts items, not chars)
for facet in &st.facets {
validate_list_facet(&items, facet, &text, doc, node, errors);
}
} else {
validate_builtin_value(&text, &st.base, doc, node, errors);
// Validate facets
for facet in &st.facets {
validate_facet(
&text,
facet,
&st.base,
doc,
node,
errors,
self.enforce_qname_length_facets,
);
}
}
}
/// Validate an attribute value against its declared type reference.
///
/// Handles all three forms of type references:
/// - `BuiltIn` → validate directly against the built-in type
/// - `Inline` → resolve to simple type and validate with facets
/// - `Named` → look up in schema types map and validate
fn validate_attribute_value(
&self,
value: &str,
type_ref: &TypeRef,
doc: &Document,
node: NodeId,
errors: &mut Vec<ValidationError>,
) {
match type_ref {
TypeRef::BuiltIn(bt) => {
validate_builtin_value(value, bt, doc, node, errors);
}
TypeRef::Inline(td) => {
match td.as_ref() {
TypeDef::Simple(st) => {
if st.is_list {
let items: Vec<&str> = value.split_whitespace().collect();
if let Some(ref item_bt) = st.item_type {
for item in &items {
validate_builtin_value(item, item_bt, doc, node, errors);
for facet in &st.item_facets {
validate_facet(
item,
facet,
item_bt,
doc,
node,
errors,
self.enforce_qname_length_facets,
);
}
}
}
for facet in &st.facets {
validate_list_facet(&items, facet, value, doc, node, errors);
}
} else {
validate_builtin_value(value, &st.base, doc, node, errors);
for facet in &st.facets {
validate_facet(
value,
facet,
&st.base,
doc,
node,
errors,
self.enforce_qname_length_facets,
);
}
}
}
TypeDef::Complex(_) => {
// Attributes shouldn't have complex types
}
}
}
TypeRef::Named(ns, name) => {
// Try to resolve the named type
let key = (ns.clone(), name.clone());
debug_log!(
"validate_attribute_value Named key={:?} found={}",
key,
self.types.contains_key(&key)
);
if let Some(TypeDef::Simple(st)) = self.types.get(&key) {
debug_log!("SimpleTypeDef base={:?} facets={:?}", st.base, st.facets);
if st.is_list {
let items: Vec<&str> = value.split_whitespace().collect();
if let Some(ref item_bt) = st.item_type {
for item in &items {
validate_builtin_value(item, item_bt, doc, node, errors);
for facet in &st.item_facets {
validate_facet(
item,
facet,
item_bt,
doc,
node,
errors,
self.enforce_qname_length_facets,
);
}
}
}
for facet in &st.facets {
validate_list_facet(&items, facet, value, doc, node, errors);
}
} else {
validate_builtin_value(value, &st.base, doc, node, errors);
for facet in &st.facets {
validate_facet(
value,
facet,
&st.base,
doc,
node,
errors,
self.enforce_qname_length_facets,
);
}
}
} else if ns.as_deref() == Some(XS_NAMESPACE) {
// It's a built-in XSD type
if let Some(bt) = parse_builtin_type(name) {
validate_builtin_value(value, &bt, doc, node, errors);
}
}
}
}
}
}