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
137
138
139
140
141
142
143
use attr_name;
use proc_macro2::TokenStream as TokenStream2;
use proc_macro2::{Ident, Span};
use syn::{Attribute, Field, Lit, Meta, MetaNameValue};
pub struct GenParams {
pub attribute_name: &'static str,
pub fn_name_prefix: &'static str,
pub fn_name_suffix: &'static str,
pub global_attr: Option<Meta>,
}
#[derive(PartialEq, Eq)]
pub enum GenMode {
Get,
Set,
GetMut,
}
pub fn attr_tuple(attr: &Attribute) -> Option<(Ident, Meta)> {
let meta = attr.interpret_meta();
meta.map(|v| (v.name(), v))
}
pub fn parse_visibility(attr: Option<&Meta>, meta_name: &str) -> Option<Ident> {
match attr {
Some(Meta::NameValue(MetaNameValue {
lit: Lit::Str(ref s),
ident,
..
})) => {
if ident == meta_name {
s.value()
.split(' ')
.find(|v| *v != "with_prefix")
.map(|v| Ident::new(&v, Span::call_site()))
} else {
None
}
}
_ => None,
}
}
fn has_prefix_attr(f: &Field) -> bool {
let inner = f
.attrs
.iter()
.filter(|v| attr_name(v).expect("Could not get attribute") == "get")
.last()
.and_then(|v| v.parse_meta().ok());
match inner {
Some(Meta::NameValue(meta)) => {
if let Lit::Str(lit) = meta.lit {
lit.value().split(' ').any(|v| v == "with_prefix")
} else {
false
}
}
_ => false,
}
}
pub fn implement(field: &Field, mode: &GenMode, params: &GenParams) -> TokenStream2 {
let field_name = field
.clone()
.ident
.expect("Expected the field to have a name");
let fn_name = Ident::new(
&format!(
"{}{}{}{}",
if has_prefix_attr(field) && (*mode == GenMode::Get || *mode == GenMode::GetMut) {
"get_"
} else {
""
},
params.fn_name_prefix,
field_name,
params.fn_name_suffix
),
Span::call_site(),
);
let ty = field.ty.clone();
let mut doc = Vec::new();
let attr = field
.attrs
.iter()
.filter_map(|v| {
let tuple = attr_tuple(v).expect("attribute");
match tuple.0.to_string().as_str() {
"doc" => {
doc.push(v);
None
}
name if params.attribute_name == name => Some(tuple.1),
_ => None,
}
})
.last()
.or_else(|| params.global_attr.clone());
let visibility = parse_visibility(attr.as_ref(), params.attribute_name);
match attr {
Some(_) => match mode {
GenMode::Get => {
quote! {
#(#doc)*
#[inline(always)]
#visibility fn #fn_name(&self) -> &#ty {
&self.#field_name
}
}
}
GenMode::Set => {
quote! {
#(#doc)*
#[inline(always)]
#visibility fn #fn_name(&mut self, val: #ty) -> &mut Self {
self.#field_name = val;
self
}
}
}
GenMode::GetMut => {
quote! {
#(#doc)*
#[inline(always)]
#visibility fn #fn_name(&mut self) -> &mut #ty {
&mut self.#field_name
}
}
}
},
None => quote! {},
}
}