use std::collections::HashMap;
use std::sync::Arc;
use crate::automaton::Automaton;
use crate::datatypes::Builtin;
pub(crate) const XS: &str = "http://www.w3.org/2001/XMLSchema";
pub(crate) const XSI: &str = "http://www.w3.org/2001/XMLSchema-instance";
pub(crate) type TypeId = usize;
pub(crate) type ElementId = usize;
pub(crate) const ANY_TYPE: TypeId = 0;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(crate) struct QName {
pub(crate) namespace: Option<String>,
pub(crate) local: String,
}
impl QName {
pub(crate) fn new(namespace: Option<&str>, local: &str) -> Self {
Self {
namespace: namespace.map(str::to_owned),
local: local.to_owned(),
}
}
pub(crate) fn matches(&self, namespace: Option<&str>, local: &str) -> bool {
self.local == local && self.namespace.as_deref() == namespace
}
}
pub(crate) fn namespace_name(namespace: Option<&str>) -> Option<&str> {
namespace.filter(|ns| !ns.is_empty())
}
pub(crate) fn clark(namespace: Option<&str>, local: &str) -> String {
match namespace {
Some(ns) => format!("{{{ns}}}{local}"),
None => local.to_owned(),
}
}
impl std::fmt::Display for QName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&clark(self.namespace.as_deref(), &self.local))
}
}
#[derive(Debug, Clone)]
pub(crate) struct ElementDecl {
pub(crate) name: QName,
pub(crate) type_id: TypeId,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ProcessContents {
Strict,
Lax,
Skip,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum NamespaceConstraint {
Any,
Other(Option<String>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Wildcard {
pub(crate) namespaces: NamespaceConstraint,
pub(crate) process: ProcessContents,
}
impl Wildcard {
pub(crate) fn allows(&self, namespace: Option<&str>) -> bool {
match &self.namespaces {
NamespaceConstraint::Any => true,
NamespaceConstraint::Other(target) => {
namespace.is_some() && namespace != target.as_deref()
}
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct AttributeUse {
pub(crate) name: QName,
pub(crate) type_id: TypeId,
pub(crate) required: bool,
pub(crate) fixed: Option<FixedValue>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct FixedValue(std::num::NonZeroU32);
impl FixedValue {
pub(crate) fn new(index: usize) -> Option<Self> {
u32::try_from(index)
.ok()
.and_then(|i| i.checked_add(1))
.and_then(std::num::NonZeroU32::new)
.map(Self)
}
fn index(self) -> usize {
usize::try_from(self.0.get() - 1).unwrap_or(usize::MAX)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ConstraintKind {
Default,
Fixed,
}
impl ConstraintKind {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::Default => "default",
Self::Fixed => "fixed",
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct ValueConstraint {
pub(crate) kind: ConstraintKind,
pub(crate) value: Box<str>,
}
#[derive(Debug, Clone)]
pub(crate) enum Content {
Empty,
Simple(TypeId),
ElementOnly(Box<Automaton>),
Mixed(Box<Automaton>),
}
#[derive(Debug, Clone)]
pub(crate) struct ComplexType {
pub(crate) name: Option<QName>,
pub(crate) base: TypeId,
pub(crate) is_abstract: bool,
pub(crate) content: Content,
pub(crate) attributes: Arc<[AttributeUse]>,
pub(crate) attribute_wildcard: Option<Wildcard>,
}
#[derive(Debug, Clone)]
pub(crate) struct SimpleType {
pub(crate) name: Option<QName>,
pub(crate) base: TypeId,
pub(crate) builtin: Builtin,
pub(crate) enumeration: Option<Vec<String>>,
pub(crate) min_length: Option<usize>,
pub(crate) max_length: Option<usize>,
}
impl SimpleType {
pub(crate) fn has_facets(&self) -> bool {
self.enumeration.is_some() || self.min_length.is_some() || self.max_length.is_some()
}
}
#[derive(Debug, Clone)]
pub(crate) enum TypeDef {
Simple(SimpleType),
Complex(ComplexType),
}
impl TypeDef {
pub(crate) fn name(&self) -> Option<&QName> {
match self {
Self::Simple(s) => s.name.as_ref(),
Self::Complex(c) => c.name.as_ref(),
}
}
pub(crate) fn base(&self) -> TypeId {
match self {
Self::Simple(s) => s.base,
Self::Complex(c) => c.base,
}
}
}
pub(crate) fn has_facets(types: &[TypeDef], type_id: TypeId) -> bool {
let mut current = type_id;
while let TypeDef::Simple(step) = &types[current] {
if step.has_facets() {
return true;
}
current = step.base;
}
false
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FacetProblem<'s> {
Enumeration(&'s [String]),
MinLength { length: usize, min: usize },
MaxLength { length: usize, max: usize },
}
impl FacetProblem<'_> {
pub(crate) fn describe(self, type_name: &str) -> String {
match self {
Self::Enumeration(values) => format!(
"not one of the values allowed by {type_name}: {}",
values
.iter()
.map(|v| quote(v))
.collect::<Vec<_>>()
.join(", ")
),
Self::MinLength { length, min } => format!(
"{length} characters long, less than the minimum length {min} of {type_name}"
),
Self::MaxLength { length, max } => format!(
"{length} characters long, more than the maximum length {max} of {type_name}"
),
}
}
}
pub(crate) fn facet_problem<'s>(
types: &'s [TypeDef],
type_id: TypeId,
value: &str,
) -> Option<FacetProblem<'s>> {
let mut length = None;
let mut current = type_id;
while let TypeDef::Simple(step) = &types[current] {
if let Some(values) = &step.enumeration
&& !values.iter().any(|v| v == value)
{
return Some(FacetProblem::Enumeration(values));
}
if step.min_length.is_some() || step.max_length.is_some() {
let length = *length.get_or_insert_with(|| value.chars().count());
if let Some(min) = step.min_length
&& length < min
{
return Some(FacetProblem::MinLength { length, min });
}
if let Some(max) = step.max_length
&& length > max
{
return Some(FacetProblem::MaxLength { length, max });
}
}
current = step.base;
}
None
}
const MAX_QUOTED: usize = 80;
pub(crate) fn quote(value: &str) -> String {
let mut out: String = value.chars().take(MAX_QUOTED).collect();
if value.chars().nth(MAX_QUOTED).is_some() {
out.push_str("...");
}
format!("{out:?}")
}
#[derive(Debug, Clone)]
pub struct Schema {
pub(crate) types: Vec<TypeDef>,
pub(crate) elements: Vec<ElementDecl>,
pub(crate) global_elements: HashMap<String, HashMap<String, ElementId>>,
pub(crate) global_types: HashMap<String, HashMap<String, TypeId>>,
pub(crate) documents: Vec<String>,
pub(crate) omitted_imports: Vec<OmittedImport>,
pub(crate) element_constraints: Vec<(ElementId, ValueConstraint)>,
pub(crate) fixed_values: Vec<Box<str>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OmittedImport {
pub file: String,
pub line: u32,
pub namespace: String,
pub location: String,
}
pub(crate) fn namespace_key(namespace: Option<&str>) -> Option<&str> {
match namespace {
None => Some(""),
Some("") => None,
Some(ns) => Some(ns),
}
}
impl Schema {
pub(crate) fn global_element(&self, namespace: Option<&str>, local: &str) -> Option<ElementId> {
let by_name = self.global_elements.get(namespace_key(namespace)?)?;
by_name.get(local).copied()
}
pub(crate) fn global_type(&self, namespace: Option<&str>, local: &str) -> Option<TypeId> {
let by_name = self.global_types.get(namespace_key(namespace)?)?;
by_name.get(local).copied()
}
pub(crate) fn shrink_to_fit(&mut self) {
self.types.shrink_to_fit();
for type_def in &mut self.types {
if let TypeDef::Simple(SimpleType {
enumeration: Some(values),
..
}) = type_def
{
values.shrink_to_fit();
}
}
self.elements.shrink_to_fit();
for by_name in self.global_elements.values_mut() {
by_name.shrink_to_fit();
}
self.global_elements.shrink_to_fit();
for by_name in self.global_types.values_mut() {
by_name.shrink_to_fit();
}
self.global_types.shrink_to_fit();
self.element_constraints.shrink_to_fit();
self.fixed_values.shrink_to_fit();
}
pub(crate) fn has_facets(&self, type_id: TypeId) -> bool {
has_facets(&self.types, type_id)
}
pub(crate) fn fixed_value(&self, fixed: FixedValue) -> &str {
self.fixed_values.get(fixed.index()).map_or("", |v| v)
}
pub(crate) fn element_constraint(&self, element: ElementId) -> Option<&ValueConstraint> {
if self.element_constraints.is_empty() {
return None;
}
self.element_constraints
.binary_search_by_key(&element, |(id, _)| *id)
.ok()
.map(|index| &self.element_constraints[index].1)
}
pub(crate) fn is_derived_from(&self, derived: TypeId, base: TypeId) -> bool {
let mut current = derived;
loop {
if current == base {
return true;
}
if current == ANY_TYPE {
return false;
}
current = self.types[current].base();
}
}
#[must_use]
pub fn documents(&self) -> &[String] {
&self.documents
}
#[must_use]
pub fn omitted_imports(&self) -> &[OmittedImport] {
&self.omitted_imports
}
#[must_use]
pub fn global_element_count(&self) -> usize {
self.global_elements.values().map(HashMap::len).sum()
}
#[must_use]
pub fn type_count(&self) -> usize {
self.types.len()
}
}