use std::any::TypeId;
use crate::shape::Shape;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Class {
Any,
Bool,
String,
Integer,
Number,
Array,
Map,
OpenObject,
Named,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Kind {
Any,
Null,
Bool,
ConstBool(bool),
ConstString(String),
Enum(Vec<String>),
String {
min_length: Option<usize>,
pattern: Option<String>,
},
Integer {
min: Option<f64>,
exclusive_min: Option<f64>,
max: Option<f64>,
},
Number {
min: Option<f64>,
exclusive_min: Option<f64>,
max: Option<f64>,
},
Array {
items: Box<ShapeDef>,
min_items: Option<usize>,
max_items: Option<usize>,
unique: bool,
},
Map {
values: Box<ShapeDef>,
min_properties: Option<usize>,
key_pattern: Option<String>,
},
Object(ObjectDef),
OneOf(Vec<ShapeDef>),
Tagged {
tag: String,
variants: Vec<(String, ShapeDef)>,
},
Not(Box<ShapeDef>),
AllOf(Vec<ShapeDef>),
Ref(String),
}
#[derive(Clone, Debug, PartialEq)]
pub struct ShapeDef {
pub description: Option<String>,
pub kind: Kind,
}
#[derive(Clone, Debug, PartialEq)]
pub struct FieldDef {
pub name: String,
pub shape: ShapeDef,
pub required: bool,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ObjectDef {
pub fields: Vec<FieldDef>,
pub closed: bool,
pub strips: bool,
pub additional: Option<Box<ShapeDef>>,
pub any_of_keys: Vec<String>,
pub one_of_keys: Vec<String>,
pub min_properties: Option<usize>,
pub dependent_required: Vec<(String, Vec<String>)>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Constraint {
Min(f64),
ExclusiveMin(f64),
Max(f64),
MinLength(usize),
Pattern(String),
MinItems(usize),
MaxItems(usize),
UniqueItems,
MinProperties(usize),
KeyPattern(String),
}
impl ShapeDef {
pub fn new(kind: Kind) -> Self {
ShapeDef {
description: None,
kind,
}
}
pub fn described(mut self, description: &str) -> Self {
self.description = Some(description.to_owned());
self
}
pub fn constant_bool(mut self, value: bool) -> Self {
self.kind = Kind::ConstBool(value);
self
}
pub fn constant_string(mut self, value: &str) -> Self {
self.kind = Kind::ConstString(value.to_owned());
self
}
pub fn constrained(mut self, constraint: Constraint) -> Self {
match (&mut self.kind, constraint) {
(Kind::Integer { min, .. } | Kind::Number { min, .. }, Constraint::Min(bound)) => {
*min = Some(bound);
}
(
Kind::Integer { exclusive_min, .. } | Kind::Number { exclusive_min, .. },
Constraint::ExclusiveMin(bound),
) => {
*exclusive_min = Some(bound);
}
(Kind::Integer { max, .. } | Kind::Number { max, .. }, Constraint::Max(bound)) => {
*max = Some(bound);
}
(Kind::String { min_length, .. }, Constraint::MinLength(length)) => {
*min_length = Some(length)
}
(Kind::String { pattern, .. }, Constraint::Pattern(source)) => {
check_pattern(&source);
*pattern = Some(source);
}
(Kind::Array { min_items, .. }, Constraint::MinItems(count)) => {
*min_items = Some(count)
}
(Kind::Array { max_items, .. }, Constraint::MaxItems(count)) => {
*max_items = Some(count)
}
(Kind::Array { unique, .. }, Constraint::UniqueItems) => *unique = true,
(Kind::Map { min_properties, .. }, Constraint::MinProperties(count)) => {
*min_properties = Some(count);
}
(Kind::Object(object), Constraint::MinProperties(count)) => {
object.min_properties = Some(count)
}
(Kind::Map { key_pattern, .. }, Constraint::KeyPattern(source)) => {
check_pattern(&source);
*key_pattern = Some(source);
}
(kind, constraint) => {
panic!("the constraint {constraint:?} does not apply to {kind:?}")
}
}
self
}
}
fn check_pattern(source: &str) {
if let Err(error) = crate::pattern::shared(source) {
panic!("{error}");
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Definitions {
entries: Vec<(String, ShapeDef)>,
}
impl Definitions {
pub fn of<T: Shape>() -> Self {
let mut registry = Registry::default();
T::register(&mut registry);
registry.into_definitions()
}
pub fn get(&self, name: &str) -> Option<&ShapeDef> {
self.entries
.iter()
.find(|(entry, _)| entry == name)
.map(|(_, shape)| shape)
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &ShapeDef)> {
self.entries
.iter()
.map(|(name, shape)| (name.as_str(), shape))
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn stripping(mut self, strip: impl Fn(&ObjectDef) -> bool) -> Self {
fn visit(shape: &mut ShapeDef, strip: &dyn Fn(&ObjectDef) -> bool) {
match &mut shape.kind {
Kind::Object(object) => {
if object.closed && strip(object) {
object.strips = true;
}
for field in &mut object.fields {
visit(&mut field.shape, strip);
}
if let Some(additional) = &mut object.additional {
visit(additional, strip);
}
}
Kind::Array { items, .. } => visit(items, strip),
Kind::Map { values, .. } => visit(values, strip),
Kind::OneOf(shapes) | Kind::AllOf(shapes) => {
shapes.iter_mut().for_each(|part| visit(part, strip));
}
Kind::Tagged { variants, .. } => {
variants
.iter_mut()
.for_each(|(_, variant)| visit(variant, strip));
}
Kind::Not(inner) => visit(inner, strip),
Kind::Any
| Kind::Null
| Kind::Bool
| Kind::ConstBool(_)
| Kind::ConstString(_)
| Kind::Enum(_)
| Kind::String { .. }
| Kind::Integer { .. }
| Kind::Number { .. }
| Kind::Ref(_) => {}
}
}
for (_, shape) in &mut self.entries {
visit(shape, &strip);
}
self
}
pub fn without(mut self, name: &str) -> Self {
self.entries.retain(|(entry, _)| entry != name);
self
}
}
#[derive(Debug, Default)]
pub struct Registry {
definitions: Definitions,
owners: Vec<(TypeId, &'static str)>,
}
impl Registry {
pub fn into_definitions(self) -> Definitions {
self.definitions
}
pub fn reserve(&mut self, name: &str, id: TypeId, type_name: &'static str) -> bool {
if let Some(position) = self
.definitions
.entries
.iter()
.position(|(entry, _)| entry == name)
{
let (owner, owner_name) = self.owners[position];
assert!(
owner == id,
"the definition name {name:?} is used by two types, {owner_name} and {type_name}; give one of them #[shape(name = \"...\")]"
);
return false;
}
self.definitions
.entries
.push((name.to_owned(), ShapeDef::new(Kind::Any)));
self.owners.push((id, type_name));
true
}
pub fn define(&mut self, name: &str, shape: ShapeDef) {
if let Some(entry) = self
.definitions
.entries
.iter_mut()
.find(|(entry, _)| entry == name)
{
entry.1 = shape;
}
}
}