Skip to main content

trilean_json_shape/
def.rs

1//! The descriptor of a shape: what a type accepts, as data, so one description drives validation, the JSON Schema
2//! and the TypeScript declarations.
3
4use std::any::TypeId;
5
6use crate::shape::Shape;
7
8/// The class of a type's shape, which decides at compile time which `#[shape(...)]` constraints may apply to a field
9/// of that type. A named type (a derived struct or enum) is written as a reference to its definition, so no
10/// constraint applies to the field itself.
11#[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/// What a value of a shape looks like.
25#[derive(Clone, Debug, PartialEq)]
26pub enum Kind {
27    /// Any JSON value.
28    Any,
29    Null,
30    Bool,
31    /// Exactly this boolean.
32    ConstBool(bool),
33    /// Exactly this string.
34    ConstString(String),
35    /// One of these strings.
36    Enum(Vec<String>),
37    /// A string, at least `min_length` characters long (Unicode scalar values, as JSON Schema counts them) and,
38    /// when `pattern` is given, matching it.
39    String {
40        min_length: Option<usize>,
41        pattern: Option<String>,
42    },
43    /// A whole number between the bounds. A number written with a zero fraction (`97.0`) is whole, as in JSON Schema.
44    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    /// An object whose every value has one shape, with keys that match `key_pattern` when it is given.
61    Map {
62        values: Box<ShapeDef>,
63        min_properties: Option<usize>,
64        key_pattern: Option<String>,
65    },
66    Object(ObjectDef),
67    /// A value that matches exactly one of the alternatives.
68    OneOf(Vec<ShapeDef>),
69    /// An object chosen by the string under `tag`: every variant is an object that holds `tag` as a constant.
70    Tagged {
71        tag: String,
72        variants: Vec<(String, ShapeDef)>,
73    },
74    /// A value that does not match the shape.
75    Not(Box<ShapeDef>),
76    /// A value that matches every shape. Written as one schema node when the shapes use different keywords, and as
77    /// `allOf` when they do not.
78    AllOf(Vec<ShapeDef>),
79    /// A named definition.
80    Ref(String),
81}
82
83/// A shape with the description that documents it.
84#[derive(Clone, Debug, PartialEq)]
85pub struct ShapeDef {
86    pub description: Option<String>,
87    pub kind: Kind,
88}
89
90/// One field of an object.
91#[derive(Clone, Debug, PartialEq)]
92pub struct FieldDef {
93    pub name: String,
94    pub shape: ShapeDef,
95    pub required: bool,
96}
97
98/// An object with named fields.
99#[derive(Clone, Debug, Default, PartialEq)]
100pub struct ObjectDef {
101    pub fields: Vec<FieldDef>,
102    /// Whether a key outside `fields` is refused.
103    pub closed: bool,
104    /// Whether a closed object's validation lets a key outside `fields` pass instead of refusing it. The schema and the
105    /// declarations still say the object is closed, and building the value drops the key, so a document that has one is
106    /// read as the object without it. It has no effect on an object that is not closed.
107    pub strips: bool,
108    /// The shape of the value of a key outside `fields`, for an object that holds any key but types its value.
109    pub additional: Option<Box<ShapeDef>>,
110    /// When not empty, at least one of these keys is present.
111    pub any_of_keys: Vec<String>,
112    /// When not empty, exactly one of these keys is present.
113    pub one_of_keys: Vec<String>,
114    pub min_properties: Option<usize>,
115    /// For each key, the keys that must be present whenever it is.
116    pub dependent_required: Vec<(String, Vec<String>)>,
117}
118
119/// A constraint a field attribute adds to the shape of the field's type.
120#[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    /// Replaces the shape with exactly the boolean `value`.
148    pub fn constant_bool(mut self, value: bool) -> Self {
149        self.kind = Kind::ConstBool(value);
150        self
151    }
152
153    /// Replaces the shape with exactly the string `value`.
154    pub fn constant_string(mut self, value: &str) -> Self {
155        self.kind = Kind::ConstString(value.to_owned());
156        self
157    }
158
159    /// Adds `constraint`.
160    ///
161    /// # Panics
162    ///
163    /// When the constraint does not apply to this kind of shape, or a pattern is outside the supported subset
164    /// (see [`crate::Pattern`]). A derive attribute that does either is a mistake in the type, found the first time
165    /// its definitions are built.
166    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/// The named shapes a document is described by, in the order they were first reached.
219#[derive(Clone, Debug, Default, PartialEq)]
220pub struct Definitions {
221    entries: Vec<(String, ShapeDef)>,
222}
223
224impl Definitions {
225    /// The definition of `T` and of every named type it refers to.
226    ///
227    /// # Panics
228    ///
229    /// When two different types reachable from `T` have the same definition name, naming both types. A derived
230    /// type's name is its identifier, or the one `#[shape(name = "...")]` gives.
231    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    /// Marks every closed object, in every definition, for which `strip` holds as one whose validation lets an unknown
259    /// key pass (see [`ObjectDef::strips`]), and returns the definitions. The schema and the declarations still write
260    /// those objects as closed, so the document describes the objects a check accepts after the key is dropped.
261    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    /// The definitions without the one named `name`, for a document that holds that shape inline.
305    pub fn without(mut self, name: &str) -> Self {
306        self.entries.retain(|(entry, _)| entry != name);
307        self
308    }
309}
310
311/// Collects definitions while a type registers itself and what it refers to.
312#[derive(Debug, Default)]
313pub struct Registry {
314    definitions: Definitions,
315    owners: Vec<(TypeId, &'static str)>,
316}
317
318impl Registry {
319    /// The definitions collected so far.
320    pub fn into_definitions(self) -> Definitions {
321        self.definitions
322    }
323
324    /// Reserves `name` for the type `id`, called `type_name` in messages. Returns whether the caller is the first to
325    /// reach it and so must call [`Registry::define`] and register what it refers to; a recursive type is reserved
326    /// before its fields are visited.
327    ///
328    /// # Panics
329    ///
330    /// When `name` is already reserved by a different type, naming both, because a definition is looked up by name
331    /// and one of the two would otherwise be silently replaced by the other.
332    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    /// Sets the definition of a reserved name.
354    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}