1use 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
109const MAX_REPORT_DEPTH: usize = 100;
111
112pub 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
139pub 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
165pub(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 (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#[derive(Debug, Clone)]
223pub struct ContentModelReport {
224 pub source: SourceView,
226 pub authored: AuthoredView,
228 pub compiled: CompiledView,
230}
231
232#[derive(Debug, Clone)]
234pub struct SourceView {
235 pub type_name: String,
237 pub document: Option<String>,
239 pub line: Option<usize>,
241 pub column: Option<usize>,
243 pub content_type: ContentType,
245 pub mixed: bool,
247 pub derivation: Option<String>,
249 pub open_content: Option<OpenContentView>,
251 pub xsd_version: XsdVersion,
253}
254
255#[derive(Debug, Clone, Default)]
257pub struct AuthoredView {
258 pub sections: Vec<AuthoredSection>,
262}
263
264#[derive(Debug, Clone)]
266pub struct AuthoredSection {
267 pub from_base_type: Option<String>,
270 pub root: Option<AuthoredNode>,
272}
273
274#[derive(Debug, Clone)]
276pub struct AuthoredNode {
277 pub kind: AuthoredKind,
279 pub min_occurs: u32,
281 pub max_occurs: Option<u32>,
283 pub occurrence: OccurrenceCompilation,
285 pub origin: Option<String>,
287 pub children: Vec<AuthoredNode>,
289}
290
291#[derive(Debug, Clone)]
293pub enum AuthoredKind {
294 Sequence,
296 Choice,
298 All,
300 GroupRef(GroupRefView),
302 Element(ElementTermView),
304 Wildcard(WildcardTermView),
306}
307
308#[derive(Debug, Clone)]
310pub struct GroupRefView {
311 pub name: String,
313 pub compositor: Option<Compositor>,
315 pub resolved: bool,
317 pub recursive: bool,
319}
320
321#[derive(Debug, Clone, Copy, PartialEq, Eq)]
323pub enum OccurrenceCompilation {
324 Single,
326 Unrolled,
329 Counted,
331 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#[derive(Debug, Clone)]
350pub enum CompiledView {
351 Nfa(NfaView),
353 AllGroup(AllGroupView),
355 Failed {
357 reason: String,
359 },
360}
361
362impl CompiledView {
363 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 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#[derive(Debug, Clone)]
386pub struct NfaView {
387 pub matcher: String,
389 pub state_count: usize,
391 pub transition_count: usize,
393 pub counters: Vec<CounterView>,
395 pub frontier: FrontierView,
397 pub states: Vec<StateRow>,
399 pub substitution_groups: Vec<SubstitutionGroupView>,
401 pub open_content: Option<OpenContentView>,
403 pub exposure: ExposureView,
405 pub note: Option<String>,
407}
408
409#[derive(Debug, Clone, Copy)]
411pub struct CounterView {
412 pub id: CounterId,
414 pub min: u32,
416 pub max: u32,
418 pub body_nullable: bool,
420}
421
422#[derive(Debug, Clone)]
424pub enum FrontierView {
425 Simple {
427 states: usize,
429 },
430 Counted {
432 configs: usize,
434 },
435 RangedSingle {
437 states: usize,
439 },
440 Hybrid {
442 configs: usize,
444 ranged_counter: usize,
446 },
447 LimitExceeded {
449 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#[derive(Debug, Clone)]
474pub struct StateRow {
475 pub id: StateId,
477 pub start: bool,
479 pub accept: bool,
481 pub term: Option<TermView>,
483 pub transitions: Vec<String>,
485 pub origin: Option<String>,
487}
488
489#[derive(Debug, Clone)]
491pub enum TermView {
492 Element(ElementTermView),
494 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#[derive(Debug, Clone)]
509pub struct ElementTermView {
510 pub name: String,
512 pub declaration: DeclarationBinding,
514 pub type_name: Option<String>,
516 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
537pub enum DeclarationBinding {
538 Global,
540 Local,
542 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#[derive(Debug, Clone)]
559pub struct WildcardTermView {
560 pub namespace: String,
562 pub process_contents: &'static str,
564 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#[derive(Debug, Clone)]
584pub struct SubstitutionGroupView {
585 pub head: String,
587 pub accepts: Vec<String>,
590}
591
592#[derive(Debug, Clone)]
594pub struct AllGroupView {
595 pub matcher: String,
597 pub outer_optional: bool,
599 pub members: Vec<AllMemberView>,
601 pub required: Vec<String>,
603 pub substitution_groups: Vec<SubstitutionGroupView>,
605 pub open_content: Option<OpenContentView>,
607 pub note: Option<String>,
609}
610
611#[derive(Debug, Clone)]
613pub struct AllMemberView {
614 pub term: TermView,
616 pub min_occurs: u32,
618 pub max_occurs: Option<u32>,
620 pub origin: Option<String>,
622}
623
624#[derive(Debug, Clone)]
626pub struct OpenContentView {
627 pub mode: &'static str,
629 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#[derive(Debug, Clone)]
645pub struct ExposureView {
646 pub counter_free: bool,
648 pub counter_count: usize,
650 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
684fn 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
726fn 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 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
806struct ParticleWalker<'a> {
810 schema_set: &'a SchemaSet,
811 target_namespace: Option<NameId>,
812 subst: Option<&'a SubstitutionGroupMap>,
813 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 if let Some(ref_name) = &group.ref_name {
866 let name = qname(self.schema_set, ref_name.namespace, ref_name.local_name);
867 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 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 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 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
1091fn 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
1478fn 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
1524fn 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
1568const 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) = §ion.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 §ion.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#[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 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 assert!(text.contains("Source"), "{text}");
1918 assert!(text.contains("Authored particles"), "{text}");
1919 assert!(text.contains("Compiled"), "{text}");
1920
1921 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 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 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 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 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 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 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 #[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 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 #[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 assert!(text.contains("0..1000000 [counter]"), "{text}");
2266
2267 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 #[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 let foreign = find_complex_type(&other, None, "Other").expect("named type");
2319 let validator = SchemaValidator::new(&ss, ValidationFlags::default());
2320 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 #[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 #[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}