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
extern crate proc_macro;

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput, Data, Fields,
          DataStruct, FieldsNamed, punctuated::Punctuated, Field,
          PathSegment};

/// Derives the `MutConfig` trait for any struct.
#[proc_macro_derive(MutConfig)]
pub fn derive(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);

    let sname = &ast.ident;
    let data = &ast.data;

    if sname.to_string().find("Config").is_none() {
        panic!("Please name the struct in a format like <name>Config (ex. MainConfig)");
    };

    let fields = filter_ignore_out(extract_fields(&data));
    let types = extract_types(&data);

    // generates an appropriate map insertion according to the field
    let insertions = (0..fields.len()).map(|i| {
        let fname = &fields[i].ident;

        let oval = into_oval(&fields[i], &types[i]);

        quote! {
            map.insert(String::from(stringify!(#fname)), #oval);
        }
    });

    let allinserts = quote! {
        #(#insertions)*
    };

    let expandify = quote! {
        impl MutConfig for #sname {
            fn to_hashmap(&self) -> HashMap<String, MutOptionVal> {
                use MutOptionVal::*;
                let mut map = HashMap::new();

                #allinserts

                map
            }
        }
    };

    expandify.into()
}

/// Extracts the names of the fields of the struct
fn extract_fields(data: &Data) -> &Punctuated<Field, syn::token::Comma>{
    if let Data::Struct(DataStruct {
        fields: Fields::Named(FieldsNamed {
            ref named,
            ..
        }), ..
    }) = data {
        named
    } else {
        unimplemented!()
    }
}

fn not_ignored(field: &Field) -> bool {
    for attr in &field.attrs {
        let segs = &attr.path.segments;

        for seg in segs {
            let attrname = seg.ident.to_string();

            if attrname == "ignore" {return false;};
        }
    };

    true
}

fn filter_ignore_out(fields: &Punctuated<Field, syn::token::Comma>) -> Vec<&Field> {
    fields.iter().filter(|f| not_ignored(*f)).collect()
}

/// Extracts the types of the fields of the struct
fn extract_types(data: &Data) -> Vec<&syn::PathSegment>{
    let fields = filter_ignore_out(extract_fields(data));

    // let type_idents: Vec<&syn::Ident> = 
    fields.iter().map(|field| {
        if let syn::Field {
            ty: syn::Type::Path(
                syn::TypePath {
                    path: syn::Path {
                        ref segments,
                        ..
                    },
                    ..
                }
            ),
            ..
        } = field {
            &segments[0]
        } else {
            eprintln!("References are not supported with #[derive(MutConfig)]. Reference found within type.");
            unimplemented!()
        }
    }).collect::<Vec<&syn::PathSegment>>()
}

/// Extracts the generic arguments of types of fields from the struct.
/// 
/// If a type has no generic arguments, the vector is empty.
/// 
/// The first Vec layer represents the types. The second Vec layer represents the args.
/// 
/// To think about it better, it's like this:
/// 
/// ```
/// output.iter().map(|TYPE| {
///     TYPE.iter().map(|ARG| {
///         ...
///     })
/// })
/// ```
fn extract_generic_types(data: &Data) -> Vec<Vec<&syn::PathSegment>> {
    let types = extract_types(data);

    let something : Vec<Vec<&syn::PathSegment>> = types.iter().map(|ps| {
        let args = 
            if let syn::PathArguments::AngleBracketed(
                syn::AngleBracketedGenericArguments {
                    ref args,
                    ..
                }
            ) = &ps.arguments {
                Some(args)
            } else {
                None
            };

        let gentype : Vec<&syn::PathSegment> = args.map_or(vec![], |sa| {
            sa.iter().map(|a| {
                if let syn::GenericArgument::Type(syn::Type::Path(
                    syn::TypePath {
                        path : syn::Path {
                            ref segments,
                            ..
                        },
                        ..
                    }
                )) = a {
                    &segments[0]
                } else {
                    eprintln!("References are not supported with #[derive(MutConfig)]. Reference found within generic.");
                    unimplemented!()
                }
            }).collect()
        });

        gentype

    }).collect();

    something
}

/// Panics if the type name isn't compatible with the macro.
/// 
/// To be used by `derive` to avoid repetition.
fn incompatible_type_panic(tyname: &String) {
    panic!("Can't use \'{0}\' type - not yet supported by derive(MutConfig).\nHint: If you meant to add a struct implementing MutConfig, please name them in the following format: '{0}Config'\nPlease use one of the supported types as shown below:\n {1:#?}",tyname, ["isize", "String", "bool", "f64", "Vec<...>", "Option<...>"]);
}

/// Turns a field into an OVal. Uses the field name and its type.
fn into_oval(field: &Field, ty: &PathSegment) -> proc_macro2::TokenStream {
    let fname = &field.ident;
    let tname = &ty.ident;
    let tstr  = &tname.to_string();

    if tstr == "isize" {
        quote! {OInt(self.#fname.clone())}
    } else if tstr == "String" {
        quote! {OString(self.#fname.clone())}
    } else if tstr == "bool" {
        quote! {OBool(self.#fname.clone())}
    } else if tstr == "f64" {
        quote! {OFloat(self.#fname.clone())}
    } else if tstr == "Vec" {
        let gen = get_first_generic(&ty);
        // let v = into_oVal(&field, &gen);
        let v = into_subval(&gen, &String::from("a"));
        quote! {OArray(self.#fname.iter().map(|a| #v).collect())}
    } else if tstr == "Option" {
        let gen = get_first_generic(&ty);
        // let v = into_oVal(&field, &gen);
        let v = into_subval(&gen, &String::from("a"));
        quote! {self.#fname.clone().map_or(ONone(), |a| #v)}
    } else if tstr.find("Config").is_some() {
        quote! {OMap(self.#fname.to_hashmap())}
    } else {
        unimplemented!()
    }
}

/// Retrieves the first generic of a type.
/// 
/// For example: `Result<isize, usize>` -> `isize`.
fn get_first_generic(ty: &PathSegment) -> &PathSegment {
    let args =
        if let syn::PathArguments::AngleBracketed(
            syn::AngleBracketedGenericArguments {
                ref args,
                ..
            }
        ) = &ty.arguments {
            args
        } else {
            unimplemented!();
        };

    let typs : Vec<&PathSegment> = args.iter().map(|a| {
        if let syn::GenericArgument::Type(syn::Type::Path(
            syn::TypePath {
                path : syn::Path {
                    ref segments,
                    ..
                },
                ..
            }
        )) = a {
            &segments[0]
        } else {
            unimplemented!()
        }
    }).collect();

    typs[0]
}

/// Used by `into_oval` to represent nested OValues.
/// 
/// For example, in `Option<Vec<String>>`, `Option<...>` is initially parsed by
/// `into_oval`, however `Vec<...>` and `String` are parsed by this function.
/// 
/// In effect, any type A<B<...>> will have A<...> parsed in `into_oval`, and 
/// `B<...>` parsed in `into_subval`
fn into_subval(ty: &PathSegment, arg_name: &String) -> proc_macro2::TokenStream {
    let tname = &ty.ident;
    let tstr = &tname.to_string();

    let arg = syn::Ident::new(arg_name, tname.span());
    let new_arg = syn::Ident::new((arg_name.clone() + "a").as_str(), tname.span());

    if tstr == "isize" {
        quote! {OInt(#arg.clone())}
    } else if tstr == "String" {
        quote! {OString(#arg.clone())}
    } else if tstr == "bool" {
        quote! {OBool(#arg.clone())}
    } else if tstr == "f64" {
        quote! {OFloat(#arg.clone())}
    } else if tstr == "Vec" {
        let gen = get_first_generic(&ty);
        // let v = into_oVal(&field, &gen);
        let v = into_subval(&gen, &new_arg.to_string());
        quote! {OArray(#arg.iter().map(|#new_arg| #v).collect())}
    } else if tstr == "Option" {
        let gen = get_first_generic(&ty);
        // let v = into_oVal(&field, &gen);
        let v = into_subval(&gen, &new_arg.to_string());
        quote! {#arg.clone().map_or(ONone(), |#new_arg| #v)}
    } else if tstr.find("Config").is_some() {
        quote! {OMap(#arg.to_hashmap())}
    } else {
        incompatible_type_panic(&tstr);
        unimplemented!();
    }
}