into_attr_derive/
lib.rs

1extern crate dot_structures;
2extern crate proc_macro;
3
4use dot_generator::attr;
5use into_attr::IntoAttribute;
6use proc_macro::TokenStream;
7use quote::quote;
8use syn::{self, Data};
9
10#[proc_macro_derive(IntoAttribute)]
11pub fn into_attr_derive(input: TokenStream) -> TokenStream {
12    let ast = syn::parse(input).unwrap();
13    impl_into_attr_macro(&ast)
14}
15
16fn impl_into_attr_macro(ast: &syn::DeriveInput) -> TokenStream {
17    let name = &ast.ident;
18    let name_str = name.to_string();
19    let gen = match &ast.data {
20        Data::Enum(de) => {
21            quote! {
22              impl IntoAttribute for #name {
23                fn into_attr(self)  -> Attribute {
24                        let v = format!("{:?}",self);
25                        let v =  v.as_str().strip_suffix("_").unwrap_or(v.as_str());
26                        attr!(#name_str,v)
27                }
28              }
29            }
30        }
31        Data::Struct(ds) => {
32            quote! {
33              impl IntoAttribute for #name {
34                fn into_attr(self) -> Attribute {
35                 attr!(#name_str,self.0)
36                }
37              }
38            }
39        }
40        _ => panic!("the unions are unexpected"),
41    };
42
43    gen.into()
44}