Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove usages of gen identifier #323

Merged
merged 1 commit into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/1.1-attributes.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ Validator docs: [required](https://github.com/Keats/validator#required) / [requi

</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">

Expand Down
4 changes: 2 additions & 2 deletions docs/2-implementing.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,10 @@ The default implementation of this function returns `Self::schema_name()`.
## json_schema

```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.

Expand Down
10 changes: 5 additions & 5 deletions docs/3-generating.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,18 @@ permalink: /generating/

# 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
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.

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).
- [`SchemaGenerator`](https://docs.rs/schemars/latest/schemars/gen/struct.SchemaGenerator.html), which manages the generation of a schema document.
- [`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/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):

Expand All @@ -30,7 +30,7 @@ See the API documentation for more info on how to use those types for custom sch

## 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
let value = MyStruct { foo = 123 };
Expand Down
4 changes: 2 additions & 2 deletions docs/_includes/examples/custom_serialization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ pub struct MyStruct {
pub bool_normal: bool,
}

fn make_custom_schema(gen: &mut SchemaGenerator) -> Schema {
let mut schema = String::json_schema(gen);
fn make_custom_schema(generator: &mut SchemaGenerator) -> Schema {
let mut schema = String::json_schema(generator);
schema
.ensure_object()
.insert("format".into(), "boolean".into());
Expand Down
6 changes: 3 additions & 3 deletions docs/_includes/examples/custom_settings.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use schemars::{gen::SchemaSettings, JsonSchema};
use schemars::{generate::SchemaSettings, JsonSchema};

#[derive(JsonSchema)]
pub struct MyStruct {
Expand All @@ -18,7 +18,7 @@ fn main() {
s.option_nullable = true;
s.option_add_null_type = false;
});
let gen = settings.into_generator();
let schema = gen.into_root_schema_for::<MyStruct>();
let generator = settings.into_generator();
let schema = generator.into_root_schema_for::<MyStruct>();
println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}
2 changes: 1 addition & 1 deletion docs/examples/4-custom_settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ summary: Generating a schema using custom settings which changes how Option<T> i

# 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" %}
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ nav_order: 1

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.

Expand Down
4 changes: 2 additions & 2 deletions schemars/examples/custom_serialization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ pub struct MyStruct {
pub bool_normal: bool,
}

fn make_custom_schema(gen: &mut SchemaGenerator) -> Schema {
let mut schema = String::json_schema(gen);
fn make_custom_schema(generator: &mut SchemaGenerator) -> Schema {
let mut schema = String::json_schema(generator);
schema
.ensure_object()
.insert("format".into(), "boolean".into());
Expand Down
6 changes: 3 additions & 3 deletions schemars/examples/custom_settings.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use schemars::{gen::SchemaSettings, JsonSchema};
use schemars::{generate::SchemaSettings, JsonSchema};

#[derive(JsonSchema)]
pub struct MyStruct {
Expand All @@ -18,7 +18,7 @@ fn main() {
s.option_nullable = true;
s.option_add_null_type = false;
});
let gen = settings.into_generator();
let schema = gen.into_root_schema_for::<MyStruct>();
let generator = settings.into_generator();
let schema = generator.into_root_schema_for::<MyStruct>();
println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}
4 changes: 2 additions & 2 deletions schemars/src/_private.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ use serde_json::{json, map::Entry, Map, Value};

// Helper for generating schemas for flattened `Option` fields.
pub fn json_schema_for_flatten<T: ?Sized + JsonSchema>(
gen: &mut SchemaGenerator,
generator: &mut SchemaGenerator,
required: bool,
) -> 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 let Some(object) = schema.as_object_mut() {
Expand Down
38 changes: 21 additions & 17 deletions schemars/src/gen.rs → schemars/src/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,13 @@ impl SchemaSettings {
///
/// # Example
/// ```
/// use schemars::gen::{SchemaGenerator, SchemaSettings};
/// use schemars::generate::{SchemaGenerator, SchemaSettings};
///
/// let settings = SchemaSettings::default().with(|s| {
/// s.option_nullable = true;
/// 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 {
configure_fn(&mut self);
Expand Down Expand Up @@ -163,8 +163,8 @@ impl SchemaSettings {
/// foo: i32,
/// }
///
/// let gen = SchemaGenerator::default();
/// let schema = gen.into_root_schema_for::<MyStruct>();
/// let generator = SchemaGenerator::default();
/// let schema = generator.into_root_schema_for::<MyStruct>();
/// ```
#[derive(Debug, Default)]
pub struct SchemaGenerator {
Expand Down Expand Up @@ -208,8 +208,8 @@ impl SchemaGenerator {
/// ```
/// use schemars::SchemaGenerator;
///
/// let gen = SchemaGenerator::default();
/// let settings = gen.settings();
/// let generator = SchemaGenerator::default();
/// let settings = generator.settings();
///
/// assert_eq!(settings.option_add_null_type, true);
/// ```
Expand Down Expand Up @@ -361,7 +361,7 @@ impl SchemaGenerator {
value: &T,
) -> Result<Schema, serde_json::Error> {
let mut schema = value.serialize(crate::ser::Serializer {
gen: self,
generator: self,
include_title: true,
})?;

Expand Down Expand Up @@ -392,7 +392,7 @@ impl SchemaGenerator {
value: &T,
) -> Result<Schema, serde_json::Error> {
let mut schema = value.serialize(crate::ser::Serializer {
gen: &mut self,
generator: &mut self,
include_title: true,
})?;

Expand All @@ -415,28 +415,32 @@ impl SchemaGenerator {

fn json_schema_internal<T: ?Sized + JsonSchema>(&mut self, id: CowStr) -> Schema {
struct PendingSchemaState<'a> {
gen: &'a mut SchemaGenerator,
generator: &'a mut SchemaGenerator,
id: CowStr,
did_add: bool,
}

impl<'a> PendingSchemaState<'a> {
fn new(gen: &'a mut SchemaGenerator, id: CowStr) -> Self {
let did_add = gen.pending_schema_ids.insert(id.clone());
Self { gen, id, did_add }
fn new(generator: &'a mut SchemaGenerator, id: CowStr) -> Self {
let did_add = generator.pending_schema_ids.insert(id.clone());
Self {
generator,
id,
did_add,
}
}
}

impl Drop for PendingSchemaState<'_> {
fn drop(&mut self) {
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);
T::json_schema(pss.gen)
T::json_schema(pss.generator)
}

fn add_definitions(
Expand Down Expand Up @@ -514,7 +518,7 @@ fn json_pointer_mut<'a>(
/// # Example
/// ```
/// use schemars::transform::Transform;
/// use schemars::gen::GenTransform;
/// use schemars::generate::GenTransform;
///
/// #[derive(Debug, Clone)]
/// struct MyTransform;
Expand All @@ -534,7 +538,7 @@ pub trait GenTransform: Transform + DynClone + Any + Send {
/// # Example
/// To remove a specific transform from an instance of `SchemaSettings`:
/// ```
/// use schemars::gen::SchemaSettings;
/// use schemars::generate::SchemaSettings;
/// use schemars::transform::ReplaceBoolSchemas;
///
/// let mut settings = SchemaSettings::openapi3();
Expand All @@ -553,7 +557,7 @@ pub trait GenTransform: Transform + DynClone + Any + Send {
/// # Example
/// To modify a specific transform in an instance of `SchemaSettings`:
/// ```
/// use schemars::gen::SchemaSettings;
/// use schemars::generate::SchemaSettings;
/// use schemars::transform::ReplaceBoolSchemas;
///
/// let mut settings = SchemaSettings::openapi3();
Expand Down
6 changes: 3 additions & 3 deletions schemars/src/json_schema_impls/array.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::SchemaGenerator;
use crate::_alloc_prelude::*;
use crate::gen::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow;

Expand Down Expand Up @@ -37,10 +37,10 @@ macro_rules! array_impls {
format!("[{}; {}]", $len, T::schema_id()).into()
}

fn json_schema(gen: &mut SchemaGenerator) -> Schema {
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
json_schema!({
"type": "array",
"items": serde_json::Value::from(gen.subschema_for::<T>()),
"items": serde_json::Value::from(generator.subschema_for::<T>()),
"minItems": $len,
"maxItems": $len,
})
Expand Down
6 changes: 3 additions & 3 deletions schemars/src/json_schema_impls/arrayvec07.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::SchemaGenerator;
use crate::_alloc_prelude::*;
use crate::gen::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema};
use arrayvec07::{ArrayString, ArrayVec};

Expand All @@ -17,10 +17,10 @@ where
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!({
"type": "array",
"items": gen.subschema_for::<T>(),
"items": generator.subschema_for::<T>(),
"maxItems": CAP
})
}
Expand Down
2 changes: 1 addition & 1 deletion schemars/src/json_schema_impls/chrono04.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::gen::SchemaGenerator;
use crate::SchemaGenerator;
use crate::{json_schema, JsonSchema, Schema};
use alloc::borrow::Cow;
use chrono04::prelude::*;
Expand Down
Loading
Loading