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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! [![Documentation](https://docs.rs/argwerk/badge.svg)](https://docs.rs/argwerk)
//! [![Crates](https://img.shields.io/crates/v/argwerk.svg)](https://crates.io/crates/argwerk)
//! [![Actions Status](https://github.com/udoprog/argwerk/workflows/Rust/badge.svg)](https://github.com/udoprog/argwerk/actions)
//!
//! Helper utility for parsing simple commandline arguments.
//!
//! This is **not** intended to be a complete commandline parser library.
//! Instead this can be used as an alternative quick-and-dirty approach that can
//! be cheaply incorporated into a tool.
//!
//! We provide:
//! * A dependency-free commandline parsing framework using declarative macros.
//!   So it's hopefully lightweight and compiles quickly.
//! * A flexible mechanism for parsing.
//! * Formatting decent looking help messages.
//!
//! We specifically do not support:
//! * As-close-to correct line wrapping with wide unicode characters as possible
//!   (see [textwrap]).
//! * Required arguments. If your argument is required, you'll have to
//!   [ok_or_else] it yourself from an `Option<T>`.
//! * Complex command structures like subcommands.
//!
//! For a more complete commandline parsing library, use [clap].
//!
//! See the documentation for [argwerk::parse!] for how to use.
//!
//! # Examples
//!
//! > This is available as a runnable example:
//! > ```sh
//! > cargo run --example tour
//! > ```
//!
//! ```rust
//! # fn main() -> Result<(), argwerk::Error> {
//! let args = argwerk::parse! {
//!     /// A command touring the capabilities of argwerk.
//!     "tour [-h]" {
//!         help: bool,
//!         file: Option<String>,
//!         input: Option<String>,
//!         limit: usize = 42,
//!         positional: Option<(String, Option<String>)>,
//!         rest: Vec<String>,
//!     }
//!     /// Prints the help.
//!     ///
//!     /// This includes:
//!     ///    * All the available switches.
//!     ///    * All the available positional arguments.
//!     ///    * Whatever else the developer decided to put in here! We even support wrapping comments which are overly long.
//!     "-h" | "--help" => {
//!         help = true;
//!         print_help();
//!         Ok(())
//!     }
//!     /// Limit the number of things by <n>.
//!     "--limit" | "-l", n => {
//!         limit = str::parse(&n)?;
//!         Ok(())
//!     }
//!     /// Write to the file specified by <path>.
//!     "--file", path if !file.is_some() => {
//!         file = Some(path);
//!         Ok(())
//!     }
//!     /// Read from the specified input.
//!     "--input", #[option] path => {
//!         input = path;
//!         Ok(())
//!     }
//!     /// Takes argument at <foo> and <bar>.
//!     ///
//!     ///    * This is an indented message. The first alphanumeric character determines the indentation to use.
//!     (foo, #[option] bar, #[rest] args) if positional.is_none() => {
//!         positional = Some((foo, bar));
//!         rest = args;
//!         Ok(())
//!     }
//! }?;
//!
//! dbg!(args);
//! # Ok(()) }
//! ```
//!
//! [ok_or_else]: https://doc.rust-lang.org/std/option/enum.Option.html#method.ok_or_else
//! [textwrap]: https://docs.rs/textwrap/0.13.2/textwrap/#displayed-width-vs-byte-size
//! [argwerk::parse!]: https://docs.rs/argwerk/0/argwerk/macro.parse.html
//! [clap]: https://docs.rs/clap

#![deny(missing_docs)]

use std::fmt;

#[doc(hidden)]
/// Macro helpers. Not intended for public use!
pub mod helpers;

use std::error;

/// An error raised by argwerk.
#[derive(Debug)]
pub struct Error {
    kind: Box<ErrorKind>,
}

impl Error {
    /// Construct a new error with the given kind.
    pub fn new(kind: ErrorKind) -> Self {
        Self {
            kind: Box::new(kind),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind.as_ref() {
            ErrorKind::MissingParameter { argument, name } => {
                write!(
                    f,
                    "missing parameter to argument `{}`: <{}>",
                    argument, name
                )
            }
            ErrorKind::MissingPositional { name } => {
                write!(f, "missing positional parameter <{}>", name)
            }
            ErrorKind::Unsupported { argument } => {
                write!(f, "unsupported argument `{}`", argument)
            }
            ErrorKind::Error { argument, error } => {
                write!(f, "bad argument `{}`: {}", argument, error)
            }
        }
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self.kind.as_ref() {
            ErrorKind::Error { error, .. } => Some(error.as_ref()),
            _ => None,
        }
    }
}

/// The kind of an error.
#[derive(Debug)]
pub enum ErrorKind {
    /// An argument that is unsupported.
    Unsupported {
        /// An unsupported argument.
        argument: Box<str>,
    },
    /// When a parameter to an argument is missing.
    MissingParameter {
        /// The argument where the named argument was missing, like `--file` in
        /// `--file <path>`.
        argument: Box<str>,
        /// The parameter that was missing, like `path` in `--file <path>`.
        name: &'static str,
    },
    /// When a positional parameter is missing.
    MissingPositional {
        /// The parameter that was missing, like `path` in `<path>`.
        name: &'static str,
    },
    /// When an error has been raised while processing an argument, typically
    /// when something is being parsed.
    Error {
        /// The argument that could not be parsed.
        argument: Box<str>,
        /// The error that caused the parsing error.
        error: Box<dyn error::Error + Send + Sync + 'static>,
    },
}

/// Parse commandline arguments.
///
/// This will generate an anonymous structure containing the arguments defined
/// which is returned by the macro.
///
/// Each branch is executed when an incoming argument matches and must return a
/// [Result], like `Ok(())`. Error raised in the branch will cause a
/// [ErrorKind::Error] error to be raised associated with that argument
/// with the relevant error attached.
///
/// This also generated two helper functions available in the parse branches:
/// * `write_help` - Which can write help to something implementing
///   [std::io::Write].
/// * `print_help` - Which will write the help string to [std::io::stdout].
///
/// The [parse] macro can be invoked in two ways.
///
/// Using `std::env::args()` to get arguments from the environment:
///
/// ```rust
/// # fn main() -> Result<(), argwerk::Error> {
/// let args = argwerk::parse! {
///     /// A simple test command.
///     "command [-h]" {
///         help: bool,
///         limit: usize = 10,
///     }
/// }?;
/// # Ok(()) }
/// ```
///
/// Or explicitly specifying an iterator to use with `<iter> => <config>`. This
/// works with anything that implements `AsRef<str>`:
///
/// ```rust
/// # fn main() -> Result<(), argwerk::Error> {
/// let args = argwerk::parse! {
///     vec!["foo", "bar", "baz"] =>
///     /// A simple test command.
///     "command [-h]" {
///         help: bool,
///         limit: usize = 10,
///         positional: Option<(&'static str, &'static str, &'static str)>,
///     }
///     (a, b, c) => {
///         positional = Some((a, b, c));
///         Ok(())
///     }
/// }?;
///
/// assert_eq!(args.positional, Some(("foo", "bar", "baz")));
/// # Ok(()) }
/// ```
///
/// ## Arguments structure
///
/// The first part of the [parse] macro defines the state available to the
/// parser. These are field-like declarations which can specify a default value.
/// This is the only required component of the macro.
///
/// Fields which do not specify an initialization value will be initialized
/// through [Default::default].
///
/// ```rust
/// # fn main() -> Result<(), argwerk::Error> {
/// let args = argwerk::parse! {
///     /// A simple test command.
///     "command [-h]" {
///         help: bool,
///         limit: usize = 10,
///     }
/// }?;
///
/// assert_eq!(args.help, false);
/// assert_eq!(args.limit, 10);
/// # Ok(()) }
/// ```
///
/// ## Argument branches
///
/// The basic form of an argument branch is:
///
/// ```rust
/// # fn main() -> Result<(), argwerk::Error> {
/// let args = argwerk::parse! {
///     vec![String::from("-h")] =>
///     /// A simple test command.
///     "command [-h]" {
///         help: bool,
///     }
///     /// Print the help.
///     "-h" | "--help" => {
///         help = true;
///         print_help();
///         Ok(())
///     }
/// }?;
///
/// assert_eq!(args.help, true);
/// # Ok(()) }
/// ```
///
/// ## Documentation
///
/// You specify documentation for argument branches with doc comments. These are
/// automatically wrapped to 80 characters and pretty printed.
///
/// ```rust
/// # fn main() -> Result<(), argwerk::Error> {
/// let args = argwerk::parse! {
///     vec![String::from("-h")] =>
///     /// A simple test command.
///     "command [-h]" {
///         help: bool,
///     }
///     /// Prints the help.
///     ///
///     /// This includes:
///     ///    * All the available switches.
///     ///    * All the available positional arguments.
///     ///    * Whatever else the developer decided to put in here! We even support wrapping comments which are overly long.
///     "-h" | "--help" => {
///         help = true;
///         print_help();
///         Ok(())
///     }
/// }?;
///
/// # Ok(()) }
/// ```
///
/// This would print:
///
/// ```text
/// Usage: command [-h]
/// A simple test command.
///
/// This is nice!
///
/// Options:
///   -h, --help  Prints the help.
///
///               This includes:
///                  * All the available switches.
///                  * All the available positional arguments.
///                  * Whatever else the developer decided to put in here! We even
///                    support wrapping comments which are overly long.
/// ```
///
/// We determine the initial indentation level from the first doc comment. Above
/// this would be "Prints the help.".
///
/// When we wrap individual lines, we determine the indentation level to use by
/// finding the first alphanumerical character on the previous line. This is why
/// the "overly long comment" above wraps correctly in the markdown list.
///
/// ## Parse all available arguments with `#[rest]`
///
/// You can write a branch that receives the rest of the arguments using the
/// `#[rest]` attribute.
///
/// ```rust
/// # fn main() -> Result<(), argwerk::Error> {
/// let args = argwerk::parse! {
///     vec![String::from("foo"), String::from("bar"), String::from("baz")] =>
///     /// A simple test command.
///     "command [-h]" {
///         rest: Vec<String>,
///     }
///     #[rest] args => {
///         rest = args;
///         Ok(())
///     }
/// }?;
///
/// assert_eq!(args.rest, &["foo", "bar", "baz"]);
/// # Ok(()) }
/// ```
///
/// ## Parse optional arguments with `#[option]`
///
/// Switches and positional arguments can be marked with the `#[option]`
/// attribute. This will cause the argument to take a value of type
/// `Option<I::Item>`.
///
/// An optional argument parses to `None` if:
/// * There are no more arguments to parse.
/// * The argument is a switch (starts with `-`).
///
/// ```rust
/// # fn main() -> Result<(), argwerk::Error> {
/// let parser = |iter: &[&str]| argwerk::parse! {
///     iter.iter().copied().map(String::from) =>
///     /// A simple test command.
///     "command [-h]" {
///         foo: Option<String>,
///         bar: bool,
///     }
///     /// A switch taking an optional argument.
///     "--foo", #[option] arg => {
///         foo = arg;
///         Ok(())
///     }
///     "--bar" => {
///         bar = true;
///         Ok(())
///     }
/// };
///
/// // Argument exists, but looks like a switch.
/// let args = parser(&["--foo", "--bar"])?;
/// assert_eq!(args.foo.as_deref(), None);
/// assert!(args.bar);
///
/// // Argument does not exist.
/// let args = parser(&["--foo"])?;
/// assert_eq!(args.foo.as_deref(), None);
/// assert!(!args.bar);
///
/// let args = parser(&["--foo", "bar"])?;
/// assert_eq!(args.foo.as_deref(), Some("bar"));
/// assert!(!args.bar);
/// # Ok(()) }
/// ```
///
/// ## Parse positional arguments
///
/// Positional arguments are parsed by specifying a tuple in the match branch.
///
/// Positional arguments support the following attributes:
/// * `#[option]` - which will cause the argument to be optionally parsed into
///   an `Option<I::Item>`.
/// * `#[rest]` - which will parse the rest of the arguments.
///
/// The following is a basic example without attributes. Both `foo` and `bar`
/// are required if the branch matches.
///
/// ```rust
/// # fn main() -> Result<(), argwerk::Error> {
/// let args = argwerk::parse! {
///     ["a", "b"].iter().copied().map(String::from) =>
///     /// A simple test command.
///     "command [-h]" {
///         positional: Option<(String, String)>,
///     }
///     /// Takes argument at <foo> and <bar>.
///     (foo, bar) if positional.is_none() => {
///         positional = Some((foo, bar));
///         Ok(())
///     }
/// }?;
///
/// assert_eq!(args.positional, Some((String::from("a"), String::from("b"))));
/// # Ok(()) }
/// ```
///
/// The following showcases positional parameters using `#[option]` and
/// `#[rest]`.
///
/// ```rust
/// # fn main() -> Result<(), argwerk::Error> {
/// let args = argwerk::parse! {
///     ["foo", "bar", "baz"].iter().copied().map(String::from) =>
///     /// A simple test command.
///     "command [-h]" {
///         first: String,
///         second: Option<String>,
///         rest: Vec<String>,
///     }
///     (a, #[option] b, #[rest] c) => {
///         first = a;
///         second = b;
///         rest = c;
///         Ok(())
///     }
/// }?;
///
/// assert_eq!(args.first, "foo");
/// assert_eq!(args.second.as_deref(), Some("bar"));
/// assert_eq!(args.rest, &["baz"]);
/// # Ok(()) }
/// ```
#[macro_export]
macro_rules! parse {
    // Parse with a custom iterator.
    (
        $it:expr => $($rest:tt)*
    ) => {{
        let mut __argwerk_it = ::std::iter::IntoIterator::into_iter($it).peekable();
        $crate::__parse_inner!(__argwerk_it, $($rest)*)
    }};

    // Parse with `std::env::args()`.
    (
        $($rest:tt)*
    ) => {{
        let mut __argwerk_it = ::std::env::args().peekable();
        __argwerk_it.next();
        $crate::__parse_inner!(__argwerk_it, $($rest)*)
    }};
}

/// Internal implementation details of the [parse] macro.
#[doc(hidden)]
#[macro_export]
macro_rules! __parse_inner {
    // The guts of the parser.
    (
        $it:ident,
        $(#[doc = $doc:literal])*
        $usage:literal {
            $($field:ident : $ty:ty $(= $expr:expr)?),* $(,)?
        }
        $($tt:tt)*
    ) => {{
        let mut parser = || {
            fn write_help(mut w: impl ::std::io::Write) -> ::std::io::Result<()> {
                use std::fmt::Write as _;

                let docs = [$($doc,)*];
                let mut help = ::argwerk::helpers::Help::new($usage, &docs[..]);
                $crate::__parse_inner!(@help help, $($tt)*);
                write!(w, "{}", help)?;
                Ok(())
            }

            fn print_help() {
                let out = ::std::io::stdout();
                let mut out = out.lock();
                write_help(out).expect("writing to stdout failed");
            }

            $($crate::__parse_inner!(@field $field, $ty $(= $expr)*);)*

            while let Some(__argwerk_arg) = $it.next() {
                $crate::__parse_inner!(@branch __argwerk_arg, $it, $($tt)*);

                return Err(::argwerk::Error::new(::argwerk::ErrorKind::Unsupported {
                    argument: __argwerk_arg.into()
                }));
            }

            #[derive(Debug)]
            struct Args { $($field: $ty,)* }

            Ok(Args {
                $($field,)*
            })
        };

        parser()
    }};

    // Parse the rest of the available arguments.
    (@positional #[rest] $it:ident, $arg:ident) => {
        (&mut $it).map(String::from).collect::<Vec<String>>();
    };

    // Parse an optional argument.
    (@positional #[option] $it:ident, $arg:ident) => {
        match $it.peek() {
            Some(n) => if !$crate::__parse_inner!(@is-switch n) {
                $it.next()
            } else {
                None
            }
            None => None,
        }
    };

    // Parse the rest of the arguments.
    (@positional $it:ident, $arg:ident) => {
        match $it.next() {
            Some($arg) => $arg,
            None => return Err(
                ::argwerk::Error::new(
                    ::argwerk::ErrorKind::MissingPositional {
                        name: stringify!($arg),
                    }
                )
            )
        }
    };

    // Try to parse an argument to a parameter.
    (@argument $argument:ident, $it:ident, $arg:ident) => {
        match $it.next() {
            Some($arg) => $arg,
            None => return Err(
                ::argwerk::Error::new(
                    ::argwerk::ErrorKind::MissingParameter {
                        argument: std::convert::AsRef::<str>::as_ref(&$argument).into(),
                        name: stringify!($arg),
                    }
                )
            ),
        }
    };

    // Test if `$n` is switch or not.
    (@is-switch $n:ident) => {
        std::convert::AsRef::<str>::as_ref($n).starts_with('-')
    };

    // Parse an optional argument.
    (@argument #[option] $argument:ident, $it:ident, $arg:ident) => {
        match $it.peek() {
            Some(n) => if !$crate::__parse_inner!(@is-switch n) {
                $it.next()
            } else {
                None
            }
            None => None,
        }
    };

    (@field $field:ident, $ty:ty) => {
        let mut $field: $ty = Default::default();
    };

    (@field $field:ident, $ty:ty = $expr:expr) => {
        let mut $field: $ty = $expr;
    };

    // Empty help generator.
    (@help $help:ident,) => {};

    // Generate help for positional parameters.
    (@help
        $help:ident,
        $(#[doc = $doc:literal])*
        ($first:ident $(, $(#[$($rest_meta:tt)*])* $rest:ident)*)
        $(if $cond:expr)? => $block:block
        $($tail:tt)*
    ) => {{
        let init = $help.switch_init_mut();

        init.push_str("  <");
        init.push_str(stringify!($first));
        init.push_str(">");

        $(
            init.push_str(" <");
            init.push_str(stringify!($rest));
            init.push_str(">");
        )*

        let docs = vec![$($doc,)*];
        $help.switch(docs);

        $crate::__parse_inner!(@help $help, $($tail)*);
    }};

    // Generate help for #[rest] bindings.
    (@help
        $help:ident,
        $(#[doc = $doc:literal])*
        #[rest] $binding:ident $(if $cond:expr)? => $block:block
        $($tail:tt)*
    ) => {{
        let init = $help.switch_init_mut();

        init.push_str("  <");
        init.push_str(stringify!($binding));
        init.push_str("..>");

        let docs = vec![$($doc,)*];
        $help.switch(docs);

        $crate::__parse_inner!(@help $help, $($tail)*);
    }};

    // A branch in a help generator.
    (@help
        $help:ident,
        $(#[doc = $doc:literal])*
        $first:literal $(| $rest:literal)* $(, $(#[$($arg_meta:tt)*])* $arg:ident)* $(if $cond:expr)? => $block:block
        $($tail:tt)*
    ) => {{
        let init = $help.switch_init_mut();

        init.clear();
        init.push_str("  ");
        init.push_str($first);

        $(
            init.push_str(", ");
            init.push_str($rest);
        )*

        $(
            init.push_str(" <");
            init.push_str(stringify!($arg));
            init.push('>');
        )*

        let docs = vec![$($doc,)*];
        $help.switch(docs);

        $crate::__parse_inner!(@help $help, $($tail)*);
    }};

    // The empty condition.
    (@cond) => { true };

    // An expression condition.
    (@cond $expr:expr) => { $expr };

    // Empty branch expansion.
    (@branch $arg:ident, $it:ident,) => {};

    // Match positional arguments.
    (@branch
        $argument:ident, $it:ident,
        $(#[doc = $doc:literal])*
        ($first:ident $(, $(#[$($rest_meta:tt)*])* $rest:ident)*)
        $(if $cond:expr)? => $block:block
        $($tail:tt)*
    ) => {
        if argwerk::__parse_inner!(@cond $($cond)*) {
            let __argwerk_error_argument = std::convert::AsRef::<str>::as_ref(&$argument).into();

            let $first = $argument;
            $(let $rest = $crate::__parse_inner!(@positional $(#[$($rest_meta)*])* $it, $rest);)*

            let mut __argwerk_handle = || -> Result<(), Box<dyn ::std::error::Error + Send + Sync + 'static>> {
                $block
            };

            if let Err(error) = __argwerk_handle() {
                return Err(::argwerk::Error::new(::argwerk::ErrorKind::Error {
                    argument: __argwerk_error_argument,
                    error
                }));
            }

            continue;
        }

        $crate::__parse_inner!(@branch $argument, $it, $($tail)*);
    };

    // Match the rest of the arguments
    (@branch
        $argument:ident, $it:ident,
        $(#[doc = $doc:literal])*
        #[rest] $binding:ident $(if $cond:expr)? => $block:block
        $($tail:tt)*
    ) => {
        if argwerk::__parse_inner!(@cond $($cond)*) {
            let __argwerk_error_argument = std::convert::AsRef::<str>::as_ref(&$argument).into();

            let $binding = Some($argument).into_iter().chain((&mut $it)).collect::<Vec<_>>();

            let mut __argwerk_handle = || -> Result<(), Box<dyn ::std::error::Error + Send + Sync + 'static>> {
                $block
            };

            if let Err(error) = __argwerk_handle() {
                return Err(::argwerk::Error::new(::argwerk::ErrorKind::Error {
                    argument: __argwerk_error_argument,
                    error
                }));
            }

            continue;
        }

        $crate::__parse_inner!(@branch $argument, $it, $($tail)*);
    };

    // A single branch expansion.
    (@branch
        $argument:ident, $it:ident,
        $(#[$($meta:tt)*])*
        $first:literal $(| $rest:literal)* $(, $(#[$($arg_meta:tt)*])* $arg:ident)* $(if $cond:expr)? => $block:block
        $($tail:tt)*
    ) => {
        match std::convert::AsRef::<str>::as_ref(&$argument) {
            $first $( | $rest)* $(if $cond)* => {
                $(let $arg = $crate::__parse_inner!(@argument $(#[$($arg_meta)*])* $argument, $it, $arg);)*

                let mut __argwerk_handle = || -> Result<(), Box<dyn ::std::error::Error + Send + Sync + 'static>> {
                    $block
                };

                if let Err(error) = __argwerk_handle() {
                    return Err(::argwerk::Error::new(::argwerk::ErrorKind::Error {
                        argument: std::convert::AsRef::<str>::as_ref(&$argument).into(),
                        error
                    }));
                }

                continue;
            }
            _ => (),
        }

        $crate::__parse_inner!(@branch $argument, $it, $($tail)*);
    };
}