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)]

// LATER The macros don't need to depend on each other but should call a common function to generate the code.

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,
        })
    }
}

/// **Experimental**. Generate the whole `Cvars` struct.
///
/// This allows both the field types and their initial values to be defined on one line.
/// The downside is that users can't specify attributes on the struct.
///
/// The generated code contains the struct definition and an impl block
/// with a `new` function which sets the initial values.
///
/// **TODO**: The generated `Default` should use the specified initial values.
///
/// # Example
///
/// ```rust
/// use cvars::cvars;
///
/// cvars! {
///     g_rocket_launcher_ammo_max: i32 = 20,
///     g_rocket_launcher_damage: f32 = 75.0,
/// }
/// ```
#[proc_macro]
pub fn cvars(input: TokenStream) -> TokenStream {
    // LATER proper error reporting (no unwraps, expect only for infallible)

    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)
}

/// Generate setters and getters that take cvar names as string.
///
/// This requires all types used as cvars to impl `FromStr` and `Display`.
///
/// The generated methods:
/// - `get` - take cvar name as string and return its value as the correct type
/// - `get_string` - take cvar name as string and return its value as a `String`
/// - `set` - take cvar name as string and its new value as the correct type
/// - `set_str` - take cvar name as string and its new value as a `&str`
///
/// Since all 4 functions can fail, all return `Result`s.
///
/// # Example
///
/// ```rust
/// use cvars::SetGet;
///
/// #[derive(SetGet)]
/// pub struct Cvars {
///     g_rocket_launcher_ammo_max: i32,
///     g_rocket_launcher_damage: f32,
/// }
///
/// impl Cvars {
///     pub fn new() -> Self {
///         Self {
///             g_rocket_launcher_ammo_max: 20,
///             g_rocket_launcher_damage: 75.0,
///         }
///     }
/// }
/// ```
#[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"),
    };

    // Get the list of all cvars and their types
    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);
    }

    // Get the set of types used as cvars.
    // We need to impl SetGetType for them and it needs to be done
    // once per type, not once per cvar.
    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];
            // Each `impl SetGetType for X` block only generates match arms for cvars of type X
            // so that the getters and setters typecheck.
            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);
            }
        }

        // LATER Is there a sane way to automatically convert? (even fallibly)
        //       e.g. integers default to i32 even though cvar type is usize
        //       At the very least, it should suggest specifying the type.
        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 {
            /// Finds the cvar whose name matches `cvar_name` and returns its value.
            ///
            /// Returns `Err` if the cvar doesn't exist.
            pub fn get<T: SetGetType>(&self, cvar_name: &str) -> ::core::result::Result<T, String> {
                // We can't generate all the match arms here because we don't know what concrete type T is.
                // Instead, we statically dispatch it through the SetGetType trait and then only look up
                // fields of the correct type in each impl block.
                SetGetType::get(self, cvar_name)
            }

            /// Finds the cvar whose name matches `cvar_name` and returns its value as a `String`.
            ///
            /// Returns `Err` if the cvar doesn't exist.
            pub fn get_string(&self, cvar_name: &str) -> ::core::result::Result<String, String> {
                match cvar_name {
                    // This doesn't need to be dispatched via SetGetType, it uses Display instead.
                    #( stringify!(#fields) => ::core::result::Result::Ok(self.#fields.to_string()), )*
                    _ => ::core::result::Result::Err(format!(
                        "Cvar named {} not found",
                        cvar_name,
                    )),
                }
            }

            /// Finds the cvar whose name matches `cvar_name` and sets it to `value`.
            ///
            /// Returns `Err` if the cvar doesn't exist or its type doesn't match that of `value`.
            ///
            /// **Note**: Rust can't infer the type of `value` based on the type of the cvar
            /// because `cvar_name` is resolved to the right struct field only at runtime.
            /// This means integer literals default to `i32` and float literals to `f64`.
            /// This in turn means if the cvar's type is e.g. usize and you try
            /// `cvars.set("sometihng_with_type_usize", 123);`, it will fail
            /// because at compile time, `123` is inferred to be `i32`.
            /// Use `123_usize` to specify the correct type.
            ///
            /// This limitation doesn't apply to `set_str` since it determines which type to parse to
            /// *after* looking up the right field at runtime.
            pub fn set<T: SetGetType>(&mut self, cvar_name: &str, value: T) -> ::core::result::Result<(), String> {
                SetGetType::set(self, cvar_name, value)
            }

            /// Finds the cvar whose name matches `cvar_name`, tries to parse `str_value` to its type and sets it to the parsed value.
            ///
            /// Returns `Err` if the cvar doesn't exist or if `str_value` fails to parse to its type.
            pub fn set_str(&mut self, cvar_name: &str, str_value: &str) -> ::core::result::Result<(), String> {
                match cvar_name {
                    // This doesn't need to be dispatched via SetGetType, it uses FromStr instead.
                    #( 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

        /// This trait is needed to dispatch cvar get/set based on its type.
        /// You're not meant to impl it yourself, it's done automatically
        /// for all types used as cvars.
        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)
}

/// Check whether the field has the `#[cvars(skip)]` attribute
fn skip_field(field: &Field) -> bool {
    for attr in &field.attrs {
        // Only attempt to parse the attribute if it's ours.
        // Not all attributes are parseable by `parse_meta`.
        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
}

/// Dummy version of SetGet for debugging how much cvars add to _incremental_ compile times of your project.
///
/// Generates the 4 setters and getters like SetGet but they contain only `unimplemented!()`,
/// therefore the code to dispatch from string to struct field is not generated.
/// This exists only to test how using SetGet affects the total compile time of downstream crates.
/// Simply replace SetGet with SetGetDummy and compare how long `cargo build` takes.
/// The resulting code should compile but will crash if the generated methods are used.
#[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)
            }
        }
    }
}