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
extern crate proc_macro;
extern crate syn;
#[macro_use] extern crate quote;
use proc_macro::TokenStream;
use syn::{Body, VariantData};
use quote::ToTokens;
#[proc_macro_derive(Getters)]
pub fn getters(input: TokenStream) -> TokenStream {
let s = input.to_string();
let ast = syn::parse_macro_input(&s).unwrap();
let gen = impl_getters(&ast);
gen.parse().unwrap()
}
fn impl_getters(ast: &syn::MacroInput) -> quote::Tokens {
let ast = ast.clone();
let structure = &ast.ident;
let slots = match ast.body {
Body::Struct(variants) => {
match variants {
VariantData::Struct(fields) => fields,
_ => { return quote::Tokens::new(); },
}
},
_ => { return quote::Tokens::new(); },
};
let mut tokens = quote::Tokens::new();
for field in slots {
let ty = field.ty;
let ident = field.ident.unwrap();
let impl_tokens = quote! {
impl #structure {
pub fn #ident<'a>(&'a self) -> &'a #ty {
&self.#ident
}
}
};
impl_tokens.to_tokens(&mut tokens);
}
tokens
}