1use crate::def::{Definitions, Kind, ObjectDef, ShapeDef};
4use crate::shape::Shape;
5use crate::value::Value;
6
7#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
9pub enum Draft {
10 Draft07,
12 #[default]
14 Draft2020_12,
15}
16
17#[derive(Clone, Copy, Debug, Default)]
19pub struct SchemaOptions<'a> {
20 pub draft: Draft,
21 pub id: Option<&'a str>,
23 pub title: Option<&'a str>,
25}
26
27#[derive(Clone, Copy)]
29struct Writer<'a> {
30 draft: Draft,
31 pointer: &'a str,
32}
33
34fn reference_token(name: &str) -> String {
37 let token = name.replace('~', "~0").replace('/', "~1");
38 let mut written = String::new();
39 for byte in token.bytes() {
40 if byte.is_ascii_alphanumeric() || b"-._~!$&'()*+,;=:@".contains(&byte) {
41 written.push(char::from(byte));
42 } else {
43 written.push_str(&format!("%{byte:02X}"));
44 }
45 }
46 written
47}
48
49fn number(value: f64) -> Value {
50 Value::Number(value)
51}
52
53fn count(value: usize) -> Value {
54 Value::Number(value as f64)
56}
57
58fn text(value: &str) -> Value {
59 Value::String(value.to_owned())
60}
61
62fn push(pairs: &mut Vec<(String, Value)>, key: &str, value: Value) {
63 pairs.push((key.to_owned(), value));
64}
65
66fn object(pairs: Vec<(String, Value)>) -> Value {
67 Value::Object(pairs)
68}
69
70fn typed(name: &str) -> Vec<(String, Value)> {
71 vec![("type".to_owned(), text(name))]
72}
73
74fn shape_schema(shape: &ShapeDef, options: Writer<'_>) -> Value {
76 let mut pairs = match &shape.kind {
77 Kind::Any => Vec::new(),
78 Kind::Null => typed("null"),
79 Kind::Bool => typed("boolean"),
80 Kind::ConstBool(flag) => vec![("const".to_owned(), Value::Bool(*flag))],
81 Kind::ConstString(value) => vec![("const".to_owned(), text(value))],
82 Kind::Enum(options) => vec![(
83 "enum".to_owned(),
84 Value::Array(options.iter().map(|option| text(option)).collect()),
85 )],
86 Kind::String {
87 min_length,
88 pattern,
89 } => {
90 let mut pairs = typed("string");
91 if let Some(least) = min_length {
92 push(&mut pairs, "minLength", count(*least));
93 }
94 if let Some(source) = pattern {
95 push(&mut pairs, "pattern", text(source));
96 }
97 pairs
98 }
99 Kind::Integer {
100 min,
101 exclusive_min,
102 max,
103 } => bounded("integer", [*min, *exclusive_min, *max]),
104 Kind::Number {
105 min,
106 exclusive_min,
107 max,
108 } => bounded("number", [*min, *exclusive_min, *max]),
109 Kind::Array {
110 items,
111 min_items,
112 max_items,
113 unique,
114 } => {
115 let mut pairs = typed("array");
116 if items.kind != Kind::Any || items.description.is_some() {
117 push(&mut pairs, "items", shape_schema(items, options));
118 }
119 if let Some(least) = min_items {
120 push(&mut pairs, "minItems", count(*least));
121 }
122 if let Some(most) = max_items {
123 push(&mut pairs, "maxItems", count(*most));
124 }
125 if *unique {
126 push(&mut pairs, "uniqueItems", Value::Bool(true));
127 }
128 pairs
129 }
130 Kind::Map {
131 values,
132 min_properties,
133 key_pattern,
134 } => {
135 let mut pairs = typed("object");
136 push(
137 &mut pairs,
138 "additionalProperties",
139 shape_schema(values, options),
140 );
141 if let Some(least) = min_properties {
142 push(&mut pairs, "minProperties", count(*least));
143 }
144 if let Some(source) = key_pattern {
145 push(
146 &mut pairs,
147 "propertyNames",
148 object(vec![("pattern".to_owned(), text(source))]),
149 );
150 }
151 pairs
152 }
153 Kind::Object(definition) => object_pairs(definition, options),
154 Kind::OneOf(alternatives) => vec![(
155 "oneOf".to_owned(),
156 Value::Array(
157 alternatives
158 .iter()
159 .map(|alternative| shape_schema(alternative, options))
160 .collect(),
161 ),
162 )],
163 Kind::Tagged { variants, .. } => vec![(
164 "oneOf".to_owned(),
165 Value::Array(
166 variants
167 .iter()
168 .map(|(_, variant)| shape_schema(variant, options))
169 .collect(),
170 ),
171 )],
172 Kind::Not(inner) => vec![("not".to_owned(), shape_schema(inner, options))],
173 Kind::AllOf(parts) => merged_or_all_of(parts, options),
174 Kind::Ref(name) => vec![(
175 "$ref".to_owned(),
176 text(&format!("{}/{}", options.pointer, reference_token(name))),
177 )],
178 };
179 if let Some(description) = &shape.description {
180 push(&mut pairs, "description", text(description));
181 }
182 object(pairs)
183}
184
185fn merged_or_all_of(parts: &[ShapeDef], options: Writer<'_>) -> Vec<(String, Value)> {
188 let written: Vec<Vec<(String, Value)>> = parts
189 .iter()
190 .map(|part| match shape_schema(part, options) {
191 Value::Object(pairs) => pairs,
192 other => unreachable!("a shape's schema is an object, not {other}"),
193 })
194 .collect();
195 let mut merged: Vec<(String, Value)> = Vec::new();
196 for pairs in &written {
197 if pairs
198 .iter()
199 .any(|(key, _)| merged.iter().any(|(known, _)| known == key))
200 {
201 return vec![(
202 "allOf".to_owned(),
203 Value::Array(written.into_iter().map(Value::Object).collect()),
204 )];
205 }
206 merged.extend(pairs.iter().cloned());
207 }
208 merged
209}
210
211fn bounded(name: &str, [min, exclusive_min, max]: [Option<f64>; 3]) -> Vec<(String, Value)> {
212 let mut pairs = typed(name);
213 if let Some(least) = min {
214 push(&mut pairs, "minimum", number(least));
215 }
216 if let Some(above) = exclusive_min {
217 push(&mut pairs, "exclusiveMinimum", number(above));
218 }
219 if let Some(most) = max {
220 push(&mut pairs, "maximum", number(most));
221 }
222 pairs
223}
224
225fn object_pairs(definition: &ObjectDef, options: Writer<'_>) -> Vec<(String, Value)> {
226 let mut pairs = typed("object");
227 if !definition.fields.is_empty() {
228 push(
229 &mut pairs,
230 "properties",
231 object(
232 definition
233 .fields
234 .iter()
235 .map(|field| (field.name.clone(), shape_schema(&field.shape, options)))
236 .collect(),
237 ),
238 );
239 }
240 let required: Vec<Value> = definition
241 .fields
242 .iter()
243 .filter(|field| field.required)
244 .map(|field| text(&field.name))
245 .collect();
246 if !required.is_empty() {
247 push(&mut pairs, "required", Value::Array(required));
248 }
249 if let Some(additional) = &definition.additional {
250 push(
251 &mut pairs,
252 "additionalProperties",
253 shape_schema(additional, options),
254 );
255 } else if definition.closed {
256 push(&mut pairs, "additionalProperties", Value::Bool(false));
257 }
258 for (keyword, keys) in [
259 ("anyOf", &definition.any_of_keys),
260 ("oneOf", &definition.one_of_keys),
261 ] {
262 if !keys.is_empty() {
263 let alternatives = keys
264 .iter()
265 .map(|key| {
266 object(vec![
267 (
268 "properties".to_owned(),
269 object(vec![(key.clone(), Value::Object(Vec::new()))]),
270 ),
271 ("required".to_owned(), Value::Array(vec![text(key)])),
272 ("type".to_owned(), text("object")),
273 ])
274 })
275 .collect();
276 push(&mut pairs, keyword, Value::Array(alternatives));
277 }
278 }
279 if let Some(least) = definition.min_properties {
280 push(&mut pairs, "minProperties", count(least));
281 }
282 if !definition.dependent_required.is_empty() {
283 let keyword = match options.draft {
284 Draft::Draft07 => "dependencies",
285 Draft::Draft2020_12 => "dependentRequired",
286 };
287 push(
288 &mut pairs,
289 keyword,
290 object(
291 definition
292 .dependent_required
293 .iter()
294 .map(|(key, others)| {
295 (
296 key.clone(),
297 Value::Array(others.iter().map(|other| text(other)).collect()),
298 )
299 })
300 .collect(),
301 ),
302 );
303 }
304 pairs
305}
306
307fn definitions_keyword(draft: Draft) -> &'static str {
308 match draft {
309 Draft::Draft07 => "definitions",
310 Draft::Draft2020_12 => "$defs",
311 }
312}
313
314pub fn schema_definitions(
317 definitions: &Definitions,
318 draft: Draft,
319 pointer: &str,
320) -> Vec<(String, Value)> {
321 let writer = Writer { draft, pointer };
322 definitions
323 .iter()
324 .map(|(name, shape)| (name.to_owned(), shape_schema(shape, writer)))
325 .collect()
326}
327
328pub fn json_schema(
332 root: &ShapeDef,
333 root_name: &str,
334 definitions: &Definitions,
335 options: &SchemaOptions<'_>,
336) -> Value {
337 let mut pairs = Vec::new();
338 push(
339 &mut pairs,
340 "$schema",
341 text(match options.draft {
342 Draft::Draft07 => "http://json-schema.org/draft-07/schema#",
343 Draft::Draft2020_12 => "https://json-schema.org/draft/2020-12/schema",
344 }),
345 );
346 if let Some(id) = options.id {
347 push(&mut pairs, "$id", text(id));
348 }
349 if let Some(title) = options.title {
350 push(&mut pairs, "title", text(title));
351 }
352 let pointer = match options.draft {
353 Draft::Draft07 => "#/definitions",
354 Draft::Draft2020_12 => "#/$defs",
355 };
356 let writer = Writer {
357 draft: options.draft,
358 pointer,
359 };
360 let Value::Object(body) = shape_schema(root, writer) else {
361 unreachable!("a shape's schema is an object")
362 };
363 pairs.extend(body);
364 let kept = if refers_to(definitions, root_name) || mentions(root, root_name) {
365 definitions.clone()
366 } else {
367 definitions.clone().without(root_name)
368 };
369 if !kept.is_empty() {
370 push(
371 &mut pairs,
372 definitions_keyword(options.draft),
373 object(schema_definitions(&kept, options.draft, pointer)),
374 );
375 }
376 object(pairs)
377}
378
379fn refers_to(definitions: &Definitions, name: &str) -> bool {
381 definitions
382 .iter()
383 .filter(|(entry, _)| *entry != name)
384 .any(|(_, shape)| mentions(shape, name))
385}
386
387fn mentions(shape: &ShapeDef, name: &str) -> bool {
388 match &shape.kind {
389 Kind::Ref(target) => target == name,
390 Kind::Array { items, .. } => mentions(items, name),
391 Kind::Map { values, .. } => mentions(values, name),
392 Kind::Object(definition) => {
393 definition
394 .fields
395 .iter()
396 .any(|field| mentions(&field.shape, name))
397 || definition
398 .additional
399 .as_ref()
400 .is_some_and(|additional| mentions(additional, name))
401 }
402 Kind::OneOf(alternatives) | Kind::AllOf(alternatives) => alternatives
403 .iter()
404 .any(|alternative| mentions(alternative, name)),
405 Kind::Not(inner) => mentions(inner, name),
406 Kind::Tagged { variants, .. } => {
407 variants.iter().any(|(_, variant)| mentions(variant, name))
408 }
409 _ => false,
410 }
411}
412
413pub fn schema_of<T: Shape>(root_name: &str, options: &SchemaOptions<'_>) -> Value {
415 json_schema(&T::definition(), root_name, &T::definitions(), options)
416}