hpl_toolkit_derive_to_schema/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
extern crate proc_macro;
mod renderers;
mod utils;
use syn::parse_macro_input;

#[proc_macro_derive(ToSchema)]
pub fn to_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input_str = input.to_string();
    let input_split = input_str.split("{").collect::<Vec<&str>>();
    let renderee = input_split.first().unwrap();

    if renderee.contains("struct") {
        let strct = parse_macro_input!(input as syn::ItemStruct);

        if strct.generics.params.len() > 0 {
            panic!("`ToSchema` derive does not allow generics");
        }

        renderers::SchemaStruct::new(strct).render()
    } else if renderee.contains("enum") {
        let enm = parse_macro_input!(input as syn::ItemEnum);

        if enm.generics.params.len() > 0 {
            panic!("`ToSchema` derive does not allow generics");
        }

        renderers::SchemaEnum::new(enm).render()
    } else {
        panic!("Unknown structured provided for ToSchema, only enum and struct are allowed")
    }
}