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
//! Schema model - SchemaSet, SchemaDocument, NamespaceTable
//!
//! This module contains the core schema organization structures:
//! - `SchemaSet` - Complete schema collection with all documents and components
//! - `SchemaDocument` - Individual schema document (root or included/imported)
//! - `NamespaceTable` - Per-namespace component lookup

use bitflags::bitflags;
use std::collections::HashMap;

use crate::arenas::SchemaArenas;
use crate::ids::*;
use crate::namespace::table::well_known;
use crate::namespace::NameTable;
use crate::namespace::QualifiedName;
use crate::parser::location::{SourceLocation, SourceMapStorage, SourceRef};
use crate::schema::annotation::Annotation;
use crate::schema::composition::{
    ComponentIdentity, ComponentKind, CompositionEdge, DocumentComponentIndex, EffectiveComponent,
};
use crate::schema::wildcard::ElementWildcard;
use crate::types::{BuiltinTypes, XmlTypeCode};

/// XSD version mode
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum XsdVersion {
    #[default]
    V1_0,
    V1_1,
}

/// Regex compatibility mode.
///
/// Controls how strictly the pattern facet grammar is enforced. The default
/// `Strict` rejects any construct outside XSD Part 2 §F (1.0) / §G (1.1)
/// regex grammar. `LenientMs` enables a closed list of safely-stripable MS
/// dialect leniencies for schemas authored against .NET's regex engine —
/// see `doc/INTRODUCTION.md` for the exact construct list.
///
/// This is an enum (not a bool) so future modes can be added without
/// breaking the API.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RegexCompat {
    /// Strict XSD Part 2 regex grammar. Default.
    #[default]
    Strict,
    /// Tolerate a closed list of MS dialect leniencies (anchors at
    /// pattern start/end, `(?#...)` comments). See `doc/INTRODUCTION.md`.
    LenientMs,
}

bitflags! {
    /// Derivation control flags (for final, block attributes)
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
    pub struct DerivationSet: u8 {
        const EXTENSION = 0x01;
        const RESTRICTION = 0x02;
        const LIST = 0x04;
        const UNION = 0x08;
        const SUBSTITUTION = 0x10;

        /// All derivation methods blocked
        const ALL = Self::EXTENSION.bits() | Self::RESTRICTION.bits() |
                   Self::LIST.bits() | Self::UNION.bits() | Self::SUBSTITUTION.bits();

        /// Element-relevant block bits (LIST and UNION are not meaningful for elements)
        const ELEMENT_BLOCK = Self::EXTENSION.bits() | Self::RESTRICTION.bits() | Self::SUBSTITUTION.bits();
    }
}

impl DerivationSet {
    /// Create a DerivationSet with only EXTENSION
    pub fn extension() -> Self {
        Self::EXTENSION
    }

    /// Create a DerivationSet with only RESTRICTION
    pub fn restriction() -> Self {
        Self::RESTRICTION
    }

    /// Check if extension is blocked/final
    pub fn contains_extension(&self) -> bool {
        self.contains(Self::EXTENSION)
    }

    /// Check if restriction is blocked/final
    pub fn contains_restriction(&self) -> bool {
        self.contains(Self::RESTRICTION)
    }

    /// Check if list derivation is blocked/final
    pub fn contains_list(&self) -> bool {
        self.contains(Self::LIST)
    }

    /// Check if union derivation is blocked/final
    pub fn contains_union(&self) -> bool {
        self.contains(Self::UNION)
    }

    /// Check if substitution is blocked
    pub fn contains_substitution(&self) -> bool {
        self.contains(Self::SUBSTITUTION)
    }

    /// Mask to only element-relevant block bits (extension, restriction, substitution).
    /// LIST and UNION are simple-type derivation methods and have no meaning in element
    /// block attributes. Per the spec, element `block="#all"` means `{extension, restriction,
    /// substitution}` only.
    pub fn element_block_mask(self) -> Self {
        self & Self::ELEMENT_BLOCK
    }
}

/// Form choice for element/attribute form defaults
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FormChoice {
    #[default]
    Unqualified,
    Qualified,
}

/// Complete schema set (possibly from multiple documents)
///
/// This is the main entry point for working with XSD schemas.
/// It owns all schema components and provides namespace-based lookup.
#[derive(Debug)]
pub struct SchemaSet {
    /// String interning table for names and namespace URIs
    pub name_table: NameTable,

    /// Centralized source map storage for all documents
    pub source_maps: SourceMapStorage,

    /// All parsed schema documents
    pub documents: Vec<SchemaDocument>,

    /// Per-namespace component tables (keyed by NameId; None = no namespace)
    pub namespaces: HashMap<Option<NameId>, NamespaceTable>,

    /// XSD version mode (1.0 or 1.1)
    pub xsd_version: XsdVersion,

    /// Regex compatibility mode for pattern facets. Default `Strict`.
    pub regex_compatibility: RegexCompat,

    /// Arena storage for all components
    pub arenas: SchemaArenas,

    /// Loaded schema locations (for cycle detection)
    pub loaded_locations: HashMap<String, DocumentId>,

    /// Secondary cache for chameleon schema variants loaded under different
    /// target namespaces. Keyed by `(resolved_uri, adopted_namespace)`.
    /// Allows the same no-namespace schema to be loaded separately for
    /// each including namespace per §4.2.3.
    pub chameleon_cache: HashMap<(String, NameId), DocumentId>,

    /// Composition graph edges recorded during directive resolution
    pub composition_edges: Vec<CompositionEdge>,

    /// Effective component map with provenance (populated by composition phase).
    /// Keyed by `ComponentIdentity` so redefine/override *replaces* the entry
    /// instead of appending, producing the final visible component set.
    pub effective_components: HashMap<ComponentIdentity, EffectiveComponent>,

    /// Built-in type registry with well-known type IDs
    builtin_types: Option<BuiltinTypes>,

    /// Parsing errors collected during error-recovery mode.
    /// These are structural errors that make the schema invalid but
    /// were deferred so parsing could continue for better diagnostics.
    pub parsing_errors: Vec<crate::error::SchemaError>,
}

impl SchemaSet {
    /// Create a new empty schema set
    pub fn new() -> Self {
        Self::with_version(XsdVersion::V1_0)
    }

    /// Create a new schema set configured for XSD 1.0.
    pub fn xsd10() -> Self {
        Self::with_version(XsdVersion::V1_0)
    }

    /// Create a new schema set configured for XSD 1.1.
    pub fn xsd11() -> Self {
        Self::with_version(XsdVersion::V1_1)
    }

    /// Create a new schema set with specified version
    pub fn with_version(version: XsdVersion) -> Self {
        let mut set = Self {
            name_table: NameTable::new(),
            source_maps: SourceMapStorage::new(),
            documents: Vec::new(),
            namespaces: HashMap::new(),
            xsd_version: version,
            regex_compatibility: RegexCompat::Strict,
            arenas: SchemaArenas::new(),
            loaded_locations: HashMap::new(),
            chameleon_cache: HashMap::new(),
            composition_edges: Vec::new(),
            effective_components: HashMap::new(),
            builtin_types: None,
            parsing_errors: Vec::new(),
        };

        // Initialize built-in types
        let builtin_types = BuiltinTypes::new(&mut set);
        set.builtin_types = Some(builtin_types);

        set
    }

    /// Returns `true` if this schema set is configured for XSD 1.0.
    pub fn is_xsd10(&self) -> bool {
        self.xsd_version == XsdVersion::V1_0
    }

    /// Returns `true` if this schema set is configured for XSD 1.1.
    pub fn is_xsd11(&self) -> bool {
        self.xsd_version == XsdVersion::V1_1
    }

    /// Set the regex compatibility mode for this schema set.
    ///
    /// Affects how pattern facets in subsequently compiled schemas are
    /// validated. Has no effect on already-compiled patterns. Default is
    /// `RegexCompat::Strict`.
    pub fn set_regex_compatibility(&mut self, compat: RegexCompat) {
        self.regex_compatibility = compat;
    }

    /// Get the regex compatibility mode for this schema set.
    pub fn regex_compatibility(&self) -> RegexCompat {
        self.regex_compatibility
    }

    /// Resolve an optional `SourceRef` to its line/column location.
    /// Returns `None` if the source is absent or cannot be located.
    pub fn locate(&self, source: Option<&SourceRef>) -> Option<SourceLocation> {
        source.and_then(|s| self.source_maps.locate(s))
    }

    /// Returns `true` if any parsing errors were collected during error-recovery parsing.
    pub fn has_parsing_errors(&self) -> bool {
        !self.parsing_errors.is_empty()
    }

    /// Iterate the normalized locations of all loaded schema documents.
    ///
    /// Useful for seeding a new [`SchemaSetBuilder`] with the same schemas
    /// when enriching with `xsi:schemaLocation` hints.
    pub fn loaded_schema_locations(&self) -> impl Iterator<Item = &str> {
        self.loaded_locations.keys().map(|s| s.as_str())
    }

    /// Check if a schema location has already been loaded
    pub fn is_loaded(&self, location: &str) -> bool {
        self.loaded_locations.contains_key(location)
    }

    /// Mark a schema location as loaded
    pub fn mark_loaded(&mut self, location: String, doc_id: DocumentId) {
        self.loaded_locations.insert(location, doc_id);
    }

    /// Get or create namespace table for a namespace
    pub fn get_or_create_namespace(&mut self, ns: Option<NameId>) -> &mut NamespaceTable {
        self.namespaces.entry(ns).or_default()
    }

    /// Look up a type by namespace and name
    pub fn lookup_type(&self, ns: Option<NameId>, name: NameId) -> Option<TypeKey> {
        self.namespaces.get(&ns)?.types.get(&name).copied()
    }

    /// Look up an element by namespace and name
    pub fn lookup_element(&self, ns: Option<NameId>, name: NameId) -> Option<ElementKey> {
        self.namespaces.get(&ns)?.elements.get(&name).copied()
    }

    /// Look up an attribute by namespace and name
    pub fn lookup_attribute(&self, ns: Option<NameId>, name: NameId) -> Option<AttributeKey> {
        self.namespaces.get(&ns)?.attributes.get(&name).copied()
    }

    /// Look up a model group by namespace and name
    pub fn lookup_model_group(&self, ns: Option<NameId>, name: NameId) -> Option<ModelGroupKey> {
        self.namespaces.get(&ns)?.model_groups.get(&name).copied()
    }

    /// Look up an attribute group by namespace and name
    pub fn lookup_attribute_group(
        &self,
        ns: Option<NameId>,
        name: NameId,
    ) -> Option<AttributeGroupKey> {
        self.namespaces
            .get(&ns)?
            .attribute_groups
            .get(&name)
            .copied()
    }

    /// Look up a notation by namespace and name
    pub fn lookup_notation(&self, ns: Option<NameId>, name: NameId) -> Option<NotationKey> {
        self.namespaces.get(&ns)?.notations.get(&name).copied()
    }

    // ========================================================================
    // Built-in type access
    // ========================================================================

    /// Get the built-in types registry.
    ///
    /// This provides access to well-known type IDs for all 47+ built-in XSD types.
    pub fn builtin_types(&self) -> &BuiltinTypes {
        self.builtin_types
            .as_ref()
            .expect("BuiltinTypes should always be initialized")
    }

    /// Get a built-in simple type by QName (namespace + local name).
    ///
    /// This only looks up built-in types in the XS namespace.
    /// For user-defined types, use `lookup_type` instead.
    ///
    /// # Arguments
    /// * `namespace` - The namespace URI (should be XS namespace for built-in types)
    /// * `local_name` - The local name of the type
    ///
    /// # Returns
    /// The `SimpleTypeKey` for the built-in type, or `None` if not found.
    pub fn get_built_in_simple_type_by_qname(
        &self,
        namespace: Option<NameId>,
        local_name: NameId,
    ) -> Option<SimpleTypeKey> {
        // Built-in types are only in the XS namespace
        if namespace != Some(well_known::XS_NAMESPACE) {
            return None;
        }
        self.builtin_types().get_by_local_name(local_name)
    }

    /// Get a built-in type by QName (namespace + local name).
    ///
    /// This includes the built-in complex type `xs:anyType` and all built-in simple types.
    pub fn get_built_in_type_by_qname(
        &self,
        namespace: Option<NameId>,
        local_name: NameId,
    ) -> Option<TypeKey> {
        if namespace != Some(well_known::XS_NAMESPACE) {
            return None;
        }

        if let Some(any_type_name) = self.name_table.get("anyType") {
            if local_name == any_type_name {
                return Some(TypeKey::Complex(self.builtin_types().any_type));
            }
        }

        self.get_built_in_simple_type_by_qname(namespace, local_name)
            .map(TypeKey::Simple)
    }

    /// Get the built-in `xs:anyType` key.
    pub fn any_type_key(&self) -> ComplexTypeKey {
        self.builtin_types().any_type
    }

    /// Check if the given type key refers to `xs:anyType`.
    pub fn is_any_type(&self, type_key: TypeKey) -> bool {
        matches!(type_key, TypeKey::Complex(key) if key == self.builtin_types().any_type)
    }

    /// Get a built-in simple type by its XmlTypeCode.
    ///
    /// # Returns
    /// The `SimpleTypeKey` for the built-in type, or `None` if not a simple type code.
    pub fn get_built_in_simple_type_by_code(&self, code: XmlTypeCode) -> Option<SimpleTypeKey> {
        self.builtin_types().get_by_type_code(code)
    }

    /// Get the XmlTypeCode for a simple type.
    ///
    /// Returns `None` if the type is not a built-in type.
    pub fn get_type_code(&self, type_id: SimpleTypeKey) -> Option<XmlTypeCode> {
        self.builtin_types().get_type_code(type_id)
    }

    /// Check if `derived` derives from `base` (transitively).
    ///
    /// For built-in types, this uses the standard XSD derivation hierarchy.
    /// For user-defined types, this walks the base type chain using resolved references.
    ///
    /// # Returns
    /// - `true` if `derived == base`
    /// - `true` if `derived` has `base` somewhere in its derivation chain
    /// - `false` otherwise
    pub fn derives_from(&self, derived: SimpleTypeKey, base: SimpleTypeKey) -> bool {
        // Same type derives from itself
        if derived == base {
            return true;
        }

        // First, check if both are built-in types and use the built-in derivation
        let builtin = self.builtin_types();
        if builtin.is_builtin(derived) && builtin.is_builtin(base) {
            return builtin.derives_from(derived, base);
        }

        // For user-defined types (or mixed), walk the resolved base type chain
        let mut current = derived;
        let mut visited = std::collections::HashSet::new();

        while visited.insert(current) {
            // Get the simple type data
            if let Some(type_def) = self.arenas.simple_types.get(current) {
                // Check the resolved base type
                if let Some(crate::ids::TypeKey::Simple(simple_base)) = type_def.resolved_base_type
                {
                    if simple_base == base {
                        return true;
                    }
                    current = simple_base;
                    continue;
                }
            }

            // If no resolved base type, try built-in derivation as fallback
            if builtin.is_builtin(current) {
                if let Some(parent) = builtin.get_base_type(current) {
                    if parent == base {
                        return true;
                    }
                    current = parent;
                    continue;
                }
            }

            // No more base types to traverse
            break;
        }

        false
    }

    // ========================================================================
    // Type derivation checking (analog of C# XmlSchemaType.IsDerivedFrom)
    // ========================================================================

    /// Check if `derived` is derived from `base`, optionally filtering by derivation method.
    ///
    /// This mirrors C#'s `XmlSchemaType.IsDerivedFrom(derivedType, baseType, method)`.
    ///
    /// # Arguments
    /// * `derived` - The potentially derived type
    /// * `base` - The potential base type
    /// * `exclude_methods` - Derivation methods to exclude from the check.
    ///   Use `DerivationSet::empty()` to allow any method (like C#'s Empty).
    ///
    /// # Returns
    /// - `true` if `derived == base`
    /// - `true` if `derived` derives from `base` via a non-excluded derivation method
    /// - `false` otherwise
    pub fn is_type_derived_from(
        &self,
        derived: TypeKey,
        base: TypeKey,
        exclude_methods: DerivationSet,
    ) -> bool {
        // Same type derives from itself
        if derived == base {
            return true;
        }

        // Everything derives from anyType. With no method exclusions we can
        // short-circuit, but with a non-empty exclusion mask we must walk the
        // chain to verify no step uses a blocked method (§3.4.6.5 / §3.16.6).
        // For Simple→AnyType the chain *always* terminates with the
        // anySimpleType→anyType restriction step, so an exclusion containing
        // RESTRICTION (or matching the simple's variety method) blocks it
        // (cvc-elt.4.3 with `block="restriction"` / `block="#all"` and
        // declared anyType: elemT026/27/28/29, elemT054/55/56/57).
        if self.is_any_type(base) {
            if exclude_methods.is_empty() {
                return true;
            }
            if let TypeKey::Simple(d) = derived {
                return self.is_simple_chain_to_any_type_ok(d, exclude_methods);
            }
            // Complex→AnyType falls through to is_complex_type_derived_from below.
        }

        match (derived, base) {
            // Case 1: Both are simple types
            (TypeKey::Simple(d), TypeKey::Simple(b)) => {
                self.is_simple_type_derived_from(d, b, exclude_methods)
            }

            // Case 2: Both are complex types
            (TypeKey::Complex(d), TypeKey::Complex(b)) => {
                self.is_complex_type_derived_from(d, b, exclude_methods)
            }

            // Case 3: Simple derives from Complex
            // All simple types derive from anyType (via anySimpleType).
            (TypeKey::Simple(_), TypeKey::Complex(_)) => false,

            // Case 4: Complex derives from Simple
            // Complex types with simpleContent can derive from simple types
            (TypeKey::Complex(d), TypeKey::Simple(b)) => {
                self.is_complex_derived_from_simple(d, b, exclude_methods)
            }
        }
    }

    /// Whether the simple→anyType derivation chain rooted at `derived` avoids
    /// every method in `exclude_methods`. Used by `is_type_derived_from` when
    /// `base = anyType` and `exclude_methods` is non-empty (§3.16.6 + the
    /// implicit anySimpleType→anyType restriction step).
    fn is_simple_chain_to_any_type_ok(
        &self,
        derived: SimpleTypeKey,
        exclude_methods: DerivationSet,
    ) -> bool {
        use crate::parser::frames::SimpleTypeVariety;

        let mut current = derived;
        let mut visited = std::collections::HashSet::new();

        while visited.insert(current) {
            if let Some(type_def) = self.arenas.simple_types.get(current) {
                let method_flag = match type_def.variety {
                    SimpleTypeVariety::Atomic => DerivationSet::RESTRICTION,
                    SimpleTypeVariety::List => DerivationSet::LIST,
                    SimpleTypeVariety::Union => DerivationSet::UNION,
                };
                if exclude_methods.contains(method_flag) {
                    return false;
                }
                if let Some(TypeKey::Simple(simple_base)) = type_def.resolved_base_type {
                    current = simple_base;
                    continue;
                }
            }
            // Fell off the user-defined simple chain — the next step is the
            // anySimpleType→anyType restriction in the built-in hierarchy.
            return !exclude_methods.contains(DerivationSet::RESTRICTION);
        }
        // Cycle detected (shouldn't happen for resolved schemas).
        false
    }

    /// Check if simple type `derived` is derived from simple type `base` with method filtering.
    ///
    /// Implements XSD spec §3.16.6.3 "Type Derivation OK (Simple)":
    /// - Clause 2.2.1/2.2.2: walks the `resolved_base_type` chain
    /// - Clause 2.2.4: if `base` is a union, checks transitive member types
    fn is_simple_type_derived_from(
        &self,
        derived: SimpleTypeKey,
        base: SimpleTypeKey,
        exclude_methods: DerivationSet,
    ) -> bool {
        use crate::parser::frames::SimpleTypeVariety;

        // Clause 1: Same type
        if derived == base {
            return true;
        }

        // Clause 2.2.1/2.2.2: Walk the base type chain
        let builtin = self.builtin_types();
        let mut current = derived;
        let mut visited = std::collections::HashSet::new();

        while visited.insert(current) {
            // Get type definition
            if let Some(type_def) = self.arenas.simple_types.get(current) {
                // Determine derivation method based on variety
                let method_flag = match type_def.variety {
                    SimpleTypeVariety::Atomic => DerivationSet::RESTRICTION,
                    SimpleTypeVariety::List => DerivationSet::LIST,
                    SimpleTypeVariety::Union => DerivationSet::UNION,
                };

                // If this derivation method is excluded, stop traversal
                if exclude_methods.contains(method_flag) {
                    break;
                }

                // Check resolved base type
                if let Some(TypeKey::Simple(simple_base)) = type_def.resolved_base_type {
                    if simple_base == base {
                        return true;
                    }
                    current = simple_base;
                    continue;
                }
            }

            // Fallback to built-in derivation
            if builtin.is_builtin(current) {
                // For built-in types, derivation is always by restriction
                if exclude_methods.contains(DerivationSet::RESTRICTION) {
                    break;
                }
                if let Some(parent) = builtin.get_base_type(current) {
                    if parent == base {
                        return true;
                    }
                    current = parent;
                    continue;
                }
            }

            break;
        }

        // Clause 2.2.4: If base is a union with no facets, check whether
        // derived is derived from a transitive member type.
        if let Some(base_def) = self.arenas.simple_types.get(base) {
            if base_def.variety == SimpleTypeVariety::Union && base_def.facets.is_empty() {
                for &member_type_key in &base_def.resolved_member_types {
                    if let TypeKey::Simple(member_key) = member_type_key {
                        if self.is_simple_type_derived_from(derived, member_key, exclude_methods) {
                            return true;
                        }
                    }
                }
            }
        }

        false
    }

    /// Check if complex type `derived` is derived from complex type `base` with method filtering.
    fn is_complex_type_derived_from(
        &self,
        derived: ComplexTypeKey,
        base: ComplexTypeKey,
        exclude_methods: DerivationSet,
    ) -> bool {
        use crate::parser::frames::DerivationMethod;

        if derived == base {
            return true;
        }

        let mut current = derived;
        let mut visited = std::collections::HashSet::new();

        while visited.insert(current) {
            if let Some(type_def) = self.arenas.complex_types.get(current) {
                // Determine derivation method flag
                let method_flag = match type_def.derivation_method {
                    Some(DerivationMethod::Extension) => DerivationSet::EXTENSION,
                    Some(DerivationMethod::Restriction) | None => DerivationSet::RESTRICTION,
                };

                // If this derivation method is excluded, stop traversal
                if exclude_methods.contains(method_flag) {
                    return false;
                }

                // Check resolved base type
                if let Some(TypeKey::Complex(complex_base)) = type_def.resolved_base_type {
                    if complex_base == base {
                        return true;
                    }
                    current = complex_base;
                    continue;
                }

                // resolved_base_type is None (shorthand complex type) or
                // Some(TypeKey::Simple(_)) (simpleContent). Both ultimately
                // derive from xs:anyType — check if that is the target.
                return base == self.any_type_key();
            }

            break;
        }

        false
    }

    /// Check if complex type `derived` (with simpleContent) derives from simple type `base`.
    fn is_complex_derived_from_simple(
        &self,
        derived: ComplexTypeKey,
        base: SimpleTypeKey,
        exclude_methods: DerivationSet,
    ) -> bool {
        use crate::parser::frames::DerivationMethod;

        // Walk the complex type chain, stepping through each derivation level.
        // A complex type with simpleContent can have a chain:
        //   ct_n (restriction of ct_{n-1}) → … → ct_1 (extension of simple_type)
        let mut current = derived;
        let mut visited = std::collections::HashSet::new();

        while visited.insert(current) {
            let Some(type_def) = self.arenas.complex_types.get(current) else {
                break;
            };

            let method_flag = match type_def.derivation_method {
                Some(DerivationMethod::Extension) => DerivationSet::EXTENSION,
                Some(DerivationMethod::Restriction) | None => DerivationSet::RESTRICTION,
            };

            if exclude_methods.contains(method_flag) {
                return false;
            }

            match type_def.resolved_base_type {
                Some(TypeKey::Simple(simple_base)) => {
                    if simple_base == base {
                        return true;
                    }
                    // Walk further up the simple type chain.
                    return self.is_simple_type_derived_from(simple_base, base, exclude_methods);
                }
                Some(TypeKey::Complex(complex_base)) => {
                    // Base is another complex type; keep walking.
                    current = complex_base;
                }
                None => break,
            }
        }

        false
    }

    /// Format a provenance note for a component (returns empty string if none/declared).
    ///
    /// Used to enrich error messages with information about where a component
    /// originated (e.g., redefined from another schema document).
    pub fn format_provenance_note(
        &self,
        kind: ComponentKind,
        namespace: Option<NameId>,
        name: NameId,
    ) -> String {
        use crate::schema::composition::CompositionAction;

        let identity = ComponentIdentity {
            kind,
            name,
            namespace,
        };
        match self.effective_components.get(&identity) {
            Some(eff) => match &eff.action {
                CompositionAction::Redefined { from_doc, replaced } => {
                    let target_uri = replaced
                        .owner_doc
                        .and_then(|id| self.documents.get(id as usize))
                        .map(|d| d.base_uri.as_str())
                        .unwrap_or("unknown");
                    let from_uri = from_doc
                        .and_then(|id| self.documents.get(id as usize))
                        .map(|d| d.base_uri.as_str())
                        .unwrap_or("unknown");
                    format!(" (originally in {}, redefined by {})", target_uri, from_uri)
                }
                #[cfg(feature = "xsd11")]
                CompositionAction::Overridden { from_doc, replaced } => {
                    let target_uri = replaced
                        .owner_doc
                        .and_then(|id| self.documents.get(id as usize))
                        .map(|d| d.base_uri.as_str())
                        .unwrap_or("unknown");
                    let from_uri = from_doc
                        .and_then(|id| self.documents.get(id as usize))
                        .map(|d| d.base_uri.as_str())
                        .unwrap_or("unknown");
                    format!(
                        " (originally in {}, overridden by {})",
                        target_uri, from_uri
                    )
                }
                CompositionAction::Included { from_doc } => {
                    let uri = self
                        .documents
                        .get(*from_doc as usize)
                        .map(|d| d.base_uri.as_str())
                        .unwrap_or("unknown");
                    format!(" (included by {})", uri)
                }
                CompositionAction::Declared => String::new(),
            },
            None => String::new(),
        }
    }

    /// Compute the effective namespace for a local element declaration per XSD spec.
    ///
    /// Rules: explicit targetNamespace > form attribute > elementFormDefault > Unqualified.
    /// Qualified → document target namespace; Unqualified → None.
    pub fn effective_local_element_namespace(
        &self,
        elem_target_namespace: Option<NameId>,
        elem_form: Option<&str>,
        source: Option<&SourceRef>,
        fallback_namespace: Option<NameId>,
    ) -> Option<NameId> {
        self.effective_local_namespace(
            elem_target_namespace,
            elem_form,
            source,
            fallback_namespace,
            |d| d.element_form_default,
        )
    }

    /// Compute the effective namespace for a local attribute declaration per XSD spec.
    ///
    /// Rules: explicit targetNamespace > form attribute > attributeFormDefault > Unqualified.
    /// Qualified → document target namespace; Unqualified → None.
    pub fn effective_local_attribute_namespace(
        &self,
        attr_target_namespace: Option<NameId>,
        attr_form: Option<&str>,
        source: Option<&SourceRef>,
        fallback_namespace: Option<NameId>,
    ) -> Option<NameId> {
        self.effective_local_namespace(
            attr_target_namespace,
            attr_form,
            source,
            fallback_namespace,
            |d| d.attribute_form_default,
        )
    }

    fn effective_local_namespace(
        &self,
        explicit_target_namespace: Option<NameId>,
        form: Option<&str>,
        source: Option<&SourceRef>,
        fallback_namespace: Option<NameId>,
        form_default: impl Fn(&SchemaDocument) -> FormChoice,
    ) -> Option<NameId> {
        if explicit_target_namespace.is_some() {
            return explicit_target_namespace;
        }
        // Use defaults_doc() so override children read the overridden
        // document's form defaults per §4.2.5 / F.2 semantics.
        let doc = source.and_then(|s| self.documents.get(s.defaults_doc() as usize));
        let default_form = doc.map(&form_default).unwrap_or(FormChoice::Unqualified);
        let target_namespace = doc
            .map(|d| d.target_namespace)
            .unwrap_or(fallback_namespace);
        let resolved_form = match form {
            Some("qualified") => FormChoice::Qualified,
            Some("unqualified") => FormChoice::Unqualified,
            _ => default_form,
        };
        match resolved_form {
            FormChoice::Qualified => target_namespace,
            FormChoice::Unqualified => None,
        }
    }
}

impl Default for SchemaSet {
    fn default() -> Self {
        Self::new()
    }
}

/// A single schema document (root or included/imported)
///
/// Represents one XSD file with its components and directives.
#[derive(Debug)]
pub struct SchemaDocument {
    /// Document ID for source map reference
    pub id: DocumentId,

    /// Base URI (location) of this document
    pub base_uri: String,

    /// The `targetNamespace` as declared in the `<xs:schema>` element.
    /// `None` when the schema document omits `targetNamespace`.
    /// Preserved even after chameleon adoption so the original fact
    /// "this document had no declared namespace" is never lost.
    pub declared_target_namespace: Option<NameId>,

    /// Effective target namespace after chameleon pre-processing (§4.2.3).
    /// Equals `declared_target_namespace` for non-chameleon documents;
    /// set to the includer's namespace for chameleon-adopted documents.
    pub target_namespace: Option<NameId>,

    /// Schema-level attributes
    pub version: Option<String>,
    pub element_form_default: FormChoice,
    pub attribute_form_default: FormChoice,
    pub block_default: DerivationSet,
    pub final_default: DerivationSet,
    pub schema_id: Option<String>,
    pub xml_lang: Option<String>,

    /// XSD 1.1: Default attributes group reference
    pub default_attributes: Option<QualifiedName>,

    /// XSD 1.1: Default namespace for XPath
    pub xpath_default_namespace: Option<NameId>,

    /// Composition directives (in document order)
    pub includes: Vec<IncludeDirective>,
    pub imports: Vec<ImportDirective>,
    pub redefines: Vec<RedefineDirective>,
    pub overrides: Vec<OverrideDirective>, // XSD 1.1

    /// XSD 1.1: Default open content
    pub default_open_content: Option<DefaultOpenContent>,

    /// Schema-level annotations
    pub annotations: Vec<Annotation>,

    /// Per-document index of top-level components declared in this document.
    /// Populated during assembly; used for document-scoped lookup in
    /// `apply_redefine()` and `apply_override()`.
    pub component_index: DocumentComponentIndex,

    /// Source reference for error reporting
    pub source: Option<SourceRef>,
}

impl SchemaDocument {
    /// Whether this document had no declared `targetNamespace` and adopted
    /// one via chameleon include pre-processing (§4.2.3 clause 2.3).
    pub fn is_chameleon(&self) -> bool {
        self.declared_target_namespace.is_none() && self.target_namespace.is_some()
    }

    /// Per-document QName visibility per XSD §3.17.6.2 `src-resolve` clause 4.
    ///
    /// Returns `true` when a QName whose resolved namespace is `qname_ns`
    /// may be referenced from this schema document. Resolution is strictly
    /// per-document and lexical: imports are not transitive.
    ///
    /// Reads `declared_target_namespace` for clause 4.1.1 / 4.2.1 so chameleon
    /// includes (no declared `targetNamespace`) take 4.1.1 for absent-NS QNames
    /// instead of failing 4.2.1 against the includer's NS. For chameleon docs
    /// whose QNames were rewritten by §4.2.3 adoption to the includer's NS,
    /// also accept the post-adoption `target_namespace`.
    pub fn can_see_namespace(&self, qname_ns: Option<NameId>, name_table: &NameTable) -> bool {
        if qname_ns.is_none() {
            // 4.1
            return self.declared_target_namespace.is_none()
                || self.imports.iter().any(|i| i.namespace.is_none());
        }
        // 4.2.1 (incl. chameleon-adopted target namespace)
        if qname_ns == self.declared_target_namespace
            || (self.is_chameleon() && qname_ns == self.target_namespace)
        {
            return true;
        }
        // 4.2.3 / 4.2.4
        if qname_ns == Some(well_known::XS_NAMESPACE) || qname_ns == Some(well_known::XSI_NAMESPACE)
        {
            return true;
        }
        // 4.2.2. `import.namespace` is `Option<String>` (not pre-interned), but every
        // *used* namespace is interned at parse time, so `get` (read-only) suffices —
        // a string never interned cannot match the already-interned `qname_ns`.
        self.imports.iter().any(|i| {
            i.namespace
                .as_deref()
                .and_then(|s| name_table.get(s))
                .map(|id| Some(id) == qname_ns)
                .unwrap_or(false)
        })
    }

    /// Create a new schema document
    pub fn new(id: DocumentId, base_uri: String) -> Self {
        Self {
            id,
            base_uri,
            declared_target_namespace: None,
            target_namespace: None,
            version: None,
            element_form_default: FormChoice::default(),
            attribute_form_default: FormChoice::default(),
            block_default: DerivationSet::empty(),
            final_default: DerivationSet::empty(),
            schema_id: None,
            xml_lang: None,
            default_attributes: None,
            xpath_default_namespace: None,
            includes: Vec::new(),
            imports: Vec::new(),
            redefines: Vec::new(),
            overrides: Vec::new(),
            default_open_content: None,
            annotations: Vec::new(),
            component_index: DocumentComponentIndex::new(),
            source: None,
        }
    }
}

/// Per-namespace component lookup tables
///
/// Each namespace has its own table mapping local names to component keys.
/// Uses NameId as keys for fast equality checks.
#[derive(Debug, Default)]
pub struct NamespaceTable {
    /// Type definitions (simple and complex)
    pub types: HashMap<NameId, TypeKey>,
    /// Element declarations
    pub elements: HashMap<NameId, ElementKey>,
    /// Attribute declarations
    pub attributes: HashMap<NameId, AttributeKey>,
    /// Attribute groups
    pub attribute_groups: HashMap<NameId, AttributeGroupKey>,
    /// Named model groups
    pub model_groups: HashMap<NameId, ModelGroupKey>,
    /// Notations
    pub notations: HashMap<NameId, NotationKey>,
    /// Identity constraints (global, for XSD 1.1 refs)
    pub identity_constraints: HashMap<NameId, IdentityConstraintKey>,
}

impl NamespaceTable {
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a type in this namespace
    pub fn register_type(&mut self, name: NameId, key: TypeKey) -> Option<TypeKey> {
        self.types.insert(name, key)
    }

    /// Register an element in this namespace
    pub fn register_element(&mut self, name: NameId, key: ElementKey) -> Option<ElementKey> {
        self.elements.insert(name, key)
    }

    /// Register an attribute in this namespace
    pub fn register_attribute(&mut self, name: NameId, key: AttributeKey) -> Option<AttributeKey> {
        self.attributes.insert(name, key)
    }

    /// Register a model group in this namespace
    pub fn register_model_group(
        &mut self,
        name: NameId,
        key: ModelGroupKey,
    ) -> Option<ModelGroupKey> {
        self.model_groups.insert(name, key)
    }

    /// Register an attribute group in this namespace
    pub fn register_attribute_group(
        &mut self,
        name: NameId,
        key: AttributeGroupKey,
    ) -> Option<AttributeGroupKey> {
        self.attribute_groups.insert(name, key)
    }

    /// Register a notation in this namespace
    pub fn register_notation(&mut self, name: NameId, key: NotationKey) -> Option<NotationKey> {
        self.notations.insert(name, key)
    }
}

// Schema composition directives

/// xs:include directive
#[derive(Debug, Clone)]
pub struct IncludeDirective {
    pub source: Option<SourceRef>,
    pub schema_location: String,
    pub resolved_doc_id: Option<DocumentId>,
}

/// xs:import directive
#[derive(Debug, Clone)]
pub struct ImportDirective {
    pub source: Option<SourceRef>,
    pub namespace: Option<String>,
    pub schema_location: Option<String>,
    pub resolved_doc_id: Option<DocumentId>,
}

/// xs:redefine directive (deprecated in XSD 1.1)
#[derive(Debug, Clone)]
pub struct RedefineDirective {
    pub source: Option<SourceRef>,
    pub schema_location: String,
    pub resolved_doc_id: Option<DocumentId>,
    pub simple_types: Vec<SimpleTypeKey>,
    pub complex_types: Vec<ComplexTypeKey>,
    pub groups: Vec<ModelGroupKey>,
    pub attribute_groups: Vec<AttributeGroupKey>,
}

/// xs:override directive (XSD 1.1)
#[derive(Debug, Clone)]
pub struct OverrideDirective {
    pub source: Option<SourceRef>,
    pub schema_location: String,
    pub resolved_doc_id: Option<DocumentId>,
    pub components: Vec<OverrideComponent>,
}

/// Component that can appear in xs:override
#[derive(Debug, Clone)]
pub enum OverrideComponent {
    SimpleType(SimpleTypeKey),
    ComplexType(ComplexTypeKey),
    Group(ModelGroupKey),
    AttributeGroup(AttributeGroupKey),
    Element(ElementKey),
    Attribute(AttributeKey),
    Notation(NotationKey),
}

/// Default open content at schema level (XSD 1.1)
#[derive(Debug, Clone)]
pub struct DefaultOpenContent {
    pub source: Option<SourceRef>,
    pub applies_to_empty: bool,
    pub mode: OpenContentMode,
    pub wildcard: Option<ElementWildcard>,
}

/// Open content mode (XSD 1.1)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OpenContentMode {
    None,
    #[default]
    Interleave,
    Suffix,
}

impl From<crate::parser::frames::OpenContentMode> for OpenContentMode {
    fn from(m: crate::parser::frames::OpenContentMode) -> Self {
        use crate::parser::frames::OpenContentMode as Src;
        match m {
            Src::None => Self::None,
            Src::Interleave => Self::Interleave,
            Src::Suffix => Self::Suffix,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::arenas::ComplexTypeDefData;
    use crate::parser::frames::ComplexContentResult;

    #[test]
    fn test_schema_set_creation() {
        let set = SchemaSet::new();
        assert_eq!(set.xsd_version, XsdVersion::V1_0);
        assert!(set.documents.is_empty());
        // XSI namespace is pre-populated with built-in attribute declarations
        assert!(set
            .namespaces
            .contains_key(&Some(crate::namespace::table::well_known::XSI_NAMESPACE)));
    }

    #[test]
    fn test_schema_set_with_version() {
        let set = SchemaSet::with_version(XsdVersion::V1_1);
        assert_eq!(set.xsd_version, XsdVersion::V1_1);
    }

    #[test]
    fn test_schema_set_xsd10() {
        let set = SchemaSet::xsd10();
        assert_eq!(set.xsd_version, XsdVersion::V1_0);
    }

    #[test]
    fn test_schema_set_xsd11() {
        let set = SchemaSet::xsd11();
        assert_eq!(set.xsd_version, XsdVersion::V1_1);
    }

    #[test]
    fn test_namespace_table_registration() {
        use slotmap::SlotMap;
        let mut table = NamespaceTable::new();

        // Create a dummy key for testing
        let mut dummy_map: SlotMap<SimpleTypeKey, ()> = SlotMap::with_key();
        let key1 = dummy_map.insert(());
        let key2 = dummy_map.insert(());

        // Register a type
        let old = table.register_type(NameId(1), TypeKey::Simple(key1));
        assert!(old.is_none());

        // Re-registering returns old value
        let old = table.register_type(NameId(1), TypeKey::Simple(key2));
        assert!(old.is_some());
    }

    #[test]
    fn test_schema_set_load_tracking() {
        let mut set = SchemaSet::new();

        assert!(!set.is_loaded("test.xsd"));
        set.mark_loaded("test.xsd".to_string(), 0);
        assert!(set.is_loaded("test.xsd"));
    }

    #[test]
    fn test_derivation_set_flags() {
        let mut flags = DerivationSet::empty();
        assert!(flags.is_empty());

        flags |= DerivationSet::EXTENSION;
        assert!(flags.contains(DerivationSet::EXTENSION));
        assert!(!flags.contains(DerivationSet::RESTRICTION));

        let all = DerivationSet::ALL;
        assert!(all.contains(DerivationSet::EXTENSION));
        assert!(all.contains(DerivationSet::RESTRICTION));
    }

    #[test]
    fn test_form_choice_default() {
        assert_eq!(FormChoice::default(), FormChoice::Unqualified);
    }

    // ========================================================================
    // Tests for is_type_derived_from (analog of C# XmlSchemaType.IsDerivedFrom)
    // ========================================================================

    #[test]
    fn test_is_type_derived_from_same_type() {
        let set = SchemaSet::new();
        let string_key = set.builtin_types().string;

        // Same type derives from itself
        assert!(set.is_type_derived_from(
            TypeKey::Simple(string_key),
            TypeKey::Simple(string_key),
            DerivationSet::empty()
        ));
    }

    #[test]
    fn test_is_type_derived_from_direct_derivation() {
        let set = SchemaSet::new();
        let builtin = set.builtin_types();

        // xs:normalizedString derives from xs:string
        assert!(set.is_type_derived_from(
            TypeKey::Simple(builtin.normalized_string),
            TypeKey::Simple(builtin.string),
            DerivationSet::empty()
        ));

        // xs:integer derives from xs:decimal
        assert!(set.is_type_derived_from(
            TypeKey::Simple(builtin.integer),
            TypeKey::Simple(builtin.decimal),
            DerivationSet::empty()
        ));
    }

    #[test]
    fn test_is_type_derived_from_transitive() {
        let set = SchemaSet::new();
        let builtin = set.builtin_types();

        // xs:NCName derives from xs:string (NCName < Name < token < normalizedString < string)
        assert!(set.is_type_derived_from(
            TypeKey::Simple(builtin.ncname),
            TypeKey::Simple(builtin.string),
            DerivationSet::empty()
        ));

        // xs:byte derives from xs:decimal (byte < short < int < long < integer < decimal)
        assert!(set.is_type_derived_from(
            TypeKey::Simple(builtin.byte),
            TypeKey::Simple(builtin.decimal),
            DerivationSet::empty()
        ));

        // xs:ID derives from xs:string (ID < NCName < Name < token < normalizedString < string)
        assert!(set.is_type_derived_from(
            TypeKey::Simple(builtin.id),
            TypeKey::Simple(builtin.string),
            DerivationSet::empty()
        ));
    }

    #[test]
    fn test_is_type_derived_from_not_derived() {
        let set = SchemaSet::new();
        let builtin = set.builtin_types();

        // xs:string does NOT derive from xs:integer
        assert!(!set.is_type_derived_from(
            TypeKey::Simple(builtin.string),
            TypeKey::Simple(builtin.integer),
            DerivationSet::empty()
        ));

        // xs:decimal does NOT derive from xs:integer (reverse direction)
        assert!(!set.is_type_derived_from(
            TypeKey::Simple(builtin.decimal),
            TypeKey::Simple(builtin.integer),
            DerivationSet::empty()
        ));

        // xs:date does NOT derive from xs:duration
        assert!(!set.is_type_derived_from(
            TypeKey::Simple(builtin.date),
            TypeKey::Simple(builtin.duration),
            DerivationSet::empty()
        ));
    }

    #[test]
    fn test_is_type_derived_from_any_simple_type() {
        let set = SchemaSet::new();
        let builtin = set.builtin_types();

        // All simple types derive from xs:anySimpleType
        assert!(set.is_type_derived_from(
            TypeKey::Simple(builtin.string),
            TypeKey::Simple(builtin.any_simple_type),
            DerivationSet::empty()
        ));

        assert!(set.is_type_derived_from(
            TypeKey::Simple(builtin.integer),
            TypeKey::Simple(builtin.any_simple_type),
            DerivationSet::empty()
        ));

        assert!(set.is_type_derived_from(
            TypeKey::Simple(builtin.byte),
            TypeKey::Simple(builtin.any_simple_type),
            DerivationSet::empty()
        ));
    }

    #[test]
    fn test_is_type_derived_from_any_type() {
        let mut set = SchemaSet::new();
        let any_type = set.builtin_types().any_type;
        let string_type = set.builtin_types().string;

        assert!(set.is_type_derived_from(
            TypeKey::Simple(string_type),
            TypeKey::Complex(any_type),
            DerivationSet::empty()
        ));

        let ct_key = set.arenas.alloc_complex_type(ComplexTypeDefData {
            name: None,
            target_namespace: None,
            base_type: None,
            derivation_method: None,
            content: ComplexContentResult::Empty,
            open_content: None,
            attributes: Vec::new(),
            attribute_groups: Vec::new(),
            attribute_wildcard: None,
            mixed: false,
            is_abstract: false,
            final_derivation: DerivationSet::empty(),
            block: DerivationSet::empty(),
            default_attributes_apply: 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,
        });

        assert!(set.is_type_derived_from(
            TypeKey::Complex(ct_key),
            TypeKey::Complex(any_type),
            DerivationSet::empty()
        ));
    }

    #[test]
    fn test_is_type_derived_from_exclude_restriction() {
        let set = SchemaSet::new();
        let builtin = set.builtin_types();

        // With RESTRICTION excluded, xs:normalizedString does NOT derive from xs:string
        assert!(!set.is_type_derived_from(
            TypeKey::Simple(builtin.normalized_string),
            TypeKey::Simple(builtin.string),
            DerivationSet::RESTRICTION
        ));

        // Same type still derives from itself even with exclusions
        assert!(set.is_type_derived_from(
            TypeKey::Simple(builtin.string),
            TypeKey::Simple(builtin.string),
            DerivationSet::RESTRICTION
        ));
    }

    #[test]
    fn test_is_type_derived_from_list_types() {
        let set = SchemaSet::new();
        let builtin = set.builtin_types();

        // xs:NMTOKENS is a list type that derives from xs:anySimpleType
        assert!(set.is_type_derived_from(
            TypeKey::Simple(builtin.nmtokens),
            TypeKey::Simple(builtin.any_simple_type),
            DerivationSet::empty()
        ));

        // With LIST excluded, xs:NMTOKENS should not derive from xs:anySimpleType
        assert!(!set.is_type_derived_from(
            TypeKey::Simple(builtin.nmtokens),
            TypeKey::Simple(builtin.any_simple_type),
            DerivationSet::LIST
        ));
    }

    /// Clause 2.2.4: D is derived from union B if D is derived from a
    /// transitive member of B and B has no facets.
    #[test]
    fn test_union_member_derivation_clause_2_2_4() {
        use crate::pipeline::load_and_process_schema;

        let xsd = r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
            <xs:simpleType name="myUnion">
                <xs:union memberTypes="xs:float xs:integer"/>
            </xs:simpleType>
        </xs:schema>"#;

        let mut set = SchemaSet::new();
        load_and_process_schema(xsd.as_bytes(), "test.xsd", &mut set, None)
            .expect("schema should parse");

        let integer_key = TypeKey::Simple(set.builtin_types().integer);
        let float_key = TypeKey::Simple(set.builtin_types().float);

        // Find myUnion by name
        let union_name = set.name_table.add("myUnion");
        let union_key = set
            .namespaces
            .get(&None)
            .unwrap()
            .types
            .get(&union_name)
            .copied()
            .expect("myUnion should exist");

        // xs:integer is a member of myUnion → should be "derived" via 2.2.4
        assert!(
            set.is_type_derived_from(integer_key, union_key, DerivationSet::empty()),
            "xs:integer should be derived from union(float, integer) via clause 2.2.4"
        );

        // xs:float is also a member
        assert!(
            set.is_type_derived_from(float_key, union_key, DerivationSet::empty()),
            "xs:float should be derived from union(float, integer) via clause 2.2.4"
        );

        // xs:string is NOT a member
        let string_key = TypeKey::Simple(set.builtin_types().string);
        assert!(
            !set.is_type_derived_from(string_key, union_key, DerivationSet::empty()),
            "xs:string should NOT be derived from union(float, integer)"
        );
    }

    /// Clause 2.2.4 with nested unions: D derived from a member of
    /// a union that is itself a member of B.
    #[test]
    fn test_union_member_derivation_transitive() {
        use crate::pipeline::load_and_process_schema;

        let xsd = r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
            <xs:simpleType name="innerUnion">
                <xs:union memberTypes="xs:boolean xs:date"/>
            </xs:simpleType>
            <xs:simpleType name="outerUnion">
                <xs:union memberTypes="xs:integer innerUnion"/>
            </xs:simpleType>
        </xs:schema>"#;

        let mut set = SchemaSet::new();
        load_and_process_schema(xsd.as_bytes(), "test.xsd", &mut set, None)
            .expect("schema should parse");

        let outer_name = set.name_table.add("outerUnion");
        let outer_key = set
            .namespaces
            .get(&None)
            .unwrap()
            .types
            .get(&outer_name)
            .copied()
            .expect("outerUnion should exist");

        // xs:boolean is in innerUnion which is in outerUnion → transitive
        let bool_key = TypeKey::Simple(set.builtin_types().boolean);
        assert!(
            set.is_type_derived_from(bool_key, outer_key, DerivationSet::empty()),
            "xs:boolean should be transitively derived from outerUnion via innerUnion"
        );

        // xs:integer is a direct member
        let int_key = TypeKey::Simple(set.builtin_types().integer);
        assert!(
            set.is_type_derived_from(int_key, outer_key, DerivationSet::empty()),
            "xs:integer should be derived from outerUnion as direct member"
        );
    }
}