cmdr_macro 0.3.12

Macros for use with cmdr crate
Documentation
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
use itertools::Itertools;
use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{
    Attribute, AttributeArgs, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta, MetaList,
    MetaNameValue, NestedMeta, ReturnType, Type,
};

pub(crate) fn format_commands(input: &ItemImpl, meta: &AttributeArgs) -> TokenStream {
    let (help_text, help_command) = parse_cmdr_attributes(meta);
    let doc_help_text = parse_help_text(&input.attrs);

    let mut command_methods = parse_commands(&input);

    if let Some(command) = help_command {
        command_methods.insert(
            0,
            CmdAttributes {
                command: command.clone(),
                method: Ident::new("help", Span::call_site()),
                alias: vec![],
                help: None,
                arguments: vec![CmdArgument::Args],
            },
        )
    }
    let command_calls: Vec<_> = command_methods.iter().map(CmdAttributes::to_call).collect();

    let quoted_help = quote_string_option(&help_text.or(doc_help_text));

    quote!(
        fn commands(&self) -> ScopeDescription {
            ScopeDescription::new(
                #quoted_help,
                vec![#(#command_methods)*]
            )
        }

        fn run_command(&mut self, command: &ScopeCmdDescription, args: &[String], writer: &mut dyn LineWriter) -> CommandResult {
            match command.name() {
                #(#command_calls)*
                _ => Err(Error::InvalidCommand(command.name().to_string()))
            }
        }
    )
}

/// Parses the help text and help command from the cmdr attribute
fn parse_cmdr_attributes(meta: &AttributeArgs) -> (Option<String>, Option<String>) {
    let mut help_text = None;
    let mut help_command = Some("help".to_string());

    for meta_item in meta {
        match meta_item {
            NestedMeta::Meta(Meta::NameValue(MetaNameValue {
                path,
                lit: Lit::Str(lit),
                ..
            })) => {
                if path.is_ident("help") {
                    help_text = Some(lit.value());
                }
                if path.is_ident("help_command") & help_command.is_some() {
                    help_command = Some(lit.value());
                }
            }
            NestedMeta::Meta(Meta::Path(path)) => {
                if path.is_ident("nohelp") | path.is_ident("no_help") {
                    help_command = None
                }
            }
            _ => (),
        }
    }

    (help_text, help_command)
}

fn quote_string_option(value: &Option<String>) -> TokenStream {
    match value {
        Some(text) => quote!(Some(#text.to_string())),
        None => quote!(None),
    }
}

/// Parse attributes for several commands
fn parse_commands(input: &ItemImpl) -> Vec<CmdAttributes> {
    input
        .items
        .iter()
        .filter_map(parse_cmd_attributes)
        .collect()
}

/// Check if this method has the right signature to be a cmd, panics if it doesnt
fn parse_cmd_signature(method: &ImplItemMethod) -> Vec<CmdArgument> {
    let method_ident = method.sig.ident.to_owned();

    // Check method return type
    if let ReturnType::Type(_, tpy) = method.sig.output.clone() {
        if let Type::Path(tpy2) = tpy.as_ref() {
            if !tpy2
                .path
                .is_ident(&Ident::new("CommandResult", Span::call_site()))
            {
                panic!(format!(
                    "Wrong return type for command {}, should be CommandReult",
                    method_ident
                ));
            }
        }
    }

    // Get method parameters and check that they are the right type
    let ins: Vec<_> = method.sig.inputs.iter().collect();

    // Todo:
    //  - check if first argument is &self or &mut self
    //  - parse writer argument, should be reference, mutable, dyn and type Writer
    //  - parse arg slice
    //  - allow different argument order

    match ins.len() {
        2 => vec![CmdArgument::Args],
        3 => vec![CmdArgument::Writer, CmdArgument::Args],
        _ => panic!(format!(
            "Invalid signature for command {}, expected '&mut self, args &[String]'",
            method_ident
        )),
    }
}

/// Parse attributes for a single command
fn parse_cmd_attributes(item: &ImplItem) -> Option<CmdAttributes> {
    if let ImplItem::Method(method) = item {
        let attributes = &method.attrs;

        let cmd_attributes: Vec<Meta> = attributes
            .iter()
            .map(Attribute::parse_meta)
            .filter_map(Result::ok)
            .filter(|meta| meta.path().is_ident("cmd"))
            .collect();

        if !cmd_attributes.is_empty() {
            let method_ident = method.sig.ident.to_owned();

            let mut help_text = parse_help_text(attributes);
            let mut command_name = method_ident.to_string();
            let mut aliasses = Vec::new();

            // Parse cmd fields
            for meta in cmd_attributes {
                // Parse command name if it is different from method name
                // #[cmd(command_name)]
                if let Meta::List(MetaList { nested, .. }) = meta {
                    for nested_val in nested {
                        match nested_val {
                            NestedMeta::Meta(Meta::Path(ref path)) => {
                                if let Some(ident) = path.get_ident() {
                                    command_name = ident.to_string()
                                }
                            }
                            NestedMeta::Meta(Meta::NameValue(MetaNameValue {
                                path,
                                lit: Lit::Str(lit),
                                ..
                            })) => {
                                if path.is_ident("name") {
                                    command_name = lit.value();
                                } else if path.is_ident("help") {
                                    help_text = Some(lit.value());
                                }
                            }
                            NestedMeta::Meta(Meta::List(ref alias_list))
                                if alias_list.path.is_ident("alias") =>
                            {
                                for alias_item in &alias_list.nested {
                                    if let NestedMeta::Meta(Meta::Path(ref alias_path)) = alias_item
                                    {
                                        if let Some(alias_ident) = alias_path.get_ident() {
                                            aliasses.push(alias_ident.to_string());
                                        }
                                    }
                                    if let NestedMeta::Lit(Lit::Str(alias_lit)) = alias_item {
                                        aliasses.push(alias_lit.value());
                                    }
                                }
                            }
                            _ => (),
                        }
                    }
                }
            }

            Some(CmdAttributes {
                command: command_name,
                method: method_ident,
                alias: aliasses,
                help: help_text,
                arguments: parse_cmd_signature(method),
            })
        } else {
            // Method has no cmd attribute so is not a command
            None
        }
    } else {
        // Not a method
        None
    }
}

/// Parse documentation from attributes
fn parse_help_text(attrs: &Vec<Attribute>) -> Option<String> {
    let mut help_lines = attrs
        .iter()
        .map(Attribute::parse_meta)
        .filter_map(Result::ok)
        .filter(|meta| meta.path().is_ident("doc"))
        .filter_map(parse_doc_string)
        .peekable();

    if help_lines.peek().is_some() {
        Some(help_lines.join("\n"))
    } else {
        None
    }
}

fn parse_doc_string(meta: Meta) -> Option<String> {
    if let Meta::NameValue(name_val) = meta {
        if let syn::Lit::Str(string) = name_val.lit {
            Some(string.value().trim().to_owned())
        } else {
            None
        }
    } else {
        None
    }
}

/// Contains all metadata for a command
#[derive(Debug, PartialEq)]
struct CmdAttributes {
    command: String,
    method: Ident,
    alias: Vec<String>,
    help: Option<String>,
    arguments: Vec<CmdArgument>,
}

/// Single cmd method argument type
#[derive(Debug, PartialEq)]
enum CmdArgument {
    /// Writer argument
    Writer,

    /// Arguments slice
    Args,
}

impl CmdAttributes {
    pub(crate) fn to_call(&self) -> CmdCall {
        CmdCall {
            command: self.command.clone(),
            method: self.method.clone(),
        }
    }
}

impl ToTokens for CmdAttributes {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let command = &self.command;
        let help_text = quote_string_option(&self.help);
        let alias_list: Vec<TokenStream> = self
            .alias
            .iter()
            .map(|alias| quote!(#alias.to_string()))
            .collect();
        let alias_quote = quote!(vec![#(#alias_list),*]);

        tokens.extend(quote!(
            ScopeCmdDescription::new(
                #command.to_string(),
                #alias_quote,
                #help_text,
            ),
        ))
    }
}

/// Contains all metadata for generating a command call
#[derive(Debug, PartialEq)]
struct CmdCall {
    command: String,
    method: Ident,
}

impl ToTokens for CmdCall {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let command = &self.command;
        let method = &self.method;

        tokens.extend(quote!(
            #command => self.#method(args),
        ));
    }
}

#[cfg(test)]
mod when_parsing_function_cmd_attributes {
    use super::*;
    use syn::parse_str;

    #[test]
    fn should_ignore_method_without_cmd_attribute() {
        let parsed = parse_cmd_attributes(
            &parse_str(
                r###"
                fn method() {}
                "###,
            )
            .unwrap(),
        );

        assert_eq!(parsed, None);
    }

    #[test]
    fn should_parse_plain_cmd_attribute() {
        let parsed = parse_cmd_attributes(
            &parse_str(
                r###"
                #[cmd]
                fn method(&self, args: &[String]) {}
                "###,
            )
            .unwrap(),
        )
        .unwrap();

        assert_eq!(parsed.command, "method".to_string());
        assert_eq!(parsed.method.to_string(), "method".to_string());
    }

    #[test]
    fn should_parse_command_name() {
        let parsed = parse_cmd_attributes(
            &parse_str(
                r###"
                #[cmd(command)]
                fn method(&self, args: &[String]) {}
                "###,
            )
            .unwrap(),
        )
        .unwrap();

        assert_eq!(parsed.command, "command".to_string());
        assert_eq!(parsed.method.to_string(), "method".to_string());
    }

    #[test]
    fn should_parse_named_command_name() {
        let parsed = parse_cmd_attributes(
            &parse_str(
                r###"
                #[cmd(name="command")]
                fn method(&self, args: &[String]) {}
                "###,
            )
            .unwrap(),
        )
        .unwrap();

        assert_eq!(parsed.command, "command".to_string());
        assert_eq!(parsed.method.to_string(), "method".to_string());
    }

    #[test]
    fn should_parse_name_from_multiple_cmd_attributes() {
        let parsed = parse_cmd_attributes(
            &parse_str(
                r###"
                #[cmd]
                #[cmd(command)]
                fn method(&self, args: &[String]) {}
                "###,
            )
            .unwrap(),
        )
        .unwrap();

        assert_eq!(parsed.command, "command".to_string());
        assert_eq!(parsed.method.to_string(), "method".to_string());
    }

    #[test]
    fn should_parse_outer_doc_string_as_help_text() {
        let parsed = parse_cmd_attributes(
            &parse_str(
                r###"
                #[cmd]
                ///Help text
                fn method(&self, args: &[String]) {}
                "###,
            )
            .unwrap(),
        )
        .unwrap();
        assert_eq!(parsed.help.unwrap(), "Help text".to_string());
    }

    #[test]
    fn should_parse_inner_doc_string_as_help_text() {
        let parsed = parse_cmd_attributes(
            &parse_str(
                r###"
                #[cmd]
                fn method(&self, args: &[String]) {
                    //!Help text
                }
                "###,
            )
            .unwrap(),
        )
        .unwrap();

        assert_eq!(parsed.help.unwrap(), "Help text".to_string());
    }

    #[test]
    fn should_strip_help_text_spaces() {
        let parsed = parse_cmd_attributes(
            &parse_str(
                r###"
                #[cmd]
                ///     Help text
                fn method(&self, args: &[String]) {}
                "###,
            )
            .unwrap(),
        )
        .unwrap();

        assert_eq!(parsed.help.unwrap(), "Help text".to_string());
    }

    #[test]
    fn should_ignore_docstring_if_cmd_attribute_help_available() {
        let parsed = parse_cmd_attributes(
            &parse_str(
                r###"
                #[cmd(name, help="Help text from the cmd attribute")]
                /// This is a docstring, not help text
                fn method(&self, args: &[String]) {}
                "###,
            )
            .unwrap(),
        )
        .unwrap();

        assert_eq!(
            parsed.help.unwrap(),
            "Help text from the cmd attribute".to_string()
        )
    }

    #[test]
    fn should_parse_multiline_help_from_cmd_attribute() {
        let parsed = parse_cmd_attributes(
            &parse_str(
                r###"
                #[cmd(name, help="Multiline help text\nFrom the cmd attribute")]
                fn method(&self, args: &[String]) {}
                "###,
            )
            .unwrap(),
        )
        .unwrap();

        assert_eq!(
            parsed.help.unwrap(),
            "Multiline help text\nFrom the cmd attribute".to_string()
        )
    }

    #[test]
    fn should_set_missing_help_text_to_none() {
        let parsed = parse_cmd_attributes(
            &parse_str(
                r###"
                #[cmd(name)]
                fn method(&self, args: &[String]) {}
                "###,
            )
            .unwrap(),
        )
        .unwrap();

        assert_eq!(parsed.help, None)
    }

    #[test]
    fn should_parse_alias_from_cmd_attribute() {
        let parsed = parse_cmd_attributes(
            &parse_str(
                r###"
                #[cmd(name, alias("one", "two", three))]
                fn method(&self, args: &[String]) {}
                "###,
            )
            .unwrap(),
        )
        .unwrap();

        assert_eq!(parsed.alias, vec!["one", "two", "three"]);
    }
}