1use std::any::TypeId;
5
6use crate::shape::Shape;
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum Class {
13 Any,
14 Bool,
15 String,
16 Integer,
17 Number,
18 Array,
19 Map,
20 OpenObject,
21 Named,
22}
23
24#[derive(Clone, Debug, PartialEq)]
26pub enum Kind {
27 Any,
29 Null,
30 Bool,
31 ConstBool(bool),
33 ConstString(String),
35 Enum(Vec<String>),
37 String {
40 min_length: Option<usize>,
41 pattern: Option<String>,
42 },
43 Integer {
45 min: Option<f64>,
46 exclusive_min: Option<f64>,
47 max: Option<f64>,
48 },
49 Number {
50 min: Option<f64>,
51 exclusive_min: Option<f64>,
52 max: Option<f64>,
53 },
54 Array {
55 items: Box<ShapeDef>,
56 min_items: Option<usize>,
57 max_items: Option<usize>,
58 unique: bool,
59 },
60 Map {
62 values: Box<ShapeDef>,
63 min_properties: Option<usize>,
64 key_pattern: Option<String>,
65 },
66 Object(ObjectDef),
67 OneOf(Vec<ShapeDef>),
69 Tagged {
71 tag: String,
72 variants: Vec<(String, ShapeDef)>,
73 },
74 Not(Box<ShapeDef>),
76 AllOf(Vec<ShapeDef>),
79 Ref(String),
81}
82
83#[derive(Clone, Debug, PartialEq)]
85pub struct ShapeDef {
86 pub description: Option<String>,
87 pub kind: Kind,
88}
89
90#[derive(Clone, Debug, PartialEq)]
92pub struct FieldDef {
93 pub name: String,
94 pub shape: ShapeDef,
95 pub required: bool,
96}
97
98#[derive(Clone, Debug, Default, PartialEq)]
100pub struct ObjectDef {
101 pub fields: Vec<FieldDef>,
102 pub closed: bool,
104 pub strips: bool,
108 pub additional: Option<Box<ShapeDef>>,
110 pub any_of_keys: Vec<String>,
112 pub one_of_keys: Vec<String>,
114 pub min_properties: Option<usize>,
115 pub dependent_required: Vec<(String, Vec<String>)>,
117}
118
119#[derive(Clone, Debug, PartialEq)]
121pub enum Constraint {
122 Min(f64),
123 ExclusiveMin(f64),
124 Max(f64),
125 MinLength(usize),
126 Pattern(String),
127 MinItems(usize),
128 MaxItems(usize),
129 UniqueItems,
130 MinProperties(usize),
131 KeyPattern(String),
132}
133
134impl ShapeDef {
135 pub fn new(kind: Kind) -> Self {
136 ShapeDef {
137 description: None,
138 kind,
139 }
140 }
141
142 pub fn described(mut self, description: &str) -> Self {
143 self.description = Some(description.to_owned());
144 self
145 }
146
147 pub fn constant_bool(mut self, value: bool) -> Self {
149 self.kind = Kind::ConstBool(value);
150 self
151 }
152
153 pub fn constant_string(mut self, value: &str) -> Self {
155 self.kind = Kind::ConstString(value.to_owned());
156 self
157 }
158
159 pub fn constrained(mut self, constraint: Constraint) -> Self {
167 match (&mut self.kind, constraint) {
168 (Kind::Integer { min, .. } | Kind::Number { min, .. }, Constraint::Min(bound)) => {
169 *min = Some(bound);
170 }
171 (
172 Kind::Integer { exclusive_min, .. } | Kind::Number { exclusive_min, .. },
173 Constraint::ExclusiveMin(bound),
174 ) => {
175 *exclusive_min = Some(bound);
176 }
177 (Kind::Integer { max, .. } | Kind::Number { max, .. }, Constraint::Max(bound)) => {
178 *max = Some(bound);
179 }
180 (Kind::String { min_length, .. }, Constraint::MinLength(length)) => {
181 *min_length = Some(length)
182 }
183 (Kind::String { pattern, .. }, Constraint::Pattern(source)) => {
184 check_pattern(&source);
185 *pattern = Some(source);
186 }
187 (Kind::Array { min_items, .. }, Constraint::MinItems(count)) => {
188 *min_items = Some(count)
189 }
190 (Kind::Array { max_items, .. }, Constraint::MaxItems(count)) => {
191 *max_items = Some(count)
192 }
193 (Kind::Array { unique, .. }, Constraint::UniqueItems) => *unique = true,
194 (Kind::Map { min_properties, .. }, Constraint::MinProperties(count)) => {
195 *min_properties = Some(count);
196 }
197 (Kind::Object(object), Constraint::MinProperties(count)) => {
198 object.min_properties = Some(count)
199 }
200 (Kind::Map { key_pattern, .. }, Constraint::KeyPattern(source)) => {
201 check_pattern(&source);
202 *key_pattern = Some(source);
203 }
204 (kind, constraint) => {
205 panic!("the constraint {constraint:?} does not apply to {kind:?}")
206 }
207 }
208 self
209 }
210}
211
212fn check_pattern(source: &str) {
213 if let Err(error) = crate::pattern::shared(source) {
214 panic!("{error}");
215 }
216}
217
218#[derive(Clone, Debug, Default, PartialEq)]
220pub struct Definitions {
221 entries: Vec<(String, ShapeDef)>,
222}
223
224impl Definitions {
225 pub fn of<T: Shape>() -> Self {
232 let mut registry = Registry::default();
233 T::register(&mut registry);
234 registry.into_definitions()
235 }
236
237 pub fn get(&self, name: &str) -> Option<&ShapeDef> {
238 self.entries
239 .iter()
240 .find(|(entry, _)| entry == name)
241 .map(|(_, shape)| shape)
242 }
243
244 pub fn iter(&self) -> impl Iterator<Item = (&str, &ShapeDef)> {
245 self.entries
246 .iter()
247 .map(|(name, shape)| (name.as_str(), shape))
248 }
249
250 pub fn len(&self) -> usize {
251 self.entries.len()
252 }
253
254 pub fn is_empty(&self) -> bool {
255 self.entries.is_empty()
256 }
257
258 pub fn stripping(mut self, strip: impl Fn(&ObjectDef) -> bool) -> Self {
262 fn visit(shape: &mut ShapeDef, strip: &dyn Fn(&ObjectDef) -> bool) {
263 match &mut shape.kind {
264 Kind::Object(object) => {
265 if object.closed && strip(object) {
266 object.strips = true;
267 }
268 for field in &mut object.fields {
269 visit(&mut field.shape, strip);
270 }
271 if let Some(additional) = &mut object.additional {
272 visit(additional, strip);
273 }
274 }
275 Kind::Array { items, .. } => visit(items, strip),
276 Kind::Map { values, .. } => visit(values, strip),
277 Kind::OneOf(shapes) | Kind::AllOf(shapes) => {
278 shapes.iter_mut().for_each(|part| visit(part, strip));
279 }
280 Kind::Tagged { variants, .. } => {
281 variants
282 .iter_mut()
283 .for_each(|(_, variant)| visit(variant, strip));
284 }
285 Kind::Not(inner) => visit(inner, strip),
286 Kind::Any
287 | Kind::Null
288 | Kind::Bool
289 | Kind::ConstBool(_)
290 | Kind::ConstString(_)
291 | Kind::Enum(_)
292 | Kind::String { .. }
293 | Kind::Integer { .. }
294 | Kind::Number { .. }
295 | Kind::Ref(_) => {}
296 }
297 }
298 for (_, shape) in &mut self.entries {
299 visit(shape, &strip);
300 }
301 self
302 }
303
304 pub fn without(mut self, name: &str) -> Self {
306 self.entries.retain(|(entry, _)| entry != name);
307 self
308 }
309}
310
311#[derive(Debug, Default)]
313pub struct Registry {
314 definitions: Definitions,
315 owners: Vec<(TypeId, &'static str)>,
316}
317
318impl Registry {
319 pub fn into_definitions(self) -> Definitions {
321 self.definitions
322 }
323
324 pub fn reserve(&mut self, name: &str, id: TypeId, type_name: &'static str) -> bool {
333 if let Some(position) = self
334 .definitions
335 .entries
336 .iter()
337 .position(|(entry, _)| entry == name)
338 {
339 let (owner, owner_name) = self.owners[position];
340 assert!(
341 owner == id,
342 "the definition name {name:?} is used by two types, {owner_name} and {type_name}; give one of them #[shape(name = \"...\")]"
343 );
344 return false;
345 }
346 self.definitions
347 .entries
348 .push((name.to_owned(), ShapeDef::new(Kind::Any)));
349 self.owners.push((id, type_name));
350 true
351 }
352
353 pub fn define(&mut self, name: &str, shape: ShapeDef) {
355 if let Some(entry) = self
356 .definitions
357 .entries
358 .iter_mut()
359 .find(|(entry, _)| entry == name)
360 {
361 entry.1 = shape;
362 }
363 }
364}