Skip to main content

tilo_resource/schema/
table.rs

1//! What `#[derive(JsonSchema)]` emits: a type's schema as constant data, and
2//! the one builder that turns it into JSON. A derived type carries no schema
3//! code of its own, only its table.
4
5use serde_json::{Value, json};
6
7use super::{
8    adjacent, constant, describe, external, internal, object, one_of, range, string_enum, tuple,
9};
10
11/// A type's schema: its description and its shape.
12pub struct TypeSchema {
13    /// The type's doc comment, plain.
14    pub doc: &'static str,
15    pub body: Body,
16}
17
18/// The shape of a type's serde JSON form.
19pub enum Body {
20    /// `#[serde(transparent)]`: the field's schema, as it is.
21    Transparent(fn() -> Value),
22    /// A struct with fields.
23    Struct(Content),
24    /// A unit struct: `null`.
25    Unit,
26    /// An enum: one alternative per variant, tagged as serde tags it. An
27    /// externally tagged enum of undocumented unit variants (`plain`) is a
28    /// string enumeration.
29    Enum {
30        tagging: Tagging,
31        plain: bool,
32        variants: &'static [Variant],
33    },
34}
35
36/// The fields of a struct or variant.
37pub enum Content {
38    /// Named fields: a closed object.
39    Object(&'static [Field]),
40    /// One unnamed field: its schema.
41    Newtype(fn() -> Value),
42    /// Several unnamed fields: an array of that length.
43    Tuple(usize),
44}
45
46/// A named field.
47pub struct Field {
48    /// Its JSON name.
49    pub name: &'static str,
50    /// Its type's schema.
51    pub schema: fn() -> Value,
52    /// Whether serde needs it present.
53    pub required: bool,
54    /// Its doc comment, plain.
55    pub doc: &'static str,
56    /// `#[schema(range(..))]`: the bounds narrowing its type's.
57    pub range: Option<Bounds>,
58}
59
60/// A field's `(minimum, maximum)`, either side optional.
61pub type Bounds = fn() -> (Option<Value>, Option<Value>);
62
63/// An enum variant.
64pub struct Variant {
65    /// Its JSON name.
66    pub name: &'static str,
67    /// Its doc comment, plain.
68    pub doc: &'static str,
69    /// Its fields; `None` for a unit variant.
70    pub content: Option<Content>,
71}
72
73/// How an enum's variants are told apart in JSON.
74pub enum Tagging {
75    External,
76    Internal(&'static str),
77    Adjacent(&'static str, &'static str),
78}
79
80/// The JSON Schema `schema` describes.
81#[must_use]
82pub fn build(schema: &TypeSchema) -> Value {
83    match &schema.body {
84        Body::Transparent(inner) => inner(),
85        Body::Struct(content) => describe(content_schema(content), schema.doc),
86        Body::Unit => describe(json!({"type": "null"}), schema.doc),
87        Body::Enum {
88            tagging,
89            plain,
90            variants,
91        } => describe(enum_schema(tagging, *plain, variants), schema.doc),
92    }
93}
94
95fn content_schema(content: &Content) -> Value {
96    match content {
97        Content::Object(fields) => object(
98            fields
99                .iter()
100                .map(|field| {
101                    let mut schema = (field.schema)();
102                    if let Some(bounds) = field.range {
103                        let (minimum, maximum) = bounds();
104                        schema = range(schema, minimum, maximum);
105                    }
106                    (field.name, describe(schema, field.doc), field.required)
107                })
108                .collect(),
109        ),
110        Content::Newtype(inner) => inner(),
111        Content::Tuple(len) => tuple(*len),
112    }
113}
114
115fn enum_schema(tagging: &Tagging, plain: bool, variants: &[Variant]) -> Value {
116    if plain {
117        let names: Vec<&str> = variants.iter().map(|variant| variant.name).collect();
118        return string_enum(&names);
119    }
120    one_of(
121        variants
122            .iter()
123            .map(|variant| {
124                let content = variant.content.as_ref().map(content_schema);
125                let alternative = match (tagging, content) {
126                    (Tagging::External, None) => constant(variant.name),
127                    (Tagging::External, Some(content)) => external(variant.name, content),
128                    (Tagging::Internal(tag), None) => {
129                        internal(tag, variant.name, object(Vec::new()))
130                    }
131                    (Tagging::Internal(tag), Some(content)) => internal(tag, variant.name, content),
132                    (Tagging::Adjacent(tag, key), content) => {
133                        adjacent(tag, key, variant.name, content)
134                    }
135                };
136                describe(alternative, variant.doc)
137            })
138            .collect(),
139    )
140}