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
//! Inline type assembly pass
//!
//! This module implements Phase 3 inline type resolution as specified in
//! XSD_INLINE_TYPE_RESOLUTION_DESIGN.md. It assembles inline type definitions
//! (TypeRefResult::Inline and inline_type fields) into arena TypeKey values.
//!
//! # Overview
//!
//! Inline types are anonymous type definitions that appear directly within
//! element declarations, attribute declarations, or as base/item/member types
//! in type derivation. These need to be allocated in the type arenas before
//! the reference resolution phase can complete.
//!
//! # Work Queue Approach
//!
//! To avoid borrow conflicts and handle nested inline types, we use a two-pass
//! work queue approach:
//!
//! 1. **Scan Pass**: Collect all inline types into `InlineTypeJob` records.
//!    Each job records the owner component and the inline type AST (cloned).
//!
//! 2. **Assembly Pass**: For each job, assemble the inline type into the
//!    arena and update the owner's resolved_* field with the TypeKey.

use crate::arenas::{
    ComplexTypeDefData, ElementDeclData, IdentityConstraintData, ResolvedAttributeUse,
    SimpleTypeDefData,
};
use std::collections::{HashMap, HashSet};

use crate::error::{SchemaError, SchemaResult};
use crate::ids::*;
use crate::namespace::NameTable;
use crate::parser::frames::{
    ComplexContentResult, ElementFrameResult, IdentityKind, IdentityResult, ParticleResult,
    ParticleTerm, QNameRef, TypeFrameResult, TypeRefResult,
};
use crate::parser::location::{SourceMapStorage, SourceRef};
use crate::schema::model::DerivationSet;
use crate::schema::SchemaSet;

/// Resolve a parsed `block`/`final` attribute to an effective `DerivationSet`.
/// `Some(set)` → explicit (including `""` = empty, which overrides the default).
/// `None` → absent; inherit the source document's default via `pick_default`,
/// following `schema_defaults_doc` for override-copied components so they see
/// the override document's defaults rather than the origin schema's.
fn resolve_derivation_default(
    parsed: Option<DerivationSet>,
    source: Option<&SourceRef>,
    schema_set: &SchemaSet,
    pick_default: impl Fn(&crate::schema::model::SchemaDocument) -> DerivationSet,
) -> DerivationSet {
    parsed.unwrap_or_else(|| {
        source
            .and_then(|s| {
                let doc_id = s.schema_defaults_doc.unwrap_or(s.doc_id);
                schema_set.documents.get(doc_id as usize)
            })
            .map(pick_default)
            .unwrap_or_default()
    })
}

fn resolve_block(
    block: Option<DerivationSet>,
    source: Option<&SourceRef>,
    schema_set: &SchemaSet,
) -> DerivationSet {
    resolve_derivation_default(block, source, schema_set, |d| d.block_default)
}

fn resolve_final(
    final_derivation: Option<DerivationSet>,
    source: Option<&SourceRef>,
    schema_set: &SchemaSet,
) -> DerivationSet {
    resolve_derivation_default(final_derivation, source, schema_set, |d| d.final_default)
}

/// Statistics from the inline type assembly pass
#[derive(Debug, Default)]
pub struct InlineAssemblyStats {
    /// Number of element inline types assembled
    pub element_inline_types: usize,
    /// Number of attribute inline types assembled
    pub attribute_inline_types: usize,
    /// Number of simple type base/item/member inline types assembled
    pub simple_type_inline_derivations: usize,
    /// Number of complex type base type inline types assembled
    pub complex_type_inline_derivations: usize,
    /// Number of inline types in model group particles assembled
    pub model_group_inline_types: usize,
    /// Number of inline types in attribute groups assembled
    pub attribute_group_inline_types: usize,
    /// Number of inline types in complex type attributes assembled
    pub complex_type_attribute_inline_types: usize,
    /// Total inline types assembled
    pub total_inline_types: usize,
}

/// Role of an inline type within its owner
#[derive(Debug, Clone, Copy)]
enum InlineRole {
    /// Element's type (inline_type field)
    ElementType,
    /// Attribute's type (inline_type field)
    AttributeType,
    /// Simple type restriction base (base_type: Inline)
    SimpleTypeBase,
    /// List type item type (item_type: Inline)
    ListItemType,
    /// Union member type (member_types[index]: Inline)
    UnionMemberType(usize),
    /// Complex type derivation base (base_type: Inline)
    ComplexTypeBase,
    /// Attribute use inline type within complex type (attributes[index])
    ComplexTypeAttribute(usize),
    /// Particle inline type in model group (particles[index])
    ModelGroupParticle(usize),
    /// Attribute use inline type in attribute group (attributes[index])
    AttributeGroupAttribute(usize),
    /// Inline type on element at index in content particle's model group
    ContentParticleType(usize),
    /// Inline type on alternative at index in element's alternatives vec (XSD 1.1)
    #[cfg(feature = "xsd11")]
    AlternativeType(usize),
    /// Inline `<xs:simpleType>` inside simpleContent/restriction
    /// (§3.4.2.2 clause 1.1 — the B simple type definition)
    SimpleContentInlineType,
}

/// Owner of an inline type
#[derive(Debug, Clone, Copy)]
enum InlineOwner {
    Element(ElementKey),
    Attribute(AttributeKey),
    SimpleType(SimpleTypeKey),
    ComplexType(ComplexTypeKey),
    ModelGroup(ModelGroupKey),
    AttributeGroup(AttributeGroupKey),
}

/// A job representing an inline type to be assembled
struct InlineTypeJob {
    owner: InlineOwner,
    role: InlineRole,
    type_frame: TypeFrameResult,
    target_namespace: Option<NameId>,
}

/// Assemble all inline types in the schema set
///
/// This function walks all components, collects inline type definitions,
/// assembles them into the arenas, and updates the resolved_* fields.
///
/// This should be called after top-level component assembly but before
/// reference resolution.
pub fn assemble_inline_types(schema_set: &mut SchemaSet) -> SchemaResult<InlineAssemblyStats> {
    let mut stats = InlineAssemblyStats::default();

    // Collect all inline type jobs
    let mut jobs = collect_inline_type_jobs(schema_set);

    // Process jobs iteratively (nested inline types may add more jobs)
    while !jobs.is_empty() {
        let current_jobs: Vec<_> = std::mem::take(&mut jobs);

        for job in current_jobs {
            let type_key = assemble_inline_type(schema_set, &job.type_frame, job.target_namespace)?;
            update_owner(schema_set, &job, type_key, &mut stats)?;

            // Check if the newly assembled type has nested inline types
            collect_nested_inline_types(schema_set, type_key, job.target_namespace, &mut jobs);
        }
    }

    Ok(stats)
}

/// Collect all inline type jobs from schema components
fn collect_inline_type_jobs(schema_set: &SchemaSet) -> Vec<InlineTypeJob> {
    let mut jobs = Vec::new();

    // Scan elements
    for (key, elem) in schema_set.arenas.elements.iter() {
        let target_ns = elem.target_namespace;
        if let Some(inline_type) = &elem.inline_type {
            jobs.push(InlineTypeJob {
                owner: InlineOwner::Element(key),
                role: InlineRole::ElementType,
                type_frame: (**inline_type).clone(),
                target_namespace: target_ns,
            });
        }
    }

    // Scan element alternatives (XSD 1.1)
    #[cfg(feature = "xsd11")]
    for (key, elem) in schema_set.arenas.elements.iter() {
        let target_ns = elem.target_namespace;
        for (idx, alt) in elem.alternatives.iter().enumerate() {
            if let Some(inline_type) = &alt.inline_type {
                jobs.push(InlineTypeJob {
                    owner: InlineOwner::Element(key),
                    role: InlineRole::AlternativeType(idx),
                    type_frame: (**inline_type).clone(),
                    target_namespace: target_ns,
                });
            }
        }
    }

    // Scan attributes
    for (key, attr) in schema_set.arenas.attributes.iter() {
        let target_ns = attr.target_namespace;
        if let Some(inline_type) = &attr.inline_type {
            jobs.push(InlineTypeJob {
                owner: InlineOwner::Attribute(key),
                role: InlineRole::AttributeType,
                type_frame: TypeFrameResult::Simple(Box::new((**inline_type).clone())),
                target_namespace: target_ns,
            });
        }
    }

    // Scan simple types
    for (key, simple) in schema_set.arenas.simple_types.iter() {
        let target_ns = simple.target_namespace;

        // Base type inline
        if let Some(TypeRefResult::Inline(inline_type)) = &simple.base_type {
            jobs.push(InlineTypeJob {
                owner: InlineOwner::SimpleType(key),
                role: InlineRole::SimpleTypeBase,
                type_frame: (**inline_type).clone(),
                target_namespace: target_ns,
            });
        }

        // Item type inline (for list types)
        if let Some(TypeRefResult::Inline(inline_type)) = &simple.item_type {
            jobs.push(InlineTypeJob {
                owner: InlineOwner::SimpleType(key),
                role: InlineRole::ListItemType,
                type_frame: (**inline_type).clone(),
                target_namespace: target_ns,
            });
        }

        // Member types inline (for union types)
        for (idx, member) in simple.member_types.iter().enumerate() {
            if let TypeRefResult::Inline(inline_type) = member {
                jobs.push(InlineTypeJob {
                    owner: InlineOwner::SimpleType(key),
                    role: InlineRole::UnionMemberType(idx),
                    type_frame: (**inline_type).clone(),
                    target_namespace: target_ns,
                });
            }
        }
    }

    // Scan complex types
    for (key, complex) in schema_set.arenas.complex_types.iter() {
        let target_ns = complex.target_namespace;

        // Base type inline
        if let Some(TypeRefResult::Inline(inline_type)) = &complex.base_type {
            jobs.push(InlineTypeJob {
                owner: InlineOwner::ComplexType(key),
                role: InlineRole::ComplexTypeBase,
                type_frame: (**inline_type).clone(),
                target_namespace: target_ns,
            });
        }

        // Attribute uses with inline types
        for (idx, attr_use) in complex.attributes.iter().enumerate() {
            if let Some(inline_type) = &attr_use.attribute.inline_type {
                jobs.push(InlineTypeJob {
                    owner: InlineOwner::ComplexType(key),
                    role: InlineRole::ComplexTypeAttribute(idx),
                    type_frame: TypeFrameResult::Simple(Box::new((**inline_type).clone())),
                    target_namespace: target_ns,
                });
            }
        }

        // Content particles (in complex content)
        collect_content_inline_types(&complex.content, key, target_ns, &mut jobs);
    }

    // Scan model groups (recursively, including nested inline groups)
    for (key, group) in schema_set.arenas.model_groups.iter() {
        let target_ns = group.target_namespace;
        let mut flat_idx = 0;
        collect_model_group_inline_types_recursive(
            &group.particles,
            key,
            target_ns,
            &mut flat_idx,
            &mut jobs,
        );
    }

    // Scan attribute groups
    for (key, group) in schema_set.arenas.attribute_groups.iter() {
        let target_ns = group.target_namespace;

        for (idx, attr_use) in group.attributes.iter().enumerate() {
            if let Some(inline_type) = &attr_use.attribute.inline_type {
                jobs.push(InlineTypeJob {
                    owner: InlineOwner::AttributeGroup(key),
                    role: InlineRole::AttributeGroupAttribute(idx),
                    type_frame: TypeFrameResult::Simple(Box::new((**inline_type).clone())),
                    target_namespace: target_ns,
                });
            }
        }
    }

    jobs
}

/// Collect inline types from complex content (recursive helper)
fn collect_content_inline_types(
    content: &ComplexContentResult,
    owner_key: ComplexTypeKey,
    target_ns: Option<NameId>,
    jobs: &mut Vec<InlineTypeJob>,
) {
    match content {
        ComplexContentResult::Complex(complex_content) => {
            // Check base type inline
            if let Some(TypeRefResult::Inline(inline_type)) = &complex_content.base_type {
                jobs.push(InlineTypeJob {
                    owner: InlineOwner::ComplexType(owner_key),
                    role: InlineRole::ComplexTypeBase,
                    type_frame: (**inline_type).clone(),
                    target_namespace: target_ns,
                });
            }

            // Check attributes in complex content
            for (idx, attr_use) in complex_content.attributes.iter().enumerate() {
                if let Some(inline_type) = &attr_use.attribute.inline_type {
                    jobs.push(InlineTypeJob {
                        owner: InlineOwner::ComplexType(owner_key),
                        role: InlineRole::ComplexTypeAttribute(idx),
                        type_frame: TypeFrameResult::Simple(Box::new((**inline_type).clone())),
                        target_namespace: target_ns,
                    });
                }
            }

            // Scan content particle for inline types on element children
            if let Some(particle) = &complex_content.particle {
                collect_particle_inline_types(particle, owner_key, target_ns, jobs);
            }
        }
        ComplexContentResult::Simple(simple_content) => {
            // Check base type inline
            if let Some(TypeRefResult::Inline(inline_type)) = &simple_content.base_type {
                jobs.push(InlineTypeJob {
                    owner: InlineOwner::ComplexType(owner_key),
                    role: InlineRole::ComplexTypeBase,
                    type_frame: (**inline_type).clone(),
                    target_namespace: target_ns,
                });
            }

            // Check attributes in simple content
            for (idx, attr_use) in simple_content.attributes.iter().enumerate() {
                if let Some(inline_type) = &attr_use.attribute.inline_type {
                    jobs.push(InlineTypeJob {
                        owner: InlineOwner::ComplexType(owner_key),
                        role: InlineRole::ComplexTypeAttribute(idx),
                        type_frame: TypeFrameResult::Simple(Box::new((**inline_type).clone())),
                        target_namespace: target_ns,
                    });
                }
            }

            // §3.4.2.2 clause 1.1: inline <xs:simpleType> inside
            // simpleContent/restriction is the content type definition B.
            if let Some(inline_st) = &simple_content.content_type {
                jobs.push(InlineTypeJob {
                    owner: InlineOwner::ComplexType(owner_key),
                    role: InlineRole::SimpleContentInlineType,
                    type_frame: TypeFrameResult::Simple(Box::new((**inline_st).clone())),
                    target_namespace: target_ns,
                });
            }
        }
        ComplexContentResult::Empty => {}
    }
}

/// Collect inline types from a content particle's model group elements (recursive)
fn collect_particle_inline_types(
    particle: &ParticleResult,
    owner_key: ComplexTypeKey,
    target_ns: Option<NameId>,
    jobs: &mut Vec<InlineTypeJob>,
) {
    if let ParticleTerm::Group(group_def) = &particle.term {
        let mut flat_idx = 0;
        collect_group_elements_recursive(
            &group_def.particles,
            owner_key,
            target_ns,
            &mut flat_idx,
            jobs,
        );
    }
}

/// Recursive helper: walk particles in depth-first order, assigning flat element indices
fn collect_group_elements_recursive(
    particles: &[ParticleResult],
    owner_key: ComplexTypeKey,
    target_ns: Option<NameId>,
    flat_idx: &mut usize,
    jobs: &mut Vec<InlineTypeJob>,
) {
    for particle in particles {
        match &particle.term {
            ParticleTerm::Element(elem) => {
                if let Some(inline_type) = &elem.inline_type {
                    jobs.push(InlineTypeJob {
                        owner: InlineOwner::ComplexType(owner_key),
                        role: InlineRole::ContentParticleType(*flat_idx),
                        type_frame: (**inline_type).clone(),
                        target_namespace: target_ns,
                    });
                }
                *flat_idx += 1;
            }
            ParticleTerm::Group(group_def) if group_def.ref_name.is_none() => {
                // Inline group (no ref) - recurse into its particles
                collect_group_elements_recursive(
                    &group_def.particles,
                    owner_key,
                    target_ns,
                    flat_idx,
                    jobs,
                );
            }
            _ => {} // Skip group refs and wildcards
        }
    }
}

/// Recursive helper: walk model group particles in depth-first order, collecting inline types
/// with flat element indices (mirroring collect_group_elements_recursive for complex types)
fn collect_model_group_inline_types_recursive(
    particles: &[ParticleResult],
    owner_key: ModelGroupKey,
    target_ns: Option<NameId>,
    flat_idx: &mut usize,
    jobs: &mut Vec<InlineTypeJob>,
) {
    for particle in particles {
        match &particle.term {
            ParticleTerm::Element(elem) => {
                if let Some(inline_type) = &elem.inline_type {
                    jobs.push(InlineTypeJob {
                        owner: InlineOwner::ModelGroup(owner_key),
                        role: InlineRole::ModelGroupParticle(*flat_idx),
                        type_frame: (**inline_type).clone(),
                        target_namespace: target_ns,
                    });
                }
                *flat_idx += 1;
            }
            ParticleTerm::Group(group_def) if group_def.ref_name.is_none() => {
                // Inline group (no ref) - recurse into its particles
                collect_model_group_inline_types_recursive(
                    &group_def.particles,
                    owner_key,
                    target_ns,
                    flat_idx,
                    jobs,
                );
            }
            _ => {} // Skip group refs and wildcards
        }
    }
}

/// Allocation job for a local element in a content particle
struct ContentParticleElementJob {
    complex_type_key: ComplexTypeKey,
    flat_idx: usize,
    elem: ElementFrameResult,
    target_namespace: Option<NameId>,
}

/// Walk content particles recursively and collect local element allocation jobs
fn collect_content_particle_elements_recursive(
    particles: &[ParticleResult],
    complex_type_key: ComplexTypeKey,
    target_ns: Option<NameId>,
    flat_idx: &mut usize,
    jobs: &mut Vec<ContentParticleElementJob>,
) {
    for particle in particles {
        match &particle.term {
            ParticleTerm::Element(elem) if elem.ref_name.is_none() => {
                jobs.push(ContentParticleElementJob {
                    complex_type_key,
                    flat_idx: *flat_idx,
                    elem: elem.clone(),
                    target_namespace: target_ns,
                });
                *flat_idx += 1;
            }
            ParticleTerm::Element(_) => {
                // Ref element - skip allocation but still increment counter
                *flat_idx += 1;
            }
            ParticleTerm::Group(group_def) if group_def.ref_name.is_none() => {
                collect_content_particle_elements_recursive(
                    &group_def.particles,
                    complex_type_key,
                    target_ns,
                    flat_idx,
                    jobs,
                );
            }
            _ => {} // Skip group refs and wildcards
        }
    }
}

/// Check that a keyref's refer target is not a keyref and has matching field count.
fn check_keyref_target(
    ic: &IdentityResult,
    target_kind: IdentityKind,
    target_field_count: usize,
    refer_name: NameId,
    name_table: &NameTable,
    source_maps: &SourceMapStorage,
) -> SchemaResult<()> {
    if target_kind == IdentityKind::Keyref {
        let ic_name = name_table.resolve_ref(ic.name);
        let refer_name_str = name_table.resolve_ref(refer_name);
        let location = ic.source.as_ref().and_then(|s| source_maps.locate(s));
        return Err(SchemaError::structural(
            "src-identity-constraint",
            format!(
                "Keyref '{}': refer target '{}' is a keyref, not a key or unique",
                ic_name, refer_name_str
            ),
            location,
        ));
    }
    if ic.fields.len() != target_field_count {
        let ic_name = name_table.resolve_ref(ic.name);
        let refer_name_str = name_table.resolve_ref(refer_name);
        let location = ic.source.as_ref().and_then(|s| source_maps.locate(s));
        return Err(SchemaError::structural(
            "src-identity-constraint",
            format!(
                "Keyref '{}': has {} field(s) but refer target '{}' has {} field(s)",
                ic_name,
                ic.fields.len(),
                refer_name_str,
                target_field_count
            ),
            location,
        ));
    }
    Ok(())
}

/// Validate keyref constraints: refer must resolve to a key/unique with matching
/// field count (§3.11.4, §3.11.6).
///
/// First checks the current element's ICs. If not found locally, performs a
/// global fallback search across the arena (the spec's `{referenced key}` is
/// resolved globally in the IC definition symbol space, not restricted to the
/// same element — the target may be on an ancestor element).
/// Resolve an XSD 1.1 identity constraint @ref to the referenced IC key.
///
/// §3.11.2: the corresponding schema component is the identity-constraint
/// definition resolved to by the actual value of the ref [attribute].
/// §3.11.6 clause 5: the referenced IC's category must match the element tag.
/// Resolve an XSD 1.1 identity constraint @ref to the referenced IC key.
///
/// §3.11.2: the corresponding schema component is the identity-constraint
/// definition resolved to by the actual value of the ref [attribute].
/// §3.11.6 clause 5: the referenced IC's category must match the element tag.
pub(crate) fn resolve_ic_ref(
    kind: IdentityKind,
    ref_name: &QNameRef,
    source: Option<&SourceRef>,
    target_namespace: Option<NameId>,
    schema_set: &crate::schema::SchemaSet,
) -> crate::error::SchemaResult<IdentityConstraintKey> {
    let ref_ns = ref_name.namespace.or(target_namespace);
    let ref_local = ref_name.local_name;

    // §3.17.6.2 clause 4 — per-document QName visibility gate.
    // Feed the *resolved* `ref_ns` (after target-namespace fallback) so an
    // unprefixed IC ref doesn't accidentally bypass the gate as "absent".
    crate::schema::resolver::check_namespace_visible_ns(
        schema_set,
        ref_ns,
        ref_local,
        source,
        "Identity constraint",
    )?;

    // Look up in namespace tables
    let target_key = schema_set
        .namespaces
        .get(&ref_ns)
        .and_then(|nt| nt.identity_constraints.get(&ref_local))
        .copied();

    let target_key = match target_key {
        Some(k) => k,
        None => {
            // Search arena as fallback (IC may not be in namespace table yet)
            let mut found = None;
            for (key, ic_data) in &schema_set.arenas.identity_constraints {
                if ic_data.name != ref_local {
                    continue;
                }
                let ic_ns = ic_data
                    .source
                    .as_ref()
                    .and_then(|s| schema_set.documents.get(s.doc_id as usize))
                    .and_then(|d| d.target_namespace);
                if ic_ns == ref_ns {
                    found = Some(key);
                    break;
                }
            }
            found.ok_or_else(|| {
                let ref_display = crate::schema::resolver::format_resolved_qname(
                    &schema_set.name_table,
                    ref_ns,
                    ref_local,
                );
                let location = source.and_then(|s| schema_set.source_maps.locate(s));
                crate::error::SchemaError::structural(
                    "src-resolve",
                    format!("Identity constraint ref target '{}' not found", ref_display),
                    location,
                )
            })?
        }
    };

    // §3.11.6 clause 5: kind must match
    let target = &schema_set.arenas.identity_constraints[target_key];
    if target.kind != kind {
        let ref_display = crate::schema::resolver::format_resolved_qname(
            &schema_set.name_table,
            ref_ns,
            ref_local,
        );
        let location = source.and_then(|s| schema_set.source_maps.locate(s));
        return Err(crate::error::SchemaError::structural(
            "src-identity-constraint.5",
            format!(
                "Identity constraint ref '{}': referenced constraint is {:?} but expected {:?}",
                ref_display, target.kind, kind
            ),
            location,
        ));
    }

    Ok(target_key)
}

pub(crate) fn validate_keyref_refers(
    identity_constraints: &[IdentityResult],
    target_namespace: Option<NameId>,
    name_table: &NameTable,
    source_maps: &SourceMapStorage,
    ic_arena: &slotmap::SlotMap<IdentityConstraintKey, IdentityConstraintData>,
    documents: &[crate::schema::model::SchemaDocument],
) -> SchemaResult<()> {
    for ic in identity_constraints {
        if ic.kind != IdentityKind::Keyref {
            continue;
        }
        if let Some(refer) = &ic.refer {
            let refer_name = refer.local_name;
            let refer_ns = refer.namespace;
            // Find the referenced constraint on the same element
            let target = identity_constraints.iter().find(|other| {
                other.name == refer_name && (refer_ns.is_none() || refer_ns == target_namespace)
            });
            match target {
                None => {
                    // Not found locally — search globally in the IC arena
                    // (target may be on an ancestor element)
                    // Fall back to target_namespace for unqualified refer (matches runtime
                    // resolve_refer_key which does refer.namespace.or(compiled.target_namespace))
                    let effective_refer_ns = refer_ns.or(target_namespace);
                    let global_target = ic_arena.values().find(|ic_data| {
                        if ic_data.name != refer_name {
                            return false;
                        }
                        // Resolve the IC's namespace via its source document.
                        // If the document is not yet in `documents` (current
                        // schema being assembled — `documents.push` happens
                        // after `assemble_schema` returns), fall back to the
                        // assembler's `target_namespace`. Distinguish "doc
                        // missing" from "doc.target_namespace is None" so
                        // genuinely no-namespace ICs are not coerced.
                        let ic_ns = match ic_data
                            .source
                            .as_ref()
                            .map(|s| documents.get(s.doc_id as usize))
                        {
                            Some(Some(d)) => d.target_namespace,
                            Some(None) => target_namespace,
                            None => None,
                        };
                        effective_refer_ns == ic_ns
                    });
                    match global_target {
                        Some(target_data) => {
                            check_keyref_target(
                                ic,
                                target_data.kind,
                                target_data.fields.len(),
                                refer_name,
                                name_table,
                                source_maps,
                            )?;
                        }
                        None => {
                            let ic_name = name_table.resolve_ref(ic.name);
                            let refer_name_str = name_table.resolve_ref(refer_name);
                            let location = ic.source.as_ref().and_then(|s| source_maps.locate(s));
                            return Err(SchemaError::structural(
                                "src-identity-constraint",
                                format!(
                                    "Keyref '{}': refer target '{}' not found among identity constraints",
                                    ic_name, refer_name_str
                                ),
                                location,
                            ));
                        }
                    }
                }
                Some(target_ic) => {
                    check_keyref_target(
                        ic,
                        target_ic.kind,
                        target_ic.fields.len(),
                        refer_name,
                        name_table,
                        source_maps,
                    )?;
                }
            }
        }
    }
    Ok(())
}

/// Allocate arena element declarations for local elements in content particles.
///
/// This enables the validator to look up nillable, fixed_value, default_value
/// and other properties for local elements via their ElementKey.
///
/// Must be called after inline type assembly and reference resolution.
pub fn allocate_content_particle_elements(schema_set: &mut SchemaSet) -> SchemaResult<()> {
    // Collection pass: walk all complex types and collect jobs.
    //
    // Skip elements whose slot in `resolved_content_particle_elements` is
    // already populated, so the function is safe to re-run (e.g., after
    // a second inline-type assembly pass for alternatives discovered on
    // local elements). The flat_idx still advances on every particle so
    // newly added complex types collected in the same pass keep correct
    // indexing.
    let mut jobs = Vec::new();
    for (key, complex) in schema_set.arenas.complex_types.iter() {
        let target_ns = complex.target_namespace;
        if let ComplexContentResult::Complex(def) = &complex.content {
            if let Some(particle) = &def.particle {
                if let ParticleTerm::Group(group_def) = &particle.term {
                    let mut flat_idx = 0;
                    collect_content_particle_elements_recursive(
                        &group_def.particles,
                        key,
                        target_ns,
                        &mut flat_idx,
                        &mut jobs,
                    );
                }
            }
        }
    }
    // Drop jobs whose slot is already filled in the owning complex type.
    jobs.retain(|job| {
        match schema_set
            .arenas
            .complex_types
            .get(job.complex_type_key)
            .and_then(|ct| ct.resolved_content_particle_elements.get(job.flat_idx))
        {
            Some(Some(_)) => false, // already allocated
            _ => true,
        }
    });

    // Build per-document sets of already-known identity constraint names for uniqueness checking
    // XSD §4.2.1: IC names must be unique per schema document, not globally
    let mut ic_names_by_doc: HashMap<DocumentId, HashSet<NameId>> = HashMap::new();
    for ic in schema_set.arenas.identity_constraints.values() {
        if let Some(source) = &ic.source {
            ic_names_by_doc
                .entry(source.doc_id)
                .or_default()
                .insert(ic.name);
        }
    }

    // Allocation pass: create element declarations and store keys
    for job in jobs {
        // §3.17.6.2 clause 4 — per-document QName visibility gate.
        // This fast path bypasses `resolve_type_ref` so it must gate the QName
        // itself; otherwise un-imported local-element type refs slip through.
        if let Some(TypeRefResult::QName(qname)) = &job.elem.type_ref {
            crate::schema::resolver::check_namespace_visible(
                schema_set,
                qname,
                job.elem.source.as_ref(),
                "Type",
            )?;
        }

        let resolved_type = schema_set
            .arenas
            .complex_types
            .get(job.complex_type_key)
            .and_then(|ct| {
                ct.resolved_content_particle_types
                    .get(job.flat_idx)
                    .copied()
                    .flatten()
            })
            .or_else(|| {
                // Try QName resolution
                match &job.elem.type_ref {
                    Some(TypeRefResult::QName(qname)) => schema_set
                        .lookup_type(qname.namespace, qname.local_name)
                        .or_else(|| {
                            schema_set.get_built_in_type_by_qname(qname.namespace, qname.local_name)
                        }),
                    _ => None,
                }
            });

        // §3.3.2 / §3.3.1: when a local element has neither `type=` nor
        // an inline `<simpleType>` / `<complexType>` (and resolved_type is
        // therefore not yet set), the {type definition} property defaults to
        // xs:anyType. Otherwise content-model initialization in
        // `init_content_model` falls back to (Simple, TextOnly), causing
        // valid mixed/lax-wildcard children to be rejected (xsd002.v01).
        let resolved_type = resolved_type.or_else(|| match &job.elem.type_ref {
            // Only fall back when no type was specified at all. If a QName
            // type-ref was given but didn't resolve, src-resolve below
            // surfaces the error.
            None => Some(TypeKey::Complex(schema_set.any_type_key())),
            _ => None,
        });

        // src-resolve §3.3.6: a local element's QName-typed type-ref must
        // resolve. Falling back silently masks bad schemas (s3_12si02).
        if resolved_type.is_none() {
            if let Some(TypeRefResult::QName(qname)) = &job.elem.type_ref {
                let display = crate::schema::resolver::format_resolved_qname(
                    &schema_set.name_table,
                    qname.namespace,
                    qname.local_name,
                );
                let location = schema_set.locate(job.elem.source.as_ref());
                return Err(SchemaError::structural(
                    "src-resolve",
                    format!("Type reference '{}' on local element not found", display),
                    location,
                ));
            }
        }

        let effective_ns = schema_set.effective_local_element_namespace(
            job.elem.target_namespace,
            job.elem.form.as_deref(),
            job.elem.source.as_ref(),
            job.target_namespace,
        );
        validate_keyref_refers(
            &job.elem.identity_constraints,
            job.target_namespace,
            &schema_set.name_table,
            &schema_set.source_maps,
            &schema_set.arenas.identity_constraints,
            &schema_set.documents,
        )?;
        let mut identity_constraint_keys = Vec::with_capacity(job.elem.identity_constraints.len());
        for ic in job.elem.identity_constraints {
            // Check per-document uniqueness using the IC's source document
            if let Some(source) = &ic.source {
                let doc_names = ic_names_by_doc.entry(source.doc_id).or_default();
                if !doc_names.insert(ic.name) {
                    let location = schema_set.source_maps.locate(source);
                    let name_str = schema_set.name_table.resolve(ic.name);
                    return Err(SchemaError::structural(
                        "ic-unique",
                        format!(
                            "Duplicate identity constraint name '{}' in schema document",
                            name_str
                        ),
                        location,
                    ));
                }
            }
            let ic_name = ic.name;
            let ic_key = schema_set
                .arenas
                .alloc_identity_constraint(IdentityConstraintData {
                    kind: ic.kind,
                    name: ic.name,
                    ref_name: ic.ref_name,
                    refer: ic.refer,
                    selector: ic.selector,
                    fields: ic.fields,
                    id: ic.id,
                    annotation: ic.annotation,
                    source: ic.source,
                });
            // Register in namespace table for @ref resolution
            let ns_table = schema_set.get_or_create_namespace(job.target_namespace);
            ns_table.identity_constraints.insert(ic_name, ic_key);
            identity_constraint_keys.push(ic_key);
        }
        // Resolve XSD 1.1 @ref identity constraint references
        for ic_ref in &job.elem.identity_constraint_refs {
            let target_key = resolve_ic_ref(
                ic_ref.kind,
                &ic_ref.ref_name,
                ic_ref.source.as_ref(),
                job.target_namespace,
                schema_set,
            )?;
            identity_constraint_keys.push(target_key);
        }

        let block = resolve_block(job.elem.block, job.elem.source.as_ref(), schema_set);
        let final_derivation = resolve_final(
            job.elem.final_derivation,
            job.elem.source.as_ref(),
            schema_set,
        );
        let elem_data = ElementDeclData {
            name: job.elem.name,
            target_namespace: effective_ns,
            ref_name: None,
            type_ref: job.elem.type_ref.clone(),
            inline_type: job.elem.inline_type.clone(),
            substitution_group: Vec::new(),
            default_value: job.elem.default_value.clone(),
            fixed_value: job.elem.fixed_value.clone(),
            nillable: job.elem.nillable,
            is_abstract: job.elem.is_abstract,
            min_occurs: job.elem.min_occurs,
            max_occurs: job.elem.max_occurs,
            block,
            final_derivation,
            form: job.elem.form.clone(),
            id: job.elem.id.clone(),
            alternatives: job.elem.alternatives.clone(),
            identity_constraints: identity_constraint_keys,
            pending_ic_refs: vec![],
            annotation: job.elem.annotation.clone(),
            source: job.elem.source.clone(),
            resolved_type,
            resolved_ref: None,
            resolved_substitution_groups: Vec::new(),
            deferred_type_error: None,
        };

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

        if let Some(ct) = schema_set
            .arenas
            .complex_types
            .get_mut(job.complex_type_key)
        {
            while ct.resolved_content_particle_elements.len() <= job.flat_idx {
                ct.resolved_content_particle_elements.push(None);
            }
            ct.resolved_content_particle_elements[job.flat_idx] = Some(elem_key);
        }
    }

    Ok(())
}

/// XSD 1.1: Assemble inline `<xs:alternative>` types attached to *local*
/// element declarations.
///
/// The first inline-type assembly pass only walks `arenas.elements`,
/// which at that point contains global elements only. Local elements
/// declared inside complex-type particles are allocated later by
/// [`allocate_content_particle_elements`], and any inline alternative
/// types they carry would otherwise stay unresolved.
///
/// Run this after [`allocate_content_particle_elements`]. It:
///
/// 1. Walks every element declaration whose alternatives have an
///    `inline_type` but no `resolved_type`.
/// 2. Calls [`assemble_inline_type`] to add the inline complex/simple
///    type to the arena and stores the resulting `TypeKey` on the
///    alternative.
/// 3. Returns the list of complex-type keys that were newly added so
///    the caller can re-run reference resolution and content-particle
///    allocation on them.
///
/// The caller must also call [`resolve_all_references`] and
/// [`allocate_content_particle_elements`] again so the new types get
/// their `resolved_base_type`, `resolved_content_particle_types`, and
/// `resolved_content_particle_elements` populated. Both passes are
/// idempotent for already-resolved entries.
#[cfg(feature = "xsd11")]
pub fn resolve_local_element_alternatives(
    schema_set: &mut SchemaSet,
) -> SchemaResult<Vec<ComplexTypeKey>> {
    use crate::ids::ComplexTypeKey;

    // Pass 1: Collect QName type_refs that need resolution (no inline type).
    // These are alternatives like `<xs:alternative test=… type="Quadrilateral"/>`
    // attached to local element declarations. The first
    // `resolve_all_references` pass walked global elements only; local
    // element alternatives copied during `allocate_content_particle_elements`
    // still carry an unresolved QName here.
    let mut qname_pending: Vec<(ElementKey, usize, QNameRef, Option<SourceRef>)> = Vec::new();
    for (key, elem) in schema_set.arenas.elements.iter() {
        for (idx, alt) in elem.alternatives.iter().enumerate() {
            if alt.resolved_type.is_some() {
                continue;
            }
            if let Some(TypeRefResult::QName(qname)) = &alt.type_ref {
                qname_pending.push((key, idx, qname.clone(), alt.source.clone()));
            }
        }
    }
    for (elem_key, alt_idx, qname, src) in qname_pending {
        let resolver = crate::schema::resolver::ReferenceResolver::new(schema_set);
        let type_key = resolver.resolve_type_ref(&qname, src.as_ref())?;
        if let Some(elem) = schema_set.arenas.elements.get_mut(elem_key) {
            if let Some(alt) = elem.alternatives.get_mut(alt_idx) {
                alt.resolved_type = Some(type_key);
            }
        }
    }

    // Pass 2: Collect (element_key, alt_idx, type_frame) triples first to
    // avoid mutating arenas while iterating them. Handles inline types.
    let mut pending: Vec<(ElementKey, usize, TypeFrameResult, Option<NameId>)> = Vec::new();
    for (key, elem) in schema_set.arenas.elements.iter() {
        for (idx, alt) in elem.alternatives.iter().enumerate() {
            if alt.resolved_type.is_some() {
                continue;
            }
            let Some(inline_type) = &alt.inline_type else {
                continue;
            };
            pending.push((key, idx, (**inline_type).clone(), elem.target_namespace));
        }
    }

    let mut new_complex_keys: Vec<ComplexTypeKey> = Vec::new();
    for (elem_key, alt_idx, type_frame, target_ns) in pending {
        let type_key = assemble_inline_type(schema_set, &type_frame, target_ns)?;
        if let TypeKey::Complex(ct_key) = type_key {
            new_complex_keys.push(ct_key);
        }
        if let Some(elem) = schema_set.arenas.elements.get_mut(elem_key) {
            if let Some(alt) = elem.alternatives.get_mut(alt_idx) {
                alt.resolved_type = Some(type_key);
            }
        }
    }

    Ok(new_complex_keys)
}

/// Allocation job for a local element in a named model group particle
struct ModelGroupElementJob {
    group_key: ModelGroupKey,
    particle_idx: usize,
    elem: ElementFrameResult,
    target_namespace: Option<NameId>,
}

/// Allocate arena element declarations for local elements in named model group particles.
///
/// This enables the validator to look up nillable, fixed_value, default_value
/// and other properties for local elements inside named groups via their ElementKey.
///
/// Must be called after inline type assembly and reference resolution.
pub fn allocate_model_group_particle_elements(schema_set: &mut SchemaSet) -> SchemaResult<()> {
    // Collection pass: walk all model groups recursively and collect jobs
    let mut jobs = Vec::new();
    for (key, group) in schema_set.arenas.model_groups.iter() {
        let target_ns = group.target_namespace;
        let mut flat_idx = 0;
        collect_model_group_elements_recursive(
            &group.particles,
            key,
            target_ns,
            &mut flat_idx,
            &mut jobs,
        );
    }

    // Build per-document sets of already-known identity constraint names for uniqueness checking
    // XSD §4.2.1: IC names must be unique per schema document, not globally
    let mut ic_names_by_doc: HashMap<DocumentId, HashSet<NameId>> = HashMap::new();
    for ic in schema_set.arenas.identity_constraints.values() {
        if let Some(source) = &ic.source {
            ic_names_by_doc
                .entry(source.doc_id)
                .or_default()
                .insert(ic.name);
        }
    }

    // Allocation pass: create element declarations and store keys
    for job in jobs {
        // §3.17.6.2 clause 4 — per-document QName visibility gate.
        if let Some(TypeRefResult::QName(qname)) = &job.elem.type_ref {
            crate::schema::resolver::check_namespace_visible(
                schema_set,
                qname,
                job.elem.source.as_ref(),
                "Type",
            )?;
        }

        let resolved_type = schema_set
            .arenas
            .model_groups
            .get(job.group_key)
            .and_then(|g| {
                g.resolved_particle_types
                    .get(job.particle_idx)
                    .copied()
                    .flatten()
            })
            .or_else(|| {
                // Try QName resolution
                match &job.elem.type_ref {
                    Some(TypeRefResult::QName(qname)) => schema_set
                        .lookup_type(qname.namespace, qname.local_name)
                        .or_else(|| {
                            schema_set.get_built_in_type_by_qname(qname.namespace, qname.local_name)
                        }),
                    _ => None,
                }
            });

        let effective_ns = schema_set.effective_local_element_namespace(
            job.elem.target_namespace,
            job.elem.form.as_deref(),
            job.elem.source.as_ref(),
            job.target_namespace,
        );
        validate_keyref_refers(
            &job.elem.identity_constraints,
            job.target_namespace,
            &schema_set.name_table,
            &schema_set.source_maps,
            &schema_set.arenas.identity_constraints,
            &schema_set.documents,
        )?;
        let mut identity_constraint_keys = Vec::with_capacity(job.elem.identity_constraints.len());
        for ic in job.elem.identity_constraints {
            // Check per-document uniqueness using the IC's source document
            if let Some(source) = &ic.source {
                let doc_names = ic_names_by_doc.entry(source.doc_id).or_default();
                if !doc_names.insert(ic.name) {
                    let location = schema_set.source_maps.locate(source);
                    let name_str = schema_set.name_table.resolve(ic.name);
                    return Err(SchemaError::structural(
                        "ic-unique",
                        format!(
                            "Duplicate identity constraint name '{}' in schema document",
                            name_str
                        ),
                        location,
                    ));
                }
            }
            let ic_name = ic.name;
            let ic_key = schema_set
                .arenas
                .alloc_identity_constraint(IdentityConstraintData {
                    kind: ic.kind,
                    name: ic.name,
                    ref_name: ic.ref_name,
                    refer: ic.refer,
                    selector: ic.selector,
                    fields: ic.fields,
                    id: ic.id,
                    annotation: ic.annotation,
                    source: ic.source,
                });
            // Register in namespace table for @ref resolution
            let ns_table = schema_set.get_or_create_namespace(job.target_namespace);
            ns_table.identity_constraints.insert(ic_name, ic_key);
            identity_constraint_keys.push(ic_key);
        }
        // Resolve XSD 1.1 @ref identity constraint references
        for ic_ref in &job.elem.identity_constraint_refs {
            let target_key = resolve_ic_ref(
                ic_ref.kind,
                &ic_ref.ref_name,
                ic_ref.source.as_ref(),
                job.target_namespace,
                schema_set,
            )?;
            identity_constraint_keys.push(target_key);
        }

        let block = resolve_block(job.elem.block, job.elem.source.as_ref(), schema_set);
        let final_derivation = resolve_final(
            job.elem.final_derivation,
            job.elem.source.as_ref(),
            schema_set,
        );
        let elem_data = ElementDeclData {
            name: job.elem.name,
            target_namespace: effective_ns,
            ref_name: None,
            type_ref: job.elem.type_ref.clone(),
            inline_type: job.elem.inline_type.clone(),
            substitution_group: Vec::new(),
            default_value: job.elem.default_value.clone(),
            fixed_value: job.elem.fixed_value.clone(),
            nillable: job.elem.nillable,
            is_abstract: job.elem.is_abstract,
            min_occurs: job.elem.min_occurs,
            max_occurs: job.elem.max_occurs,
            block,
            final_derivation,
            form: job.elem.form.clone(),
            id: job.elem.id.clone(),
            alternatives: job.elem.alternatives.clone(),
            identity_constraints: identity_constraint_keys,
            pending_ic_refs: vec![],
            annotation: job.elem.annotation.clone(),
            source: job.elem.source.clone(),
            resolved_type,
            resolved_ref: None,
            resolved_substitution_groups: Vec::new(),
            deferred_type_error: None,
        };

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

        if let Some(group) = schema_set.arenas.model_groups.get_mut(job.group_key) {
            while group.resolved_particle_elements.len() <= job.particle_idx {
                group.resolved_particle_elements.push(None);
            }
            group.resolved_particle_elements[job.particle_idx] = Some(elem_key);
        }
    }

    Ok(())
}

/// Walk model group particles recursively and collect local element allocation jobs
fn collect_model_group_elements_recursive(
    particles: &[ParticleResult],
    group_key: ModelGroupKey,
    target_ns: Option<NameId>,
    flat_idx: &mut usize,
    jobs: &mut Vec<ModelGroupElementJob>,
) {
    for particle in particles {
        match &particle.term {
            ParticleTerm::Element(elem) if elem.ref_name.is_none() => {
                jobs.push(ModelGroupElementJob {
                    group_key,
                    particle_idx: *flat_idx,
                    elem: elem.clone(),
                    target_namespace: target_ns,
                });
                *flat_idx += 1;
            }
            ParticleTerm::Element(_) => {
                // Ref element - skip allocation but still increment counter
                *flat_idx += 1;
            }
            ParticleTerm::Group(group_def) if group_def.ref_name.is_none() => {
                collect_model_group_elements_recursive(
                    &group_def.particles,
                    group_key,
                    target_ns,
                    flat_idx,
                    jobs,
                );
            }
            _ => {} // Skip group refs and wildcards
        }
    }
}

/// Assemble an inline type into the arena
///
/// Returns the TypeKey for the newly allocated type.
/// Anonymous types are not registered in namespace tables.
fn assemble_inline_type(
    schema_set: &mut SchemaSet,
    type_frame: &TypeFrameResult,
    target_namespace: Option<NameId>,
) -> SchemaResult<TypeKey> {
    match type_frame {
        TypeFrameResult::Simple(simple) => {
            let final_derivation =
                resolve_final(simple.final_derivation, simple.source.as_ref(), schema_set);
            let data = SimpleTypeDefData {
                name: simple.name, // May be None for anonymous types
                target_namespace,
                variety: simple.variety,
                base_type: simple.base_type.clone(),
                item_type: simple.item_type.clone(),
                member_types: simple.member_types.clone(),
                facets: simple.facets.clone(),
                final_derivation,
                id: simple.id.clone(),
                derivation_id: simple.derivation_id.clone(),
                annotation: simple.annotation.clone(),
                source: simple.source.clone(),
                // Resolved references (to be populated later)
                resolved_base_type: None,
                resolved_item_type: None,
                resolved_member_types: Vec::new(),
                redefine_original: None,
                deferred_item_type_error: None,
            };
            let key = schema_set.arenas.alloc_simple_type(data);
            Ok(TypeKey::Simple(key))
        }
        TypeFrameResult::Complex(complex) => {
            let open_content = match &complex.content {
                ComplexContentResult::Complex(def) => def.open_content.clone(),
                _ => None,
            };
            #[cfg(feature = "xsd11")]
            let assertions = match &complex.content {
                ComplexContentResult::Simple(sc) => sc.assertions.clone(),
                ComplexContentResult::Complex(cc) => cc.assertions.clone(),
                ComplexContentResult::Empty => Vec::new(),
            };
            let block = resolve_block(complex.block, complex.source.as_ref(), schema_set);
            let final_derivation = resolve_final(
                complex.final_derivation,
                complex.source.as_ref(),
                schema_set,
            );
            let data = ComplexTypeDefData {
                name: complex.name, // May be None for anonymous types
                target_namespace,
                base_type: complex.base_type.clone(),
                derivation_method: complex.derivation_method,
                content: complex.content.clone(),
                open_content,
                attributes: complex.attributes.clone(),
                attribute_groups: complex.attribute_groups.clone(),
                attribute_wildcard: complex.attribute_wildcard.clone(),
                mixed: complex.mixed,
                is_abstract: complex.is_abstract,
                final_derivation,
                block,
                default_attributes_apply: complex.default_attributes_apply,
                id: complex.id.clone(),
                #[cfg(feature = "xsd11")]
                assertions,
                #[cfg(feature = "xsd11")]
                xpath_default_namespace: complex.xpath_default_namespace.clone(),
                annotation: complex.annotation.clone(),
                source: complex.source.clone(),
                // Resolved references (to be populated later)
                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 key = schema_set.arenas.alloc_complex_type(data);
            Ok(TypeKey::Complex(key))
        }
    }
}

/// Update the owner component with the resolved type key
fn update_owner(
    schema_set: &mut SchemaSet,
    job: &InlineTypeJob,
    type_key: TypeKey,
    stats: &mut InlineAssemblyStats,
) -> SchemaResult<()> {
    match job.owner {
        InlineOwner::Element(key) => {
            if let Some(elem) = schema_set.arenas.elements.get_mut(key) {
                match job.role {
                    #[cfg(feature = "xsd11")]
                    InlineRole::AlternativeType(idx) => {
                        if let Some(alt) = elem.alternatives.get_mut(idx) {
                            alt.resolved_type = Some(type_key);
                        }
                    }
                    _ => {
                        elem.resolved_type = Some(type_key);
                        stats.element_inline_types += 1;
                    }
                }
                stats.total_inline_types += 1;
            }
        }
        InlineOwner::Attribute(key) => {
            if let Some(attr) = schema_set.arenas.attributes.get_mut(key) {
                attr.resolved_type = Some(type_key);
                stats.attribute_inline_types += 1;
                stats.total_inline_types += 1;
            }
        }
        InlineOwner::SimpleType(key) => {
            if let Some(simple) = schema_set.arenas.simple_types.get_mut(key) {
                match job.role {
                    InlineRole::SimpleTypeBase => {
                        simple.resolved_base_type = Some(type_key);
                    }
                    InlineRole::ListItemType => {
                        simple.resolved_item_type = Some(type_key);
                    }
                    InlineRole::UnionMemberType(idx) => {
                        // For union members, we need to track position
                        // Insert at the correct position in resolved_member_types
                        while simple.resolved_member_types.len() <= idx {
                            // Use a placeholder that will be overwritten
                            // This handles sparse indices from inline types
                            simple.resolved_member_types.push(type_key);
                        }
                        simple.resolved_member_types[idx] = type_key;
                    }
                    _ => {}
                }
                stats.simple_type_inline_derivations += 1;
                stats.total_inline_types += 1;
            }
        }
        InlineOwner::ComplexType(key) => {
            if let Some(complex) = schema_set.arenas.complex_types.get_mut(key) {
                match job.role {
                    InlineRole::ComplexTypeBase => {
                        complex.resolved_base_type = Some(type_key);
                        stats.complex_type_inline_derivations += 1;
                    }
                    InlineRole::ComplexTypeAttribute(idx) => {
                        // Ensure resolved_attributes vec is large enough
                        while complex.resolved_attributes.len() <= idx {
                            complex.resolved_attributes.push(ResolvedAttributeUse {
                                resolved_type: None,
                                resolved_ref: None,
                            });
                        }
                        complex.resolved_attributes[idx].resolved_type = Some(type_key);
                        stats.complex_type_attribute_inline_types += 1;
                    }
                    InlineRole::ContentParticleType(idx) => {
                        while complex.resolved_content_particle_types.len() <= idx {
                            complex.resolved_content_particle_types.push(None);
                        }
                        complex.resolved_content_particle_types[idx] = Some(type_key);
                        stats.complex_type_inline_derivations += 1;
                    }
                    InlineRole::SimpleContentInlineType => {
                        complex.resolved_simple_content_type = Some(type_key);
                        stats.complex_type_inline_derivations += 1;
                    }
                    _ => {}
                }
                stats.total_inline_types += 1;
            }
        }
        InlineOwner::ModelGroup(key) => {
            if let Some(group) = schema_set.arenas.model_groups.get_mut(key) {
                if let InlineRole::ModelGroupParticle(flat_idx) = job.role {
                    // Store in flat-indexed resolved_particle_types
                    while group.resolved_particle_types.len() <= flat_idx {
                        group.resolved_particle_types.push(None);
                    }
                    group.resolved_particle_types[flat_idx] = Some(type_key);
                    stats.model_group_inline_types += 1;
                    stats.total_inline_types += 1;
                }
            }
        }
        InlineOwner::AttributeGroup(key) => {
            if let Some(group) = schema_set.arenas.attribute_groups.get_mut(key) {
                if let InlineRole::AttributeGroupAttribute(idx) = job.role {
                    // Ensure resolved_attributes vec is large enough
                    while group.resolved_attributes.len() <= idx {
                        group.resolved_attributes.push(ResolvedAttributeUse {
                            resolved_type: None,
                            resolved_ref: None,
                        });
                    }
                    group.resolved_attributes[idx].resolved_type = Some(type_key);
                    stats.attribute_group_inline_types += 1;
                    stats.total_inline_types += 1;
                }
            }
        }
    }
    Ok(())
}

/// Collect nested inline types from a newly assembled type
fn collect_nested_inline_types(
    schema_set: &SchemaSet,
    type_key: TypeKey,
    target_namespace: Option<NameId>,
    jobs: &mut Vec<InlineTypeJob>,
) {
    match type_key {
        TypeKey::Simple(key) => {
            if let Some(simple) = schema_set.arenas.simple_types.get(key) {
                // Check for nested inline types in base/item/member
                if let Some(TypeRefResult::Inline(inline_type)) = &simple.base_type {
                    jobs.push(InlineTypeJob {
                        owner: InlineOwner::SimpleType(key),
                        role: InlineRole::SimpleTypeBase,
                        type_frame: (**inline_type).clone(),
                        target_namespace,
                    });
                }
                if let Some(TypeRefResult::Inline(inline_type)) = &simple.item_type {
                    jobs.push(InlineTypeJob {
                        owner: InlineOwner::SimpleType(key),
                        role: InlineRole::ListItemType,
                        type_frame: (**inline_type).clone(),
                        target_namespace,
                    });
                }
                for (idx, member) in simple.member_types.iter().enumerate() {
                    if let TypeRefResult::Inline(inline_type) = member {
                        jobs.push(InlineTypeJob {
                            owner: InlineOwner::SimpleType(key),
                            role: InlineRole::UnionMemberType(idx),
                            type_frame: (**inline_type).clone(),
                            target_namespace,
                        });
                    }
                }
            }
        }
        TypeKey::Complex(key) => {
            if let Some(complex) = schema_set.arenas.complex_types.get(key) {
                // Check for nested inline types in base type
                if let Some(TypeRefResult::Inline(inline_type)) = &complex.base_type {
                    jobs.push(InlineTypeJob {
                        owner: InlineOwner::ComplexType(key),
                        role: InlineRole::ComplexTypeBase,
                        type_frame: (**inline_type).clone(),
                        target_namespace,
                    });
                }

                // Check for inline types in attributes
                for (idx, attr_use) in complex.attributes.iter().enumerate() {
                    if let Some(inline_type) = &attr_use.attribute.inline_type {
                        jobs.push(InlineTypeJob {
                            owner: InlineOwner::ComplexType(key),
                            role: InlineRole::ComplexTypeAttribute(idx),
                            type_frame: TypeFrameResult::Simple(Box::new((**inline_type).clone())),
                            target_namespace,
                        });
                    }
                }

                // Check content for nested inline types
                collect_content_inline_types(&complex.content, key, target_namespace, jobs);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::arenas::ElementDeclData;
    use crate::parser::frames::{SimpleTypeResult, SimpleTypeVariety};
    use crate::schema::model::DerivationSet;
    use crate::types::facets::FacetSet;

    fn create_simple_type_frame(variety: SimpleTypeVariety) -> TypeFrameResult {
        TypeFrameResult::Simple(Box::new(SimpleTypeResult {
            name: None,
            variety,
            base_type: None,
            item_type: None,
            member_types: Vec::new(),
            facets: FacetSet::new(),
            final_derivation: None,
            id: None,
            derivation_id: None,
            annotation: None,
            source: None,
        }))
    }

    #[test]
    fn test_assemble_inline_types_empty_schema() {
        let mut schema_set = SchemaSet::new();
        let result = assemble_inline_types(&mut schema_set);
        assert!(result.is_ok());
        let stats = result.unwrap();
        assert_eq!(stats.total_inline_types, 0);
    }

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

        let elem_name = schema_set.name_table.add("testElement");
        let inline_type = Box::new(create_simple_type_frame(SimpleTypeVariety::Atomic));

        let elem_data = ElementDeclData {
            name: Some(elem_name),
            target_namespace: None,
            ref_name: None,
            type_ref: None,
            inline_type: Some(inline_type),
            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);

        // Run inline assembly
        let result = assemble_inline_types(&mut schema_set);
        assert!(result.is_ok());
        let stats = result.unwrap();
        assert_eq!(stats.element_inline_types, 1);
        assert_eq!(stats.total_inline_types, 1);

        // Verify resolved_type is set
        let elem = schema_set.arenas.elements.get(elem_key).unwrap();
        assert!(elem.resolved_type.is_some());
        assert!(matches!(elem.resolved_type, Some(TypeKey::Simple(_))));

        // Verify inline_type is preserved
        assert!(elem.inline_type.is_some());
    }

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

        let type_name = schema_set.name_table.add("testType");
        let inline_base = Box::new(create_simple_type_frame(SimpleTypeVariety::Atomic));

        let type_data = SimpleTypeDefData {
            name: Some(type_name),
            target_namespace: None,
            variety: SimpleTypeVariety::Atomic,
            base_type: Some(TypeRefResult::Inline(inline_base)),
            item_type: None,
            member_types: Vec::new(),
            facets: FacetSet::new(),
            final_derivation: DerivationSet::empty(),
            id: None,
            derivation_id: None,
            annotation: None,
            source: None,
            resolved_base_type: None,
            resolved_item_type: None,
            resolved_member_types: Vec::new(),
            redefine_original: None,
            deferred_item_type_error: None,
        };

        let type_key = schema_set.arenas.alloc_simple_type(type_data);

        // Run inline assembly
        let result = assemble_inline_types(&mut schema_set);
        assert!(result.is_ok());
        let stats = result.unwrap();
        assert_eq!(stats.simple_type_inline_derivations, 1);

        // Verify resolved_base_type is set
        let simple = schema_set.arenas.simple_types.get(type_key).unwrap();
        assert!(simple.resolved_base_type.is_some());

        // Verify original base_type is preserved
        assert!(matches!(simple.base_type, Some(TypeRefResult::Inline(_))));
    }

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

        let type_name = schema_set.name_table.add("listType");
        let inline_item = Box::new(create_simple_type_frame(SimpleTypeVariety::Atomic));

        let type_data = SimpleTypeDefData {
            name: Some(type_name),
            target_namespace: None,
            variety: SimpleTypeVariety::List,
            base_type: None,
            item_type: Some(TypeRefResult::Inline(inline_item)),
            member_types: Vec::new(),
            facets: FacetSet::new(),
            final_derivation: DerivationSet::empty(),
            id: None,
            derivation_id: None,
            annotation: None,
            source: None,
            resolved_base_type: None,
            resolved_item_type: None,
            resolved_member_types: Vec::new(),
            redefine_original: None,
            deferred_item_type_error: None,
        };

        let type_key = schema_set.arenas.alloc_simple_type(type_data);

        // Run inline assembly
        let result = assemble_inline_types(&mut schema_set);
        assert!(result.is_ok());

        // Verify resolved_item_type is set
        let simple = schema_set.arenas.simple_types.get(type_key).unwrap();
        assert!(simple.resolved_item_type.is_some());
    }

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

        let type_name = schema_set.name_table.add("unionType");
        let inline_member1 = Box::new(create_simple_type_frame(SimpleTypeVariety::Atomic));
        let inline_member2 = Box::new(create_simple_type_frame(SimpleTypeVariety::Atomic));

        let type_data = SimpleTypeDefData {
            name: Some(type_name),
            target_namespace: None,
            variety: SimpleTypeVariety::Union,
            base_type: None,
            item_type: None,
            member_types: vec![
                TypeRefResult::Inline(inline_member1),
                TypeRefResult::Inline(inline_member2),
            ],
            facets: FacetSet::new(),
            final_derivation: DerivationSet::empty(),
            id: None,
            derivation_id: None,
            annotation: None,
            source: None,
            resolved_base_type: None,
            resolved_item_type: None,
            resolved_member_types: Vec::new(),
            redefine_original: None,
            deferred_item_type_error: None,
        };

        let type_key = schema_set.arenas.alloc_simple_type(type_data);

        // Run inline assembly
        let result = assemble_inline_types(&mut schema_set);
        assert!(result.is_ok());
        let stats = result.unwrap();
        assert_eq!(stats.simple_type_inline_derivations, 2);

        // Verify resolved_member_types has both members
        let simple = schema_set.arenas.simple_types.get(type_key).unwrap();
        assert_eq!(simple.resolved_member_types.len(), 2);
    }

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

        let mut schema_set = SchemaSet::new();

        let elem_name = schema_set.name_table.add("detail");
        let inline_type = Box::new(create_simple_type_frame(SimpleTypeVariety::Atomic));

        // Create a named model group with an element that has an inline type
        let group_data = ModelGroupData {
            name: Some(schema_set.name_table.add("myGroup")),
            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,
                    inline_type: Some(inline_type),
                    substitution_group: vec![],
                    default_value: None,
                    fixed_value: None,
                    nillable: false,
                    is_abstract: false,
                    min_occurs: 1,
                    max_occurs: Some(1),
                    block: Default::default(),
                    final_derivation: Default::default(),
                    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,
            resolved_particles: Vec::new(),
            resolved_particle_types: Vec::new(),
            resolved_particle_elements: Vec::new(),
            redefine_original: None,
            redefine_requires_restriction_check: false,
        };

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

        let result = assemble_inline_types(&mut schema_set);
        assert!(result.is_ok());
        let stats = result.unwrap();
        assert_eq!(stats.model_group_inline_types, 1);
        assert_eq!(stats.total_inline_types, 1);

        // Verify resolved_particle_types has the type set
        let group = schema_set.arenas.model_groups.get(_group_key).unwrap();
        assert_eq!(group.resolved_particle_types.len(), 1);
        assert!(
            group.resolved_particle_types[0].is_some(),
            "Expected resolved type at flat index 0"
        );
    }

    #[test]
    fn test_inline_type_in_content_particle_resolved() {
        use crate::parser::frames::{
            ComplexContentDefResult, Compositor, ElementFrameResult, ModelGroupDefResult,
        };

        let mut schema_set = SchemaSet::new();

        let elem_name = schema_set.name_table.add("child");
        let inline_type = Box::new(create_simple_type_frame(SimpleTypeVariety::Atomic));

        // Create a complex type with a content particle containing an element with inline type
        let content_particle = ParticleResult {
            term: ParticleTerm::Group(ModelGroupDefResult {
                name: 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,
                        inline_type: Some(inline_type),
                        substitution_group: vec![],
                        default_value: None,
                        fixed_value: None,
                        nillable: false,
                        is_abstract: false,
                        min_occurs: 1,
                        max_occurs: Some(1),
                        block: Default::default(),
                        final_derivation: Default::default(),
                        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,
            }),
            min_occurs: 1,
            max_occurs: Some(1),
            source: None,
        };

        let complex_data = ComplexTypeDefData {
            name: Some(schema_set.name_table.add("MyComplexType")),
            target_namespace: None,
            base_type: None,
            derivation_method: None,
            content: ComplexContentResult::Complex(ComplexContentDefResult {
                particle: Some(content_particle),
                derivation: crate::parser::frames::DerivationMethod::Restriction,
                mixed: false,
                mixed_explicit: false,
                base_type: None,
                open_content: None,
                attributes: Vec::new(),
                attribute_groups: Vec::new(),
                attribute_wildcard: None,
                assertions: Vec::new(),
                id: None,
                derivation_id: None,
                source: None,
            }),
            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: true,
            id: None,
            #[cfg(feature = "xsd11")]
            assertions: Vec::new(),
            #[cfg(feature = "xsd11")]
            xpath_default_namespace: None,
            annotation: None,
            source: None,
            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(complex_data);

        let result = assemble_inline_types(&mut schema_set);
        assert!(result.is_ok());
        let stats = result.unwrap();
        assert!(stats.total_inline_types >= 1);

        // Verify resolved_content_particle_types has the type set
        let ct = schema_set.arenas.complex_types.get(ct_key).unwrap();
        assert_eq!(ct.resolved_content_particle_types.len(), 1);
        assert!(ct.resolved_content_particle_types[0].is_some());
    }

    #[test]
    fn test_nested_inline_type_in_model_group() {
        use crate::arenas::ModelGroupData;
        use crate::parser::frames::{Compositor, ElementFrameResult, ModelGroupDefResult};

        let mut schema_set = SchemaSet::new();

        let elem_name = schema_set.name_table.add("nested_elem");
        let inline_type = Box::new(create_simple_type_frame(SimpleTypeVariety::Atomic));

        // Create a named model group:
        //   <xs:group name="G">
        //     <xs:sequence>
        //       <xs:choice>
        //         <xs:element name="nested_elem">
        //           <xs:simpleType>...</xs:simpleType>
        //         </xs:element>
        //       </xs:choice>
        //     </xs:sequence>
        //   </xs:group>
        let group_data = ModelGroupData {
            name: Some(schema_set.name_table.add("G")),
            target_namespace: None,
            ref_name: None,
            compositor: Some(Compositor::Sequence),
            particles: vec![ParticleResult {
                term: ParticleTerm::Group(ModelGroupDefResult {
                    name: None,
                    ref_name: None,
                    compositor: Some(Compositor::Choice),
                    particles: vec![ParticleResult {
                        term: ParticleTerm::Element(ElementFrameResult {
                            name: Some(elem_name),
                            ref_name: None,
                            target_namespace: None,
                            type_ref: None,
                            inline_type: Some(inline_type),
                            substitution_group: vec![],
                            default_value: None,
                            fixed_value: None,
                            nillable: false,
                            is_abstract: false,
                            min_occurs: 1,
                            max_occurs: Some(1),
                            block: Default::default(),
                            final_derivation: Default::default(),
                            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,
                }),
                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,
            resolved_particles: Vec::new(),
            resolved_particle_types: Vec::new(),
            resolved_particle_elements: Vec::new(),
            redefine_original: None,
            redefine_requires_restriction_check: false,
        };

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

        // Run inline assembly
        let result = assemble_inline_types(&mut schema_set);
        assert!(result.is_ok());
        let stats = result.unwrap();
        assert_eq!(stats.model_group_inline_types, 1);
        assert_eq!(stats.total_inline_types, 1);

        // Verify resolved_particle_types has the type at flat index 0
        let group = schema_set.arenas.model_groups.get(group_key).unwrap();
        assert_eq!(group.resolved_particle_types.len(), 1);
        assert!(
            group.resolved_particle_types[0].is_some(),
            "Expected resolved type for nested element at flat index 0"
        );
        assert!(matches!(
            group.resolved_particle_types[0],
            Some(TypeKey::Simple(_))
        ));
    }
}