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
384
385
386
387
388
389
390
391
392
393

#![recursion_limit="128"]

#[macro_use]
extern crate quote;
extern crate syn;

extern crate proc_macro;
extern crate proc_macro2;

#[proc_macro_derive(Builder, attributes(method, result, mysqldate, truebool))]
pub fn derive_builder(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let ast: syn::DeriveInput = syn::parse(input).expect("Couldn't parse derive(Builder) item");
    let gen = match ast.data {
        syn::Data::Struct(ref s) => {
            new_for_struct(&ast, &s.fields)
        },
        _ => {
            panic!("works with structs only")
        }
    };
    
    gen.into()
}

/// Field summery for struct
struct FieldSummary<'a> {
    name: &'a proc_macro2::Ident,
    member_type: &'a syn::Type,
    param_type: syn::Type,
    mandatory: bool,
    alternative_format: bool,
}

impl<'a> std::fmt::Debug for FieldSummary<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        let alt = match self.alternative_format {
            true => { " ALT" },
            false => { "" },
        };
        let manopt = match self.mandatory {
            true => {  " mandatory" },
            false => { "  optional" },
        };
        write!(f, "[ {}: {}{} ]", manopt, self.name.to_string(), alt)
    }
}

/// Handle builder derive for struct.
fn new_for_struct(ast: &syn::DeriveInput, fields: &syn::Fields) -> proc_macro2::TokenStream {
    let struct_name = &ast.ident;
    let mut summaries = Vec::new();
    let mut flickr_api_type: Option<syn::Type> = None;
    
    let mut method_name: Option<String> = None; 
    let mut result_struct_type: Option<String> = None;
    for attr in &ast.attrs {
        let attr_name = attr.path.segments.last().expect("last segment").into_tuple().0.ident.to_string();
        for tt in attr.clone().tts.into_iter() {
            match tt {
                proc_macro2::TokenTree::Literal(lit) => {
                    if attr_name == "method" {
                        method_name = Some(strip_quotes(&lit.to_string()));
                    }

                    if attr_name == "result" {
                        result_struct_type = Some(strip_quotes(&lit.to_string()));
                    }
                },
                _ => {
                }
            }
        }
    }
    
    match fields {
        syn::Fields::Named(fields_named) => {
            for ref f in fields_named.named.iter() {
                // Look for macro attributes
                let mut alternative_format = false; // TODO
                for attr in &f.attrs {
                    if let Some(pair) = attr.path.segments.last() {
                        match pair {
                            syn::punctuated::Pair::Punctuated(_t, _p) => {
                            },
                            syn::punctuated::Pair::End(t) => {
                                if t.ident == "mysqldate" {
                                    alternative_format = true;
                                } else if t.ident == "truebool" {
                                    alternative_format = true;
                                }
                            }
                        }
                    }
                }
                
                if let Some(ref field_name) = f.ident {
                    // Check field name
                    let field_name_string = field_name.to_string();
                    if field_name_string == "flickr" { 
                        flickr_api_type = Some(f.ty.clone());
                        continue; 
                    }
                    
                    // Method parameter type
                    let member_type = &f.ty;
                    let mut param_type = f.ty.clone();
                    let mut mandatory = true;
                    match param_type.clone() {
                        syn::Type::Path(ref mut pt) => {
                            let seg1 = pt.path.segments
                                    .first()
                                    .expect("Option")
                                    .into_tuple().0;
                        
                            // Convert Option<T> to T
                            if seg1.ident.to_string() == "Option" 
                            {
                                mandatory = false;
                                
                                match &seg1.arguments {
                                    syn::PathArguments::AngleBracketed(abga) => {
                                        let arg1 = abga
                                                .args
                                                .first()
                                                .expect("GenericArgument")
                                                .into_tuple().0;
                                        match arg1 {
                                            syn::GenericArgument::Type(ty) => {
                                                param_type = ty.clone();
                                            },
                                            _ => { }
                                        }
                                    },
                                    _ => { }
                                }
                            }
                        },
                        _ => { }
                    };

                    // Create field summary                    
                    summaries.push(FieldSummary{
                        name: field_name,
                        member_type: member_type,
                        param_type: param_type,
                        mandatory: mandatory,
                        alternative_format: alternative_format,
                    });
                }
                
                //println!("{:?}", summaries.last().unwrap());
            }
        },
        _ => { }
    }    

    let mut r = proc_macro2::TokenStream::new();

    // Generate a setters
    for summary in summaries.iter() {
        r.extend(generate_setter_method(&summary));
    }

    // Generate separate methods
    if let Some(ty) = flickr_api_type {
        r.extend(generate_constructor(struct_name, &ty, &summaries));
        if let Some(method_name) = method_name {
            if let Some(result_struct_type) = result_struct_type {
                r.extend(generate_perform_method(
                        &method_name, 
                        &result_struct_type, 
                        &summaries));
            } else {
                panic!("Attribute 'return' name not defined for struct {}", 
                       struct_name.to_string());
            }
        } else {
            panic!("Attribute 'method' name not defined for struct {}", 
                   struct_name.to_string());
        }
    } else {
        panic!("Member field 'flickr' not found in struct {}", 
               struct_name.to_string());
    }

    // Generate the surrounding block
    generate_impl(struct_name, r)
}

/// Generate impl block
fn generate_impl(struct_name: &syn::Ident, functions: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
    let r = quote! {
        impl<'a> #struct_name<'a> {
            #functions
        }
    };
    //println!("{}", r);
    r
}

/// Generates a setter method for Builder.
fn generate_setter_method(summary: &FieldSummary) -> proc_macro2::TokenStream {
    let func_name = summary.name;
    let field_name = summary.name;
    let param_type = &summary.param_type;

    if summary.mandatory {
        quote! { 
            #[inline(always)]
            pub fn #func_name(&mut self, value: #param_type) -> &mut Self {
                self.#field_name = value;
                self
            }
        }
    } else {
        quote! {  
            #[inline(always)]
            pub fn #func_name(&mut self, value: #param_type) -> &mut Self {
                self.#field_name = Some(value);
                self
            }
        }
    }
}

/// Generates a constructor
fn generate_constructor(struct_name: &syn::Ident, flickr_api_type: &syn::Type, summaries: &Vec<FieldSummary>) -> proc_macro2::TokenStream {
    let mut rf = proc_macro2::TokenStream::new();
    for summary in summaries.iter() {
        let field_name = summary.name;
        let field_type = summary.member_type;
        match field_type { // TODO: many brave assumptions below
            syn::Type::Reference(_) => {
                rf.extend(quote! {
                    #field_name: "",
                });
            },
            _ => {
                if summary.mandatory {
                    rf.extend(quote! {
                        #field_name: #field_type::default(),
                    });
                } else {
                    rf.extend(quote! {
                        #field_name: Option::None,
                    });
                }
            }
        }
    }

    let mut r = proc_macro2::TokenStream::new();
    r.extend(quote! {  
        pub fn new(flickr: #flickr_api_type) -> Self {
            #struct_name {
                flickr: flickr,
                #rf
            }
        }
    });
    r
}

/// Generates a perform method which calls Flickr API.
fn generate_perform_method(method_name: &str, result_struct_type: &str, summaries: &Vec<FieldSummary>) -> proc_macro2::TokenStream {

    // Generate parameter assignments to hashmap
    let mut params_to_p = proc_macro2::TokenStream::new();
    for summary in summaries.iter() {
        let field_name = summary.name;
        let field_name_lit = syn::LitStr::new(&field_name.to_string(), 
                                              proc_macro2::Span::call_site());

        // Assignment and possible type conversion
        let value_to_string = match get_real_type(&summary.param_type) {
            Some(type_name) => {
                match type_name.as_str() {
                    // Conversion of booleans into numeric url parameters
                    "bool" => {
                        if summary.alternative_format {
                            quote! { 
                                match value {
                                    true => "true".into(),
                                    false => "false".into(),
                                }
                            }
                        } else {
                            quote! { 
                                match value {
                                    true => "1".into(),
                                    false => "0".into(),
                                }
                            }
                        }
                    },
                    // Conversion of DateTime objects into numbers
                    "DateTime" => {
                        if summary.alternative_format {
                            // MySQL datetime format, 2018-11-26 20:32:01
                            quote! {
                                {
                                    let utc_tz = Utc::now().timezone();
                                    let value_utc = value.with_timezone(&utc_tz);
                                    format!("{}", value_utc.format("%Y-%m-%d %H:%M:%S"))
                                }
                            }
                        } else {
                            quote! {
                                format!("{}", value.timestamp())
                            }
                        }
                    },
                    // Other types need only basic conversion into string
                    _ => {
                        quote! { value.to_string() }
                    }
                }
            },
            None => {
                // This should never be needed...
                quote! { value.to_string() }
            }
        };

        // Add fields to params if they are mandatory or if they are set
        if summary.mandatory {
            params_to_p.extend(quote! {
                let value = &self.#field_name;
                p.insert(#field_name_lit, #value_to_string);
            });
        } else {
            params_to_p.extend(quote! {
                if let Some(ref value) = self.#field_name {
                    p.insert(#field_name_lit, #value_to_string);
                }
            });
        }
    }

    // Strenghtening certain types
    let result_struct_type_ident = 
            syn::Ident::new(
                result_struct_type, 
                proc_macro2::Span::call_site());
    let method_name_lit = syn::LitStr::new(
                                            method_name, 
                                            proc_macro2::Span::call_site());

    // Generate code
    quote! {  
        pub fn perform(&'a mut self) -> Result<#result_struct_type_ident, FlickrError> {
            if !self.flickr.is_authenticated() { 
                self.flickr.do_auth()?; 
            }

            let mut p: std::collections::BTreeMap<&str, String> 
                = std::collections::BTreeMap::new();
            
            #params_to_p

            let content = self.flickr.call_method(#method_name_lit, p)?;
            let r: #result_struct_type_ident = serde_json::from_str(&content)?;
            Ok(r)
        }
    }
}

/// Gets the nested type of the syn type, or None if not found.
fn get_real_type(ty: &syn::Type) -> Option<String> {
    match ty {
        syn::Type::Path(tp) => {
            match tp.path.segments.last()? {
                syn::punctuated::Pair::Punctuated(t, _p) => {
                    Some(t.ident.to_string())
                },
                syn::punctuated::Pair::End(t) => {
                    //println!("end : ident: {}", t.ident);
                    Some(t.ident.to_string())
                }
            }
        },
        _ => {
            None
        }
    }
}

/// Removes quote marks from the string
fn strip_quotes(s: &String) -> String {
    s.replace("\"", "")
}