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
//! Built-in type registry for XSD types
//!
//! This module provides the `BuiltinTypes` struct which contains pre-allocated
//! `SimpleTypeKey` references for all 50 built-in XSD simple types, plus
//! the built-in complex `xs:anyType`.
//!
//! ## Usage
//!
//! Built-in types are initialized when a `SchemaSet` is created and can be
//! accessed via `schema_set.builtin_types()`.
//!
//! ```rust
//! use xsd_schema::SchemaSet;
//!
//! let schema_set = SchemaSet::new();
//! let string_key = schema_set.builtin_types().string;
//! ```

use std::collections::HashMap;

use super::{BuiltInType, XmlTypeCode};
use crate::arenas::{ComplexTypeDefData, SimpleTypeDefData};
use crate::ids::{AttributeKey, ComplexTypeKey, NameId, SimpleTypeKey, TypeKey};
use crate::namespace::table::well_known;
use crate::parser::frames::{
    ComplexContentDefResult, ComplexContentResult, DerivationMethod, ParticleResult, ParticleTerm,
    ProcessContents, WildcardNamespace, WildcardResult,
};
use crate::schema::model::{SchemaSet, XsdVersion};

/// Well-known built-in type IDs for fast access.
///
/// This struct contains `SimpleTypeKey` references for all 50 built-in XSD
/// simple types. It is initialized when a `SchemaSet` is created.
///
/// Types are organized by category:
/// - Abstract types (anySimpleType, anyAtomicType)
/// - String types (string, normalizedString, token, etc.)
/// - Numeric types (boolean, decimal, float, double, integer hierarchy)
/// - Date/time types (duration, dateTime, date, time, gregorian types)
/// - Binary types (hexBinary, base64Binary)
/// - Other types (anyURI, QName, NOTATION)
/// - List types (NMTOKENS, IDREFS, ENTITIES)
#[derive(Debug, Clone)]
pub struct BuiltinTypes {
    // Complex types
    /// xs:anyType - the ur-type
    pub any_type: ComplexTypeKey,

    // Abstract types
    /// xs:anySimpleType - base of all simple types
    pub any_simple_type: SimpleTypeKey,
    /// xs:anyAtomicType - base of all atomic types (XSD 1.1)
    pub any_atomic_type: Option<SimpleTypeKey>,

    // String types
    /// xs:string
    pub string: SimpleTypeKey,
    /// xs:normalizedString
    pub normalized_string: SimpleTypeKey,
    /// xs:token
    pub token: SimpleTypeKey,
    /// xs:language
    pub language: SimpleTypeKey,
    /// xs:NMTOKEN
    pub nmtoken: SimpleTypeKey,
    /// xs:Name
    pub name: SimpleTypeKey,
    /// xs:NCName
    pub ncname: SimpleTypeKey,
    /// xs:ID
    pub id: SimpleTypeKey,
    /// xs:IDREF
    pub idref: SimpleTypeKey,
    /// xs:ENTITY
    pub entity: SimpleTypeKey,

    // Numeric types
    /// xs:boolean
    pub boolean: SimpleTypeKey,
    /// xs:decimal
    pub decimal: SimpleTypeKey,
    /// xs:float
    pub float: SimpleTypeKey,
    /// xs:double
    pub double: SimpleTypeKey,
    /// xs:integer
    pub integer: SimpleTypeKey,
    /// xs:nonPositiveInteger
    pub non_positive_integer: SimpleTypeKey,
    /// xs:negativeInteger
    pub negative_integer: SimpleTypeKey,
    /// xs:long
    pub long: SimpleTypeKey,
    /// xs:int
    pub int: SimpleTypeKey,
    /// xs:short
    pub short: SimpleTypeKey,
    /// xs:byte
    pub byte: SimpleTypeKey,
    /// xs:nonNegativeInteger
    pub non_negative_integer: SimpleTypeKey,
    /// xs:unsignedLong
    pub unsigned_long: SimpleTypeKey,
    /// xs:unsignedInt
    pub unsigned_int: SimpleTypeKey,
    /// xs:unsignedShort
    pub unsigned_short: SimpleTypeKey,
    /// xs:unsignedByte
    pub unsigned_byte: SimpleTypeKey,
    /// xs:positiveInteger
    pub positive_integer: SimpleTypeKey,

    // Date/time types
    /// xs:duration
    pub duration: SimpleTypeKey,
    /// xs:dateTime
    pub datetime: SimpleTypeKey,
    /// xs:time
    pub time: SimpleTypeKey,
    /// xs:date
    pub date: SimpleTypeKey,
    /// xs:gYearMonth
    pub g_year_month: SimpleTypeKey,
    /// xs:gYear
    pub g_year: SimpleTypeKey,
    /// xs:gMonthDay
    pub g_month_day: SimpleTypeKey,
    /// xs:gDay
    pub g_day: SimpleTypeKey,
    /// xs:gMonth
    pub g_month: SimpleTypeKey,

    // XSD 1.1 date/time additions
    /// xs:yearMonthDuration (XSD 1.1)
    pub year_month_duration: Option<SimpleTypeKey>,
    /// xs:dayTimeDuration (XSD 1.1)
    pub day_time_duration: Option<SimpleTypeKey>,
    /// xs:dateTimeStamp (XSD 1.1)
    pub datetime_stamp: Option<SimpleTypeKey>,
    /// xs:untypedAtomic (XSD 1.1)
    pub untyped_atomic: Option<SimpleTypeKey>,

    // XSD 1.1 bottom type
    /// xs:error - the bottom type (union of no members); has no valid values (XSD 1.1)
    pub error: Option<SimpleTypeKey>,

    // Binary types
    /// xs:hexBinary
    pub hex_binary: SimpleTypeKey,
    /// xs:base64Binary
    pub base64_binary: SimpleTypeKey,

    // URI types
    /// xs:anyURI
    pub any_uri: SimpleTypeKey,

    /// Anonymous `list(xs:anyURI)` — type of `xsi:schemaLocation` built-in attribute
    pub xsi_schema_location_type: SimpleTypeKey,

    // QName types
    /// xs:QName
    pub qname: SimpleTypeKey,
    /// xs:NOTATION
    pub notation: SimpleTypeKey,

    // List types (built-in)
    /// xs:NMTOKENS
    pub nmtokens: SimpleTypeKey,
    /// xs:IDREFS
    pub idrefs: SimpleTypeKey,
    /// xs:ENTITIES
    pub entities: SimpleTypeKey,

    // Lookup maps for fast access
    /// Map from XmlTypeCode to SimpleTypeKey
    by_type_code: HashMap<XmlTypeCode, SimpleTypeKey>,
    /// Reverse map from SimpleTypeKey to XmlTypeCode, so `get_type_code` is O(1).
    by_key: HashMap<SimpleTypeKey, XmlTypeCode>,
    /// Map from local name NameId to SimpleTypeKey (for XS namespace)
    by_local_name: HashMap<NameId, SimpleTypeKey>,

    // Built-in XSI attribute declarations (§3.2.7)
    /// `xsi:type` built-in attribute declaration
    pub xsi_type_attr: AttributeKey,
    /// `xsi:nil` built-in attribute declaration
    pub xsi_nil_attr: AttributeKey,
    /// `xsi:schemaLocation` built-in attribute declaration
    pub xsi_schema_location_attr: AttributeKey,
    /// `xsi:noNamespaceSchemaLocation` built-in attribute declaration
    pub xsi_no_namespace_schema_location_attr: AttributeKey,
}

impl BuiltinTypes {
    /// Initialize all built-in types and register them in the schema set.
    ///
    /// This creates `SimpleTypeDefData` entries in the arenas for all
    /// 47 XSD 1.0 built-in types (plus 3 additional XSD 1.1 types if
    /// the version is XSD 1.1).
    pub fn new(schema_set: &mut SchemaSet) -> Self {
        let xsd_version = schema_set.xsd_version;
        let xs_ns = Some(well_known::XS_NAMESPACE);

        let any_type_name = schema_set.name_table.add("anyType");
        let any_type = schema_set.arenas.alloc_complex_type(ComplexTypeDefData {
            name: Some(any_type_name),
            target_namespace: xs_ns,
            base_type: None,
            derivation_method: None,
            content: ComplexContentResult::Complex(ComplexContentDefResult {
                particle: Some(ParticleResult {
                    term: ParticleTerm::Any(WildcardResult {
                        namespace: WildcardNamespace::Any,
                        process_contents: ProcessContents::Lax,
                        not_namespace: Vec::new(),
                        not_qname: Vec::new(),
                        id: None,
                        annotation: None,
                        source: None,
                    }),
                    min_occurs: 0,
                    max_occurs: None,
                    source: None,
                }),
                derivation: DerivationMethod::Restriction,
                mixed: true,
                mixed_explicit: true,
                base_type: None,
                open_content: None,
                attributes: Vec::new(),
                attribute_groups: Vec::new(),
                attribute_wildcard: Some(WildcardResult {
                    namespace: WildcardNamespace::Any,
                    process_contents: ProcessContents::Lax,
                    not_namespace: Vec::new(),
                    not_qname: Vec::new(),
                    id: None,
                    annotation: None,
                    source: None,
                }),
                assertions: Vec::new(),
                id: None,
                derivation_id: None,
                source: None,
            }),
            open_content: None,
            attributes: Vec::new(),
            attribute_groups: Vec::new(),
            attribute_wildcard: None,
            mixed: true,
            is_abstract: false,
            final_derivation: crate::schema::model::DerivationSet::empty(),
            block: crate::schema::model::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 references (built-in types have no unresolved references)
            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,
        });

        // Helper to create and register a built-in type
        let mut create_type = |builtin: BuiltInType| -> SimpleTypeKey {
            let local_name = builtin.local_name();
            let name_id = schema_set.name_table.add(local_name);
            let variety = match builtin {
                BuiltInType::NMTOKENS | BuiltInType::IDREFS | BuiltInType::ENTITIES => {
                    crate::parser::frames::SimpleTypeVariety::List
                }
                BuiltInType::XsError => crate::parser::frames::SimpleTypeVariety::Union,
                _ => crate::parser::frames::SimpleTypeVariety::Atomic,
            };

            let data = SimpleTypeDefData {
                name: Some(name_id),
                target_namespace: xs_ns,
                variety,
                base_type: None,
                item_type: None,
                member_types: Vec::new(),
                facets: crate::types::simple::effective_arena_facets_for_builtin(builtin),
                final_derivation: crate::schema::model::DerivationSet::empty(),
                id: None,
                derivation_id: None,
                annotation: None,
                source: None,
                // Resolved references (built-in types have no unresolved references)
                resolved_base_type: None,
                resolved_item_type: None,
                resolved_member_types: Vec::new(),
                redefine_original: None,
                deferred_item_type_error: None,
            };

            schema_set.arenas.alloc_simple_type(data)
        };

        // Create all XSD 1.0 types
        let any_simple_type = create_type(BuiltInType::AnySimpleType);
        let string = create_type(BuiltInType::String);
        let normalized_string = create_type(BuiltInType::NormalizedString);
        let token = create_type(BuiltInType::Token);
        let language = create_type(BuiltInType::Language);
        let nmtoken = create_type(BuiltInType::NMTOKEN);
        let name = create_type(BuiltInType::Name);
        let ncname = create_type(BuiltInType::NCName);
        let id = create_type(BuiltInType::ID);
        let idref = create_type(BuiltInType::IDREF);
        let entity = create_type(BuiltInType::ENTITY);

        let boolean = create_type(BuiltInType::Boolean);
        let decimal = create_type(BuiltInType::Decimal);
        let float = create_type(BuiltInType::Float);
        let double = create_type(BuiltInType::Double);
        let integer = create_type(BuiltInType::Integer);
        let non_positive_integer = create_type(BuiltInType::NonPositiveInteger);
        let negative_integer = create_type(BuiltInType::NegativeInteger);
        let long = create_type(BuiltInType::Long);
        let int = create_type(BuiltInType::Int);
        let short = create_type(BuiltInType::Short);
        let byte = create_type(BuiltInType::Byte);
        let non_negative_integer = create_type(BuiltInType::NonNegativeInteger);
        let unsigned_long = create_type(BuiltInType::UnsignedLong);
        let unsigned_int = create_type(BuiltInType::UnsignedInt);
        let unsigned_short = create_type(BuiltInType::UnsignedShort);
        let unsigned_byte = create_type(BuiltInType::UnsignedByte);
        let positive_integer = create_type(BuiltInType::PositiveInteger);

        let duration = create_type(BuiltInType::Duration);
        let datetime = create_type(BuiltInType::DateTime);
        let time = create_type(BuiltInType::Time);
        let date = create_type(BuiltInType::Date);
        let g_year_month = create_type(BuiltInType::GYearMonth);
        let g_year = create_type(BuiltInType::GYear);
        let g_month_day = create_type(BuiltInType::GMonthDay);
        let g_day = create_type(BuiltInType::GDay);
        let g_month = create_type(BuiltInType::GMonth);

        let hex_binary = create_type(BuiltInType::HexBinary);
        let base64_binary = create_type(BuiltInType::Base64Binary);

        let any_uri = create_type(BuiltInType::AnyURI);
        let qname = create_type(BuiltInType::QName);
        let notation = create_type(BuiltInType::NOTATION);

        let nmtokens = create_type(BuiltInType::NMTOKENS);
        let idrefs = create_type(BuiltInType::IDREFS);
        let entities = create_type(BuiltInType::ENTITIES);

        // XSD 1.1 types (only if XSD 1.1 mode)
        let (
            any_atomic_type,
            untyped_atomic,
            year_month_duration,
            day_time_duration,
            datetime_stamp,
            error,
        ) = if xsd_version == XsdVersion::V1_1 {
            (
                Some(create_type(BuiltInType::AnyAtomicType)),
                Some(create_type(BuiltInType::UntypedAtomic)),
                Some(create_type(BuiltInType::YearMonthDuration)),
                Some(create_type(BuiltInType::DayTimeDuration)),
                Some(create_type(BuiltInType::DateTimeStamp)),
                Some(create_type(BuiltInType::XsError)),
            )
        } else {
            (None, None, None, None, None, None)
        };

        // Anonymous list(anyURI) for xsi:schemaLocation built-in attribute type.
        // Created after `create_type` closure is no longer needed.
        let xsi_schema_location_type = {
            let data = SimpleTypeDefData {
                name: None,
                target_namespace: None,
                variety: crate::parser::frames::SimpleTypeVariety::List,
                base_type: None,
                item_type: None,
                member_types: Vec::new(),
                facets: crate::types::facets::FacetSet::new(),
                final_derivation: crate::schema::model::DerivationSet::empty(),
                id: None,
                derivation_id: None,
                annotation: None,
                source: None,
                resolved_base_type: None,
                resolved_item_type: None,
                resolved_member_types: Vec::new(),
                redefine_original: None,
                deferred_item_type_error: None,
            };
            schema_set.arenas.alloc_simple_type(data)
        };

        // Build lookup maps
        let mut by_type_code = HashMap::new();
        let mut by_key = HashMap::new();
        let mut by_local_name = HashMap::new();

        // Helper to add to lookup maps
        let mut add_to_maps = |builtin: BuiltInType, key: SimpleTypeKey| {
            let type_code = builtin.type_code();
            by_type_code.insert(type_code, key);
            by_key.insert(key, type_code);

            let local_name = builtin.local_name();
            let name_id = schema_set.name_table.add(local_name);
            by_local_name.insert(name_id, key);
        };

        // Add all types to maps
        add_to_maps(BuiltInType::AnySimpleType, any_simple_type);
        add_to_maps(BuiltInType::String, string);
        add_to_maps(BuiltInType::NormalizedString, normalized_string);
        add_to_maps(BuiltInType::Token, token);
        add_to_maps(BuiltInType::Language, language);
        add_to_maps(BuiltInType::NMTOKEN, nmtoken);
        add_to_maps(BuiltInType::Name, name);
        add_to_maps(BuiltInType::NCName, ncname);
        add_to_maps(BuiltInType::ID, id);
        add_to_maps(BuiltInType::IDREF, idref);
        add_to_maps(BuiltInType::ENTITY, entity);
        add_to_maps(BuiltInType::Boolean, boolean);
        add_to_maps(BuiltInType::Decimal, decimal);
        add_to_maps(BuiltInType::Float, float);
        add_to_maps(BuiltInType::Double, double);
        add_to_maps(BuiltInType::Integer, integer);
        add_to_maps(BuiltInType::NonPositiveInteger, non_positive_integer);
        add_to_maps(BuiltInType::NegativeInteger, negative_integer);
        add_to_maps(BuiltInType::Long, long);
        add_to_maps(BuiltInType::Int, int);
        add_to_maps(BuiltInType::Short, short);
        add_to_maps(BuiltInType::Byte, byte);
        add_to_maps(BuiltInType::NonNegativeInteger, non_negative_integer);
        add_to_maps(BuiltInType::UnsignedLong, unsigned_long);
        add_to_maps(BuiltInType::UnsignedInt, unsigned_int);
        add_to_maps(BuiltInType::UnsignedShort, unsigned_short);
        add_to_maps(BuiltInType::UnsignedByte, unsigned_byte);
        add_to_maps(BuiltInType::PositiveInteger, positive_integer);
        add_to_maps(BuiltInType::Duration, duration);
        add_to_maps(BuiltInType::DateTime, datetime);
        add_to_maps(BuiltInType::Time, time);
        add_to_maps(BuiltInType::Date, date);
        add_to_maps(BuiltInType::GYearMonth, g_year_month);
        add_to_maps(BuiltInType::GYear, g_year);
        add_to_maps(BuiltInType::GMonthDay, g_month_day);
        add_to_maps(BuiltInType::GDay, g_day);
        add_to_maps(BuiltInType::GMonth, g_month);
        add_to_maps(BuiltInType::HexBinary, hex_binary);
        add_to_maps(BuiltInType::Base64Binary, base64_binary);
        add_to_maps(BuiltInType::AnyURI, any_uri);
        add_to_maps(BuiltInType::QName, qname);
        add_to_maps(BuiltInType::NOTATION, notation);
        add_to_maps(BuiltInType::NMTOKENS, nmtokens);
        add_to_maps(BuiltInType::IDREFS, idrefs);
        add_to_maps(BuiltInType::ENTITIES, entities);

        // Add XSD 1.1 types to maps
        if let Some(key) = any_atomic_type {
            add_to_maps(BuiltInType::AnyAtomicType, key);
        }
        if let Some(key) = untyped_atomic {
            add_to_maps(BuiltInType::UntypedAtomic, key);
        }
        if let Some(key) = year_month_duration {
            add_to_maps(BuiltInType::YearMonthDuration, key);
        }
        if let Some(key) = day_time_duration {
            add_to_maps(BuiltInType::DayTimeDuration, key);
        }
        if let Some(key) = datetime_stamp {
            add_to_maps(BuiltInType::DateTimeStamp, key);
        }
        if let Some(key) = error {
            add_to_maps(BuiltInType::XsError, key);
        }

        // Resolve item types for built-in list types so that
        // validate_list_type can validate each item individually.
        for (list_key, item_key) in [
            (nmtokens, nmtoken),
            (idrefs, idref),
            (entities, entity),
            (xsi_schema_location_type, any_uri),
        ] {
            if let Some(st) = schema_set.arenas.get_simple_type_mut(list_key) {
                st.resolved_item_type = Some(TypeKey::Simple(item_key));
            }
        }

        // Allocate built-in XSI attribute declarations (§3.2.7)
        let xsi_ns = Some(well_known::XSI_NAMESPACE);
        let xsi_type_attr = schema_set
            .arenas
            .alloc_attribute(crate::arenas::AttributeDeclData {
                name: Some(well_known::XSI_TYPE),
                target_namespace: xsi_ns,
                ref_name: None,
                type_ref: None,
                inline_type: None,
                default_value: None,
                fixed_value: None,
                use_kind: None,
                form: None,
                inheritable: false,
                id: None,
                annotation: None,
                source: None,
                resolved_type: Some(TypeKey::Simple(qname)),
                resolved_ref: None,
            });
        let xsi_nil_attr = schema_set
            .arenas
            .alloc_attribute(crate::arenas::AttributeDeclData {
                name: Some(well_known::XSI_NIL),
                target_namespace: xsi_ns,
                ref_name: None,
                type_ref: None,
                inline_type: None,
                default_value: None,
                fixed_value: None,
                use_kind: None,
                form: None,
                inheritable: false,
                id: None,
                annotation: None,
                source: None,
                resolved_type: Some(TypeKey::Simple(boolean)),
                resolved_ref: None,
            });
        let xsi_schema_location_attr =
            schema_set
                .arenas
                .alloc_attribute(crate::arenas::AttributeDeclData {
                    name: Some(well_known::XSI_SCHEMA_LOCATION),
                    target_namespace: xsi_ns,
                    ref_name: None,
                    type_ref: None,
                    inline_type: None,
                    default_value: None,
                    fixed_value: None,
                    use_kind: None,
                    form: None,
                    inheritable: false,
                    id: None,
                    annotation: None,
                    source: None,
                    resolved_type: Some(TypeKey::Simple(xsi_schema_location_type)),
                    resolved_ref: None,
                });
        let xsi_no_namespace_schema_location_attr =
            schema_set
                .arenas
                .alloc_attribute(crate::arenas::AttributeDeclData {
                    name: Some(well_known::XSI_NO_NAMESPACE_SCHEMA_LOCATION),
                    target_namespace: xsi_ns,
                    ref_name: None,
                    type_ref: None,
                    inline_type: None,
                    default_value: None,
                    fixed_value: None,
                    use_kind: None,
                    form: None,
                    inheritable: false,
                    id: None,
                    annotation: None,
                    source: None,
                    resolved_type: Some(TypeKey::Simple(any_uri)),
                    resolved_ref: None,
                });

        // Register XSI attribute declarations in the XSI namespace table
        // so that lookup_attribute(XSI_NAMESPACE, name) finds them.
        {
            let xsi_ns_table = schema_set.get_or_create_namespace(Some(well_known::XSI_NAMESPACE));
            xsi_ns_table
                .attributes
                .insert(well_known::XSI_TYPE, xsi_type_attr);
            xsi_ns_table
                .attributes
                .insert(well_known::XSI_NIL, xsi_nil_attr);
            xsi_ns_table
                .attributes
                .insert(well_known::XSI_SCHEMA_LOCATION, xsi_schema_location_attr);
            xsi_ns_table.attributes.insert(
                well_known::XSI_NO_NAMESPACE_SCHEMA_LOCATION,
                xsi_no_namespace_schema_location_attr,
            );
        }

        Self {
            any_type,
            any_simple_type,
            any_atomic_type,
            string,
            normalized_string,
            token,
            language,
            nmtoken,
            name,
            ncname,
            id,
            idref,
            entity,
            boolean,
            decimal,
            float,
            double,
            integer,
            non_positive_integer,
            negative_integer,
            long,
            int,
            short,
            byte,
            non_negative_integer,
            unsigned_long,
            unsigned_int,
            unsigned_short,
            unsigned_byte,
            positive_integer,
            duration,
            datetime,
            time,
            date,
            g_year_month,
            g_year,
            g_month_day,
            g_day,
            g_month,
            year_month_duration,
            day_time_duration,
            datetime_stamp,
            untyped_atomic,
            error,
            hex_binary,
            base64_binary,
            any_uri,
            xsi_schema_location_type,
            qname,
            notation,
            nmtokens,
            idrefs,
            entities,
            by_type_code,
            by_key,
            by_local_name,
            xsi_type_attr,
            xsi_nil_attr,
            xsi_schema_location_attr,
            xsi_no_namespace_schema_location_attr,
        }
    }

    /// Get a built-in type by its XmlTypeCode.
    ///
    /// Returns `None` for node types, AnyType, and other non-simple type codes.
    pub fn get_by_type_code(&self, code: XmlTypeCode) -> Option<SimpleTypeKey> {
        self.by_type_code.get(&code).copied()
    }

    /// Get a built-in type by its local name (within the XS namespace).
    ///
    /// The local name must be interned in the NameTable (passed as NameId).
    pub fn get_by_local_name(&self, name: NameId) -> Option<SimpleTypeKey> {
        self.by_local_name.get(&name).copied()
    }

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

    /// Check if a type key is a built-in type.
    pub fn is_builtin(&self, key: SimpleTypeKey) -> bool {
        self.get_type_code(key).is_some()
    }

    /// True when `key` is the `xs:anyAtomicType` built-in (XSD 1.1 only).
    #[inline]
    pub fn is_any_atomic_type(&self, key: SimpleTypeKey) -> bool {
        self.any_atomic_type == Some(key)
    }

    /// Get the base type for a built-in type (for derivation hierarchy).
    ///
    /// Returns the immediate base type in the XSD type hierarchy.
    /// Returns `None` for `anySimpleType` (the root of simple types).
    ///
    /// In XSD 1.1 mode, primitive atomic types derive from `xs:anyAtomicType`
    /// per §3.16.7.3; in XSD 1.0 they derive from `xs:anySimpleType`.
    pub fn get_base_type(&self, key: SimpleTypeKey) -> Option<SimpleTypeKey> {
        let code = self.get_type_code(key)?;
        let base_code = get_builtin_base_type(code)?;
        if base_code == XmlTypeCode::AnySimpleType
            && code.is_primitive_atomic()
            && self.any_atomic_type.is_some()
        {
            return self.any_atomic_type;
        }
        self.get_by_type_code(base_code)
    }

    /// Check if `derived` derives from `base` (transitively).
    ///
    /// Returns `true` if:
    /// - `derived == base`, or
    /// - `derived` has `base` somewhere in its derivation chain
    pub fn derives_from(&self, derived: SimpleTypeKey, base: SimpleTypeKey) -> bool {
        if derived == base {
            return true;
        }

        // Walk up the derivation chain
        let mut current = derived;
        while let Some(parent) = self.get_base_type(current) {
            if parent == base {
                return true;
            }
            current = parent;
        }

        false
    }

    /// Returns the number of registered built-in types.
    ///
    /// This is 47 for XSD 1.0, or 50+ for XSD 1.1.
    pub fn count(&self) -> usize {
        self.by_type_code.len()
    }
}

/// Get the base type code for a built-in type.
///
/// Returns the immediate parent in the XSD derivation hierarchy.
fn get_builtin_base_type(code: XmlTypeCode) -> Option<XmlTypeCode> {
    match code {
        // anySimpleType has no base (it's the root of simple types)
        XmlTypeCode::AnySimpleType => None,

        // anyAtomicType derives from anySimpleType
        XmlTypeCode::AnyAtomicType => Some(XmlTypeCode::AnySimpleType),

        // All primitives derive from anyAtomicType (conceptually)
        // But for XSD 1.0, they derive from anySimpleType
        XmlTypeCode::String
        | XmlTypeCode::Boolean
        | XmlTypeCode::Decimal
        | XmlTypeCode::Float
        | XmlTypeCode::Double
        | XmlTypeCode::Duration
        | XmlTypeCode::DateTime
        | XmlTypeCode::Time
        | XmlTypeCode::Date
        | XmlTypeCode::GYearMonth
        | XmlTypeCode::GYear
        | XmlTypeCode::GMonthDay
        | XmlTypeCode::GDay
        | XmlTypeCode::GMonth
        | XmlTypeCode::HexBinary
        | XmlTypeCode::Base64Binary
        | XmlTypeCode::AnyUri
        | XmlTypeCode::QName
        | XmlTypeCode::Notation => Some(XmlTypeCode::AnySimpleType),

        // String-derived types
        XmlTypeCode::NormalizedString => Some(XmlTypeCode::String),
        XmlTypeCode::Token => Some(XmlTypeCode::NormalizedString),
        XmlTypeCode::Language => Some(XmlTypeCode::Token),
        XmlTypeCode::NmToken => Some(XmlTypeCode::Token),
        XmlTypeCode::Name => Some(XmlTypeCode::Token),
        XmlTypeCode::NCName => Some(XmlTypeCode::Name),
        XmlTypeCode::Id => Some(XmlTypeCode::NCName),
        XmlTypeCode::IdRef => Some(XmlTypeCode::NCName),
        XmlTypeCode::Entity => Some(XmlTypeCode::NCName),

        // Decimal-derived types (integer hierarchy)
        XmlTypeCode::Integer => Some(XmlTypeCode::Decimal),
        XmlTypeCode::NonPositiveInteger => Some(XmlTypeCode::Integer),
        XmlTypeCode::NegativeInteger => Some(XmlTypeCode::NonPositiveInteger),
        XmlTypeCode::Long => Some(XmlTypeCode::Integer),
        XmlTypeCode::Int => Some(XmlTypeCode::Long),
        XmlTypeCode::Short => Some(XmlTypeCode::Int),
        XmlTypeCode::Byte => Some(XmlTypeCode::Short),
        XmlTypeCode::NonNegativeInteger => Some(XmlTypeCode::Integer),
        XmlTypeCode::UnsignedLong => Some(XmlTypeCode::NonNegativeInteger),
        XmlTypeCode::UnsignedInt => Some(XmlTypeCode::UnsignedLong),
        XmlTypeCode::UnsignedShort => Some(XmlTypeCode::UnsignedInt),
        XmlTypeCode::UnsignedByte => Some(XmlTypeCode::UnsignedShort),
        XmlTypeCode::PositiveInteger => Some(XmlTypeCode::NonNegativeInteger),

        // XSD 1.1 types
        XmlTypeCode::UntypedAtomic => Some(XmlTypeCode::AnyAtomicType),
        XmlTypeCode::YearMonthDuration => Some(XmlTypeCode::Duration),
        XmlTypeCode::DayTimeDuration => Some(XmlTypeCode::Duration),
        XmlTypeCode::DateTimeStamp => Some(XmlTypeCode::DateTime),
        // xs:error is a union with no members; formally derives from xs:anySimpleType
        XmlTypeCode::Error => Some(XmlTypeCode::AnySimpleType),

        // List types derive from anySimpleType
        XmlTypeCode::NmTokens | XmlTypeCode::IdRefs | XmlTypeCode::Entities => {
            Some(XmlTypeCode::AnySimpleType)
        }

        // Non-simple types have no base in this hierarchy
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_schema_set() -> SchemaSet {
        SchemaSet::new()
    }

    fn create_test_schema_set_v11() -> SchemaSet {
        SchemaSet::with_version(XsdVersion::V1_1)
    }

    #[test]
    fn test_builtin_types_creation() {
        let mut schema_set = create_test_schema_set();
        let builtin = BuiltinTypes::new(&mut schema_set);

        assert_eq!(builtin.count(), 45);
    }

    #[test]
    fn test_builtin_types_xsd11() {
        let mut schema_set = create_test_schema_set_v11();
        let builtin = BuiltinTypes::new(&mut schema_set);

        assert_eq!(builtin.count(), 51);

        // XSD 1.1 types should be present
        assert!(builtin.any_atomic_type.is_some());
        assert!(builtin.untyped_atomic.is_some());
        assert!(builtin.year_month_duration.is_some());
        assert!(builtin.day_time_duration.is_some());
        assert!(builtin.datetime_stamp.is_some());
    }

    #[test]
    fn test_builtin_types_xsd10_no_xsd11() {
        let mut schema_set = create_test_schema_set();
        let builtin = BuiltinTypes::new(&mut schema_set);

        // XSD 1.1 types should not be present in XSD 1.0 mode
        assert!(builtin.any_atomic_type.is_none());
        assert!(builtin.untyped_atomic.is_none());
        assert!(builtin.year_month_duration.is_none());
        assert!(builtin.day_time_duration.is_none());
        assert!(builtin.datetime_stamp.is_none());
    }

    #[test]
    fn test_get_by_type_code() {
        let mut schema_set = create_test_schema_set();
        let builtin = BuiltinTypes::new(&mut schema_set);

        assert_eq!(
            builtin.get_by_type_code(XmlTypeCode::String),
            Some(builtin.string)
        );
        assert_eq!(
            builtin.get_by_type_code(XmlTypeCode::Integer),
            Some(builtin.integer)
        );
        assert_eq!(
            builtin.get_by_type_code(XmlTypeCode::DateTime),
            Some(builtin.datetime)
        );
        assert_eq!(
            builtin.get_by_type_code(XmlTypeCode::AnySimpleType),
            Some(builtin.any_simple_type)
        );

        // Node types should not be found
        assert!(builtin.get_by_type_code(XmlTypeCode::Element).is_none());
        assert!(builtin.get_by_type_code(XmlTypeCode::AnyType).is_none());
    }

    #[test]
    fn test_get_by_local_name() {
        let mut schema_set = create_test_schema_set();
        let builtin = BuiltinTypes::new(&mut schema_set);

        let string_id = schema_set.name_table.add("string");
        assert_eq!(builtin.get_by_local_name(string_id), Some(builtin.string));

        let integer_id = schema_set.name_table.add("integer");
        assert_eq!(builtin.get_by_local_name(integer_id), Some(builtin.integer));

        let nonexistent_id = schema_set.name_table.add("nonExistent");
        assert!(builtin.get_by_local_name(nonexistent_id).is_none());
    }

    #[test]
    fn test_get_type_code() {
        let mut schema_set = create_test_schema_set();
        let builtin = BuiltinTypes::new(&mut schema_set);

        assert_eq!(
            builtin.get_type_code(builtin.string),
            Some(XmlTypeCode::String)
        );
        assert_eq!(
            builtin.get_type_code(builtin.integer),
            Some(XmlTypeCode::Integer)
        );
        assert_eq!(
            builtin.get_type_code(builtin.any_simple_type),
            Some(XmlTypeCode::AnySimpleType)
        );
    }

    #[test]
    fn test_is_builtin() {
        let mut schema_set = create_test_schema_set();
        let builtin = BuiltinTypes::new(&mut schema_set);

        assert!(builtin.is_builtin(builtin.string));
        assert!(builtin.is_builtin(builtin.integer));
        assert!(builtin.is_builtin(builtin.any_simple_type));

        // Create a non-builtin type
        let custom_type = schema_set.arenas.alloc_simple_type(SimpleTypeDefData {
            name: Some(NameId(999)),
            target_namespace: None,
            variety: crate::parser::frames::SimpleTypeVariety::Atomic,
            base_type: None,
            item_type: None,
            member_types: Vec::new(),
            facets: crate::types::facets::FacetSet::new(),
            final_derivation: crate::schema::model::DerivationSet::empty(),
            id: None,
            derivation_id: None,
            annotation: None,
            source: None,
            // Resolved references
            resolved_base_type: None,
            resolved_item_type: None,
            resolved_member_types: Vec::new(),
            redefine_original: None,
            deferred_item_type_error: None,
        });
        assert!(!builtin.is_builtin(custom_type));
    }

    #[test]
    fn test_derives_from_same() {
        let mut schema_set = create_test_schema_set();
        let builtin = BuiltinTypes::new(&mut schema_set);

        // A type derives from itself
        assert!(builtin.derives_from(builtin.string, builtin.string));
        assert!(builtin.derives_from(builtin.integer, builtin.integer));
    }

    #[test]
    fn test_derives_from_direct() {
        let mut schema_set = create_test_schema_set();
        let builtin = BuiltinTypes::new(&mut schema_set);

        // Direct derivation
        assert!(builtin.derives_from(builtin.normalized_string, builtin.string));
        assert!(builtin.derives_from(builtin.integer, builtin.decimal));
        assert!(builtin.derives_from(builtin.long, builtin.integer));
    }

    #[test]
    fn test_derives_from_transitive() {
        let mut schema_set = create_test_schema_set();
        let builtin = BuiltinTypes::new(&mut schema_set);

        // Transitive derivation: byte < short < int < long < integer < decimal
        assert!(builtin.derives_from(builtin.byte, builtin.decimal));
        assert!(builtin.derives_from(builtin.byte, builtin.integer));
        assert!(builtin.derives_from(builtin.byte, builtin.long));
        assert!(builtin.derives_from(builtin.int, builtin.decimal));

        // NCName < Name < token < normalizedString < string
        assert!(builtin.derives_from(builtin.ncname, builtin.string));
        assert!(builtin.derives_from(builtin.id, builtin.string));
    }

    #[test]
    fn test_derives_from_negative() {
        let mut schema_set = create_test_schema_set();
        let builtin = BuiltinTypes::new(&mut schema_set);

        // Not derived
        assert!(!builtin.derives_from(builtin.string, builtin.integer));
        assert!(!builtin.derives_from(builtin.decimal, builtin.integer)); // Reverse
        assert!(!builtin.derives_from(builtin.float, builtin.double));
    }

    #[test]
    fn test_derives_from_any_simple_type() {
        let mut schema_set = create_test_schema_set();
        let builtin = BuiltinTypes::new(&mut schema_set);

        // All simple types derive from anySimpleType
        assert!(builtin.derives_from(builtin.string, builtin.any_simple_type));
        assert!(builtin.derives_from(builtin.integer, builtin.any_simple_type));
        assert!(builtin.derives_from(builtin.byte, builtin.any_simple_type));
        assert!(builtin.derives_from(builtin.nmtokens, builtin.any_simple_type));
    }

    #[test]
    fn test_get_base_type() {
        let mut schema_set = create_test_schema_set();
        let builtin = BuiltinTypes::new(&mut schema_set);

        // anySimpleType has no base
        assert!(builtin.get_base_type(builtin.any_simple_type).is_none());

        // Primitives derive from anySimpleType
        assert_eq!(
            builtin.get_base_type(builtin.string),
            Some(builtin.any_simple_type)
        );

        // normalizedString derives from string
        assert_eq!(
            builtin.get_base_type(builtin.normalized_string),
            Some(builtin.string)
        );

        // integer derives from decimal
        assert_eq!(
            builtin.get_base_type(builtin.integer),
            Some(builtin.decimal)
        );
    }

    #[test]
    fn test_builtin_base_type_hierarchy() {
        // Test the get_builtin_base_type function directly
        assert_eq!(get_builtin_base_type(XmlTypeCode::AnySimpleType), None);
        assert_eq!(
            get_builtin_base_type(XmlTypeCode::String),
            Some(XmlTypeCode::AnySimpleType)
        );
        assert_eq!(
            get_builtin_base_type(XmlTypeCode::NormalizedString),
            Some(XmlTypeCode::String)
        );
        assert_eq!(
            get_builtin_base_type(XmlTypeCode::Token),
            Some(XmlTypeCode::NormalizedString)
        );
        assert_eq!(
            get_builtin_base_type(XmlTypeCode::NCName),
            Some(XmlTypeCode::Name)
        );
        assert_eq!(
            get_builtin_base_type(XmlTypeCode::Integer),
            Some(XmlTypeCode::Decimal)
        );
        assert_eq!(
            get_builtin_base_type(XmlTypeCode::Long),
            Some(XmlTypeCode::Integer)
        );
        assert_eq!(
            get_builtin_base_type(XmlTypeCode::Byte),
            Some(XmlTypeCode::Short)
        );
    }
}