Debian Codegraph @

src/_private/mod.rs

raw symbols SCIP
1 use crate::_alloc_prelude::*;
2 use crate::transform::{transform_immediate_subschemas, Transform};
3 use crate::{JsonSchema, Schema, SchemaGenerator};
4 use alloc::borrow::Cow;
5 use serde::Serialize;
6 use serde_json::{json, map::Entry, Map, Value};
7
8 mod regex_syntax;
9 mod rustdoc;
10
11 pub extern crate alloc;
12 pub extern crate serde_json;
13
14 pub use rustdoc::get_title_and_description;
15
16 pub fn json_schema_for_internally_tagged_enum_newtype_variant<T: ?Sized + JsonSchema>(
17 generator: &mut SchemaGenerator,
18 ) -> Schema {
19 let mut schema = T::json_schema(generator);
20
21 // Inline the newtype's inner schema if any of:
22 // - The type specifies that its schema should always be inlined
23 // - The generator settings specify that all schemas should be inlined
24 // - The inner type is a unit struct, which would cause an unsatisfiable schema due to mismatched `type`.
25 // In this case, we replace its type with "object" in `apply_internal_enum_variant_tag`
26 // - The inner schema specified `"additionalProperties": false` or `"unevaluatedProperties": false`,
27 // since that would disallow the variant tag. If additional/unevaluatedProperties is in the top-level
28 // schema, then we can leave it there, because it will "see" the variant tag property. But if it is
29 // nested e.g. in an `allOf`, then it must be removed, which is why we run `AllowUnknownProperties`
30 // but only on immediate subschemas.
31
32 let mut transform = AllowUnknownProperties::default();
33 transform_immediate_subschemas(&mut transform, &mut schema);
34
35 if T::inline_schema()
36 || generator.settings().inline_subschemas
37 || schema.get("type").and_then(Value::as_str) == Some("null")
38 || schema.get("additionalProperties").and_then(Value::as_bool) == Some(false)
39 || schema.get("unevaluatedProperties").and_then(Value::as_bool) == Some(false)
40 || transform.did_modify
41 {
42 return schema;
43 }
44
45 // ...otherwise, we can freely refer to the schema via a `$ref`
46 generator.subschema_for::<T>()
47 }
48
49 // Helper for generating schemas for flattened enums and `Option` fields.
50 pub fn json_schema_for_flatten<T: ?Sized + JsonSchema>(
51 generator: &mut SchemaGenerator,
52 required: bool,
53 ) -> Schema {
54 /// Non-generic inner function to reduce monomorphization overhead
55 fn inner(mut schema: Schema, is_optional: bool) -> Schema {
56 // Special handling for externally-tagged enums with unit variants.
57 // Unit variants are normally serialized as strings, but when flattened, are serialized
58 // as objects like `{ "VariantName": null }`
59 if let Some(unit_variants) = remove_unit_variants(&mut schema) {
60 if let Value::Array(one_of) = schema
61 .ensure_object()
62 .entry("oneOf")
63 .or_insert(Value::Array(Vec::new()))
64 {
65 one_of.extend(
66 unit_variants
67 .iter()
68 .filter_map(Value::as_str)
69 .map(|variant| {
70 json!({
71 "type": "object",
72 "properties": {
73 variant: {
74 "type": "null"
75 }
76 },
77 "required": [variant],
78 })
79 }),
80 );
81 }
82 }
83
84 if is_optional {
85 schema.remove("required");
86
87 // Handle `Option<>` of externally/internally/adjacently-tagged enums
88 if let Some(one_of) = schema.remove("oneOf") {
89 // We can't just add `{}` to the existing `oneOf`, because its items must be
90 // mutually-exclusive, and `{}` matches everything.
91 flatten(
92 &mut schema,
93 json_schema!({
94 "anyOf": [
95 { "oneOf": one_of },
96 {}
97 ]
98 }),
99 );
100 }
101
102 // Handle `Option<>` of untagged enums
103 if let Some(Value::Array(any_of)) = schema.get_mut("anyOf") {
104 let empty_object = Value::Object(Map::new());
105 if !any_of.contains(&empty_object) {
106 any_of.push(empty_object);
107 }
108 }
109 }
110
111 // Always allow aditional/unevaluated properties, because the outer struct determines
112 // whether it denies unknown fields.
113 AllowUnknownProperties::default().transform(&mut schema);
114
115 schema
116 }
117
118 fn remove_unit_variants(schema: &mut Schema) -> Option<Vec<Value>> {
119 // For enums that only have unit variants, all variants are in `enum`
120 if schema.get("type").and_then(Value::as_str) == Some("string") {
121 // Remove both `"enum": [...]`...
122 if let Some(Value::Array(a)) = schema.remove("enum") {
123 // ...and `"type": "string"`, since the variants are not serialized as strings
124 schema.remove("type");
125 return Some(a);
126 }
127 }
128
129 // For enums that have unit and other variants, unit variants are in the first `oneOf` item
130 let one_of = schema.get_mut("oneOf")?.as_array_mut()?;
131 let first = <&mut Schema>::try_from(one_of.get_mut(0)?).ok()?;
132 if first.get("type").and_then(Value::as_str) == Some("string") {
133 if let Some(Value::Array(a)) = first.remove("enum") {
134 one_of.remove(0);
135 return Some(a);
136 }
137 }
138
139 None
140 }
141
142 inner(
143 T::_schemars_private_non_optional_json_schema(generator),
144 T::_schemars_private_is_option() && !required,
145 )
146 }
147
148 #[derive(Default)]
149 struct AllowUnknownProperties {
150 did_modify: bool,
151 }
152
153 impl Transform for AllowUnknownProperties {
154 fn transform(&mut self, schema: &mut Schema) {
155 if schema.get("additionalProperties").and_then(Value::as_bool) == Some(false) {
156 schema.remove("additionalProperties");
157 self.did_modify = true;
158 }
159 if schema.get("unevaluatedProperties").and_then(Value::as_bool) == Some(false) {
160 schema.remove("unevaluatedProperties");
161 self.did_modify = true;
162 }
163
164 transform_immediate_subschemas(self, schema);
165 }
166 }
167
168 /// Hack to simulate specialization:
169 /// `MaybeSerializeWrapper(x).maybe_to_value()` will resolve to either
170 /// - The inherent method `MaybeSerializeWrapper::maybe_to_value(...)` if x is `Serialize`
171 /// - The trait method `NoSerialize::maybe_to_value(...)` from the blanket impl otherwise
172 #[doc(hidden)]
173 #[macro_export]
174 macro_rules! _schemars_maybe_to_value {
175 ($expression:expr) => {{
176 #[allow(unused_imports)]
177 use $crate::_private::{MaybeSerializeWrapper, NoSerialize as _};
178
179 MaybeSerializeWrapper($expression).maybe_to_value()
180 }};
181 }
182
183 pub struct MaybeSerializeWrapper<T>(pub T);
184
185 pub trait NoSerialize: Sized {
186 fn maybe_to_value(self) -> Option<Value> {
187 None
188 }
189 }
190
191 impl<T> NoSerialize for T {}
192
193 impl<T: Serialize> MaybeSerializeWrapper<T> {
194 pub fn maybe_to_value(self) -> Option<Value> {
195 serde_json::value::to_value(self.0).ok()
196 }
197 }
198
199 /// Create a schema for a unit enum variant
200 #[must_use]
201 pub fn new_unit_enum_variant(variant: &str) -> Schema {
202 json_schema!({
203 "type": "string",
204 "const": variant,
205 })
206 }
207
208 /// Hack to simulate specialization:
209 /// `<MaybeJsonSchemaWrapper<T>>::maybe_schema_id()` will resolve to either
210 /// - The inherent method `MaybeJsonSchemaWrapper::maybe_schema_id()` if T impls `JsonSchema`
211 /// - this returns `T::schema_id()`
212 /// - The trait method `NoJsonSchema::maybe_schema_id()` from the blanket impl otherwise
213 /// - this returns `core::any::type_name::<T>()``
214 #[doc(hidden)]
215 #[macro_export]
216 macro_rules! _schemars_maybe_schema_id {
217 ($ty:ty) => {{
218 #[allow(unused_imports)]
219 use $crate::_private::{MaybeJsonSchemaWrapper, NoJsonSchema as _};
220
221 <MaybeJsonSchemaWrapper<$ty>>::maybe_schema_id()
222 }};
223 }
224
225 pub struct MaybeJsonSchemaWrapper<T: ?Sized>(core::marker::PhantomData<T>);
226
227 pub trait NoJsonSchema {
228 #[must_use]
229 fn maybe_schema_id() -> Cow<'static, str> {
230 Cow::Borrowed(core::any::type_name::<Self>())
231 }
232 }
233
234 impl<T: ?Sized> NoJsonSchema for T {}
235
236 impl<T: JsonSchema + ?Sized> MaybeJsonSchemaWrapper<T> {
237 #[must_use]
238 pub fn maybe_schema_id() -> Cow<'static, str> {
239 T::schema_id()
240 }
241 }
242
243 /// Create a schema for an externally tagged enum variant
244 #[allow(clippy::needless_pass_by_value)]
245 #[must_use]
246 pub fn new_externally_tagged_enum_variant(variant: &str, sub_schema: Schema) -> Schema {
247 // TODO: this can be optimised by inserting the `sub_schema` as a `Value` rather than
248 // using the `json_schema!` macro which borrows and serializes the sub_schema
249 json_schema!({
250 "type": "object",
251 "properties": {
252 variant: sub_schema
253 },
254 "required": [variant],
255 "additionalProperties": false,
256 })
257 }
258
259 /// Update a schema for an internally tagged enum variant
260 pub fn apply_internal_enum_variant_tag(
261 schema: &mut Schema,
262 tag_name: &str,
263 variant: &str,
264 deny_unknown_fields: bool,
265 ) {
266 let obj = schema.ensure_object();
267 let is_unit = obj.get("type").and_then(Value::as_str) == Some("null");
268
269 obj.insert("type".to_owned(), "object".into());
270
271 if let Some(properties) = obj
272 .entry("properties")
273 .or_insert(Value::Object(Map::new()))
274 .as_object_mut()
275 {
276 properties.insert(
277 tag_name.to_string(),
278 json!({
279 "type": "string",
280 "const": variant
281 }),
282 );
283 }
284
285 if let Some(required) = obj
286 .entry("required")
287 .or_insert(Value::Array(Vec::new()))
288 .as_array_mut()
289 {
290 required.insert(0, tag_name.into());
291 }
292
293 if deny_unknown_fields && is_unit {
294 obj.entry("additionalProperties").or_insert(false.into());
295 }
296 }
297
298 pub fn insert_object_property(
299 schema: &mut Schema,
300 key: &str,
301 is_optional: bool,
302 sub_schema: Schema,
303 ) {
304 let obj = schema.ensure_object();
305 if let Some(properties) = obj
306 .entry("properties")
307 .or_insert(Value::Object(Map::new()))
308 .as_object_mut()
309 {
310 properties.insert(key.to_owned(), sub_schema.into());
311 }
312
313 if !is_optional {
314 if let Some(req) = obj
315 .entry("required")
316 .or_insert(Value::Array(Vec::new()))
317 .as_array_mut()
318 {
319 req.push(key.into());
320 }
321 }
322 }
323
324 pub fn insert_metadata_property_if_nonempty(
325 schema: &mut Schema,
326 key: &str,
327 value: impl Into<String>,
328 ) {
329 let value: String = value.into();
330 if !value.is_empty() {
331 schema.insert(key.to_owned(), value.into());
332 }
333 }
334
335 pub fn insert_validation_property(
336 schema: &mut Schema,
337 required_type: &str,
338 key: &str,
339 value: impl Into<Value>,
340 ) {
341 if schema.has_type(required_type) || (required_type == "number" && schema.has_type("integer")) {
342 schema.insert(key.to_owned(), value.into());
343 }
344 }
345
346 pub fn must_contain(schema: &mut Schema, substring: &str) {
347 let escaped = regex_syntax::escape(substring);
348 insert_validation_property(schema, "string", "pattern", escaped);
349 }
350
351 pub fn apply_inner_validation(schema: &mut Schema, f: fn(&mut Schema) -> ()) {
352 if let Some(inner_schema) = schema.get_mut("items").and_then(|i| i.try_into().ok()) {
353 f(inner_schema);
354 }
355 }
356
357 pub fn flatten(schema: &mut Schema, other: Schema) {
358 fn flatten_property(obj1: &mut Map<String, Value>, key: String, value2: Value) {
359 match obj1.entry(key) {
360 Entry::Vacant(vacant) => {
361 vacant.insert(value2);
362 }
363 Entry::Occupied(occupied) => {
364 match occupied.key().as_str() {
365 "required" | "allOf" => {
366 if let Value::Array(a1) = occupied.into_mut() {
367 if let Value::Array(a2) = value2 {
368 a1.extend(a2);
369 }
370 }
371 }
372 "properties" | "patternProperties" => {
373 if let Value::Object(o1) = occupied.into_mut() {
374 if let Value::Object(o2) = value2 {
375 o1.extend(o2);
376 }
377 }
378 }
379 "oneOf" | "anyOf" => {
380 let (key, current) = occupied.remove_entry();
381 flatten_property(
382 obj1,
383 "allOf".to_owned(),
384 json!([
385 { &key: current },
386 { key: value2 }
387 ]),
388 );
389 }
390 _ => {
391 // leave the original value as it is (don't modify `schema`)
392 }
393 }
394 }
395 }
396 }
397
398 match other.try_to_object() {
399 Err(false) => {}
400 Err(true) => {
401 if let Some(obj) = schema.as_object_mut() {
402 if !obj.contains_key("additionalProperties")
403 && !obj.contains_key("unevaluatedProperties")
404 {
405 let key = if contains_immediate_subschema(obj) {
406 "unevaluatedProperties"
407 } else {
408 "additionalProperties"
409 };
410 obj.insert(key.to_owned(), true.into());
411 }
412 }
413 }
414 Ok(mut obj2) => {
415 let obj1 = schema.ensure_object();
416
417 // For complex merges, replace `additionalProperties` with `unevaluatedProperties`
418 // which usually "works out better".
419 normalise_additional_unevaluated_properties(obj1, &obj2);
420 normalise_additional_unevaluated_properties(&mut obj2, obj1);
421
422 for (key, value2) in obj2 {
423 flatten_property(obj1, key, value2);
424 }
425 }
426 }
427 }
428
429 fn normalise_additional_unevaluated_properties(
430 schema_obj1: &mut Map<String, Value>,
431 schema_obj2: &Map<String, Value>,
432 ) {
433 if schema_obj1.contains_key("additionalProperties")
434 && (schema_obj2.contains_key("unevaluatedProperties")
435 || contains_immediate_subschema(schema_obj2))
436 {
437 let ap = schema_obj1.remove("additionalProperties");
438 schema_obj1.insert("unevaluatedProperties".to_owned(), ap.into());
439 }
440 }
441
442 fn contains_immediate_subschema(schema_obj: &Map<String, Value>) -> bool {
443 ["if", "allOf", "anyOf", "oneOf", "$ref"]
444 .into_iter()
445 .any(|k| schema_obj.contains_key(k))
446 }
447
448 pub(crate) fn allow_null(generator: &mut SchemaGenerator, schema: &mut Schema) {
449 fn is_null_schema(value: &Value) -> bool {
450 <&Schema>::try_from(value).is_ok_and(|s| s.has_type("null"))
451 }
452
453 match schema.try_as_object_mut() {
454 Ok(obj) => {
455 if obj.len() == 1
456 && obj
457 .get("anyOf")
458 .and_then(Value::as_array)
459 .is_some_and(|a| a.iter().any(is_null_schema))
460 {
461 return;
462 }
463
464 if contains_immediate_subschema(obj) {
465 *schema = json_schema!({
466 "anyOf": [
467 obj,
468 <()>::json_schema(generator)
469 ]
470 });
471 // No need to check `type`/`const`/`enum` because they're trivially not present
472 return;
473 }
474
475 if let Some(instance_type) = obj.get_mut("type") {
476 match instance_type {
477 Value::Array(array) => {
478 let null = Value::from("null");
479 if !array.contains(&null) {
480 array.push(null);
481 }
482 }
483 Value::String(string) if string != "null" => {
484 let current_type = core::mem::take(string).into();
485 *instance_type = Value::Array(vec![current_type, "null".into()]);
486 }
487 _ => {}
488 }
489 }
490
491 if let Some(c) = obj.remove("const") {
492 if !c.is_null() {
493 obj.insert("enum".to_string(), Value::Array(vec![c, Value::Null]));
494 }
495 } else if let Some(Value::Array(e)) = obj.get_mut("enum") {
496 if !e.contains(&Value::Null) {
497 e.push(Value::Null);
498 }
499 }
500 }
501 Err(true) => {}
502 Err(false) => {
503 *schema = <()>::json_schema(generator);
504 }
505 }
506 }
507
508 #[cfg(test)]
509 mod tests {
510 use pretty_assertions::assert_eq;
511
512 #[test]
513 fn nested_option_schemas() {
514 let mut option_schema = schema_for!(Option<Result<i8, u8>>);
515 option_schema.remove("title");
516 let mut nested_option_schema = schema_for!(Option<Option<Option<Result<i8, u8>>>>);
517 nested_option_schema.remove("title");
518
519 assert_eq!(option_schema, nested_option_schema);
520 }
521 }