Skip to main content

xsd_schema/compiler/
inspect.rs

1//! Readable, source-attributed reports for compiled content models.
2//!
3//! A complex type's content model passes through three representations before
4//! it validates anything: the particles the schema author wrote, the matcher
5//! the compiler builds from them, and the frontier the runtime executes. When
6//! a model behaves unexpectedly — a counter where an unrolled range was
7//! expected, a wildcard that swallows a declared element, a substitution group
8//! that admits more names than it looks like it should — the only way to see
9//! which of the three disagrees with the others used to be a debugger.
10//!
11//! [`inspect_content_model`] produces a [`ContentModelReport`] with those three
12//! views side by side:
13//!
14//! * **Source** — the type's expanded name, the schema document and line/column
15//!   it was written at, its content type, mixed flag, derivation, the effective
16//!   open content, and the XSD version the schema set runs in.
17//! * **Authored particles** — an indented tree of the *resolved* content
18//!   particles as the schema wrote them: compositors, group references
19//!   (expanded inline but labelled as references), element particles with their
20//!   resolved declaration and type, and wildcards with their namespace
21//!   constraint. Every node carries `minOccurs..maxOccurs` and says whether
22//!   that range will be **unrolled** (`maxOccurs` ≤ `COUNTED_THRESHOLD`) or
23//!   compiled to a **counter**. For an extension, the base type's contribution
24//!   is shown first, in the order the compiler concatenates it.
25//! * **Compiled** — the matcher the validator actually runs: the matcher kind,
26//!   state and transition counts, counter definitions, the initial frontier
27//!   variant [`ActiveStates::try_from_nfa`] picks (or the execution limit it
28//!   hits), a full state table with per-state origins, and an *exposure* line
29//!   naming the models that can reach [`MAX_ACTIVE_CONFIGS`].
30//!
31//! # The compiled view is what runs
32//!
33//! [`inspect_content_model`] compiles through [`compile_content_model_matcher`]
34//! — the same function
35//! [`SchemaValidator`](crate::validation::SchemaValidator) calls at
36//! construction — and derives the frontier through
37//! [`ActiveStates::try_from_nfa`], the same constructor the runtime uses. It
38//! runs no alternative path and applies no simplification, so the state table
39//! is the automaton validation executes, state ids included.
40//!
41//! [`SchemaValidator::describe_content_model`](crate::validation::SchemaValidator::describe_content_model)
42//! goes one better: it reads the *already prepared* model out of the validator
43//! rather than recompiling, so the report is that exact object. For a type
44//! listed in
45//! [`content_model_failures`](crate::validation::SchemaValidator::content_model_failures)
46//! it reports the preparation failure and its reason in place of a compiled
47//! view.
48//!
49//! # Example
50//!
51//! ```
52//! use xsd_schema::compiler::{find_complex_type, inspect_content_model};
53//! use xsd_schema::SchemaSetBuilder;
54//!
55//! let schema_set = SchemaSetBuilder::new()
56//!     .add_source(
57//!         r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
58//!              <xs:complexType name="Pair">
59//!                <xs:sequence>
60//!                  <xs:element name="a" type="xs:string"/>
61//!                  <xs:element name="b" type="xs:string" minOccurs="0"/>
62//!                </xs:sequence>
63//!              </xs:complexType>
64//!            </xs:schema>"#,
65//!         "file:///pair.xsd",
66//!     )
67//!     .expect("schema source accepted")
68//!     .compile()
69//!     .expect("schema compiles")
70//!     .into_schema_set();
71//!
72//! let key = find_complex_type(&schema_set, None, "Pair").expect("named type");
73//! let report = inspect_content_model(&schema_set, key).expect("model compiles");
74//! let text = report.to_string();
75//! assert!(text.contains("Authored particles"));
76//! assert!(text.contains("element a"));
77//! assert!(text.contains("[unrolled]"));
78//! ```
79
80use std::fmt;
81
82use crate::arenas::ComplexTypeDefData;
83use crate::ids::{ComplexTypeKey, ElementKey, ModelGroupKey, NameId, TypeKey};
84use crate::namespace::XS_NAMESPACE;
85use crate::parser::frames::{
86    ComplexContentResult, Compositor, DerivationMethod, ElementFrameResult, ModelGroupDefResult,
87    NamespaceToken, NotQNameItem, ParticleResult, ParticleTerm, TypeRefResult, WildcardNamespace,
88    WildcardResult,
89};
90use crate::parser::location::SourceRef;
91use crate::schema::model::XsdVersion;
92use crate::schema::SchemaSet;
93use crate::types::complex::{
94    NamespaceConstraint, OpenContentMode as TypesOpenContentMode, ProcessContents, WildcardRef,
95};
96use crate::validation::content::CompiledContentModel;
97use crate::validation::info::ContentType;
98
99use super::all_group::{AllGroupModel, OpenContentMode as AllGroupOpenContentMode};
100use super::error::NfaCompileError;
101use super::nfa::{
102    ActiveStates, CounterDef, CounterId, NfaTable, NfaTerm, StateId, TransitionKind,
103    MAX_ACTIVE_CONFIGS,
104};
105use super::particle::COUNTED_THRESHOLD;
106use super::substitution::{build_substitution_group_map, SubstitutionGroupMap};
107use super::{compile_content_model_matcher, ContentModelMatcher};
108
109/// Guard against pathological base-type chains while collecting authored views.
110const MAX_REPORT_DEPTH: usize = 100;
111
112// ---------------------------------------------------------------------------
113// Entry points
114// ---------------------------------------------------------------------------
115
116/// Look up a **named global complex type** by its expanded name.
117///
118/// `namespace` is the namespace URI, or `None` for the absent namespace. Only
119/// named, globally declared complex types can be found this way — an anonymous
120/// local type has no expanded name, and its [`ComplexTypeKey`] must be reached
121/// through the declaration that owns it (an element declaration's
122/// `resolved_type`, for instance).
123///
124/// Returns `None` when the name is not interned in this schema set, resolves to
125/// no type, or resolves to a *simple* type.
126pub fn find_complex_type(
127    schema_set: &SchemaSet,
128    namespace: Option<&str>,
129    local: &str,
130) -> Option<ComplexTypeKey> {
131    let ns = match namespace {
132        Some(ns) => Some(schema_set.name_table.get(ns)?),
133        None => None,
134    };
135    let local_id = schema_set.name_table.get(local)?;
136    schema_set.lookup_type(ns, local_id)?.as_complex()
137}
138
139/// Compile a complex type's content model and describe it in three views.
140///
141/// Compilation goes through [`compile_content_model_matcher`], the same entry
142/// point the validator uses, so the **Compiled** view is exactly the matcher
143/// validation would execute for this type.
144///
145/// Returns the compiler's error when the model does not compile. A model that
146/// compiles but whose initial frontier exceeds an execution limit is *not* an
147/// error here: the report is produced and its frontier line names the limit.
148///
149/// # Panics
150///
151/// Panics if `ct_key` does not belong to `schema_set`, matching the indexing
152/// convention the rest of the crate uses for arena keys.
153pub fn inspect_content_model(
154    schema_set: &SchemaSet,
155    ct_key: ComplexTypeKey,
156) -> Result<ContentModelReport, NfaCompileError> {
157    let ct_data = &schema_set.arenas.complex_types[ct_key];
158    let subst = build_substitution_group_map(schema_set);
159    let subst = (!subst.is_empty()).then_some(subst);
160    let matcher = compile_content_model_matcher(schema_set, ct_data)?;
161    let compiled = compiled_view_from_matcher(schema_set, subst.as_ref(), &matcher);
162    Ok(assemble(schema_set, ct_data, subst.as_ref(), compiled))
163}
164
165/// Build a report for a type whose model the validator already prepared (or
166/// failed to prepare). Backs
167/// [`SchemaValidator::describe_content_model`](crate::validation::SchemaValidator::describe_content_model).
168pub(crate) fn report_from_prepared(
169    schema_set: &SchemaSet,
170    ct_key: ComplexTypeKey,
171    prepared: Option<&CompiledContentModel>,
172    failure: Option<&str>,
173    subst: Option<&SubstitutionGroupMap>,
174) -> Option<ContentModelReport> {
175    let ct_data = schema_set.arenas.get_complex_type(ct_key)?;
176    let compiled = match (failure, prepared) {
177        (Some(reason), _) => CompiledView::Failed {
178            reason: reason.to_string(),
179        },
180        (None, Some(model)) => compiled_view_from_prepared(schema_set, subst, model),
181        // No model prepared and no failure recorded: the type's content type is
182        // neither element-only nor mixed, so the validator never builds one.
183        // Compile on the spot so the view still shows what this type would get.
184        (None, None) => match compile_content_model_matcher(schema_set, ct_data) {
185            Ok(matcher) => {
186                let mut view = compiled_view_from_matcher(schema_set, subst, &matcher);
187                view.mark_not_prepared();
188                view
189            }
190            Err(err) => CompiledView::Failed {
191                reason: err.to_string(),
192            },
193        },
194    };
195    Some(assemble(schema_set, ct_data, subst, compiled))
196}
197
198fn assemble(
199    schema_set: &SchemaSet,
200    ct_data: &ComplexTypeDefData,
201    subst: Option<&SubstitutionGroupMap>,
202    compiled: CompiledView,
203) -> ContentModelReport {
204    let source = source_view(schema_set, ct_data, &compiled);
205    let authored = authored_view(schema_set, ct_data, subst, &compiled);
206    ContentModelReport {
207        source,
208        authored,
209        compiled,
210    }
211}
212
213// ---------------------------------------------------------------------------
214// Report structure
215// ---------------------------------------------------------------------------
216
217/// A three-view description of one complex type's content model.
218///
219/// See the [module documentation](self) for what each view contains. The
220/// [`Display`](fmt::Display) rendering is stable and deterministic: every set
221/// borrowed from a hash map is sorted before it reaches the output.
222#[derive(Debug, Clone)]
223pub struct ContentModelReport {
224    /// Where the type came from and what kind of content it declares.
225    pub source: SourceView,
226    /// The resolved particle tree as the schema wrote it.
227    pub authored: AuthoredView,
228    /// The matcher the validator executes.
229    pub compiled: CompiledView,
230}
231
232/// Identity and declaration-level facts about the inspected type.
233#[derive(Debug, Clone)]
234pub struct SourceView {
235    /// `{namespace}local`, or `(anonymous)` for an unnamed local type.
236    pub type_name: String,
237    /// Base URI of the schema document, when a location is available.
238    pub document: Option<String>,
239    /// 1-based line of the type definition, when a location is available.
240    pub line: Option<usize>,
241    /// 1-based column of the type definition, when a location is available.
242    pub column: Option<usize>,
243    /// Content type as the validator determines it.
244    pub content_type: ContentType,
245    /// The type's `mixed` flag as declared.
246    pub mixed: bool,
247    /// `extension of {ns}Base` / `restriction of {ns}Base`, when derived.
248    pub derivation: Option<String>,
249    /// Effective open content carried by the compiled matcher (XSD 1.1).
250    pub open_content: Option<OpenContentView>,
251    /// XSD version the schema set is configured for.
252    pub xsd_version: XsdVersion,
253}
254
255/// The authored particle tree, in compiler concatenation order.
256#[derive(Debug, Clone, Default)]
257pub struct AuthoredView {
258    /// One section per contributing type: for an extension chain the
259    /// outermost base comes first and the inspected type's own particle last,
260    /// matching the order [`compile_content_model_matcher`] concatenates them.
261    pub sections: Vec<AuthoredSection>,
262}
263
264/// One contributing type's authored particle.
265#[derive(Debug, Clone)]
266pub struct AuthoredSection {
267    /// `None` for the inspected type's own content; `Some(name)` when this
268    /// section is inherited from a base type through extension.
269    pub from_base_type: Option<String>,
270    /// The root particle, or `None` when the type declares no particle.
271    pub root: Option<AuthoredNode>,
272}
273
274/// One node of the authored particle tree.
275#[derive(Debug, Clone)]
276pub struct AuthoredNode {
277    /// What this particle is.
278    pub kind: AuthoredKind,
279    /// `minOccurs`.
280    pub min_occurs: u32,
281    /// `maxOccurs`; `None` is `unbounded`.
282    pub max_occurs: Option<u32>,
283    /// How the compiler realises this occurrence range.
284    pub occurrence: OccurrenceCompilation,
285    /// `file:line:column`, when the particle carries a source location.
286    pub origin: Option<String>,
287    /// Child particles (compositors and expanded group references).
288    pub children: Vec<AuthoredNode>,
289}
290
291/// The kind of an authored particle.
292#[derive(Debug, Clone)]
293pub enum AuthoredKind {
294    /// `xs:sequence`.
295    Sequence,
296    /// `xs:choice`.
297    Choice,
298    /// `xs:all`.
299    All,
300    /// `xs:group ref="..."`, expanded inline below this node.
301    GroupRef(GroupRefView),
302    /// An element particle.
303    Element(ElementTermView),
304    /// An `xs:any` wildcard.
305    Wildcard(WildcardTermView),
306}
307
308/// A resolved named model group reference.
309#[derive(Debug, Clone)]
310pub struct GroupRefView {
311    /// `{namespace}local` of the referenced group.
312    pub name: String,
313    /// Compositor of the referenced group, when it resolved.
314    pub compositor: Option<Compositor>,
315    /// `false` when the reference could not be resolved in this schema set.
316    pub resolved: bool,
317    /// `true` when expansion stopped because the group references itself.
318    pub recursive: bool,
319}
320
321/// How the compiler realises an occurrence range.
322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
323pub enum OccurrenceCompilation {
324    /// `1..1`: nothing to repeat.
325    Single,
326    /// `maxOccurs` ≤ `COUNTED_THRESHOLD` (or unbounded with a small
327    /// `minOccurs`): the fragment is cloned into the automaton.
328    Unrolled,
329    /// Above the threshold: counter transitions enforce the bound exactly.
330    Counted,
331    /// Inside an all-group model: the bound is enforced by the all-group's own
332    /// per-particle counter, not by the NFA.
333    AllGroupCounter,
334}
335
336impl fmt::Display for OccurrenceCompilation {
337    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338        let s = match self {
339            OccurrenceCompilation::Single => "single",
340            OccurrenceCompilation::Unrolled => "unrolled",
341            OccurrenceCompilation::Counted => "counter",
342            OccurrenceCompilation::AllGroupCounter => "all-group counter",
343        };
344        f.write_str(s)
345    }
346}
347
348/// The matcher the validator executes for this type.
349#[derive(Debug, Clone)]
350pub enum CompiledView {
351    /// An NFA, possibly carrying an open-content wildcard.
352    Nfa(NfaView),
353    /// An all-group model (unordered particles).
354    AllGroup(AllGroupView),
355    /// The validator could not prepare a model for this type.
356    Failed {
357        /// The compiler error or execution-limit message.
358        reason: String,
359    },
360}
361
362impl CompiledView {
363    /// Note that the validator holds no prepared model for this type, so the
364    /// view below was compiled on demand.
365    fn mark_not_prepared(&mut self) {
366        let note = "compiled on demand: the validator prepares no model for this content type";
367        match self {
368            CompiledView::Nfa(view) => view.note = Some(note.to_string()),
369            CompiledView::AllGroup(view) => view.note = Some(note.to_string()),
370            CompiledView::Failed { .. } => {}
371        }
372    }
373
374    /// The matcher kind, in the vocabulary the compiler uses.
375    pub fn matcher_kind(&self) -> &str {
376        match self {
377            CompiledView::Nfa(view) => &view.matcher,
378            CompiledView::AllGroup(view) => &view.matcher,
379            CompiledView::Failed { .. } => "(preparation failed)",
380        }
381    }
382}
383
384/// A compiled NFA content model.
385#[derive(Debug, Clone)]
386pub struct NfaView {
387    /// `NFA`, or `NFA + open content (interleave|suffix)`.
388    pub matcher: String,
389    /// Number of states in the table.
390    pub state_count: usize,
391    /// Total number of transitions across all states.
392    pub transition_count: usize,
393    /// Counter definitions, in counter-id order.
394    pub counters: Vec<CounterView>,
395    /// The initial frontier variant, or the limit it exceeded.
396    pub frontier: FrontierView,
397    /// One row per state, in state-id order.
398    pub states: Vec<StateRow>,
399    /// Substitution groups reachable from this model's element terms, sorted.
400    pub substitution_groups: Vec<SubstitutionGroupView>,
401    /// Effective open content, when the matcher carries one.
402    pub open_content: Option<OpenContentView>,
403    /// Whether this model can reach [`MAX_ACTIVE_CONFIGS`].
404    pub exposure: ExposureView,
405    /// Free-form note about how this view was obtained.
406    pub note: Option<String>,
407}
408
409/// One counted loop of an NFA.
410#[derive(Debug, Clone, Copy)]
411pub struct CounterView {
412    /// Counter id; printed as `c{id}`.
413    pub id: CounterId,
414    /// Minimum completed iterations required to exit the loop.
415    pub min: u32,
416    /// Maximum iterations the loop may run.
417    pub max: u32,
418    /// Whether the loop body can be traversed without consuming input.
419    pub body_nullable: bool,
420}
421
422/// The initial frontier [`ActiveStates::try_from_nfa`] produces.
423#[derive(Debug, Clone)]
424pub enum FrontierView {
425    /// Counter-free NFA: a plain state bitset.
426    Simple {
427        /// States in the start-state epsilon closure.
428        states: usize,
429    },
430    /// Scalar counted configurations.
431    Counted {
432        /// Configurations in the initial closure.
433        configs: usize,
434    },
435    /// Single nullable counter collapsed into per-state ranges.
436    RangedSingle {
437        /// States carrying a counter range.
438        states: usize,
439    },
440    /// One ranged counter plus scalar companions.
441    Hybrid {
442        /// Configurations in the initial closure.
443        configs: usize,
444        /// Index of the counter chosen for ranging.
445        ranged_counter: usize,
446    },
447    /// The initial closure itself exceeded an execution limit.
448    LimitExceeded {
449        /// The limit message.
450        message: String,
451    },
452}
453
454impl fmt::Display for FrontierView {
455    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
456        match self {
457            FrontierView::Simple { states } => write!(f, "Simple({states} states)"),
458            FrontierView::Counted { configs } => write!(f, "Counted({configs} configs)"),
459            FrontierView::RangedSingle { states } => write!(f, "RangedSingle({states} states)"),
460            FrontierView::Hybrid {
461                configs,
462                ranged_counter,
463            } => write!(
464                f,
465                "Hybrid(ranged counter c{ranged_counter}, {configs} configs)"
466            ),
467            FrontierView::LimitExceeded { message } => write!(f, "unavailable: {message}"),
468        }
469    }
470}
471
472/// One row of the NFA state table.
473#[derive(Debug, Clone)]
474pub struct StateRow {
475    /// State id, as used inside the automaton.
476    pub id: StateId,
477    /// `true` for the start state.
478    pub start: bool,
479    /// `true` for the accepting state.
480    pub accept: bool,
481    /// The term a consuming transition into this state must match.
482    pub term: Option<TermView>,
483    /// Outgoing transitions, in declaration order.
484    pub transitions: Vec<String>,
485    /// `file:line:column`, when the state carries an origin.
486    pub origin: Option<String>,
487}
488
489/// An element or wildcard term.
490#[derive(Debug, Clone)]
491pub enum TermView {
492    /// A specific element.
493    Element(ElementTermView),
494    /// A wildcard.
495    Wildcard(WildcardTermView),
496}
497
498impl fmt::Display for TermView {
499    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500        match self {
501            TermView::Element(e) => write!(f, "{e}"),
502            TermView::Wildcard(w) => write!(f, "{w}"),
503        }
504    }
505}
506
507/// An element term with its resolved bindings.
508#[derive(Debug, Clone)]
509pub struct ElementTermView {
510    /// `{namespace}local`.
511    pub name: String,
512    /// How the declaration resolved.
513    pub declaration: DeclarationBinding,
514    /// The governing type's name, when it resolved.
515    pub type_name: Option<String>,
516    /// Other element names this term accepts through substitution, sorted.
517    /// Empty when the term matches only its own name.
518    pub substitutable: Vec<String>,
519}
520
521impl fmt::Display for ElementTermView {
522    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523        write!(f, "element {}", self.name)?;
524        if let Some(ty) = &self.type_name {
525            write!(f, " : {ty}")?;
526        }
527        write!(f, " [{}", self.declaration)?;
528        if !self.substitutable.is_empty() {
529            write!(f, ", +{} substitutable", self.substitutable.len() - 1)?;
530        }
531        f.write_str("]")
532    }
533}
534
535/// How an element particle's declaration resolved.
536#[derive(Debug, Clone, Copy, PartialEq, Eq)]
537pub enum DeclarationBinding {
538    /// Resolved to a global (top-level) element declaration.
539    Global,
540    /// Resolved to a local element declaration inside this content model.
541    Local,
542    /// No declaration key: the term matches by name only.
543    Unresolved,
544}
545
546impl fmt::Display for DeclarationBinding {
547    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
548        let s = match self {
549            DeclarationBinding::Global => "global decl",
550            DeclarationBinding::Local => "local decl",
551            DeclarationBinding::Unresolved => "no decl",
552        };
553        f.write_str(s)
554    }
555}
556
557/// A wildcard term.
558#[derive(Debug, Clone)]
559pub struct WildcardTermView {
560    /// Namespace constraint, in schema spelling (`##any`, `##other`, a list…).
561    pub namespace: String,
562    /// `strict` / `lax` / `skip`.
563    pub process_contents: &'static str,
564    /// Excluded QNames (XSD 1.1 `notQName`), sorted.
565    pub not_qnames: Vec<String>,
566}
567
568impl fmt::Display for WildcardTermView {
569    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
570        write!(
571            f,
572            "any {} [processContents={}]",
573            self.namespace, self.process_contents
574        )?;
575        if !self.not_qnames.is_empty() {
576            write!(f, " notQName={{{}}}", self.not_qnames.join(" "))?;
577        }
578        Ok(())
579    }
580}
581
582/// A substitution group reachable from a content model's element terms.
583#[derive(Debug, Clone)]
584pub struct SubstitutionGroupView {
585    /// The head element's `{namespace}local`.
586    pub head: String,
587    /// Every name the head's term accepts, sorted (the head included when it
588    /// is not abstract).
589    pub accepts: Vec<String>,
590}
591
592/// A compiled all-group model.
593#[derive(Debug, Clone)]
594pub struct AllGroupView {
595    /// `all-group`, or `all-group + open content (interleave|suffix)`.
596    pub matcher: String,
597    /// `true` when the whole group is optional (`minOccurs="0"` outside).
598    pub outer_optional: bool,
599    /// Members, in declaration order.
600    pub members: Vec<AllMemberView>,
601    /// Members with `minOccurs > 0`, in declaration order.
602    pub required: Vec<String>,
603    /// Substitution groups reachable from the members, sorted.
604    pub substitution_groups: Vec<SubstitutionGroupView>,
605    /// Open content carried by the model.
606    pub open_content: Option<OpenContentView>,
607    /// Free-form note about how this view was obtained.
608    pub note: Option<String>,
609}
610
611/// One member of an all-group.
612#[derive(Debug, Clone)]
613pub struct AllMemberView {
614    /// The member's term.
615    pub term: TermView,
616    /// `minOccurs`.
617    pub min_occurs: u32,
618    /// `maxOccurs`; `None` is `unbounded`.
619    pub max_occurs: Option<u32>,
620    /// `file:line:column`, when the member carries an origin.
621    pub origin: Option<String>,
622}
623
624/// Effective open content of a content model (XSD 1.1).
625#[derive(Debug, Clone)]
626pub struct OpenContentView {
627    /// `none` / `interleave` / `suffix`.
628    pub mode: &'static str,
629    /// The open-content wildcard, when one is present.
630    pub wildcard: Option<WildcardTermView>,
631}
632
633impl fmt::Display for OpenContentView {
634    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
635        write!(f, "{}", self.mode)?;
636        if let Some(w) = &self.wildcard {
637            write!(f, ", {w}")?;
638        }
639        Ok(())
640    }
641}
642
643/// Whether this model can hit [`MAX_ACTIVE_CONFIGS`] during validation.
644#[derive(Debug, Clone)]
645pub struct ExposureView {
646    /// `true` when the NFA has no counters at all.
647    pub counter_free: bool,
648    /// Total number of counters.
649    pub counter_count: usize,
650    /// Counters whose loop body is nullable — the shape that multiplies
651    /// configurations.
652    pub nullable_counters: Vec<CounterId>,
653}
654
655impl fmt::Display for ExposureView {
656    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
657        if self.counter_free {
658            return write!(
659                f,
660                "counter-free — one configuration per state, MAX_ACTIVE_CONFIGS ({MAX_ACTIVE_CONFIGS}) unreachable"
661            );
662        }
663        write!(f, "{} counter(s)", self.counter_count)?;
664        if self.nullable_counters.is_empty() {
665            write!(
666                f,
667                ", no nullable body — configurations stay bounded by the loop structure"
668            )
669        } else {
670            let list = self
671                .nullable_counters
672                .iter()
673                .map(|c| format!("c{c}"))
674                .collect::<Vec<_>>()
675                .join(", ");
676            write!(
677                f,
678                ", nullable body in {list} — this model can reach MAX_ACTIVE_CONFIGS ({MAX_ACTIVE_CONFIGS})"
679            )
680        }
681    }
682}
683
684// ---------------------------------------------------------------------------
685// Source view
686// ---------------------------------------------------------------------------
687
688fn source_view(
689    schema_set: &SchemaSet,
690    ct_data: &ComplexTypeDefData,
691    compiled: &CompiledView,
692) -> SourceView {
693    let type_name = match ct_data.name {
694        Some(name) => qname(schema_set, ct_data.target_namespace, name),
695        None => "(anonymous)".to_string(),
696    };
697    let location = schema_set.locate(ct_data.source.as_ref());
698    let derivation = ct_data.derivation_method.map(|method| {
699        let verb = match method {
700            DerivationMethod::Extension => "extension",
701            DerivationMethod::Restriction => "restriction",
702        };
703        match ct_data.resolved_base_type {
704            Some(key) => format!("{verb} of {}", type_key_name(schema_set, key)),
705            None => format!("{verb} of (unresolved base)"),
706        }
707    });
708    let open_content = match compiled {
709        CompiledView::Nfa(view) => view.open_content.clone(),
710        CompiledView::AllGroup(view) => view.open_content.clone(),
711        CompiledView::Failed { .. } => None,
712    };
713    SourceView {
714        type_name,
715        document: location.as_ref().map(|l| l.base_uri.clone()),
716        line: location.as_ref().map(|l| l.line),
717        column: location.as_ref().map(|l| l.column),
718        content_type: crate::validation::runtime::determine_content_type(schema_set, ct_data),
719        mixed: ct_data.mixed,
720        derivation,
721        open_content,
722        xsd_version: schema_set.xsd_version,
723    }
724}
725
726// ---------------------------------------------------------------------------
727// Authored view
728// ---------------------------------------------------------------------------
729
730fn authored_view(
731    schema_set: &SchemaSet,
732    ct_data: &ComplexTypeDefData,
733    subst: Option<&SubstitutionGroupMap>,
734    compiled: &CompiledView,
735) -> AuthoredView {
736    let all_group_model = matches!(compiled, CompiledView::AllGroup(_));
737
738    let mut sections = Vec::new();
739    collect_sections(
740        schema_set,
741        ct_data,
742        subst,
743        all_group_model,
744        None,
745        0,
746        &mut sections,
747    );
748    AuthoredView { sections }
749}
750
751fn collect_sections(
752    schema_set: &SchemaSet,
753    ct_data: &ComplexTypeDefData,
754    subst: Option<&SubstitutionGroupMap>,
755    all_group_model: bool,
756    owner: Option<String>,
757    depth: usize,
758    out: &mut Vec<AuthoredSection>,
759) {
760    if depth >= MAX_REPORT_DEPTH {
761        return;
762    }
763    // An extension prepends its base type's content, so the base's authored
764    // particle is shown first — the order the compiler concatenates them in.
765    if matches!(ct_data.derivation_method, Some(DerivationMethod::Extension)) {
766        if let Some(TypeKey::Complex(base_key)) = ct_data.resolved_base_type {
767            if let Some(base_data) = schema_set.arenas.get_complex_type(base_key) {
768                let base_name = complex_type_name(schema_set, base_data);
769                collect_sections(
770                    schema_set,
771                    base_data,
772                    subst,
773                    all_group_model,
774                    Some(base_name),
775                    depth + 1,
776                    out,
777                );
778            }
779        }
780    }
781
782    let particle = match &ct_data.content {
783        ComplexContentResult::Complex(def) => def.particle.as_ref(),
784        ComplexContentResult::Empty | ComplexContentResult::Simple(_) => None,
785    };
786    let root = particle.map(|p| {
787        let mut walker = ParticleWalker {
788            schema_set,
789            target_namespace: ct_data.target_namespace,
790            subst,
791            all_group_model,
792            flat_idx: 0,
793            resolved_types: ct_data.resolved_content_particle_types.clone(),
794            resolved_elements: ct_data.resolved_content_particle_elements.clone(),
795            depth: 0,
796            group_path: Vec::new(),
797        };
798        walker.walk(p, false)
799    });
800    out.push(AuthoredSection {
801        from_base_type: owner,
802        root,
803    });
804}
805
806/// Walks authored particles in the same depth-first order the compiler does, so
807/// the flat `resolved_content_particle_*` indices line up with the elements it
808/// reports.
809struct ParticleWalker<'a> {
810    schema_set: &'a SchemaSet,
811    target_namespace: Option<NameId>,
812    subst: Option<&'a SubstitutionGroupMap>,
813    /// `true` when the compiled matcher for this type is an all-group model,
814    /// in which case the top-level group's members are counted by the
815    /// all-group state rather than unrolled into an automaton.
816    all_group_model: bool,
817    flat_idx: usize,
818    resolved_types: Vec<Option<TypeKey>>,
819    resolved_elements: Vec<Option<ElementKey>>,
820    depth: usize,
821    group_path: Vec<ModelGroupKey>,
822}
823
824impl ParticleWalker<'_> {
825    fn walk(&mut self, particle: &ParticleResult, all_mode: bool) -> AuthoredNode {
826        let is_root = self.depth == 0;
827        let origin = short_location(self.schema_set, particle.source.as_ref());
828        let occurrence = if all_mode {
829            OccurrenceCompilation::AllGroupCounter
830        } else {
831            classify_occurs(particle.min_occurs, particle.max_occurs)
832        };
833
834        let (kind, children) = match &particle.term {
835            ParticleTerm::Element(elem) => (
836                AuthoredKind::Element(self.element_term(elem, particle.source.as_ref())),
837                Vec::new(),
838            ),
839            ParticleTerm::Any(wildcard) => (
840                AuthoredKind::Wildcard(authored_wildcard(self.schema_set, wildcard)),
841                Vec::new(),
842            ),
843            ParticleTerm::Group(group) => self.walk_group(group, is_root, all_mode),
844        };
845
846        AuthoredNode {
847            kind,
848            min_occurs: particle.min_occurs,
849            max_occurs: particle.max_occurs,
850            occurrence,
851            origin,
852            children,
853        }
854    }
855
856    fn walk_group(
857        &mut self,
858        group: &ModelGroupDefResult,
859        is_root: bool,
860        all_mode: bool,
861    ) -> (AuthoredKind, Vec<AuthoredNode>) {
862        // A named reference: expand the referenced group inline, but keep the
863        // node labelled as a reference and swap in the group's own flat
864        // resolution arrays — exactly what `compile_model_group_data` does.
865        if let Some(ref_name) = &group.ref_name {
866            let name = qname(self.schema_set, ref_name.namespace, ref_name.local_name);
867            // Inside a group `xs:redefine` redefines, a reference to its own
868            // name is the original group (`SchemaSet::model_group_ref_within`).
869            let key = self.schema_set.model_group_ref_within(
870                self.group_path.last().copied(),
871                ref_name.namespace,
872                ref_name.local_name,
873            );
874            let Some(key) = key else {
875                return (
876                    AuthoredKind::GroupRef(GroupRefView {
877                        name,
878                        compositor: None,
879                        resolved: false,
880                        recursive: false,
881                    }),
882                    Vec::new(),
883                );
884            };
885            if self.group_path.contains(&key) || self.depth >= MAX_REPORT_DEPTH {
886                return (
887                    AuthoredKind::GroupRef(GroupRefView {
888                        name,
889                        compositor: None,
890                        resolved: true,
891                        recursive: true,
892                    }),
893                    Vec::new(),
894                );
895            }
896            let Some(data) = self.schema_set.arenas.get_model_group(key) else {
897                return (
898                    AuthoredKind::GroupRef(GroupRefView {
899                        name,
900                        compositor: None,
901                        resolved: false,
902                        recursive: false,
903                    }),
904                    Vec::new(),
905                );
906            };
907
908            let saved_flat = std::mem::replace(&mut self.flat_idx, 0);
909            let saved_types = std::mem::replace(
910                &mut self.resolved_types,
911                data.resolved_particle_types.clone(),
912            );
913            let saved_elements = std::mem::replace(
914                &mut self.resolved_elements,
915                data.resolved_particle_elements.clone(),
916            );
917            self.group_path.push(key);
918            let child_all = all_mode || (self.all_group_model && is_root);
919            let children = self.walk_children(&data.particles, child_all);
920            self.group_path.pop();
921            self.flat_idx = saved_flat;
922            self.resolved_types = saved_types;
923            self.resolved_elements = saved_elements;
924
925            return (
926                AuthoredKind::GroupRef(GroupRefView {
927                    name,
928                    compositor: Some(data.compositor.unwrap_or(Compositor::Sequence)),
929                    resolved: true,
930                    recursive: false,
931                }),
932                children,
933            );
934        }
935
936        let compositor = group.compositor.unwrap_or(Compositor::Sequence);
937        let kind = match compositor {
938            Compositor::Sequence => AuthoredKind::Sequence,
939            Compositor::Choice => AuthoredKind::Choice,
940            Compositor::All => AuthoredKind::All,
941        };
942        let child_all =
943            all_mode || (self.all_group_model && is_root && compositor == Compositor::All);
944        let children = self.walk_children(&group.particles, child_all);
945        (kind, children)
946    }
947
948    fn walk_children(&mut self, particles: &[ParticleResult], all_mode: bool) -> Vec<AuthoredNode> {
949        self.depth += 1;
950        let children = particles
951            .iter()
952            .map(|p| self.walk(p, all_mode))
953            .collect::<Vec<_>>();
954        self.depth -= 1;
955        children
956    }
957
958    /// Mirrors `CompileContext::build_element_term`: the same name/namespace
959    /// resolution and the same flat depth-first index into the resolved arrays.
960    fn element_term(
961        &mut self,
962        elem: &ElementFrameResult,
963        source: Option<&SourceRef>,
964    ) -> ElementTermView {
965        let flat_idx = self.flat_idx;
966        self.flat_idx += 1;
967
968        let (name, namespace, element_key) = if let Some(ref_name) = &elem.ref_name {
969            let key = self
970                .schema_set
971                .lookup_element(ref_name.namespace, ref_name.local_name);
972            (ref_name.local_name, ref_name.namespace, key)
973        } else if let Some(name) = elem.name {
974            let source_ref = source.or(elem.source.as_ref());
975            let namespace = self.schema_set.effective_local_element_namespace(
976                elem.target_namespace,
977                elem.form.as_deref(),
978                source_ref,
979                self.target_namespace,
980            );
981            let key = self.resolved_elements.get(flat_idx).copied().flatten();
982            (name, namespace, key)
983        } else {
984            // `build_element_term` errors here; the report just says so.
985            return ElementTermView {
986                name: "(anonymous element without name or ref)".to_string(),
987                declaration: DeclarationBinding::Unresolved,
988                type_name: None,
989                substitutable: Vec::new(),
990            };
991        };
992
993        let resolved_type = if element_key.is_none() {
994            self.resolved_types
995                .get(flat_idx)
996                .copied()
997                .flatten()
998                .or_else(|| match &elem.type_ref {
999                    Some(TypeRefResult::QName(q)) => self
1000                        .schema_set
1001                        .lookup_type(q.namespace, q.local_name)
1002                        .or_else(|| {
1003                            self.schema_set
1004                                .get_built_in_type_by_qname(q.namespace, q.local_name)
1005                        }),
1006                    _ => None,
1007                })
1008        } else {
1009            None
1010        };
1011
1012        element_view(
1013            self.schema_set,
1014            self.subst,
1015            name,
1016            namespace,
1017            element_key,
1018            resolved_type,
1019        )
1020    }
1021}
1022
1023fn classify_occurs(min: u32, max: Option<u32>) -> OccurrenceCompilation {
1024    // Mirrors `apply_occurs`.
1025    match max {
1026        Some(1) if min == 1 => OccurrenceCompilation::Single,
1027        None if min > COUNTED_THRESHOLD => OccurrenceCompilation::Counted,
1028        None => OccurrenceCompilation::Unrolled,
1029        Some(m) if m <= COUNTED_THRESHOLD => OccurrenceCompilation::Unrolled,
1030        Some(_) => OccurrenceCompilation::Counted,
1031    }
1032}
1033
1034fn authored_wildcard(schema_set: &SchemaSet, wildcard: &WildcardResult) -> WildcardTermView {
1035    let namespace = if wildcard.not_namespace.is_empty() {
1036        match &wildcard.namespace {
1037            WildcardNamespace::Any => "##any".to_string(),
1038            WildcardNamespace::Other => "##other".to_string(),
1039            WildcardNamespace::TargetNamespace => "##targetNamespace".to_string(),
1040            WildcardNamespace::Local => "##local".to_string(),
1041            WildcardNamespace::List(tokens) => namespace_token_list(schema_set, tokens),
1042        }
1043    } else {
1044        format!(
1045            "notNamespace={}",
1046            namespace_token_list(schema_set, &wildcard.not_namespace)
1047        )
1048    };
1049    let mut not_qnames: Vec<String> = wildcard
1050        .not_qname
1051        .iter()
1052        .map(|item| match item {
1053            NotQNameItem::QName {
1054                namespace,
1055                local_name,
1056            } => qname(schema_set, *namespace, *local_name),
1057            NotQNameItem::Defined => "##defined".to_string(),
1058            NotQNameItem::DefinedSibling => "##definedSibling".to_string(),
1059        })
1060        .collect();
1061    not_qnames.sort();
1062    WildcardTermView {
1063        namespace,
1064        process_contents: frame_process_contents(wildcard.process_contents),
1065        not_qnames,
1066    }
1067}
1068
1069fn namespace_token_list(schema_set: &SchemaSet, tokens: &[NamespaceToken]) -> String {
1070    let mut names: Vec<String> = tokens
1071        .iter()
1072        .map(|t| match t {
1073            NamespaceToken::Uri(id) => schema_set.name_table.resolve(*id),
1074            NamespaceToken::Local => "##local".to_string(),
1075            NamespaceToken::TargetNamespace => "##targetNamespace".to_string(),
1076        })
1077        .collect();
1078    names.sort();
1079    format!("{{{}}}", names.join(" "))
1080}
1081
1082fn frame_process_contents(pc: crate::parser::frames::ProcessContents) -> &'static str {
1083    use crate::parser::frames::ProcessContents as P;
1084    match pc {
1085        P::Strict => "strict",
1086        P::Lax => "lax",
1087        P::Skip => "skip",
1088    }
1089}
1090
1091// ---------------------------------------------------------------------------
1092// Compiled view
1093// ---------------------------------------------------------------------------
1094
1095fn compiled_view_from_matcher(
1096    schema_set: &SchemaSet,
1097    subst: Option<&SubstitutionGroupMap>,
1098    matcher: &ContentModelMatcher,
1099) -> CompiledView {
1100    match matcher {
1101        ContentModelMatcher::Nfa(nfa) => {
1102            CompiledView::Nfa(nfa_view(schema_set, subst, nfa, None, frontier_of(nfa)))
1103        }
1104        ContentModelMatcher::WithOpenContent {
1105            nfa,
1106            mode,
1107            wildcard,
1108        } => {
1109            let oc = open_content_from_wildcard(schema_set, *mode, wildcard.as_ref());
1110            CompiledView::Nfa(nfa_view(schema_set, subst, nfa, oc, frontier_of(nfa)))
1111        }
1112        ContentModelMatcher::AllGroup(model) => {
1113            CompiledView::AllGroup(all_group_view(schema_set, subst, model))
1114        }
1115    }
1116}
1117
1118fn compiled_view_from_prepared(
1119    schema_set: &SchemaSet,
1120    subst: Option<&SubstitutionGroupMap>,
1121    model: &CompiledContentModel,
1122) -> CompiledView {
1123    match model {
1124        CompiledContentModel::Nfa { nfa, initial } => CompiledView::Nfa(nfa_view(
1125            schema_set,
1126            subst,
1127            nfa,
1128            None,
1129            frontier_from(initial),
1130        )),
1131        CompiledContentModel::NfaWithOpenContent {
1132            nfa,
1133            initial,
1134            open_content,
1135        } => {
1136            let oc = open_content.as_ref().map(|info| OpenContentView {
1137                mode: types_open_content_mode(info.mode),
1138                wildcard: Some(WildcardTermView {
1139                    namespace: namespace_constraint_name(schema_set, &info.namespace_constraint),
1140                    process_contents: process_contents_name(info.process_contents),
1141                    not_qnames: qname_pairs(schema_set, &info.not_qnames),
1142                }),
1143            });
1144            CompiledView::Nfa(nfa_view(schema_set, subst, nfa, oc, frontier_from(initial)))
1145        }
1146        CompiledContentModel::AllGroup(model) => {
1147            CompiledView::AllGroup(all_group_view(schema_set, subst, model))
1148        }
1149    }
1150}
1151
1152fn nfa_view(
1153    schema_set: &SchemaSet,
1154    subst: Option<&SubstitutionGroupMap>,
1155    nfa: &NfaTable,
1156    open_content: Option<OpenContentView>,
1157    frontier: FrontierView,
1158) -> NfaView {
1159    let matcher = match &open_content {
1160        Some(oc) if oc.wildcard.is_some() => format!("NFA + open content ({})", oc.mode),
1161        _ => "NFA".to_string(),
1162    };
1163    let counters: Vec<CounterView> = nfa
1164        .counter_defs
1165        .iter()
1166        .enumerate()
1167        .map(|(i, def)| counter_view(i, def))
1168        .collect();
1169    let mut transition_count = 0;
1170    let mut states = Vec::with_capacity(nfa.states.len());
1171    let mut groups: Vec<SubstitutionGroupView> = Vec::new();
1172    for state in &nfa.states {
1173        transition_count += state.transitions.len();
1174        let term = state
1175            .term
1176            .as_ref()
1177            .map(|t| term_view(schema_set, subst, t, &mut groups));
1178        states.push(StateRow {
1179            id: state.id,
1180            start: state.id == nfa.start_state,
1181            accept: state.id == nfa.accept_state,
1182            term,
1183            transitions: state
1184                .transitions
1185                .iter()
1186                .map(|t| format_transition(t.kind, t.target))
1187                .collect(),
1188            origin: short_location(schema_set, state.origin.as_ref()),
1189        });
1190    }
1191    dedup_groups(&mut groups);
1192    let nullable_counters = counters
1193        .iter()
1194        .filter(|c| c.body_nullable)
1195        .map(|c| c.id)
1196        .collect();
1197    let exposure = ExposureView {
1198        counter_free: counters.is_empty(),
1199        counter_count: counters.len(),
1200        nullable_counters,
1201    };
1202    NfaView {
1203        matcher,
1204        state_count: nfa.states.len(),
1205        transition_count,
1206        counters,
1207        frontier,
1208        states,
1209        substitution_groups: groups,
1210        open_content,
1211        exposure,
1212        note: None,
1213    }
1214}
1215
1216fn counter_view(index: usize, def: &CounterDef) -> CounterView {
1217    CounterView {
1218        id: index as CounterId,
1219        min: def.min,
1220        max: def.max,
1221        body_nullable: def.body_nullable,
1222    }
1223}
1224
1225fn all_group_view(
1226    schema_set: &SchemaSet,
1227    subst: Option<&SubstitutionGroupMap>,
1228    model: &AllGroupModel,
1229) -> AllGroupView {
1230    let open_content = model.open_content.as_ref().map(|oc| OpenContentView {
1231        mode: all_group_open_content_mode(oc.mode),
1232        wildcard: Some(WildcardTermView {
1233            namespace: namespace_constraint_name(schema_set, &oc.namespace_constraint),
1234            process_contents: process_contents_name(oc.process_contents),
1235            not_qnames: qname_pairs(schema_set, &oc.not_qnames),
1236        }),
1237    });
1238    let matcher = match &open_content {
1239        Some(oc) if oc.wildcard.is_some() => format!("all-group + open content ({})", oc.mode),
1240        _ => "all-group".to_string(),
1241    };
1242    let mut groups: Vec<SubstitutionGroupView> = Vec::new();
1243    let mut members = Vec::with_capacity(model.particles.len());
1244    let mut required = Vec::new();
1245    for particle in &model.particles {
1246        let term = term_view(schema_set, subst, &particle.term, &mut groups);
1247        if particle.min_occurs > 0 {
1248            required.push(term.to_string());
1249        }
1250        members.push(AllMemberView {
1251            term,
1252            min_occurs: particle.min_occurs,
1253            max_occurs: particle.max_occurs.to_option(),
1254            origin: short_location(schema_set, particle.source.as_ref()),
1255        });
1256    }
1257    dedup_groups(&mut groups);
1258    AllGroupView {
1259        matcher,
1260        outer_optional: model.outer_optional,
1261        members,
1262        required,
1263        substitution_groups: groups,
1264        open_content,
1265        note: None,
1266    }
1267}
1268
1269fn frontier_of(nfa: &NfaTable) -> FrontierView {
1270    match ActiveStates::try_from_nfa(nfa) {
1271        Ok(active) => frontier_from(&active),
1272        Err(limit) => FrontierView::LimitExceeded {
1273            message: limit.to_string(),
1274        },
1275    }
1276}
1277
1278fn frontier_from(active: &ActiveStates) -> FrontierView {
1279    match active {
1280        ActiveStates::Simple(set) => FrontierView::Simple {
1281            states: set.iter().count(),
1282        },
1283        ActiveStates::Counted { configs, .. } => FrontierView::Counted {
1284            configs: configs.len(),
1285        },
1286        ActiveStates::RangedSingle { state_ranges, .. } => FrontierView::RangedSingle {
1287            states: state_ranges.len(),
1288        },
1289        ActiveStates::Hybrid {
1290            configs,
1291            ranged_counter_idx,
1292            ..
1293        } => FrontierView::Hybrid {
1294            configs: configs.len(),
1295            ranged_counter: *ranged_counter_idx,
1296        },
1297    }
1298}
1299
1300fn format_transition(kind: TransitionKind, target: StateId) -> String {
1301    match kind {
1302        TransitionKind::Epsilon => format!("ε → #{target}"),
1303        TransitionKind::Consume => format!("consume → #{target}"),
1304        TransitionKind::CounterReset(c) => format!("reset c{c} → #{target}"),
1305        TransitionKind::CounterIncrement(c) => format!("c{c}++ → #{target}"),
1306        TransitionKind::CounterMaxGuard(c) => format!("c{c}<max → #{target}"),
1307        TransitionKind::CounterMinGuard(c) => format!("c{c}>=min → #{target}"),
1308    }
1309}
1310
1311fn term_view(
1312    schema_set: &SchemaSet,
1313    subst: Option<&SubstitutionGroupMap>,
1314    term: &NfaTerm,
1315    groups: &mut Vec<SubstitutionGroupView>,
1316) -> TermView {
1317    match term {
1318        NfaTerm::Element {
1319            name,
1320            namespace,
1321            element_key,
1322            resolved_type,
1323        } => {
1324            let view = element_view(
1325                schema_set,
1326                subst,
1327                *name,
1328                *namespace,
1329                *element_key,
1330                *resolved_type,
1331            );
1332            if !view.substitutable.is_empty() {
1333                groups.push(SubstitutionGroupView {
1334                    head: view.name.clone(),
1335                    accepts: view.substitutable.clone(),
1336                });
1337            }
1338            TermView::Element(view)
1339        }
1340        NfaTerm::Wildcard {
1341            namespace_constraint,
1342            process_contents,
1343            not_qnames,
1344        } => TermView::Wildcard(WildcardTermView {
1345            namespace: namespace_constraint_name(schema_set, namespace_constraint),
1346            process_contents: process_contents_name(*process_contents),
1347            not_qnames: qname_pairs(schema_set, not_qnames),
1348        }),
1349    }
1350}
1351
1352fn element_view(
1353    schema_set: &SchemaSet,
1354    subst: Option<&SubstitutionGroupMap>,
1355    name: NameId,
1356    namespace: Option<NameId>,
1357    element_key: Option<ElementKey>,
1358    resolved_type: Option<TypeKey>,
1359) -> ElementTermView {
1360    let declaration = match element_key {
1361        None => DeclarationBinding::Unresolved,
1362        Some(key) => {
1363            if schema_set.lookup_element(namespace, name) == Some(key) {
1364                DeclarationBinding::Global
1365            } else {
1366                DeclarationBinding::Local
1367            }
1368        }
1369    };
1370    let type_key = match element_key {
1371        Some(key) => schema_set
1372            .arenas
1373            .get_element(key)
1374            .and_then(|decl| decl.resolved_type),
1375        None => resolved_type,
1376    };
1377    let substitutable = match (element_key, subst) {
1378        (Some(key), Some(map)) => match map.get(&key) {
1379            Some(names) => {
1380                let mut list: Vec<String> = names
1381                    .iter()
1382                    .map(|(local, ns)| qname(schema_set, *ns, *local))
1383                    .collect();
1384                list.sort();
1385                list
1386            }
1387            None => Vec::new(),
1388        },
1389        _ => Vec::new(),
1390    };
1391    ElementTermView {
1392        name: qname(schema_set, namespace, name),
1393        declaration,
1394        type_name: type_key.map(|k| type_key_name(schema_set, k)),
1395        substitutable,
1396    }
1397}
1398
1399fn dedup_groups(groups: &mut Vec<SubstitutionGroupView>) {
1400    groups.sort_by(|a, b| a.head.cmp(&b.head));
1401    groups.dedup_by(|a, b| a.head == b.head);
1402}
1403
1404fn open_content_from_wildcard(
1405    schema_set: &SchemaSet,
1406    mode: TypesOpenContentMode,
1407    wildcard: Option<&WildcardRef>,
1408) -> Option<OpenContentView> {
1409    Some(OpenContentView {
1410        mode: types_open_content_mode(mode),
1411        wildcard: Some(WildcardTermView {
1412            namespace: namespace_constraint_name(schema_set, &wildcard?.namespace_constraint),
1413            process_contents: process_contents_name(wildcard?.process_contents),
1414            not_qnames: qname_pairs(schema_set, &wildcard?.not_qnames),
1415        }),
1416    })
1417}
1418
1419fn types_open_content_mode(mode: TypesOpenContentMode) -> &'static str {
1420    match mode {
1421        TypesOpenContentMode::None => "none",
1422        TypesOpenContentMode::Interleave => "interleave",
1423        TypesOpenContentMode::Suffix => "suffix",
1424    }
1425}
1426
1427fn all_group_open_content_mode(mode: AllGroupOpenContentMode) -> &'static str {
1428    match mode {
1429        AllGroupOpenContentMode::None => "none",
1430        AllGroupOpenContentMode::Interleave => "interleave",
1431        AllGroupOpenContentMode::Suffix => "suffix",
1432    }
1433}
1434
1435fn process_contents_name(pc: ProcessContents) -> &'static str {
1436    match pc {
1437        ProcessContents::Strict => "strict",
1438        ProcessContents::Lax => "lax",
1439        ProcessContents::Skip => "skip",
1440    }
1441}
1442
1443fn namespace_constraint_name(schema_set: &SchemaSet, nc: &NamespaceConstraint) -> String {
1444    match nc {
1445        NamespaceConstraint::Any => "##any".to_string(),
1446        NamespaceConstraint::Other => "##other".to_string(),
1447        NamespaceConstraint::TargetNamespace => "##targetNamespace".to_string(),
1448        NamespaceConstraint::Local => "##local".to_string(),
1449        NamespaceConstraint::List(list) => format!("{{{}}}", namespace_list(schema_set, list)),
1450        NamespaceConstraint::Not(list) => {
1451            format!("notNamespace={{{}}}", namespace_list(schema_set, list))
1452        }
1453    }
1454}
1455
1456fn namespace_list(schema_set: &SchemaSet, list: &[Option<NameId>]) -> String {
1457    let mut names: Vec<String> = list
1458        .iter()
1459        .map(|ns| match ns {
1460            Some(id) => schema_set.name_table.resolve(*id),
1461            None => "##local".to_string(),
1462        })
1463        .collect();
1464    names.sort();
1465    names.join(" ")
1466}
1467
1468fn qname_pairs(schema_set: &SchemaSet, pairs: &[(Option<NameId>, NameId)]) -> Vec<String> {
1469    let mut names: Vec<String> = pairs
1470        .iter()
1471        .map(|(ns, local)| qname(schema_set, *ns, *local))
1472        .collect();
1473    names.sort();
1474    names.dedup();
1475    names
1476}
1477
1478// ---------------------------------------------------------------------------
1479// Name and location helpers
1480// ---------------------------------------------------------------------------
1481
1482/// Format an expanded name as `{namespace}local`, abbreviating the XSD
1483/// namespace to the conventional `xs:` prefix.
1484fn qname(schema_set: &SchemaSet, namespace: Option<NameId>, local: NameId) -> String {
1485    let local = schema_set.name_table.resolve(local);
1486    match namespace {
1487        None => local,
1488        Some(ns) => {
1489            let ns = schema_set.name_table.resolve(ns);
1490            if ns.is_empty() {
1491                local
1492            } else if ns == XS_NAMESPACE {
1493                format!("xs:{local}")
1494            } else {
1495                format!("{{{ns}}}{local}")
1496            }
1497        }
1498    }
1499}
1500
1501fn complex_type_name(schema_set: &SchemaSet, ct_data: &ComplexTypeDefData) -> String {
1502    match ct_data.name {
1503        Some(name) => qname(schema_set, ct_data.target_namespace, name),
1504        None => "(anonymous)".to_string(),
1505    }
1506}
1507
1508fn type_key_name(schema_set: &SchemaSet, key: TypeKey) -> String {
1509    match key {
1510        TypeKey::Complex(k) => match schema_set.arenas.get_complex_type(k) {
1511            Some(data) => complex_type_name(schema_set, data),
1512            None => "(unknown complex type)".to_string(),
1513        },
1514        TypeKey::Simple(k) => match schema_set.arenas.get_simple_type(k) {
1515            Some(data) => match data.name {
1516                Some(name) => qname(schema_set, data.target_namespace, name),
1517                None => "(anonymous simple type)".to_string(),
1518            },
1519            None => "(unknown simple type)".to_string(),
1520        },
1521    }
1522}
1523
1524/// `file.xsd:line:column` — the document's file name only, so state tables stay
1525/// narrow. The full base URI is in the Source view.
1526fn short_location(schema_set: &SchemaSet, source: Option<&SourceRef>) -> Option<String> {
1527    let loc = schema_set.locate(source)?;
1528    let file = loc.base_uri.rsplit('/').next().unwrap_or("");
1529    let file = if file.is_empty() {
1530        loc.base_uri.as_str()
1531    } else {
1532        file
1533    };
1534    Some(format!("{file}:{}:{}", loc.line, loc.column))
1535}
1536
1537fn occurs(min: u32, max: Option<u32>) -> String {
1538    match max {
1539        Some(m) => format!("{min}..{m}"),
1540        None => format!("{min}..unbounded"),
1541    }
1542}
1543
1544fn content_type_name(ct: ContentType) -> &'static str {
1545    match ct {
1546        ContentType::Empty => "empty",
1547        ContentType::TextOnly => "simple",
1548        ContentType::ElementOnly => "element-only",
1549        ContentType::Mixed => "mixed",
1550    }
1551}
1552
1553fn xsd_version_name(v: XsdVersion) -> &'static str {
1554    match v {
1555        XsdVersion::V1_0 => "1.0",
1556        XsdVersion::V1_1 => "1.1",
1557    }
1558}
1559
1560fn compositor_name(c: Compositor) -> &'static str {
1561    match c {
1562        Compositor::Sequence => "sequence",
1563        Compositor::Choice => "choice",
1564        Compositor::All => "all",
1565    }
1566}
1567
1568// ---------------------------------------------------------------------------
1569// Display
1570// ---------------------------------------------------------------------------
1571
1572const KEY_WIDTH: usize = 15;
1573
1574fn kv(f: &mut fmt::Formatter<'_>, key: &str, value: &str) -> fmt::Result {
1575    writeln!(f, "  {key:<KEY_WIDTH$}{value}")
1576}
1577
1578fn heading(f: &mut fmt::Formatter<'_>, title: &str) -> fmt::Result {
1579    writeln!(f, "{title}")?;
1580    writeln!(f, "{}", "-".repeat(title.len()))
1581}
1582
1583impl fmt::Display for ContentModelReport {
1584    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1585        writeln!(f, "Content model report: {}", self.source.type_name)?;
1586        writeln!(f)?;
1587        self.source.fmt(f)?;
1588        writeln!(f)?;
1589        self.authored.fmt(f)?;
1590        writeln!(f)?;
1591        self.compiled.fmt(f)
1592    }
1593}
1594
1595impl fmt::Display for SourceView {
1596    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1597        heading(f, "Source")?;
1598        kv(f, "type", &self.type_name)?;
1599        kv(
1600            f,
1601            "document",
1602            self.document.as_deref().unwrap_or("(no source location)"),
1603        )?;
1604        match (self.line, self.column) {
1605            (Some(line), Some(column)) => kv(f, "at", &format!("line {line}, column {column}"))?,
1606            _ => kv(f, "at", "(unknown)")?,
1607        }
1608        kv(f, "content type", content_type_name(self.content_type))?;
1609        kv(f, "mixed", if self.mixed { "yes" } else { "no" })?;
1610        kv(
1611            f,
1612            "derivation",
1613            self.derivation.as_deref().unwrap_or("(none)"),
1614        )?;
1615        match &self.open_content {
1616            Some(oc) => kv(f, "open content", &oc.to_string())?,
1617            None => kv(f, "open content", "(none)")?,
1618        }
1619        kv(f, "xsd version", xsd_version_name(self.xsd_version))
1620    }
1621}
1622
1623impl fmt::Display for AuthoredView {
1624    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1625        heading(f, "Authored particles")?;
1626        if self.sections.is_empty() {
1627            return writeln!(f, "  (no content particle)");
1628        }
1629        let multi = self.sections.len() > 1;
1630        for section in &self.sections {
1631            if let Some(base) = &section.from_base_type {
1632                writeln!(f, "  from base type {base} (prepended by extension):")?;
1633            } else if multi {
1634                writeln!(f, "  own content:")?;
1635            }
1636            let depth = usize::from(multi);
1637            match &section.root {
1638                Some(root) => write_node(f, root, depth)?,
1639                None => writeln!(f, "  {}(no content particle)", "  ".repeat(depth))?,
1640            }
1641        }
1642        Ok(())
1643    }
1644}
1645
1646fn write_node(f: &mut fmt::Formatter<'_>, node: &AuthoredNode, depth: usize) -> fmt::Result {
1647    let indent = "  ".repeat(depth + 1);
1648    let label = match &node.kind {
1649        AuthoredKind::Sequence => "sequence".to_string(),
1650        AuthoredKind::Choice => "choice".to_string(),
1651        AuthoredKind::All => "all".to_string(),
1652        AuthoredKind::GroupRef(g) => {
1653            let mut s = format!("group ref {}", g.name);
1654            if let Some(c) = g.compositor {
1655                s.push_str(&format!(" ({})", compositor_name(c)));
1656            }
1657            if !g.resolved {
1658                s.push_str(" [unresolved]");
1659            } else if g.recursive {
1660                s.push_str(" [recursive, not expanded]");
1661            }
1662            s
1663        }
1664        AuthoredKind::Element(e) => e.to_string(),
1665        AuthoredKind::Wildcard(w) => w.to_string(),
1666    };
1667    write!(
1668        f,
1669        "{indent}{label}  {}  [{}]",
1670        occurs(node.min_occurs, node.max_occurs),
1671        node.occurrence
1672    )?;
1673    match &node.origin {
1674        Some(origin) => writeln!(f, "  ({origin})")?,
1675        None => writeln!(f)?,
1676    }
1677    for child in &node.children {
1678        write_node(f, child, depth + 1)?;
1679    }
1680    Ok(())
1681}
1682
1683impl fmt::Display for CompiledView {
1684    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1685        heading(f, "Compiled")?;
1686        match self {
1687            CompiledView::Nfa(view) => view.fmt(f),
1688            CompiledView::AllGroup(view) => view.fmt(f),
1689            CompiledView::Failed { reason } => {
1690                kv(f, "matcher", "(none — preparation failed)")?;
1691                kv(f, "failure", reason)?;
1692                writeln!(
1693                    f,
1694                    "  the first element governed by this type raises \
1695                     validation-preparation-failed and aborts the run"
1696                )
1697            }
1698        }
1699    }
1700}
1701
1702impl fmt::Display for NfaView {
1703    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1704        kv(f, "matcher", &self.matcher)?;
1705        kv(f, "states", &self.state_count.to_string())?;
1706        kv(f, "transitions", &self.transition_count.to_string())?;
1707        if self.counters.is_empty() {
1708            kv(f, "counters", "(none)")?;
1709        } else {
1710            for c in &self.counters {
1711                let line = format!(
1712                    "c{}: {}..{}, body nullable? {}",
1713                    c.id,
1714                    c.min,
1715                    c.max,
1716                    if c.body_nullable { "yes" } else { "no" }
1717                );
1718                kv(f, if c.id == 0 { "counters" } else { "" }, &line)?;
1719            }
1720        }
1721        kv(f, "frontier", &self.frontier.to_string())?;
1722        if let Some(oc) = &self.open_content {
1723            kv(f, "open content", &oc.to_string())?;
1724        }
1725        kv(f, "exposure", &self.exposure.to_string())?;
1726        if let Some(note) = &self.note {
1727            kv(f, "note", note)?;
1728        }
1729        writeln!(f)?;
1730        write_state_table(f, &self.states)?;
1731        write_substitution_groups(f, &self.substitution_groups)
1732    }
1733}
1734
1735fn write_state_table(f: &mut fmt::Formatter<'_>, states: &[StateRow]) -> fmt::Result {
1736    let rows: Vec<(String, String, String, String, &str)> = states
1737        .iter()
1738        .map(|s| {
1739            let flags = match (s.start, s.accept) {
1740                (true, true) => "start,accept",
1741                (true, false) => "start",
1742                (false, true) => "accept",
1743                (false, false) => "",
1744            };
1745            (
1746                format!("#{}", s.id),
1747                flags.to_string(),
1748                s.term
1749                    .as_ref()
1750                    .map(|t| t.to_string())
1751                    .unwrap_or_else(|| "(epsilon)".to_string()),
1752                if s.transitions.is_empty() {
1753                    "(none)".to_string()
1754                } else {
1755                    s.transitions.join(", ")
1756                },
1757                s.origin.as_deref().unwrap_or("(no origin)"),
1758            )
1759        })
1760        .collect();
1761    let w_id = rows.iter().map(|r| r.0.len()).chain([3]).max().unwrap_or(3);
1762    let w_flags = rows.iter().map(|r| r.1.len()).chain([5]).max().unwrap_or(5);
1763    let w_term = rows.iter().map(|r| r.2.len()).chain([4]).max().unwrap_or(4);
1764    let w_trans = rows
1765        .iter()
1766        .map(|r| r.3.len())
1767        .chain([11])
1768        .max()
1769        .unwrap_or(11);
1770    writeln!(
1771        f,
1772        "  {:<w_id$}  {:<w_flags$}  {:<w_term$}  {:<w_trans$}  origin",
1773        "#id", "flags", "term", "transitions"
1774    )?;
1775    writeln!(
1776        f,
1777        "  {}  {}  {}  {}  {}",
1778        "-".repeat(w_id),
1779        "-".repeat(w_flags),
1780        "-".repeat(w_term),
1781        "-".repeat(w_trans),
1782        "-".repeat(6)
1783    )?;
1784    for (id, flags, term, trans, origin) in &rows {
1785        writeln!(
1786            f,
1787            "  {id:<w_id$}  {flags:<w_flags$}  {term:<w_term$}  {trans:<w_trans$}  {origin}"
1788        )?;
1789    }
1790    Ok(())
1791}
1792
1793fn write_substitution_groups(
1794    f: &mut fmt::Formatter<'_>,
1795    groups: &[SubstitutionGroupView],
1796) -> fmt::Result {
1797    if groups.is_empty() {
1798        return Ok(());
1799    }
1800    writeln!(f)?;
1801    writeln!(f, "  substitution groups")?;
1802    for g in groups {
1803        writeln!(f, "    {} accepts {}", g.head, g.accepts.join(", "))?;
1804    }
1805    Ok(())
1806}
1807
1808impl fmt::Display for AllGroupView {
1809    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1810        kv(f, "matcher", &self.matcher)?;
1811        kv(
1812            f,
1813            "outer",
1814            if self.outer_optional {
1815                "optional (minOccurs=0)"
1816            } else {
1817                "required (minOccurs=1)"
1818            },
1819        )?;
1820        kv(f, "members", &self.members.len().to_string())?;
1821        if let Some(oc) = &self.open_content {
1822            kv(f, "open content", &oc.to_string())?;
1823        }
1824        if let Some(note) = &self.note {
1825            kv(f, "note", note)?;
1826        }
1827        writeln!(f)?;
1828        for m in &self.members {
1829            writeln!(
1830                f,
1831                "    {}  {}  ({})",
1832                m.term,
1833                occurs(m.min_occurs, m.max_occurs),
1834                m.origin.as_deref().unwrap_or("no origin")
1835            )?;
1836        }
1837        writeln!(f)?;
1838        if self.required.is_empty() {
1839            writeln!(f, "  required members: (none — the group may stay empty)")?;
1840        } else {
1841            writeln!(f, "  required members:")?;
1842            for r in &self.required {
1843                writeln!(f, "    {r}")?;
1844            }
1845        }
1846        write_substitution_groups(f, &self.substitution_groups)
1847    }
1848}
1849
1850// ---------------------------------------------------------------------------
1851// Tests
1852// ---------------------------------------------------------------------------
1853
1854#[cfg(test)]
1855mod tests {
1856    use super::*;
1857    use crate::builder::SchemaSetBuilder;
1858    use crate::validation::{SchemaValidator, ValidationFlags};
1859
1860    fn schema(xsd: &str) -> SchemaSet {
1861        SchemaSetBuilder::new()
1862            .add_source(xsd, "file:///inspect.xsd")
1863            .expect("schema source accepted")
1864            .compile()
1865            .expect("schema compiles")
1866            .into_schema_set()
1867    }
1868
1869    #[cfg(feature = "xsd11")]
1870    fn schema11(xsd: &str) -> SchemaSet {
1871        SchemaSetBuilder::xsd11()
1872            .add_source(xsd, "file:///inspect11.xsd")
1873            .expect("schema source accepted")
1874            .compile()
1875            .expect("schema compiles")
1876            .into_schema_set()
1877    }
1878
1879    fn report(schema_set: &SchemaSet, local: &str) -> String {
1880        let key = find_complex_type(schema_set, None, local)
1881            .unwrap_or_else(|| panic!("no named complex type {local}"));
1882        inspect_content_model(schema_set, key)
1883            .expect("content model compiles")
1884            .to_string()
1885    }
1886
1887    /// The anonymous complex type of a named global element declaration.
1888    fn anonymous_type_of(schema_set: &SchemaSet, element: &str) -> ComplexTypeKey {
1889        let name = schema_set
1890            .name_table
1891            .get(element)
1892            .expect("element interned");
1893        let key = schema_set
1894            .lookup_element(None, name)
1895            .expect("global element");
1896        match schema_set.arenas.elements[key].resolved_type {
1897            Some(TypeKey::Complex(k)) => k,
1898            other => panic!("element {element} has no complex type: {other:?}"),
1899        }
1900    }
1901
1902    #[test]
1903    fn plain_sequence_shows_three_views() {
1904        let ss = schema(
1905            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
1906  <xs:complexType name="Pair">
1907    <xs:sequence>
1908      <xs:element name="a" type="xs:string"/>
1909      <xs:element name="b" type="xs:int" minOccurs="0"/>
1910    </xs:sequence>
1911  </xs:complexType>
1912</xs:schema>"#,
1913        );
1914        let text = report(&ss, "Pair");
1915
1916        // Three labelled views.
1917        assert!(text.contains("Source"), "{text}");
1918        assert!(text.contains("Authored particles"), "{text}");
1919        assert!(text.contains("Compiled"), "{text}");
1920
1921        // Source view.
1922        assert!(text.contains("type           Pair"), "{text}");
1923        assert!(text.contains("file:///inspect.xsd"), "{text}");
1924        assert!(text.contains("content type   element-only"), "{text}");
1925        assert!(text.contains("mixed          no"), "{text}");
1926        assert!(text.contains("xsd version    1.0"), "{text}");
1927
1928        // Authored view: tree, bounds, unroll decision, locations.
1929        assert!(text.contains("sequence  1..1  [single]"), "{text}");
1930        assert!(
1931            text.contains("element a : xs:string [local decl]"),
1932            "{text}"
1933        );
1934        assert!(text.contains("element b : xs:int [local decl]"), "{text}");
1935        assert!(text.contains("0..1  [unrolled]"), "{text}");
1936        assert!(text.contains("inspect.xsd:"), "{text}");
1937
1938        // Compiled view.
1939        assert!(text.contains("matcher        NFA"), "{text}");
1940        assert!(text.contains("counters       (none)"), "{text}");
1941        assert!(text.contains("frontier       Simple("), "{text}");
1942        assert!(text.contains("counter-free"), "{text}");
1943        assert!(text.contains("consume → #"), "{text}");
1944        assert!(text.contains("start"), "{text}");
1945        assert!(text.contains("accept"), "{text}");
1946    }
1947
1948    #[test]
1949    fn unbounded_choice_is_unrolled_with_no_counter() {
1950        let ss = schema(
1951            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
1952  <xs:complexType name="Stream">
1953    <xs:choice minOccurs="0" maxOccurs="unbounded">
1954      <xs:element name="a" type="xs:string"/>
1955      <xs:element name="b" type="xs:string"/>
1956    </xs:choice>
1957  </xs:complexType>
1958</xs:schema>"#,
1959        );
1960        let text = report(&ss, "Stream");
1961        assert!(text.contains("choice  0..unbounded  [unrolled]"), "{text}");
1962        assert!(text.contains("counters       (none)"), "{text}");
1963        assert!(text.contains("counter-free"), "{text}");
1964        assert!(text.contains("frontier       Simple("), "{text}");
1965    }
1966
1967    #[test]
1968    fn large_bound_compiles_to_a_counter_not_an_unrolled_range() {
1969        let ss = schema(
1970            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
1971  <xs:complexType name="Big">
1972    <xs:sequence>
1973      <xs:element name="a" type="xs:string" minOccurs="0" maxOccurs="10001"/>
1974    </xs:sequence>
1975  </xs:complexType>
1976</xs:schema>"#,
1977        );
1978        let text = report(&ss, "Big");
1979        assert!(text.contains("0..10001  [counter]"), "{text}");
1980        assert!(text.contains("c0: 0..10001"), "{text}");
1981        assert!(text.contains("body nullable? no"), "{text}");
1982        assert!(!text.contains("counter-free"), "{text}");
1983        // Counter transitions are spelled out in the state table.
1984        assert!(text.contains("reset c0 → #"), "{text}");
1985        assert!(text.contains("c0++ → #"), "{text}");
1986        assert!(text.contains("c0<max → #"), "{text}");
1987        assert!(text.contains("c0>=min → #"), "{text}");
1988        // A counted, non-nullable body still uses the scalar path.
1989        assert!(text.contains("frontier       Counted("), "{text}");
1990    }
1991
1992    #[test]
1993    fn nullable_counted_body_is_flagged_as_exposed() {
1994        let ss = schema(
1995            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
1996  <xs:complexType name="Nullable">
1997    <xs:sequence minOccurs="0" maxOccurs="500">
1998      <xs:element name="a" type="xs:string" minOccurs="0"/>
1999    </xs:sequence>
2000  </xs:complexType>
2001</xs:schema>"#,
2002        );
2003        let text = report(&ss, "Nullable");
2004        assert!(text.contains("body nullable? yes"), "{text}");
2005        assert!(text.contains("nullable body in c0"), "{text}");
2006        assert!(text.contains("MAX_ACTIVE_CONFIGS"), "{text}");
2007        assert!(text.contains("frontier       RangedSingle("), "{text}");
2008    }
2009
2010    #[test]
2011    fn all_group_lists_members_and_required_members() {
2012        let ss = schema(
2013            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
2014  <xs:complexType name="Unordered">
2015    <xs:all>
2016      <xs:element name="a" type="xs:string"/>
2017      <xs:element name="b" type="xs:string" minOccurs="0"/>
2018    </xs:all>
2019  </xs:complexType>
2020</xs:schema>"#,
2021        );
2022        let text = report(&ss, "Unordered");
2023        assert!(text.contains("matcher        all-group"), "{text}");
2024        assert!(text.contains("outer          required"), "{text}");
2025        assert!(text.contains("members        2"), "{text}");
2026        assert!(text.contains("required members:"), "{text}");
2027        assert!(text.contains("element a"), "{text}");
2028        // All-group bounds are enforced by the group's own counters.
2029        assert!(text.contains("[all-group counter]"), "{text}");
2030        assert!(text.contains("all  1..1"), "{text}");
2031    }
2032
2033    #[test]
2034    fn substitution_group_head_lists_its_members() {
2035        let ss = schema(
2036            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
2037  <xs:element name="shape" type="xs:string"/>
2038  <xs:element name="circle" type="xs:string" substitutionGroup="shape"/>
2039  <xs:element name="square" type="xs:string" substitutionGroup="shape"/>
2040  <xs:complexType name="Canvas">
2041    <xs:sequence>
2042      <xs:element ref="shape" maxOccurs="unbounded"/>
2043    </xs:sequence>
2044  </xs:complexType>
2045</xs:schema>"#,
2046        );
2047        let text = report(&ss, "Canvas");
2048        assert!(text.contains("element shape"), "{text}");
2049        assert!(text.contains("[global decl"), "{text}");
2050        assert!(text.contains("+2 substitutable"), "{text}");
2051        assert!(text.contains("substitution groups"), "{text}");
2052        assert!(
2053            text.contains("shape accepts circle, shape, square"),
2054            "{text}"
2055        );
2056    }
2057
2058    #[test]
2059    fn anonymous_local_type_is_named_anonymous() {
2060        let ss = schema(
2061            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
2062  <xs:element name="root">
2063    <xs:complexType>
2064      <xs:sequence>
2065        <xs:element name="a" type="xs:string"/>
2066      </xs:sequence>
2067    </xs:complexType>
2068  </xs:element>
2069</xs:schema>"#,
2070        );
2071        let key = anonymous_type_of(&ss, "root");
2072        let text = inspect_content_model(&ss, key)
2073            .expect("model compiles")
2074            .to_string();
2075        assert!(text.contains("Content model report: (anonymous)"), "{text}");
2076        assert!(text.contains("type           (anonymous)"), "{text}");
2077        assert!(text.contains("element a : xs:string"), "{text}");
2078        // A named type can not be found for it.
2079        assert!(find_complex_type(&ss, None, "root").is_none());
2080    }
2081
2082    #[test]
2083    fn group_reference_is_expanded_but_labelled_as_a_reference() {
2084        let ss = schema(
2085            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
2086  <xs:group name="names">
2087    <xs:sequence>
2088      <xs:element name="first" type="xs:string"/>
2089      <xs:element name="last" type="xs:string"/>
2090    </xs:sequence>
2091  </xs:group>
2092  <xs:complexType name="Person">
2093    <xs:sequence>
2094      <xs:group ref="names"/>
2095      <xs:element name="age" type="xs:int"/>
2096    </xs:sequence>
2097  </xs:complexType>
2098</xs:schema>"#,
2099        );
2100        let text = report(&ss, "Person");
2101        assert!(text.contains("group ref names (sequence)"), "{text}");
2102        assert!(text.contains("element first : xs:string"), "{text}");
2103        assert!(text.contains("element last : xs:string"), "{text}");
2104        assert!(text.contains("element age : xs:int"), "{text}");
2105    }
2106
2107    #[test]
2108    fn extension_shows_the_base_contribution_first() {
2109        let ss = schema(
2110            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
2111  <xs:complexType name="Base">
2112    <xs:sequence>
2113      <xs:element name="a" type="xs:string"/>
2114    </xs:sequence>
2115  </xs:complexType>
2116  <xs:complexType name="Derived">
2117    <xs:complexContent>
2118      <xs:extension base="Base">
2119        <xs:sequence>
2120          <xs:element name="b" type="xs:string"/>
2121        </xs:sequence>
2122      </xs:extension>
2123    </xs:complexContent>
2124  </xs:complexType>
2125</xs:schema>"#,
2126        );
2127        let text = report(&ss, "Derived");
2128        assert!(text.contains("derivation     extension of Base"), "{text}");
2129        let base_at = text.find("from base type Base").expect("base section");
2130        let own_at = text.find("own content:").expect("own section");
2131        assert!(base_at < own_at, "base section comes first:\n{text}");
2132        assert!(text.contains("element a : xs:string"), "{text}");
2133        assert!(text.contains("element b : xs:string"), "{text}");
2134    }
2135
2136    #[test]
2137    fn wildcard_shows_constraint_and_process_contents() {
2138        let ss = schema(
2139            r###"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
2140             targetNamespace="urn:w" xmlns:w="urn:w">
2141  <xs:complexType name="Open">
2142    <xs:sequence>
2143      <xs:any namespace="##other" processContents="lax" minOccurs="0"/>
2144    </xs:sequence>
2145  </xs:complexType>
2146</xs:schema>"###,
2147        );
2148        let key = find_complex_type(&ss, Some("urn:w"), "Open").expect("named type");
2149        let text = inspect_content_model(&ss, key)
2150            .expect("model compiles")
2151            .to_string();
2152        assert!(text.contains("any ##other [processContents=lax]"), "{text}");
2153        assert!(text.contains("{urn:w}Open"), "{text}");
2154    }
2155
2156    #[cfg(feature = "xsd11")]
2157    #[test]
2158    fn open_content_is_reported_in_source_and_compiled_views() {
2159        let ss = schema11(
2160            r###"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
2161  <xs:complexType name="Extensible">
2162    <xs:openContent mode="interleave">
2163      <xs:any namespace="##other" processContents="lax"/>
2164    </xs:openContent>
2165    <xs:sequence>
2166      <xs:element name="a" type="xs:string"/>
2167    </xs:sequence>
2168  </xs:complexType>
2169</xs:schema>"###,
2170        );
2171        let text = report(&ss, "Extensible");
2172        assert!(
2173            text.contains("matcher        NFA + open content (interleave)"),
2174            "{text}"
2175        );
2176        assert!(
2177            text.contains("open content   interleave, any ##other"),
2178            "{text}"
2179        );
2180        assert!(text.contains("xsd version    1.1"), "{text}");
2181    }
2182
2183    #[cfg(feature = "xsd11")]
2184    #[test]
2185    fn all_group_open_content_suffix_is_reported() {
2186        let ss = schema11(
2187            r###"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
2188  <xs:complexType name="OpenAll">
2189    <xs:openContent mode="suffix">
2190      <xs:any namespace="##other" processContents="skip"/>
2191    </xs:openContent>
2192    <xs:all>
2193      <xs:element name="a" type="xs:string"/>
2194      <xs:element name="b" type="xs:string" minOccurs="0"/>
2195    </xs:all>
2196  </xs:complexType>
2197</xs:schema>"###,
2198        );
2199        let text = report(&ss, "OpenAll");
2200        assert!(
2201            text.contains("matcher        all-group + open content (suffix)"),
2202            "{text}"
2203        );
2204        assert!(text.contains("processContents=skip"), "{text}");
2205    }
2206
2207    /// `describe_content_model` must reuse the validator's prepared model.
2208    #[test]
2209    fn describe_content_model_uses_the_prepared_model() {
2210        let ss = schema(
2211            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
2212  <xs:complexType name="Pair">
2213    <xs:sequence>
2214      <xs:element name="a" type="xs:string"/>
2215    </xs:sequence>
2216  </xs:complexType>
2217</xs:schema>"#,
2218        );
2219        let key = find_complex_type(&ss, None, "Pair").expect("named type");
2220        let validator = SchemaValidator::new(&ss, ValidationFlags::default());
2221        let text = validator
2222            .describe_content_model(key)
2223            .expect("type is in the schema set")
2224            .to_string();
2225        assert!(text.contains("matcher        NFA"), "{text}");
2226        assert!(text.contains("element a : xs:string"), "{text}");
2227        // The free function compiles the same thing.
2228        let fresh = inspect_content_model(&ss, key)
2229            .expect("compiles")
2230            .to_string();
2231        assert_eq!(text, fresh, "prepared and freshly compiled views agree");
2232    }
2233
2234    /// `((a?){0,1000000}){0,1000000}`: preparation fails, and the report says so.
2235    #[test]
2236    fn describe_content_model_names_a_preparation_failure() {
2237        let ss = schema(
2238            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
2239  <xs:element name="r">
2240    <xs:complexType>
2241      <xs:sequence>
2242        <xs:sequence minOccurs="0" maxOccurs="1000000">
2243          <xs:sequence minOccurs="0" maxOccurs="1000000">
2244            <xs:element name="a" type="xs:string" minOccurs="0"/>
2245          </xs:sequence>
2246        </xs:sequence>
2247      </xs:sequence>
2248    </xs:complexType>
2249  </xs:element>
2250</xs:schema>"#,
2251        );
2252        let validator = SchemaValidator::new(&ss, ValidationFlags::default());
2253        let failures = validator.content_model_failures();
2254        assert_eq!(failures.len(), 1, "exactly one failure: {failures:?}");
2255        let key = failures[0].0;
2256
2257        let text = validator
2258            .describe_content_model(key)
2259            .expect("type is in the schema set")
2260            .to_string();
2261        assert!(text.contains("(none — preparation failed)"), "{text}");
2262        assert!(text.contains("execution limit exceeded"), "{text}");
2263        assert!(text.contains("validation-preparation-failed"), "{text}");
2264        // The authored view still renders, so the shape that failed is visible.
2265        assert!(text.contains("0..1000000  [counter]"), "{text}");
2266
2267        // The free function still compiles the model — only preparation failed.
2268        let fresh = inspect_content_model(&ss, key).expect("the model compiles");
2269        assert!(matches!(fresh.compiled, CompiledView::Nfa(_)));
2270        assert!(
2271            matches!(
2272                &fresh.compiled,
2273                CompiledView::Nfa(v) if matches!(v.frontier, FrontierView::LimitExceeded { .. })
2274            ),
2275            "the frontier names the limit: {}",
2276            fresh
2277        );
2278    }
2279
2280    /// No model is prepared for an empty-content type, so the view is
2281    /// compiled on demand and says so.
2282    #[test]
2283    fn describe_content_model_marks_an_unprepared_model() {
2284        let ss = schema(
2285            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
2286  <xs:complexType name="Marker">
2287    <xs:attribute name="id" type="xs:string"/>
2288  </xs:complexType>
2289</xs:schema>"#,
2290        );
2291        let key = find_complex_type(&ss, None, "Marker").expect("named type");
2292        let validator = SchemaValidator::new(&ss, ValidationFlags::default());
2293        let text = validator
2294            .describe_content_model(key)
2295            .expect("type is in the schema set")
2296            .to_string();
2297        assert!(text.contains("content type   empty"), "{text}");
2298        assert!(text.contains("compiled on demand"), "{text}");
2299        assert!(text.contains("(no content particle)"), "{text}");
2300    }
2301
2302    #[test]
2303    fn describe_content_model_returns_none_for_a_foreign_key() {
2304        let ss = schema(
2305            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
2306  <xs:complexType name="Pair"><xs:sequence/></xs:complexType>
2307</xs:schema>"#,
2308        );
2309        let other = schema(
2310            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
2311  <xs:complexType name="Other">
2312    <xs:sequence><xs:element name="z" type="xs:string"/></xs:sequence>
2313  </xs:complexType>
2314</xs:schema>"#,
2315        );
2316        // A key from a *different* schema set is (almost certainly) absent here;
2317        // slotmap keys carry a version, so the lookup must not panic.
2318        let foreign = find_complex_type(&other, None, "Other").expect("named type");
2319        let validator = SchemaValidator::new(&ss, ValidationFlags::default());
2320        // Either None (key absent) or Some (key collides with a live slot) is
2321        // acceptable — the contract is only that it does not panic.
2322        let _ = validator.describe_content_model(foreign);
2323    }
2324
2325    #[test]
2326    fn find_complex_type_rejects_simple_types_and_unknown_names() {
2327        let ss = schema(
2328            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
2329  <xs:simpleType name="Code">
2330    <xs:restriction base="xs:string"/>
2331  </xs:simpleType>
2332  <xs:complexType name="Pair"><xs:sequence/></xs:complexType>
2333</xs:schema>"#,
2334        );
2335        assert!(find_complex_type(&ss, None, "Code").is_none());
2336        assert!(find_complex_type(&ss, None, "Nope").is_none());
2337        assert!(find_complex_type(&ss, Some("urn:nope"), "Pair").is_none());
2338        assert!(find_complex_type(&ss, None, "Pair").is_some());
2339    }
2340
2341    /// Branch, merge and occurrence-wrapper states are invented by the
2342    /// compiler rather than written by the schema author, but each still
2343    /// belongs to the construct that caused it. Every state row must name a
2344    /// location — the state table used to render about half its rows as
2345    /// `(no origin)`.
2346    #[test]
2347    fn epsilon_states_carry_the_origin_of_their_construct() {
2348        let ss = schema(
2349            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
2350  <xs:complexType name="Mixed">
2351    <xs:sequence>
2352      <xs:element name="a" type="xs:string"/>
2353      <xs:choice minOccurs="0" maxOccurs="3">
2354        <xs:element name="b" type="xs:string"/>
2355        <xs:element name="c" type="xs:string"/>
2356      </xs:choice>
2357    </xs:sequence>
2358  </xs:complexType>
2359</xs:schema>"#,
2360        );
2361        let key = find_complex_type(&ss, None, "Mixed").expect("named type");
2362        let rep = inspect_content_model(&ss, key).expect("content model compiles");
2363        let CompiledView::Nfa(view) = &rep.compiled else {
2364            panic!("expected an NFA model, got {}", rep.compiled.matcher_kind());
2365        };
2366
2367        let epsilons: Vec<&StateRow> = view.states.iter().filter(|s| s.term.is_none()).collect();
2368        assert!(
2369            !epsilons.is_empty(),
2370            "this model is built by composition, so it has epsilon states"
2371        );
2372        for state in &epsilons {
2373            assert!(
2374                state.origin.is_some(),
2375                "epsilon state #{} has no origin",
2376                state.id
2377            );
2378        }
2379
2380        let text = rep.to_string();
2381        assert!(!text.contains("(no origin)"), "{text}");
2382    }
2383
2384    /// Report rendering must not depend on hash-map iteration order.
2385    #[test]
2386    fn rendering_is_deterministic() {
2387        let ss = schema(
2388            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
2389  <xs:element name="shape" type="xs:string"/>
2390  <xs:element name="circle" type="xs:string" substitutionGroup="shape"/>
2391  <xs:element name="square" type="xs:string" substitutionGroup="shape"/>
2392  <xs:complexType name="Canvas">
2393    <xs:choice maxOccurs="unbounded">
2394      <xs:element ref="shape"/>
2395      <xs:any namespace="urn:b urn:a urn:c" processContents="skip"/>
2396    </xs:choice>
2397  </xs:complexType>
2398</xs:schema>"#,
2399        );
2400        let first = report(&ss, "Canvas");
2401        for _ in 0..4 {
2402            assert_eq!(first, report(&ss, "Canvas"));
2403        }
2404        assert!(first.contains("{urn:a urn:b urn:c}"), "{first}");
2405    }
2406}