Remove usages of gen identifier (#323)

`gen` is a reserved keyword in rust 2024, making it very awkward to use as a module/variable name.
This commit is contained in:
Graham Esau 2024-08-21 16:15:13 +01:00 committed by GitHub
parent 8142be1ea2
commit b4f214f6dc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
42 changed files with 186 additions and 171 deletions

View file

@ -267,7 +267,7 @@ Validator docs: [required](https://github.com/Keats/validator#required) / [requi
</h3> </h3>
Set on a variant or field to generate this field's schema using the given function. This function must be callable as `fn(&mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema`. Set on a variant or field to generate this field's schema using the given function. This function must be callable as `fn(&mut schemars::SchemaGenerator) -> schemars::schema::Schema`.
<h3 id="title-description"> <h3 id="title-description">

View file

@ -60,10 +60,10 @@ The default implementation of this function returns `Self::schema_name()`.
## json_schema ## json_schema
```rust ```rust
fn json_schema(gen: &mut gen::SchemaGenerator) -> Schema; fn json_schema(generator: &mut SchemaGenerator) -> Schema;
``` ```
This function creates the JSON schema itself. The `gen` argument can be used to check the schema generation settings, or to get schemas for other types. If you do need schemas for other types, you should call the `gen.subschema_for::<T>()` method instead of `<T>::json_schema(gen)`, as `subschema_for` can add `T`'s schema to the root schema's `$defs` so that it does not need to be duplicated when used more than once. This function creates the JSON schema itself. The `generator` argument can be used to check the schema generation settings, or to get schemas for other types. If you do need schemas for other types, you should call the `generator.subschema_for::<T>()` method instead of `<T>::json_schema(generator)`, as `subschema_for` can add `T`'s schema to the root schema's `$defs` so that it does not need to be duplicated when used more than once.
`json_schema` should not return a `$ref` schema. `json_schema` should not return a `$ref` schema.

View file

@ -6,7 +6,7 @@ permalink: /generating/
# Generating Schemas # Generating Schemas
The easiest way to generate a schema for a type that implements is to use the [`schema_for!` macro](https://docs.rs/schemars/latest/schemars/macro.schema_for.html), like so: The easiest way to generate a schema for a type that implements is to use the [`schema_for!` macro](https://docs.rs/schemars/1.0.0--latest/schemars/macro.schema_for.html), like so:
```rust ```rust
let my_schema = schema_for!(MyStruct); let my_schema = schema_for!(MyStruct);
@ -14,10 +14,10 @@ let my_schema = schema_for!(MyStruct);
This will create a schema that conforms to [JSON Schema 2020-12](https://json-schema.org/specification-links#2020-12), but this is liable to change in a future version of Schemars if support for other JSON Schema versions is added. This will create a schema that conforms to [JSON Schema 2020-12](https://json-schema.org/specification-links#2020-12), but this is liable to change in a future version of Schemars if support for other JSON Schema versions is added.
If you want more control over how the schema is generated, you can use the [`gen` module](https://docs.rs/schemars/latest/schemars/gen/). There are two main types in this module: If you want more control over how the schema is generated, you can use the [`generate` module](https://docs.rs/schemars/1.0.0--latest/schemars/generate/). There are two main types in this module:
- [`SchemaSettings`](https://docs.rs/schemars/latest/schemars/gen/struct.SchemaSettings.html), which defines what JSON Schema features should be used when generating schemas (for example, how `Option`s should be represented). - [`SchemaSettings`](https://docs.rs/schemars/1.0.0--latest/schemars/generate/struct.SchemaSettings.html), which defines what JSON Schema features should be used when generating schemas (for example, how `Option`s should be represented).
- [`SchemaGenerator`](https://docs.rs/schemars/latest/schemars/gen/struct.SchemaGenerator.html), which manages the generation of a schema document. - [`SchemaGenerator`](https://docs.rs/schemars/1.0.0--latest/schemars/generate/struct.SchemaGenerator.html), which manages the generation of a schema document.
For example, to generate a schema that conforms to [JSON Schema Draft 7](https://json-schema.org/specification-links.html#draft-7): For example, to generate a schema that conforms to [JSON Schema Draft 7](https://json-schema.org/specification-links.html#draft-7):
@ -30,7 +30,7 @@ See the API documentation for more info on how to use those types for custom sch
## Schema from Example Value ## Schema from Example Value
If you want a schema for a type that can't/doesn't implement `JsonSchema`, but does implement `serde::Serialize`, then you can generate a JSON schema from a value of that type using the [`schema_for_value!` macro](https://docs.rs/schemars/latest/schemars/macro.schema_for_value.html). However, this schema will generally be less precise than if the type implemented `JsonSchema` - particularly when it involves enums, since schemars will not make any assumptions about the structure of an enum based on a single variant. If you want a schema for a type that can't/doesn't implement `JsonSchema`, but does implement `serde::Serialize`, then you can generate a JSON schema from a value of that type using the [`schema_for_value!` macro](https://docs.rs/schemars/1.0.0--latest/schemars/macro.schema_for_value.html). However, this schema will generally be less precise than if the type implemented `JsonSchema` - particularly when it involves enums, since schemars will not make any assumptions about the structure of an enum based on a single variant.
```rust ```rust
let value = MyStruct { foo = 123 }; let value = MyStruct { foo = 123 };

View file

@ -19,8 +19,8 @@ pub struct MyStruct {
pub bool_normal: bool, pub bool_normal: bool,
} }
fn make_custom_schema(gen: &mut SchemaGenerator) -> Schema { fn make_custom_schema(generator: &mut SchemaGenerator) -> Schema {
let mut schema = String::json_schema(gen); let mut schema = String::json_schema(generator);
schema schema
.ensure_object() .ensure_object()
.insert("format".into(), "boolean".into()); .insert("format".into(), "boolean".into());

View file

@ -1,4 +1,4 @@
use schemars::{gen::SchemaSettings, JsonSchema}; use schemars::{generate::SchemaSettings, JsonSchema};
#[derive(JsonSchema)] #[derive(JsonSchema)]
pub struct MyStruct { pub struct MyStruct {
@ -18,7 +18,7 @@ fn main() {
s.option_nullable = true; s.option_nullable = true;
s.option_add_null_type = false; s.option_add_null_type = false;
}); });
let gen = settings.into_generator(); let generator = settings.into_generator();
let schema = gen.into_root_schema_for::<MyStruct>(); let schema = generator.into_root_schema_for::<MyStruct>();
println!("{}", serde_json::to_string_pretty(&schema).unwrap()); println!("{}", serde_json::to_string_pretty(&schema).unwrap());
} }

View file

@ -7,6 +7,6 @@ summary: Generating a schema using custom settings which changes how Option<T> i
# Custom Schema Settings # Custom Schema Settings
The `gen` module allows you to customise how schemas are generated. For example, the default behaviour for `Option<T>` is to include `null` in the schema's `type`s, but we can instead add a `nullable` property to its schema: The `generate` module allows you to customise how schemas are generated. For example, the default behaviour for `Option<T>` is to include `null` in the schema's `type`s, but we can instead add a `nullable` property to its schema:
{% include example.md name="custom_settings" %} {% include example.md name="custom_settings" %}

View file

@ -7,7 +7,7 @@ nav_order: 1
Schemars is a library to generate JSON Schema documents from Rust data structures. Schemars is a library to generate JSON Schema documents from Rust data structures.
This is built on Rust's trait system - any type which implements the [`JsonSchema`](https://docs.rs/schemars/latest/schemars/trait.JsonSchema.html) trait can have a JSON Schema generated describing that type. Schemars implements this on many standard library types, and provides a derive macro to automatically implement it on custom types. This is built on Rust's trait system - any type which implements the [`JsonSchema`](https://docs.rs/schemars/1.0.0--latest/schemars/trait.JsonSchema.html) trait can have a JSON Schema generated describing that type. Schemars implements this on many standard library types, and provides a derive macro to automatically implement it on custom types.
One of the main aims of this library is compatibility with [Serde](https://github.com/serde-rs/serde). Any generated schema _should_ match how [serde_json](https://github.com/serde-rs/json) would serialize/deserialize to/from JSON. To support this, Schemars will check for any `#[serde(...)]` attributes on types that derive `JsonSchema`, and adjust the generated schema accordingly. One of the main aims of this library is compatibility with [Serde](https://github.com/serde-rs/serde). Any generated schema _should_ match how [serde_json](https://github.com/serde-rs/json) would serialize/deserialize to/from JSON. To support this, Schemars will check for any `#[serde(...)]` attributes on types that derive `JsonSchema`, and adjust the generated schema accordingly.

View file

@ -19,8 +19,8 @@ pub struct MyStruct {
pub bool_normal: bool, pub bool_normal: bool,
} }
fn make_custom_schema(gen: &mut SchemaGenerator) -> Schema { fn make_custom_schema(generator: &mut SchemaGenerator) -> Schema {
let mut schema = String::json_schema(gen); let mut schema = String::json_schema(generator);
schema schema
.ensure_object() .ensure_object()
.insert("format".into(), "boolean".into()); .insert("format".into(), "boolean".into());

View file

@ -1,4 +1,4 @@
use schemars::{gen::SchemaSettings, JsonSchema}; use schemars::{generate::SchemaSettings, JsonSchema};
#[derive(JsonSchema)] #[derive(JsonSchema)]
pub struct MyStruct { pub struct MyStruct {
@ -18,7 +18,7 @@ fn main() {
s.option_nullable = true; s.option_nullable = true;
s.option_add_null_type = false; s.option_add_null_type = false;
}); });
let gen = settings.into_generator(); let generator = settings.into_generator();
let schema = gen.into_root_schema_for::<MyStruct>(); let schema = generator.into_root_schema_for::<MyStruct>();
println!("{}", serde_json::to_string_pretty(&schema).unwrap()); println!("{}", serde_json::to_string_pretty(&schema).unwrap());
} }

View file

@ -5,10 +5,10 @@ use serde_json::{json, map::Entry, Map, Value};
// Helper for generating schemas for flattened `Option` fields. // Helper for generating schemas for flattened `Option` fields.
pub fn json_schema_for_flatten<T: ?Sized + JsonSchema>( pub fn json_schema_for_flatten<T: ?Sized + JsonSchema>(
gen: &mut SchemaGenerator, generator: &mut SchemaGenerator,
required: bool, required: bool,
) -> Schema { ) -> Schema {
let mut schema = T::_schemars_private_non_optional_json_schema(gen); let mut schema = T::_schemars_private_non_optional_json_schema(generator);
if T::_schemars_private_is_option() && !required { if T::_schemars_private_is_option() && !required {
if let Some(object) = schema.as_object_mut() { if let Some(object) = schema.as_object_mut() {

View file

@ -127,13 +127,13 @@ impl SchemaSettings {
/// ///
/// # Example /// # Example
/// ``` /// ```
/// use schemars::gen::{SchemaGenerator, SchemaSettings}; /// use schemars::generate::{SchemaGenerator, SchemaSettings};
/// ///
/// let settings = SchemaSettings::default().with(|s| { /// let settings = SchemaSettings::default().with(|s| {
/// s.option_nullable = true; /// s.option_nullable = true;
/// s.option_add_null_type = false; /// s.option_add_null_type = false;
/// }); /// });
/// let gen = settings.into_generator(); /// let generator = settings.into_generator();
/// ``` /// ```
pub fn with(mut self, configure_fn: impl FnOnce(&mut Self)) -> Self { pub fn with(mut self, configure_fn: impl FnOnce(&mut Self)) -> Self {
configure_fn(&mut self); configure_fn(&mut self);
@ -163,8 +163,8 @@ impl SchemaSettings {
/// foo: i32, /// foo: i32,
/// } /// }
/// ///
/// let gen = SchemaGenerator::default(); /// let generator = SchemaGenerator::default();
/// let schema = gen.into_root_schema_for::<MyStruct>(); /// let schema = generator.into_root_schema_for::<MyStruct>();
/// ``` /// ```
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct SchemaGenerator { pub struct SchemaGenerator {
@ -208,8 +208,8 @@ impl SchemaGenerator {
/// ``` /// ```
/// use schemars::SchemaGenerator; /// use schemars::SchemaGenerator;
/// ///
/// let gen = SchemaGenerator::default(); /// let generator = SchemaGenerator::default();
/// let settings = gen.settings(); /// let settings = generator.settings();
/// ///
/// assert_eq!(settings.option_add_null_type, true); /// assert_eq!(settings.option_add_null_type, true);
/// ``` /// ```
@ -361,7 +361,7 @@ impl SchemaGenerator {
value: &T, value: &T,
) -> Result<Schema, serde_json::Error> { ) -> Result<Schema, serde_json::Error> {
let mut schema = value.serialize(crate::ser::Serializer { let mut schema = value.serialize(crate::ser::Serializer {
gen: self, generator: self,
include_title: true, include_title: true,
})?; })?;
@ -392,7 +392,7 @@ impl SchemaGenerator {
value: &T, value: &T,
) -> Result<Schema, serde_json::Error> { ) -> Result<Schema, serde_json::Error> {
let mut schema = value.serialize(crate::ser::Serializer { let mut schema = value.serialize(crate::ser::Serializer {
gen: &mut self, generator: &mut self,
include_title: true, include_title: true,
})?; })?;
@ -415,28 +415,32 @@ impl SchemaGenerator {
fn json_schema_internal<T: ?Sized + JsonSchema>(&mut self, id: CowStr) -> Schema { fn json_schema_internal<T: ?Sized + JsonSchema>(&mut self, id: CowStr) -> Schema {
struct PendingSchemaState<'a> { struct PendingSchemaState<'a> {
gen: &'a mut SchemaGenerator, generator: &'a mut SchemaGenerator,
id: CowStr, id: CowStr,
did_add: bool, did_add: bool,
} }
impl<'a> PendingSchemaState<'a> { impl<'a> PendingSchemaState<'a> {
fn new(gen: &'a mut SchemaGenerator, id: CowStr) -> Self { fn new(generator: &'a mut SchemaGenerator, id: CowStr) -> Self {
let did_add = gen.pending_schema_ids.insert(id.clone()); let did_add = generator.pending_schema_ids.insert(id.clone());
Self { gen, id, did_add } Self {
generator,
id,
did_add,
}
} }
} }
impl Drop for PendingSchemaState<'_> { impl Drop for PendingSchemaState<'_> {
fn drop(&mut self) { fn drop(&mut self) {
if self.did_add { if self.did_add {
self.gen.pending_schema_ids.remove(&self.id); self.generator.pending_schema_ids.remove(&self.id);
} }
} }
} }
let pss = PendingSchemaState::new(self, id); let pss = PendingSchemaState::new(self, id);
T::json_schema(pss.gen) T::json_schema(pss.generator)
} }
fn add_definitions( fn add_definitions(
@ -514,7 +518,7 @@ fn json_pointer_mut<'a>(
/// # Example /// # Example
/// ``` /// ```
/// use schemars::transform::Transform; /// use schemars::transform::Transform;
/// use schemars::gen::GenTransform; /// use schemars::generate::GenTransform;
/// ///
/// #[derive(Debug, Clone)] /// #[derive(Debug, Clone)]
/// struct MyTransform; /// struct MyTransform;
@ -534,7 +538,7 @@ pub trait GenTransform: Transform + DynClone + Any + Send {
/// # Example /// # Example
/// To remove a specific transform from an instance of `SchemaSettings`: /// To remove a specific transform from an instance of `SchemaSettings`:
/// ``` /// ```
/// use schemars::gen::SchemaSettings; /// use schemars::generate::SchemaSettings;
/// use schemars::transform::ReplaceBoolSchemas; /// use schemars::transform::ReplaceBoolSchemas;
/// ///
/// let mut settings = SchemaSettings::openapi3(); /// let mut settings = SchemaSettings::openapi3();
@ -553,7 +557,7 @@ pub trait GenTransform: Transform + DynClone + Any + Send {
/// # Example /// # Example
/// To modify a specific transform in an instance of `SchemaSettings`: /// To modify a specific transform in an instance of `SchemaSettings`:
/// ``` /// ```
/// use schemars::gen::SchemaSettings; /// use schemars::generate::SchemaSettings;
/// use schemars::transform::ReplaceBoolSchemas; /// use schemars::transform::ReplaceBoolSchemas;
/// ///
/// let mut settings = SchemaSettings::openapi3(); /// let mut settings = SchemaSettings::openapi3();

View file

@ -1,5 +1,5 @@
use crate::SchemaGenerator;
use crate::_alloc_prelude::*; use crate::_alloc_prelude::*;
use crate::gen::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema}; use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow; use alloc::borrow::Cow;
@ -37,10 +37,10 @@ macro_rules! array_impls {
format!("[{}; {}]", $len, T::schema_id()).into() format!("[{}; {}]", $len, T::schema_id()).into()
} }
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(generator: &mut SchemaGenerator) -> Schema {
json_schema!({ json_schema!({
"type": "array", "type": "array",
"items": serde_json::Value::from(gen.subschema_for::<T>()), "items": serde_json::Value::from(generator.subschema_for::<T>()),
"minItems": $len, "minItems": $len,
"maxItems": $len, "maxItems": $len,
}) })

View file

@ -1,5 +1,5 @@
use crate::SchemaGenerator;
use crate::_alloc_prelude::*; use crate::_alloc_prelude::*;
use crate::gen::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema}; use crate::{json_schema, JsonSchema, Schema};
use arrayvec07::{ArrayString, ArrayVec}; use arrayvec07::{ArrayString, ArrayVec};
@ -17,10 +17,10 @@ where
format!("Array_up_to_size_{}_of_{}", CAP, T::schema_name()).into() format!("Array_up_to_size_{}_of_{}", CAP, T::schema_name()).into()
} }
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(generator: &mut SchemaGenerator) -> Schema {
json_schema!({ json_schema!({
"type": "array", "type": "array",
"items": gen.subschema_for::<T>(), "items": generator.subschema_for::<T>(),
"maxItems": CAP "maxItems": CAP
}) })
} }

View file

@ -1,4 +1,4 @@
use crate::gen::SchemaGenerator; use crate::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema}; use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow; use alloc::borrow::Cow;
use chrono04::prelude::*; use chrono04::prelude::*;

View file

@ -1,5 +1,5 @@
use crate::SchemaGenerator;
use crate::_alloc_prelude::*; use crate::_alloc_prelude::*;
use crate::gen::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema}; use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow; use alloc::borrow::Cow;
use core::ops::{Bound, Range, RangeInclusive}; use core::ops::{Bound, Range, RangeInclusive};
@ -16,10 +16,10 @@ impl<T: JsonSchema> JsonSchema for Option<T> {
format!("Option<{}>", T::schema_id()).into() format!("Option<{}>", T::schema_id()).into()
} }
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(generator: &mut SchemaGenerator) -> Schema {
let mut schema = gen.subschema_for::<T>(); let mut schema = generator.subschema_for::<T>();
if gen.settings().option_add_null_type { if generator.settings().option_add_null_type {
schema = match schema.try_to_object() { schema = match schema.try_to_object() {
Ok(mut obj) => { Ok(mut obj) => {
let instance_type = obj.get_mut("type"); let instance_type = obj.get_mut("type");
@ -43,17 +43,17 @@ impl<T: JsonSchema> JsonSchema for Option<T> {
_ => json_schema!({ _ => json_schema!({
"anyOf": [ "anyOf": [
obj, obj,
<()>::json_schema(gen) <()>::json_schema(generator)
] ]
}), }),
} }
} }
Err(true) => true.into(), Err(true) => true.into(),
Err(false) => <()>::json_schema(gen), Err(false) => <()>::json_schema(generator),
} }
} }
if gen.settings().option_nullable { if generator.settings().option_nullable {
schema schema
.ensure_object() .ensure_object()
.insert("nullable".into(), true.into()); .insert("nullable".into(), true.into());
@ -62,8 +62,8 @@ impl<T: JsonSchema> JsonSchema for Option<T> {
schema schema
} }
fn _schemars_private_non_optional_json_schema(gen: &mut SchemaGenerator) -> Schema { fn _schemars_private_non_optional_json_schema(generator: &mut SchemaGenerator) -> Schema {
T::_schemars_private_non_optional_json_schema(gen) T::_schemars_private_non_optional_json_schema(generator)
} }
fn _schemars_private_is_option() -> bool { fn _schemars_private_is_option() -> bool {
@ -80,20 +80,20 @@ impl<T: JsonSchema, E: JsonSchema> JsonSchema for Result<T, E> {
format!("Result<{}, {}>", T::schema_id(), E::schema_id()).into() format!("Result<{}, {}>", T::schema_id(), E::schema_id()).into()
} }
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(generator: &mut SchemaGenerator) -> Schema {
json_schema!({ json_schema!({
"oneOf": [ "oneOf": [
{ {
"type": "object", "type": "object",
"properties": { "properties": {
"Ok": gen.subschema_for::<T>() "Ok": generator.subschema_for::<T>()
}, },
"required": ["Ok"] "required": ["Ok"]
}, },
{ {
"type": "object", "type": "object",
"properties": { "properties": {
"Err": gen.subschema_for::<E>() "Err": generator.subschema_for::<E>()
}, },
"required": ["Err"] "required": ["Err"]
} }
@ -111,20 +111,20 @@ impl<T: JsonSchema> JsonSchema for Bound<T> {
format!("Bound<{}>", T::schema_id()).into() format!("Bound<{}>", T::schema_id()).into()
} }
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(generator: &mut SchemaGenerator) -> Schema {
json_schema!({ json_schema!({
"oneOf": [ "oneOf": [
{ {
"type": "object", "type": "object",
"properties": { "properties": {
"Included": gen.subschema_for::<T>() "Included": generator.subschema_for::<T>()
}, },
"required": ["Included"] "required": ["Included"]
}, },
{ {
"type": "object", "type": "object",
"properties": { "properties": {
"Excluded": gen.subschema_for::<T>() "Excluded": generator.subschema_for::<T>()
}, },
"required": ["Excluded"] "required": ["Excluded"]
}, },
@ -146,8 +146,8 @@ impl<T: JsonSchema> JsonSchema for Range<T> {
format!("Range<{}>", T::schema_id()).into() format!("Range<{}>", T::schema_id()).into()
} }
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(generator: &mut SchemaGenerator) -> Schema {
let subschema = gen.subschema_for::<T>(); let subschema = generator.subschema_for::<T>();
json_schema!({ json_schema!({
"type": "object", "type": "object",
"properties": { "properties": {

View file

@ -1,4 +1,4 @@
use crate::gen::SchemaGenerator; use crate::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema}; use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow; use alloc::borrow::Cow;

View file

@ -1,5 +1,5 @@
use crate::_alloc_prelude::*; use crate::_alloc_prelude::*;
use crate::gen::SchemaGenerator; use crate::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema}; use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow; use alloc::borrow::Cow;
use either1::Either; use either1::Either;
@ -15,9 +15,9 @@ impl<L: JsonSchema, R: JsonSchema> JsonSchema for Either<L, R> {
format!("either::Either<{}, {}>", L::schema_id(), R::schema_id()).into() format!("either::Either<{}, {}>", L::schema_id(), R::schema_id()).into()
} }
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(generator: &mut SchemaGenerator) -> Schema {
json_schema!({ json_schema!({
"anyOf": [gen.subschema_for::<L>(), gen.subschema_for::<R>()], "anyOf": [generator.subschema_for::<L>(), generator.subschema_for::<R>()],
}) })
} }
} }

View file

@ -1,5 +1,5 @@
use crate::SchemaGenerator;
use crate::_alloc_prelude::*; use crate::_alloc_prelude::*;
use crate::gen::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema}; use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow; use alloc::borrow::Cow;
use std::ffi::{CStr, CString, OsStr, OsString}; use std::ffi::{CStr, CString, OsStr, OsString};
@ -13,20 +13,20 @@ impl JsonSchema for OsString {
"std::ffi::OsString".into() "std::ffi::OsString".into()
} }
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(generator: &mut SchemaGenerator) -> Schema {
json_schema!({ json_schema!({
"oneOf": [ "oneOf": [
{ {
"type": "object", "type": "object",
"properties": { "properties": {
"Unix": <Vec<u8>>::json_schema(gen) "Unix": <Vec<u8>>::json_schema(generator)
}, },
"required": ["Unix"] "required": ["Unix"]
}, },
{ {
"type": "object", "type": "object",
"properties": { "properties": {
"Windows": <Vec<u16>>::json_schema(gen) "Windows": <Vec<u16>>::json_schema(generator)
}, },
"required": ["Windows"] "required": ["Windows"]
}, },

View file

@ -1,5 +1,5 @@
use crate::_alloc_prelude::*; use crate::_alloc_prelude::*;
use crate::gen::SchemaGenerator; use crate::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema}; use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow; use alloc::borrow::Cow;
@ -19,10 +19,10 @@ macro_rules! map_impl {
format!("Map<{}>", V::schema_id()).into() format!("Map<{}>", V::schema_id()).into()
} }
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(generator: &mut SchemaGenerator) -> Schema {
json_schema!({ json_schema!({
"type": "object", "type": "object",
"additionalProperties": gen.subschema_for::<V>(), "additionalProperties": generator.subschema_for::<V>(),
}) })
} }
} }

View file

@ -21,12 +21,12 @@ macro_rules! forward_impl {
<$target>::schema_id() <$target>::schema_id()
} }
fn json_schema(gen: &mut $crate::gen::SchemaGenerator) -> $crate::Schema { fn json_schema(generator: &mut $crate::SchemaGenerator) -> $crate::Schema {
<$target>::json_schema(gen) <$target>::json_schema(generator)
} }
fn _schemars_private_non_optional_json_schema(gen: &mut $crate::gen::SchemaGenerator) -> $crate::Schema { fn _schemars_private_non_optional_json_schema(generator: &mut $crate::SchemaGenerator) -> $crate::Schema {
<$target>::_schemars_private_non_optional_json_schema(gen) <$target>::_schemars_private_non_optional_json_schema(generator)
} }
fn _schemars_private_is_option() -> bool { fn _schemars_private_is_option() -> bool {

View file

@ -1,5 +1,5 @@
use crate::SchemaGenerator;
use crate::_alloc_prelude::*; use crate::_alloc_prelude::*;
use crate::gen::SchemaGenerator;
use crate::{JsonSchema, Schema}; use crate::{JsonSchema, Schema};
use alloc::borrow::Cow; use alloc::borrow::Cow;
use core::num::*; use core::num::*;
@ -17,8 +17,8 @@ macro_rules! nonzero_unsigned_impl {
stringify!(std::num::$type).into() stringify!(std::num::$type).into()
} }
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(generator: &mut SchemaGenerator) -> Schema {
let mut schema = <$primitive>::json_schema(gen); let mut schema = <$primitive>::json_schema(generator);
let object = schema.ensure_object(); let object = schema.ensure_object();
object.insert("not".to_owned(), serde_json::json!({ object.insert("not".to_owned(), serde_json::json!({
"const": 0 "const": 0

View file

@ -1,7 +1,7 @@
use crate::_alloc_prelude::*;
use crate::gen::SchemaGenerator;
use crate::JsonSchema; use crate::JsonSchema;
use crate::Schema; use crate::Schema;
use crate::SchemaGenerator;
use crate::_alloc_prelude::*;
use alloc::borrow::Cow; use alloc::borrow::Cow;
use core::num::*; use core::num::*;
@ -18,8 +18,8 @@ macro_rules! nonzero_unsigned_impl {
stringify!(std::num::$type).into() stringify!(std::num::$type).into()
} }
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(generator: &mut SchemaGenerator) -> Schema {
let mut schema = <$primitive>::json_schema(gen); let mut schema = <$primitive>::json_schema(generator);
let object = schema.ensure_object(); let object = schema.ensure_object();
object.insert("minimum".to_owned(), 1.into()); object.insert("minimum".to_owned(), 1.into());
schema schema

View file

@ -1,5 +1,5 @@
use crate::_alloc_prelude::*; use crate::_alloc_prelude::*;
use crate::gen::SchemaGenerator; use crate::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema}; use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow; use alloc::borrow::Cow;

View file

@ -1,4 +1,4 @@
use crate::gen::SchemaGenerator; use crate::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema}; use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow; use alloc::borrow::Cow;
use semver1::Version; use semver1::Version;

View file

@ -1,5 +1,5 @@
use crate::SchemaGenerator;
use crate::_alloc_prelude::*; use crate::_alloc_prelude::*;
use crate::gen::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema}; use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow; use alloc::borrow::Cow;
@ -19,10 +19,10 @@ macro_rules! seq_impl {
format!("[{}]", T::schema_id()).into() format!("[{}]", T::schema_id()).into()
} }
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(generator: &mut SchemaGenerator) -> Schema {
json_schema!({ json_schema!({
"type": "array", "type": "array",
"items": gen.subschema_for::<T>(), "items": generator.subschema_for::<T>(),
}) })
} }
} }
@ -45,11 +45,11 @@ macro_rules! set_impl {
format!("Set<{}>", T::schema_id()).into() format!("Set<{}>", T::schema_id()).into()
} }
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(generator: &mut SchemaGenerator) -> Schema {
json_schema!({ json_schema!({
"type": "array", "type": "array",
"uniqueItems": true, "uniqueItems": true,
"items": gen.subschema_for::<T>(), "items": generator.subschema_for::<T>(),
}) })
} }
} }

View file

@ -1,5 +1,5 @@
use crate::_alloc_prelude::*; use crate::_alloc_prelude::*;
use crate::gen::SchemaGenerator; use crate::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema}; use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow; use alloc::borrow::Cow;
use alloc::collections::BTreeMap; use alloc::collections::BTreeMap;

View file

@ -1,4 +1,4 @@
use crate::gen::SchemaGenerator; use crate::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema}; use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow; use alloc::borrow::Cow;
@ -11,13 +11,13 @@ impl JsonSchema for core::time::Duration {
"std::time::Duration".into() "std::time::Duration".into()
} }
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(generator: &mut SchemaGenerator) -> Schema {
json_schema!({ json_schema!({
"type": "object", "type": "object",
"required": ["secs", "nanos"], "required": ["secs", "nanos"],
"properties": { "properties": {
"secs": u64::json_schema(gen), "secs": u64::json_schema(generator),
"nanos": u32::json_schema(gen), "nanos": u32::json_schema(generator),
} }
}) })
} }
@ -33,13 +33,13 @@ impl JsonSchema for std::time::SystemTime {
"std::time::SystemTime".into() "std::time::SystemTime".into()
} }
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(generator: &mut SchemaGenerator) -> Schema {
json_schema!({ json_schema!({
"type": "object", "type": "object",
"required": ["secs_since_epoch", "nanos_since_epoch"], "required": ["secs_since_epoch", "nanos_since_epoch"],
"properties": { "properties": {
"secs_since_epoch": u64::json_schema(gen), "secs_since_epoch": u64::json_schema(generator),
"nanos_since_epoch": u32::json_schema(gen), "nanos_since_epoch": u32::json_schema(generator),
} }
}) })
} }

View file

@ -1,5 +1,5 @@
use crate::SchemaGenerator;
use crate::_alloc_prelude::*; use crate::_alloc_prelude::*;
use crate::gen::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema}; use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow; use alloc::borrow::Cow;
@ -23,11 +23,11 @@ macro_rules! tuple_impls {
id.into() id.into()
} }
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(generator: &mut SchemaGenerator) -> Schema {
json_schema!({ json_schema!({
"type": "array", "type": "array",
"prefixItems": [ "prefixItems": [
$(gen.subschema_for::<$name>()),+ $(generator.subschema_for::<$name>()),+
], ],
"minItems": $len, "minItems": $len,
"maxItems": $len, "maxItems": $len,

View file

@ -1,4 +1,4 @@
use crate::gen::SchemaGenerator; use crate::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema}; use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow; use alloc::borrow::Cow;
use url2::Url; use url2::Url;

View file

@ -1,4 +1,4 @@
use crate::gen::SchemaGenerator; use crate::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema}; use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow; use alloc::borrow::Cow;
use uuid1::Uuid; use uuid1::Uuid;

View file

@ -24,7 +24,7 @@ mod macros;
/// outside of `schemars`, and should not be considered part of the public API. /// outside of `schemars`, and should not be considered part of the public API.
#[doc(hidden)] #[doc(hidden)]
pub mod _private; pub mod _private;
pub mod gen; pub mod generate;
pub mod transform; pub mod transform;
#[cfg(feature = "schemars_derive")] #[cfg(feature = "schemars_derive")]
@ -40,7 +40,7 @@ pub extern crate alloc as _alloc;
#[doc(hidden)] #[doc(hidden)]
pub extern crate serde_json as _serde_json; pub extern crate serde_json as _serde_json;
pub use gen::SchemaGenerator; pub use generate::SchemaGenerator;
pub use schema::Schema; pub use schema::Schema;
mod _alloc_prelude { mod _alloc_prelude {
@ -52,6 +52,17 @@ mod _alloc_prelude {
pub use alloc::vec::Vec; pub use alloc::vec::Vec;
} }
#[deprecated = "Only included for backward-compatibility - use the `schemars::generate` module instead."]
#[doc(hidden)]
pub mod r#gen {
#[deprecated = "Only included for backward-compatibility - use `schemars::SchemaGenerator` or `schemars::generate::SchemaGenerator` instead."]
pub type SchemaGenerator = crate::generate::SchemaGenerator;
#[deprecated = "Only included for backward-compatibility - use `schemars::generate::SchemaSettings` instead."]
pub type SchemaSettings = crate::generate::SchemaSettings;
#[deprecated = "Only included for backward-compatibility - use `schemars::generate::GenTransform` instead."]
pub use crate::generate::GenTransform;
}
/// A type which can be described as a JSON Schema document. /// A type which can be described as a JSON Schema document.
/// ///
/// This is implemented for many Rust primitive and standard library types. /// This is implemented for many Rust primitive and standard library types.
@ -166,12 +177,12 @@ pub trait JsonSchema {
/// add them to the [`SchemaGenerator`]'s schema definitions. /// add them to the [`SchemaGenerator`]'s schema definitions.
/// ///
/// This should not return a `$ref` schema. /// This should not return a `$ref` schema.
fn json_schema(gen: &mut SchemaGenerator) -> Schema; fn json_schema(generator: &mut SchemaGenerator) -> Schema;
// TODO document and bring into public API? // TODO document and bring into public API?
#[doc(hidden)] #[doc(hidden)]
fn _schemars_private_non_optional_json_schema(gen: &mut SchemaGenerator) -> Schema { fn _schemars_private_non_optional_json_schema(generator: &mut SchemaGenerator) -> Schema {
Self::json_schema(gen) Self::json_schema(generator)
} }
// TODO document and bring into public API? // TODO document and bring into public API?

View file

@ -242,7 +242,7 @@ impl crate::JsonSchema for Schema {
"schemars::Schema".into() "schemars::Schema".into()
} }
fn json_schema(_: &mut crate::gen::SchemaGenerator) -> Schema { fn json_schema(_: &mut crate::SchemaGenerator) -> Schema {
crate::json_schema!({ crate::json_schema!({
"type": ["object", "boolean"] "type": ["object", "boolean"]
}) })

View file

@ -4,23 +4,23 @@ use core::fmt::Display;
use serde_json::{Error, Map, Value}; use serde_json::{Error, Map, Value};
pub(crate) struct Serializer<'a> { pub(crate) struct Serializer<'a> {
pub(crate) gen: &'a mut SchemaGenerator, pub(crate) generator: &'a mut SchemaGenerator,
pub(crate) include_title: bool, pub(crate) include_title: bool,
} }
pub(crate) struct SerializeSeq<'a> { pub(crate) struct SerializeSeq<'a> {
gen: &'a mut SchemaGenerator, generator: &'a mut SchemaGenerator,
items: Option<Schema>, items: Option<Schema>,
} }
pub(crate) struct SerializeTuple<'a> { pub(crate) struct SerializeTuple<'a> {
gen: &'a mut SchemaGenerator, generator: &'a mut SchemaGenerator,
items: Vec<Schema>, items: Vec<Schema>,
title: &'static str, title: &'static str,
} }
pub(crate) struct SerializeMap<'a> { pub(crate) struct SerializeMap<'a> {
gen: &'a mut SchemaGenerator, generator: &'a mut SchemaGenerator,
properties: Map<String, Value>, properties: Map<String, Value>,
current_key: Option<String>, current_key: Option<String>,
title: &'static str, title: &'static str,
@ -29,7 +29,7 @@ pub(crate) struct SerializeMap<'a> {
macro_rules! forward_to_subschema_for { macro_rules! forward_to_subschema_for {
($fn:ident, $ty:ty) => { ($fn:ident, $ty:ty) => {
fn $fn(self, _value: $ty) -> Result<Self::Ok, Self::Error> { fn $fn(self, _value: $ty) -> Result<Self::Ok, Self::Error> {
Ok(self.gen.subschema_for::<$ty>()) Ok(self.generator.subschema_for::<$ty>())
} }
}; };
} }
@ -78,7 +78,7 @@ impl<'a> serde::Serializer for Serializer<'a> {
where where
T: Display, T: Display,
{ {
Ok(self.gen.subschema_for::<&str>()) Ok(self.generator.subschema_for::<&str>())
} }
fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error> fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error>
@ -95,7 +95,7 @@ impl<'a> serde::Serializer for Serializer<'a> {
} }
let schema = v.serialize(Serializer { let schema = v.serialize(Serializer {
gen: self.gen, generator: self.generator,
include_title: false, include_title: false,
})?; })?;
Ok(match &acc { Ok(match &acc {
@ -113,7 +113,7 @@ impl<'a> serde::Serializer for Serializer<'a> {
} }
fn serialize_none(self) -> Result<Self::Ok, Self::Error> { fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(self.gen.subschema_for::<Option<Value>>()) Ok(self.generator.subschema_for::<Option<Value>>())
} }
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> { fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
@ -125,11 +125,11 @@ impl<'a> serde::Serializer for Serializer<'a> {
T: serde::Serialize, T: serde::Serialize,
{ {
let mut schema = value.serialize(Serializer { let mut schema = value.serialize(Serializer {
gen: self.gen, generator: self.generator,
include_title: false, include_title: false,
})?; })?;
if self.gen.settings().option_add_null_type { if self.generator.settings().option_add_null_type {
schema = match schema.try_to_object() { schema = match schema.try_to_object() {
Ok(mut obj) => { Ok(mut obj) => {
let value = obj.get_mut("type"); let value = obj.get_mut("type");
@ -153,17 +153,17 @@ impl<'a> serde::Serializer for Serializer<'a> {
_ => json_schema!({ _ => json_schema!({
"anyOf": [ "anyOf": [
obj, obj,
<()>::json_schema(self.gen) <()>::json_schema(self.generator)
] ]
}), }),
} }
} }
Err(true) => true.into(), Err(true) => true.into(),
Err(false) => <()>::json_schema(self.gen), Err(false) => <()>::json_schema(self.generator),
} }
} }
if self.gen.settings().option_nullable { if self.generator.settings().option_nullable {
schema schema
.ensure_object() .ensure_object()
.insert("nullable".into(), true.into()); .insert("nullable".into(), true.into());
@ -173,7 +173,7 @@ impl<'a> serde::Serializer for Serializer<'a> {
} }
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> { fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
Ok(self.gen.subschema_for::<()>()) Ok(self.generator.subschema_for::<()>())
} }
fn serialize_unit_variant( fn serialize_unit_variant(
@ -218,14 +218,14 @@ impl<'a> serde::Serializer for Serializer<'a> {
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> { fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
Ok(SerializeSeq { Ok(SerializeSeq {
gen: self.gen, generator: self.generator,
items: None, items: None,
}) })
} }
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> { fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
Ok(SerializeTuple { Ok(SerializeTuple {
gen: self.gen, generator: self.generator,
items: Vec::with_capacity(len), items: Vec::with_capacity(len),
title: "", title: "",
}) })
@ -238,7 +238,7 @@ impl<'a> serde::Serializer for Serializer<'a> {
) -> Result<Self::SerializeTupleStruct, Self::Error> { ) -> Result<Self::SerializeTupleStruct, Self::Error> {
let title = if self.include_title { name } else { "" }; let title = if self.include_title { name } else { "" };
Ok(SerializeTuple { Ok(SerializeTuple {
gen: self.gen, generator: self.generator,
items: Vec::with_capacity(len), items: Vec::with_capacity(len),
title, title,
}) })
@ -256,7 +256,7 @@ impl<'a> serde::Serializer for Serializer<'a> {
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> { fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
Ok(SerializeMap { Ok(SerializeMap {
gen: self.gen, generator: self.generator,
properties: Map::new(), properties: Map::new(),
current_key: None, current_key: None,
title: "", title: "",
@ -270,7 +270,7 @@ impl<'a> serde::Serializer for Serializer<'a> {
) -> Result<Self::SerializeStruct, Self::Error> { ) -> Result<Self::SerializeStruct, Self::Error> {
let title = if self.include_title { name } else { "" }; let title = if self.include_title { name } else { "" };
Ok(SerializeMap { Ok(SerializeMap {
gen: self.gen, generator: self.generator,
properties: Map::new(), properties: Map::new(),
current_key: None, current_key: None,
title, title,
@ -334,7 +334,7 @@ impl serde::ser::SerializeSeq for SerializeSeq<'_> {
{ {
if self.items != Some(true.into()) { if self.items != Some(true.into()) {
let schema = value.serialize(Serializer { let schema = value.serialize(Serializer {
gen: self.gen, generator: self.generator,
include_title: false, include_title: false,
})?; })?;
match &self.items { match &self.items {
@ -369,7 +369,7 @@ impl serde::ser::SerializeTuple for SerializeTuple<'_> {
T: serde::Serialize, T: serde::Serialize,
{ {
let schema = value.serialize(Serializer { let schema = value.serialize(Serializer {
gen: self.gen, generator: self.generator,
include_title: false, include_title: false,
})?; })?;
self.items.push(schema); self.items.push(schema);
@ -437,7 +437,7 @@ impl serde::ser::SerializeMap for SerializeMap<'_> {
{ {
let key = self.current_key.take().unwrap_or_default(); let key = self.current_key.take().unwrap_or_default();
let schema = value.serialize(Serializer { let schema = value.serialize(Serializer {
gen: self.gen, generator: self.generator,
include_title: false, include_title: false,
})?; })?;
self.properties.insert(key, schema.into()); self.properties.insert(key, schema.into());
@ -474,7 +474,7 @@ impl serde::ser::SerializeStruct for SerializeMap<'_> {
T: serde::Serialize, T: serde::Serialize,
{ {
let prop_schema = value.serialize(Serializer { let prop_schema = value.serialize(Serializer {
gen: self.gen, generator: self.generator,
include_title: false, include_title: false,
})?; })?;
self.properties.insert(key.to_string(), prop_schema.into()); self.properties.insert(key.to_string(), prop_schema.into());

View file

@ -1,5 +1,5 @@
mod util; mod util;
use schemars::{gen::SchemaSettings, JsonSchema}; use schemars::{generate::SchemaSettings, JsonSchema};
use util::*; use util::*;
#[allow(dead_code)] #[allow(dead_code)]

View file

@ -1,5 +1,5 @@
mod util; mod util;
use schemars::gen::{SchemaGenerator, SchemaSettings}; use schemars::generate::{SchemaGenerator, SchemaSettings};
use serde::Serialize; use serde::Serialize;
use std::collections::HashMap; use std::collections::HashMap;
use util::*; use util::*;
@ -53,32 +53,32 @@ fn make_value() -> MyStruct {
#[test] #[test]
fn schema_from_value_matches_draft07() -> TestResult { fn schema_from_value_matches_draft07() -> TestResult {
let gen = SchemaSettings::draft07().into_generator(); let generator = SchemaSettings::draft07().into_generator();
let actual = gen.into_root_schema_for_value(&make_value())?; let actual = generator.into_root_schema_for_value(&make_value())?;
test_schema(&actual, "from_value_draft07") test_schema(&actual, "from_value_draft07")
} }
#[test] #[test]
fn schema_from_value_matches_2019_09() -> TestResult { fn schema_from_value_matches_2019_09() -> TestResult {
let gen = SchemaSettings::draft2019_09().into_generator(); let generator = SchemaSettings::draft2019_09().into_generator();
let actual = gen.into_root_schema_for_value(&make_value())?; let actual = generator.into_root_schema_for_value(&make_value())?;
test_schema(&actual, "from_value_2019_09") test_schema(&actual, "from_value_2019_09")
} }
#[test] #[test]
fn schema_from_value_matches_openapi3() -> TestResult { fn schema_from_value_matches_openapi3() -> TestResult {
let gen = SchemaSettings::openapi3().into_generator(); let generator = SchemaSettings::openapi3().into_generator();
let actual = gen.into_root_schema_for_value(&make_value())?; let actual = generator.into_root_schema_for_value(&make_value())?;
test_schema(&actual, "from_value_openapi3") test_schema(&actual, "from_value_openapi3")
} }
#[test] #[test]
fn schema_from_json_value() -> TestResult { fn schema_from_json_value() -> TestResult {
let gen = SchemaGenerator::default(); let generator = SchemaGenerator::default();
let actual = gen.into_root_schema_for_value(&serde_json::json!({ let actual = generator.into_root_schema_for_value(&serde_json::json!({
"zero": 0, "zero": 0,
"one": 1, "one": 1,
"minusOne": -1, "minusOne": -1,

View file

@ -1,5 +1,5 @@
mod util; mod util;
use schemars::gen::SchemaSettings; use schemars::generate::SchemaSettings;
use schemars::JsonSchema; use schemars::JsonSchema;
use util::*; use util::*;

View file

@ -1,5 +1,5 @@
mod util; mod util;
use schemars::gen::SchemaSettings; use schemars::generate::SchemaSettings;
use schemars::{JsonSchema, Schema}; use schemars::{JsonSchema, Schema};
use serde_json::Value; use serde_json::Value;
use std::collections::BTreeMap; use std::collections::BTreeMap;

View file

@ -2,8 +2,8 @@ mod util;
use schemars::JsonSchema; use schemars::JsonSchema;
use util::*; use util::*;
fn schema_fn(gen: &mut schemars::SchemaGenerator) -> schemars::Schema { fn schema_fn(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
<bool>::json_schema(gen) <bool>::json_schema(generator)
} }
#[derive(Debug)] #[derive(Debug)]

View file

@ -2,8 +2,8 @@ mod util;
use schemars::JsonSchema; use schemars::JsonSchema;
use util::*; use util::*;
fn schema_fn(gen: &mut schemars::SchemaGenerator) -> schemars::Schema { fn schema_fn(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
<bool>::json_schema(gen) <bool>::json_schema(generator)
} }
struct DoesntImplementJsonSchema; struct DoesntImplementJsonSchema;

View file

@ -1,5 +1,5 @@
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use schemars::{gen::SchemaSettings, schema_for, JsonSchema, Schema}; use schemars::{generate::SchemaSettings, schema_for, JsonSchema, Schema};
use std::error::Error; use std::error::Error;
use std::format; use std::format;
use std::fs; use std::fs;

View file

@ -68,12 +68,12 @@ fn derive_json_schema(mut input: syn::DeriveInput, repr: bool) -> syn::Result<To
<#ty as schemars::JsonSchema>::schema_id() <#ty as schemars::JsonSchema>::schema_id()
} }
fn json_schema(gen: &mut schemars::SchemaGenerator) -> schemars::Schema { fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
<#ty as schemars::JsonSchema>::json_schema(gen) <#ty as schemars::JsonSchema>::json_schema(generator)
} }
fn _schemars_private_non_optional_json_schema(gen: &mut schemars::SchemaGenerator) -> schemars::Schema { fn _schemars_private_non_optional_json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
<#ty as schemars::JsonSchema>::_schemars_private_non_optional_json_schema(gen) <#ty as schemars::JsonSchema>::_schemars_private_non_optional_json_schema(generator)
} }
fn _schemars_private_is_option() -> bool { fn _schemars_private_is_option() -> bool {
@ -186,7 +186,7 @@ fn derive_json_schema(mut input: syn::DeriveInput, repr: bool) -> syn::Result<To
#schema_id #schema_id
} }
fn json_schema(gen: &mut schemars::SchemaGenerator) -> schemars::Schema { fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
#schema_expr #schema_expr
} }
}; };

View file

@ -70,19 +70,19 @@ pub fn expr_for_repr(cont: &Container) -> Result<TokenStream, syn::Error> {
fn expr_for_field(field: &Field, allow_ref: bool) -> TokenStream { fn expr_for_field(field: &Field, allow_ref: bool) -> TokenStream {
let (ty, type_def) = type_for_field_schema(field); let (ty, type_def) = type_for_field_schema(field);
let span = field.original.span(); let span = field.original.span();
let gen = quote!(gen); let generator = quote!(generator);
let mut schema_expr = if field.validation_attrs.required() { let mut schema_expr = if field.validation_attrs.required() {
quote_spanned! {span=> quote_spanned! {span=>
<#ty as schemars::JsonSchema>::_schemars_private_non_optional_json_schema(#gen) <#ty as schemars::JsonSchema>::_schemars_private_non_optional_json_schema(#generator)
} }
} else if allow_ref { } else if allow_ref {
quote_spanned! {span=> quote_spanned! {span=>
#gen.subschema_for::<#ty>() #generator.subschema_for::<#ty>()
} }
} else { } else {
quote_spanned! {span=> quote_spanned! {span=>
<#ty as schemars::JsonSchema>::json_schema(#gen) <#ty as schemars::JsonSchema>::json_schema(#generator)
} }
}; };
@ -127,8 +127,8 @@ fn type_for_schema(with_attr: &WithAttr) -> (syn::Type, Option<TokenStream>) {
)) ))
} }
fn json_schema(gen: &mut schemars::SchemaGenerator) -> schemars::Schema { fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
#fun(gen) #fun(generator)
} }
} }
}; };
@ -361,9 +361,9 @@ fn variant_subschemas(unique: bool, schemas: Vec<TokenStream>) -> TokenStream {
fn expr_for_untagged_enum_variant(variant: &Variant, deny_unknown_fields: bool) -> TokenStream { fn expr_for_untagged_enum_variant(variant: &Variant, deny_unknown_fields: bool) -> TokenStream {
if let Some(with_attr) = &variant.attrs.with { if let Some(with_attr) = &variant.attrs.with {
let (ty, type_def) = type_for_schema(with_attr); let (ty, type_def) = type_for_schema(with_attr);
let gen = quote!(gen); let generator = quote!(generator);
let mut schema_expr = quote_spanned! {variant.original.span()=> let mut schema_expr = quote_spanned! {variant.original.span()=>
#gen.subschema_for::<#ty>() #generator.subschema_for::<#ty>()
}; };
prepend_type_def(type_def, &mut schema_expr); prepend_type_def(type_def, &mut schema_expr);
@ -384,9 +384,9 @@ fn expr_for_internal_tagged_enum_variant(
) -> TokenStream { ) -> TokenStream {
if let Some(with_attr) = &variant.attrs.with { if let Some(with_attr) = &variant.attrs.with {
let (ty, type_def) = type_for_schema(with_attr); let (ty, type_def) = type_for_schema(with_attr);
let gen = quote!(gen); let generator = quote!(generator);
let mut schema_expr = quote_spanned! {variant.original.span()=> let mut schema_expr = quote_spanned! {variant.original.span()=>
<#ty as schemars::JsonSchema>::json_schema(#gen) <#ty as schemars::JsonSchema>::json_schema(#generator)
}; };
prepend_type_def(type_def, &mut schema_expr); prepend_type_def(type_def, &mut schema_expr);
@ -403,7 +403,7 @@ fn expr_for_internal_tagged_enum_variant(
fn expr_for_unit_struct() -> TokenStream { fn expr_for_unit_struct() -> TokenStream {
quote! { quote! {
gen.subschema_for::<()>() generator.subschema_for::<()>()
} }
} }
@ -449,7 +449,7 @@ fn expr_for_struct(
let required = field.validation_attrs.required(); let required = field.validation_attrs.required();
let args = quote!(gen, #required); let args = quote!(generator, #required);
let mut schema_expr = quote_spanned! {ty.span()=> let mut schema_expr = quote_spanned! {ty.span()=>
schemars::_private::json_schema_for_flatten::<#ty>(#args) schemars::_private::json_schema_for_flatten::<#ty>(#args)
}; };
@ -475,14 +475,14 @@ fn expr_for_struct(
..field.attrs.as_metadata() ..field.attrs.as_metadata()
}; };
let gen = quote!(gen); let generator = quote!(generator);
let mut schema_expr = if field.validation_attrs.required() { let mut schema_expr = if field.validation_attrs.required() {
quote_spanned! {ty.span()=> quote_spanned! {ty.span()=>
<#ty as schemars::JsonSchema>::_schemars_private_non_optional_json_schema(#gen) <#ty as schemars::JsonSchema>::_schemars_private_non_optional_json_schema(#generator)
} }
} else { } else {
quote_spanned! {ty.span()=> quote_spanned! {ty.span()=>
#gen.subschema_for::<#ty>() #generator.subschema_for::<#ty>()
} }
}; };