fastxml 0.8.1

A fast, memory-efficient XML library with XPath and XSD validation support
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
//! XSD schema type definitions.

use std::collections::HashMap;
use std::sync::Arc;

use indexmap::IndexMap;

/// A namespace-qualified name for collision-free lookups.
///
/// Uses (namespace_uri, local_name) instead of "prefix:local_name"
/// to avoid non-deterministic prefix collisions when multiple namespaces
/// define types/elements with the same local name.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NsName {
    /// Namespace URI (empty string for no-namespace)
    pub namespace_uri: String,
    /// Local name
    pub local_name: String,
}

impl NsName {
    /// Creates a new NsName.
    pub fn new(namespace_uri: impl Into<String>, local_name: impl Into<String>) -> Self {
        Self {
            namespace_uri: namespace_uri.into(),
            local_name: local_name.into(),
        }
    }
}

/// Content model type for an element (used in caches).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ContentModelType {
    /// Sequence - all elements in order, each with their own min/max occurs
    #[default]
    Sequence,
    /// Choice - exactly one of the elements must be present
    Choice,
    /// All - all elements must be present, but in any order
    All,
    /// Empty - no child elements allowed
    Empty,
}

/// Pre-computed child element constraints for a type.
///
/// This struct caches the flattened inheritance chain for a complex type,
/// eliminating the need to traverse the inheritance hierarchy at validation time.
#[derive(Debug, Clone)]
pub struct FlattenedChildren {
    /// Child element constraints (name -> (min_occurs, max_occurs))
    pub constraints: HashMap<String, (u32, Option<u32>)>,
    /// Content model type
    pub content_model_type: ContentModelType,
    /// Ordered element names for sequence validation.
    /// Using Arc<[String]> to make cloning cheap (pointer copy instead of deep clone).
    pub ordered_elements: Arc<[String]>,
}

impl FlattenedChildren {
    /// Creates a new empty FlattenedChildren.
    pub fn new() -> Self {
        Self {
            constraints: HashMap::new(),
            content_model_type: ContentModelType::Empty,
            ordered_elements: Arc::from([]),
        }
    }

    /// Creates a FlattenedChildren with the given content model type.
    pub fn with_content_model(content_model_type: ContentModelType) -> Self {
        Self {
            constraints: HashMap::new(),
            content_model_type,
            ordered_elements: Arc::from([]),
        }
    }
}

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

/// A compiled XSD schema.
#[derive(Debug, Clone)]
pub struct CompiledSchema {
    /// Target namespace
    pub target_namespace: Option<String>,
    /// Element definitions
    pub elements: IndexMap<String, ElementDef>,
    /// Type definitions
    pub types: IndexMap<String, TypeDef>,
    /// Attribute definitions
    pub attributes: IndexMap<String, AttributeDef>,
    /// Imported schemas (namespace -> schema)
    pub imports: HashMap<String, CompiledSchema>,
    /// Substitution groups (head element name -> list of substitute element names)
    pub substitution_groups: HashMap<String, Vec<String>>,

    // === Namespace resolution ===
    /// Namespace URI to prefix mapping (uri -> prefix).
    /// Used to resolve element lookups when XML uses different prefix than schema.
    pub namespace_prefixes: HashMap<String, String>,

    // === Namespace-aware indices ===
    /// Prefix to namespace URI mapping (prefix -> uri).
    pub prefix_namespaces: HashMap<String, String>,

    /// Namespace-aware type children cache: (namespace_uri, local_name) -> FlattenedChildren.
    ///
    /// This is the primary cache for type children lookups. It uses namespace URIs
    /// instead of prefixes to avoid cross-namespace collisions.
    pub ns_type_children_cache: HashMap<NsName, Arc<FlattenedChildren>>,

    // === Performance optimization caches (legacy, prefix-based) ===
    /// Pre-computed flattened child elements per type (type_name -> `Arc<FlattenedChildren>`).
    ///
    /// This cache stores the inheritance-flattened child element constraints for each type,
    /// eliminating the need to traverse the type hierarchy at validation time.
    pub type_children_cache: HashMap<String, Arc<FlattenedChildren>>,

    /// Pre-computed transitive substitution groups (head -> all members).
    ///
    /// This cache stores all transitive members of each substitution group head,
    /// including indirect members (e.g., if A has member B, and B has member C,
    /// this stores [B, C] for A).
    pub transitive_substitution_groups: HashMap<String, Arc<Vec<String>>>,

    /// Reverse lookup: substitution group member -> head element.
    ///
    /// This allows O(1) lookup of which substitution group head an element belongs to.
    pub substitution_group_heads: HashMap<String, String>,
}

impl CompiledSchema {
    /// Creates a new empty schema.
    pub fn new() -> Self {
        Self {
            target_namespace: None,
            elements: IndexMap::new(),
            types: IndexMap::new(),
            attributes: IndexMap::new(),
            imports: HashMap::new(),
            substitution_groups: HashMap::new(),
            // Namespace resolution
            namespace_prefixes: HashMap::new(),
            prefix_namespaces: HashMap::new(),
            // Namespace-aware caches
            ns_type_children_cache: HashMap::new(),
            // Legacy prefix-based caches
            type_children_cache: HashMap::new(),
            transitive_substitution_groups: HashMap::new(),
            substitution_group_heads: HashMap::new(),
        }
    }

    /// Creates a schema with a target namespace.
    pub fn with_namespace(namespace: impl Into<String>) -> Self {
        Self {
            target_namespace: Some(namespace.into()),
            ..Self::new()
        }
    }

    /// Looks up an element definition by qualified name.
    ///
    /// This method tries multiple strategies:
    /// 1. Direct lookup with the full qname (e.g., "dem:ReliefFeature")
    /// 2. If qname has a prefix, extract local name and try:
    ///    a. The local name in imported schemas
    ///    b. The local name in the main elements map (for merged schemas)
    pub fn get_element(&self, qname: &str) -> Option<&ElementDef> {
        // Try with full qname first
        if let Some(elem) = self.elements.get(qname) {
            return Some(elem);
        }

        // If qname has a prefix, try the local name
        if let Some((_prefix, local)) = qname.split_once(':') {
            // Try imported schemas first
            for schema in self.imports.values() {
                if let Some(elem) = schema.elements.get(local) {
                    return Some(elem);
                }
            }
            // Also try local name in main map (for merged schemas)
            if let Some(elem) = self.elements.get(local) {
                return Some(elem);
            }
        }

        None
    }

    /// Looks up an element definition by namespace URI and local name.
    ///
    /// This method resolves the namespace URI to the prefix used in the schema,
    /// then constructs the qualified name and looks it up. This allows finding
    /// elements even when the XML uses a different prefix than the schema.
    ///
    /// Example: If schema uses `tran:Road` but XML uses `tr:Road` (same namespace),
    /// calling `get_element_by_ns("http://...transportation...", "Road")` will
    /// correctly find the element.
    pub fn get_element_by_ns(&self, namespace_uri: &str, local_name: &str) -> Option<&ElementDef> {
        // First, try to find the schema's prefix for this namespace URI
        if let Some(prefix) = self.namespace_prefixes.get(namespace_uri) {
            // Construct the qname using the schema's prefix
            let qname = if prefix.is_empty() {
                local_name.to_string()
            } else {
                format!("{}:{}", prefix, local_name)
            };
            if let Some(elem) = self.elements.get(&qname) {
                return Some(elem);
            }
        }

        // Try local name directly (for schemas without prefix)
        if let Some(elem) = self.elements.get(local_name) {
            return Some(elem);
        }

        // Try all elements with matching local name (brute force fallback)
        for (key, elem) in &self.elements {
            if let Some((_prefix, local)) = key.split_once(':') {
                if local == local_name {
                    return Some(elem);
                }
            }
        }

        None
    }

    /// Looks up a type definition by qualified name.
    ///
    /// This method tries multiple strategies:
    /// 1. Direct lookup with the full qname (e.g., "core:AbstractCityObjectType")
    /// 2. If qname has a prefix, extract local name and try:
    ///    a. The local name in imported schemas
    ///    b. The local name in the main types map (for merged schemas)
    pub fn get_type(&self, qname: &str) -> Option<&TypeDef> {
        // Try with full qname first
        if let Some(typ) = self.types.get(qname) {
            return Some(typ);
        }

        // If qname has a prefix, try the local name
        if let Some((_prefix, local)) = qname.split_once(':') {
            // Try imported schemas first
            for schema in self.imports.values() {
                if let Some(typ) = schema.types.get(local) {
                    return Some(typ);
                }
            }
            // Also try local name in main map (for merged schemas)
            if let Some(typ) = self.types.get(local) {
                return Some(typ);
            }
        }

        None
    }

    /// Resolves a prefixed type reference to a NsName using prefix_namespaces.
    ///
    /// "bldg:WallSurfaceType" → NsName("http://...building...", "WallSurfaceType")
    /// "WallSurfaceType" (no prefix) → NsName(target_namespace, "WallSurfaceType")
    pub fn resolve_type_ref_to_ns(&self, type_ref: &str) -> Option<NsName> {
        if let Some((prefix, local)) = type_ref.split_once(':') {
            let ns_uri = self.prefix_namespaces.get(prefix)?;
            Some(NsName::new(ns_uri.clone(), local))
        } else {
            // No prefix - use target namespace
            let ns = self.target_namespace.as_deref().unwrap_or("");
            Some(NsName::new(ns, type_ref))
        }
    }

    /// Looks up type children cache by namespace URI and local name.
    pub fn get_ns_type_children(
        &self,
        namespace_uri: &str,
        local_name: &str,
    ) -> Option<&Arc<FlattenedChildren>> {
        self.ns_type_children_cache
            .get(&NsName::new(namespace_uri, local_name))
    }

    /// Looks up a type by namespace URI and local name.
    pub fn get_type_by_ns(&self, namespace_uri: &str, local_name: &str) -> Option<&TypeDef> {
        // Use namespace_prefixes (uri → prefix) to construct the canonical key
        if let Some(prefix) = self.namespace_prefixes.get(namespace_uri) {
            let qname = if prefix.is_empty() {
                local_name.to_string()
            } else {
                format!("{}:{}", prefix, local_name)
            };
            if let Some(typ) = self.types.get(&qname) {
                return Some(typ);
            }
        }
        // Fallback: try local name
        self.types.get(local_name)
    }
}

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

/// An element definition.
#[derive(Debug, Clone)]
pub struct ElementDef {
    /// Element name
    pub name: String,
    /// Type reference (name of a type definition)
    pub type_ref: Option<String>,
    /// Inline type definition
    pub inline_type: Option<TypeDef>,
    /// Minimum occurrences
    pub min_occurs: u32,
    /// Maximum occurrences (None = unbounded)
    pub max_occurs: Option<u32>,
    /// Whether this element is abstract
    pub is_abstract: bool,
    /// Substitution group head
    pub substitution_group: Option<String>,
    /// Whether the element is nillable
    pub nillable: bool,
    /// Identity constraints (unique, key, keyref)
    pub constraints: Vec<CompiledConstraint>,
}

impl ElementDef {
    /// Creates a new element definition.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            type_ref: None,
            inline_type: None,
            min_occurs: 1,
            max_occurs: Some(1),
            is_abstract: false,
            substitution_group: None,
            nillable: false,
            constraints: Vec::new(),
        }
    }

    /// Sets the type reference.
    pub fn with_type(mut self, type_ref: impl Into<String>) -> Self {
        self.type_ref = Some(type_ref.into());
        self
    }

    /// Sets the occurrence bounds.
    pub fn with_occurs(mut self, min: u32, max: Option<u32>) -> Self {
        self.min_occurs = min;
        self.max_occurs = max;
        self
    }

    /// Makes this element optional (minOccurs=0).
    pub fn optional(mut self) -> Self {
        self.min_occurs = 0;
        self
    }

    /// Makes this element repeatable (maxOccurs=unbounded).
    pub fn unbounded(mut self) -> Self {
        self.max_occurs = None;
        self
    }
}

/// A type definition.
#[derive(Debug, Clone)]
pub enum TypeDef {
    /// Simple type (string, integer, etc.)
    Simple(SimpleType),
    /// Complex type (elements, attributes)
    Complex(ComplexType),
}

/// A simple type definition.
#[derive(Debug, Clone)]
pub struct SimpleType {
    /// Type name
    pub name: String,
    /// Base type (restriction or extension)
    pub base_type: Option<String>,
    /// Enumeration values
    pub enumeration: Vec<String>,
    /// Pattern restriction
    pub pattern: Option<String>,
    /// Min length restriction
    pub min_length: Option<u32>,
    /// Max length restriction
    pub max_length: Option<u32>,
    /// Minimum value (inclusive)
    pub min_inclusive: Option<String>,
    /// Maximum value (inclusive)
    pub max_inclusive: Option<String>,
}

impl SimpleType {
    /// Creates a new simple type.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            base_type: None,
            enumeration: Vec::new(),
            pattern: None,
            min_length: None,
            max_length: None,
            min_inclusive: None,
            max_inclusive: None,
        }
    }

    /// Creates a string type.
    pub fn string() -> Self {
        Self::new("string").with_base("xs:string")
    }

    /// Creates an integer type.
    pub fn integer() -> Self {
        Self::new("integer").with_base("xs:integer")
    }

    /// Sets the base type.
    pub fn with_base(mut self, base: impl Into<String>) -> Self {
        self.base_type = Some(base.into());
        self
    }
}

/// A complex type definition.
#[derive(Debug, Clone)]
pub struct ComplexType {
    /// Type name
    pub name: String,
    /// Base type (for extension or restriction)
    pub base_type: Option<String>,
    /// Content model
    pub content: ContentModel,
    /// Attribute definitions
    pub attributes: Vec<AttributeDef>,
    /// Whether this type is abstract
    pub is_abstract: bool,
    /// Whether content is mixed (text + elements)
    pub mixed: bool,
}

impl ComplexType {
    /// Creates a new complex type.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            base_type: None,
            content: ContentModel::Empty,
            attributes: Vec::new(),
            is_abstract: false,
            mixed: false,
        }
    }

    /// Creates a complex type with sequence content.
    pub fn sequence(name: impl Into<String>, elements: Vec<ElementDef>) -> Self {
        Self {
            name: name.into(),
            base_type: None,
            content: ContentModel::Sequence(elements),
            attributes: Vec::new(),
            is_abstract: false,
            mixed: false,
        }
    }
}

/// Content model for complex types.
#[derive(Debug, Clone)]
pub enum ContentModel {
    /// Empty content
    Empty,
    /// Sequence of elements (in order)
    Sequence(Vec<ElementDef>),
    /// Choice of elements (one of)
    Choice(Vec<ElementDef>),
    /// All (unordered)
    All(Vec<ElementDef>),
    /// Simple content (text with optional extension)
    SimpleContent {
        /// Base type for the content
        base_type: String,
    },
    /// Complex content extension
    ComplexExtension {
        /// Base type being extended
        base_type: String,
        /// Additional child elements
        elements: Vec<ElementDef>,
    },
    /// Any content (wildcard)
    Any {
        /// Target namespace for wildcard
        namespace: Option<String>,
        /// How to process the content
        process_contents: ProcessContents,
    },
}

/// How to process wildcard content.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessContents {
    /// Strict - must validate
    Strict,
    /// Lax - validate if schema available
    Lax,
    /// Skip - don't validate
    Skip,
}

/// An attribute definition.
#[derive(Debug, Clone)]
pub struct AttributeDef {
    /// Attribute name
    pub name: String,
    /// Type reference
    pub type_ref: Option<String>,
    /// Whether the attribute is required
    pub required: bool,
    /// Default value
    pub default: Option<String>,
    /// Fixed value
    pub fixed: Option<String>,
}

impl AttributeDef {
    /// Creates a new attribute definition.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            type_ref: None,
            required: false,
            default: None,
            fixed: None,
        }
    }

    /// Creates a required attribute.
    pub fn required(name: impl Into<String>) -> Self {
        Self {
            required: true,
            ..Self::new(name)
        }
    }

    /// Sets the type reference.
    pub fn with_type(mut self, type_ref: impl Into<String>) -> Self {
        self.type_ref = Some(type_ref.into());
        self
    }

    /// Sets a default value.
    pub fn with_default(mut self, default: impl Into<String>) -> Self {
        self.default = Some(default.into());
        self
    }
}

/// Type of compiled identity constraint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompiledConstraintType {
    /// Values must be unique (null allowed)
    Unique,
    /// Values must be unique and non-null
    Key,
    /// Values must reference an existing key
    KeyRef,
}

/// A compiled identity constraint ready for validation.
#[derive(Debug, Clone)]
pub struct CompiledConstraint {
    /// Constraint name
    pub name: String,
    /// Type of constraint
    pub constraint_type: CompiledConstraintType,
    /// XPath selector expression (for selecting scope)
    pub selector_xpath: String,
    /// XPath field expressions (for selecting key values)
    pub field_xpaths: Vec<String>,
    /// For keyref: the key being referenced
    pub refer: Option<String>,
}

impl CompiledConstraint {
    /// Creates a new compiled unique constraint.
    pub fn unique(name: impl Into<String>, selector: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            constraint_type: CompiledConstraintType::Unique,
            selector_xpath: selector.into(),
            field_xpaths: Vec::new(),
            refer: None,
        }
    }

    /// Creates a new compiled key constraint.
    pub fn key(name: impl Into<String>, selector: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            constraint_type: CompiledConstraintType::Key,
            selector_xpath: selector.into(),
            field_xpaths: Vec::new(),
            refer: None,
        }
    }

    /// Creates a new compiled keyref constraint.
    pub fn keyref(
        name: impl Into<String>,
        selector: impl Into<String>,
        refer: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            constraint_type: CompiledConstraintType::KeyRef,
            selector_xpath: selector.into(),
            field_xpaths: Vec::new(),
            refer: Some(refer.into()),
        }
    }

    /// Adds a field XPath expression.
    pub fn with_field(mut self, field: impl Into<String>) -> Self {
        self.field_xpaths.push(field.into());
        self
    }

    /// Adds multiple field XPath expressions.
    pub fn with_fields(mut self, fields: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.field_xpaths.extend(fields.into_iter().map(Into::into));
        self
    }
}

/// Built-in XSD types.
pub mod builtin {
    /// Built-in string type name.
    pub const STRING: &str = "xs:string";
    /// Built-in integer type name.
    pub const INTEGER: &str = "xs:integer";
    /// Built-in decimal type name.
    pub const DECIMAL: &str = "xs:decimal";
    /// Built-in boolean type name.
    pub const BOOLEAN: &str = "xs:boolean";
    /// Built-in date type name.
    pub const DATE: &str = "xs:date";
    /// Built-in dateTime type name.
    pub const DATE_TIME: &str = "xs:dateTime";
    /// Built-in double type name.
    pub const DOUBLE: &str = "xs:double";
    /// Built-in float type name.
    pub const FLOAT: &str = "xs:float";
    /// Built-in anyURI type name.
    pub const ANY_URI: &str = "xs:anyURI";
    /// Built-in ID type name.
    pub const ID: &str = "xs:ID";
}

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

    #[test]
    fn test_get_element_with_local_name() {
        let mut schema = CompiledSchema::new();
        schema.elements.insert(
            "ReliefFeature".to_string(),
            ElementDef::new("ReliefFeature"),
        );

        // Local name lookup should work
        assert!(schema.get_element("ReliefFeature").is_some());
    }

    #[test]
    fn test_get_element_with_qualified_name() {
        let mut schema = CompiledSchema::new();
        schema.elements.insert(
            "ReliefFeature".to_string(),
            ElementDef::new("ReliefFeature"),
        );

        // Qualified name lookup should fall back to local name
        assert!(
            schema.get_element("dem:ReliefFeature").is_some(),
            "Should find 'ReliefFeature' when looking up 'dem:ReliefFeature'"
        );
    }

    #[test]
    fn test_get_type_with_local_name() {
        let mut schema = CompiledSchema::new();
        schema.types.insert(
            "AbstractCityObjectType".to_string(),
            TypeDef::Complex(ComplexType::new("AbstractCityObjectType")),
        );

        // Local name lookup should work
        assert!(schema.get_type("AbstractCityObjectType").is_some());
    }

    #[test]
    fn test_get_type_with_qualified_name() {
        let mut schema = CompiledSchema::new();
        schema.types.insert(
            "AbstractCityObjectType".to_string(),
            TypeDef::Complex(ComplexType::new("AbstractCityObjectType")),
        );

        // Qualified name lookup should fall back to local name
        assert!(
            schema.get_type("core:AbstractCityObjectType").is_some(),
            "Should find 'AbstractCityObjectType' when looking up 'core:AbstractCityObjectType'"
        );
    }

    #[test]
    fn test_get_type_not_found() {
        let schema = CompiledSchema::new();
        assert!(schema.get_type("NonExistentType").is_none());
        assert!(schema.get_type("prefix:NonExistentType").is_none());
    }

    #[test]
    fn test_get_element_not_found() {
        let schema = CompiledSchema::new();
        assert!(schema.get_element("NonExistentElement").is_none());
        assert!(schema.get_element("prefix:NonExistentElement").is_none());
    }
}