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
//! Main XSD parser event loop
//!
//! This module provides the main parser that processes XSD documents using
//! a frame-based state machine. Each XSD element type is handled by a
//! corresponding frame that validates structure and collects content.
//!
//! # Architecture
//!
//! The parser uses:
//! - `TrackedReader` for XML parsing with byte position tracking
//! - `NamespaceContext` for scoped namespace management
//! - Frame stack for nested element handling
//! - `create_frame` factory for frame instantiation
//!
//! # Example
//!
//! ```
//! use xsd_schema::parser::parse::parse_schema;
//! use xsd_schema::SchemaSet;
//!
//! let mut schema_set = SchemaSet::new();
//! let xsd = r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
//!     <xs:element name="root" type="xs:string"/>
//! </xs:schema>"#;
//!
//! let doc_id = parse_schema(xsd.as_bytes(), "test.xsd", &mut schema_set)
//!     .expect("parse failed");
//! assert_eq!(doc_id, 0);
//! ```

use std::collections::HashSet;

use quick_xml::events::Event;

use crate::error::{SchemaError, SchemaResult};
use crate::ids::{DocumentId, NameId};
use crate::namespace::{is_ncname, NameTable, NamespaceContext, XS_NAMESPACE};
use crate::parser::assemble::assemble_schema;
use crate::parser::attrs::{categorize_attributes, parse_attributes, AttributeMap};
use crate::parser::frames::{
    create_frame, create_frame_recovering, xsd_names, Frame, FrameResult, SchemaFrameResult,
    SkipFrame,
};
use crate::parser::location::{SourceLocation, SourceMap, SourceRef, SourceSpan};
use crate::parser::reader::{split_qname, TrackedReader};
use crate::parser::structure::{
    validate_attribute_group_structure, validate_attribute_structure,
    validate_complex_type_structure, validate_element_structure, validate_extension_structure,
    validate_group_structure, validate_import_structure, validate_include_structure,
    validate_key_unique_structure, validate_keyref_structure, validate_notation_structure,
    validate_redefine_structure, validate_schema_structure, validate_simple_type_structure,
    validate_xsd_version_attribute, validate_xsd_version_element, ValidationContext,
};
use crate::schema::annotation::ForeignAttribute;
use crate::schema::model::XsdVersion;
use crate::SchemaSet;

/// Parser configuration options
#[derive(Debug, Clone)]
pub struct ParserConfig {
    /// Whether to recover from errors and continue parsing
    pub error_recovery: bool,
    /// Whether to collect foreign attributes
    pub collect_foreign_attributes: bool,
    /// Maximum nesting depth (0 = unlimited)
    pub max_depth: usize,
    /// XSD version mode (1.0 or 1.1).
    /// Derived from `SchemaSet.xsd_version` in `parse_schema_with_config`.
    pub(crate) xsd_version: XsdVersion,
}

impl Default for ParserConfig {
    fn default() -> Self {
        Self {
            error_recovery: true,
            collect_foreign_attributes: true,
            max_depth: 0,
            xsd_version: XsdVersion::V1_0,
        }
    }
}

/// Parser state during schema parsing
struct ParserState<'a, 'b, 'c> {
    /// Namespace context for prefix resolution
    ns_context: NamespaceContext<'a>,
    /// Stack of parser frames
    frame_stack: Vec<Box<dyn Frame>>,
    /// Current document ID
    doc_id: DocumentId,
    /// Errors collected during parsing
    errors: Vec<SchemaError>,
    /// Parser configuration
    config: &'b ParserConfig,
    /// XSD namespace ID (cached)
    xsd_ns_id: Option<NameId>,
    /// Source map for location resolution
    source_map: &'c SourceMap,
    /// Completed root schema result (set when root frame finishes)
    root_schema: Option<SchemaFrameResult>,
    /// Collected xs:ID values for document-level uniqueness checking
    id_values: HashSet<String>,
    /// True when the root xs:schema element has a vc: version condition that
    /// excludes this document; all children of xs:schema are then skipped.
    vc_schema_excluded: bool,
    /// Chameleon namespace to adopt (§4.2.3 clause 2.3) when this document
    /// is being included by a schema with a target namespace and itself has
    /// neither a `targetNamespace` attribute nor an explicit `xmlns` default.
    /// Applied to the root `<xs:schema>` scope so that unqualified QName
    /// references inside the included document resolve to the includer's
    /// target namespace (matching how top-level definitions are re-namespaced).
    chameleon_namespace: Option<NameId>,
}

impl<'a, 'b, 'c> ParserState<'a, 'b, 'c> {
    fn new(
        name_table: &'a mut NameTable,
        doc_id: DocumentId,
        config: &'b ParserConfig,
        source_map: &'c SourceMap,
        chameleon_namespace: Option<NameId>,
    ) -> Self {
        let ns_context = NamespaceContext::new(name_table);
        Self {
            ns_context,
            frame_stack: Vec::new(),
            doc_id,
            errors: Vec::new(),
            config,
            xsd_ns_id: None,
            source_map,
            root_schema: None,
            id_values: HashSet::new(),
            vc_schema_excluded: false,
            chameleon_namespace,
        }
    }

    /// Get the XSD namespace ID, caching it for efficiency
    fn get_xsd_ns_id(&mut self) -> Option<NameId> {
        if self.xsd_ns_id.is_none() {
            self.xsd_ns_id = self.ns_context.name_table().get(XS_NAMESPACE);
        }
        self.xsd_ns_id
    }

    /// Check if a namespace URI is the XSD namespace
    fn is_in_xsd_namespace(&mut self, namespace: Option<NameId>) -> bool {
        match (namespace, self.get_xsd_ns_id()) {
            (Some(ns), Some(xsd_ns)) => ns == xsd_ns,
            (None, _) => false, // Unqualified elements are not XSD elements
            _ => false,
        }
    }

    /// Push a namespace scope
    fn push_scope(&mut self) {
        self.ns_context.push_scope();
    }

    /// Pop a namespace scope
    fn pop_scope(&mut self) {
        self.ns_context.pop_scope();
    }

    /// Get current frame
    fn current_frame(&self) -> Option<&dyn Frame> {
        self.frame_stack.last().map(|b| b.as_ref())
    }

    /// Get current frame mutably
    fn current_frame_mut(&mut self) -> Option<&mut Box<dyn Frame>> {
        self.frame_stack.last_mut()
    }

    /// Add an error
    fn add_error(&mut self, error: SchemaError) {
        self.errors.push(error);
    }

    /// In error-recovery mode, collect the error and continue; otherwise fail.
    fn recover_or_fail(&mut self, error: SchemaError) -> SchemaResult<()> {
        if self.config.error_recovery {
            self.add_error(error);
            Ok(())
        } else {
            Err(error)
        }
    }

    /// Create a source reference for the given span
    fn source_ref(&self, span: SourceSpan) -> SourceRef {
        SourceRef::new(self.doc_id, span)
    }

    /// Create validation context for structural checks.
    /// Elements are top-level if their parent frame reports `children_are_top_level`
    /// (schema, redefine, and override frames).
    fn validation_context(&self, source: Option<SourceRef>) -> ValidationContext {
        let is_top_level = self
            .frame_stack
            .last()
            .map(|f| f.children_are_top_level())
            .unwrap_or(false);
        // Walk the frame stack to detect a `<complexType>` lexical ancestor.
        // Stop walking when we hit a frame whose children are top-level
        // (schema/redefine/override) — there's nothing more to look at.
        let inside_complex_type = self
            .frame_stack
            .iter()
            .rev()
            .any(|f| f.children_inside_complex_type());
        ValidationContext {
            xsd_version: self.config.xsd_version,
            is_top_level,
            inside_complex_type,
            source,
        }
    }
}

/// Parse an XSD schema document
///
/// This is the main entry point for parsing XSD documents.
///
/// # Arguments
///
/// * `xml` - Raw XML bytes of the schema document
/// * `base_uri` - Base URI for this document (for error messages and include resolution)
/// * `schema_set` - Schema set to add the parsed document to
///
/// # Returns
///
/// The document ID of the parsed schema, or an error if parsing failed.
pub fn parse_schema(
    xml: &[u8],
    base_uri: &str,
    schema_set: &mut SchemaSet,
) -> SchemaResult<DocumentId> {
    let config = ParserConfig::default();
    parse_schema_with_config(xml, base_uri, schema_set, &config)
}

/// Parse an XSD schema document with custom configuration.
///
/// The XSD version is always derived from `schema_set.xsd_version`,
/// regardless of what `config.xsd_version` contains.
pub fn parse_schema_with_config(
    xml: &[u8],
    base_uri: &str,
    schema_set: &mut SchemaSet,
    config: &ParserConfig,
) -> SchemaResult<DocumentId> {
    parse_schema_with_chameleon(xml, base_uri, schema_set, config, None)
}

/// Parse an XSD schema document with chameleon namespace support.
///
/// If `chameleon_namespace` is `Some` and the parsed document has no
/// `targetNamespace`, the chameleon namespace is adopted per §4.2.3
/// clause 2.3 (chameleon include pre-processing).
pub fn parse_schema_with_chameleon(
    xml: &[u8],
    base_uri: &str,
    schema_set: &mut SchemaSet,
    config: &ParserConfig,
    chameleon_namespace: Option<NameId>,
) -> SchemaResult<DocumentId> {
    // Override parser version from the single source of truth
    let mut config = config.clone();
    config.xsd_version = schema_set.xsd_version;

    // Create source map - keep local reference for location resolution during parsing
    let source_text = String::from_utf8_lossy(xml).into_owned();
    let source_map = SourceMap::new(base_uri.to_string(), source_text);

    // Pre-assign document ID (will be used when we add the source map later)
    let doc_id = schema_set.source_maps.len() as DocumentId;

    // Create parser state with reference to source_map
    let mut state = ParserState::new(
        &mut schema_set.name_table,
        doc_id,
        &config,
        &source_map,
        chameleon_namespace,
    );

    // Create XML reader
    let mut reader = TrackedReader::from_bytes(xml);
    let mut buf = Vec::new();

    // Track if we've seen the root schema element
    let mut seen_root = false;

    // Main event loop
    loop {
        buf.clear();
        let tracked_event = reader.read_event(&mut buf)?;
        let span = tracked_event.span;

        match tracked_event.event {
            Event::Start(ref e) => {
                handle_start_element(&mut state, e, span, &mut seen_root)?;
            }
            Event::Empty(ref e) => {
                // Empty elements are treated as Start + End
                handle_start_element(&mut state, e, span, &mut seen_root)?;
                handle_end_element(&mut state, span)?;
            }
            Event::End(_) => {
                handle_end_element(&mut state, span)?;
            }
            Event::Text(ref e) => {
                handle_text(&mut state, e, span)?;
            }
            Event::CData(ref e) => {
                handle_cdata(&mut state, e, span)?;
            }
            Event::Comment(_) => {
                // Ignore comments
            }
            Event::PI(_) => {
                // Ignore processing instructions
            }
            Event::Decl(_) => {
                // Ignore XML declaration
            }
            Event::DocType(_) => {
                // Ignore DOCTYPE
            }
            Event::Eof => break,
        }
    }

    // Check for incomplete parsing
    if !state.frame_stack.is_empty() {
        return Err(SchemaError::structural(
            "src-resolve",
            "Schema document ended with unclosed elements",
            None,
        ));
    }

    // Store any collected parsing errors on the schema set so they can be
    // surfaced later (e.g. when process_loaded_schemas runs).
    let parsing_errors = std::mem::take(&mut state.errors);

    let mut root_schema = state
        .root_schema
        .take()
        .ok_or_else(|| SchemaError::internal("No schema result produced during parsing"))?;
    drop(state);

    schema_set.parsing_errors.extend(parsing_errors);

    // Record the declared targetNamespace before chameleon adoption.
    let declared_target_namespace = root_schema.target_namespace;

    // src-include §4.2.3 clause 2.1: when included via `<xs:include>` from a
    // schema with a `targetNamespace`, the included document's declared
    // `targetNamespace`, when present, must equal the includer's.
    if let Some(includer_ns) = chameleon_namespace {
        if let Some(declared) = declared_target_namespace {
            if declared != includer_ns {
                return Err(SchemaError::structural(
                    "src-include",
                    format!(
                        "Included schema's targetNamespace '{}' does not match \
                         including schema's targetNamespace '{}'",
                        schema_set.name_table.resolve(declared),
                        schema_set.name_table.resolve(includer_ns),
                    ),
                    None,
                ));
            }
        }
    }

    // Chameleon pre-processing (§4.2.3 clause 2.3): if the parsed document
    // has no targetNamespace and the includer specifies one, adopt it.
    if root_schema.target_namespace.is_none() {
        if let Some(ns) = chameleon_namespace {
            root_schema.target_namespace = Some(ns);
        }
    }

    // Add the source map to storage now that parsing is complete
    // Note: We ensured doc_id matches the position where this will be added
    let added_id = schema_set.source_maps.add(source_map);
    debug_assert_eq!(doc_id, added_id, "Document ID mismatch");

    let mut doc = assemble_schema(schema_set, doc_id, base_uri, root_schema)?;
    doc.declared_target_namespace = declared_target_namespace;
    schema_set.documents.push(doc);

    Ok(doc_id)
}

/// Validate element-specific structural constraints
///
/// Dispatches to the appropriate validation function based on element name.
/// This enforces constraints like name/ref exclusivity, required attributes, etc.
fn validate_element_attributes(
    local_name: &str,
    attrs: &AttributeMap,
    name_table: &NameTable,
    ctx: &ValidationContext,
) -> SchemaResult<()> {
    match local_name {
        xsd_names::ELEMENT => validate_element_structure(attrs, name_table, ctx),
        xsd_names::ATTRIBUTE => validate_attribute_structure(attrs, name_table, ctx),
        xsd_names::SIMPLE_TYPE => validate_simple_type_structure(attrs, name_table, ctx),
        xsd_names::COMPLEX_TYPE => validate_complex_type_structure(attrs, name_table, ctx),
        xsd_names::GROUP => validate_group_structure(attrs, name_table, ctx),
        xsd_names::ATTRIBUTE_GROUP => validate_attribute_group_structure(attrs, name_table, ctx),
        xsd_names::NOTATION => validate_notation_structure(attrs, name_table, ctx),
        xsd_names::INCLUDE => validate_include_structure(attrs, name_table),
        xsd_names::IMPORT => validate_import_structure(attrs, name_table),
        xsd_names::REDEFINE => validate_redefine_structure(attrs, name_table),
        xsd_names::SCHEMA => validate_schema_structure(attrs, name_table),
        xsd_names::KEY | xsd_names::UNIQUE => validate_key_unique_structure(attrs, name_table),
        xsd_names::KEYREF => validate_keyref_structure(attrs, name_table),
        xsd_names::EXTENSION => validate_extension_structure(attrs, name_table),
        // Note: restriction and list/union validation requires child info (has_inline_type),
        // so they're validated at frame finish time, not here
        _ => Ok(()),
    }
}

fn intern_attribute_values(local_name: &str, attrs: &AttributeMap, name_table: &mut NameTable) {
    fn add_if_present(attrs: &AttributeMap, name_table: &mut NameTable, attr: &str) {
        if let Some(value) = attrs.get_value_by_name(name_table, attr) {
            name_table.add(value);
        }
    }

    match local_name {
        xsd_names::SCHEMA => {
            add_if_present(attrs, name_table, "targetNamespace");
            add_if_present(attrs, name_table, "defaultAttributes");
        }
        xsd_names::SIMPLE_TYPE | xsd_names::COMPLEX_TYPE => {
            add_if_present(attrs, name_table, "name");
        }
        xsd_names::ELEMENT | xsd_names::ATTRIBUTE => {
            add_if_present(attrs, name_table, "name");
            add_if_present(attrs, name_table, "targetNamespace");
        }
        xsd_names::GROUP | xsd_names::ATTRIBUTE_GROUP | xsd_names::NOTATION => {
            add_if_present(attrs, name_table, "name");
        }
        xsd_names::KEY | xsd_names::KEYREF | xsd_names::UNIQUE => {
            add_if_present(attrs, name_table, "name");
        }
        _ => {}
    }
}

/// Handle a start element event
fn handle_start_element(
    state: &mut ParserState,
    element: &quick_xml::events::BytesStart,
    span: SourceSpan,
    seen_root: &mut bool,
) -> SchemaResult<()> {
    // Push namespace scope for this element
    state.push_scope();

    // Parse element name
    let name = element.name();
    let name_bytes = name.as_ref();
    let (local_name_bytes, prefix_bytes) = split_qname(name_bytes);

    let local_name = std::str::from_utf8(local_name_bytes).map_err(|e| {
        SchemaError::xml(
            format!("Invalid UTF-8 in element name: {}", e),
            Some(state.source_ref(span).to_location(state.source_map)),
        )
    })?;

    // First, process namespace declarations from attributes
    for attr_result in element.attributes() {
        let attr =
            attr_result.map_err(|e| SchemaError::xml(format!("Attribute error: {}", e), None))?;

        let attr_name = attr.key.as_ref();
        let attr_value = attr
            .unescape_value()
            .map_err(|e| SchemaError::xml(format!("Attribute value error: {}", e), None))?;

        // Check for xmlns declarations
        if attr_name == b"xmlns" {
            // Default namespace
            state.ns_context.add_namespace("", &attr_value);
        } else if attr_name.starts_with(b"xmlns:") {
            // Prefixed namespace
            let prefix = std::str::from_utf8(&attr_name[6..]).unwrap_or("");
            state.ns_context.add_namespace(prefix, &attr_value);
        }
    }

    // Now resolve the element's namespace
    let element_ns = if let Some(prefix) = prefix_bytes {
        let prefix_str = std::str::from_utf8(prefix).unwrap_or("");
        state.ns_context.lookup_namespace(prefix_str)
    } else {
        state.ns_context.default_namespace()
    };

    // Check if this is the root schema element
    if !*seen_root {
        *seen_root = true;

        // Must be xs:schema
        if local_name != xsd_names::SCHEMA || !state.is_in_xsd_namespace(element_ns) {
            return Err(SchemaError::structural(
                "sch-props-correct",
                format!("Root element must be xs:schema, found '{}'", local_name),
                None,
            ));
        }
    }

    // Parse and categorize attributes
    let source_ref = Some(state.source_ref(span));
    let parsed_attrs = parse_attributes(
        element.attributes(),
        &mut state.ns_context,
        source_ref.clone(),
    )?;
    // sch-props-correct: attributes on XSD-namespace elements must be
    // unqualified — an explicit `xsd:`/`xs:` prefix on an XSD attribute
    // (e.g. `xsd:targetNamespace`) is not the same lexical attribute as the
    // unqualified one, and the schema-for-schemas content model only
    // declares the unqualified attribute. addB070a (test64756.xsd):
    // `<xsd:schema ... xsd:targetNamespace="http://foobar">` must be rejected.
    if state.is_in_xsd_namespace(element_ns) {
        let xsd_ns = state.get_xsd_ns_id();
        for attr in &parsed_attrs {
            if attr.prefix.is_some() && attr.namespace == xsd_ns {
                let attr_name = state.ns_context.name_table().resolve(attr.local_name);
                let location = attr
                    .source
                    .as_ref()
                    .map(|s| s.to_location(state.source_map));
                state.recover_or_fail(SchemaError::structural(
                    "sch-props-correct",
                    format!(
                        "XSD attribute '{}' on element '{}' must be unqualified, not in \
                         the XSD namespace",
                        attr_name, local_name,
                    ),
                    location,
                ))?;
            }
        }
    }
    let (xsd_attrs, foreign_attrs) =
        categorize_attributes(parsed_attrs, state.ns_context.name_table());
    let attr_map = AttributeMap::new(xsd_attrs);

    // Chameleon include (§4.2.3 clause 2.3): if this is the root `<xs:schema>`
    // of a document being chameleon-included and the document declares neither
    // its own `targetNamespace` nor an explicit `xmlns` default, install the
    // includer's target namespace as the default for QName resolution. Unqualified
    // type/element/group/attribute references inside the document will then
    // resolve to the includer's namespace — matching the fact that top-level
    // definitions in the included schema are re-namespaced into the includer's
    // target namespace (see `parse_schema_with_chameleon` below).
    if state.frame_stack.is_empty()
        && local_name == xsd_names::SCHEMA
        && state.is_in_xsd_namespace(element_ns)
    {
        if let Some(chameleon_ns) = state.chameleon_namespace {
            let has_own_tns = attr_map
                .get_value_by_name(state.ns_context.name_table(), "targetNamespace")
                .is_some();
            let default_is_null = state.ns_context.default_namespace().is_none();
            if !has_own_tns && default_is_null {
                state
                    .ns_context
                    .set_default_namespace_id(Some(chameleon_ns));
            }
        }
    }

    // §F (XSD 1.1 Appendix F): conditional inclusion via vc:* attributes.
    let vc_excluded = if foreign_attrs.is_empty() {
        false
    } else {
        let ns_snapshot = state.ns_context.snapshot();
        should_skip_for_vc(
            &foreign_attrs,
            state.ns_context.name_table(),
            &ns_snapshot,
            state.config.xsd_version,
        )?
    };
    if state.frame_stack.is_empty() {
        if vc_excluded {
            state.vc_schema_excluded = true;
        }
    } else if vc_excluded || state.vc_schema_excluded {
        push_skip_frame(state, source_ref, foreign_attrs)?;
        return Ok(());
    }

    // Check if this is an XSD element (must do before borrowing frame)
    let is_in_xsd_ns = state.is_in_xsd_namespace(element_ns);

    // Check if current frame allows this child and handle skip frames
    let (allows_child, has_frame, in_skip_frame, accepts_foreign) = {
        if let Some(frame) = state.current_frame() {
            let mut allowed = frame.allows(local_name, state.ns_context.name_table());
            // Reject duplicate annotations: each XSD element allows at most one annotation
            if allowed && local_name == xsd_names::ANNOTATION && frame.has_annotation() {
                allowed = false;
            }
            (
                allowed,
                true,
                frame.is_skip_frame(),
                frame.accepts_foreign_children(),
            )
        } else {
            (true, false, false, false)
        }
    };

    if has_frame {
        // If we're inside a skip frame, absorb all children without creating new frames
        if in_skip_frame {
            // Just notify the skip frame (increments depth) and return
            if let Some(mut frame) = state.frame_stack.pop() {
                frame.on_child_start(local_name, state.ns_context.name_table());
                state.frame_stack.push(frame);
            }
            return Ok(());
        }

        // `xs:appinfo` / `xs:documentation` (and any frame opting into
        // `accepts_foreign_children`) treats its content as opaque XML —
        // including child elements that happen to be in the XSD namespace.
        // Without this gate a `<xs:complexType>` literal embedded in
        // documentation prose (addB194) would be parsed as a real
        // schema-level complexType and fail src-ct's "inline complexType
        // cannot have name" check.
        if accepts_foreign {
            push_skip_frame(state, source_ref, foreign_attrs)?;
            return Ok(());
        }

        if !is_in_xsd_ns {
            // Non-XSD child element. The schema-for-schemas content model
            // forbids foreign elements (sch-props-correct). Surface a
            // structural error and (in error recovery mode) skip the
            // subtree so subsequent valid content can still be parsed.
            let location = source_ref.as_ref().map(|s| s.to_location(state.source_map));
            state.recover_or_fail(SchemaError::structural(
                "sch-props-correct",
                format!(
                    "Foreign-namespace element '{}' is not allowed here",
                    local_name
                ),
                location,
            ))?;
            push_skip_frame(state, source_ref, foreign_attrs)?;
            return Ok(());
        }

        if !allows_child {
            if state.config.error_recovery {
                // Push a skip frame for error recovery
                state.add_error(SchemaError::structural(
                    "sch-props-correct",
                    format!("Unexpected element '{}' in current context", local_name),
                    None,
                ));
                push_skip_frame(state, source_ref, foreign_attrs)?;
                return Ok(());
            } else {
                return Err(SchemaError::structural(
                    "sch-props-correct",
                    format!("Unexpected element '{}' in current context", local_name),
                    None,
                ));
            }
        }

        // Notify current frame about child start
        // Pop the frame, call method, push it back to avoid borrow issues
        if let Some(mut frame) = state.frame_stack.pop() {
            frame.on_child_start(local_name, state.ns_context.name_table());
            state.frame_stack.push(frame);
        }
    }

    // Validate XSD version compatibility
    let validation_ctx = state.validation_context(source_ref.clone());
    if let Err(e) = validate_xsd_version_element(local_name, &validation_ctx) {
        if state.config.error_recovery {
            state.add_error(e);
            push_skip_frame(state, source_ref, foreign_attrs)?;
            return Ok(());
        } else {
            return Err(e);
        }
    }

    // Perform element-specific structural validation
    if let Err(e) = validate_element_attributes(
        local_name,
        &attr_map,
        state.ns_context.name_table(),
        &validation_ctx,
    ) {
        state.recover_or_fail(e)?;
    }

    // §3.13.2 / xs:annotation: xml:lang on documentation/appinfo, when present,
    // must be a valid xs:language value. Empty / whitespace-only values are
    // rejected by the language regex.
    if matches!(local_name, xsd_names::DOCUMENTATION | xsd_names::APPINFO) {
        let xml_ns = state
            .ns_context
            .name_table()
            .get(crate::namespace::XML_NAMESPACE);
        let lang_local = state.ns_context.name_table().get("lang");
        if let (Some(xml_ns), Some(lang_local)) = (xml_ns, lang_local) {
            for fa in &foreign_attrs {
                if fa.namespace == Some(xml_ns)
                    && fa.local_name == lang_local
                    && !crate::types::validators::is_valid_language(
                        &crate::types::facets::normalize_whitespace(
                            &fa.value,
                            crate::types::facets::WhitespaceMode::Collapse,
                        ),
                    )
                {
                    state.recover_or_fail(SchemaError::structural(
                        "s4s-att-invalid-value",
                        format!(
                            "'{}' xml:lang value '{}' is not a valid xs:language",
                            local_name, fa.value
                        ),
                        source_ref.as_ref().map(|s| s.to_location(state.source_map)),
                    ))?;
                }
            }
        }
    }

    // Validate XSD version for individual attributes
    if is_in_xsd_ns {
        for attr_name_id in attr_map.names() {
            let attr_name = state.ns_context.name_table().resolve(attr_name_id);
            if let Err(e) = validate_xsd_version_attribute(&attr_name, local_name, &validation_ctx)
            {
                state.recover_or_fail(e)?;
            }
        }
    }

    // Validate xs:ID attribute (NCName format + document-level uniqueness).
    // Skip xs:appinfo and xs:documentation — they don't define `id` in the XSD spec.
    if !matches!(local_name, xsd_names::APPINFO | xsd_names::DOCUMENTATION) {
        if let Some(id_val) = attr_map.get_value_by_name(state.ns_context.name_table(), "id") {
            if !is_ncname(id_val) {
                state.recover_or_fail(SchemaError::structural(
                    "s4s-att-invalid-value",
                    format!(
                        "'{}' attribute 'id' has invalid value '{}': not a valid xs:ID",
                        local_name, id_val
                    ),
                    source_ref.as_ref().map(|s| s.to_location(state.source_map)),
                ))?;
            } else if !state.id_values.insert(id_val.to_string()) {
                state.recover_or_fail(SchemaError::structural(
                    "s4s-att-invalid-value",
                    format!(
                        "Duplicate xs:ID value '{}' on element '{}'",
                        id_val, local_name
                    ),
                    source_ref.as_ref().map(|s| s.to_location(state.source_map)),
                ))?;
            }
        }
    }

    // Intern attribute values that are represented as NameId in frame results
    if is_in_xsd_ns {
        intern_attribute_values(local_name, &attr_map, state.ns_context.name_table_mut());
    }

    // Create namespace snapshot for QName resolution during frame construction
    let ns_snapshot = state.ns_context.snapshot();

    // Create the new frame
    let frame = if state.config.error_recovery {
        let mut frame = create_frame_recovering(
            local_name,
            &attr_map,
            state.ns_context.name_table(),
            source_ref.clone(),
            &ns_snapshot,
            &mut state.errors,
        );
        frame.set_foreign_attributes(foreign_attrs);
        // Set namespace context for annotation content frames
        if matches!(local_name, xsd_names::APPINFO | xsd_names::DOCUMENTATION) {
            frame.set_namespaces(ns_snapshot.clone());
        }
        frame
    } else {
        let mut frame = create_frame(
            local_name,
            &attr_map,
            state.ns_context.name_table(),
            source_ref.clone(),
            &ns_snapshot,
        )?;
        frame.set_foreign_attributes(foreign_attrs);
        // Set namespace context for annotation content frames
        if matches!(local_name, xsd_names::APPINFO | xsd_names::DOCUMENTATION) {
            frame.set_namespaces(ns_snapshot.clone());
        }
        frame
    };

    // Push frame onto stack
    state.frame_stack.push(frame);

    Ok(())
}

/// Handle an end element event
fn handle_end_element(state: &mut ParserState, _span: SourceSpan) -> SchemaResult<()> {
    // Check if current frame is a skip frame with pending depth
    {
        if let Some(mut frame) = state.frame_stack.pop() {
            if frame.is_skip_frame() {
                // Call on_child_end to decrement depth
                // Returns true if this is the final end element for the skipped element
                if !frame.on_child_end() {
                    // Still inside nested children, put frame back and just pop scope
                    state.frame_stack.push(frame);
                    state.pop_scope();
                    return Ok(());
                }
            }
            // Put frame back for normal processing
            state.frame_stack.push(frame);
        }
    }

    // Pop the current frame and get its result
    let frame = match state.frame_stack.pop() {
        Some(f) => f,
        None => {
            return Err(SchemaError::internal("End element with no frame on stack"));
        }
    };

    // Save source ref before finish() consumes the frame
    let source_ref = frame.source().cloned();

    let result = match frame.finish() {
        Ok(r) => r,
        Err(e) => {
            // Add source location to error if available
            let e = if let Some(ref src) = source_ref {
                e.with_location(state.source_map.locate(src.span.start))
            } else {
                e
            };
            return Err(e);
        }
    };

    // Pop namespace scope
    state.pop_scope();

    // Attach result to parent frame. Errors from attach() (e.g. st-props-correct
    // duplicate facet from apply_facet) are attributed to the child frame's
    // source location — that is the offending element per §3.16.2.
    if let Some(parent) = state.current_frame_mut() {
        if let Err(e) = parent.attach(result) {
            let e = if let Some(ref src) = source_ref {
                e.with_location(state.source_map.locate(src.span.start))
            } else {
                e
            };
            return Err(e);
        }
    }
    // If no parent, store the root schema result
    else if let FrameResult::Schema(schema_result) = result {
        state.root_schema = Some(schema_result);
    } else {
        return Err(SchemaError::internal(
            "Root frame did not produce a schema result",
        ));
    }

    Ok(())
}

/// Handle a text event
fn handle_text(
    state: &mut ParserState,
    text: &quick_xml::events::BytesText,
    span: SourceSpan,
) -> SchemaResult<()> {
    let text_content = text
        .unescape()
        .map_err(|e| SchemaError::xml(format!("Text content error: {}", e), None))?;

    // Pass text to current frame if it accepts text content; otherwise reject
    // any non-whitespace text. XSD elements like xs:notation, xs:complexType,
    // xs:sequence, etc. only allow inter-element whitespace as text content
    // (sch-props-correct / element-specific content models).
    if let Some(mut frame) = state.frame_stack.pop() {
        if frame.accepts_text() {
            frame.on_text(&text_content);
        } else if !frame.is_skip_frame() && !text_content.trim().is_empty() {
            let source_ref = state.source_ref(span);
            state.frame_stack.push(frame);
            return state.recover_or_fail(SchemaError::structural(
                "sch-props-correct",
                "Non-whitespace text is not allowed here",
                Some(source_ref.to_location(state.source_map)),
            ));
        }
        state.frame_stack.push(frame);
    }

    Ok(())
}

/// Handle a CDATA section
fn handle_cdata(
    state: &mut ParserState,
    cdata: &quick_xml::events::BytesCData,
    span: SourceSpan,
) -> SchemaResult<()> {
    // CDATA is similar to text, typically in annotations
    if let Some(mut frame) = state.frame_stack.pop() {
        if frame.accepts_text() {
            // Convert CDATA to string
            if let Ok(cdata_str) = std::str::from_utf8(cdata.as_ref()) {
                frame.on_cdata(cdata_str);
            }
        } else if !frame.is_skip_frame() {
            // CDATA content is significant — even whitespace-only CDATA represents
            // intentional text. In an XSD element that doesn't allow text content,
            // this is invalid.
            let cdata_is_whitespace = std::str::from_utf8(cdata.as_ref())
                .map(|s| s.trim().is_empty())
                .unwrap_or(false);
            if !cdata_is_whitespace {
                let source_ref = state.source_ref(span);
                state.frame_stack.push(frame);
                return state.recover_or_fail(SchemaError::structural(
                    "sch-props-correct",
                    "Non-whitespace CDATA is not allowed here",
                    Some(source_ref.to_location(state.source_map)),
                ));
            }
        }
        state.frame_stack.push(frame);
    }
    Ok(())
}

/// XSD 1.1 Appendix F — conditional inclusion via vc:* version attributes.
///
/// Returns `Ok(true)` if the element should be excluded (skipped), `Ok(false)`
/// if it should be included. Returns `Err` if any vc:* version attribute has
/// an invalid decimal value (the schema is then structurally invalid).
fn should_skip_for_vc(
    foreign_attrs: &[ForeignAttribute],
    name_table: &NameTable,
    ns_snapshot: &crate::namespace::NamespaceContextSnapshot,
    xsd_version: XsdVersion,
) -> SchemaResult<bool> {
    const VC_NAMESPACE: &str = "http://www.w3.org/2007/XMLSchema-versioning";
    let Some(vc_ns_id) = name_table.get(VC_NAMESPACE) else {
        return Ok(false);
    };
    let current: f64 = match xsd_version {
        XsdVersion::V1_0 => 1.0,
        XsdVersion::V1_1 => 1.1,
    };
    for attr in foreign_attrs {
        if attr.namespace != Some(vc_ns_id) {
            continue;
        }
        let local = name_table.resolve_ref(attr.local_name);
        let include = match local {
            "minVersion" | "maxVersion" | "minVersionExclusive" | "maxVersionExclusive" => {
                let bound = match attr.value.trim().parse::<f64>() {
                    Ok(v) => v,
                    Err(_) => {
                        if xsd_version == XsdVersion::V1_1 {
                            return Err(err_versioning(format!(
                                "Invalid vc:{} value '{}': must be a valid xs:decimal",
                                local,
                                attr.value.trim()
                            )));
                        }
                        // XSD 1.0: vc: attributes are informational only; ignore invalid values
                        continue;
                    }
                };
                match local {
                    "minVersion" => current >= bound,
                    "maxVersion" => current <= bound,
                    "minVersionExclusive" => current > bound,
                    _ => current < bound,
                }
            }
            "typeAvailable" | "typeUnavailable" | "facetAvailable" | "facetUnavailable" => {
                // The W3C XMLSchema-versioning spec says vc: attributes "SHOULD
                // be honored" when recognized. Saxon honors them under both
                // XSD 1.0 and 1.1, and the suite tests (e.g. vc014 under
                // version="1.0 1.1") expect xs:error / XSD-1.1-only types to
                // be considered "unavailable" under XSD 1.0. Evaluate in both
                // modes so VC-driven branches are filtered correctly.
                let is_available_attr = matches!(local, "typeAvailable" | "facetAvailable");
                let is_type_check = matches!(local, "typeAvailable" | "typeUnavailable");
                let mut available_count = 0usize;
                let mut total_count = 0usize;
                for token in attr.value.split_whitespace() {
                    total_count += 1;
                    if vc_token_available(
                        token,
                        local,
                        is_type_check,
                        ns_snapshot,
                        name_table,
                        xsd_version,
                    )? {
                        available_count += 1;
                    }
                }
                if total_count == 0 {
                    continue;
                }
                // typeAvailable/facetAvailable: include iff ALL items available.
                // typeUnavailable/facetUnavailable: include iff ANY item is unavailable.
                if is_available_attr {
                    available_count == total_count
                } else {
                    available_count < total_count
                }
            }
            _ => continue,
        };
        if !include {
            return Ok(true);
        }
    }
    Ok(false)
}

fn err_versioning(msg: String) -> SchemaError {
    SchemaError::structural("src-versioning", msg, None)
}

/// Evaluate a single QName token in a vc:typeAvailable / facetAvailable list.
fn vc_token_available(
    token: &str,
    local: &str,
    is_type_check: bool,
    ns_snapshot: &crate::namespace::NamespaceContextSnapshot,
    name_table: &NameTable,
    xsd_version: XsdVersion,
) -> SchemaResult<bool> {
    use crate::namespace::is_ncname;
    let (prefix_str, local_str) = match token.find(':') {
        Some(pos) => (Some(&token[..pos]), &token[pos + 1..]),
        None => (None, token),
    };
    if !is_ncname(local_str) {
        return Err(err_versioning(format!(
            "Invalid QName '{}' in vc:{}: '{}' is not a valid NCName",
            token, local, local_str
        )));
    }
    let ns_id = match prefix_str {
        Some(p) => {
            if !is_ncname(p) {
                return Err(err_versioning(format!(
                    "Invalid QName '{}' in vc:{}: '{}' is not a valid NCName prefix",
                    token, local, p
                )));
            }
            let p_id = name_table.get(p).ok_or_else(|| {
                err_versioning(format!(
                    "Undeclared prefix '{}' in vc:{} value '{}'",
                    p, local, token
                ))
            })?;
            Some(ns_snapshot.resolve_prefix(p_id).ok_or_else(|| {
                err_versioning(format!(
                    "Undeclared prefix '{}' in vc:{} value '{}'",
                    p, local, token
                ))
            })?)
        }
        None => None,
    };
    if ns_id != Some(crate::namespace::well_known::XS_NAMESPACE) {
        return Ok(false);
    }
    Ok(if is_type_check {
        vc_is_xs_type_available(local_str, xsd_version)
    } else {
        vc_is_xs_facet_available(local_str)
    })
}

fn vc_is_xs_type_available(local_name: &str, xsd_version: XsdVersion) -> bool {
    match crate::types::XmlTypeCode::from_local_name(local_name) {
        Some(code) => !code.is_xsd11() || xsd_version == XsdVersion::V1_1,
        None => false,
    }
}

fn vc_is_xs_facet_available(local_name: &str) -> bool {
    matches!(
        local_name,
        "minLength"
            | "maxLength"
            | "length"
            | "pattern"
            | "enumeration"
            | "whiteSpace"
            | "totalDigits"
            | "fractionDigits"
            | "minInclusive"
            | "maxInclusive"
            | "minExclusive"
            | "maxExclusive"
            | "assertion"
            | "explicitTimezone"
    )
}

/// Push a skip frame for error recovery
fn push_skip_frame(
    state: &mut ParserState,
    source: Option<SourceRef>,
    foreign_attrs: Vec<ForeignAttribute>,
) -> SchemaResult<()> {
    let mut frame: Box<dyn Frame> = Box::new(SkipFrame::new(source));
    frame.set_foreign_attributes(foreign_attrs);
    state.frame_stack.push(frame);
    Ok(())
}

/// Helper extension for SourceRef to convert to SourceLocation
trait SourceRefExt {
    fn to_location(&self, source_map: &SourceMap) -> SourceLocation;
}

impl SourceRefExt for SourceRef {
    fn to_location(&self, source_map: &SourceMap) -> SourceLocation {
        source_map.locate(self.span.start)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ids::TypeKey;
    use crate::schema::model::FormChoice;

    #[test]
    fn test_parse_minimal_schema() {
        let mut schema_set = SchemaSet::new();
        let xsd = r#"<?xml version="1.0" encoding="UTF-8"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
            </xs:schema>"#;

        let result = parse_schema(xsd.as_bytes(), "test.xsd", &mut schema_set);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_schema_with_element() {
        let mut schema_set = SchemaSet::new();
        let xsd = r#"<?xml version="1.0" encoding="UTF-8"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="root" type="xs:string"/>
            </xs:schema>"#;

        let result = parse_schema(xsd.as_bytes(), "test.xsd", &mut schema_set);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_schema_with_complex_type() {
        let mut schema_set = SchemaSet::new();
        let xsd = r#"<?xml version="1.0" encoding="UTF-8"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:complexType name="PersonType">
                    <xs:sequence>
                        <xs:element name="name" type="xs:string"/>
                        <xs:element name="age" type="xs:int"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:schema>"#;

        let result = parse_schema(xsd.as_bytes(), "test.xsd", &mut schema_set);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_schema_with_simple_type() {
        let mut schema_set = SchemaSet::new();
        let xsd = r#"<?xml version="1.0" encoding="UTF-8"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:simpleType name="StringList">
                    <xs:list itemType="xs:string"/>
                </xs:simpleType>
            </xs:schema>"#;

        let result = parse_schema(xsd.as_bytes(), "test.xsd", &mut schema_set);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_schema_with_target_namespace() {
        let mut schema_set = SchemaSet::new();
        let xsd = r#"<?xml version="1.0" encoding="UTF-8"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
                       targetNamespace="http://example.com/test">
            </xs:schema>"#;

        let result = parse_schema(xsd.as_bytes(), "test.xsd", &mut schema_set);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_schema_with_import() {
        let mut schema_set = SchemaSet::new();
        let xsd = r#"<?xml version="1.0" encoding="UTF-8"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:import namespace="http://www.w3.org/XML/1998/namespace"/>
            </xs:schema>"#;

        let result = parse_schema(xsd.as_bytes(), "test.xsd", &mut schema_set);
        assert!(result.is_ok());
    }

    #[cfg(feature = "xsd11")]
    #[test]
    fn test_parse_schema_assembles_arena_fields() {
        use crate::parser::frames::TypeFrameResult;
        use crate::schema::model::OpenContentMode;
        use crate::schema::wildcard::{NamespaceConstraint, ProcessContents};

        let mut schema_set = SchemaSet::xsd11();
        let xsd = r###"<?xml version="1.0" encoding="UTF-8"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
                       defaultAttributes="common">
                <xs:defaultOpenContent mode="suffix">
                    <xs:any namespace="##other" processContents="lax"/>
                </xs:defaultOpenContent>
                <xs:attributeGroup name="common">
                    <xs:attribute name="lang" type="xs:string"/>
                </xs:attributeGroup>
                <xs:element name="head1" type="xs:string"/>
                <xs:element name="head2" type="xs:string"/>
                <xs:element name="root" substitutionGroup="head1 head2">
                    <xs:complexType>
                        <xs:attribute name="code" type="xs:string"/>
                    </xs:complexType>
                </xs:element>
            </xs:schema>"###;

        let doc_id = parse_schema_with_config(
            xsd.as_bytes(),
            "test.xsd",
            &mut schema_set,
            &ParserConfig::default(),
        )
        .unwrap();

        let doc = &schema_set.documents[doc_id as usize];
        let default_attrs = doc.default_attributes.as_ref().expect("defaultAttributes");
        assert_eq!(
            schema_set.name_table.resolve(default_attrs.local_name),
            "common"
        );
        assert!(default_attrs.namespace_uri.is_none());

        let default_open = doc
            .default_open_content
            .as_ref()
            .expect("defaultOpenContent");
        assert_eq!(default_open.mode, OpenContentMode::Suffix);
        let wildcard = default_open.wildcard.as_ref().expect("wildcard");
        assert!(matches!(
            wildcard.namespace_constraint,
            NamespaceConstraint::Other
        ));
        assert_eq!(wildcard.process_contents, ProcessContents::Lax);

        let common_id = schema_set.name_table.get("common").unwrap();
        let group_key = schema_set
            .lookup_attribute_group(None, common_id)
            .expect("attributeGroup lookup");
        let group = schema_set.arenas.get_attribute_group(group_key).unwrap();
        assert_eq!(group.attributes.len(), 1);
        let lang_id = group.attributes[0].attribute.name.unwrap();
        assert_eq!(schema_set.name_table.resolve(lang_id), "lang");

        let root_id = schema_set.name_table.get("root").unwrap();
        let root_key = schema_set
            .lookup_element(None, root_id)
            .expect("element lookup");
        let root = schema_set.arenas.get_element(root_key).unwrap();
        assert_eq!(root.substitution_group.len(), 2);
        assert_eq!(
            schema_set
                .name_table
                .resolve(root.substitution_group[0].local_name),
            "head1"
        );
        assert_eq!(
            schema_set
                .name_table
                .resolve(root.substitution_group[1].local_name),
            "head2"
        );

        let inline = root.inline_type.as_ref().expect("inline type");
        match inline.as_ref() {
            TypeFrameResult::Complex(ct) => {
                assert_eq!(ct.attributes.len(), 1);
                let code_id = ct.attributes[0].attribute.name.unwrap();
                assert_eq!(schema_set.name_table.resolve(code_id), "code");
            }
            _ => panic!("expected inline complex type"),
        }
    }

    #[test]
    fn test_parse_invalid_root() {
        let mut schema_set = SchemaSet::new();
        let xsd = r#"<?xml version="1.0" encoding="UTF-8"?>
            <notSchema xmlns:xs="http://www.w3.org/2001/XMLSchema">
            </notSchema>"#;

        let result = parse_schema(xsd.as_bytes(), "test.xsd", &mut schema_set);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_form_choice() {
        assert_eq!(
            crate::parser::assemble::parse_form_choice(Some("qualified")),
            FormChoice::Qualified
        );
        assert_eq!(
            crate::parser::assemble::parse_form_choice(Some("unqualified")),
            FormChoice::Unqualified
        );
        assert_eq!(
            crate::parser::assemble::parse_form_choice(None),
            FormChoice::Unqualified
        );
    }

    #[test]
    fn test_parser_config_default() {
        let config = ParserConfig::default();
        assert!(config.error_recovery);
        assert!(config.collect_foreign_attributes);
        assert_eq!(config.max_depth, 0);
    }

    #[test]
    fn test_apply_schema_defaults_to_elements_and_types() {
        let mut schema_set = SchemaSet::new();
        let xsd = r#"<?xml version="1.0" encoding="UTF-8"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
                       blockDefault="extension"
                       finalDefault="restriction">
              <xs:element name="head" type="xs:string"/>
              <xs:complexType name="Base"/>
              <xs:simpleType name="Simple">
                <xs:restriction base="xs:string"/>
              </xs:simpleType>
            </xs:schema>"#;

        let result = parse_schema(xsd.as_bytes(), "test.xsd", &mut schema_set);
        assert!(result.is_ok());

        let name_id = schema_set.name_table.get("head").expect("name id for head");
        let ns_table = schema_set
            .namespaces
            .get(&None)
            .expect("default namespace table");
        let elem_key = ns_table.elements.get(&name_id).expect("element key");
        let elem = schema_set
            .arenas
            .elements
            .get(*elem_key)
            .expect("element data");
        assert!(elem.block.contains_extension());
        assert!(elem.final_derivation.contains_restriction());

        let base_id = schema_set.name_table.get("Base").expect("name id for Base");
        let base_key = ns_table.types.get(&base_id).expect("type key for Base");
        match base_key {
            TypeKey::Complex(key) => {
                let base = schema_set
                    .arenas
                    .complex_types
                    .get(*key)
                    .expect("complex type data");
                assert!(base.block.contains_extension());
                assert!(base.final_derivation.contains_restriction());
            }
            _ => panic!("expected complex type for Base"),
        }

        let simple_id = schema_set
            .name_table
            .get("Simple")
            .expect("name id for Simple");
        let simple_key = ns_table.types.get(&simple_id).expect("type key for Simple");
        match simple_key {
            TypeKey::Simple(key) => {
                let simple = schema_set
                    .arenas
                    .simple_types
                    .get(*key)
                    .expect("simple type data");
                assert!(simple.final_derivation.contains_restriction());
            }
            _ => panic!("expected simple type for Simple"),
        }
    }

    /// §3.3.1.2 / §3.4.1: `final=""` on an element/type is an explicit empty override —
    /// it must NOT be replaced by the document-level `finalDefault`. Only absent `final=`
    /// inherits `finalDefault`. This test verifies that the assembler correctly distinguishes
    /// the two cases (T22b fix).
    #[test]
    fn test_final_explicit_empty_overrides_final_default() {
        let mut schema_set = SchemaSet::new();
        let xsd = r#"<?xml version="1.0" encoding="UTF-8"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
                       finalDefault="restriction">
              <!-- final="" is explicit override: no derivation blocked, despite finalDefault -->
              <xs:element name="unlocked" type="xs:string" final=""/>
              <!-- absent final= inherits finalDefault="restriction" -->
              <xs:element name="inherited" type="xs:string"/>
              <xs:complexType name="UnlockedType" final=""/>
              <xs:complexType name="InheritedType"/>
              <xs:simpleType name="UnlockedSimple" final="">
                <xs:restriction base="xs:string"/>
              </xs:simpleType>
              <xs:simpleType name="InheritedSimple">
                <xs:restriction base="xs:string"/>
              </xs:simpleType>
            </xs:schema>"#;

        let result = parse_schema(xsd.as_bytes(), "test.xsd", &mut schema_set);
        assert!(result.is_ok());

        let ns_table = schema_set.namespaces.get(&None).expect("default namespace");

        // Element: final="" → empty (NOT restriction)
        let unlocked_id = schema_set.name_table.get("unlocked").expect("unlocked");
        let unlocked_key = ns_table.elements.get(&unlocked_id).expect("element key");
        let unlocked = schema_set
            .arenas
            .elements
            .get(*unlocked_key)
            .expect("element");
        assert!(
            unlocked.final_derivation.is_empty(),
            "final=\"\" must produce empty set, not inherit finalDefault"
        );

        // Element: absent final → restriction (from finalDefault)
        let inherited_id = schema_set.name_table.get("inherited").expect("inherited");
        let inherited_key = ns_table.elements.get(&inherited_id).expect("element key");
        let inherited = schema_set
            .arenas
            .elements
            .get(*inherited_key)
            .expect("element");
        assert!(
            inherited.final_derivation.contains_restriction(),
            "absent final= must inherit finalDefault=restriction"
        );

        // ComplexType: final="" → empty
        let ut_id = schema_set
            .name_table
            .get("UnlockedType")
            .expect("UnlockedType");
        let ut_key = ns_table.types.get(&ut_id).expect("type key");
        if let crate::ids::TypeKey::Complex(key) = ut_key {
            let ct = schema_set
                .arenas
                .complex_types
                .get(*key)
                .expect("complex type");
            assert!(
                ct.final_derivation.is_empty(),
                "complexType final=\"\" must not inherit finalDefault"
            );
        }

        // ComplexType: absent final → restriction
        let it_id = schema_set
            .name_table
            .get("InheritedType")
            .expect("InheritedType");
        let it_key = ns_table.types.get(&it_id).expect("type key");
        if let crate::ids::TypeKey::Complex(key) = it_key {
            let ct = schema_set
                .arenas
                .complex_types
                .get(*key)
                .expect("complex type");
            assert!(
                ct.final_derivation.contains_restriction(),
                "complexType absent final= must inherit finalDefault"
            );
        }

        // SimpleType: final="" → empty
        let us_id = schema_set
            .name_table
            .get("UnlockedSimple")
            .expect("UnlockedSimple");
        let us_key = ns_table.types.get(&us_id).expect("type key");
        if let crate::ids::TypeKey::Simple(key) = us_key {
            let st = schema_set
                .arenas
                .simple_types
                .get(*key)
                .expect("simple type");
            assert!(
                st.final_derivation.is_empty(),
                "simpleType final=\"\" must not inherit finalDefault"
            );
        }

        // SimpleType: absent final → restriction
        let is_id = schema_set
            .name_table
            .get("InheritedSimple")
            .expect("InheritedSimple");
        let is_key = ns_table.types.get(&is_id).expect("type key");
        if let crate::ids::TypeKey::Simple(key) = is_key {
            let st = schema_set
                .arenas
                .simple_types
                .get(*key)
                .expect("simple type");
            assert!(
                st.final_derivation.contains_restriction(),
                "simpleType absent final= must inherit finalDefault"
            );
        }
    }

    #[test]
    fn test_duplicate_id_detected() {
        let mut schema_set = SchemaSet::new();
        let xsd = r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
            <xs:element id="foo123" name="a" type="xs:string"/>
            <xs:element id="foo123" name="b" type="xs:string"/>
        </xs:schema>"#;
        let result = parse_schema(xsd.as_bytes(), "test.xsd", &mut schema_set);
        assert!(result.is_ok());
        assert!(schema_set
            .parsing_errors
            .iter()
            .any(|e| { e.to_string().contains("Duplicate xs:ID value 'foo123'") }));
    }

    #[test]
    fn test_unique_ids_valid() {
        let mut schema_set = SchemaSet::new();
        let xsd = r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
            <xs:element id="id1" name="a" type="xs:string"/>
            <xs:element id="id2" name="b" type="xs:string"/>
        </xs:schema>"#;
        let result = parse_schema(xsd.as_bytes(), "test.xsd", &mut schema_set);
        assert!(result.is_ok());
        assert!(schema_set.parsing_errors.is_empty());
    }

    #[test]
    fn test_invalid_id_format() {
        let mut schema_set = SchemaSet::new();
        let xsd = r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
            <xs:element id="123bad" name="a" type="xs:string"/>
        </xs:schema>"#;
        let result = parse_schema(xsd.as_bytes(), "test.xsd", &mut schema_set);
        assert!(result.is_ok());
        assert!(schema_set
            .parsing_errors
            .iter()
            .any(|e| { e.to_string().contains("not a valid xs:ID") }));
    }
}