onlyargs_derive 0.2.0

Obsessively tiny argument parsing derive macro
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
520
521
522
523
524
525
526
527
528
529
530
531
532
//! Derive macro for [`onlyargs`](https://docs.rs/onlyargs).
//!
//! The parser generated by this macro is very opinionated. The implementation attempts to be as
//! light as possible while also being usable for most applications.
//!
//! # Example
//!
//! ```
//! use onlyargs_derive::OnlyArgs;
//!
//! /// Doc comments will appear in your application's help text.
//! ///
//! /// Features:
//! ///   - Supports multi-line strings.
//! ///   - Supports indentation.
//! #[derive(Debug, OnlyArgs)]
//! #[footer = "Footer attributes will be included at the bottom of the help message."]
//! #[footer = ""]
//! #[footer = "Features:"]
//! #[footer = "  - Also supports multi-line strings."]
//! #[footer = "  - Also supports indentation."]
//! struct Args {
//!     /// Optional output path.
//!     output: Option<std::path::PathBuf>,
//!
//!     /// Enable verbose output.
//!     verbose: bool,
//! }
//!
//! let args: Args = onlyargs::parse()?;
//!
//! if let Some(output) = args.output {
//!     if args.verbose {
//!         eprintln!("Creating file: `{path}`", path = output.display());
//!     }
//!
//!     // Do something with `output`...
//! }
//! # Ok::<_, onlyargs::CliError>(())
//! ```
//!
//! # DSL reference
//!
//! Only structs with named fields are supported. Doc comments are used for the generated help text.
//! Argument names are generated automatically from field names with only a few rules:
//!
//! - Long argument names start with `--`, ASCII alphabetic characters are made lowercase, and all
//!   `_` characters are replaced with `-`.
//! - Short argument names use the first ASCII alphabetic character of the field name following a
//!   `-`. Short arguments are not allowed to be duplicated.
//!   - This behavior can be suppressed with the `#[long]` attribute (see below).
//!   - Alternatively, the `#[short('…')]` attribute can be used to set a specific short name.
//!
//! # Footer
//!
//! The `#[footer = "..."]` attribute on the argument struct will add lines to the bottom of the
//! help message. It can be used multiple times.
//!
//! # Provided arguments
//!
//! `--help|-h` and `--version|-V` arguments are automatically generated. When the parser encounters
//! either, it will print the help or version message and exit the application with exit code 0.
//!
//! # Field attributes
//!
//! Parsing options are configurable with the following attributes:
//!
//! - `#[long]`: Only generate long argument names like `--help`. Short args like `-h` are generated
//!   by default, and this attribute suppresses that behavior.
//! - `#[short('N')]`: Generate a short argument name with the given character. In this example, it
//!   will be `-N`.
//!   - If `#[long]` and `#[short]` are used together, `#[long]` takes precedence.
//! - `#[default(T)]`: Specify a default value for an argument. Where `T` is a literal value.
//!   - Accepts string literals for `PathBuf`.
//!   - Accepts numeric literals for numeric types.
//!   - Accepts `true` and `false` idents and `"true"` and `"false"` string literals for `boolean`.
//! - `#[required]`: Can be used on `Vec<T>` to require at least one value. This ensures the vector
//!   is never empty.
//! - `#[positional]`: Makes a `Vec<T>` the dumping ground for positional arguments.
//!
//! # Supported types
//!
//! Here is the list of supported field "primitive" types:
//!
//! | Type             | Description                                      |
//! |------------------|--------------------------------------------------|
//! | `bool`           | Defines a flag.                                  |
//! | `f32`\|`f64`     | Floating point number option.                    |
//! | `i8`\|`u8`       | 8-bit integer option.                            |
//! | `i16`\|`u16`     | 16-bit integer option.                           |
//! | `i32`\|`u32`     | 32-bit integer option.                           |
//! | `i64`\|`u64`     | 64-bit integer option.                           |
//! | `i128`\|`u128`   | 128-bit integer option.                          |
//! | `isize`\|`usize` | Pointer-sized integer option.                    |
//! | `OsString`       | A string option with platform-specific encoding. |
//! | `PathBuf`        | A file system path option.                       |
//! | `String`         | UTF-8 encoded string option.                     |
//!
//! Additionally, some wrapper and composite types are also available, where the type `T` must be
//! one of the primitive types listed above (except `bool`).
//!
//! | Type        | Description                                                |
//! |-------------|------------------------------------------------------------|
//! | `Option<T>` | An optional argument.                                      |
//! | `Vec<T>`    | Multivalue and positional arguments (see `#[positional]`). |
//!
//! In argument parsing parlance, "flags" are simple boolean values; the argument does not require
//! a value. For example, the argument `--help`.
//!
//! "Options" carry a value and the argument parser requires the value to directly follow the
//! argument name. Arguments can be made optional with `Option<T>`.
//!
//! Multivalue arguments can be passed on the command line by using the same argument multiple
//! times.

#![forbid(unsafe_code)]
#![deny(clippy::all)]
#![deny(clippy::pedantic)]
#![allow(clippy::let_underscore_untyped)]

use crate::parser::{ArgFlag, ArgOption, ArgProperty, ArgType, ArgView, ArgumentStruct};
use myn::utils::spanned_error;
use proc_macro::{Ident, Span, TokenStream};
use std::{collections::HashMap, fmt::Write as _, str::FromStr as _};

mod parser;

/// See the [root module documentation](crate) for the DSL specification.
#[allow(clippy::too_many_lines)]
#[proc_macro_derive(
    OnlyArgs,
    attributes(footer, default, long, positional, required, short)
)]
pub fn derive_parser(input: TokenStream) -> TokenStream {
    let ast = match ArgumentStruct::parse(input) {
        Ok(ast) => ast,
        Err(err) => return err,
    };

    let mut flags = vec![
        ArgFlag::new_priv(
            Ident::new("help", Span::call_site()),
            Some('h'),
            vec!["Show this help message.".to_string()],
        ),
        ArgFlag::new_priv(
            Ident::new("version", Span::call_site()),
            Some('V'),
            vec!["Show the application version.".to_string()],
        ),
    ];
    flags.extend(ast.flags);

    // De-dupe short args.
    let mut dupes = HashMap::new();
    for flag in &flags {
        if let Err(err) = dedupe(&mut dupes, flag.as_view()) {
            return err;
        }
    }
    for opt in &ast.options {
        if let Err(err) = dedupe(&mut dupes, opt.as_view()) {
            return err;
        }
    }

    // Produce help text for all arguments.
    let max_width = get_max_width(flags.iter().map(ArgFlag::as_view));
    let flags_help = flags
        .iter()
        .map(|arg| to_help(arg.as_view(), max_width))
        .collect::<String>();

    let max_width = get_max_width(ast.options.iter().map(ArgOption::as_view));
    let options_help = ast
        .options
        .iter()
        .map(|arg| to_help(arg.as_view(), max_width))
        .collect::<String>();

    let positional_header = ast
        .positional
        .as_ref()
        .map(|opt| format!(" [{}...]", opt.name))
        .unwrap_or_default();
    let positional_help = ast
        .positional
        .as_ref()
        .map(|opt| format!("\n{}:\n  {}\n", opt.name, opt.doc.join("\n  ")))
        .unwrap_or_default();

    // Produce variables for argument parser state.
    let flags_vars =
        flags
            .iter()
            .filter(|&flag| flag.output)
            .fold(String::new(), |mut flags, flag| {
                write!(
                    flags,
                    "let mut {name} = {default:?};",
                    name = flag.name,
                    default = flag.default,
                )
                .unwrap();
                flags
            });
    let options_vars = ast
        .options
        .iter()
        .map(|opt| {
            let name = &opt.name;
            if let Some(default) = opt.default.as_ref() {
                format!("let mut {name} = {default}{};", opt.ty_help.converter())
            } else {
                match opt.property {
                    ArgProperty::Optional | ArgProperty::Required => {
                        format!("let mut {name} = None;")
                    }
                    ArgProperty::MultiValue { .. } => {
                        format!("let mut {name} = vec![];")
                    }
                    ArgProperty::Positional { .. } => unreachable!(),
                }
            }
        })
        .collect::<String>();
    let positional_var = ast
        .positional
        .as_ref()
        .map(|opt| {
            let name = &opt.name;
            format!("let mut {name} = vec![];")
        })
        .unwrap_or_default();

    // Produce matchers for parser.
    let flags_matchers =
        flags
            .iter()
            .filter(|&flag| flag.output)
            .fold(String::new(), |mut matchers, flag| {
                let name = &flag.name;
                let short = flag
                    .short
                    .map(|ch| format!(r#"| Some("-{ch}")"#))
                    .unwrap_or_default();

                write!(
                    matchers,
                    r#"Some("--{arg}") {short} => {name} = true,"#,
                    arg = to_arg_name(name)
                )
                .unwrap();
                matchers
            });
    let options_matchers = ast.options.iter().fold(String::new(), |mut matchers, opt| {
        let name = &opt.name;
        let short = opt
            .short
            .map(|ch| format!(r#"| Some(arg_name_ @ "-{ch}")"#))
            .unwrap_or_default();
        let assignment = if opt.default.is_some() {
            match opt.ty_help {
                ArgType::Float => format!("{name} = args.next().parse_float(arg_name_)?"),
                ArgType::Integer => format!("{name} = args.next().parse_int(arg_name_)?"),
                ArgType::OsString => format!("{name} = args.next().parse_osstr(arg_name_)?"),
                ArgType::Path => format!("{name} = args.next().parse_path(arg_name_)?"),
                ArgType::String => format!("{name} = args.next().parse_str(arg_name_)?"),
            }
        } else {
            match opt.property {
                ArgProperty::Optional | ArgProperty::Required => match opt.ty_help {
                    ArgType::Float => format!("{name} = Some(args.next().parse_float(arg_name_)?)"),
                    ArgType::Integer => format!("{name} = Some(args.next().parse_int(arg_name_)?)"),
                    ArgType::OsString => {
                        format!("{name} = Some(args.next().parse_osstr(arg_name_)?)")
                    }
                    ArgType::Path => format!("{name} = Some(args.next().parse_path(arg_name_)?)"),
                    ArgType::String => format!("{name} = Some(args.next().parse_str(arg_name_)?)"),
                },
                ArgProperty::MultiValue { .. } => match opt.ty_help {
                    ArgType::Float => format!("{name}.push(args.next().parse_float(arg_name_)?)"),
                    ArgType::Integer => format!("{name}.push(args.next().parse_int(arg_name_)?)"),
                    ArgType::OsString => {
                        format!("{name}.push(args.next().parse_osstr(arg_name_)?)")
                    }
                    ArgType::Path => format!("{name}.push(args.next().parse_path(arg_name_)?)"),
                    ArgType::String => format!("{name}.push(args.next().parse_str(arg_name_)?)"),
                },
                ArgProperty::Positional { .. } => unreachable!(),
            }
        };

        write!(
            matchers,
            r#"Some(arg_name_ @ "--{arg}") {short} => {assignment},"#,
            arg = to_arg_name(name)
        )
        .unwrap();
        matchers
    });
    let positional_matcher = match ast.positional.as_ref() {
        Some(opt) => {
            let name = &opt.name;
            let value = match opt.ty_help {
                ArgType::Float => r#"arg.parse_float("<POSITIONAL>")?"#,
                ArgType::Integer => r#"arg.parse_int("<POSITIONAL>")?"#,
                ArgType::OsString => r#"arg.parse_osstr("<POSITIONAL>")?"#,
                ArgType::Path => r#"arg.parse_path("<POSITIONAL>")?"#,
                ArgType::String => r#"arg.parse_str("<POSITIONAL>")?"#,
            };

            format!(
                r#"
                    Some("--") => {{
                        for arg in args {{
                            {name}.push({value});
                        }}
                        break;
                    }}
                    _ => {name}.push({value}),
                "#
            )
        }
        None => r#"
            Some("--") => break,
            _ => return Err(::onlyargs::CliError::Unknown(arg)),
        "#
        .to_string(),
    };

    // Produce identifiers for args constructor.
    let flags_idents = flags
        .iter()
        .filter_map(|flag| flag.output.then_some(format!("{},", flag.name)))
        .collect::<String>();
    let options_idents = ast
        .options
        .iter()
        .map(|opt| {
            let name = &opt.name;
            let optional = matches!(
                opt.property,
                ArgProperty::Optional
                    | ArgProperty::Positional { required: false }
                    | ArgProperty::MultiValue { required: false }
            );
            if opt.default.is_some() || optional {
                format!("{name},")
            } else {
                format!(
                    r#"{name}: {name}.required("--{arg}")?,"#,
                    arg = to_arg_name(name)
                )
            }
        })
        .collect::<String>();
    let positional_ident = ast
        .positional
        .map(|opt| {
            if matches!(opt.property, ArgProperty::Positional { required: true }) {
                format!(
                    r#"{}: {}.required("{arg}")?,"#,
                    opt.name,
                    opt.name,
                    arg = to_arg_name(&opt.name),
                )
            } else {
                format!("{},", opt.name)
            }
        })
        .unwrap_or_default();

    let name = ast.name;
    let doc_comment = if ast.doc.is_empty() {
        String::new()
    } else {
        format!("\n{}\n", ast.doc.join("\n"))
    };
    let footer = if ast.footer.is_empty() {
        String::new()
    } else {
        format!("\n{}\n", ast.footer.join("\n"))
    };
    let bin_name = std::env::var_os("CARGO_BIN_NAME").and_then(|name| name.into_string().ok());
    let help_impl = if bin_name.is_none() {
        r#"fn help() -> ! {
            let bin_name = ::std::env::args_os()
                .next()
                .unwrap_or_default()
                .to_string_lossy()
                .into_owned();
            ::std::eprintln!("{}", Self::HELP.replace("{bin_name}", &bin_name));
            ::std::process::exit(0);
        }"#
    } else {
        ""
    };
    let bin_name = bin_name.unwrap_or_else(|| "{bin_name}".to_string());

    // Produce final code.
    let code = TokenStream::from_str(&format!(
        r#"
            impl ::onlyargs::OnlyArgs for {name} {{
                const HELP: &'static str = ::std::concat!(
                    env!("CARGO_PKG_NAME"),
                    " v",
                    env!("CARGO_PKG_VERSION"),
                    "\n",
                    env!("CARGO_PKG_DESCRIPTION"),
                    "\n",
                    {doc_comment:?},
                    "\nUsage:\n  ",
                    {bin_name:?},
                    " [flags] [options]",
                    {positional_header:?},
                    "\n\nFlags:\n",
                    {flags_help:?},
                    "\nOptions:\n",
                    {options_help:?},
                    {positional_help:?},
                    {footer:?},
                );

                const VERSION: &'static str = concat!(
                    env!("CARGO_PKG_NAME"),
                    " v",
                    env!("CARGO_PKG_VERSION"),
                    "\n",
                );

                {help_impl}

                fn parse(args: Vec<::std::ffi::OsString>) ->
                    ::std::result::Result<Self, ::onlyargs::CliError>
                {{
                    use ::onlyargs::traits::*;
                    use ::std::option::Option::{{None, Some}};
                    use ::std::result::Result::{{Err, Ok}};

                    {flags_vars}
                    {options_vars}
                    {positional_var}

                    let mut args = args.into_iter();
                    while let Some(arg) = args.next() {{
                        match arg.to_str() {{
                            // TODO: Add an attribute to disable help/version.
                            Some("--help") | Some("-h") => Self::help(),
                            Some("--version") | Some("-V") => Self::version(),
                            {flags_matchers}
                            {options_matchers}
                            {positional_matcher}
                        }}
                    }}

                    Ok(Self {{
                        {flags_idents}
                        {options_idents}
                        {positional_ident}
                    }})
                }}
            }}
        "#
    ));

    match code {
        Ok(stream) => stream,
        Err(err) => spanned_error(err.to_string(), Span::call_site()),
    }
}

// 1 hyphen + 1 char + 1 trailing space.
const SHORT_PAD: usize = 3;
// 2 leading spaces + 2 hyphens + 2 trailing spaces.
const LONG_PAD: usize = 6;

fn to_arg_name(ident: &Ident) -> String {
    let mut name = ident.to_string().replace('_', "-");
    name.make_ascii_lowercase();

    name
}

fn to_help(view: ArgView, max_width: usize) -> String {
    let name = to_arg_name(view.name);
    let ty = match view.ty_help.as_ref() {
        Some(ty_help) => ty_help.as_str(),
        None => "",
    };
    let pad = " ".repeat(max_width + LONG_PAD);
    let help = view.doc.join(&format!("\n{pad}"));

    let width = max_width - name.len();
    if let Some(ch) = view.short {
        let width = width - SHORT_PAD;

        format!("  -{ch} --{name}{ty:<width$}  {help}\n")
    } else {
        format!("  --{name}{ty:<width$}  {help}\n")
    }
}

fn get_max_width<'a, I>(iter: I) -> usize
where
    I: Iterator<Item = ArgView<'a>>,
{
    iter.fold(0, |acc, view| {
        let short = view.short.map(|_| SHORT_PAD).unwrap_or_default();
        let ty = match view.ty_help.as_ref() {
            Some(ty_help) => ty_help.as_str(),
            None => "",
        };

        acc.max(view.name.to_string().len() + ty.len() + short)
    })
}

fn dedupe<'a>(dupes: &mut HashMap<char, &'a Ident>, arg: ArgView<'a>) -> Result<(), TokenStream> {
    if let Some(ch) = arg.short {
        if let Some(other) = dupes.get(&ch) {
            let msg =
                format!("Only one short arg is allowed. `-{ch}` also used on field `{other}`");

            return Err(spanned_error(msg, arg.name.span()));
        }

        dupes.insert(ch, arg.name);
    }

    Ok(())
}