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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! `thunder.rs` a zero-boilerplate commandline argument parser ✨
#![feature(external_doc)]
#![doc(include = "../README.md")]
#![feature(proc_macro, proc_macro_lib)]
#![allow(unused_imports, unused_variables)]

extern crate proc_macro;

#[macro_use]
extern crate syn;

#[macro_use]
extern crate quote;

use proc_macro::TokenStream;
use quote::ToTokens;
use std::collections::HashSet as Set;
use std::str::FromStr;
use syn::fold::{self, Fold};
use syn::punctuated::Punctuated;
use syn::synom::Synom;
use syn::LitStr;
use syn::{
    DeriveInput, Expr, FnArg, GenericArgument, Ident, ImplItem, ImplItemMethod, Item, ItemImpl,
    ItemStatic, Pat, PathArguments, PathSegment, Stmt, Type,
};

macro_rules! check_input {
    ($y:expr, $x:expr) => {
        match $x {
            Ok(s) => s,
            Err(e) => panic!(
                "Failed to parse type in global arg annotation '{}'. Specific error: {:?}",
                $y, e
            ),
        }
    };
}

/// Main macro that implements automated clap generation. This invokes ✨ *magic* ✨
///
/// Foremost every `impl` block tagged with the macro will turn into a Thunder-app. At
/// the moment only a single Thunder app can exist in the same scope (this will change).
///
/// What a `thunder` app does is take every function in it's scope and turn it into a
/// CLI handle with `clap`, meaning that all arguments will be mapped to the user shell
/// as they are described in the function body.
///
/// ## Example
///
/// ```rust norun
/// fn say_hello(name: &str, age: Option<u16>) {
///     // ...
/// }
/// ```
///
/// This function will turn into the CLI option `say_hello` that always takes a name
/// parameter (which is a String) and optionally a number (which has to fit into u16!)
///
/// These conversion checks are done at run-time but functions are only called if
/// the parameters are valid. As such, you don't have to worry :)
///
/// ### A more complete example
///
/// The block below defines a medium sized `thunder` application.
///
/// ```rust norun
/// struct MyApp;
///
/// #[thunderclap]
/// impl MyApp {
///     /// Say hello to someone on the other side
///     fn say_hello(name: &str, age: Option<u16>) { /* ... */ }
///     
///     /// It was nice to meet you!
///     fn goodybe(name: Option<&str>) { /* ... */ }
/// }
///
/// fn main() {
///     // This starts the match execution
///     MyApp::start();
/// }
/// ```
///
/// ## Global variables
///
/// It's possible to declare argument parameters that can be invoked on any function and
/// are available outside of regular context. `thunder` generates an argument store which
/// you can use to get results from these global arguments.
///
/// They can be both mandatory (`T`) or optional (`Option<T>`) and are named and also have
/// a description displayed to the user. Their names are abbreviated with `--name` and `-n`
/// if the parameter was called `name`.
///
/// A small example below.
///
/// ```rust norun
/// struct MyApp;
///
/// #[thunder(arg1: u32: "A small description", arg2: Option<bool>: "Optional global")]
/// impl MyApp {
///     fn hello(name: &str) {}
/// }
///
/// fn main() {
///     MyApp::start();
/// }
/// ```
///
/// If you have more questions or encounter bugs, don't hesitate to contact us!
/// PR's always welcome (we're friendly ❤️)
#[proc_macro_attribute]
pub fn thunderclap(args: TokenStream, input: TokenStream) -> TokenStream {
    let i: ItemImpl = match syn::parse(input.clone()) {
        Ok(input) => input,
        Err(e) => panic!("Error: '{}'", e),
    };

    /* Manually parse any argument pars given to us */
    let args: String = args.to_string();
    let global_args = if args.len() != 0 {
        args.split(',')
            .map(|i| i.trim())
            .map(|i| i.split(':').map(|x| x.trim()).collect::<Vec<&str>>())
            .map(|triple| (triple[0], triple[1], triple[2]))
            .map(|(x, y, z)| {
                (
                    check_input! { x, TokenStream::from_str(&x.replace("\"", "")) },
                    check_input! { y, TokenStream::from_str(y) },
                    z.replace("\"", ""),
                )
            })
            .map(|(x, y, z)| {
                (
                    check_input! { x, syn::parse(x.clone()) },
                    check_input! { y, syn::parse(y.clone()) },
                    z,
                )
            })
            .map(|(x, y, z)| (x, y, String::from(z)))
            .collect::<Vec<(Type, Type, String)>>()
    } else {
        Vec::new()
    };

    let (name, app_token) = match *i.self_ty {
        Type::Path(ref p) => {
            let meh = p.path.segments[0].ident;
            (format!("{}", p.path.segments[0].ident), quote!( #meh ))
        }
        _ => (format!("Unknown App"), quote!()),
    };

    let about = i.attrs
        .iter()
        .map(|x| (x, x.path.segments.first()))
        .filter(|(a, x)| x.is_some())
        .map(|(a, x)| (a, x.unwrap().value().clone()))
        .map(|(a, v)| match &v.ident.to_string().as_str() {
            &"doc" => String::from(
                format!("{}", a.tts)
                    .replace("/", "")
                    .replace("\\", "")
                    .replace("\"", "")
                    .replace("=", "")
                    .trim(),
            ),
            _ => String::from(""),
        })
        .collect::<String>();

    let mut matches: Vec<quote::Tokens> = Vec::new();
    let orignal = quote!(#i);
    let mut app = quote! {
        App::new(#name).about(#about).setting(AppSettings::SubcommandRequired)
    };

    let mut accessors = quote!{};
    let mut data_struct_fields = quote!{};
    let mut init_struct_fields = quote!{};
    let mut global_match_state_matcher = quote!{};

    global_args.iter().for_each(|(name, typed, about)| {
        let (name, name_token) = match name {
            Type::Path(ref p) => {
                let meh = p.path.segments[0].ident;
                (format!("{}", p.path.segments[0].ident), quote!( #meh ))
            }
            _ => (format!("Unknown App"), quote!()),
        };

        let name = format!("{}", name);
        let optional = match typed {
            Type::Path(ref p) => match p.path.segments.first() {
                Some(ps) => match &ps.value().ident.to_string().as_str() {
                    &"Option" => true,
                    _ => false,
                },
                _ => false,
            },
            _ => false,
        };

        let inner = if optional {
            match typed {
                Type::Path(ref p) => match p.path.segments.first() {
                    Some(ps) => match ps.value().arguments {
                        PathArguments::AngleBracketed(ref b) => match b.args.first() {
                            Some(pair) => match pair.value() {
                                GenericArgument::Type(Type::Path(pp)) => {
                                    Some(Type::from(pp.clone()))
                                }
                                _ => None,
                            },
                            _ => None,
                        },
                        _ => None,
                    },
                    _ => None,
                },
                _ => None,
            }
        } else {
            None
        };

        accessors = quote! {
            #accessors

            #[allow(unused)]
            fn #name_token ( /* No Parameters */ ) -> #typed {
                unsafe {
                    __THUNDER_DATA_STATIC.as_ref().unwrap().#name_token.as_ref().unwrap().clone()
                }
            }
        };

        data_struct_fields = quote! {
            #data_struct_fields
            #name_token : Option< #typed > ,
        };

        init_struct_fields = quote! {
            #init_struct_fields
            #name_token : None ,
        };

        global_match_state_matcher = if optional {
            let inner = inner.unwrap();
            quote! {
                #global_match_state_matcher
                global_match_states.#name_token = match args.value_of(#name) {
                    Some(v) => Some(Some(v.parse::<#inner>().expect("Failed to parse value. Double check!"))),
                    None => None,
                };
            }
        } else {
            quote! {
                #global_match_state_matcher
                global_match_states.#name_token = Some(args.value_of(#name).unwrap().parse::<#typed>().expect("Failed to parse value. Double check!"));
            }
        };

        app = if optional {
            let long = format!("--{}", name);
            let short = format!("-{}", &name[..1]);
            quote! {
                #app
                .arg(Arg::with_name(#name).long(#long).short(#short).takes_value(true).help(#about))
            }
        } else {
            quote! {
                #app
                .arg(Arg::with_name(#name).takes_value(true).required(true).help(#about))
            }
        };
    });

    for item in &i.items {
        match item {
            &ImplItem::Method(ref i) => {
                let name = LitStr::new(&i.sig.ident.to_string(), i.sig.ident.span);
                let func_id = &i.sig.ident;
                let about = match i.attrs.first() {
                    Some(a) => String::from(
                        format!("{}", a.tts)
                        /* Clean the tokens TODO: Make this not suck */
                        .replace("/", "")
                        .replace("\\", "")
                        .replace("\"", "")
                        .replace("=", "").trim(),
                    ),
                    _ => String::new(),
                };

                let mut arguments = quote!();

                let mut index: usize = 0;
                let args = i.sig
                    .decl
                    .inputs
                    .iter()
                    .fold(quote!{}, |acc, arg| match arg {
                        &FnArg::Captured(ref arg) => match &arg.pat {
                            &Pat::Ident(ref i) => {
                                let name = format!("{}", i.ident);
                                let optional = match arg.ty {
                                    Type::Path(ref p) => match p.path.segments.first() {
                                        Some(ps) => match &ps.value().ident.to_string().as_str() {
                                            &"Option" => true,
                                            _ => false,
                                        },
                                        _ => false,
                                    },
                                    _ => false,
                                };

                                let mmm = if let Some(typed) = match arg.ty {
                                    Type::Path(ref p) => match p.path.segments.first() {
                                        Some(ps) => match optional {
                                            false => Some(arg.ty.clone()),
                                            true => match ps.value().arguments {
                                                PathArguments::AngleBracketed(ref b) => {
                                                    match b.args.first() {
                                                        Some(pair) => match pair.value() {
                                                            GenericArgument::Type(Type::Path(
                                                                pp,
                                                            )) => Some(Type::from(pp.clone())),
                                                            _ => None,
                                                        },
                                                        _ => None,
                                                    }
                                                }
                                                _ => None,
                                            },
                                        },
                                        _ => None,
                                    },
                                    _ => None,
                                } {
                                    if optional {
                                        quote! {
                                            match m.value_of(#name) {
                                                Some(m) => Some(m.parse::<#typed>().unwrap()),
                                                None => None
                                            }
                                        }
                                    } else {
                                        quote! { m.value_of(#name).unwrap().parse::<#typed>().unwrap() }
                                    }
                                } else {
                                    if optional {
                                        quote! { m.value_of(#name) }
                                    } else {
                                        quote! { m.value_of(#name).unwrap() }
                                    }
                                };

                                index += 1;
                                if optional {
                                    arguments = quote! {
                                        #arguments
                                        #mmm
                                    };
                                    quote! { #acc.arg(Arg::with_name(#name)) }
                                } else {
                                    arguments = quote! {
                                        #arguments
                                        #mmm,
                                    };
                                    quote! { #acc.arg(Arg::with_name(#name).required(true)) }
                                }
                            }
                            _ => quote!{ #acc },
                        },
                        _ => quote!{ #acc },
                    });

                app = quote! {
                    #app.subcommand(
                        SubCommand::with_name(#name).about(#about)#args
                    )
                };

                matches.push(quote! { (#name, Some(m)) => #app_token :: #func_id ( #arguments ), });
            }
            _ => {}
        }
    }

    // let mut matchy = quote!{ match args.subcommand() { };
    let mut matchy = quote!{};

    for m in &matches {
        matchy = quote! {
            #matchy
            #m
        };
    }

    matchy = quote! {
        match args.subcommand() {
            #matchy
            _ => { /* We drop errors for now... */ },
        }
    };

    matchy = quote! {
        let mut global_match_states = __ThunderDataStaticStore::new_empty_store();
        #global_match_state_matcher

        unsafe {
            __THUNDER_DATA_STATIC = Some(global_match_states);
        }

        #matchy
    };

    let tokens = quote! {
        #orignal

        /// This block was generated by thunder v0.0.0
        #[allow(unused)]
        impl #app_token {

            /// Starts the CLI parsing and calls whichever function handles the input
            fn start() {
                use clap::{App, SubCommand, Arg, AppSettings};

                let app = #app;
                let args = app.get_matches();
                #matchy
            }

            #accessors
        }

        static mut __THUNDER_DATA_STATIC: Option<__ThunderDataStaticStore> = None;

        /// This block was generated by thunder v0.0.0
        #[allow(unused)]
        #[doc(hidden)]
        struct __ThunderDataStaticStore {
            #data_struct_fields
        }

        #[allow(unused)]
        #[doc(hidden)]
        impl __ThunderDataStaticStore {
            pub fn new_empty_store() -> __ThunderDataStaticStore {
                __ThunderDataStaticStore {
                    #init_struct_fields
                }
            }
        }
    };

    tokens.into()
}