diff --git a/CHANGELOG.md b/CHANGELOG.md index 4033b69..12c8f80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## [0.8.4] - **In-dev** +### Added: +- `#[schemars(schema_with = "...")]` attribute can now be set on enum variants. + +## [0.8.3] - 2021-04-05 +### Added: +- Support for `#[schemars(crate = "...")]` attribute to allow deriving JsonSchema when the schemars crate is aliased to a different name (https://github.com/GREsau/schemars/pull/55 / https://github.com/GREsau/schemars/pull/80) +- Implement `JsonSchema` for `bytes::Bytes` and `bytes::BytesMut` (https://github.com/GREsau/schemars/pull/68) + +### Fixed: +- Fix deriving JsonSchema on types defined inside macros (https://github.com/GREsau/schemars/issues/59 / https://github.com/GREsau/schemars/issues/66 / https://github.com/GREsau/schemars/pull/79) + ## [0.8.2] - 2021-03-27 ### Added: - Enable generating a schema from any serializable value using `schema_for_value!(...)` macro or `SchemaGenerator::root_schema_for_value()`/`SchemaGenerator::into_root_schema_for_value()` methods (https://github.com/GREsau/schemars/pull/75) diff --git a/README.md b/README.md index e91b1bd..571045d 100644 --- a/README.md +++ b/README.md @@ -273,3 +273,4 @@ Schemars can implement `JsonSchema` on types from several popular crates, enable - [`smallvec`](https://crates.io/crates/smallvec) (^1.0) - [`arrayvec`](https://crates.io/crates/arrayvec) (^0.5) - [`url`](https://crates.io/crates/url) (^2.0) +- [`bytes`](https://crates.io/crates/bytes) (^1.0) diff --git a/docs/1.1-attributes.md b/docs/1.1-attributes.md index 3cc38c4..64d4d14 100644 --- a/docs/1.1-attributes.md +++ b/docs/1.1-attributes.md @@ -38,6 +38,7 @@ TABLE OF CONTENTS - [`title` / `description`](#title-description) - [`example`](#example) - [`deprecated`](#deprecated) + - [`crate`](#crate) - [Doc Comments (`doc`)](#doc) @@ -182,6 +183,13 @@ Set on a container, variant or field to include the result of the given function Set the Rust built-in [`deprecated`](https://doc.rust-lang.org/edition-guide/rust-2018/the-compiler/an-attribute-for-deprecation.html) attribute on a struct, enum, field or variant to set the generated schema's `deprecated` keyword to `true`. +

+ +`#[schemars(crate = "other_crate::schemars")]` +

+ +Set the path to the schemars crate instance the generated code should depend on. This is mostly useful for other crates that depend on schemars in their macros. +

Doc Comments (`#[doc = "..."]`) diff --git a/docs/4-features.md b/docs/4-features.md index af3e652..d080908 100644 --- a/docs/4-features.md +++ b/docs/4-features.md @@ -27,3 +27,4 @@ Schemars can implement `JsonSchema` on types from several popular crates, enable - [`smallvec`](https://crates.io/crates/smallvec) (^1.0) - [`arrayvec`](https://crates.io/crates/arrayvec) (^0.5) - [`url`](https://crates.io/crates/url) (^2.0) +- [`bytes`](https://crates.io/crates/bytes) (^1.0) diff --git a/schemars/Cargo.toml b/schemars/Cargo.toml index a85238e..6fe3121 100644 --- a/schemars/Cargo.toml +++ b/schemars/Cargo.toml @@ -3,7 +3,7 @@ name = "schemars" description = "Generate JSON Schemas from Rust code" homepage = "https://graham.cool/schemars/" repository = "https://github.com/GREsau/schemars" -version = "0.8.2" +version = "0.8.3" authors = ["Graham Esau "] edition = "2018" license = "MIT" @@ -13,7 +13,7 @@ categories = ["encoding"] build = "build.rs" [dependencies] -schemars_derive = { version = "=0.8.2", optional = true, path = "../schemars_derive" } +schemars_derive = { version = "=0.8.3", optional = true, path = "../schemars_derive" } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" dyn-clone = "1.0" @@ -25,6 +25,7 @@ uuid = { version = "0.8", default-features = false, optional = true } smallvec = { version = "1.0", optional = true } arrayvec = { version = "0.5", default-features = false, optional = true } url = { version = "2.0", default-features = false, optional = true } +bytes = { version = "1.0", optional = true } [dev-dependencies] pretty_assertions = "0.6.1" @@ -66,6 +67,10 @@ required-features = ["uuid"] name = "smallvec" required-features = ["smallvec"] +[[test]] +name = "bytes" +required-features = ["bytes"] + [[test]] name = "arrayvec" required-features = ["arrayvec"] diff --git a/schemars/src/_private.rs b/schemars/src/_private.rs new file mode 100644 index 0000000..8b8e2d1 --- /dev/null +++ b/schemars/src/_private.rs @@ -0,0 +1,55 @@ +use crate::flatten::Merge; +use crate::gen::SchemaGenerator; +use crate::schema::{Metadata, Schema, SchemaObject}; +use crate::JsonSchema; + +// Helper for generating schemas for flattened `Option` fields. +pub fn json_schema_for_flatten(gen: &mut SchemaGenerator) -> Schema { + let mut schema = T::_schemars_private_non_optional_json_schema(gen); + if T::_schemars_private_is_option() { + if let Schema::Object(SchemaObject { + object: Some(ref mut object_validation), + .. + }) = schema + { + object_validation.required.clear(); + } + } + schema +} + +// Helper for generating schemas for `Option` fields. +pub fn add_schema_as_property( + gen: &mut SchemaGenerator, + parent: &mut SchemaObject, + name: String, + metadata: Option, + required: Option, +) { + let is_type_option = T::_schemars_private_is_option(); + let required = required.unwrap_or(!is_type_option); + let mut schema = if required && is_type_option { + T::_schemars_private_non_optional_json_schema(gen) + } else { + gen.subschema_for::() + }; + schema = apply_metadata(schema, metadata); + + let object = parent.object(); + if required { + object.required.insert(name.clone()); + } + object.properties.insert(name, schema); +} + +pub fn apply_metadata(schema: Schema, metadata: Option) -> Schema { + match metadata { + None => schema, + Some(ref metadata) if *metadata == Metadata::default() => schema, + Some(metadata) => { + let mut schema_obj = schema.into_object(); + schema_obj.metadata = Some(Box::new(metadata)).merge(schema_obj.metadata); + Schema::Object(schema_obj) + } + } +} diff --git a/schemars/src/gen.rs b/schemars/src/gen.rs index 72c1700..2634e12 100644 --- a/schemars/src/gen.rs +++ b/schemars/src/gen.rs @@ -7,7 +7,6 @@ There are two main types in this module:two main types in this module: * [`SchemaGenerator`], which manages the generation of a schema document. */ -use crate::flatten::Merge; use crate::schema::*; use crate::{visit::*, JsonSchema, Map}; use dyn_clone::DynClone; @@ -422,22 +421,6 @@ impl SchemaGenerator { } } - /// This function is only public for use by schemars_derive. - /// - /// It should not be considered part of the public API. - #[doc(hidden)] - pub fn apply_metadata(&self, schema: Schema, metadata: Option) -> Schema { - match metadata { - None => schema, - Some(ref metadata) if *metadata == Metadata::default() => schema, - Some(metadata) => { - let mut schema_obj = schema.into_object(); - schema_obj.metadata = Some(Box::new(metadata)).merge(schema_obj.metadata); - Schema::Object(schema_obj) - } - } - } - fn json_schema_internal(&mut self, name: &str) -> Schema { struct PendingSchemaState<'a> { gen: &'a mut SchemaGenerator, diff --git a/schemars/src/json_schema_impls/bytes.rs b/schemars/src/json_schema_impls/bytes.rs new file mode 100644 index 0000000..f1a0f29 --- /dev/null +++ b/schemars/src/json_schema_impls/bytes.rs @@ -0,0 +1,7 @@ +use crate::gen::SchemaGenerator; +use crate::schema::*; +use crate::JsonSchema; +use bytes::{Bytes, BytesMut}; + +forward_impl!((JsonSchema for Bytes) => Vec); +forward_impl!((JsonSchema for BytesMut) => Vec); diff --git a/schemars/src/json_schema_impls/core.rs b/schemars/src/json_schema_impls/core.rs index 647030f..10f9f0f 100644 --- a/schemars/src/json_schema_impls/core.rs +++ b/schemars/src/json_schema_impls/core.rs @@ -45,34 +45,12 @@ impl JsonSchema for Option { schema } - fn json_schema_for_flatten(gen: &mut SchemaGenerator) -> Schema { - let mut schema = T::json_schema_for_flatten(gen); - if let Schema::Object(SchemaObject { - object: Some(ref mut object_validation), - .. - }) = schema - { - object_validation.required.clear(); - } - schema + fn _schemars_private_non_optional_json_schema(gen: &mut SchemaGenerator) -> Schema { + T::_schemars_private_non_optional_json_schema(gen) } - fn add_schema_as_property( - gen: &mut SchemaGenerator, - parent: &mut SchemaObject, - name: String, - metadata: Option, - required: Option, - ) { - if required == Some(true) { - T::add_schema_as_property(gen, parent, name, metadata, required) - } else { - let mut schema = gen.subschema_for::(); - schema = gen.apply_metadata(schema, metadata); - - let object = parent.object(); - object.properties.insert(name, schema); - } + fn _schemars_private_is_option() -> bool { + true } } diff --git a/schemars/src/json_schema_impls/mod.rs b/schemars/src/json_schema_impls/mod.rs index 4d96ee2..ff2e1e7 100644 --- a/schemars/src/json_schema_impls/mod.rs +++ b/schemars/src/json_schema_impls/mod.rs @@ -21,18 +21,12 @@ macro_rules! forward_impl { <$target>::json_schema(gen) } - fn json_schema_for_flatten(gen: &mut SchemaGenerator) -> Schema { - <$target>::json_schema_for_flatten(gen) + fn _schemars_private_non_optional_json_schema(gen: &mut SchemaGenerator) -> Schema { + <$target>::_schemars_private_non_optional_json_schema(gen) } - fn add_schema_as_property( - gen: &mut SchemaGenerator, - parent: &mut crate::schema::SchemaObject, - name: String, - metadata: Option, - required: Option, - ) { - <$target>::add_schema_as_property(gen, parent, name, metadata, required) + fn _schemars_private_is_option() -> bool { + <$target>::_schemars_private_is_option() } } }; @@ -46,6 +40,8 @@ mod array; mod arrayvec; #[cfg(std_atomic)] mod atomic; +#[cfg(feature = "bytes")] +mod bytes; #[cfg(feature = "chrono")] mod chrono; mod core; diff --git a/schemars/src/json_schema_impls/tuple.rs b/schemars/src/json_schema_impls/tuple.rs index d9e8971..383f839 100644 --- a/schemars/src/json_schema_impls/tuple.rs +++ b/schemars/src/json_schema_impls/tuple.rs @@ -9,7 +9,9 @@ macro_rules! tuple_impls { no_ref_schema!(); fn schema_name() -> String { - ["Tuple_of".to_owned()$(, $name::schema_name())+].join("_and_") + let mut name = "Tuple_of_".to_owned(); + name.push_str(&[$($name::schema_name()),+].join("_and_")); + name } fn json_schema(gen: &mut SchemaGenerator) -> Schema { diff --git a/schemars/src/lib.rs b/schemars/src/lib.rs index 9a9e65c..e400ccf 100644 --- a/schemars/src/lib.rs +++ b/schemars/src/lib.rs @@ -268,6 +268,7 @@ Schemars can implement `JsonSchema` on types from several popular crates, enable - [`smallvec`](https://crates.io/crates/smallvec) (^1.0) - [`arrayvec`](https://crates.io/crates/arrayvec) (^0.5) - [`url`](https://crates.io/crates/url) (^2.0) +- [`bytes`](https://crates.io/crates/bytes) (^1.0) */ /// The map type used by schemars types. @@ -300,6 +301,10 @@ mod ser; #[macro_use] mod macros; +/// This module is only public for use by `schemars_derive`. It should not need to be used by code +/// outside of `schemars`, and should not be considered part of the public API. +#[doc(hidden)] +pub mod _private; pub mod gen; pub mod schema; pub mod visit; @@ -313,7 +318,7 @@ pub use schemars_derive::*; #[doc(hidden)] pub use serde_json as _serde_json; -use schema::{Schema, SchemaObject}; +use schema::Schema; /// A type which can be described as a JSON Schema document. /// @@ -356,35 +361,16 @@ pub trait JsonSchema { /// This should not return a `$ref` schema. fn json_schema(gen: &mut gen::SchemaGenerator) -> Schema; - /// Helper for generating schemas for flattened `Option` fields. - /// - /// This should not need to be called or implemented by code outside of `schemars`, - /// and should not be considered part of the public API. + // TODO document and bring into public API? #[doc(hidden)] - fn json_schema_for_flatten(gen: &mut gen::SchemaGenerator) -> Schema { + fn _schemars_private_non_optional_json_schema(gen: &mut gen::SchemaGenerator) -> Schema { Self::json_schema(gen) } - /// Helper for generating schemas for `Option` fields. - /// - /// This should not need to be called or implemented by code outside of `schemars`, - /// and should not be considered part of the public API. + // TODO document and bring into public API? #[doc(hidden)] - fn add_schema_as_property( - gen: &mut gen::SchemaGenerator, - parent: &mut SchemaObject, - name: String, - metadata: Option, - required: Option, - ) { - let mut schema = gen.subschema_for::(); - schema = gen.apply_metadata(schema, metadata); - - let object = parent.object(); - if required.unwrap_or(true) { - object.required.insert(name.clone()); - } - object.properties.insert(name, schema); + fn _schemars_private_is_option() -> bool { + false } } diff --git a/schemars/tests/bytes.rs b/schemars/tests/bytes.rs new file mode 100644 index 0000000..688ab21 --- /dev/null +++ b/schemars/tests/bytes.rs @@ -0,0 +1,8 @@ +mod util; +use bytes::{Bytes, BytesMut}; +use util::*; + +#[test] +fn bytes() -> TestResult { + test_default_generated_schema::<(Bytes, BytesMut)>("bytes") +} diff --git a/schemars/tests/crate_alias.rs b/schemars/tests/crate_alias.rs new file mode 100644 index 0000000..5f8d83c --- /dev/null +++ b/schemars/tests/crate_alias.rs @@ -0,0 +1,19 @@ +mod util; +use ::schemars as not_schemars; +use util::*; + +#[allow(unused_imports)] +use std as schemars; + +#[derive(Debug, not_schemars::JsonSchema)] +#[schemars(crate = "not_schemars")] +pub struct Struct { + /// This is a document + foo: i32, + bar: bool, +} + +#[test] +fn test_crate_alias() -> TestResult { + test_default_generated_schema::("crate_alias") +} diff --git a/schemars/tests/enum_deny_unknown_fields.rs b/schemars/tests/enum_deny_unknown_fields.rs index 4fcb4bf..bf0f400 100644 --- a/schemars/tests/enum_deny_unknown_fields.rs +++ b/schemars/tests/enum_deny_unknown_fields.rs @@ -14,8 +14,8 @@ pub struct Struct { bar: bool, } -// Outer container should always have additionalPropreties: false -// `Struct` variant should have additionalPropreties: false +// Outer container should always have additionalProperties: false +// `Struct` variant should have additionalProperties: false #[derive(Debug, JsonSchema)] #[schemars(rename_all = "camelCase", deny_unknown_fields)] pub enum External { @@ -38,7 +38,7 @@ fn enum_external_tag() -> TestResult { test_default_generated_schema::("enum-external-duf") } -// Only `Struct` variant should have additionalPropreties: false +// Only `Struct` variant should have additionalProperties: false #[derive(Debug, JsonSchema)] #[schemars(tag = "typeProperty", deny_unknown_fields)] pub enum Internal { @@ -60,7 +60,7 @@ fn enum_internal_tag() -> TestResult { test_default_generated_schema::("enum-internal-duf") } -// Only `Struct` variant should have additionalPropreties: false +// Only `Struct` variant should have additionalProperties: false #[derive(Debug, JsonSchema)] #[schemars(untagged, deny_unknown_fields)] pub enum Untagged { @@ -82,7 +82,7 @@ fn enum_untagged() -> TestResult { test_default_generated_schema::("enum-untagged-duf") } -// Outer container and `Struct` variant should have additionalPropreties: false +// Outer container and `Struct` variant should have additionalProperties: false #[derive(Debug, JsonSchema)] #[schemars(tag = "t", content = "c", deny_unknown_fields)] pub enum Adjacent { diff --git a/schemars/tests/expected/bytes.json b/schemars/tests/expected/bytes.json new file mode 100644 index 0000000..5e1f9a5 --- /dev/null +++ b/schemars/tests/expected/bytes.json @@ -0,0 +1,25 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Tuple_of_Array_of_uint8_and_Array_of_uint8", + "type": "array", + "items": [ + { + "type": "array", + "items": { + "type": "integer", + "format": "uint8", + "minimum": 0.0 + } + }, + { + "type": "array", + "items": { + "type": "integer", + "format": "uint8", + "minimum": 0.0 + } + } + ], + "maxItems": 2, + "minItems": 2 +} \ No newline at end of file diff --git a/schemars/tests/expected/crate_alias.json b/schemars/tests/expected/crate_alias.json new file mode 100644 index 0000000..66bf749 --- /dev/null +++ b/schemars/tests/expected/crate_alias.json @@ -0,0 +1,19 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Struct", + "type": "object", + "required": [ + "bar", + "foo" + ], + "properties": { + "foo": { + "description": "This is a document", + "type": "integer", + "format": "int32" + }, + "bar": { + "type": "boolean" + } + } +} \ No newline at end of file diff --git a/schemars/tests/expected/macro_built_enum.json b/schemars/tests/expected/macro_built_enum.json new file mode 100644 index 0000000..8564ef7 --- /dev/null +++ b/schemars/tests/expected/macro_built_enum.json @@ -0,0 +1,23 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "OuterEnum", + "anyOf": [ + { + "type": "object", + "required": [ + "InnerStruct" + ], + "properties": { + "InnerStruct": { + "$ref": "#/definitions/InnerStruct" + } + }, + "additionalProperties": false + } + ], + "definitions": { + "InnerStruct": { + "type": "object" + } + } +} \ No newline at end of file diff --git a/schemars/tests/expected/macro_built_struct.json b/schemars/tests/expected/macro_built_struct.json new file mode 100644 index 0000000..811eae3 --- /dev/null +++ b/schemars/tests/expected/macro_built_struct.json @@ -0,0 +1,20 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "A", + "type": "object", + "required": [ + "v", + "x" + ], + "properties": { + "x": { + "type": "integer", + "format": "uint8", + "minimum": 0.0 + }, + "v": { + "type": "integer", + "format": "int32" + } + } +} \ No newline at end of file diff --git a/schemars/tests/expected/schema_with-enum-adjacent-tagged.json b/schemars/tests/expected/schema_with-enum-adjacent-tagged.json index 1258d30..f464511 100644 --- a/schemars/tests/expected/schema_with-enum-adjacent-tagged.json +++ b/schemars/tests/expected/schema_with-enum-adjacent-tagged.json @@ -74,6 +74,24 @@ "minItems": 2 } } + }, + { + "type": "object", + "required": [ + "c", + "t" + ], + "properties": { + "t": { + "type": "string", + "enum": [ + "Unit" + ] + }, + "c": { + "type": "boolean" + } + } } ] } \ No newline at end of file diff --git a/schemars/tests/expected/schema_with-enum-external.json b/schemars/tests/expected/schema_with-enum-external.json index 364b5f3..92fb5a6 100644 --- a/schemars/tests/expected/schema_with-enum-external.json +++ b/schemars/tests/expected/schema_with-enum-external.json @@ -56,6 +56,18 @@ } }, "additionalProperties": false + }, + { + "type": "object", + "required": [ + "unit" + ], + "properties": { + "unit": { + "type": "boolean" + } + }, + "additionalProperties": false } ] } \ No newline at end of file diff --git a/schemars/tests/expected/schema_with-enum-internal.json b/schemars/tests/expected/schema_with-enum-internal.json index ae6ce94..ea39afe 100644 --- a/schemars/tests/expected/schema_with-enum-internal.json +++ b/schemars/tests/expected/schema_with-enum-internal.json @@ -36,6 +36,23 @@ ] } } + }, + { + "type": [ + "boolean", + "object" + ], + "required": [ + "typeProperty" + ], + "properties": { + "typeProperty": { + "type": "string", + "enum": [ + "Unit" + ] + } + } } ] } \ No newline at end of file diff --git a/schemars/tests/expected/schema_with-enum-untagged.json b/schemars/tests/expected/schema_with-enum-untagged.json index d22f5a3..55147de 100644 --- a/schemars/tests/expected/schema_with-enum-untagged.json +++ b/schemars/tests/expected/schema_with-enum-untagged.json @@ -29,6 +29,9 @@ ], "maxItems": 2, "minItems": 2 + }, + { + "type": "boolean" } ] } \ No newline at end of file diff --git a/schemars/tests/macro.rs b/schemars/tests/macro.rs new file mode 100644 index 0000000..9991494 --- /dev/null +++ b/schemars/tests/macro.rs @@ -0,0 +1,67 @@ +mod util; +use schemars::JsonSchema; +use util::*; + +macro_rules! build_struct { + ( + $id:ident { $($t:tt)* } + ) => { + #[derive(Debug, JsonSchema)] + pub struct $id { + x: u8, + $($t)* + } + }; +} + +build_struct!(A { v: i32 }); + +#[test] +fn macro_built_struct() -> TestResult { + test_default_generated_schema::("macro_built_struct") +} + +macro_rules! build_enum { + ( + $(#[$outer_derive:meta])* + $outer:ident { + $($(#[$inner_derive:meta])* + $inner:ident { + $( $(#[$field_attribute:meta])* + $field:ident : $ty:ty),* + })* + } + ) => { + + $( + $(#[$inner_derive])* + pub struct $inner { + $( + $(#[$field_attribute])* + pub $field: $ty + ),* + } + )* + + $(#[$outer_derive])* + pub enum $outer { + $( + $inner($inner) + ),* + } + } +} + +build_enum!( + #[derive(Debug, JsonSchema)] + OuterEnum { + #[derive(Debug, JsonSchema)] + InnerStruct {} + } + +); + +#[test] +fn macro_built_enum() -> TestResult { + test_default_generated_schema::("macro_built_enum") +} diff --git a/schemars/tests/schema_with_enum.rs b/schemars/tests/schema_with_enum.rs index 38cef03..c204644 100644 --- a/schemars/tests/schema_with_enum.rs +++ b/schemars/tests/schema_with_enum.rs @@ -2,8 +2,6 @@ mod util; use schemars::JsonSchema; use util::*; -// FIXME determine whether schema_with should be allowed on unit variants - fn schema_fn(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { ::json_schema(gen) } @@ -23,8 +21,8 @@ pub enum External { #[schemars(schema_with = "schema_fn")] DoesntImplementJsonSchema, i32, ), - // #[schemars(schema_with = "schema_fn")] - // Unit, + #[schemars(schema_with = "schema_fn")] + Unit, } #[test] @@ -40,8 +38,8 @@ pub enum Internal { foo: DoesntImplementJsonSchema, }, NewType(#[schemars(schema_with = "schema_fn")] DoesntImplementJsonSchema), - // #[schemars(schema_with = "schema_fn")] - // Unit, + #[schemars(schema_with = "schema_fn")] + Unit, } #[test] @@ -61,8 +59,8 @@ pub enum Untagged { #[schemars(schema_with = "schema_fn")] DoesntImplementJsonSchema, i32, ), - // #[schemars(schema_with = "schema_fn")] - // Unit, + #[schemars(schema_with = "schema_fn")] + Unit, } #[test] @@ -82,8 +80,8 @@ pub enum Adjacent { #[schemars(schema_with = "schema_fn")] DoesntImplementJsonSchema, i32, ), - // #[schemars(schema_with = "schema_fn")] - // Unit, + #[schemars(schema_with = "schema_fn")] + Unit, } #[test] diff --git a/schemars_derive/Cargo.toml b/schemars_derive/Cargo.toml index 05e84cf..0535f1d 100644 --- a/schemars_derive/Cargo.toml +++ b/schemars_derive/Cargo.toml @@ -3,7 +3,7 @@ name = "schemars_derive" description = "Macros for #[derive(JsonSchema)], for use with schemars" homepage = "https://graham.cool/schemars/" repository = "https://github.com/GREsau/schemars" -version = "0.8.2" +version = "0.8.3" authors = ["Graham Esau "] edition = "2018" license = "MIT" diff --git a/schemars_derive/src/attr/mod.rs b/schemars_derive/src/attr/mod.rs index d7a6628..10ed772 100644 --- a/schemars_derive/src/attr/mod.rs +++ b/schemars_derive/src/attr/mod.rs @@ -13,6 +13,10 @@ use syn::Meta::{List, NameValue}; use syn::MetaNameValue; use syn::NestedMeta::{Lit, Meta}; +// FIXME using the same struct for containers+variants+fields means that +// with/schema_with are accepted (but ignored) on containers, and +// repr/crate_name are accepted (but ignored) on variants and fields etc. + #[derive(Debug, Default)] pub struct Attrs { pub with: Option, @@ -21,6 +25,7 @@ pub struct Attrs { pub deprecated: bool, pub examples: Vec, pub repr: Option, + pub crate_name: Option, } #[derive(Debug)] @@ -125,6 +130,16 @@ impl Attrs { } } + Meta(NameValue(m)) if m.path.is_ident("crate") && attr_type == "schemars" => { + if let Ok(p) = parse_lit_into_path(errors, attr_type, "crate", &m.lit) { + if self.crate_name.is_some() { + duplicate_error(m) + } else { + self.crate_name = Some(p) + } + } + } + _ if ignore_errors => {} Meta(meta_item) => { diff --git a/schemars_derive/src/attr/validation.rs b/schemars_derive/src/attr/validation.rs index 8f13168..a721ec5 100644 --- a/schemars_derive/src/attr/validation.rs +++ b/schemars_derive/src/attr/validation.rs @@ -125,11 +125,11 @@ impl ValidationAttrs { // `schema_object` - the SchemaObject for the struct that contains this field. let mut statements = Vec::new(); - if self.required { - statements.push(quote! { - schema_object.object().required.insert(#field_name.to_owned()); - }); - } + // if self.required { + // statements.push(quote! { + // schema_object.object().required.insert(#field_name.to_owned()); + // }); + // } let mut array_validation = Vec::new(); let mut number_validation = Vec::new(); diff --git a/schemars_derive/src/lib.rs b/schemars_derive/src/lib.rs index c737380..5325f92 100644 --- a/schemars_derive/src/lib.rs +++ b/schemars_derive/src/lib.rs @@ -14,6 +14,7 @@ mod schema_exprs; use ast::*; use proc_macro2::TokenStream; +use syn::spanned::Spanned; #[proc_macro_derive(JsonSchema, attributes(schemars, serde, validate))] pub fn derive_json_schema_wrapper(input: proc_macro::TokenStream) -> proc_macro::TokenStream { @@ -40,14 +41,20 @@ fn derive_json_schema( attr::process_serde_attrs(&mut input)?; let cont = Container::from_ast(&input)?; + let crate_alias = cont.attrs.crate_name.as_ref().map(|path| { + quote_spanned! {path.span()=> + use #path as schemars; + } + }); let type_name = &cont.ident; let (impl_generics, ty_generics, where_clause) = cont.generics.split_for_impl(); if let Some(transparent_field) = cont.transparent_field() { - let (ty, type_def) = schema_exprs::type_for_schema(transparent_field, 0); + let (ty, type_def) = schema_exprs::type_for_field_schema(transparent_field, 0); return Ok(quote! { const _: () = { + #crate_alias #type_def #[automatically_derived] @@ -64,18 +71,12 @@ fn derive_json_schema( <#ty as schemars::JsonSchema>::json_schema(gen) } - fn json_schema_for_flatten(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { - <#ty as schemars::JsonSchema>::json_schema_for_flatten(gen) + fn _schemars_private_non_optional_json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + <#ty as schemars::JsonSchema>::_schemars_private_non_optional_json_schema(gen) } - fn add_schema_as_property( - gen: &mut schemars::gen::SchemaGenerator, - parent: &mut schemars::schema::SchemaObject, - name: String, - metadata: Option, - required: Option, - ) { - <#ty as schemars::JsonSchema>::add_schema_as_property(gen, parent, name, metadata, required) + fn _schemars_private_is_option() -> bool { + <#ty as schemars::JsonSchema>::_schemars_private_is_option() } }; }; @@ -122,16 +123,20 @@ fn derive_json_schema( }; Ok(quote! { - #[automatically_derived] - #[allow(unused_braces)] - impl #impl_generics schemars::JsonSchema for #type_name #ty_generics #where_clause { - fn schema_name() -> std::string::String { - #schema_name - } + const _: () = { + #crate_alias - fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { - #schema_expr - } + #[automatically_derived] + #[allow(unused_braces)] + impl #impl_generics schemars::JsonSchema for #type_name #ty_generics #where_clause { + fn schema_name() -> std::string::String { + #schema_name + } + + fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + #schema_expr + } + }; }; }) } diff --git a/schemars_derive/src/metadata.rs b/schemars_derive/src/metadata.rs index 435469a..a84deca 100644 --- a/schemars_derive/src/metadata.rs +++ b/schemars_derive/src/metadata.rs @@ -49,7 +49,7 @@ impl<'a> SchemaMetadata<'a> { quote! { { let schema = #schema_expr; - gen.apply_metadata(schema, #self) + schemars::_private::apply_metadata(schema, #self) } } } diff --git a/schemars_derive/src/schema_exprs.rs b/schemars_derive/src/schema_exprs.rs index 4965fd5..ed69873 100644 --- a/schemars_derive/src/schema_exprs.rs +++ b/schemars_derive/src/schema_exprs.rs @@ -57,31 +57,38 @@ pub fn expr_for_repr(cont: &Container) -> Result { } fn expr_for_field(field: &Field, allow_ref: bool) -> TokenStream { - let (ty, type_def) = type_for_schema(field, 0); + let (ty, type_def) = type_for_field_schema(field, 0); let span = field.original.span(); + let gen = quote!(gen); if allow_ref { quote_spanned! {span=> { #type_def - gen.subschema_for::<#ty>() + #gen.subschema_for::<#ty>() } } } else { quote_spanned! {span=> { #type_def - <#ty as schemars::JsonSchema>::json_schema(gen) + <#ty as schemars::JsonSchema>::json_schema(#gen) } } } } -pub fn type_for_schema(field: &Field, local_id: usize) -> (syn::Type, Option) { +pub fn type_for_field_schema(field: &Field, local_id: usize) -> (syn::Type, Option) { match &field.attrs.with { None => (field.ty.to_owned(), None), - Some(WithAttr::Type(ty)) => (ty.to_owned(), None), - Some(WithAttr::Function(fun)) => { + Some(with_attr) => type_for_schema(with_attr, local_id), + } +} + +fn type_for_schema(with_attr: &WithAttr, local_id: usize) -> (syn::Type, Option) { + match with_attr { + WithAttr::Type(ty) => (ty.to_owned(), None), + WithAttr::Function(fun) => { let ty_name = format_ident!("_SchemarsSchemaWithFunction{}", local_id); let fn_name = fun.segments.last().unwrap().ident.to_string(); @@ -315,9 +322,14 @@ fn expr_for_adjacent_tagged_enum<'a>( } fn expr_for_untagged_enum_variant(variant: &Variant, deny_unknown_fields: bool) -> TokenStream { - if let Some(WithAttr::Type(with)) = &variant.attrs.with { + if let Some(with_attr) = &variant.attrs.with { + let (ty, type_def) = type_for_schema(with_attr, 0); + let gen = quote!(gen); return quote_spanned! {variant.original.span()=> - gen.subschema_for::<#with>() + { + #type_def + #gen.subschema_for::<#ty>() + } }; } @@ -333,9 +345,14 @@ fn expr_for_untagged_enum_variant_for_flatten( variant: &Variant, deny_unknown_fields: bool, ) -> Option { - if let Some(WithAttr::Type(with)) = &variant.attrs.with { + if let Some(with_attr) = &variant.attrs.with { + let (ty, type_def) = type_for_schema(with_attr, 0); + let gen = quote!(gen); return Some(quote_spanned! {variant.original.span()=> - <#with as schemars::JsonSchema>::json_schema(gen) + { + #type_def + <#ty as schemars::JsonSchema>::json_schema(#gen) + } }); } @@ -362,7 +379,7 @@ fn expr_for_tuple_struct(fields: &[Field]) -> TokenStream { .iter() .filter(|f| !f.serde_attrs.skip_deserializing()) .enumerate() - .map(|(i, f)| type_for_schema(f, i)) + .map(|(i, f)| type_for_field_schema(f, i)) .unzip(); quote! { { @@ -409,20 +426,16 @@ fn expr_for_struct( ..SchemaMetadata::from_attrs(&field.attrs) }; - let (ty, type_def) = type_for_schema(field, type_defs.len()); + let (ty, type_def) = type_for_field_schema(field, type_defs.len()); if let Some(type_def) = type_def { type_defs.push(type_def); } + let args = quote!(gen, &mut schema_object, #name.to_owned(), #metadata, #required); let validation = field.validation_attrs.validation_statements(&name); quote_spanned! {ty.span()=> - <#ty as schemars::JsonSchema>::add_schema_as_property( - gen, - &mut schema_object, - #name.to_owned(), - #metadata, - #required); + schemars::_private::add_schema_as_property::<#ty>(#args); #validation } }) @@ -431,13 +444,14 @@ fn expr_for_struct( let flattens: Vec<_> = flattened_fields .into_iter() .map(|field| { - let (ty, type_def) = type_for_schema(field, type_defs.len()); + let (ty, type_def) = type_for_field_schema(field, type_defs.len()); if let Some(type_def) = type_def { type_defs.push(type_def); } + let gen = quote!(gen); quote_spanned! {ty.span()=> - .flatten(<#ty as schemars::JsonSchema>::json_schema_for_flatten(gen)) + .flatten(schemars::_private::json_schema_for_flatten::<#ty>(#gen)) } }) .collect();