1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
use crate::*;
use std::ops::{Deref, DerefMut};

/// Describes the metadata and shape of a type.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Schema {
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub deprecated: Option<String>,

    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub description: Option<String>,

    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub name: Option<String>,

    #[cfg_attr(feature = "serde", serde(default, skip_serializing))]
    pub nullable: bool,

    pub ty: SchemaType,
}

impl Schema {
    /// Create a schema with the provided type.
    pub fn new(ty: impl Into<SchemaType>) -> Self {
        Self {
            ty: ty.into(),
            ..Default::default()
        }
    }

    /// Create an array schema.
    pub fn array(value: ArrayType) -> Self {
        Self::new(SchemaType::Array(Box::new(value)))
    }

    /// Create a boolean schema.
    pub fn boolean(value: BooleanType) -> Self {
        Self::new(SchemaType::Boolean(Box::new(value)))
    }

    /// Create an enum schema.
    pub fn enumerable(value: EnumType) -> Self {
        Self::new(SchemaType::Enum(Box::new(value)))
    }

    /// Create a float schema.
    pub fn float(value: FloatType) -> Self {
        Self::new(SchemaType::Float(Box::new(value)))
    }

    /// Create an integer schema.
    pub fn integer(value: IntegerType) -> Self {
        Self::new(SchemaType::Integer(Box::new(value)))
    }

    /// Create a literal schema.
    pub fn literal(value: LiteralType) -> Self {
        Self::new(SchemaType::Literal(Box::new(value)))
    }

    /// Create a literal schema with the provided value.
    pub fn literal_value(value: LiteralValue) -> Self {
        Self::new(SchemaType::Literal(Box::new(LiteralType::new(value))))
    }

    /// Create an object schema.
    pub fn object(value: ObjectType) -> Self {
        Self::new(SchemaType::Object(Box::new(value)))
    }

    /// Create a string schema.
    pub fn string(value: StringType) -> Self {
        Self::new(SchemaType::String(Box::new(value)))
    }

    /// Create a struct schema.
    pub fn structure(value: StructType) -> Self {
        Self::new(SchemaType::Struct(Box::new(value)))
    }

    /// Create a tuple schema.
    pub fn tuple(value: TupleType) -> Self {
        Self::new(SchemaType::Tuple(Box::new(value)))
    }

    /// Create a union schema.
    pub fn union(value: UnionType) -> Self {
        Self::new(SchemaType::Union(Box::new(value)))
    }

    /// Create a null schema.
    pub fn null() -> Self {
        Self::new(SchemaType::Null)
    }

    /// Create an unknown schema.
    pub fn unknown() -> Self {
        Self::new(SchemaType::Unknown)
    }

    /// Convert the current schema to a nullable type. If already nullable,
    /// do nothing, otherwise convert to a union.
    pub fn nullify(&mut self) {
        if self.nullable {
            // May already be a null union through inferrence
            return;
        }

        self.nullable = true;

        if let SchemaType::Union(inner) = &mut self.ty {
            // If the union has an explicit name, then we can assume it's a distinct
            // type, so we shouldn't add null to it and alter the intended type.
            if self.name.is_none() {
                if !inner.variants_types.iter().any(|t| t.is_null()) {
                    inner.variants_types.push(Box::new(Schema::null()));
                }

                return;
            }
        }

        // Convert to a nullable union
        let mut new_schema = Schema::new(std::mem::replace(&mut self.ty, SchemaType::Unknown));
        new_schema.name = self.name.take();
        new_schema.description.clone_from(&self.description);
        new_schema.deprecated.clone_from(&self.deprecated);

        self.ty = SchemaType::Union(Box::new(UnionType::new_any([new_schema, Schema::null()])));
    }

    /// Mark the inner schema type as partial. Only structs and unions can be marked partial,
    /// but arrays and objects will also be recursively set to update the inner type.
    pub fn partialize(&mut self) {
        match &mut self.ty {
            SchemaType::Array(ref mut inner) => inner.items_type.partialize(),
            SchemaType::Object(ref mut inner) => inner.value_type.partialize(),
            SchemaType::Struct(ref mut inner) => {
                inner.partial = true;
            }
            SchemaType::Union(ref mut inner) => {
                inner.partial = true;

                // This is to handle things wrapped in `Option`, is it correct?
                // Not sure of a better way to do this at the moment...
                let is_nullable = inner.variants_types.iter().any(|t| t.ty.is_null());

                if is_nullable {
                    for item in inner.variants_types.iter_mut() {
                        if !item.is_null() {
                            item.partialize();
                        }
                    }
                }
            }
            _ => {}
        };
    }
}

impl Deref for Schema {
    type Target = SchemaType;

    fn deref(&self) -> &Self::Target {
        &self.ty
    }
}

impl DerefMut for Schema {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.ty
    }
}

impl From<Schema> for SchemaType {
    fn from(val: Schema) -> Self {
        val.ty
    }
}

impl Schematic for Schema {}

fn is_false(value: &bool) -> bool {
    !value
}

/// Describes the metadata and shape of a field within a struct or enum.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct SchemaField {
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub comment: Option<String>,

    pub schema: Schema,

    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub deprecated: Option<String>,

    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub env_var: Option<String>,

    #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "is_false"))]
    pub hidden: bool,

    #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "is_false"))]
    pub nullable: bool,

    #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "is_false"))]
    pub optional: bool,

    #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "is_false"))]
    pub read_only: bool,

    #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "is_false"))]
    pub write_only: bool,
}

impl SchemaField {
    pub fn new(schema: impl Into<Schema>) -> Self {
        Self {
            schema: schema.into(),
            ..Default::default()
        }
    }
}

impl From<SchemaField> for Schema {
    fn from(val: SchemaField) -> Self {
        val.schema
    }
}

impl From<Schema> for SchemaField {
    fn from(mut schema: Schema) -> Self {
        SchemaField {
            comment: schema.description.take(),
            schema,
            ..Default::default()
        }
    }
}

impl Schematic for SchemaField {}