xsd-schema 0.1.0

XML Schema (XSD 1.0/1.1) validator with PSVI and a built-in XPath 2.0 engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
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
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
//! Reference resolution for QName → component ID conversion
//!
//! This module resolves QName string references to component keys (IDs).
//! It is run after all schemas are parsed and assembled, but before
//! type derivation validation or content model compilation.
//!
//! # Resolution Process
//!
//! 1. Check built-in types first (for XS namespace types)
//! 2. Look up in namespace tables for user-defined types
//! 3. Return error with source location if not found
//!
//! # Supported References
//!
//! - Type references (QName → TypeKey)
//! - Element references (QName → ElementKey)
//! - Attribute references (QName → AttributeKey)
//! - Model group references (QName → ModelGroupKey)
//! - Attribute group references (QName → AttributeGroupKey)
//! - Notation references (QName → NotationKey)

use crate::error::{SchemaError, SchemaResult};
use crate::ids::*;
use crate::parser::frames::SimpleTypeVariety;
use crate::parser::frames::{QNameRef, TypeRefResult};
use crate::parser::location::SourceRef;
use crate::schema::composition::ComponentKind;
use crate::schema::SchemaSet;

/// Enforce XSD §3.17.6.2 `src-resolve` clause 4 (per-document QName visibility)
/// for a (namespace, local) pair attributed to a lexical document via `source`.
///
/// Returns `Ok(())` when no source is attached (synthesized arena entries are
/// not subject to src-resolve) or when the namespace is reachable from the
/// lexical document. Otherwise returns a `src-resolve` error.
pub(crate) fn check_namespace_visible_ns(
    schema_set: &SchemaSet,
    namespace: Option<NameId>,
    local_name: NameId,
    source: Option<&SourceRef>,
    kind_label: &str,
) -> SchemaResult<()> {
    let Some(source) = source else { return Ok(()) };
    let Some(doc) = schema_set.documents.get(source.doc_id as usize) else {
        return Ok(());
    };
    if doc.can_see_namespace(namespace, &schema_set.name_table) {
        return Ok(());
    }
    let location = schema_set.source_maps.locate(source);
    let qname_str = format_resolved_qname(&schema_set.name_table, namespace, local_name);
    let ns_label = match namespace {
        Some(ns) => format!("'{}'", schema_set.name_table.resolve_ref(ns)),
        None => "the absent namespace".to_string(),
    };
    Err(SchemaError::structural(
        "src-resolve",
        format!(
            "{} reference '{}' to namespace {} is not <xs:import>-ed by schema document '{}'",
            kind_label, qname_str, ns_label, doc.base_uri,
        ),
        location,
    ))
}

/// Convenience wrapper around [`check_namespace_visible_ns`] for callers that
/// already hold a `QNameRef`.
pub(crate) fn check_namespace_visible(
    schema_set: &SchemaSet,
    qname: &QNameRef,
    source: Option<&SourceRef>,
    kind_label: &str,
) -> SchemaResult<()> {
    check_namespace_visible_ns(schema_set, qname.namespace, qname.local_name, source, kind_label)
}

/// Reference resolver for QName → component ID resolution
///
/// This struct holds a reference to the schema set and provides
/// methods to resolve different types of QName references.
pub struct ReferenceResolver<'a> {
    schema_set: &'a SchemaSet,
}

impl<'a> ReferenceResolver<'a> {
    /// Create a new reference resolver for the given schema set
    pub fn new(schema_set: &'a SchemaSet) -> Self {
        Self { schema_set }
    }

    /// Resolve a type reference (QName → TypeKey)
    ///
    /// Checks built-in types first, then user-defined types.
    /// The namespace should already be resolved during parsing via NamespaceContextSnapshot.
    pub fn resolve_type_ref(
        &self,
        qname: &QNameRef,
        source: Option<&SourceRef>,
    ) -> SchemaResult<TypeKey> {
        // Use the namespace resolved during parsing
        let namespace = qname.namespace;

        // 1. Check built-in types first (XS namespace)
        if let Some(type_key) = self
            .schema_set
            .get_built_in_type_by_qname(namespace, qname.local_name)
        {
            return Ok(type_key);
        }

        // §3.17.6.2 clause 4 — per-document QName visibility gate.
        check_namespace_visible(self.schema_set, qname, source, "Type")?;

        // 2. Look up in namespace table
        if let Some(type_key) = self.schema_set.lookup_type(namespace, qname.local_name) {
            return Ok(type_key);
        }

        // 3. Not found - error with provenance note
        let location = source.and_then(|s| self.schema_set.source_maps.locate(s));
        Err(SchemaError::structural(
            "src-resolve",
            format_type_not_found_message(self.schema_set, qname, "Type"),
            location,
        ))
    }

    /// Lookup-only variant of [`resolve_type_ref`]: returns `Ok(None)` when
    /// the QName resolves to no component, while still propagating
    /// namespace-visibility errors as `Err`. Used by callers that want to
    /// defer a missing-component miss instead of failing compilation.
    pub fn try_resolve_type_ref(
        &self,
        qname: &QNameRef,
        source: Option<&SourceRef>,
    ) -> SchemaResult<Option<TypeKey>> {
        if let Some(type_key) = self
            .schema_set
            .get_built_in_type_by_qname(qname.namespace, qname.local_name)
        {
            return Ok(Some(type_key));
        }
        check_namespace_visible(self.schema_set, qname, source, "Type")?;
        Ok(self.schema_set.lookup_type(qname.namespace, qname.local_name))
    }

    /// Lookup-only variant of [`resolve_element_ref`]: returns `Ok(None)` for
    /// the "not found" case, while still propagating visibility errors.
    pub fn try_resolve_element_ref(
        &self,
        qname: &QNameRef,
        source: Option<&SourceRef>,
    ) -> SchemaResult<Option<ElementKey>> {
        check_namespace_visible(self.schema_set, qname, source, "Element")?;
        Ok(self
            .schema_set
            .lookup_element(qname.namespace, qname.local_name))
    }

    /// Resolve a TypeRefResult to a TypeKey
    ///
    /// Handles both QName references and inline types.
    /// For inline types, the type must already be allocated in the arena.
    pub fn resolve_type_ref_result(
        &self,
        type_ref: &TypeRefResult,
        source: Option<&SourceRef>,
    ) -> SchemaResult<Option<TypeKey>> {
        match type_ref {
            TypeRefResult::QName(qname) => Ok(Some(self.resolve_type_ref(qname, source)?)),
            TypeRefResult::Inline(_) => {
                // Inline types are handled during assembly and should already
                // have their keys stored elsewhere. Return None to indicate
                // the caller should use the inline type key.
                Ok(None)
            }
        }
    }

    /// Resolve a component reference by looking up in the schema set's namespace
    /// tables, returning a `src-resolve` error if not found.
    ///
    /// When a lookup fails the error message is enriched with provenance
    /// information (e.g. "originally in base.xsd, redefined by main.xsd")
    /// when available.
    fn resolve_ref<K: Copy>(
        &self,
        qname: &QNameRef,
        source: Option<&SourceRef>,
        kind_label: &str,
        component_kind: ComponentKind,
        lookup: impl FnOnce(&SchemaSet, Option<NameId>, NameId) -> Option<K>,
    ) -> SchemaResult<K> {
        // §3.17.6.2 clause 4 — per-document QName visibility gate.
        check_namespace_visible(self.schema_set, qname, source, kind_label)?;
        if let Some(key) = lookup(self.schema_set, qname.namespace, qname.local_name) {
            return Ok(key);
        }
        let location = source.and_then(|s| self.schema_set.source_maps.locate(s));
        let name_str = self.format_qname(qname);
        let note = self.schema_set.format_provenance_note(
            component_kind,
            qname.namespace,
            qname.local_name,
        );
        Err(SchemaError::structural(
            "src-resolve",
            format!("{} '{}' not found{}", kind_label, name_str, note),
            location,
        ))
    }

    /// Resolve an element reference (QName → ElementKey)
    pub fn resolve_element_ref(
        &self,
        qname: &QNameRef,
        source: Option<&SourceRef>,
    ) -> SchemaResult<ElementKey> {
        self.resolve_ref(
            qname,
            source,
            "Element",
            ComponentKind::Element,
            SchemaSet::lookup_element,
        )
    }

    /// Resolve an attribute reference (QName → AttributeKey)
    pub fn resolve_attribute_ref(
        &self,
        qname: &QNameRef,
        source: Option<&SourceRef>,
    ) -> SchemaResult<AttributeKey> {
        self.resolve_ref(
            qname,
            source,
            "Attribute",
            ComponentKind::Attribute,
            SchemaSet::lookup_attribute,
        )
    }

    /// Resolve a model group reference (QName → ModelGroupKey)
    pub fn resolve_group_ref(
        &self,
        qname: &QNameRef,
        source: Option<&SourceRef>,
    ) -> SchemaResult<ModelGroupKey> {
        self.resolve_ref(
            qname,
            source,
            "Group",
            ComponentKind::ModelGroup,
            SchemaSet::lookup_model_group,
        )
    }

    /// Resolve an attribute group reference (QName → AttributeGroupKey)
    pub fn resolve_attribute_group_ref(
        &self,
        qname: &QNameRef,
        source: Option<&SourceRef>,
    ) -> SchemaResult<AttributeGroupKey> {
        self.resolve_ref(
            qname,
            source,
            "Attribute group",
            ComponentKind::AttributeGroup,
            SchemaSet::lookup_attribute_group,
        )
    }

    /// Resolve a notation reference (QName → NotationKey)
    pub fn resolve_notation_ref(
        &self,
        qname: &QNameRef,
        source: Option<&SourceRef>,
    ) -> SchemaResult<NotationKey> {
        self.resolve_ref(
            qname,
            source,
            "Notation",
            ComponentKind::Notation,
            SchemaSet::lookup_notation,
        )
    }

    /// Format a QName for error messages
    fn format_qname(&self, qname: &QNameRef) -> String {
        format_resolved_qname(
            &self.schema_set.name_table,
            qname.namespace,
            qname.local_name,
        )
    }
}

/// Format a resolved QName (namespace + local name) for error messages.
pub(crate) fn format_resolved_qname(
    name_table: &crate::namespace::NameTable,
    namespace: Option<crate::ids::NameId>,
    local_name: crate::ids::NameId,
) -> String {
    let local = name_table.resolve(local_name);
    if let Some(ns_id) = namespace {
        let ns = name_table.resolve(ns_id);
        if ns.is_empty() {
            local
        } else {
            format!("{{{}}}{}", ns, local)
        }
    } else {
        local
    }
}

/// Collected resolution results for a component
#[derive(Debug, Default)]
pub struct ResolvedReferences {
    /// Resolved type reference for elements/attributes
    pub resolved_type: Option<TypeKey>,
    /// Resolved element reference (for element refs)
    pub resolved_ref: Option<ElementKey>,
    /// Resolved substitution group heads
    pub resolved_substitution_groups: Vec<ElementKey>,
    /// Resolved attribute reference (for attribute refs)
    pub resolved_attr_ref: Option<AttributeKey>,
    /// Resolved base type for type definitions
    pub resolved_base_type: Option<TypeKey>,
    /// Resolved item type for list types
    pub resolved_item_type: Option<TypeKey>,
    /// Resolved member types for union types
    pub resolved_member_types: Vec<TypeKey>,
    /// Resolved attribute group references
    pub resolved_attribute_groups: Vec<AttributeGroupKey>,
    /// Resolved model group reference
    pub resolved_group_ref: Option<ModelGroupKey>,
}

/// Statistics from the resolution pass
#[derive(Debug, Default)]
pub struct ResolutionStats {
    /// Number of type references resolved
    pub types_resolved: usize,
    /// Number of element references resolved
    pub elements_resolved: usize,
    /// Number of attribute references resolved
    pub attributes_resolved: usize,
    /// Number of group references resolved
    pub groups_resolved: usize,
    /// Number of attribute group references resolved
    pub attribute_groups_resolved: usize,
    /// Number of notation references resolved
    pub notations_resolved: usize,
    /// Total errors encountered
    pub errors: usize,
}

/// Drain `pending_ic_refs` for one element and try to resolve each entry.
///
/// On success the target is appended to the element's `identity_constraints`.
/// On failure: if `defer_failures` is true, the entry is kept on the element
/// for a later retry pass; otherwise the error is appended to `errors`.
fn drain_pending_ic_refs_for(
    schema_set: &mut SchemaSet,
    key: ElementKey,
    defer_failures: bool,
    errors: &mut Vec<SchemaError>,
) {
    let pending = std::mem::take(&mut schema_set.arenas.elements[key].pending_ic_refs);
    if pending.is_empty() {
        return;
    }
    let target_ns = schema_set.arenas.elements[key].target_namespace;
    let mut still_pending = Vec::new();
    for (kind, ref_name, source) in pending {
        match crate::schema::inline::resolve_ic_ref(
            kind,
            &ref_name,
            source.as_ref(),
            target_ns,
            schema_set,
        ) {
            Ok(target_key) => {
                schema_set.arenas.elements[key]
                    .identity_constraints
                    .push(target_key);
            }
            Err(e) => {
                if defer_failures {
                    still_pending.push((kind, ref_name, source));
                } else {
                    errors.push(e);
                }
            }
        }
    }
    if !still_pending.is_empty() {
        schema_set.arenas.elements[key].pending_ic_refs = still_pending;
    }
}

/// Finalize any remaining pending IC `@ref` references on elements.
///
/// `resolve_all_references` keeps unresolved IC refs in `pending_ic_refs`
/// because the target IC may live on a *local* element, which isn't
/// allocated until `allocate_content_particle_elements`. After that pass
/// runs, we call this function to resolve and clear the remaining refs,
/// reporting an error for any still-unresolved ones.
pub fn finalize_pending_ic_refs(schema_set: &mut SchemaSet) -> SchemaResult<()> {
    let element_keys: Vec<ElementKey> = schema_set.arenas.elements.keys().collect();
    let mut errors: Vec<SchemaError> = Vec::new();
    for key in element_keys {
        drain_pending_ic_refs_for(schema_set, key, false, &mut errors);
    }
    if let Some(first) = errors.into_iter().next() {
        return Err(first);
    }
    Ok(())
}

/// Resolve all references in a schema set
///
/// This function walks all components and resolves QName references
/// to component keys. It should be called after all schemas are
/// parsed and assembled, but before type derivation validation.
///
/// # Errors
///
/// Returns an error if any reference cannot be resolved.
/// The error will contain the source location of the unresolved reference.
pub fn resolve_all_references(schema_set: &mut SchemaSet) -> SchemaResult<ResolutionStats> {
    let mut stats = ResolutionStats::default();
    let mut errors: Vec<SchemaError> = Vec::new();

    // Create resolver (borrows schema_set immutably for lookups)
    // We need to collect keys first, then iterate with mutable access

    // Collect all keys first to avoid borrowing issues
    let element_keys: Vec<ElementKey> = schema_set.arenas.elements.keys().collect();
    let attribute_keys: Vec<AttributeKey> = schema_set.arenas.attributes.keys().collect();
    let simple_type_keys: Vec<SimpleTypeKey> = schema_set.arenas.simple_types.keys().collect();
    let complex_type_keys: Vec<ComplexTypeKey> = schema_set.arenas.complex_types.keys().collect();
    let model_group_keys: Vec<ModelGroupKey> = schema_set.arenas.model_groups.keys().collect();
    let attribute_group_keys: Vec<AttributeGroupKey> =
        schema_set.arenas.attribute_groups.keys().collect();

    // Resolve element references
    for key in &element_keys {
        if let Err(e) = resolve_element_references(schema_set, *key, &mut stats) {
            errors.push(e);
            stats.errors += 1;
        }
    }

    // Post-pass: inherit type from substitution group head for elements that have a
    // substitutionGroup but no explicit type (§3.3.2.1 rule 3).  We iterate until
    // stable so that transitive chains (A → B → C where none have an explicit type)
    // are fully resolved.
    if errors.is_empty() {
        loop {
            let mut changed = false;
            for &key in &element_keys {
                let (needs_type, subst_groups) = {
                    let elem = schema_set.arenas.elements.get(key).unwrap();
                    (
                        elem.resolved_type.is_none()
                            && elem.resolved_ref.is_none()
                            && elem.deferred_type_error.is_none()
                            && !elem.resolved_substitution_groups.is_empty(),
                        elem.resolved_substitution_groups.clone(),
                    )
                };
                if needs_type {
                    for &head_key in &subst_groups {
                        if let Some(head_type) = schema_set
                            .arenas
                            .elements
                            .get(head_key)
                            .and_then(|h| h.resolved_type)
                        {
                            let elem = schema_set.arenas.elements.get_mut(key).unwrap();
                            assign_element_type(elem, head_type);
                            changed = true;
                            break;
                        }
                    }
                }
            }
            if !changed {
                break;
            }
        }
        // Secondary post-pass: when no head has a resolved type but at least
        // one carries a deferred src-resolve error on its own `type` attribute,
        // propagate that deferred error down to the member. Without this, the
        // late `xs:anyType` fallback below would silently substitute anyType
        // and runtime validation against the member would never fire the
        // deferred error.
        for &key in &element_keys {
            let needs_deferred = {
                let elem = schema_set.arenas.elements.get(key).unwrap();
                elem.resolved_type.is_none()
                    && elem.resolved_ref.is_none()
                    && elem.deferred_type_error.is_none()
                    && !elem.resolved_substitution_groups.is_empty()
            };
            if !needs_deferred {
                continue;
            }
            let inherited = {
                let elem = schema_set.arenas.elements.get(key).unwrap();
                elem.resolved_substitution_groups
                    .iter()
                    .find_map(|&head_key| {
                        schema_set
                            .arenas
                            .elements
                            .get(head_key)
                            .and_then(|h| h.deferred_type_error.clone())
                    })
            };
            if let Some(deferred) = inherited {
                if let Some(elem) = schema_set.arenas.elements.get_mut(key) {
                    elem.deferred_type_error = Some(deferred);
                }
            }
        }
        // Final anyType fallback for elements that still have no type (e.g., circular
        // substitution group chains or heads that themselves have no type).
        // Skip elements that carry a deferred src-resolve error on their explicit
        // `type` attribute — runtime must report the deferred error rather than
        // silently substituting `xs:anyType`.
        let any_type = TypeKey::Complex(schema_set.any_type_key());
        for &key in &element_keys {
            if let Some(elem) = schema_set.arenas.elements.get_mut(key) {
                if elem.resolved_type.is_none()
                    && elem.resolved_ref.is_none()
                    && elem.deferred_type_error.is_none()
                {
                    assign_element_type(elem, any_type);
                }
            }
        }
    }

    // Resolve XSD 1.1 identity constraint @ref references on top-level elements.
    // This runs after element resolution so ICs from all elements are registered.
    // Failures are KEPT in `pending_ic_refs` so a later pass (after local
    // elements are allocated) can resolve refs that point to ICs declared on
    // a local element — otherwise the local IC isn't registered yet here.
    for &key in &element_keys {
        drain_pending_ic_refs_for(schema_set, key, true, &mut errors);
    }

    // Resolve attribute references
    for key in attribute_keys {
        if let Err(e) = resolve_attribute_references(schema_set, key, &mut stats) {
            errors.push(e);
            stats.errors += 1;
        }
    }

    // Resolve simple type references. Run twice so that a restriction-of-X
    // type whose base X resolves later in the arena order can still inherit
    // X's variety / resolved_member_types / resolved_item_type.  Without
    // the second pass, dt = restriction(inline-union) ends up with
    // variety=Union and an empty resolved_member_types vector when dt is
    // visited before the inline union (saxon simple016).
    for key in simple_type_keys.clone() {
        if let Err(e) = resolve_simple_type_references(schema_set, key, &mut stats) {
            errors.push(e);
            stats.errors += 1;
        }
    }
    for key in simple_type_keys {
        if let Err(e) = resolve_simple_type_references(schema_set, key, &mut stats) {
            errors.push(e);
            stats.errors += 1;
        }
    }

    // Resolve complex type references
    for &key in &complex_type_keys {
        if let Err(e) = resolve_complex_type_references(schema_set, key, &mut stats) {
            errors.push(e);
            stats.errors += 1;
        }
    }

    // Resolve model group references
    for key in model_group_keys {
        if let Err(e) = resolve_model_group_references(schema_set, key, &mut stats) {
            errors.push(e);
            stats.errors += 1;
        }
    }

    // Resolve attribute group references
    for key in attribute_group_keys {
        if let Err(e) = resolve_attribute_group_references(schema_set, key, &mut stats) {
            errors.push(e);
            stats.errors += 1;
        }
    }

    // Resolve notation references
    // Note: Notation references can appear in:
    // 1. The NOTATION facet in simple type restrictions
    // 2. Element declarations (rare)
    // Currently the data model doesn't store unresolved notation QNames,
    // but we iterate notations here for completeness and future support.
    let notation_keys: Vec<NotationKey> = schema_set.arenas.notations.keys().collect();
    for key in notation_keys {
        if let Err(e) = resolve_notation_references(schema_set, key, &mut stats) {
            errors.push(e);
            stats.errors += 1;
        }
    }

    // Resolve schema-level defaultAttributes and inject into complex types
    // Step A: Pre-resolve document-level default attribute groups
    let mut doc_default_attr_groups: Vec<Option<AttributeGroupKey>> =
        Vec::with_capacity(schema_set.documents.len());
    for doc in &schema_set.documents {
        if let Some(ref qname) = doc.default_attributes {
            if let Err(e) = check_namespace_visible_ns(
                schema_set,
                qname.namespace_uri,
                qname.local_name,
                doc.source.as_ref(),
                "Attribute group",
            ) {
                errors.push(e);
                stats.errors += 1;
                doc_default_attr_groups.push(None);
                continue;
            }
            if let Some(key) =
                schema_set.lookup_attribute_group(qname.namespace_uri, qname.local_name)
            {
                doc_default_attr_groups.push(Some(key));
                stats.attribute_groups_resolved += 1;
            } else {
                // Step B: Error for unresolvable defaultAttributes
                let location = schema_set.locate(doc.source.as_ref());
                let name_str = format_resolved_qname(
                    &schema_set.name_table,
                    qname.namespace_uri,
                    qname.local_name,
                );
                errors.push(SchemaError::structural(
                    "src-resolve",
                    format!("Attribute group '{}' not found", name_str),
                    location,
                ));
                stats.errors += 1;
                doc_default_attr_groups.push(None);
            }
        } else {
            doc_default_attr_groups.push(None);
        }
    }

    // Step C: Inject default attribute group into applicable complex types
    for &key in &complex_type_keys {
        let doc_id = {
            let type_def = match schema_set.arenas.complex_types.get(key) {
                Some(td) => td,
                None => continue,
            };
            if !type_def.default_attributes_apply {
                continue;
            }
            match type_def.source.as_ref() {
                // Use defaults_doc() so override children read the
                // overridden document's defaultAttributes per §4.2.5.
                Some(src) => src.defaults_doc(),
                None => continue, // synthesized types have no source
            }
        };
        if let Some(Some(group_key)) = doc_default_attr_groups.get(doc_id as usize) {
            let group_key = *group_key;
            let type_def = schema_set.arenas.complex_types.get_mut(key).unwrap();
            if !type_def.resolved_attribute_groups.contains(&group_key) {
                type_def.resolved_attribute_groups.push(group_key);
            }
        }
    }

    // §3.17.6.2 clause 4 — per-document QName visibility on complex-type
    // content particles and model-group particles. References inside
    // particles are NOT looked up by `resolve_all_references` for top-level
    // complex types (they're looked up lazily at NFA compile time), so we
    // must validate visibility here.
    if let Err(e) = validate_particle_qname_visibility(schema_set) {
        errors.push(e);
        stats.errors += 1;
    }

    // If there were errors, return the first one
    if let Some(first_error) = errors.into_iter().next() {
        return Err(first_error);
    }

    Ok(stats)
}

/// Walk complex-type content particles, enforcing §3.17.6.2 clause 4 on every
/// QName reference therein.
///
/// Complex-type content particle refs (element/type/group) are looked up
/// lazily during NFA compilation, bypassing `ReferenceResolver`'s gate; this
/// pass plugs that gap. Top-level model groups are not re-walked — their
/// particles already pass through `resolve_model_group_references`.
fn validate_particle_qname_visibility(schema_set: &SchemaSet) -> SchemaResult<()> {
    use crate::parser::frames::{ParticleResult, ParticleTerm};

    fn visit(
        schema_set: &SchemaSet,
        particles: &[ParticleResult],
        depth: usize,
    ) -> SchemaResult<()> {
        if depth > 64 {
            return Ok(());
        }
        for particle in particles {
            match &particle.term {
                ParticleTerm::Element(elem) => {
                    let src = elem.source.as_ref().or(particle.source.as_ref());
                    if let Some(ref_qn) = &elem.ref_name {
                        check_namespace_visible(schema_set, ref_qn, src, "Element")?;
                    }
                    if let Some(TypeRefResult::QName(qname)) = &elem.type_ref {
                        check_namespace_visible(schema_set, qname, src, "Type")?;
                    }
                }
                ParticleTerm::Group(group_def) => {
                    if let Some(ref_qn) = &group_def.ref_name {
                        check_namespace_visible(
                            schema_set,
                            ref_qn,
                            particle.source.as_ref(),
                            "Group",
                        )?;
                    }
                    visit(schema_set, &group_def.particles, depth + 1)?;
                }
                ParticleTerm::Any(_) => {}
            }
        }
        Ok(())
    }

    for (_, ct) in schema_set.arenas.complex_types.iter() {
        if let crate::parser::frames::ComplexContentResult::Complex(content) = &ct.content {
            if let Some(particle) = &content.particle {
                visit(schema_set, std::slice::from_ref(particle), 0)?;
            }
        }
    }
    Ok(())
}

/// Set an element's resolved type and propagate to XSD 1.1 type alternatives
/// that have no explicit type (they use the element's declared type as fallback).
fn assign_element_type(elem: &mut crate::arenas::ElementDeclData, type_key: TypeKey) {
    elem.resolved_type = Some(type_key);
    #[cfg(feature = "xsd11")]
    for alt in &mut elem.alternatives {
        if alt.resolved_type.is_none() && alt.type_ref.is_none() {
            alt.resolved_type = Some(type_key);
        }
    }
}

/// Resolve references in an element declaration
fn resolve_element_references(
    schema_set: &mut SchemaSet,
    key: ElementKey,
    stats: &mut ResolutionStats,
) -> SchemaResult<()> {
    // First pass: extract QName references we need to resolve (only Clone-able data)
    // Also check if resolved_type is already set (from inline type assembly)
    let (type_qname, ref_name, substitution_groups, source, already_resolved_type) = {
        let elem = schema_set
            .arenas
            .elements
            .get(key)
            .ok_or_else(|| SchemaError::internal("Element not found in arena"))?;

        // Extract QName from TypeRefResult if it's a QName reference
        let type_qname = match &elem.type_ref {
            Some(TypeRefResult::QName(qname)) => Some(qname.clone()),
            _ => None,
        };

        (
            type_qname,
            elem.ref_name.clone(),
            elem.substitution_group.clone(),
            elem.source.clone(),
            elem.resolved_type, // Already resolved from inline type assembly
        )
    };

    // Create resolver
    let resolver = ReferenceResolver::new(schema_set);

    // XSD 1.0 permits an unresolved `type` reference on an unused element
    // declaration; XSD 1.1 treats the same miss as a fatal compile error.
    let lazy_src_resolve = schema_set.is_xsd10();

    // Resolve type reference (if not already resolved from inline type).
    // Under XSD 1.0, a missing target is deferred via `deferred_type_error`
    // and the schema still compiles. Visibility violations remain fatal.
    let mut deferred_type_error: Option<crate::arenas::DeferredSrcResolve> = None;
    let mut resolved_type = if already_resolved_type.is_some() {
        // Type was already resolved during assembly (inline type)
        already_resolved_type
    } else if let Some(ref qname) = type_qname {
        if lazy_src_resolve {
            match resolver.try_resolve_type_ref(qname, source.as_ref())? {
                Some(type_key) => {
                    stats.types_resolved += 1;
                    Some(type_key)
                }
                None => {
                    deferred_type_error = Some(build_deferred_type_resolve(
                        schema_set,
                        qname,
                        source.as_ref(),
                        "Type",
                    ));
                    None
                }
            }
        } else {
            let type_key = resolver.resolve_type_ref(qname, source.as_ref())?;
            stats.types_resolved += 1;
            Some(type_key)
        }
    } else {
        None
    };
    // Only fall back to anyType when there is no substitution group AND no
    // deferred type error. An explicit but unresolved `type` attribute must
    // not be silently rewritten as `xs:anyType`; runtime checks the deferred
    // error instead. Elements with a substitutionGroup but no explicit type
    // inherit the head's type in the post-pass inside `resolve_all_references`
    // (§3.3.2.1 rule 3).
    if resolved_type.is_none()
        && deferred_type_error.is_none()
        && ref_name.is_none()
        && substitution_groups.is_empty()
    {
        resolved_type = Some(TypeKey::Complex(schema_set.any_type_key()));
    }

    // Resolve element reference (for <xs:element ref="...">)
    let resolved_ref = if let Some(ref qname) = ref_name {
        let elem_key = resolver.resolve_element_ref(qname, source.as_ref())?;
        stats.elements_resolved += 1;
        Some(elem_key)
    } else {
        None
    };

    // Resolve substitution groups. Under XSD 1.0, an unresolved head is
    // dropped silently — direct validation of the affiliating element is
    // still permitted, so the missing affiliation must not poison the rest
    // of the declaration. Under XSD 1.1, a missing head is fatal.
    let mut resolved_subst_groups = Vec::with_capacity(substitution_groups.len());
    for qname in &substitution_groups {
        if lazy_src_resolve {
            match resolver.try_resolve_element_ref(qname, source.as_ref())? {
                Some(elem_key) => {
                    stats.elements_resolved += 1;
                    resolved_subst_groups.push(elem_key);
                }
                None => {
                    // Drop unresolved head; do not poison the affiliating element.
                }
            }
        } else {
            let elem_key = resolver.resolve_element_ref(qname, source.as_ref())?;
            stats.elements_resolved += 1;
            resolved_subst_groups.push(elem_key);
        }
    }

    // Resolve alternative type references (XSD 1.1)
    #[cfg(feature = "xsd11")]
    let resolved_alt_types = {
        let elem = schema_set
            .arenas
            .elements
            .get(key)
            .ok_or_else(|| SchemaError::internal("Element not found in arena"))?;
        let mut alt_types: Vec<Option<TypeKey>> = Vec::with_capacity(elem.alternatives.len());
        for alt in &elem.alternatives {
            if alt.resolved_type.is_some() {
                // Already resolved (from inline type assembly)
                alt_types.push(alt.resolved_type);
            } else if let Some(TypeRefResult::QName(ref qname)) = alt.type_ref {
                let resolver = ReferenceResolver::new(schema_set);
                let type_key = resolver.resolve_type_ref(qname, source.as_ref())?;
                stats.types_resolved += 1;
                alt_types.push(Some(type_key));
            } else {
                // No type specified — use element's declared type as fallback
                alt_types.push(resolved_type);
            }
        }
        alt_types
    };

    // Store resolved references back
    if let Some(elem) = schema_set.arenas.elements.get_mut(key) {
        elem.resolved_type = resolved_type;
        elem.resolved_ref = resolved_ref;
        elem.resolved_substitution_groups = resolved_subst_groups;
        elem.deferred_type_error = deferred_type_error;

        #[cfg(feature = "xsd11")]
        for (i, alt_type) in resolved_alt_types.into_iter().enumerate() {
            if let Some(alt) = elem.alternatives.get_mut(i) {
                alt.resolved_type = alt_type;
            }
        }
    }

    Ok(())
}

/// Format a "type not found" `src-resolve` message with provenance, trying
/// the `SimpleType` arena first and falling back to `ComplexType`. `label`
/// is the human-facing kind ("Type", "List item type") prepended to the
/// QName.
fn format_type_not_found_message(
    schema_set: &SchemaSet,
    qname: &QNameRef,
    label: &str,
) -> String {
    let name_str = format_resolved_qname(&schema_set.name_table, qname.namespace, qname.local_name);
    let simple_note = schema_set.format_provenance_note(
        ComponentKind::SimpleType,
        qname.namespace,
        qname.local_name,
    );
    let note = if simple_note.is_empty() {
        schema_set.format_provenance_note(
            ComponentKind::ComplexType,
            qname.namespace,
            qname.local_name,
        )
    } else {
        simple_note
    };
    format!("{} '{}' not found{}", label, name_str, note)
}

/// Build a deferred `src-resolve` error payload for a missing type reference.
fn build_deferred_type_resolve(
    schema_set: &SchemaSet,
    qname: &QNameRef,
    source: Option<&SourceRef>,
    label: &str,
) -> crate::arenas::DeferredSrcResolve {
    crate::arenas::DeferredSrcResolve {
        message: format_type_not_found_message(schema_set, qname, label),
        source: source.cloned(),
    }
}

/// Resolve references in an attribute declaration
fn resolve_attribute_references(
    schema_set: &mut SchemaSet,
    key: AttributeKey,
    stats: &mut ResolutionStats,
) -> SchemaResult<()> {
    // First pass: extract QName references we need to resolve
    // Also check if resolved_type is already set (from inline type assembly)
    let (type_qname, ref_name, source, already_resolved_type) = {
        let attr = schema_set
            .arenas
            .attributes
            .get(key)
            .ok_or_else(|| SchemaError::internal("Attribute not found in arena"))?;

        // Extract QName from TypeRefResult if it's a QName reference
        let type_qname = match &attr.type_ref {
            Some(TypeRefResult::QName(qname)) => Some(qname.clone()),
            _ => None,
        };

        (
            type_qname,
            attr.ref_name.clone(),
            attr.source.clone(),
            attr.resolved_type,
        )
    };

    // Create resolver
    let resolver = ReferenceResolver::new(schema_set);

    // Resolve type reference (if not already resolved from inline type)
    let resolved_type = if already_resolved_type.is_some() {
        // Type was already resolved during assembly (inline type)
        already_resolved_type
    } else if let Some(ref qname) = type_qname {
        let type_key = resolver.resolve_type_ref(qname, source.as_ref())?;
        stats.types_resolved += 1;
        Some(type_key)
    } else {
        None
    };

    // Resolve attribute reference (for <xs:attribute ref="...">)
    let resolved_ref = if let Some(ref qname) = ref_name {
        let attr_key = resolver.resolve_attribute_ref(qname, source.as_ref())?;
        stats.attributes_resolved += 1;
        Some(attr_key)
    } else {
        None
    };

    // Store resolved references back
    if let Some(attr) = schema_set.arenas.attributes.get_mut(key) {
        attr.resolved_type = resolved_type;
        attr.resolved_ref = resolved_ref;
    }

    Ok(())
}

/// Resolve references in a simple type definition
fn resolve_simple_type_references(
    schema_set: &mut SchemaSet,
    key: SimpleTypeKey,
    stats: &mut ResolutionStats,
) -> SchemaResult<()> {
    // First pass: extract QName references we need to resolve
    // Also get already resolved types from assembly (for inline types)
    let (
        base_qname,
        item_qname,
        member_qnames,
        source,
        already_resolved_base,
        already_resolved_item,
        already_resolved_members,
        redefine_original,
        type_name,
        type_ns,
    ) = {
        let type_def = schema_set
            .arenas
            .simple_types
            .get(key)
            .ok_or_else(|| SchemaError::internal("Simple type not found in arena"))?;

        // Extract QName from TypeRefResult if it's a QName reference
        let base_qname = match &type_def.base_type {
            Some(TypeRefResult::QName(qname)) => Some(qname.clone()),
            _ => None,
        };
        let item_qname = match &type_def.item_type {
            Some(TypeRefResult::QName(qname)) => Some(qname.clone()),
            _ => None,
        };
        let member_qnames: Vec<_> = type_def
            .member_types
            .iter()
            .filter_map(|tr| match tr {
                TypeRefResult::QName(qname) => Some(qname.clone()),
                _ => None,
            })
            .collect();

        (
            base_qname,
            item_qname,
            member_qnames,
            type_def.source.clone(),
            type_def.resolved_base_type,
            type_def.resolved_item_type,
            type_def.resolved_member_types.clone(),
            type_def.redefine_original,
            type_def.name,
            type_def.target_namespace,
        )
    };

    // Create resolver
    let resolver = ReferenceResolver::new(schema_set);

    // Resolve base type reference (for restriction) - if not already resolved
    // For redefine self-references, redirect to the original type key
    let resolved_base = if already_resolved_base.is_some() {
        already_resolved_base
    } else if let Some(ref qname) = base_qname {
        let is_redefine_self_ref = redefine_original.is_some()
            && Some(qname.local_name) == type_name
            && qname.namespace == type_ns;
        if is_redefine_self_ref {
            stats.types_resolved += 1;
            Some(TypeKey::Simple(redefine_original.unwrap()))
        } else {
            let type_key = resolver.resolve_type_ref(qname, source.as_ref())?;
            stats.types_resolved += 1;
            Some(type_key)
        }
    } else {
        None
    };

    // Resolve item type reference (for list) - if not already resolved.
    // Under XSD 1.0, a missing target is deferred via
    // `deferred_item_type_error` and the simple type still compiles. Under
    // XSD 1.1, the miss is fatal. Visibility violations and missing
    // `base` / union `memberTypes` references are always fatal.
    let lazy_src_resolve = schema_set.is_xsd10();
    let mut deferred_item_error: Option<crate::arenas::DeferredSrcResolve> = None;
    let resolved_item = if already_resolved_item.is_some() {
        already_resolved_item
    } else if let Some(ref qname) = item_qname {
        if lazy_src_resolve {
            match resolver.try_resolve_type_ref(qname, source.as_ref())? {
                Some(type_key) => {
                    stats.types_resolved += 1;
                    Some(type_key)
                }
                None => {
                    deferred_item_error = Some(build_deferred_type_resolve(
                        schema_set,
                        qname,
                        source.as_ref(),
                        "List item type",
                    ));
                    None
                }
            }
        } else {
            let type_key = resolver.resolve_type_ref(qname, source.as_ref())?;
            stats.types_resolved += 1;
            Some(type_key)
        }
    } else {
        None
    };

    // Resolve member type references (for union)
    // Per XSD spec, memberTypes attribute members come first, then inline simpleType children
    let mut resolved_members = Vec::new();
    for qname in &member_qnames {
        let type_key = resolver.resolve_type_ref(qname, source.as_ref())?;
        stats.types_resolved += 1;
        resolved_members.push(type_key);
    }
    resolved_members.extend(already_resolved_members);

    // For list and union types without an explicit base, the XSD spec defines the
    // {base type definition} to be anySimpleType (§4.1.2 / §3.16.2.2).
    // Setting resolved_base_type here makes is_simple_type_derived_from work
    // correctly when checking derivation from anySimpleType (e.g. e-props-correct.4).
    let resolved_base = if resolved_base.is_none() {
        let variety = schema_set
            .arenas
            .simple_types
            .get(key)
            .map(|t| t.variety)
            .unwrap_or(SimpleTypeVariety::Atomic);
        if matches!(variety, SimpleTypeVariety::List | SimpleTypeVariety::Union) {
            let any_simple = schema_set.builtin_types().any_simple_type;
            Some(TypeKey::Simple(any_simple))
        } else {
            None
        }
    } else {
        resolved_base
    };

    // Store resolved references back
    if let Some(type_def) = schema_set.arenas.simple_types.get_mut(key) {
        type_def.resolved_base_type = resolved_base;
        type_def.resolved_item_type = resolved_item;
        type_def.resolved_member_types = resolved_members;
        type_def.deferred_item_type_error = deferred_item_error;
    }

    // Inherit variety and structural properties from base type for restriction-derived types.
    // Parser sets variety=Atomic for all restrictions, but restrictions of union/list types
    // must inherit the base type's variety and member types / item type.
    if let Some(TypeKey::Simple(base_sk)) = resolved_base {
        let (base_variety, base_members, base_item, base_deferred_item) = {
            if let Some(base_def) = schema_set.arenas.simple_types.get(base_sk) {
                (
                    base_def.variety,
                    base_def.resolved_member_types.clone(),
                    base_def.resolved_item_type,
                    base_def.deferred_item_type_error.clone(),
                )
            } else {
                (SimpleTypeVariety::Atomic, Vec::new(), None, None)
            }
        };
        if let Some(type_def) = schema_set.arenas.simple_types.get_mut(key) {
            if type_def.variety == SimpleTypeVariety::Atomic
                && base_variety != SimpleTypeVariety::Atomic
            {
                type_def.variety = base_variety;
            }
            if base_variety == SimpleTypeVariety::Union && type_def.resolved_member_types.is_empty()
            {
                type_def.resolved_member_types = base_members;
            }
            if base_variety == SimpleTypeVariety::List && type_def.resolved_item_type.is_none() {
                type_def.resolved_item_type = base_item;
                // Propagate the base's deferred itemType miss so a derived
                // list type doesn't silently fall through to "untyped" at
                // validation time when the base's itemType was lazy-resolved.
                if type_def.deferred_item_type_error.is_none() {
                    type_def.deferred_item_type_error = base_deferred_item;
                }
            }
        }
    }

    Ok(())
}

/// Resolve references in a complex type definition
fn resolve_complex_type_references(
    schema_set: &mut SchemaSet,
    key: ComplexTypeKey,
    stats: &mut ResolutionStats,
) -> SchemaResult<()> {
    use crate::arenas::ResolvedAttributeUse;

    // First pass: extract QName references we need to resolve
    // Also get already resolved base type from assembly (for inline types)
    let (
        base_qname,
        attribute_groups,
        attribute_uses,
        source,
        already_resolved_base,
        redefine_original,
        type_name,
        type_ns,
        already_resolved_attrs,
    ) = {
        let type_def = schema_set
            .arenas
            .complex_types
            .get(key)
            .ok_or_else(|| SchemaError::internal("Complex type not found in arena"))?;

        // Extract QName from TypeRefResult if it's a QName reference
        let base_qname = match &type_def.base_type {
            Some(TypeRefResult::QName(qname)) => Some(qname.clone()),
            _ => None,
        };

        // Extract attribute use info for resolution
        let attribute_uses: Vec<_> = type_def
            .attributes
            .iter()
            .map(|attr_use| {
                let type_qname = match &attr_use.attribute.type_ref {
                    Some(TypeRefResult::QName(qname)) => Some(qname.clone()),
                    _ => None,
                };
                (
                    attr_use.attribute.ref_name.clone(),
                    type_qname,
                    attr_use.attribute.source.clone(),
                )
            })
            .collect();

        // Preserve resolved_attributes from inline type assembly (Phase 3)
        let already_resolved_attrs = type_def.resolved_attributes.clone();

        (
            base_qname,
            type_def.attribute_groups.clone(),
            attribute_uses,
            type_def.source.clone(),
            type_def.resolved_base_type,
            type_def.redefine_original,
            type_def.name,
            type_def.target_namespace,
            already_resolved_attrs,
        )
    };

    // Create resolver
    let resolver = ReferenceResolver::new(schema_set);

    // Resolve base type reference - if not already resolved
    // For redefine self-references, redirect to the original type key
    let resolved_base = if already_resolved_base.is_some() {
        already_resolved_base
    } else if let Some(ref qname) = base_qname {
        let is_redefine_self_ref = redefine_original.is_some()
            && Some(qname.local_name) == type_name
            && qname.namespace == type_ns;
        if is_redefine_self_ref {
            stats.types_resolved += 1;
            Some(TypeKey::Complex(redefine_original.unwrap()))
        } else {
            let type_key = resolver.resolve_type_ref(qname, source.as_ref())?;
            stats.types_resolved += 1;
            Some(type_key)
        }
    } else {
        None
    };

    // Resolve attribute group references
    let mut resolved_attr_groups = Vec::with_capacity(attribute_groups.len());
    for qname in &attribute_groups {
        let group_key = resolver.resolve_attribute_group_ref(qname, source.as_ref())?;
        stats.attribute_groups_resolved += 1;
        resolved_attr_groups.push(group_key);
    }

    // Resolve attribute use references
    let mut resolved_attrs = Vec::with_capacity(attribute_uses.len());
    for (i, (ref_name, type_qname, attr_source)) in attribute_uses.iter().enumerate() {
        let resolved_type = if let Some(ref qname) = type_qname {
            let type_key = resolver.resolve_type_ref(qname, attr_source.as_ref())?;
            stats.types_resolved += 1;
            Some(type_key)
        } else {
            // Preserve type from inline assembly (Phase 3) when no QName ref
            already_resolved_attrs.get(i).and_then(|r| r.resolved_type)
        };
        let resolved_ref = if let Some(ref qname) = ref_name {
            let attr_key = resolver.resolve_attribute_ref(qname, attr_source.as_ref())?;
            stats.attributes_resolved += 1;
            Some(attr_key)
        } else {
            // Preserve ref from inline assembly
            already_resolved_attrs.get(i).and_then(|r| r.resolved_ref)
        };
        resolved_attrs.push(ResolvedAttributeUse {
            resolved_type,
            resolved_ref,
        });
    }

    // Store resolved references back
    if let Some(type_def) = schema_set.arenas.complex_types.get_mut(key) {
        type_def.resolved_base_type = resolved_base;
        type_def.resolved_attribute_groups = resolved_attr_groups;
        type_def.resolved_attributes = resolved_attrs;
    }

    Ok(())
}

/// Resolve references in a model group definition
fn resolve_model_group_references(
    schema_set: &mut SchemaSet,
    key: ModelGroupKey,
    stats: &mut ResolutionStats,
) -> SchemaResult<()> {
    use crate::arenas::ResolvedParticleTerm;
    use crate::parser::frames::ParticleTerm;

    // Get the model group data to read references
    let group = schema_set
        .arenas
        .model_groups
        .get(key)
        .ok_or_else(|| SchemaError::internal("Model group not found in arena"))?;

    // Clone references we need to resolve
    let ref_name = group.ref_name.clone();
    let source = group.source.clone();
    let particles_clone = group.particles.clone();

    // Capture redefine info for self-reference redirection
    let redefine_original = group.redefine_original;
    let group_name = group.name;
    let group_ns = group.target_namespace;

    // Read existing resolved_particles BEFORE building new ones,
    // so we can preserve inline-resolved types from Phase 3.
    let existing_resolved: Vec<_> = group.resolved_particles.clone();
    let existing_particle_types = group.resolved_particle_types.clone();

    // Extract particle info for resolution
    let particle_info: Vec<_> = group
        .particles
        .iter()
        .map(|p| match &p.term {
            ParticleTerm::Element(elem) => {
                let type_qname = match &elem.type_ref {
                    Some(TypeRefResult::QName(qname)) => Some(qname.clone()),
                    _ => None,
                };
                (0, elem.ref_name.clone(), type_qname, p.source.clone())
            }
            ParticleTerm::Group(grp) => (1, grp.ref_name.clone(), None, p.source.clone()),
            ParticleTerm::Any(_) => (2, None, None, p.source.clone()),
        })
        .collect();

    // Create resolver
    let resolver = ReferenceResolver::new(schema_set);

    // Resolve group reference (for <xs:group ref="...">)
    let resolved_ref = if let Some(ref qname) = ref_name {
        let group_key = resolver.resolve_group_ref(qname, source.as_ref())?;
        stats.groups_resolved += 1;
        Some(group_key)
    } else {
        None
    };

    // Resolve particle references
    let mut resolved_particles = Vec::with_capacity(particle_info.len());
    for (i, (kind, elem_or_group_ref, type_qname, particle_source)) in
        particle_info.iter().enumerate()
    {
        match kind {
            0 => {
                // Element particle — preserve inline-resolved type from Phase 3
                let already_resolved_type = existing_resolved.get(i).and_then(|rp| {
                    if let ResolvedParticleTerm::Element {
                        resolved_type: Some(key),
                        ..
                    } = rp
                    {
                        Some(*key)
                    } else {
                        None
                    }
                });
                let resolved_type = if let Some(key) = already_resolved_type {
                    Some(key)
                } else if let Some(ref qname) = type_qname {
                    let type_key = resolver.resolve_type_ref(qname, particle_source.as_ref())?;
                    stats.types_resolved += 1;
                    Some(type_key)
                } else {
                    None
                };
                let resolved_elem_ref = if let Some(ref qname) = elem_or_group_ref {
                    let elem_key = resolver.resolve_element_ref(qname, particle_source.as_ref())?;
                    stats.elements_resolved += 1;
                    Some(elem_key)
                } else {
                    None
                };
                resolved_particles.push(ResolvedParticleTerm::Element {
                    resolved_type,
                    resolved_ref: resolved_elem_ref,
                });
            }
            1 => {
                // Group particle — redirect self-references to the original group
                let resolved_group_ref = if let Some(ref qname) = elem_or_group_ref {
                    let is_self_ref = redefine_original.is_some()
                        && Some(qname.local_name) == group_name
                        && qname.namespace == group_ns;
                    let grp_key = if is_self_ref {
                        redefine_original.unwrap()
                    } else {
                        resolver.resolve_group_ref(qname, particle_source.as_ref())?
                    };
                    stats.groups_resolved += 1;
                    Some(grp_key)
                } else {
                    None
                };
                resolved_particles.push(ResolvedParticleTerm::Group {
                    resolved_ref: resolved_group_ref,
                });
            }
            _ => {
                // Wildcard
                resolved_particles.push(ResolvedParticleTerm::Any);
            }
        }
    }

    // Build flat-indexed resolved_particle_types (including nested inline groups)
    let mut resolved_particle_types = Vec::new();
    let mut flat_idx = 0;
    resolve_model_group_particle_types_recursive(
        &particles_clone,
        &existing_particle_types,
        &resolver,
        &mut flat_idx,
        &mut resolved_particle_types,
        stats,
    )?;

    // Store resolved references back
    if let Some(group) = schema_set.arenas.model_groups.get_mut(key) {
        group.resolved_ref = resolved_ref;
        group.resolved_particles = resolved_particles;
        group.resolved_particle_types = resolved_particle_types;
    }

    Ok(())
}

/// Recursive helper: resolve types for model group particles in depth-first order
fn resolve_model_group_particle_types_recursive(
    particles: &[crate::parser::frames::ParticleResult],
    existing_types: &[Option<TypeKey>],
    resolver: &ReferenceResolver,
    flat_idx: &mut usize,
    resolved_types: &mut Vec<Option<TypeKey>>,
    stats: &mut ResolutionStats,
) -> SchemaResult<()> {
    use crate::parser::frames::ParticleTerm;

    for particle in particles {
        match &particle.term {
            ParticleTerm::Element(elem) => {
                let idx = *flat_idx;
                *flat_idx += 1;
                // Preserve inline-resolved type from Phase 3
                let already_resolved = existing_types.get(idx).copied().flatten();
                let resolved_type = if let Some(key) = already_resolved {
                    Some(key)
                } else {
                    // Try QName resolution
                    match &elem.type_ref {
                        Some(TypeRefResult::QName(qname)) => {
                            let type_key =
                                resolver.resolve_type_ref(qname, particle.source.as_ref())?;
                            stats.types_resolved += 1;
                            Some(type_key)
                        }
                        _ => None,
                    }
                };
                while resolved_types.len() <= idx {
                    resolved_types.push(None);
                }
                resolved_types[idx] = resolved_type;
            }
            ParticleTerm::Group(group_def) if group_def.ref_name.is_none() => {
                resolve_model_group_particle_types_recursive(
                    &group_def.particles,
                    existing_types,
                    resolver,
                    flat_idx,
                    resolved_types,
                    stats,
                )?;
            }
            _ => {} // Skip group refs and wildcards
        }
    }
    Ok(())
}

/// Resolve references in an attribute group definition
fn resolve_attribute_group_references(
    schema_set: &mut SchemaSet,
    key: AttributeGroupKey,
    stats: &mut ResolutionStats,
) -> SchemaResult<()> {
    use crate::arenas::ResolvedAttributeUse;

    // Get the attribute group data to read references
    let group = schema_set
        .arenas
        .attribute_groups
        .get(key)
        .ok_or_else(|| SchemaError::internal("Attribute group not found in arena"))?;

    // Clone references we need to resolve
    let ref_name = group.ref_name.clone();
    let nested_groups = group.attribute_groups.clone();
    let source = group.source.clone();

    // Capture redefine info for self-reference redirection
    let redefine_original = group.redefine_original;
    let group_name = group.name;
    let group_ns = group.target_namespace;

    // Extract attribute use info for resolution
    let attribute_uses: Vec<_> = group
        .attributes
        .iter()
        .map(|attr_use| {
            let type_qname = match &attr_use.attribute.type_ref {
                Some(TypeRefResult::QName(qname)) => Some(qname.clone()),
                _ => None,
            };
            (
                attr_use.attribute.ref_name.clone(),
                type_qname,
                attr_use.attribute.source.clone(),
            )
        })
        .collect();

    // Preserve resolved_attributes from inline type assembly (Phase 3)
    let already_resolved_attrs = group.resolved_attributes.clone();

    // Create resolver
    let resolver = ReferenceResolver::new(schema_set);

    // Resolve group reference (for <xs:attributeGroup ref="...">)
    let resolved_ref = if let Some(ref qname) = ref_name {
        let group_key = resolver.resolve_attribute_group_ref(qname, source.as_ref())?;
        stats.attribute_groups_resolved += 1;
        Some(group_key)
    } else {
        None
    };

    // Resolve nested attribute group references — redirect self-references to the original
    let mut resolved_nested = Vec::with_capacity(nested_groups.len());
    for qname in &nested_groups {
        let is_self_ref = redefine_original.is_some()
            && Some(qname.local_name) == group_name
            && qname.namespace == group_ns;
        let group_key = if is_self_ref {
            redefine_original.unwrap()
        } else {
            resolver.resolve_attribute_group_ref(qname, source.as_ref())?
        };
        stats.attribute_groups_resolved += 1;
        resolved_nested.push(group_key);
    }

    // Resolve attribute use references
    let mut resolved_attrs = Vec::with_capacity(attribute_uses.len());
    for (i, (ref_name_opt, type_qname, attr_source)) in attribute_uses.iter().enumerate() {
        let resolved_type = if let Some(ref qname) = type_qname {
            let type_key = resolver.resolve_type_ref(qname, attr_source.as_ref())?;
            stats.types_resolved += 1;
            Some(type_key)
        } else {
            // Preserve type from inline assembly (Phase 3) when no QName ref
            already_resolved_attrs.get(i).and_then(|r| r.resolved_type)
        };
        let resolved_attr_ref = if let Some(ref qname) = ref_name_opt {
            let attr_key = resolver.resolve_attribute_ref(qname, attr_source.as_ref())?;
            stats.attributes_resolved += 1;
            Some(attr_key)
        } else {
            // Preserve ref from inline assembly
            already_resolved_attrs.get(i).and_then(|r| r.resolved_ref)
        };
        resolved_attrs.push(ResolvedAttributeUse {
            resolved_type,
            resolved_ref: resolved_attr_ref,
        });
    }

    // Store resolved references back
    if let Some(group) = schema_set.arenas.attribute_groups.get_mut(key) {
        group.resolved_ref = resolved_ref;
        group.resolved_attribute_groups = resolved_nested;
        group.resolved_attributes = resolved_attrs;
    }

    Ok(())
}

/// Resolve references in a notation declaration
///
/// Currently notations don't have internal references that need resolution,
/// but this function is provided for completeness and to track notation
/// processing in statistics. In the future, if notation references are
/// added to the data model, resolution logic would go here.
fn resolve_notation_references(
    schema_set: &mut SchemaSet,
    key: NotationKey,
    stats: &mut ResolutionStats,
) -> SchemaResult<()> {
    // Verify the notation exists
    let _notation = schema_set
        .arenas
        .notations
        .get(key)
        .ok_or_else(|| SchemaError::internal("Notation not found in arena"))?;

    // Track notation processing
    stats.notations_resolved += 1;

    // Currently notations don't have unresolved references in the data model.
    // Future: If NOTATION facet references or element notation attributes
    // are stored as QNames, resolve them here.

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::namespace::table::well_known;

    #[test]
    fn test_reference_resolver_creation() {
        let schema_set = SchemaSet::new();
        let _resolver = ReferenceResolver::new(&schema_set);
    }

    #[test]
    fn test_resolve_builtin_type() {
        let schema_set = SchemaSet::new();
        let resolver = ReferenceResolver::new(&schema_set);

        // Create a QNameRef for xs:string
        let string_name = schema_set.name_table.get("string").unwrap();
        let qname = QNameRef {
            prefix: None,
            local_name: string_name,
            namespace: Some(well_known::XS_NAMESPACE),
        };

        let result = resolver.resolve_type_ref(&qname, None);
        assert!(result.is_ok(), "Should resolve xs:string");

        if let Ok(TypeKey::Simple(key)) = result {
            // Verify it's the string type
            let string_key = schema_set.builtin_types().string;
            assert_eq!(key, string_key);
        } else {
            panic!("Expected Simple type key");
        }
    }

    #[test]
    fn test_resolve_builtin_integer() {
        let schema_set = SchemaSet::new();
        let resolver = ReferenceResolver::new(&schema_set);

        // Create a QNameRef for xs:integer
        let integer_name = schema_set.name_table.get("integer").unwrap();
        let qname = QNameRef {
            prefix: None,
            local_name: integer_name,
            namespace: Some(well_known::XS_NAMESPACE),
        };

        let result = resolver.resolve_type_ref(&qname, None);
        assert!(result.is_ok(), "Should resolve xs:integer");
    }

    #[test]
    fn test_resolve_builtin_any_type() {
        let schema_set = SchemaSet::new();
        let resolver = ReferenceResolver::new(&schema_set);

        let any_type_name = schema_set.name_table.get("anyType").unwrap();
        let qname = QNameRef {
            prefix: None,
            local_name: any_type_name,
            namespace: Some(well_known::XS_NAMESPACE),
        };

        let result = resolver.resolve_type_ref(&qname, None);
        assert!(result.is_ok(), "Should resolve xs:anyType");

        if let Ok(TypeKey::Complex(key)) = result {
            assert_eq!(key, schema_set.builtin_types().any_type);
        } else {
            panic!("Expected Complex type key");
        }
    }

    #[test]
    fn test_resolve_unknown_type_error() {
        let schema_set = SchemaSet::new();

        // Add the name before creating the resolver to avoid borrow conflicts
        let unknown_name = schema_set.name_table.add("nonExistentType");

        let resolver = ReferenceResolver::new(&schema_set);
        let qname = QNameRef {
            prefix: None,
            local_name: unknown_name,
            namespace: Some(well_known::XS_NAMESPACE),
        };

        let result = resolver.resolve_type_ref(&qname, None);
        assert!(result.is_err(), "Should fail for unknown type");
    }

    #[test]
    fn test_format_qname_with_namespace() {
        let schema_set = SchemaSet::new();
        let resolver = ReferenceResolver::new(&schema_set);

        // "string" should already exist from built-in types initialization
        let string_name = schema_set.name_table.get("string").unwrap();
        let qname = QNameRef {
            prefix: None,
            local_name: string_name,
            namespace: Some(well_known::XS_NAMESPACE),
        };

        let formatted = resolver.format_qname(&qname);
        assert!(formatted.contains("string"));
        assert!(formatted.contains("XMLSchema"));
    }

    #[test]
    fn test_format_qname_without_namespace() {
        let schema_set = SchemaSet::new();

        // Add the name before creating the resolver to avoid borrow conflicts
        let local_name = schema_set.name_table.add("localType");

        let resolver = ReferenceResolver::new(&schema_set);
        let qname = QNameRef {
            prefix: None,
            local_name,
            namespace: None,
        };

        let formatted = resolver.format_qname(&qname);
        assert_eq!(formatted, "localType");
    }

    #[test]
    fn test_resolution_stats_default() {
        let stats = ResolutionStats::default();
        assert_eq!(stats.types_resolved, 0);
        assert_eq!(stats.elements_resolved, 0);
        assert_eq!(stats.errors, 0);
    }

    #[test]
    fn test_resolve_all_references_empty_schema() {
        let mut schema_set = SchemaSet::new();

        // Should succeed with empty schema (only built-in types)
        let result = resolve_all_references(&mut schema_set);
        assert!(result.is_ok());

        let stats = result.unwrap();
        // Should resolve notations (0 user-defined notations)
        assert_eq!(stats.errors, 0);
    }

    #[test]
    fn test_resolve_user_defined_element_with_builtin_type() {
        use crate::arenas::ElementDeclData;
        use crate::parser::frames::QNameRef;
        use crate::schema::model::DerivationSet;

        let mut schema_set = SchemaSet::new();

        // Get names
        let elem_name = schema_set.name_table.add("myElement");
        let string_name = schema_set.name_table.get("string").unwrap();

        // Create an element with type="xs:string"
        let type_ref = TypeRefResult::QName(QNameRef {
            prefix: None,
            local_name: string_name,
            namespace: Some(well_known::XS_NAMESPACE),
        });

        let elem_data = ElementDeclData {
            name: Some(elem_name),
            target_namespace: None,
            ref_name: None,
            type_ref: Some(type_ref),
            inline_type: None,
            substitution_group: Vec::new(),
            default_value: None,
            fixed_value: None,
            nillable: false,
            is_abstract: false,
            min_occurs: 1,
            max_occurs: Some(1),
            block: DerivationSet::empty(),
            final_derivation: DerivationSet::empty(),
            form: None,
            id: None,
            alternatives: Vec::new(),
            identity_constraints: Vec::new(),
            pending_ic_refs: vec![],
            annotation: None,
            source: None,
            resolved_type: None,
            resolved_ref: None,
            resolved_substitution_groups: Vec::new(),
            deferred_type_error: None,
        };

        let elem_key = schema_set.arenas.alloc_element(elem_data);

        // Resolve references
        let result = resolve_all_references(&mut schema_set);
        assert!(result.is_ok(), "Resolution should succeed: {:?}", result);

        // Verify the type was resolved
        let elem = schema_set.arenas.elements.get(elem_key).unwrap();
        assert!(elem.resolved_type.is_some(), "Type should be resolved");

        if let Some(TypeKey::Simple(key)) = elem.resolved_type {
            assert_eq!(key, schema_set.builtin_types().string);
        } else {
            panic!("Expected Simple type key for xs:string");
        }
    }

    #[test]
    fn test_resolve_attribute_with_builtin_type() {
        use crate::arenas::AttributeDeclData;
        use crate::parser::frames::QNameRef;

        let mut schema_set = SchemaSet::new();

        // Get names
        let attr_name = schema_set.name_table.add("myAttribute");
        let integer_name = schema_set.name_table.get("integer").unwrap();

        // Create an attribute with type="xs:integer"
        let type_ref = TypeRefResult::QName(QNameRef {
            prefix: None,
            local_name: integer_name,
            namespace: Some(well_known::XS_NAMESPACE),
        });

        let attr_data = AttributeDeclData {
            name: Some(attr_name),
            target_namespace: None,
            ref_name: None,
            type_ref: Some(type_ref),
            inline_type: None,
            default_value: None,
            fixed_value: None,
            use_kind: None,
            form: None,
            inheritable: false,
            id: None,
            annotation: None,
            source: None,
            resolved_type: None,
            resolved_ref: None,
        };

        let attr_key = schema_set.arenas.alloc_attribute(attr_data);

        // Resolve references
        let result = resolve_all_references(&mut schema_set);
        assert!(result.is_ok());

        // Verify the type was resolved
        let attr = schema_set.arenas.attributes.get(attr_key).unwrap();
        assert!(attr.resolved_type.is_some(), "Type should be resolved");
    }

    #[test]
    fn test_resolve_element_already_resolved_inline_type() {
        use crate::arenas::ElementDeclData;
        use crate::schema::model::DerivationSet;

        let mut schema_set = SchemaSet::new();

        let elem_name = schema_set.name_table.add("myElement");

        // Pre-resolved type (as if from inline type assembly)
        let string_key = schema_set.builtin_types().string;

        let elem_data = ElementDeclData {
            name: Some(elem_name),
            target_namespace: None,
            ref_name: None,
            type_ref: None,
            inline_type: None,
            substitution_group: Vec::new(),
            default_value: None,
            fixed_value: None,
            nillable: false,
            is_abstract: false,
            min_occurs: 1,
            max_occurs: Some(1),
            block: DerivationSet::empty(),
            final_derivation: DerivationSet::empty(),
            form: None,
            id: None,
            alternatives: Vec::new(),
            identity_constraints: Vec::new(),
            pending_ic_refs: vec![],
            annotation: None,
            source: None,
            // Already resolved (from inline type assembly)
            resolved_type: Some(TypeKey::Simple(string_key)),
            resolved_ref: None,
            resolved_substitution_groups: Vec::new(),
            deferred_type_error: None,
        };

        let elem_key = schema_set.arenas.alloc_element(elem_data);

        // Resolve references - should preserve the pre-resolved type
        let result = resolve_all_references(&mut schema_set);
        assert!(result.is_ok());

        // Verify the pre-resolved type was preserved
        let elem = schema_set.arenas.elements.get(elem_key).unwrap();
        assert!(elem.resolved_type.is_some());
        assert_eq!(elem.resolved_type, Some(TypeKey::Simple(string_key)));
    }

    #[test]
    fn test_resolver_preserves_inline_resolved_type_in_model_group() {
        use crate::arenas::{ModelGroupData, ResolvedParticleTerm};
        use crate::parser::frames::{Compositor, ElementFrameResult, ParticleResult, ParticleTerm};

        let mut schema_set = SchemaSet::new();

        let elem_name = schema_set.name_table.add("detail");
        let group_name = schema_set.name_table.add("myGroup");

        // Pre-resolved type (as if from inline type assembly)
        let string_key = schema_set.builtin_types().string;

        // Create a model group with one element particle
        let group_data = ModelGroupData {
            name: Some(group_name),
            target_namespace: None,
            ref_name: None,
            compositor: Some(Compositor::Sequence),
            particles: vec![ParticleResult {
                term: ParticleTerm::Element(ElementFrameResult {
                    name: Some(elem_name),
                    ref_name: None,
                    target_namespace: None,
                    type_ref: None, // No QName type ref
                    inline_type: None,
                    substitution_group: vec![],
                    default_value: None,
                    fixed_value: None,
                    nillable: false,
                    is_abstract: false,
                    min_occurs: 1,
                    max_occurs: Some(1),
                    block: None,
                    final_derivation: None,
                    form: None,
                    id: None,
                    alternatives: vec![],
                    identity_constraints: vec![],
                    identity_constraint_refs: vec![],
                    annotation: None,
                    source: None,
                }),
                min_occurs: 1,
                max_occurs: Some(1),
                source: None,
            }],
            min_occurs: 1,
            max_occurs: Some(1),
            id: None,
            annotation: None,
            source: None,
            resolved_ref: None,
            // Pre-populate with inline-resolved type
            resolved_particles: vec![ResolvedParticleTerm::Element {
                resolved_type: Some(TypeKey::Simple(string_key)),
                resolved_ref: None,
            }],
            resolved_particle_types: vec![Some(TypeKey::Simple(string_key))],
            resolved_particle_elements: Vec::new(),
            redefine_original: None,
            redefine_requires_restriction_check: false,
        };

        let group_key = schema_set.arenas.alloc_model_group(group_data);

        // Resolve references - should preserve the pre-resolved type
        let result = resolve_all_references(&mut schema_set);
        assert!(result.is_ok());

        // Verify the pre-resolved type was preserved
        let group = schema_set.arenas.model_groups.get(group_key).unwrap();
        assert_eq!(group.resolved_particles.len(), 1);
        match &group.resolved_particles[0] {
            ResolvedParticleTerm::Element {
                resolved_type: Some(TypeKey::Simple(key)),
                ..
            } => {
                assert_eq!(*key, string_key, "Inline-resolved type should be preserved");
            }
            other => panic!("Expected Element with pre-resolved type, got {:?}", other),
        }
    }

    /// Helper: set up a SchemaSet with a default attribute group and a complex type.
    /// Returns (schema_set, complex_type_key, attribute_group_key).
    fn setup_default_attrs_test(
        default_attributes_apply: bool,
    ) -> (
        SchemaSet,
        crate::ids::ComplexTypeKey,
        crate::ids::AttributeGroupKey,
    ) {
        use crate::arenas::{AttributeGroupData, ComplexTypeDefData};
        use crate::namespace::QualifiedName;
        use crate::parser::frames::ComplexContentResult;
        use crate::parser::location::{SourceRef, SourceSpan};
        use crate::schema::model::{DerivationSet, SchemaDocument};

        let mut schema_set = SchemaSet::new();

        let group_name = schema_set.name_table.add("commonAttrs");
        let group_data = AttributeGroupData {
            name: Some(group_name),
            target_namespace: None,
            ref_name: None,
            attributes: Vec::new(),
            attribute_groups: Vec::new(),
            attribute_wildcard: None,
            id: None,
            annotation: None,
            source: None,
            resolved_ref: None,
            resolved_attribute_groups: Vec::new(),
            resolved_attributes: Vec::new(),
            redefine_original: None,
            redefine_requires_restriction_check: false,
        };
        let group_key = schema_set.arenas.alloc_attribute_group(group_data);
        schema_set
            .get_or_create_namespace(None)
            .register_attribute_group(group_name, group_key);

        let doc_id = schema_set.documents.len() as u32;
        let mut doc = SchemaDocument::new(doc_id, "test.xsd".to_string());
        doc.default_attributes = Some(QualifiedName::local(group_name));
        schema_set.documents.push(doc);

        let type_name = schema_set.name_table.add("myType");
        let ct_data = ComplexTypeDefData {
            name: Some(type_name),
            target_namespace: None,
            base_type: None,
            derivation_method: None,
            content: ComplexContentResult::Empty,
            open_content: None,
            attributes: Vec::new(),
            attribute_groups: Vec::new(),
            attribute_wildcard: None,
            mixed: false,
            is_abstract: false,
            final_derivation: DerivationSet::empty(),
            block: DerivationSet::empty(),
            default_attributes_apply,
            id: None,
            #[cfg(feature = "xsd11")]
            assertions: Vec::new(),
            #[cfg(feature = "xsd11")]
            xpath_default_namespace: None,
            annotation: None,
            source: Some(SourceRef::new(doc_id, SourceSpan::new(0, 0))),
            resolved_base_type: None,
            resolved_attribute_groups: Vec::new(),
            resolved_attributes: Vec::new(),
            resolved_content_particle_types: Vec::new(),
            resolved_content_particle_elements: Vec::new(),
            resolved_simple_content_type: None,
            redefine_original: None,
        };
        let ct_key = schema_set.arenas.alloc_complex_type(ct_data);

        (schema_set, ct_key, group_key)
    }

    #[test]
    fn test_resolve_default_attributes_injects_group() {
        let (mut schema_set, ct_key, group_key) = setup_default_attrs_test(true);

        let result = resolve_all_references(&mut schema_set);
        assert!(result.is_ok(), "Resolution should succeed: {:?}", result);

        let ct = schema_set.arenas.complex_types.get(ct_key).unwrap();
        assert!(
            ct.resolved_attribute_groups.contains(&group_key),
            "Default attribute group should be injected into resolved_attribute_groups"
        );
    }

    #[test]
    fn test_resolve_default_attributes_opt_out() {
        let (mut schema_set, ct_key, _group_key) = setup_default_attrs_test(false);

        let result = resolve_all_references(&mut schema_set);
        assert!(result.is_ok(), "Resolution should succeed: {:?}", result);

        let ct = schema_set.arenas.complex_types.get(ct_key).unwrap();
        assert!(
            ct.resolved_attribute_groups.is_empty(),
            "Default attribute group should NOT be injected when defaultAttributesApply=false"
        );
    }
}