1use std::collections::HashMap;
4use std::sync::Arc;
5
6use crate::automaton::Automaton;
7use crate::datatypes::Builtin;
8
9pub(crate) const XS: &str = "http://www.w3.org/2001/XMLSchema";
11pub(crate) const XSI: &str = "http://www.w3.org/2001/XMLSchema-instance";
13
14pub(crate) type TypeId = usize;
15pub(crate) type ElementId = usize;
16
17pub(crate) const ANY_TYPE: TypeId = 0;
19
20#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
22pub(crate) struct QName {
23 pub(crate) namespace: Option<String>,
24 pub(crate) local: String,
25}
26
27impl QName {
28 pub(crate) fn new(namespace: Option<&str>, local: &str) -> Self {
29 Self {
30 namespace: namespace.map(str::to_owned),
31 local: local.to_owned(),
32 }
33 }
34
35 pub(crate) fn matches(&self, namespace: Option<&str>, local: &str) -> bool {
36 self.local == local && self.namespace.as_deref() == namespace
37 }
38}
39
40pub(crate) fn namespace_name(namespace: Option<&str>) -> Option<&str> {
43 namespace.filter(|ns| !ns.is_empty())
44}
45
46pub(crate) fn clark(namespace: Option<&str>, local: &str) -> String {
48 match namespace {
49 Some(ns) => format!("{{{ns}}}{local}"),
50 None => local.to_owned(),
51 }
52}
53
54impl std::fmt::Display for QName {
55 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56 f.write_str(&clark(self.namespace.as_deref(), &self.local))
57 }
58}
59
60#[derive(Debug, Clone)]
63pub(crate) struct ElementDecl {
64 pub(crate) name: QName,
65 pub(crate) type_id: TypeId,
66}
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub(crate) enum ProcessContents {
71 Strict,
72 Lax,
73 Skip,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
78pub(crate) enum NamespaceConstraint {
79 Any,
81 Other(Option<String>),
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub(crate) struct Wildcard {
87 pub(crate) namespaces: NamespaceConstraint,
88 pub(crate) process: ProcessContents,
89}
90
91impl Wildcard {
92 pub(crate) fn allows(&self, namespace: Option<&str>) -> bool {
93 match &self.namespaces {
94 NamespaceConstraint::Any => true,
95 NamespaceConstraint::Other(target) => {
96 namespace.is_some() && namespace != target.as_deref()
97 }
98 }
99 }
100}
101
102#[derive(Debug, Clone)]
104pub(crate) struct AttributeUse {
105 pub(crate) name: QName,
106 pub(crate) type_id: TypeId,
108 pub(crate) required: bool,
109 pub(crate) fixed: Option<FixedValue>,
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub(crate) struct FixedValue(std::num::NonZeroU32);
122
123impl FixedValue {
124 pub(crate) fn new(index: usize) -> Option<Self> {
127 u32::try_from(index)
128 .ok()
129 .and_then(|i| i.checked_add(1))
130 .and_then(std::num::NonZeroU32::new)
131 .map(Self)
132 }
133
134 fn index(self) -> usize {
135 usize::try_from(self.0.get() - 1).unwrap_or(usize::MAX)
138 }
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub(crate) enum ConstraintKind {
145 Default,
146 Fixed,
147}
148
149impl ConstraintKind {
150 pub(crate) fn as_str(self) -> &'static str {
151 match self {
152 Self::Default => "default",
153 Self::Fixed => "fixed",
154 }
155 }
156}
157
158#[derive(Debug, Clone)]
161pub(crate) struct ValueConstraint {
162 pub(crate) kind: ConstraintKind,
163 pub(crate) value: Box<str>,
165}
166
167#[derive(Debug, Clone)]
169pub(crate) enum Content {
170 Empty,
172 Simple(TypeId),
174 ElementOnly(Box<Automaton>),
176 Mixed(Box<Automaton>),
178}
179
180#[derive(Debug, Clone)]
181pub(crate) struct ComplexType {
182 pub(crate) name: Option<QName>,
183 pub(crate) base: TypeId,
186 pub(crate) is_abstract: bool,
187 pub(crate) content: Content,
188 pub(crate) attributes: Arc<[AttributeUse]>,
190 pub(crate) attribute_wildcard: Option<Wildcard>,
191}
192
193#[derive(Debug, Clone)]
194pub(crate) struct SimpleType {
195 pub(crate) name: Option<QName>,
196 pub(crate) base: TypeId,
198 pub(crate) builtin: Builtin,
202 pub(crate) enumeration: Option<Vec<String>>,
204 pub(crate) min_length: Option<usize>,
207 pub(crate) max_length: Option<usize>,
209}
210
211impl SimpleType {
212 pub(crate) fn has_facets(&self) -> bool {
215 self.enumeration.is_some() || self.min_length.is_some() || self.max_length.is_some()
216 }
217}
218
219#[derive(Debug, Clone)]
220pub(crate) enum TypeDef {
221 Simple(SimpleType),
222 Complex(ComplexType),
223}
224
225impl TypeDef {
226 pub(crate) fn name(&self) -> Option<&QName> {
227 match self {
228 Self::Simple(s) => s.name.as_ref(),
229 Self::Complex(c) => c.name.as_ref(),
230 }
231 }
232
233 pub(crate) fn base(&self) -> TypeId {
234 match self {
235 Self::Simple(s) => s.base,
236 Self::Complex(c) => c.base,
237 }
238 }
239}
240
241pub(crate) fn has_facets(types: &[TypeDef], type_id: TypeId) -> bool {
244 let mut current = type_id;
245 while let TypeDef::Simple(step) = &types[current] {
246 if step.has_facets() {
247 return true;
248 }
249 current = step.base;
250 }
251 false
252}
253
254#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub(crate) enum FacetProblem<'s> {
257 Enumeration(&'s [String]),
259 MinLength { length: usize, min: usize },
261 MaxLength { length: usize, max: usize },
263}
264
265impl FacetProblem<'_> {
266 pub(crate) fn describe(self, type_name: &str) -> String {
269 match self {
270 Self::Enumeration(values) => format!(
271 "not one of the values allowed by {type_name}: {}",
272 values
273 .iter()
274 .map(|v| quote(v))
275 .collect::<Vec<_>>()
276 .join(", ")
277 ),
278 Self::MinLength { length, min } => format!(
279 "{length} characters long, less than the minimum length {min} of {type_name}"
280 ),
281 Self::MaxLength { length, max } => format!(
282 "{length} characters long, more than the maximum length {max} of {type_name}"
283 ),
284 }
285 }
286}
287
288pub(crate) fn facet_problem<'s>(
293 types: &'s [TypeDef],
294 type_id: TypeId,
295 value: &str,
296) -> Option<FacetProblem<'s>> {
297 let mut length = None;
298 let mut current = type_id;
299 while let TypeDef::Simple(step) = &types[current] {
300 if let Some(values) = &step.enumeration
301 && !values.iter().any(|v| v == value)
302 {
303 return Some(FacetProblem::Enumeration(values));
304 }
305 if step.min_length.is_some() || step.max_length.is_some() {
306 let length = *length.get_or_insert_with(|| value.chars().count());
307 if let Some(min) = step.min_length
308 && length < min
309 {
310 return Some(FacetProblem::MinLength { length, min });
311 }
312 if let Some(max) = step.max_length
313 && length > max
314 {
315 return Some(FacetProblem::MaxLength { length, max });
316 }
317 }
318 current = step.base;
319 }
320 None
321}
322
323const MAX_QUOTED: usize = 80;
325
326pub(crate) fn quote(value: &str) -> String {
328 let mut out: String = value.chars().take(MAX_QUOTED).collect();
329 if value.chars().nth(MAX_QUOTED).is_some() {
330 out.push_str("...");
331 }
332 format!("{out:?}")
333}
334
335#[derive(Debug, Clone)]
337pub struct Schema {
338 pub(crate) types: Vec<TypeDef>,
339 pub(crate) elements: Vec<ElementDecl>,
340 pub(crate) global_elements: HashMap<String, HashMap<String, ElementId>>,
343 pub(crate) global_types: HashMap<String, HashMap<String, TypeId>>,
346 pub(crate) documents: Vec<String>,
348 pub(crate) omitted_imports: Vec<OmittedImport>,
350 pub(crate) element_constraints: Vec<(ElementId, ValueConstraint)>,
353 pub(crate) fixed_values: Vec<Box<str>>,
355}
356
357#[derive(Debug, Clone, PartialEq, Eq)]
363pub struct OmittedImport {
364 pub file: String,
367 pub line: u32,
369 pub namespace: String,
371 pub location: String,
374}
375
376pub(crate) fn namespace_key(namespace: Option<&str>) -> Option<&str> {
381 match namespace {
382 None => Some(""),
383 Some("") => None,
384 Some(ns) => Some(ns),
385 }
386}
387
388impl Schema {
389 pub(crate) fn global_element(&self, namespace: Option<&str>, local: &str) -> Option<ElementId> {
390 let by_name = self.global_elements.get(namespace_key(namespace)?)?;
391 by_name.get(local).copied()
392 }
393
394 pub(crate) fn global_type(&self, namespace: Option<&str>, local: &str) -> Option<TypeId> {
395 let by_name = self.global_types.get(namespace_key(namespace)?)?;
396 by_name.get(local).copied()
397 }
398
399 pub(crate) fn shrink_to_fit(&mut self) {
402 self.types.shrink_to_fit();
403 for type_def in &mut self.types {
404 if let TypeDef::Simple(SimpleType {
405 enumeration: Some(values),
406 ..
407 }) = type_def
408 {
409 values.shrink_to_fit();
410 }
411 }
412 self.elements.shrink_to_fit();
413 for by_name in self.global_elements.values_mut() {
414 by_name.shrink_to_fit();
415 }
416 self.global_elements.shrink_to_fit();
417 for by_name in self.global_types.values_mut() {
418 by_name.shrink_to_fit();
419 }
420 self.global_types.shrink_to_fit();
421 self.element_constraints.shrink_to_fit();
422 self.fixed_values.shrink_to_fit();
423 }
424
425 pub(crate) fn has_facets(&self, type_id: TypeId) -> bool {
428 has_facets(&self.types, type_id)
429 }
430
431 pub(crate) fn fixed_value(&self, fixed: FixedValue) -> &str {
433 self.fixed_values.get(fixed.index()).map_or("", |v| v)
434 }
435
436 pub(crate) fn element_constraint(&self, element: ElementId) -> Option<&ValueConstraint> {
438 if self.element_constraints.is_empty() {
439 return None;
440 }
441 self.element_constraints
442 .binary_search_by_key(&element, |(id, _)| *id)
443 .ok()
444 .map(|index| &self.element_constraints[index].1)
445 }
446
447 pub(crate) fn is_derived_from(&self, derived: TypeId, base: TypeId) -> bool {
450 let mut current = derived;
451 loop {
452 if current == base {
453 return true;
454 }
455 if current == ANY_TYPE {
456 return false;
457 }
458 current = self.types[current].base();
459 }
460 }
461
462 #[must_use]
464 pub fn documents(&self) -> &[String] {
465 &self.documents
466 }
467
468 #[must_use]
473 pub fn omitted_imports(&self) -> &[OmittedImport] {
474 &self.omitted_imports
475 }
476
477 #[must_use]
479 pub fn global_element_count(&self) -> usize {
480 self.global_elements.values().map(HashMap::len).sum()
481 }
482
483 #[must_use]
485 pub fn type_count(&self) -> usize {
486 self.types.len()
487 }
488}