introspection_derive/
lib.rs1extern crate proc_macro;
2extern crate syn;
3#[macro_use]
4extern crate quote;
5extern crate introspection;
6
7use proc_macro::TokenStream;
8
9#[proc_macro_derive(Introspection)]
10pub fn introspection(input: TokenStream) -> TokenStream {
11 let s = input.to_string();
13
14 let ast = syn::parse_derive_input(&s).unwrap();
16
17 let gen = impl_introspection(&ast);
19
20 gen.parse().unwrap()
22}
23
24fn get_entity_type(ast: &syn::DeriveInput) -> introspection::Type {
25 if let syn::Body::Enum(_) = ast.body {
26 return introspection::Type::Enum;
27 }
28 introspection::Type::Struct
29}
30
31fn get_fields(ast: &syn::DeriveInput) -> Vec<String> {
32 match ast.body {
33 syn::Body::Enum(ref variants) => {
34 variants.iter().map(|v| v.ident.clone().to_string()).collect::<Vec<String>>()
35 },
36 syn::Body::Struct(ref variant_data) => {
37 variant_data.fields().iter().map(|f| {
38 if let Some(ref id) = f.ident {
39 id.clone().to_string()
40 } else {
41 String::default()
42 }
43 }).collect::<Vec<String>>()
44 },
45 }
46}
47
48fn quote_fields(fields: Vec<String>) -> quote::Tokens {
49 quote! {
50 vec![
51 #(#fields.to_owned(),)*
52 ]
53 }
54}
55
56fn impl_introspection(ast: &syn::DeriveInput) -> quote::Tokens {
57 let name = &ast.ident;
58 let vis = introspection::Visibility::from(ast.vis.clone());
59 let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
60 let entity_type = get_entity_type(&ast);
61 let fields = quote_fields(get_fields(&ast));
62 quote! {
63 impl #impl_generics introspection::Introspection for #name #ty_generics #where_clause {
64 fn introspection() -> introspection::IntrospectionInfo {
65 introspection::IntrospectionInfo {
66 ident: stringify!(#name).to_owned(),
67 visibility: #vis,
68 entity_type: #entity_type,
69 fields: #fields,
70 }
71 }
72 }
73 }
74}