fastxml 0.11.0

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
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
//! Reference-integrity checking over the XSD AST.
//!
//! After all schema documents of a set are known, every QName reference
//! (`type=`, `base=`, `ref=`, `itemType=`, `memberTypes=`, `substitutionGroup=`,
//! keyref `refer=`) must resolve to a declared component — but only when the
//! referenced namespace is *strict*: fully present in the compiled set. A
//! namespace whose imports/includes could not be resolved (or were never
//! fetched, as in single-document compilation) is *poisoned* and stays lenient,
//! so real-world schema sets with partial dependencies keep compiling.

use std::collections::{HashMap, HashSet};

use crate::error::Result;
use crate::schema::error::SchemaError;

use super::super::types::*;

/// The XSD schema namespace.
const XSD_NS: &str = "http://www.w3.org/2001/XMLSchema";
/// The XML namespace (implicitly bound to the `xml` prefix).
const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
/// The XML Schema instance namespace.
const XSI_NS: &str = "http://www.w3.org/2001/XMLSchema-instance";

use crate::schema::xsd::builtin::is_builtin_xsd_type_local;

use super::facet_checks::{FacetBase, check_facets, classify_builtin_base};

/// Namespaces that are always lenient because fastxml provides (partial)
/// built-in definitions for them rather than compiled schema documents.
fn is_always_lenient(ns: &str) -> bool {
    ns == XML_NS
        || ns == XSI_NS
        || ns == crate::schema::xsd::builtin::GML_NAMESPACE
        || ns == crate::schema::xsd::builtin::GML31_NAMESPACE
}

/// Which namespaces of a schema set are strict (fully present) vs poisoned.
///
/// Must be computed *before* `xs:redefine` application drains the redefine
/// declarations from the AST.
#[derive(Debug, Default)]
pub(crate) struct Strictness {
    /// Target namespaces defined by schemas in the set ("" = no namespace).
    defined: HashSet<String>,
    /// Namespaces with unresolved imports/includes targeting them.
    poisoned: HashSet<String>,
}

impl Strictness {
    /// Computes strictness from the full AST set.
    ///
    /// A namespace is poisoned when:
    /// - an `xs:import` for it has no resolved document in the set, or
    /// - a schema of that namespace has `xs:include`/`xs:redefine` but no other
    ///   document of the same namespace is present (the include was never
    ///   fetched), or
    /// - a schema of that namespace includes documents while a chameleon
    ///   (no-targetNamespace) document is in the set (its components are not
    ///   re-homed into the includer's namespace).
    pub(crate) fn compute(schemas: &[XsdSchema]) -> Self {
        let mut defined: HashSet<String> = HashSet::new();
        for schema in schemas {
            defined.insert(tns_key(schema));
        }

        let has_chameleon_doc = schemas
            .iter()
            .any(|s| s.target_namespace.is_none() && schemas.len() > 1);

        let mut poisoned: HashSet<String> = HashSet::new();
        for schema in schemas {
            for import in &schema.imports {
                let ns = import.namespace.clone().unwrap_or_default();
                if !defined.contains(&ns) {
                    poisoned.insert(ns);
                }
            }
            if !schema.includes.is_empty() || !schema.redefines.is_empty() {
                let own = tns_key(schema);
                let satisfied = schemas
                    .iter()
                    .any(|other| !std::ptr::eq(other, schema) && tns_key(other) == own);
                if !satisfied || (has_chameleon_doc && schema.target_namespace.is_some()) {
                    poisoned.insert(own);
                }
            }
        }

        Self { defined, poisoned }
    }

    /// Whether references into `ns` must resolve.
    fn is_strict(&self, ns: &str) -> bool {
        if self.poisoned.contains(ns) || is_always_lenient(ns) {
            return false;
        }
        // The XSD namespace resolves against built-ins even when no schema
        // document for it is present.
        ns == XSD_NS || self.defined.contains(ns)
    }
}

pub(super) fn tns_key(schema: &XsdSchema) -> String {
    schema.target_namespace.clone().unwrap_or_default()
}

/// What a keyref `refer=` may point at.
#[derive(Debug, Clone, Copy)]
struct KeyInfo {
    /// Whether the constraint is a key/unique (a legal refer target).
    is_key_or_unique: bool,
    /// Number of field expressions.
    field_count: usize,
}

/// What is known about a top-level type definition.
#[derive(Debug, Clone, Copy, Default)]
struct TypeInfo {
    /// Whether the type is a complex type.
    is_complex: bool,
    /// final blocks derivation by extension.
    final_extension: bool,
    /// final blocks derivation by restriction.
    final_restriction: bool,
    /// final blocks use as a list item type.
    final_list: bool,
    /// final blocks use as a union member type.
    final_union: bool,
}

/// Expands a final/finalDefault control into per-method flags.
fn final_flags(control: Option<&DerivationControl>) -> (bool, bool, bool, bool) {
    match control {
        None => (false, false, false, false),
        Some(DerivationControl::All) => (true, true, true, true),
        Some(DerivationControl::List(types)) => (
            types.contains(&DerivationType::Extension),
            types.contains(&DerivationType::Restriction),
            types.contains(&DerivationType::List),
            types.contains(&DerivationType::Union),
        ),
    }
}

/// Symbol tables of top-level component names, keyed by namespace.
#[derive(Debug, Default)]
struct SymbolTables {
    /// Type names with their kind and derivation controls.
    types: HashMap<String, HashMap<String, TypeInfo>>,
    elements: HashMap<String, HashSet<String>>,
    attributes: HashMap<String, HashSet<String>>,
    groups: HashMap<String, HashSet<String>>,
    attribute_groups: HashMap<String, HashSet<String>>,
    /// Identity-constraint names (for keyref refer=) with their metadata.
    keys: HashMap<String, HashMap<String, KeyInfo>>,
}

impl SymbolTables {
    fn build(schemas: &[XsdSchema]) -> Self {
        let mut tables = Self::default();
        for schema in schemas {
            let ns = tns_key(schema);
            for type_def in &schema.types {
                if let Some(name) = type_def.name() {
                    // Effective final: the type's own final, else the
                    // schema's finalDefault.
                    let control = match type_def {
                        XsdTypeDef::Complex(ct) => ct.final_.as_ref(),
                        XsdTypeDef::Simple(st) => st.final_.as_ref(),
                    }
                    .or(schema.final_default.as_ref());
                    let (ext, restr, list, union) = final_flags(control);
                    let info = if type_def.is_complex() {
                        TypeInfo {
                            is_complex: true,
                            final_extension: ext,
                            final_restriction: restr,
                            // list/union do not apply to complex types.
                            final_list: false,
                            final_union: false,
                        }
                    } else {
                        TypeInfo {
                            is_complex: false,
                            // extension does not apply to simple-type final.
                            final_extension: false,
                            final_restriction: restr,
                            final_list: list,
                            final_union: union,
                        }
                    };
                    tables
                        .types
                        .entry(ns.clone())
                        .or_default()
                        .insert(name.to_string(), info);
                }
            }
            for element in &schema.elements {
                tables
                    .elements
                    .entry(ns.clone())
                    .or_default()
                    .insert(element.name.clone());
                collect_constraint_names(element, &ns, &mut tables.keys);
            }
            for attr in &schema.attributes {
                if let Some(name) = &attr.name {
                    tables
                        .attributes
                        .entry(ns.clone())
                        .or_default()
                        .insert(name.clone());
                }
            }
            for group in &schema.groups {
                if let Some(name) = &group.name {
                    tables
                        .groups
                        .entry(ns.clone())
                        .or_default()
                        .insert(name.clone());
                }
            }
            for ag in &schema.attribute_groups {
                if let Some(name) = &ag.name {
                    tables
                        .attribute_groups
                        .entry(ns.clone())
                        .or_default()
                        .insert(name.clone());
                }
            }
            // Identity constraints can sit on elements nested inside types.
            for type_def in &schema.types {
                collect_constraints_in_type(type_def, &ns, &mut tables.keys);
            }
        }
        tables
    }

    /// Looks up keyref-refer metadata, with the same chameleon no-namespace
    /// fallback as [`Self::contains`].
    fn lookup_key(&self, ns: &str, local: &str) -> Option<KeyInfo> {
        if let Some(info) = self.keys.get(ns).and_then(|m| m.get(local)) {
            return Some(*info);
        }
        if !ns.is_empty() {
            return self.keys.get("").and_then(|m| m.get(local)).copied();
        }
        None
    }

    /// Looks up what is known about a type reference target, with the same
    /// fallbacks as [`Self::contains`].
    fn lookup_type_info(&self, ns: &str, local: &str) -> Option<TypeInfo> {
        if let Some(info) = self.types.get(ns).and_then(|m| m.get(local)) {
            return Some(*info);
        }
        if !ns.is_empty()
            && let Some(info) = self.types.get("").and_then(|m| m.get(local))
        {
            return Some(*info);
        }
        if (ns == XSD_NS || ns.is_empty()) && is_builtin_xsd_type_local(local) {
            // Every built-in datatype is simple except the ur-type; none
            // carries a final constraint.
            return Some(TypeInfo {
                is_complex: local == "anyType",
                ..TypeInfo::default()
            });
        }
        None
    }

    fn contains(&self, kind: RefKind, ns: &str, local: &str) -> bool {
        if kind == RefKind::Key {
            return self.lookup_key(ns, local).is_some();
        }
        if kind == RefKind::Type {
            return self.lookup_type_info(ns, local).is_some();
        }
        let table = match kind {
            RefKind::Element => &self.elements,
            RefKind::Attribute => &self.attributes,
            RefKind::Group => &self.groups,
            RefKind::AttributeGroup => &self.attribute_groups,
            RefKind::Type | RefKind::Key => unreachable!("handled above"),
        };
        if table.get(ns).is_some_and(|set| set.contains(local)) {
            return true;
        }
        // Components from chameleon (no-targetNamespace) documents are merged
        // by the compiler under their local names; let them satisfy references
        // into any namespace so we never reject what the compiler resolves.
        !ns.is_empty() && table.get("").is_some_and(|set| set.contains(local))
    }
}

/// Collects key/unique constraint names declared on an element (and its
/// nested content) into the per-namespace key table.
fn collect_constraint_names(
    element: &XsdElement,
    ns: &str,
    keys: &mut HashMap<String, HashMap<String, KeyInfo>>,
) {
    for ic in &element.identity_constraints {
        // keyref names share the symbol space; record them too so refer
        // resolution can distinguish "missing" from "wrong kind".
        keys.entry(ns.to_string()).or_default().insert(
            ic.name.clone(),
            KeyInfo {
                is_key_or_unique: ic.constraint_type != XsdConstraintType::KeyRef,
                field_count: ic.fields.len(),
            },
        );
    }
    if let Some(inline) = &element.inline_type {
        collect_constraints_in_type(inline, ns, keys);
    }
}

fn collect_constraints_in_type(
    type_def: &XsdTypeDef,
    ns: &str,
    keys: &mut HashMap<String, HashMap<String, KeyInfo>>,
) {
    let XsdTypeDef::Complex(ct) = type_def else {
        return;
    };
    let mut walk_particle = |particle: &XsdParticle| {
        collect_constraints_in_particle(particle, ns, keys);
    };
    match &ct.content {
        XsdComplexContent::Particle(p) => walk_particle(p),
        XsdComplexContent::ComplexContent(cc) => match &cc.derivation {
            XsdComplexContentDerivation::Extension(ext) => {
                if let Some(p) = &ext.particle {
                    walk_particle(p);
                }
            }
            XsdComplexContentDerivation::Restriction(r) => {
                if let Some(p) = &r.particle {
                    walk_particle(p);
                }
            }
        },
        _ => {}
    }
}

fn collect_constraints_in_particle(
    particle: &XsdParticle,
    ns: &str,
    keys: &mut HashMap<String, HashMap<String, KeyInfo>>,
) {
    match particle {
        XsdParticle::Sequence(seq) => {
            for item in &seq.particles {
                collect_constraints_in_item(item, ns, keys);
            }
        }
        XsdParticle::Choice(choice) => {
            for item in &choice.particles {
                collect_constraints_in_item(item, ns, keys);
            }
        }
        XsdParticle::All(all) => {
            for element in &all.elements {
                collect_constraint_names(element, ns, keys);
            }
        }
        XsdParticle::GroupRef(_) | XsdParticle::Any(_) => {}
    }
}

fn collect_constraints_in_item(
    item: &XsdParticleItem,
    ns: &str,
    keys: &mut HashMap<String, HashMap<String, KeyInfo>>,
) {
    match item {
        XsdParticleItem::Element(element) => collect_constraint_names(element, ns, keys),
        XsdParticleItem::Sequence(seq) => {
            for nested in &seq.particles {
                collect_constraints_in_item(nested, ns, keys);
            }
        }
        XsdParticleItem::Choice(choice) => {
            for nested in &choice.particles {
                collect_constraints_in_item(nested, ns, keys);
            }
        }
        XsdParticleItem::GroupRef(_) | XsdParticleItem::Any(_) => {}
    }
}

/// The kind of component a reference points at.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RefKind {
    Type,
    Element,
    Attribute,
    Group,
    AttributeGroup,
    Key,
}

impl RefKind {
    fn as_str(self) -> &'static str {
        match self {
            RefKind::Type => "type",
            RefKind::Element => "element",
            RefKind::Attribute => "attribute",
            RefKind::Group => "group",
            RefKind::AttributeGroup => "attribute group",
            RefKind::Key => "identity constraint",
        }
    }
}

/// Checks every QName reference in the schema set. Call after
/// `apply_redefines` (so redefined self-references point at the surviving
/// synthetic names) with a [`Strictness`] computed before it.
pub(crate) fn check_references(schemas: &[XsdSchema], strictness: &Strictness) -> Result<()> {
    let tables = SymbolTables::build(schemas);
    super::cycles::check_definition_cycles(schemas)?;
    for schema in schemas {
        let checker = Checker {
            schema,
            strictness,
            tables: &tables,
        };
        checker.check_schema()?;
    }
    Ok(())
}

/// Per-schema reference checker (QName prefixes resolve against the owning
/// document's namespace bindings).
struct Checker<'a> {
    schema: &'a XsdSchema,
    strictness: &'a Strictness,
    tables: &'a SymbolTables,
}

impl Checker<'_> {
    /// Resolves a QName's namespace using this schema's bindings.
    /// Returns `None` when the prefix is undeclared. QName attribute values
    /// are whitespace-collapsed, so stray whitespace is trimmed first.
    fn resolve_ns(&self, prefix: Option<&str>) -> Option<String> {
        match prefix {
            Some("xml") => Some(XML_NS.to_string()),
            Some(p) => self.schema.namespace_bindings.get(p).cloned(),
            None => Some(
                self.schema
                    .namespace_bindings
                    .get("")
                    .cloned()
                    .unwrap_or_default(),
            ),
        }
    }

    /// Checks one reference; errors when it points into a strict namespace
    /// but no matching declaration exists.
    fn check_ref(&self, kind: RefKind, qname: &QName, from: &str) -> Result<()> {
        self.check_ref_inner(kind, qname, from, true)
    }

    /// Lazily checks a reference: per the resolution rules the W3C test suite
    /// expects (saxonData/Missing), a dangling `type=` on an unused top-level
    /// element, `substitutionGroup=`, `itemType=` or `memberTypes=` is only an
    /// error when the component is needed for validation — except when the
    /// QName can *never* resolve (undeclared prefix, or a miss in the closed
    /// built-in XSD namespace).
    fn check_ref_lazy(&self, kind: RefKind, qname: &QName, from: &str) -> Result<()> {
        self.check_ref_inner(kind, qname, from, false)
    }

    fn check_ref_inner(
        &self,
        kind: RefKind,
        qname: &QName,
        from: &str,
        require_existence: bool,
    ) -> Result<()> {
        // QName values are whitespace-collapsed before resolution.
        let prefix = qname.prefix.as_deref().map(str::trim);
        let local = qname.local.trim();
        let Some(ns) = self.resolve_ns(prefix) else {
            // Undeclared prefix: the QName cannot denote any component.
            return Err(SchemaError::DanglingReference {
                kind: kind.as_str(),
                name: qname.to_string_full(),
                referenced_from: format!("{} (undeclared namespace prefix)", from),
            }
            .into());
        };
        if self.tables.contains(kind, &ns, local) {
            return Ok(());
        }
        // Mirror the compiler's leniency: an unprefixed reference falls back
        // to the schema's own target namespace.
        if prefix.is_none()
            && let Some(own) = &self.schema.target_namespace
            && *own != ns
            && self.tables.contains(kind, own, local)
        {
            return Ok(());
        }
        // The XSD namespace is closed: a miss there can never be satisfied
        // later, even under lazy resolution.
        let must_resolve = self.strictness.is_strict(&ns) && (require_existence || ns == XSD_NS);
        if !must_resolve {
            return Ok(());
        }
        Err(SchemaError::DanglingReference {
            kind: kind.as_str(),
            name: qname.to_string_full(),
            referenced_from: from.to_string(),
        }
        .into())
    }

    fn check_schema(&self) -> Result<()> {
        for element in &self.schema.elements {
            self.check_element_at(element, "top-level element", true)?;
        }
        for type_def in &self.schema.types {
            self.check_type_def(type_def)?;
        }
        for attr in &self.schema.attributes {
            self.check_attribute(attr, "top-level attribute")?;
        }
        for group in &self.schema.groups {
            if let Some(particle) = &group.particle {
                let from = format!("group '{}'", group.name.as_deref().unwrap_or("(anonymous)"));
                self.check_particle(particle, &from)?;
            }
        }
        for ag in &self.schema.attribute_groups {
            let from = format!(
                "attribute group '{}'",
                ag.name.as_deref().unwrap_or("(anonymous)")
            );
            self.check_attribute_group_body(ag, &from)?;
        }
        Ok(())
    }

    fn check_element(&self, element: &XsdElement, from: &str) -> Result<()> {
        self.check_element_at(element, from, false)
    }

    fn check_element_at(&self, element: &XsdElement, from: &str, top_level: bool) -> Result<()> {
        if let Some(r) = &element.ref_ {
            self.check_ref(RefKind::Element, r, from)?;
        }
        if let Some(t) = &element.type_ref {
            // A dangling type on an unused top-level element declaration is
            // tolerated under lazy component resolution (saxonData/Missing).
            if top_level {
                self.check_ref_lazy(RefKind::Type, t, from)?;
            } else {
                self.check_ref(RefKind::Type, t, from)?;
            }
        }
        if let Some(sg) = &element.substitution_group {
            self.check_ref_lazy(RefKind::Element, sg, from)?;
        }
        if let Some(inline) = &element.inline_type {
            self.check_type_def(inline)?;
        }
        for ic in &element.identity_constraints {
            if let Some(refer) = &ic.refer {
                let from = format!("keyref '{}'", ic.name);
                self.check_ref(RefKind::Key, refer, &from)?;
                self.check_keyref_target(ic, refer)?;
            }
        }
        Ok(())
    }

    /// Classifies a restriction base for facet checking: a built-in XSD
    /// datatype yields its primitive class; user-defined or unresolved bases
    /// are `Unknown` (only base-independent facet checks run).
    fn facet_base(&self, base: Option<&QName>) -> FacetBase {
        let Some(qname) = base else {
            return FacetBase::Unknown;
        };
        let prefix = qname.prefix.as_deref().map(str::trim);
        let local = qname.local.trim();
        let Some(ns) = self.resolve_ns(prefix) else {
            return FacetBase::Unknown;
        };
        // A user-defined type shadowing a built-in name stays Unknown.
        if self
            .tables
            .types
            .get(&ns)
            .is_some_and(|m| m.contains_key(local))
        {
            return FacetBase::Unknown;
        }
        if ns == XSD_NS || (ns.is_empty() && is_builtin_xsd_type_local(local)) {
            classify_builtin_base(local)
        } else {
            FacetBase::Unknown
        }
    }

    /// Resolves what is known about a type reference target with the same
    /// resolution order as [`Self::check_ref`].
    fn resolve_type_info(&self, qname: &QName) -> Option<TypeInfo> {
        let prefix = qname.prefix.as_deref().map(str::trim);
        let local = qname.local.trim();
        let ns = self.resolve_ns(prefix)?;
        if let Some(info) = self.tables.lookup_type_info(&ns, local) {
            return Some(info);
        }
        if prefix.is_none()
            && let Some(own) = &self.schema.target_namespace
            && *own != ns
        {
            return self.tables.lookup_type_info(own, local);
        }
        None
    }

    /// Errors when a type reference resolves to a complex type in a context
    /// that requires a simple type.
    fn require_simple_type(&self, qname: &QName, from: &str) -> Result<()> {
        if self.resolve_type_info(qname).is_some_and(|i| i.is_complex) {
            return Err(SchemaError::InvalidSchema {
                message: format!(
                    "{} requires a simple type, but '{}' is complex",
                    from, qname
                ),
            }
            .into());
        }
        Ok(())
    }

    /// Errors when a complexContent base resolves to a simple type.
    fn require_complex_type(&self, qname: &QName, from: &str) -> Result<()> {
        if self.resolve_type_info(qname).is_some_and(|i| !i.is_complex) {
            return Err(SchemaError::InvalidSchema {
                message: format!(
                    "{} requires a complex type, but '{}' is simple",
                    from, qname
                ),
            }
            .into());
        }
        Ok(())
    }

    /// Errors when the base type's final constraint blocks this derivation
    /// or use (`method` selects which final flag applies).
    fn check_final(&self, qname: &QName, method: DerivationType, from: &str) -> Result<()> {
        let Some(info) = self.resolve_type_info(qname) else {
            return Ok(());
        };
        let blocked = match method {
            DerivationType::Extension => info.final_extension,
            DerivationType::Restriction => info.final_restriction,
            DerivationType::List => info.final_list,
            DerivationType::Union => info.final_union,
            DerivationType::Substitution => false,
        };
        if blocked {
            return Err(SchemaError::InvalidSchema {
                message: format!(
                    "type '{}' is final and cannot be used for {} ({})",
                    qname,
                    match method {
                        DerivationType::Extension => "derivation by extension",
                        DerivationType::Restriction => "derivation by restriction",
                        DerivationType::List => "a list item type",
                        DerivationType::Union => "a union member type",
                        DerivationType::Substitution => "substitution",
                    },
                    from
                ),
            }
            .into());
        }
        Ok(())
    }

    /// When a keyref's refer target resolves, it must be a key/unique (not
    /// another keyref) and its field count must match the keyref's.
    fn check_keyref_target(&self, ic: &XsdIdentityConstraint, refer: &QName) -> Result<()> {
        let prefix = refer.prefix.as_deref().map(str::trim);
        let local = refer.local.trim();
        let Some(ns) = self.resolve_ns(prefix) else {
            return Ok(()); // already reported by check_ref
        };
        let Some(info) = self.tables.lookup_key(&ns, local) else {
            return Ok(()); // missing target is handled by check_ref
        };
        if !info.is_key_or_unique {
            return Err(SchemaError::InvalidSchema {
                message: format!(
                    "keyref '{}' must refer to a key or unique constraint, but '{}' is a keyref",
                    ic.name, refer
                ),
            }
            .into());
        }
        if info.field_count != ic.fields.len() {
            return Err(SchemaError::InvalidSchema {
                message: format!(
                    "keyref '{}' has {} field(s) but referred constraint '{}' has {}",
                    ic.name,
                    ic.fields.len(),
                    refer,
                    info.field_count
                ),
            }
            .into());
        }
        Ok(())
    }

    fn check_attribute(&self, attr: &XsdAttribute, from: &str) -> Result<()> {
        if let Some(r) = &attr.ref_ {
            self.check_ref(RefKind::Attribute, r, from)?;
        }
        if let Some(t) = &attr.type_ref {
            self.check_ref(RefKind::Type, t, from)?;
            self.require_simple_type(t, "attribute type")?;
        }
        if let Some(inline) = &attr.inline_type {
            self.check_simple_type(inline)?;
        }
        Ok(())
    }

    fn check_type_def(&self, type_def: &XsdTypeDef) -> Result<()> {
        match type_def {
            XsdTypeDef::Simple(st) => self.check_simple_type(st),
            XsdTypeDef::Complex(ct) => self.check_complex_type(ct),
        }
    }

    fn check_simple_type(&self, st: &XsdSimpleType) -> Result<()> {
        let from = format!(
            "simple type '{}'",
            st.name.as_deref().unwrap_or("(anonymous)")
        );
        match &st.content {
            XsdSimpleTypeContent::Restriction(r) => {
                if let Some(base) = &r.base {
                    self.check_ref(RefKind::Type, base, &from)?;
                    self.require_simple_type(base, "simple type restriction base")?;
                    self.check_final(base, DerivationType::Restriction, &from)?;
                }
                if let Some(inline) = &r.inline_base {
                    self.check_simple_type(inline)?;
                }
                check_facets(&r.facets, self.facet_base(r.base.as_ref()))?;
            }
            XsdSimpleTypeContent::List(list) => {
                if let Some(item) = &list.item_type {
                    self.check_ref_lazy(RefKind::Type, item, &from)?;
                    self.require_simple_type(item, "list item type")?;
                    self.check_final(item, DerivationType::List, &from)?;
                }
                if let Some(inline) = &list.inline_type {
                    self.check_simple_type(inline)?;
                }
            }
            XsdSimpleTypeContent::Union(union) => {
                for member in &union.member_types {
                    self.check_ref_lazy(RefKind::Type, member, &from)?;
                    self.require_simple_type(member, "union member type")?;
                    self.check_final(member, DerivationType::Union, &from)?;
                }
                for inline in &union.inline_types {
                    self.check_simple_type(inline)?;
                }
            }
        }
        Ok(())
    }

    fn check_complex_type(&self, ct: &XsdComplexType) -> Result<()> {
        let from = format!(
            "complex type '{}'",
            ct.name.as_deref().unwrap_or("(anonymous)")
        );
        match &ct.content {
            XsdComplexContent::Empty => {}
            XsdComplexContent::Particle(p) => self.check_particle(p, &from)?,
            XsdComplexContent::SimpleContent(sc) => match &sc.derivation {
                XsdSimpleContentDerivation::Extension(ext) => {
                    self.check_ref(RefKind::Type, &ext.base, &from)?;
                    self.check_final(&ext.base, DerivationType::Extension, &from)?;
                    for attr in &ext.attributes {
                        self.check_attribute(attr, &from)?;
                    }
                    for ag in &ext.attribute_groups {
                        self.check_ref(RefKind::AttributeGroup, ag, &from)?;
                    }
                }
                XsdSimpleContentDerivation::Restriction(r) => {
                    self.check_ref(RefKind::Type, &r.base, &from)?;
                    self.check_final(&r.base, DerivationType::Restriction, &from)?;
                    check_facets(&r.facets, self.facet_base(Some(&r.base)))?;
                    for attr in &r.attributes {
                        self.check_attribute(attr, &from)?;
                    }
                    for ag in &r.attribute_groups {
                        self.check_ref(RefKind::AttributeGroup, ag, &from)?;
                    }
                }
            },
            XsdComplexContent::ComplexContent(cc) => match &cc.derivation {
                XsdComplexContentDerivation::Extension(ext) => {
                    self.check_ref(RefKind::Type, &ext.base, &from)?;
                    self.require_complex_type(&ext.base, "complexContent extension base")?;
                    self.check_final(&ext.base, DerivationType::Extension, &from)?;
                    if let Some(p) = &ext.particle {
                        self.check_particle(p, &from)?;
                    }
                    for attr in &ext.attributes {
                        self.check_attribute(attr, &from)?;
                    }
                    for ag in &ext.attribute_groups {
                        self.check_ref(RefKind::AttributeGroup, ag, &from)?;
                    }
                }
                XsdComplexContentDerivation::Restriction(r) => {
                    self.check_ref(RefKind::Type, &r.base, &from)?;
                    self.require_complex_type(&r.base, "complexContent restriction base")?;
                    self.check_final(&r.base, DerivationType::Restriction, &from)?;
                    if let Some(p) = &r.particle {
                        self.check_particle(p, &from)?;
                    }
                    for attr in &r.attributes {
                        self.check_attribute(attr, &from)?;
                    }
                    for ag in &r.attribute_groups {
                        self.check_ref(RefKind::AttributeGroup, ag, &from)?;
                    }
                }
            },
        }
        for attr in &ct.attributes {
            self.check_attribute(attr, &from)?;
        }
        for ag in &ct.attribute_groups {
            self.check_ref(RefKind::AttributeGroup, ag, &from)?;
        }
        Ok(())
    }

    fn check_attribute_group_body(&self, ag: &XsdAttributeGroup, from: &str) -> Result<()> {
        if let Some(r) = &ag.ref_ {
            self.check_ref(RefKind::AttributeGroup, r, from)?;
        }
        for attr in &ag.attributes {
            self.check_attribute(attr, from)?;
        }
        for nested in &ag.attribute_groups {
            self.check_ref(RefKind::AttributeGroup, nested, from)?;
        }
        Ok(())
    }

    fn check_particle(&self, particle: &XsdParticle, from: &str) -> Result<()> {
        match particle {
            XsdParticle::Sequence(seq) => {
                for item in &seq.particles {
                    self.check_item(item, from)?;
                }
            }
            XsdParticle::Choice(choice) => {
                for item in &choice.particles {
                    self.check_item(item, from)?;
                }
            }
            XsdParticle::All(all) => {
                for element in &all.elements {
                    self.check_element(element, from)?;
                }
            }
            XsdParticle::GroupRef(group_ref) => {
                self.check_ref(RefKind::Group, &group_ref.name, from)?;
            }
            XsdParticle::Any(_) => {}
        }
        Ok(())
    }

    fn check_item(&self, item: &XsdParticleItem, from: &str) -> Result<()> {
        match item {
            XsdParticleItem::Element(element) => self.check_element(element, from),
            XsdParticleItem::Sequence(seq) => {
                for nested in &seq.particles {
                    self.check_item(nested, from)?;
                }
                Ok(())
            }
            XsdParticleItem::Choice(choice) => {
                for nested in &choice.particles {
                    self.check_item(nested, from)?;
                }
                Ok(())
            }
            XsdParticleItem::GroupRef(group_ref) => {
                self.check_ref(RefKind::Group, &group_ref.name, from)
            }
            XsdParticleItem::Any(_) => Ok(()),
        }
    }
}