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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
extern crate gtmpl_value;
extern crate proc_macro;
extern crate proc_macro2;
#[macro_use]
extern crate quote;
extern crate syn;
use proc_macro::TokenStream;
#[proc_macro_derive(Gtmpl)]
pub fn gtmpl_derive(input: TokenStream) -> TokenStream {
let ast = syn::parse(input).unwrap();
let gen = impl_gtmpl(&ast);
gen.into()
}
fn impl_gtmpl(ast: &syn::DeriveInput) -> proc_macro2::TokenStream {
let name = &ast.ident;
let to_value = match ast.data {
syn::Data::Struct(syn::DataStruct { ref fields, .. }) => {
let fields = fields
.iter()
.filter_map(|field| field.ident.as_ref())
.map(|ident| quote! { m.insert(stringify!(#ident).to_owned(), s.#ident.into()) })
.collect::<Vec<_>>();
quote! { #(#fields);* }
}
_ => {
panic!("#[derive(Gtmpl)] is only defined for structs, not for enums!");
}
};
quote! {
impl From<#name> for ::gtmpl_value::Value {
fn from(s: #name) -> ::gtmpl_value::Value {
use std::collections::HashMap;
#[warn(unused_mut)]
let mut m: HashMap<String, ::gtmpl_value::Value> = HashMap::new();
#to_value;
::gtmpl_value::Value::Object(m)
}
}
}
}