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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#[macro_use] extern crate quote;
extern crate proc_macro;
extern crate syn;
use std::convert::From;
use proc_macro::TokenStream;
use syn::{Data, Type, Ident, Fields, Field, token::Comma};
use syn::punctuated::Punctuated;
static INVALID_STRUCT: &str = "Struct must be a named struct. Not unnamed or unit.";
static INVALID_VARIANT: &str = "Variant must be a struct. Not an enum or union.";
static GETTER_PREFIX: &str = "";
#[proc_macro_derive(Getters)]
pub fn getters(input: TokenStream) -> TokenStream {
let ast = syn::parse(input).unwrap();
let impl_tokens = setup_getters_impl(&ast);
let mut tokens = quote::Tokens::new();
tokens.append_all(impl_tokens.into_iter());
tokens.into()
}
struct StructSlot {
label: Ident,
_name: Ident,
ty: Type,
}
impl StructSlot {
fn new(label: Ident, name: Ident, ty: Type) -> StructSlot {
StructSlot {
label: label,
_name: name,
ty: ty,
}
}
}
fn field_to_struct_slot(field: &Field) -> StructSlot {
let name = field.ident.as_ref().unwrap().clone();
let label = Ident::from(format!("{}{}", GETTER_PREFIX, &name).as_str());
StructSlot::new(label, name, field.ty.clone())
}
fn get_slots<'a>(
data: &'a syn::Data
) -> Result<&'a Punctuated<Field, Comma>, &'static str> {
match data {
&Data::Struct(ref body) => {
match &body.fields {
&Fields::Named(ref named) => Ok(&named.named),
_ => Err(INVALID_STRUCT),
}
},
_ => Err(INVALID_VARIANT),
}
}
fn setup_getters_impl<'a>(ast: &'a syn::DeriveInput) -> quote::Tokens {
let slots: Vec<StructSlot> = get_slots(&ast.data)
.unwrap_or_else(|e| panic!("Couldn't autogenerate: {}", e))
.iter()
.map(field_to_struct_slot)
.collect();
let struct_methods: Vec<quote::Tokens> = slots
.iter()
.map(|slot| {
let label = slot.label.clone();
let ty = slot.ty.clone();
quote! {
pub fn #label(&self) -> &#ty {
&self.#label
}
}
})
.collect();
let struct_name = ast.ident.clone();
quote! {
impl #struct_name {
#(#struct_methods)*
}
}
}