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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
use proc_macro::TokenStream;
use proc_macro2::{Ident, TokenTree};
use quote::{format_ident, quote};
use syn::{parse_macro_input, Attribute, Data, DeriveInput, Error, Expr, Fields, Meta, Result};

#[proc_macro_derive(Command, attributes(command, scopes, paths))]
pub fn derive_command(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    match command(input) {
        Ok(expansion) => expansion,
        Err(err) => err.to_compile_error().into(),
    }
}

fn command(input: DeriveInput) -> Result<TokenStream> {
    let input_name = input.ident;

    let outer_scopes = input
        .attrs
        .iter()
        .filter_map(|attr| get_lit_list_attr(attr, "scopes"))
        .next()
        .unwrap_or(Vec::new());

    match input.data {
        Data::Enum(ref data_enum) => {
            let mut alias_paths = match input.attrs.iter().filter_map(parse_path).next() {
                // there should only be one base command name set
                Some(paths) => paths,
                None => {
                    return Err(Error::new_spanned(
                        input_name,
                        "No paths attribute found for command enum",
                    ))
                }
            };

            let base_path = alias_paths.remove(0);

            let fields = &data_enum.variants;
            let mut paths = Vec::new();

            for variant in fields {
                for attr in variant.attrs.iter() {
                    if let Some(attr_paths) = parse_path(attr) {
                        paths.push((attr_paths, variant.fields.clone(), variant.ident.clone()));
                    }
                }
            }

            let mut expanded_nodes = Vec::new();

            for (paths, fields, variant_ident) in paths {
                expanded_nodes.push({
                    let processed = process_paths_enum(
                        &input_name,
                        paths,
                        &fields,
                        variant_ident.clone(),
                        true,
                    );
                    quote! { #processed; }
                });
            }

            let base_command_expansion = {
                let processed = process_paths_enum(
                    &input_name,
                    vec![base_path],
                    &Fields::Unit,
                    format_ident!("{}Root", input_name), // this is more of placeholder
                    // (should never be used)
                    false,
                ); // this will error if the base path has args
                let mut expanded_main_command = quote! {
                    let command_root_node = #processed
                };

                if !outer_scopes.is_empty() {
                    expanded_main_command = quote! {
                        #expanded_main_command
                            .with_scopes(vec![#(#outer_scopes),*])
                    }
                }

                quote! {
                    #expanded_main_command.id();
                }
            };

            let command_alias_expansion = {
                let mut alias_expansion = quote! {};
                for path in alias_paths {
                    let processed = process_paths_enum(
                        &input_name,
                        vec![path],
                        &Fields::Unit,
                        format_ident!("{}Root", input_name),
                        false,
                    );

                    alias_expansion = quote! {
                        #alias_expansion

                        #processed
                            .redirect_to(command_root_node)
                    };

                    if !outer_scopes.is_empty() {
                        alias_expansion = quote! {
                            #alias_expansion
                                .with_scopes(vec![#(#outer_scopes),*])
                        }
                    }

                    alias_expansion = quote! {
                        #alias_expansion;
                    }
                }

                alias_expansion
            };

            let _new_struct = format_ident!("{}Command", input_name);

            Ok(TokenStream::from(quote! {

                impl valence::command::Command for #input_name {
                    fn assemble_graph(command_graph: &mut valence::command::graph::CommandGraphBuilder<Self>) {
                        use valence::command::parsers::CommandArg;
                        #base_command_expansion

                        #command_alias_expansion

                        #(#expanded_nodes)*
                    }
                }
            }))
        }
        Data::Struct(x) => {
            let mut paths = Vec::new();

            for attr in input.attrs.iter() {
                if let Some(attr_paths) = parse_path(attr) {
                    paths.push(attr_paths);
                }
            }

            let mut expanded_nodes = Vec::new();

            for path in paths {
                expanded_nodes.push({
                    let mut processed =
                        process_paths_struct(&input_name, path, &x.fields, outer_scopes.clone());
                    // add scopes

                    if !outer_scopes.is_empty() {
                        processed = quote! {
                            #processed
                                .with_scopes(vec![#(#outer_scopes),*])
                        }
                    }

                    quote! { #processed; }
                });
            }

            Ok(TokenStream::from(quote! {

                impl valence::command::Command for #input_name {
                    fn assemble_graph(command_graph: &mut valence::command::graph::CommandGraphBuilder<Self>) {
                        use valence::command::parsers::CommandArg;
                        #(#expanded_nodes)*
                    }
                }
            }))
        }
        Data::Union(x) => Err(Error::new_spanned(
            x.union_token,
            "Command enum must be an enum, not a union",
        )),
    }
}

fn process_paths_enum(
    enum_name: &Ident,
    paths: Vec<(Vec<CommandArg>, bool)>,
    fields: &Fields,
    variant_ident: Ident,
    executables: bool,
) -> proc_macro2::TokenStream {
    let mut inner_expansion = quote! {};
    let mut first = true;

    for path in paths {
        if !first {
            inner_expansion = if executables && !path.1 {
                quote! {
                        #inner_expansion;

                        command_graph.at(command_root_node)
                }
            } else {
                quote! {
                    #inner_expansion;

                    command_graph.root()
                }
            };
        } else {
            inner_expansion = if executables && !path.1 {
                quote! {
                    command_graph.at(command_root_node)
                }
            } else {
                quote! {
                    command_graph.root()
                }
            };

            first = false;
        }

        let path = path.0;

        let mut final_executable = Vec::new();
        for (i, arg) in path.iter().enumerate() {
            match arg {
                CommandArg::Literal(lit) => {
                    inner_expansion = quote! {
                        #inner_expansion.literal(#lit)

                    };
                    if executables && i == path.len() - 1 {
                        inner_expansion = quote! {
                            #inner_expansion
                                .with_executable(|s| #enum_name::#variant_ident{#(#final_executable,)*})
                        };
                    }
                }
                CommandArg::Required(ident) => {
                    let field_type = &fields
                        .iter()
                        .find(|field| field.ident.as_ref().unwrap() == ident)
                        .expect("Required arg not found")
                        .ty;
                    let ident_string = ident.to_string();

                    inner_expansion = quote! {
                        #inner_expansion
                            .argument(#ident_string)
                            .with_parser::<#field_type>()
                    };

                    final_executable.push(quote! {
                        #ident: #field_type::parse_arg(s).unwrap()
                    });

                    if i == path.len() - 1 {
                        inner_expansion = quote! {
                            #inner_expansion
                                .with_executable(|s| {
                                    #enum_name::#variant_ident {
                                        #(#final_executable,)*
                                    }
                                })
                        };
                    }
                }
                CommandArg::Optional(ident) => {
                    let field_type = &fields
                        .iter()
                        .find(|field| field.ident.as_ref().unwrap() == ident)
                        .expect("Optional arg not found")
                        .ty;
                    let so_far_ident = format_ident!("graph_til_{}", ident);

                    // get what is inside the Option<...>
                    let option_inner = match field_type {
                        syn::Type::Path(ref type_path) => {
                            let path = &type_path.path;
                            if path.segments.len() != 1 {
                                return Error::new_spanned(
                                    path,
                                    "Option type must be a single path segment",
                                )
                                .into_compile_error();
                            }
                            let segment = &path.segments.first().unwrap();
                            if segment.ident != "Option" {
                                return Error::new_spanned(
                                    &segment.ident,
                                    "Option type must be a option",
                                )
                                .into_compile_error();
                            }
                            match &segment.arguments {
                                syn::PathArguments::AngleBracketed(ref angle_bracketed) => {
                                    if angle_bracketed.args.len() != 1 {
                                        return Error::new_spanned(
                                            angle_bracketed,
                                            "Option type must have a single generic argument",
                                        )
                                        .into_compile_error();
                                    }
                                    match angle_bracketed.args.first().unwrap() {
                                        syn::GenericArgument::Type(ref generic_type) => {
                                            generic_type
                                        }
                                        _ => {
                                            return Error::new_spanned(
                                                angle_bracketed,
                                                "Option type must have a single generic argument",
                                            )
                                            .into_compile_error();
                                        }
                                    }
                                }
                                _ => {
                                    return Error::new_spanned(
                                        segment,
                                        "Option type must have a single generic argument",
                                    )
                                    .into_compile_error();
                                }
                            }
                        }
                        _ => {
                            return Error::new_spanned(
                                field_type,
                                "Option type must be a single path segment",
                            )
                            .into_compile_error();
                        }
                    };

                    let ident_string = ident.to_string();

                    // find the ident of all following optional args
                    let mut next_optional_args = Vec::new();
                    for next_arg in path.iter().skip(i + 1) {
                        match next_arg {
                            CommandArg::Optional(ident) => next_optional_args.push(ident),
                            _ => {
                                return Error::new_spanned(
                                    variant_ident,
                                    "Only optional args can follow an optional arg",
                                )
                                .into_compile_error();
                            }
                        }
                    }

                    inner_expansion = quote! {
                        let #so_far_ident = {#inner_expansion
                            .with_executable(|s| {
                                #enum_name::#variant_ident {
                                    #(#final_executable,)*
                                    #ident: None,
                                    #(#next_optional_args: None,)*
                                }
                            })
                            .id()};

                        command_graph.at(#so_far_ident)
                            .argument(#ident_string)
                            .with_parser::<#option_inner>()
                    };

                    final_executable.push(quote! {
                        #ident: Some(#option_inner::parse_arg(s).unwrap())
                    });

                    if i == path.len() - 1 {
                        inner_expansion = quote! {
                            #inner_expansion
                                .with_executable(|s| {
                                    #enum_name::#variant_ident {
                                        #(#final_executable,)*
                                    }
                                })
                        };
                    }
                }
            }
        }
    }
    quote!(#inner_expansion)
}

fn process_paths_struct(
    struct_name: &Ident,
    paths: Vec<(Vec<CommandArg>, bool)>,
    fields: &Fields,
    outer_scopes: Vec<String>,
) -> proc_macro2::TokenStream {
    let mut inner_expansion = quote! {};
    let mut first = true;

    for path in paths {
        if !first {
            inner_expansion = quote! {
                #inner_expansion;

                command_graph.root()
            };
        } else {
            inner_expansion = quote! {
                command_graph.root()
            };

            first = false;
        }

        let path = path.0;

        let mut final_executable = Vec::new();
        let mut path_first = true;
        for (i, arg) in path.iter().enumerate() {
            match arg {
                CommandArg::Literal(lit) => {
                    inner_expansion = quote! {
                        #inner_expansion.literal(#lit)

                    };
                    if i == path.len() - 1 {
                        inner_expansion = quote! {
                            #inner_expansion
                                .with_executable(|s| #struct_name{#(#final_executable,)*})
                        };
                    }

                    if path_first {
                        inner_expansion = quote! {
                            #inner_expansion
                                .with_scopes(vec![#(#outer_scopes),*])
                        };
                        path_first = false;
                    }
                }
                CommandArg::Required(ident) => {
                    let field_type = &fields
                        .iter()
                        .find(|field| field.ident.as_ref().unwrap() == ident)
                        .expect("Required arg not found")
                        .ty;
                    let ident_string = ident.to_string();

                    inner_expansion = quote! {
                        #inner_expansion
                            .argument(#ident_string)
                            .with_parser::<#field_type>()
                    };

                    final_executable.push(quote! {
                        #ident: #field_type::parse_arg(s).unwrap()
                    });

                    if i == path.len() - 1 {
                        inner_expansion = quote! {
                            #inner_expansion
                                .with_executable(|s| {
                                    #struct_name {
                                        #(#final_executable,)*
                                    }
                                })
                        };
                    }

                    if path_first {
                        inner_expansion = quote! {
                            #inner_expansion
                                .with_scopes(vec![#(#outer_scopes),*])
                        };
                        path_first = false;
                    }
                }
                CommandArg::Optional(ident) => {
                    let field_type = &fields
                        .iter()
                        .find(|field| field.ident.as_ref().unwrap() == ident)
                        .expect("Optional arg not found")
                        .ty;
                    let so_far_ident = format_ident!("graph_til_{}", ident);

                    // get what is inside the Option<...>
                    let option_inner = match field_type {
                        syn::Type::Path(ref type_path) => {
                            let path = &type_path.path;
                            if path.segments.len() != 1 {
                                return Error::new_spanned(
                                    path,
                                    "Option type must be a single path segment",
                                )
                                .into_compile_error();
                            }
                            let segment = &path.segments.first().unwrap();
                            if segment.ident != "Option" {
                                return Error::new_spanned(
                                    &segment.ident,
                                    "Option type must be a option",
                                )
                                .into_compile_error();
                            }
                            match &segment.arguments {
                                syn::PathArguments::AngleBracketed(ref angle_bracketed) => {
                                    if angle_bracketed.args.len() != 1 {
                                        return Error::new_spanned(
                                            angle_bracketed,
                                            "Option type must have a single generic argument",
                                        )
                                        .into_compile_error();
                                    }
                                    match angle_bracketed.args.first().unwrap() {
                                        syn::GenericArgument::Type(ref generic_type) => {
                                            generic_type
                                        }
                                        _ => {
                                            return Error::new_spanned(
                                                angle_bracketed,
                                                "Option type must have a single generic argument",
                                            )
                                            .into_compile_error();
                                        }
                                    }
                                }
                                _ => {
                                    return Error::new_spanned(
                                        segment,
                                        "Option type must have a single generic argument",
                                    )
                                    .into_compile_error();
                                }
                            }
                        }
                        _ => {
                            return Error::new_spanned(
                                field_type,
                                "Option type must be a single path segment",
                            )
                            .into_compile_error();
                        }
                    };

                    let ident_string = ident.to_string();

                    // find the ident of all following optional args
                    let mut next_optional_args = Vec::new();
                    for next_arg in path.iter().skip(i + 1) {
                        match next_arg {
                            CommandArg::Optional(ident) => next_optional_args.push(ident),
                            _ => {
                                return Error::new_spanned(
                                    struct_name,
                                    "Only optional args can follow an optional arg",
                                )
                                .into_compile_error();
                            }
                        }
                    }

                    inner_expansion = quote! {
                        let #so_far_ident = {#inner_expansion
                            .with_executable(|s| {
                                #struct_name {
                                    #(#final_executable,)*
                                    #ident: None,
                                    #(#next_optional_args: None,)*
                                }
                            })
                            .id()};

                        command_graph.at(#so_far_ident)
                            .argument(#ident_string)
                            .with_parser::<#option_inner>()
                    };

                    final_executable.push(quote! {
                        #ident: Some(#option_inner::parse_arg(s).unwrap())
                    });

                    if i == path.len() - 1 {
                        inner_expansion = quote! {
                            #inner_expansion
                                .with_executable(|s| {
                                    #struct_name {
                                        #(#final_executable,)*
                                    }
                                })
                        };
                    }

                    if path_first {
                        inner_expansion = quote! {
                            #inner_expansion
                                .with_scopes(vec![#(#outer_scopes),*])
                        };
                        path_first = false;
                    }
                }
            }
        }
    }
    quote!(#inner_expansion)
}

#[derive(Debug)]
enum CommandArg {
    Required(Ident),
    Optional(Ident),
    Literal(String),
}

// example input: #[paths = "strawberry {0?}"]
// example output: [CommandArg::Literal("Strawberry"), CommandArg::Optional(0)]
fn parse_path(path: &Attribute) -> Option<Vec<(Vec<CommandArg>, bool)>> {
    let path_strings: Vec<String> = get_lit_list_attr(path, "paths")?;

    let mut paths = Vec::new();
    // we now have the path as a string eg "strawberry {0?}"
    // the first word is a literal
    // the next word is an optional arg with the index 0
    for path_str in path_strings {
        let mut args = Vec::new();
        let at_root = path_str.starts_with("{/}");

        for word in path_str
            .split_whitespace()
            .skip(if at_root { 1 } else { 0 })
        {
            if word.starts_with('{') && word.ends_with('}') {
                if word.ends_with("?}") {
                    args.push(CommandArg::Optional(format_ident!(
                        "{}",
                        word[1..word.len() - 2].to_string()
                    )));
                } else {
                    args.push(CommandArg::Required(format_ident!(
                        "{}",
                        word[1..word.len() - 1].to_string()
                    )));
                }
            } else {
                args.push(CommandArg::Literal(word.to_string()));
            }
        }
        paths.push((args, at_root));
    }

    Some(paths)
}

fn get_lit_list_attr(attr: &Attribute, ident: &str) -> Option<Vec<String>> {
    match attr.meta {
        Meta::NameValue(ref key_value) => {
            if !key_value.path.is_ident(ident) {
                return None;
            }

            match key_value.value {
                Expr::Lit(ref lit) => match lit.lit {
                    syn::Lit::Str(ref lit_str) => Some(vec![lit_str.value()]),
                    _ => None,
                },
                _ => None,
            }
        }
        Meta::List(ref list) => {
            if !list.path.is_ident(ident) {
                return None;
            }

            let mut path_strings = Vec::new();
            // parse as array with strings
            let mut comma_next = false;
            for token in list.tokens.clone() {
                match token {
                    TokenTree::Literal(lit) => {
                        if comma_next {
                            return None;
                        }
                        let lit_str = lit.to_string();
                        path_strings.push(
                            lit_str
                                .strip_prefix('"')
                                .unwrap()
                                .strip_suffix('"')
                                .unwrap()
                                .to_string(),
                        );
                        comma_next = true;
                    }
                    TokenTree::Punct(punct) => {
                        if punct.as_char() != ',' || !comma_next {
                            return None;
                        }
                        comma_next = false;
                    }
                    _ => return None,
                }
            }
            Some(path_strings)
        }
        _ => None,
    }
}