Skip to main content

schemars_derive/
lib.rs

1#![forbid(unsafe_code)]
2
3#[macro_use]
4extern crate quote;
5#[macro_use]
6extern crate syn;
7extern crate proc_macro;
8
9mod ast;
10mod attr;
11mod metadata;
12mod regex_syntax;
13mod schema_exprs;
14
15use ast::*;
16use proc_macro2::TokenStream;
17use syn::spanned::Spanned;
18
19#[proc_macro_derive(JsonSchema, attributes(schemars, serde, validate))]
20pub fn derive_json_schema_wrapper(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
21    let input = parse_macro_input!(input as syn::DeriveInput);
22    derive_json_schema(input, false).unwrap_or_else(syn::Error::into_compile_error).into()
23}
24
25#[proc_macro_derive(JsonSchema_repr, attributes(schemars, serde))]
26pub fn derive_json_schema_repr_wrapper(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
27    let input = parse_macro_input!(input as syn::DeriveInput);
28    derive_json_schema(input, true).unwrap_or_else(syn::Error::into_compile_error).into()
29}
30
31fn derive_json_schema(mut input: syn::DeriveInput, repr: bool) -> syn::Result<TokenStream> {
32    attr::process_serde_attrs(&mut input)?;
33
34    let mut cont = Container::from_ast(&input)?;
35    add_trait_bounds(&mut cont);
36
37    let crate_alias = cont.attrs.crate_name.as_ref().map(|path| {
38        quote_spanned! {path.span()=>
39            use #path as schemars;
40        }
41    });
42
43    let type_name = &cont.ident;
44    let (impl_generics, ty_generics, where_clause) = cont.generics.split_for_impl();
45
46    if let Some(transparent_field) = cont.transparent_field() {
47        let (ty, type_def) = schema_exprs::type_for_field_schema(transparent_field);
48        return Ok(quote! {
49            const _: () = {
50                #crate_alias
51                #type_def
52
53                #[automatically_derived]
54                impl #impl_generics schemars::JsonSchema for #type_name #ty_generics #where_clause {
55                    fn is_referenceable() -> bool {
56                        <#ty as schemars::JsonSchema>::is_referenceable()
57                    }
58
59                    fn schema_name() -> std::string::String {
60                        <#ty as schemars::JsonSchema>::schema_name()
61                    }
62
63                    fn schema_id() -> std::borrow::Cow<'static, str> {
64                        <#ty as schemars::JsonSchema>::schema_id()
65                    }
66
67                    fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
68                        <#ty as schemars::JsonSchema>::json_schema(generator)
69                    }
70
71                    fn _schemars_private_non_optional_json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
72                        <#ty as schemars::JsonSchema>::_schemars_private_non_optional_json_schema(generator)
73                    }
74
75                    fn _schemars_private_is_option() -> bool {
76                        <#ty as schemars::JsonSchema>::_schemars_private_is_option()
77                    }
78                };
79            };
80        });
81    }
82
83    let mut schema_base_name = cont.name().to_string();
84
85    if !cont.attrs.is_renamed {
86        if let Some(path) = cont.serde_attrs.remote() {
87            if let Some(segment) = path.segments.last() {
88                schema_base_name = segment.ident.to_string();
89            }
90        }
91    }
92
93    // FIXME improve handling of generic type params which may not implement JsonSchema
94    let type_params: Vec<_> = cont.generics.type_params().map(|ty| &ty.ident).collect();
95    let const_params: Vec<_> = cont.generics.const_params().map(|c| &c.ident).collect();
96    let params: Vec<_> = type_params.iter().chain(const_params.iter()).collect();
97
98    let (schema_name, schema_id) = if params.is_empty()
99        || (cont.attrs.is_renamed && !schema_base_name.contains('{'))
100    {
101        (
102            quote! {
103                #schema_base_name.to_owned()
104            },
105            quote! {
106                std::borrow::Cow::Borrowed(std::concat!(
107                    std::module_path!(),
108                    "::",
109                    #schema_base_name
110                ))
111            },
112        )
113    } else if cont.attrs.is_renamed {
114        let mut schema_name_fmt = schema_base_name;
115        for tp in &params {
116            schema_name_fmt.push_str(&format!("{{{}:.0}}", tp));
117        }
118        (
119            quote! {
120                format!(#schema_name_fmt #(,#type_params=#type_params::schema_name())* #(,#const_params=#const_params)*)
121            },
122            quote! {
123                std::borrow::Cow::Owned(
124                    format!(
125                        std::concat!(
126                            std::module_path!(),
127                            "::",
128                            #schema_name_fmt
129                        )
130                        #(,#type_params=#type_params::schema_id())*
131                        #(,#const_params=#const_params)*
132                    )
133                )
134            },
135        )
136    } else {
137        let mut schema_name_fmt = schema_base_name;
138        schema_name_fmt.push_str("_for_{}");
139        schema_name_fmt.push_str(&"_and_{}".repeat(params.len() - 1));
140        (
141            quote! {
142                format!(#schema_name_fmt #(,#type_params::schema_name())* #(,#const_params)*)
143            },
144            quote! {
145                std::borrow::Cow::Owned(
146                    format!(
147                        std::concat!(
148                            std::module_path!(),
149                            "::",
150                            #schema_name_fmt
151                        )
152                        #(,#type_params::schema_id())*
153                        #(,#const_params)*
154                    )
155                )
156            },
157        )
158    };
159
160    let schema_expr = if repr {
161        schema_exprs::expr_for_repr(&cont)?
162    } else {
163        schema_exprs::expr_for_container(&cont)
164    };
165
166    Ok(quote! {
167        const _: () = {
168            #crate_alias
169
170            #[automatically_derived]
171            #[allow(unused_braces)]
172            impl #impl_generics schemars::JsonSchema for #type_name #ty_generics #where_clause {
173                fn schema_name() -> std::string::String {
174                    #schema_name
175                }
176
177                fn schema_id() -> std::borrow::Cow<'static, str> {
178                    #schema_id
179                }
180
181                fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
182                    #schema_expr
183                }
184            };
185        };
186    })
187}
188
189fn add_trait_bounds(cont: &mut Container) {
190    if let Some(bounds) = cont.serde_attrs.ser_bound() {
191        let where_clause = cont.generics.make_where_clause();
192        where_clause.predicates.extend(bounds.iter().cloned());
193    } else {
194        // No explicit trait bounds specified, assume the Rust convention of adding the trait to each type parameter
195        // TODO consider also adding trait bound to associated types when used as fields - I think Serde does this?
196        for param in &mut cont.generics.params {
197            if let syn::GenericParam::Type(ref mut type_param) = *param {
198                type_param.bounds.push(parse_quote!(schemars::JsonSchema));
199            }
200        }
201    }
202}