Skip to main content

trilean_json_shape/
shape.rs

1//! The trait a type implements to be described, validated and emitted, and its implementations for the types a
2//! derived shape is built from.
3
4use std::borrow::Cow;
5
6use crate::def::{Class, Definitions, Kind, Registry, ShapeDef};
7use crate::path::{Issues, Path};
8use crate::validate::check;
9use crate::value::{MAX_SAFE_INTEGER, Value};
10
11/// A type with a shape. `#[derive(Shape)]` implements it from the type's serde attributes and `#[shape(...)]`.
12pub trait Shape: Sized {
13    /// Whether a field of this type may be absent from its object.
14    const OPTIONAL: bool = false;
15
16    /// The class of the shape, which decides at compile time which constraints a field of this type may carry.
17    const CLASS: Class;
18
19    /// Whether the type is a struct, which is what a flattened field and a newtype variant of a tagged enum must be.
20    const IS_OBJECT: bool = false;
21
22    /// Whether the type collects the members of an object that no field names, so a flattened field of it types them.
23    const CATCH_ALL: bool = false;
24
25    /// The shape of those members, for a type with `CATCH_ALL`.
26    fn catch_all_shape() -> Option<ShapeDef> {
27        None
28    }
29
30    /// The keys of the object this type is, own and flattened, which a derive checks for duplicates at compile time.
31    const KEYS: &'static [&'static str] = &[];
32
33    /// How a field of this type is described: a named type gives a reference to its definition, a built-in gives
34    /// its shape inline.
35    fn reference() -> ShapeDef;
36
37    /// The complete shape of this type, which for a named type is what its definition holds.
38    fn definition() -> ShapeDef {
39        Self::reference()
40    }
41
42    /// Adds this type and every named type it refers to to `registry`.
43    fn register(registry: &mut Registry);
44
45    /// Adds the named types this type's fields refer to, without this type itself, for a type whose fields are
46    /// merged into another object's definition.
47    fn register_members(registry: &mut Registry) {
48        Self::register(registry);
49    }
50
51    /// The value of a field of this type that is absent from its object, for a type that allows that.
52    fn absent() -> Option<Self> {
53        None
54    }
55
56    /// The definitions this type is described by.
57    fn definitions() -> Cow<'static, Definitions> {
58        Cow::Owned(Definitions::of::<Self>())
59    }
60
61    /// Converts the members of an object that are not in `known`, for a type with `CATCH_ALL`.
62    fn build_rest(value: &Value, path: &mut Path, known: &[&str]) -> Result<Self, Issues> {
63        let _ = (value, known);
64        mismatch(path, "a type that collects the other members")
65    }
66
67    /// Converts a value that already matches this type's shape. A mismatch means the shape and the conversion
68    /// disagree, and is reported as an issue rather than a panic.
69    fn build(value: &Value, path: &mut Path) -> Result<Self, Issues>;
70
71    /// Validates `value` against this type's shape, collecting every issue with its path, then converts it. This is
72    /// what deserialising a derived type does, so deserialising is validating.
73    fn from_json(value: &Value) -> Result<Self, Issues> {
74        let issues = check(&Self::definitions(), &Self::reference(), value);
75        if !issues.is_empty() {
76            return Err(Issues(issues));
77        }
78        Self::build(value, &mut Path::new())
79    }
80
81    /// Whether `value` matches this type's shape.
82    fn accepts(value: &Value) -> bool {
83        check(&Self::definitions(), &Self::reference(), value).is_empty()
84    }
85}
86
87fn mismatch<T>(path: &Path, expected: &str) -> Result<T, Issues> {
88    Err(Issues::at(
89        path,
90        format!("the shape and the conversion disagree: expected {expected}"),
91    ))
92}
93
94impl Shape for String {
95    const CLASS: Class = Class::String;
96    fn reference() -> ShapeDef {
97        ShapeDef::new(Kind::String {
98            min_length: None,
99            pattern: None,
100        })
101    }
102    fn register(_: &mut Registry) {}
103    fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
104        match value.as_str() {
105            Some(text) => Ok(text.to_owned()),
106            None => mismatch(path, "a string"),
107        }
108    }
109}
110
111impl Shape for bool {
112    const CLASS: Class = Class::Bool;
113    fn reference() -> ShapeDef {
114        ShapeDef::new(Kind::Bool)
115    }
116    fn register(_: &mut Registry) {}
117    fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
118        match value.as_bool() {
119            Some(flag) => Ok(flag),
120            None => mismatch(path, "a boolean"),
121        }
122    }
123}
124
125impl Shape for f64 {
126    const CLASS: Class = Class::Number;
127    fn reference() -> ShapeDef {
128        ShapeDef::new(Kind::Number {
129            min: None,
130            exclusive_min: None,
131            max: None,
132        })
133    }
134    fn register(_: &mut Registry) {}
135    fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
136        match value.as_f64() {
137            Some(number) => Ok(number),
138            None => mismatch(path, "a number"),
139        }
140    }
141}
142
143/// Any JSON value, kept in order.
144impl Shape for Value {
145    const CLASS: Class = Class::Any;
146    fn reference() -> ShapeDef {
147        ShapeDef::new(Kind::Any)
148    }
149    fn register(_: &mut Registry) {}
150    fn build(value: &Value, _: &mut Path) -> Result<Self, Issues> {
151        Ok(value.clone())
152    }
153}
154
155macro_rules! integer_shape {
156    ($type:ty, $min:expr, $max:expr, $convert:expr) => {
157        impl Shape for $type {
158            const CLASS: Class = Class::Integer;
159            fn reference() -> ShapeDef {
160                ShapeDef::new(Kind::Integer {
161                    min: Some($min),
162                    exclusive_min: None,
163                    max: Some($max),
164                })
165            }
166            fn register(_: &mut Registry) {}
167            fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
168                match value.as_f64() {
169                    // The shape bounds the number to a whole value the integer type holds, so the cast is exact.
170                    Some(number) if number.fract() == 0.0 => {
171                        let convert: fn(i64) -> Option<$type> = $convert;
172                        convert(number as i64)
173                            .map_or_else(|| mismatch(path, "an integer in range"), Ok)
174                    }
175                    _ => mismatch(path, "an integer"),
176                }
177            }
178        }
179    };
180}
181
182integer_shape!(u8, 0.0, f64::from(u8::MAX), |n| u8::try_from(n).ok());
183integer_shape!(u16, 0.0, f64::from(u16::MAX), |n| u16::try_from(n).ok());
184integer_shape!(u32, 0.0, f64::from(u32::MAX), |n| u32::try_from(n).ok());
185integer_shape!(i32, f64::from(i32::MIN), f64::from(i32::MAX), |n| {
186    i32::try_from(n).ok()
187});
188// Wider integers are bounded by what a JavaScript number holds exactly, which is the largest integer the corpus allows.
189integer_shape!(u64, 0.0, MAX_SAFE_INTEGER, |n| u64::try_from(n).ok());
190integer_shape!(usize, 0.0, MAX_SAFE_INTEGER, |n| usize::try_from(n).ok());
191integer_shape!(i64, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, Some);
192
193impl<T: Shape> Shape for Vec<T> {
194    const CLASS: Class = Class::Array;
195    fn reference() -> ShapeDef {
196        ShapeDef::new(Kind::Array {
197            items: Box::new(T::reference()),
198            min_items: None,
199            max_items: None,
200            unique: false,
201        })
202    }
203    fn register(registry: &mut Registry) {
204        T::register(registry);
205    }
206    fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
207        let Some(elements) = value.as_array() else {
208            return mismatch(path, "an array");
209        };
210        let mut built = Vec::with_capacity(elements.len());
211        for (position, element) in elements.iter().enumerate() {
212            path.push_index(position);
213            let item = T::build(element, path);
214            path.pop();
215            built.push(item?);
216        }
217        Ok(built)
218    }
219}
220
221/// An absent field, and so an optional one. It is not an object type for a flattened field, whose fields would then be
222/// optional as a group, which a shape cannot say. A field that is present is described by `T` alone, so `null` is not an
223/// accepted spelling of absence.
224impl<T: Shape> Shape for Option<T> {
225    const OPTIONAL: bool = true;
226    const CLASS: Class = T::CLASS;
227    fn reference() -> ShapeDef {
228        T::reference()
229    }
230    fn register(registry: &mut Registry) {
231        T::register(registry);
232    }
233    fn absent() -> Option<Self> {
234        Some(None)
235    }
236    fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
237        T::build(value, path).map(Some)
238    }
239}
240
241impl<T: Shape> Shape for Box<T> {
242    const CLASS: Class = T::CLASS;
243    const IS_OBJECT: bool = T::IS_OBJECT;
244    const KEYS: &'static [&'static str] = T::KEYS;
245    fn reference() -> ShapeDef {
246        T::reference()
247    }
248    fn definition() -> ShapeDef {
249        T::definition()
250    }
251    fn register(registry: &mut Registry) {
252        T::register(registry);
253    }
254    fn register_members(registry: &mut Registry) {
255        T::register_members(registry);
256    }
257    fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
258        T::build(value, path).map(Box::new)
259    }
260}
261
262/// An object whose values all have one shape, kept in input order. A key called `__proto__` is dropped when the map is
263/// built, as it is when a document is read as the shape (see [`crate::normalise`]): a consumer that assigns the keys to
264/// an object of its own would otherwise change that object's prototype.
265#[derive(Clone, Debug, PartialEq)]
266pub struct Map<T>(pub Vec<(String, T)>);
267
268impl<T: Shape> Shape for Map<T> {
269    const CLASS: Class = Class::Map;
270    const CATCH_ALL: bool = true;
271    fn catch_all_shape() -> Option<ShapeDef> {
272        Some(T::reference())
273    }
274    fn build_rest(value: &Value, path: &mut Path, known: &[&str]) -> Result<Self, Issues> {
275        let Some(pairs) = value.as_object() else {
276            return mismatch(path, "an object");
277        };
278        let mut built = Vec::new();
279        for (key, entry) in pairs
280            .iter()
281            .filter(|(key, _)| !known.contains(&key.as_str()))
282        {
283            path.push_key(key);
284            let item = T::build(entry, path);
285            path.pop();
286            built.push((key.clone(), item?));
287        }
288        Ok(Map(built))
289    }
290    fn reference() -> ShapeDef {
291        ShapeDef::new(Kind::Map {
292            values: Box::new(T::reference()),
293            min_properties: None,
294            key_pattern: None,
295        })
296    }
297    fn register(registry: &mut Registry) {
298        T::register(registry);
299    }
300    fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
301        let Some(pairs) = value.as_object() else {
302            return mismatch(path, "an object");
303        };
304        let mut built = Vec::with_capacity(pairs.len());
305        for (key, entry) in pairs.iter().filter(|(key, _)| key != "__proto__") {
306            path.push_key(key);
307            let item = T::build(entry, path);
308            path.pop();
309            built.push((key.clone(), item?));
310        }
311        Ok(Map(built))
312    }
313}
314
315/// An object with any keys and any values, kept in input order.
316#[derive(Clone, Debug, PartialEq)]
317pub struct OpenObject(pub Vec<(String, Value)>);
318
319impl Shape for OpenObject {
320    const CLASS: Class = Class::OpenObject;
321    const CATCH_ALL: bool = true;
322    fn catch_all_shape() -> Option<ShapeDef> {
323        Some(ShapeDef::new(Kind::Any))
324    }
325    fn build_rest(value: &Value, path: &mut Path, known: &[&str]) -> Result<Self, Issues> {
326        match value.as_object() {
327            Some(pairs) => Ok(OpenObject(
328                pairs
329                    .iter()
330                    .filter(|(key, _)| !known.contains(&key.as_str()))
331                    .cloned()
332                    .collect(),
333            )),
334            None => mismatch(path, "an object"),
335        }
336    }
337    fn reference() -> ShapeDef {
338        ShapeDef::new(Kind::Object(crate::def::ObjectDef::default()))
339    }
340    fn register(_: &mut Registry) {}
341    fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
342        match value.as_object() {
343            Some(pairs) => Ok(OpenObject(pairs.to_vec())),
344            None => mismatch(path, "an object"),
345        }
346    }
347}