Skip to main content

trilean_json_shape/
lib.rs

1//! One definition of a JSON shape that validates documents and writes the JSON Schema and TypeScript declarations
2//! for them, so the three cannot disagree.
3//!
4//! A type derives [`Shape`], reading the serde attributes it already carries. Deserialising it through serde is
5//! validating, and the same descriptor writes the JSON Schema ([`json_schema`], [`schema_definitions`]) and the
6//! declarations ([`typescript_declarations`]).
7//!
8//! # Compile-time checks
9//!
10//! The derive refuses at compile time what could never validate: a constraint on a type it does not apply to, a
11//! pattern outside the supported subset, a flattened field or newtype variant that is not a struct, a property key
12//! used twice once a tag and flattened fields are counted, an attribute it does not read, and two unit variants in an
13//! untagged enum. Two different types with one definition name cannot be told apart at compile time, because they may
14//! live in different crates, so [`Definitions::of`] panics naming both; `#[shape(name = "...")]` renames one.
15//!
16//! # Limits that follow from JSON text, and from JSON Schema
17//!
18//! - Numbers are `f64`s, and a literal is read as the nearest double, as `JSON.parse` reads it (`serde_json` is built
19//!   with `float_roundtrip` for that). Written back, [`Value`]'s `Display` is the text `JSON.stringify` writes, and
20//!   its `Serialize` writes the same text, for every finite double, through `serde_json`'s raw value (see [`Value`]): it is
21//!   written for `serde_json`'s serialisers, and another serialiser shows a number that is not a whole number below 2^53 as
22//!   that type's marker, not as a number. Integer types are bounded by
23//!   [`MAX_SAFE_INTEGER`] in both the validator and the schema.
24//! - Reading goes through `serde_json`, which refuses nesting deeper than 128 levels and an unpaired surrogate
25//!   escape. A JSON Schema validator in JavaScript accepts both, so the schema accepts documents this crate cannot
26//!   read; the agreement tests leave them out for that reason.
27//! - A union is checked in time linear in the document: alternatives that cannot match the value's kind or lack a
28//!   required key are discarded first, and an alternative that accepted a value is remembered.
29//! - Patterns are a subset of ECMAScript regular expressions over Unicode scalar values, compiled to an automaton, so
30//!   matching is linear in the text.
31//! - In draft-07 a `$ref` ignores its sibling keywords, so a field of a named type that carries a description is
32//!   written as `{"$ref": ..., "description": ...}` and a validator that follows the draft to the letter drops the
33//!   description (and only the description: every validation keyword is in the referenced definition). Draft
34//!   2020-12 applies both. The consumer that publishes draft-07 decides, against its own published file, whether that
35//!   matters to it.
36
37// The derive names this crate by path, which inside the crate itself is `self`.
38extern crate self as trilean_json_shape;
39
40mod def;
41mod path;
42mod pattern;
43mod schema;
44mod shape;
45mod typescript;
46mod validate;
47mod value;
48
49pub use def::{Class, Constraint, Definitions, FieldDef, Kind, ObjectDef, Registry, ShapeDef};
50pub use path::{Issue, Issues, Path, PathSegment};
51pub use pattern::{Pattern, PatternError};
52pub use schema::{Draft, SchemaOptions, json_schema, schema_definitions, schema_of};
53pub use shape::{Map, OpenObject, Shape};
54pub use trilean_json_shape_derive::Shape;
55pub use typescript::typescript_declarations;
56pub use validate::{accepts, check, check_with_work, normalise};
57pub use value::{MAX_SAFE_INTEGER, Value, number_to_string};
58
59/// What the derive's generated code names; not part of the contract.
60#[doc(hidden)]
61pub mod private {
62    pub use serde;
63
64    use crate::def::{Class, Definitions, ShapeDef};
65    use crate::path::Path;
66    use crate::value::Value;
67
68    /// Whether `actual` is one of `allowed`, for a compile-time assertion.
69    pub const fn class_in(actual: Class, allowed: &[Class]) -> bool {
70        let mut position = 0;
71        while position < allowed.len() {
72            if allowed[position] as u8 == actual as u8 {
73                return true;
74            }
75            position += 1;
76        }
77        false
78    }
79
80    const fn same(left: &str, right: &str) -> bool {
81        let (left, right) = (left.as_bytes(), right.as_bytes());
82        if left.len() != right.len() {
83            return false;
84        }
85        let mut position = 0;
86        while position < left.len() {
87            if left[position] != right[position] {
88                return false;
89            }
90            position += 1;
91        }
92        true
93    }
94
95    /// Whether no key appears twice across `parts`, for a compile-time assertion.
96    pub const fn keys_unique(parts: &[&[&str]]) -> bool {
97        let mut first_part = 0;
98        while first_part < parts.len() {
99            let mut first_key = 0;
100            while first_key < parts[first_part].len() {
101                let mut second_part = first_part;
102                while second_part < parts.len() {
103                    let mut second_key = if second_part == first_part {
104                        first_key + 1
105                    } else {
106                        0
107                    };
108                    while second_key < parts[second_part].len() {
109                        if same(parts[first_part][first_key], parts[second_part][second_key]) {
110                            return false;
111                        }
112                        second_key += 1;
113                    }
114                    second_part += 1;
115                }
116                first_key += 1;
117            }
118            first_part += 1;
119        }
120        true
121    }
122
123    /// The keys of every part in one array of the length `N`, which is the sum of their lengths.
124    pub const fn concat_keys<const N: usize>(parts: &[&[&'static str]]) -> [&'static str; N] {
125        let mut joined = [""; N];
126        let mut written = 0;
127        let mut part = 0;
128        while part < parts.len() {
129            let mut key = 0;
130            while key < parts[part].len() {
131                joined[written] = parts[part][key];
132                written += 1;
133                key += 1;
134            }
135            part += 1;
136        }
137        assert!(written == N, "the length does not match the keys");
138        joined
139    }
140
141    /// Whether `alternative` accepts `value`, remembered in `path`.
142    pub fn decide(
143        path: &mut Path,
144        definitions: &Definitions,
145        alternative: &ShapeDef,
146        value: &Value,
147    ) -> bool {
148        crate::validate::decide(path, definitions, alternative, value)
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::Class;
155
156    #[test]
157    fn messages_quote_strings_as_serde_json_does() {
158        for text in [
159            "",
160            "plain",
161            "a \"quote\" and a \\ backslash",
162            "\n\r\t\u{8}\u{c}\u{0}\u{1f}\u{7f}",
163            "\u{2028}\u{2029}\u{e9}\u{1F600}",
164            "^[a-z]\\.json$",
165        ] {
166            assert_eq!(
167                crate::pattern::json_quote(text),
168                serde_json::to_string(text).expect("JSON"),
169                "{text:?}"
170            );
171        }
172    }
173
174    use super::private::{class_in, concat_keys, keys_unique};
175
176    #[test]
177    fn classes_are_matched_by_identity() {
178        assert!(class_in(Class::String, &[Class::Integer, Class::String]));
179        assert!(!class_in(Class::Named, &[Class::Integer, Class::String]));
180    }
181
182    #[test]
183    fn keys_are_unique_only_when_no_part_repeats_one() {
184        assert!(keys_unique(&[&["a", "b"], &["c"], &[]]));
185        assert!(!keys_unique(&[&["a", "b"], &["c", "a"]]));
186        assert!(!keys_unique(&[&["a", "a"]]));
187    }
188
189    #[test]
190    fn keys_are_joined_in_order() {
191        assert_eq!(
192            concat_keys::<3>(&[&["a"], &[], &["b", "c"]]),
193            ["a", "b", "c"]
194        );
195    }
196}