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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
use std::collections::HashSet;
use proc_macro::TokenStream;
use quote::quote;
use syn::{
parse::{Parse, Parser},
parse_macro_input,
punctuated::Punctuated,
Attribute, DeriveInput, Expr, Field, Ident, Meta, MetaList, NestedMeta, Token, Type,
};
struct CvarDef {
attrs: Vec<Attribute>,
name: Ident,
ty: Type,
value: Expr,
}
impl Parse for CvarDef {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let attrs = input.call(Attribute::parse_outer)?;
let name = input.parse()?;
let _: Token![:] = input.parse()?;
let ty = input.parse()?;
let _: Token![=] = input.parse()?;
let value = input.parse()?;
Ok(CvarDef {
attrs,
name,
ty,
value,
})
}
}
#[proc_macro]
pub fn cvars(input: TokenStream) -> TokenStream {
let parser = Punctuated::<CvarDef, Token![,]>::parse_terminated;
let punctuated = parser.parse(input).unwrap();
let cvar_defs: Vec<_> = punctuated.iter().collect();
let attrss: Vec<_> = cvar_defs.iter().map(|cvar_def| &cvar_def.attrs).collect();
let names: Vec<_> = cvar_defs.iter().map(|cvar_def| &cvar_def.name).collect();
let tys: Vec<_> = cvar_defs.iter().map(|cvar_def| &cvar_def.ty).collect();
let values: Vec<_> = cvar_defs.iter().map(|cvar_def| &cvar_def.value).collect();
let expanded = quote! {
#[derive(Debug, Clone, ::cvars::SetGet)]
pub struct Cvars {
#(
#( #attrss )*
pub #names: #tys,
)*
}
#[automatically_derived]
impl ::std::default::Default for Cvars {
fn default() -> Self {
Self {
#(
#names: #values,
)*
}
}
}
};
TokenStream::from(expanded)
}
#[proc_macro_derive(SetGet, attributes(cvars))]
pub fn derive(input: TokenStream) -> TokenStream {
let input: DeriveInput = parse_macro_input!(input);
let struct_name = input.ident;
let set_get_impl = impl_set_get(&struct_name);
let named_fields = match input.data {
syn::Data::Struct(struct_data) => match struct_data.fields {
syn::Fields::Named(named_fields) => named_fields,
syn::Fields::Unnamed(_) => panic!("tuple structs are not supported, use named fields"),
syn::Fields::Unit => panic!("unit structs are not supported, use curly braces"),
},
syn::Data::Enum(_) => panic!("enums are not supported, use a struct"),
syn::Data::Union(_) => panic!("unions are not supported, use a struct"),
};
let mut fields = Vec::new();
let mut tys = Vec::new();
for field in &named_fields.named {
if skip_field(field) {
continue;
}
let ident = field.ident.as_ref().expect("ident was None");
fields.push(ident);
tys.push(&field.ty);
}
let unique_tys: HashSet<_> = tys.iter().collect();
let mut trait_impls = Vec::new();
for unique_ty in unique_tys {
let mut getter_arms = Vec::new();
let mut setter_arms = Vec::new();
for i in 0..fields.len() {
let field = fields[i];
let ty = tys[i];
if ty == *unique_ty {
let getter_arm = quote! {
stringify!(#field) => ::core::result::Result::Ok(cvars.#field),
};
getter_arms.push(getter_arm);
let setter_arm = quote! {
stringify!(#field) => ::core::result::Result::Ok(cvars.#field = value),
};
setter_arms.push(setter_arm);
}
}
let trait_impl = quote! {
#[automatically_derived]
impl SetGetType for #unique_ty {
fn get(cvars: &Cvars, cvar_name: &str) -> ::core::result::Result<Self, String> {
match cvar_name {
#( #getter_arms )*
_ => ::core::result::Result::Err(format!(
"Cvar named {} with type {} not found",
cvar_name,
stringify!(#unique_ty)
)),
}
}
fn set(cvars: &mut Cvars, cvar_name: &str, value: Self) -> ::core::result::Result<(), String> {
match cvar_name {
#( #setter_arms )*
_ => ::core::result::Result::Err(format!(
"Cvar named {} with type {} not found",
cvar_name,
stringify!(#unique_ty),
)),
}
}
}
};
trait_impls.push(trait_impl);
}
let expanded = quote! {
#[automatically_derived]
impl #struct_name {
pub fn get<T: SetGetType>(&self, cvar_name: &str) -> ::core::result::Result<T, String> {
SetGetType::get(self, cvar_name)
}
pub fn get_string(&self, cvar_name: &str) -> ::core::result::Result<String, String> {
match cvar_name {
#( stringify!(#fields) => ::core::result::Result::Ok(self.#fields.to_string()), )*
_ => ::core::result::Result::Err(format!(
"Cvar named {} not found",
cvar_name,
)),
}
}
pub fn set<T: SetGetType>(&mut self, cvar_name: &str, value: T) -> ::core::result::Result<(), String> {
SetGetType::set(self, cvar_name, value)
}
pub fn set_str(&mut self, cvar_name: &str, str_value: &str) -> ::core::result::Result<(), String> {
match cvar_name {
#( stringify!(#fields) => match str_value.parse() {
::core::result::Result::Ok(val) => ::core::result::Result::Ok(self.#fields = val),
::core::result::Result::Err(err) => ::core::result::Result::Err(format!("failed to parse {} as type {}: {}",
str_value,
stringify!(#tys),
err,
))
}, )*
_ => ::core::result::Result::Err(format!(
"Cvar named {} not found",
cvar_name
)),
}
}
}
#set_get_impl
pub trait SetGetType {
fn get(cvars: &Cvars, cvar_name: &str) -> ::core::result::Result<Self, String>
where Self: Sized;
fn set(cvars: &mut Cvars, cvar_name: &str, value: Self) -> ::core::result::Result<(), String>;
}
#( #trait_impls )*
};
TokenStream::from(expanded)
}
fn skip_field(field: &Field) -> bool {
for attr in &field.attrs {
if !attr.path.is_ident("cvars") {
continue;
}
let meta = attr
.parse_meta()
.expect("expected #[cvars(skip)], failed to parse");
if let Meta::List(MetaList { nested, .. }) = meta {
if nested.len() != 1 {
panic!("expected #[cvars(skip)]");
}
let nested_meta = nested.first().expect("len != 1");
if let NestedMeta::Meta(Meta::Path(path)) = nested_meta {
if path.is_ident("skip") {
return true;
} else {
panic!("expected #[cvars(skip)]");
}
} else {
panic!("expected #[cvars(skip)]");
}
} else {
panic!("expected #[cvars(skip)]");
}
}
false
}
#[doc(hidden)]
#[proc_macro_derive(SetGetDummy, attributes(cvars))]
pub fn derive_dummy(input: TokenStream) -> TokenStream {
let input: DeriveInput = parse_macro_input!(input);
let struct_name = input.ident;
let set_get_impl = impl_set_get(&struct_name);
let expanded = quote! {
#[automatically_derived]
impl #struct_name {
pub fn get<T>(&self, cvar_name: &str) -> ::core::result::Result<T, String> {
unimplemented!("SetGetDummy is only for compile time testing.");
}
pub fn get_string(&self, cvar_name: &str) -> ::core::result::Result<String, String> {
unimplemented!("SetGetDummy is only for compile time testing.");
}
pub fn set<T>(&mut self, cvar_name: &str, value: T) -> ::core::result::Result<(), String> {
unimplemented!("SetGetDummy is only for compile time testing.");
}
pub fn set_str(&mut self, cvar_name: &str, str_value: &str) -> ::core::result::Result<(), String> {
unimplemented!("SetGetDummy is only for compile time testing.");
}
}
#set_get_impl
};
TokenStream::from(expanded)
}
fn impl_set_get(struct_name: &Ident) -> proc_macro2::TokenStream {
quote! {
#[automatically_derived]
impl ::cvars::SetGet for #struct_name {
fn get_string(&self, cvar_name: &str) -> ::core::result::Result<String, String> {
self.get_string(cvar_name)
}
fn set_str(&mut self, cvar_name: &str, cvar_value: &str) -> ::core::result::Result<(), String> {
self.set_str(cvar_name, cvar_value)
}
}
}
}