use std::collections::HashMap;
use crate::error::Result;
const MAX_INHERITANCE_DEPTH: usize = 256;
#[derive(Debug, Clone)]
pub struct Schema {
name: String,
entities: Vec<Entity>,
index: HashMap<String, usize>,
types: HashMap<String, TypeDef>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Entity {
pub name: String,
pub is_abstract: bool,
pub supertypes: Vec<String>,
pub attributes: Vec<Attribute>,
pub redeclared: Vec<Redeclaration>,
pub derived: Vec<AttributeRef>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Attribute {
pub name: String,
pub optional: bool,
pub ty: TypeRef,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct AttributeRef {
pub entity: String,
pub attribute: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Redeclaration {
pub attribute: AttributeRef,
pub optional: bool,
pub ty: TypeRef,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TypeRef {
Named(String),
Builtin(String),
Aggregate {
kind: AggregateKind,
lower: Option<u64>,
upper: Option<u64>,
element: Box<TypeRef>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AggregateKind {
Array,
Bag,
List,
Set,
Aggregate,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TypeDef {
Alias(TypeRef),
Constructed,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Slot {
pub entity: String,
pub name: String,
pub optional: bool,
pub derived: bool,
pub min_len: Option<u64>,
}
#[derive(Default)]
struct Override {
derived: bool,
ty: Option<TypeRef>,
}
impl Schema {
pub(crate) fn new(
name: String,
entities: Vec<Entity>,
types: HashMap<String, TypeDef>,
) -> Self {
let index = entities
.iter()
.enumerate()
.map(|(i, entity)| (entity.name.clone(), i))
.collect();
Self {
name,
entities,
index,
types,
}
}
pub fn parse(src: &[u8]) -> Result<Self> {
super::parser::parse(src)
}
pub fn name(&self) -> &str {
&self.name
}
pub fn matches(&self, file_schema: &str) -> bool {
file_schema
.split(|c: char| c.is_whitespace() || c == '{')
.next()
.is_some_and(|name| name.eq_ignore_ascii_case(&self.name))
}
pub fn entities(&self) -> &[Entity] {
&self.entities
}
pub fn entity(&self, name: &str) -> Option<&Entity> {
self.position(name).map(|i| &self.entities[i])
}
pub fn type_def(&self, name: &str) -> Option<&TypeDef> {
self.types.get(&name.to_ascii_uppercase())
}
pub fn slots(&self, entity: &str) -> Option<Vec<Slot>> {
let order = self.closure(&[entity])?;
let overrides = self.overrides(&order);
Some(
order
.iter()
.flat_map(|&i| self.own_slots(i, &overrides))
.collect(),
)
}
pub fn complex_slots(&self, partials: &[&str]) -> Option<Vec<Vec<Slot>>> {
let order = self.closure(partials)?;
let overrides = self.overrides(&order);
partials
.iter()
.map(|name| self.position(name).map(|i| self.own_slots(i, &overrides)))
.collect()
}
pub fn min_len(&self, ty: &TypeRef) -> Option<u64> {
let mut ty = ty;
for _ in 0..MAX_INHERITANCE_DEPTH {
match ty {
TypeRef::Aggregate { lower, .. } => return *lower,
TypeRef::Named(name) => match self.types.get(name)? {
TypeDef::Alias(underlying) => ty = underlying,
TypeDef::Constructed => return None,
},
TypeRef::Builtin(_) => return None,
}
}
None
}
fn position(&self, name: &str) -> Option<usize> {
self.index.get(&name.to_ascii_uppercase()).copied()
}
fn closure(&self, roots: &[&str]) -> Option<Vec<usize>> {
let mut order = Vec::new();
let mut seen = vec![false; self.entities.len()];
for root in roots {
self.visit(self.position(root)?, &mut seen, &mut order, 0)?;
}
Some(order)
}
fn visit(
&self,
entity: usize,
seen: &mut [bool],
order: &mut Vec<usize>,
depth: usize,
) -> Option<()> {
if seen[entity] {
return Some(());
}
if depth > MAX_INHERITANCE_DEPTH {
return None;
}
seen[entity] = true;
for supertype in &self.entities[entity].supertypes {
self.visit(self.position(supertype)?, seen, order, depth + 1)?;
}
order.push(entity);
Some(())
}
fn overrides(&self, order: &[usize]) -> HashMap<(usize, String), Override> {
let mut overrides: HashMap<(usize, String), Override> = HashMap::new();
for &i in order {
let entity = &self.entities[i];
for redeclaration in &entity.redeclared {
if let Some(key) = self.declaring(&redeclaration.attribute) {
overrides.entry(key).or_default().ty = Some(redeclaration.ty.clone());
}
}
for derived in &entity.derived {
if let Some(key) = self.declaring(derived) {
overrides.entry(key).or_default().derived = true;
}
}
}
overrides
}
fn declaring(&self, reference: &AttributeRef) -> Option<(usize, String)> {
let order = self.closure(&[&reference.entity])?;
order
.iter()
.rev()
.copied()
.find(|&i| {
self.entities[i]
.attributes
.iter()
.any(|a| a.name == reference.attribute)
})
.map(|i| (i, reference.attribute.clone()))
}
fn own_slots(
&self,
entity: usize,
overrides: &HashMap<(usize, String), Override>,
) -> Vec<Slot> {
let declaring = &self.entities[entity];
declaring
.attributes
.iter()
.map(|attribute| {
let redeclared = overrides.get(&(entity, attribute.name.clone()));
let ty = redeclared
.and_then(|o| o.ty.as_ref())
.unwrap_or(&attribute.ty);
Slot {
entity: declaring.name.clone(),
name: attribute.name.clone(),
optional: attribute.optional,
derived: redeclared.is_some_and(|o| o.derived),
min_len: self.min_len(ty),
}
})
.collect()
}
}