mirror of
https://gitlab.com/msrd0/gotham-restful.git
synced 2025-04-20 06:54:46 +00:00
allow deriving enums
This commit is contained in:
parent
0b11aaf1f9
commit
50ed2411c9
3 changed files with 73 additions and 12 deletions
|
@ -4,10 +4,66 @@ use quote::quote;
|
|||
use syn::{
|
||||
Field,
|
||||
Fields,
|
||||
Item,
|
||||
ItemEnum,
|
||||
ItemStruct,
|
||||
Variant,
|
||||
parse_macro_input
|
||||
};
|
||||
|
||||
pub fn expand(tokens : TokenStream) -> TokenStream
|
||||
{
|
||||
let input = parse_macro_input!(tokens as Item);
|
||||
|
||||
match input {
|
||||
Item::Enum(item) => expand_enum(item),
|
||||
Item::Struct(item) => expand_struct(item),
|
||||
_ => panic!("derive(OpenapiType) not supported for this context")
|
||||
}.into()
|
||||
}
|
||||
|
||||
fn expand_variant(variant : &Variant) -> TokenStream2
|
||||
{
|
||||
if variant.fields != Fields::Unit
|
||||
{
|
||||
panic!("Enum Variants with Fields not supported");
|
||||
}
|
||||
|
||||
let ident = &variant.ident;
|
||||
|
||||
quote! {
|
||||
enumeration.push(stringify!(#ident).to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn expand_enum(input : ItemEnum) -> TokenStream2
|
||||
{
|
||||
let ident = input.ident;
|
||||
let generics = input.generics;
|
||||
|
||||
let variants : Vec<TokenStream2> = input.variants.iter().map(expand_variant).collect();
|
||||
|
||||
quote! {
|
||||
impl #generics ::gotham_restful::OpenapiType for #ident #generics
|
||||
{
|
||||
fn to_schema() -> ::gotham_restful::OpenapiSchema
|
||||
{
|
||||
use ::gotham_restful::{helper::openapi::*, OpenapiSchema};
|
||||
|
||||
let mut enumeration : Vec<String> = Vec::new();
|
||||
|
||||
#(#variants)*
|
||||
|
||||
OpenapiSchema::new(SchemaKind::Type(Type::String(StringType {
|
||||
format: VariantOrUnknownOrEmpty::Empty,
|
||||
pattern: None,
|
||||
enumeration
|
||||
})))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn expand_field(field : &Field) -> TokenStream2
|
||||
{
|
||||
let ident = match &field.ident {
|
||||
|
@ -48,10 +104,8 @@ fn expand_field(field : &Field) -> TokenStream2
|
|||
}}
|
||||
}
|
||||
|
||||
pub fn expand(tokens : TokenStream) -> TokenStream
|
||||
pub fn expand_struct(input : ItemStruct) -> TokenStream2
|
||||
{
|
||||
let input = parse_macro_input!(tokens as ItemStruct);
|
||||
|
||||
let ident = input.ident;
|
||||
let generics = input.generics;
|
||||
|
||||
|
@ -63,7 +117,7 @@ pub fn expand(tokens : TokenStream) -> TokenStream
|
|||
Fields::Unit => Vec::new()
|
||||
};
|
||||
|
||||
let output = quote!{
|
||||
quote!{
|
||||
impl #generics ::gotham_restful::OpenapiType for #ident #generics
|
||||
{
|
||||
fn to_schema() -> ::gotham_restful::OpenapiSchema
|
||||
|
@ -92,7 +146,5 @@ pub fn expand(tokens : TokenStream) -> TokenStream
|
|||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
output.into()
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue