mirror of
https://gitlab.com/msrd0/gotham-restful.git
synced 2025-04-20 06:54:46 +00:00
add derive macro for resource
This commit is contained in:
parent
75c399d97a
commit
0cf7c9aa3a
9 changed files with 132 additions and 15 deletions
60
gotham_restful_derive/src/resource.rs
Normal file
60
gotham_restful_derive/src/resource.rs
Normal file
|
@ -0,0 +1,60 @@
|
|||
use crate::method::Method;
|
||||
use proc_macro::TokenStream;
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
use quote::quote;
|
||||
use syn::{
|
||||
parse::{Parse, ParseStream, Result as SynResult},
|
||||
punctuated::Punctuated,
|
||||
token::Comma,
|
||||
Ident,
|
||||
ItemStruct,
|
||||
parenthesized,
|
||||
parse_macro_input
|
||||
};
|
||||
use std::str::FromStr;
|
||||
|
||||
struct MethodList(Punctuated<Ident, Comma>);
|
||||
|
||||
impl Parse for MethodList
|
||||
{
|
||||
fn parse(input: ParseStream) -> SynResult<Self>
|
||||
{
|
||||
let content;
|
||||
let _paren = parenthesized!(content in input);
|
||||
let list : Punctuated<Ident, Comma> = Punctuated::parse_separated_nonempty(&content)?;
|
||||
Ok(Self(list))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn expand_resource(tokens : TokenStream) -> TokenStream
|
||||
{
|
||||
let input = parse_macro_input!(tokens as ItemStruct);
|
||||
let ident = input.ident;
|
||||
|
||||
let methods : Vec<TokenStream2> = input.attrs.into_iter().filter(|attr|
|
||||
attr.path.segments.iter().last().map(|segment| segment.ident.to_string()) == Some("rest_resource".to_string()) // TODO wtf
|
||||
).flat_map(|attr| {
|
||||
let m : MethodList = syn::parse2(attr.tokens).expect("unable to parse attributes");
|
||||
m.0.into_iter()
|
||||
}).map(|method| {
|
||||
let method = Method::from_str(&method.to_string()).expect("unknown method");
|
||||
let ident = method.setup_ident();
|
||||
quote!(#ident(&mut route);)
|
||||
}).collect();
|
||||
|
||||
let output = quote! {
|
||||
impl ::gotham_restful::Resource for #ident
|
||||
{
|
||||
fn name() -> String
|
||||
{
|
||||
stringify!(#ident).to_string()
|
||||
}
|
||||
|
||||
fn setup<D : ::gotham_restful::DrawResourceRoutes>(mut route : D)
|
||||
{
|
||||
#(#methods)*
|
||||
}
|
||||
}
|
||||
};
|
||||
output.into()
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue