clap_v3/
macros.rs

1/// A convenience macro for loading the YAML file at compile time (relative to the current file,
2/// like modules work). That YAML object can then be passed to this function.
3///
4/// # Panics
5///
6/// The YAML file must be properly formatted or this function will panic!(). A good way to
7/// ensure this doesn't happen is to run your program with the `--help` switch. If this passes
8/// without error, you needn't worry because the YAML is properly formatted.
9///
10/// # Examples
11///
12/// The following example shows how to load a properly formatted YAML file to build an instance
13/// of an `App` struct.
14///
15/// ```ignore
16/// # #[macro_use]
17/// # extern crate clap;
18/// # use clap::App;
19/// # fn main() {
20/// let yml = load_yaml!("app.yml");
21/// let app = App::from_yaml(yml);
22///
23/// // continued logic goes here, such as `app.get_matches()` etc.
24/// # }
25/// ```
26#[cfg(feature = "yaml")]
27#[macro_export]
28macro_rules! load_yaml {
29    ($yml:expr) => {
30        &$crate::YamlLoader::load_from_str(include_str!($yml)).expect("failed to load YAML file")[0]
31    };
32}
33
34/// Convenience macro getting a typed value `T` where `T` implements [`std::str::FromStr`] from an
35/// argument value. This macro returns a `Result<T,String>` which allows you as the developer to
36/// decide what you'd like to do on a failed parse. There are two types of errors, parse failures
37/// and those where the argument wasn't present (such as a non-required argument). You can use
38/// it to get a single value, or a iterator as with the [`ArgMatches::values_of`]
39///
40/// # Examples
41///
42/// ```no_run
43/// # #[macro_use]
44/// # extern crate clap;
45/// # use clap::App;
46/// # fn main() {
47/// let matches = App::new("myapp")
48///               .arg("[length] 'Set the length to use as a pos whole num, i.e. 20'")
49///               .get_matches();
50///
51/// let len      = value_t!(matches.value_of("length"), u32).unwrap_or_else(|e| e.exit());
52/// let also_len = value_t!(matches, "length", u32).unwrap_or_else(|e| e.exit());
53///
54/// println!("{} + 2: {}", len, len + 2);
55/// # }
56/// ```
57/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
58/// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
59/// [`Result<T,String>`]: https://doc.rust-lang.org/std/result/enum.Result.html
60#[macro_export]
61macro_rules! value_t {
62    ($m:ident, $v:expr, $t:ty) => {
63        $crate::value_t!($m.value_of($v), $t)
64    };
65    ($m:ident.value_of($v:expr), $t:ty) => {
66        if let Some(v) = $m.value_of($v) {
67            match v.parse::<$t>() {
68                Ok(val) => Ok(val),
69                Err(_) => Err($crate::Error::value_validation_auto(&format!(
70                    "The argument '{}' isn't a valid value",
71                    v
72                ))),
73            }
74        } else {
75            Err($crate::Error::argument_not_found_auto($v))
76        }
77    };
78}
79
80/// Convenience macro getting a typed value `T` where `T` implements [`std::str::FromStr`] or
81/// exiting upon error, instead of returning a [`Result`] type.
82///
83/// **NOTE:** This macro is for backwards compatibility sake. Prefer
84/// [`value_t!(/* ... */).unwrap_or_else(|e| e.exit())`]
85///
86/// # Examples
87///
88/// ```no_run
89/// # #[macro_use]
90/// # extern crate clap;
91/// # use clap::App;
92/// # fn main() {
93/// let matches = App::new("myapp")
94///               .arg("[length] 'Set the length to use as a pos whole num, i.e. 20'")
95///               .get_matches();
96///
97/// let len      = value_t_or_exit!(matches.value_of("length"), u32);
98/// let also_len = value_t_or_exit!(matches, "length", u32);
99///
100/// println!("{} + 2: {}", len, len + 2);
101/// # }
102/// ```
103/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
104/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
105/// [`value_t!(/* ... */).unwrap_or_else(|e| e.exit())`]: ./macro.value_t!.html
106#[macro_export]
107macro_rules! value_t_or_exit {
108    ($m:ident, $v:expr, $t:ty) => {
109        $crate::value_t_or_exit!($m.value_of($v), $t)
110    };
111    ($m:ident.value_of($v:expr), $t:ty) => {
112        if let Some(v) = $m.value_of($v) {
113            match v.parse::<$t>() {
114                Ok(val) => val,
115                Err(_) => $crate::Error::value_validation_auto(&format!(
116                    "The argument '{}' isn't a valid value",
117                    v
118                ))
119                .exit(),
120            }
121        } else {
122            $crate::Error::argument_not_found_auto($v).exit()
123        }
124    };
125}
126
127/// Convenience macro getting a typed value [`Vec<T>`] where `T` implements [`std::str::FromStr`]
128/// This macro returns a [`clap::Result<Vec<T>>`] which allows you as the developer to decide
129/// what you'd like to do on a failed parse.
130///
131/// # Examples
132///
133/// ```no_run
134/// # #[macro_use]
135/// # extern crate clap;
136/// # use clap::App;
137/// # fn main() {
138/// let matches = App::new("myapp")
139///               .arg("[seq]... 'A sequence of pos whole nums, i.e. 20 45'")
140///               .get_matches();
141///
142/// let vals = values_t!(matches.values_of("seq"), u32).unwrap_or_else(|e| e.exit());
143/// for v in &vals {
144///     println!("{} + 2: {}", v, v + 2);
145/// }
146///
147/// let vals = values_t!(matches, "seq", u32).unwrap_or_else(|e| e.exit());
148/// for v in &vals {
149///     println!("{} + 2: {}", v, v + 2);
150/// }
151/// # }
152/// ```
153/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
154/// [`Vec<T>`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
155/// [`clap::Result<Vec<T>>`]: ./type.Result.html
156#[macro_export]
157macro_rules! values_t {
158    ($m:ident, $v:expr, $t:ty) => {
159        $crate::values_t!($m.values_of($v), $t)
160    };
161    ($m:ident.values_of($v:expr), $t:ty) => {
162        if let Some(vals) = $m.values_of($v) {
163            let mut tmp = vec![];
164            let mut err = None;
165            for pv in vals {
166                match pv.parse::<$t>() {
167                    Ok(rv) => tmp.push(rv),
168                    Err(..) => {
169                        err = Some($crate::Error::value_validation_auto(&format!(
170                            "The argument '{}' isn't a valid value",
171                            pv
172                        )));
173                        break;
174                    }
175                }
176            }
177            match err {
178                Some(e) => Err(e),
179                None => Ok(tmp),
180            }
181        } else {
182            Err($crate::Error::argument_not_found_auto($v))
183        }
184    };
185}
186
187/// Convenience macro getting a typed value [`Vec<T>`] where `T` implements [`std::str::FromStr`]
188/// or exiting upon error.
189///
190/// **NOTE:** This macro is for backwards compatibility sake. Prefer
191/// [`values_t!(/* ... */).unwrap_or_else(|e| e.exit())`]
192///
193/// # Examples
194///
195/// ```no_run
196/// # #[macro_use]
197/// # extern crate clap;
198/// # use clap::App;
199/// # fn main() {
200/// let matches = App::new("myapp")
201///               .arg("[seq]... 'A sequence of pos whole nums, i.e. 20 45'")
202///               .get_matches();
203///
204/// let vals = values_t_or_exit!(matches.values_of("seq"), u32);
205/// for v in &vals {
206///     println!("{} + 2: {}", v, v + 2);
207/// }
208///
209/// // type for example only
210/// let vals: Vec<u32> = values_t_or_exit!(matches, "seq", u32);
211/// for v in &vals {
212///     println!("{} + 2: {}", v, v + 2);
213/// }
214/// # }
215/// ```
216/// [`values_t!(/* ... */).unwrap_or_else(|e| e.exit())`]: ./macro.values_t!.html
217/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
218/// [`Vec<T>`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
219#[macro_export]
220macro_rules! values_t_or_exit {
221    ($m:ident, $v:expr, $t:ty) => {
222        $crate::values_t_or_exit!($m.values_of($v), $t)
223    };
224    ($m:ident.values_of($v:expr), $t:ty) => {
225        if let Some(vals) = $m.values_of($v) {
226            vals.map(|v| {
227                v.parse::<$t>().unwrap_or_else(|_| {
228                    $crate::Error::value_validation_auto(&format!(
229                        "One or more arguments aren't valid values"
230                    ))
231                    .exit()
232                })
233            })
234            .collect::<Vec<$t>>()
235        } else {
236            $crate::Error::argument_not_found_auto($v).exit()
237        }
238    };
239}
240
241// _clap_count_exprs! is derived from https://github.com/DanielKeep/rust-grabbag
242// commit: 82a35ca5d9a04c3b920622d542104e3310ee5b07
243// License: MIT
244// Copyright ⓒ 2015 grabbag contributors.
245// Licensed under the MIT license (see LICENSE or <http://opensource.org
246// /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
247// <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
248// files in the project carrying such notice may not be copied, modified,
249// or distributed except according to those terms.
250//
251/// Counts the number of comma-delimited expressions passed to it.  The result is a compile-time
252/// evaluable expression, suitable for use as a static array size, or the value of a `const`.
253///
254/// # Examples
255///
256/// ```
257/// # #[macro_use] extern crate clap;
258/// # fn main() {
259/// const COUNT: usize = _clap_count_exprs!(a, 5+1, "hi there!".into_string());
260/// assert_eq!(COUNT, 3);
261/// # }
262/// ```
263#[macro_export]
264macro_rules! _clap_count_exprs {
265    () => { 0 };
266    ($e:expr) => { 1 };
267    ($e:expr, $($es:expr),+) => { 1 + $crate::_clap_count_exprs!($($es),*) };
268}
269
270/// Convenience macro to generate more complete enums with variants to be used as a type when
271/// parsing arguments. This enum also provides a `variants()` function which can be used to
272/// retrieve a `Vec<&'static str>` of the variant names, as well as implementing [`FromStr`] and
273/// [`Display`] automatically.
274///
275/// **NOTE:** Case insensitivity is supported for ASCII characters only. It's highly recommended to
276/// use [`Arg::case_insensitive(true)`] for args that will be used with these enums
277///
278/// **NOTE:** This macro automatically implements [`std::str::FromStr`] and [`std::fmt::Display`]
279///
280/// **NOTE:** These enums support pub (or not) and uses of the `#[derive()]` traits
281///
282/// # Examples
283///
284/// ```rust
285/// # #[macro_use]
286/// # extern crate clap;
287/// # use clap::{App, Arg};
288/// arg_enum!{
289///     #[derive(PartialEq, Debug)]
290///     pub enum Foo {
291///         Bar,
292///         Baz,
293///         Qux
294///     }
295/// }
296/// // Foo enum can now be used via Foo::Bar, or Foo::Baz, etc
297/// // and implements std::str::FromStr to use with the value_t! macros
298/// fn main() {
299///     let m = App::new("app")
300///                 .arg(Arg::from("<foo> 'the foo'")
301///                     .possible_values(&Foo::variants())
302///                     .case_insensitive(true))
303///                 .get_matches_from(vec![
304///                     "app", "baz"
305///                 ]);
306///     let f = value_t!(m, "foo", Foo).unwrap_or_else(|e| e.exit());
307///
308///     assert_eq!(f, Foo::Baz);
309/// }
310/// ```
311/// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
312/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
313/// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
314/// [`std::fmt::Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
315/// [`Arg::case_insensitive(true)`]: ./struct.Arg.html#method.case_insensitive
316#[macro_export]
317macro_rules! arg_enum {
318    (@as_item $($i:item)*) => ($($i)*);
319    (@impls ( $($tts:tt)* ) -> ($e:ident, $($v:ident),+)) => {
320        $crate::arg_enum!(@as_item
321        $($tts)*
322
323        impl ::std::str::FromStr for $e {
324            type Err = String;
325
326            fn from_str(s: &str) -> ::std::result::Result<Self,Self::Err> {
327                match s {
328                    $(stringify!($v) |
329                    _ if s.eq_ignore_ascii_case(stringify!($v)) => Ok($e::$v)),+,
330                    _ => Err({
331                        let v = vec![
332                            $(stringify!($v),)+
333                        ];
334                        format!("valid values: {}",
335                            v.join(" ,"))
336                    }),
337                }
338            }
339        }
340        impl ::std::fmt::Display for $e {
341            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
342                match *self {
343                    $($e::$v => write!(f, stringify!($v)),)+
344                }
345            }
346        }
347        impl $e {
348            #[allow(dead_code)]
349            #[allow(missing_docs)]
350            pub fn variants() -> [&'static str; $crate::_clap_count_exprs!($(stringify!($v)),+)] {
351                [
352                    $(stringify!($v),)+
353                ]
354            }
355        });
356    };
357    ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => {
358        $crate::arg_enum!(@impls
359            ($(#[$($m),+])+
360            pub enum $e {
361                $($v$(=$val)*),+
362            }) -> ($e, $($v),+)
363        );
364    };
365    ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
366        $crate::arg_enum!(@impls
367            ($(#[$($m),+])+
368            pub enum $e {
369                $($v$(=$val)*),+
370            }) -> ($e, $($v),+)
371        );
372    };
373    ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => {
374        $crate::arg_enum!($(#[$($m:meta),+])+
375            enum $e:ident {
376                $($v:ident $(=$val:expr)*),+
377            }
378        );
379    };
380    ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
381        $crate::arg_enum!(@impls
382            ($(#[$($m),+])+
383            enum $e {
384                $($v$(=$val)*),+
385            }) -> ($e, $($v),+)
386        );
387    };
388    (pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => {
389        $crate::arg_enum!(pub enum $e:ident {
390            $($v:ident $(=$val:expr)*),+
391        });
392    };
393    (pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
394        $crate::arg_enum!(@impls
395            (pub enum $e {
396                $($v$(=$val)*),+
397            }) -> ($e, $($v),+)
398        );
399    };
400    (enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => {
401        $crate::arg_enum!(enum $e:ident {
402            $($v:ident $(=$val:expr)*),+
403        });
404    };
405    (enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
406        $crate::arg_enum!(@impls
407            (enum $e {
408                $($v$(=$val)*),+
409            }) -> ($e, $($v),+)
410        );
411    };
412}
413
414/// Allows you to pull the version from your Cargo.toml at compile time as
415/// `MAJOR.MINOR.PATCH_PKGVERSION_PRE`
416///
417/// # Examples
418///
419/// ```no_run
420/// # #[macro_use]
421/// # extern crate clap;
422/// # use clap::App;
423/// # fn main() {
424/// let m = App::new("app")
425///             .version(crate_version!())
426///             .get_matches();
427/// # }
428/// ```
429#[cfg(feature = "cargo")]
430#[macro_export]
431macro_rules! crate_version {
432    () => {
433        env!("CARGO_PKG_VERSION")
434    };
435}
436
437/// Allows you to pull the authors for the app from your Cargo.toml at
438/// compile time in the form:
439/// `"author1 lastname <author1@example.com>:author2 lastname <author2@example.com>"`
440///
441/// You can replace the colons with a custom separator by supplying a
442/// replacement string, so, for example,
443/// `crate_authors!(",\n")` would become
444/// `"author1 lastname <author1@example.com>,\nauthor2 lastname <author2@example.com>,\nauthor3 lastname <author3@example.com>"`
445///
446/// # Examples
447///
448/// ```no_run
449/// # #[macro_use]
450/// # extern crate clap;
451/// # use clap::App;
452/// # fn main() {
453/// let m = App::new("app")
454///             .author(crate_authors!("\n"))
455///             .get_matches();
456/// # }
457/// ```
458#[cfg(feature = "cargo")]
459#[macro_export]
460macro_rules! crate_authors {
461    ($sep:expr) => {{
462        use std::ops::Deref;
463        use std::boxed::Box;
464        use std::cell::Cell;
465
466        #[allow(missing_copy_implementations)]
467        #[allow(dead_code)]
468        struct CargoAuthors {
469            authors: Cell<Option<&'static str>>,
470            __private_field: (),
471        };
472
473        impl Deref for CargoAuthors {
474            type Target = str;
475
476            fn deref(&self) -> &'static str {
477                let authors = self.authors.take();
478                if authors.is_some() {
479                    let unwrapped_authors = authors.unwrap();
480                    self.authors.replace(Some(unwrapped_authors));
481                    unwrapped_authors
482                } else {
483                    // This caches the result for subsequent invocations of the same instance of the macro
484                    // to avoid performing one memory allocation per call.
485                    // If performance ever becomes a problem for this code, it should be moved to build.rs
486                    let s: Box<String> = Box::new(env!("CARGO_PKG_AUTHORS").replace(':', $sep));
487                    let static_string = Box::leak(s);
488                    self.authors.replace(Some(&*static_string));
489                    &*static_string // weird but compiler-suggested way to turn a String into &str
490                }
491            }
492        }
493
494        &*CargoAuthors {
495            authors: std::cell::Cell::new(Option::None),
496            __private_field: (),
497        }
498    }};
499    () => {
500        env!("CARGO_PKG_AUTHORS")
501    };
502}
503
504/// Allows you to pull the description from your Cargo.toml at compile time.
505///
506/// # Examples
507///
508/// ```no_run
509/// # #[macro_use]
510/// # extern crate clap;
511/// # use clap::App;
512/// # fn main() {
513/// let m = App::new("app")
514///             .about(crate_description!())
515///             .get_matches();
516/// # }
517/// ```
518#[cfg(feature = "cargo")]
519#[macro_export]
520macro_rules! crate_description {
521    () => {
522        env!("CARGO_PKG_DESCRIPTION")
523    };
524}
525
526/// Allows you to pull the name from your Cargo.toml at compile time.
527///
528/// # Examples
529///
530/// ```no_run
531/// # #[macro_use]
532/// # extern crate clap;
533/// # use clap::App;
534/// # fn main() {
535/// let m = App::new(crate_name!())
536///             .get_matches();
537/// # }
538/// ```
539#[cfg(feature = "cargo")]
540#[macro_export]
541macro_rules! crate_name {
542    () => {
543        env!("CARGO_PKG_NAME")
544    };
545}
546
547/// Allows you to build the `App` instance from your Cargo.toml at compile time.
548///
549/// Equivalent to using the `crate_*!` macros with their respective fields.
550///
551/// Provided separator is for the [`crate_authors!`](macro.crate_authors.html) macro,
552/// refer to the documentation therefor.
553///
554/// **NOTE:** Changing the values in your `Cargo.toml` does not trigger a re-build automatically,
555/// and therefore won't change the generated output until you recompile.
556///
557/// **Pro Tip:** In some cases you can "trick" the compiler into triggering a rebuild when your
558/// `Cargo.toml` is changed by including this in your `src/main.rs` file
559/// `include_str!("../Cargo.toml");`
560///
561/// # Examples
562///
563/// ```no_run
564/// # #[macro_use]
565/// # extern crate clap;
566/// # fn main() {
567/// let m = app_from_crate!().get_matches();
568/// # }
569/// ```
570#[cfg(feature = "cargo")]
571#[macro_export]
572macro_rules! app_from_crate {
573    () => {
574        $crate::App::new($crate::crate_name!())
575            .version($crate::crate_version!())
576            .author($crate::crate_authors!())
577            .about($crate::crate_description!())
578    };
579    ($sep:expr) => {
580        $crate::App::new($crate::crate_name!())
581            .version($crate::crate_version!())
582            .author($crate::crate_authors!($sep))
583            .about($crate::crate_description!())
584    };
585}
586
587/// Build `App`, `Arg`s, ``s and `Group`s with Usage-string like input
588/// but without the associated parsing runtime cost.
589///
590/// `clap_app!` also supports several shorthand syntaxes.
591///
592/// # Examples
593///
594/// ```no_run
595/// # #[macro_use]
596/// # extern crate clap;
597/// # fn main() {
598/// let matches = clap_app!(myapp =>
599///     (version: "1.0")
600///     (author: "Kevin K. <kbknapp@gmail.com>")
601///     (about: "Does awesome things")
602///     (@arg CONFIG: -c --config +takes_value "Sets a custom config file")
603///     (@arg INPUT: +required "Sets the input file to use")
604///     (@arg debug: -d ... "Sets the level of debugging information")
605///     (@group difficulty =>
606///         (@arg hard: -h --hard "Sets hard mode")
607///         (@arg normal: -n --normal "Sets normal mode")
608///         (@arg easy: -e --easy "Sets easy mode")
609///     )
610///     (@subcommand test =>
611///         (about: "controls testing features")
612///         (version: "1.3")
613///         (author: "Someone E. <someone_else@other.com>")
614///         (@arg verbose: -v --verbose "Print test information verbosely")
615///     )
616/// );
617/// # }
618/// ```
619/// # Shorthand Syntax for Args
620///
621/// * A single hyphen followed by a character (such as `-c`) sets the [`Arg::short`]
622/// * A double hyphen followed by a character or word (such as `--config`) sets [`Arg::long`]
623///   * If one wishes to use a [`Arg::long`] with a hyphen inside (i.e. `--config-file`), you
624///     must use `--("config-file")` due to limitations of the Rust macro system.
625/// * Three dots (`...`) sets [`Arg::multiple(true)`]
626/// * Angled brackets after either a short or long will set [`Arg::value_name`] and
627/// `Arg::required(true)` such as `--config <FILE>` = `Arg::value_name("FILE")` and
628/// `Arg::required(true)`
629/// * Square brackets after either a short or long will set [`Arg::value_name`] and
630/// `Arg::required(false)` such as `--config [FILE]` = `Arg::value_name("FILE")` and
631/// `Arg::required(false)`
632/// * There are short hand syntaxes for Arg methods that accept booleans
633///   * A plus sign will set that method to `true` such as `+required` = `Arg::required(true)`
634///   * An exclamation will set that method to `false` such as `!required` = `Arg::required(false)`
635/// * A `#{min, max}` will set [`Arg::min_values(min)`] and [`Arg::max_values(max)`]
636/// * An asterisk (`*`) will set `Arg::required(true)`
637/// * Curly brackets around a `fn` will set [`Arg::validator`] as in `{fn}` = `Arg::validator(fn)`
638/// * An Arg method that accepts a string followed by square brackets will set that method such as
639/// `conflicts_with[FOO]` will set `Arg::conflicts_with("FOO")` (note the lack of quotes around
640/// `FOO` in the macro)
641/// * An Arg method that takes a string and can be set multiple times (such as
642/// [`Arg::conflicts_with`]) followed by square brackets and a list of values separated by spaces
643/// will set that method such as `conflicts_with[FOO BAR BAZ]` will set
644/// `Arg::conflicts_with("FOO")`, `Arg::conflicts_with("BAR")`, and `Arg::conflicts_with("BAZ")`
645/// (note the lack of quotes around the values in the macro)
646///
647/// # Shorthand Syntax for Groups
648///
649/// * There are short hand syntaxes for `ArgGroup` methods that accept booleans
650///   * A plus sign will set that method to `true` such as `+required` = `ArgGroup::required(true)`
651///   * An exclamation will set that method to `false` such as `!required` = `ArgGroup::required(false)`
652///
653/// # Alternative form for non-ident values
654///
655/// Certain places that normally accept an `ident`, will optionally accept an alternative of `("expr enclosed by parens")`
656/// * `(@arg something: --something)` could also be `(@arg ("something-else"): --("something-else"))`
657/// * `(@subcommand something => ...)` could also be `(@subcommand ("something-else") => ...)`
658///
659/// [`Arg::short`]: ./struct.Arg.html#method.short
660/// [`Arg::long`]: ./struct.Arg.html#method.long
661/// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
662/// [`Arg::value_name`]: ./struct.Arg.html#method.value_name
663/// [`Arg::min_values(min)`]: ./struct.Arg.html#method.min_values
664/// [`Arg::max_values(max)`]: ./struct.Arg.html#method.max_values
665/// [`Arg::validator`]: ./struct.Arg.html#method.validator
666/// [`Arg::conflicts_with`]: ./struct.Arg.html#method.conflicts_with
667#[macro_export]
668macro_rules! clap_app {
669    (@app ($builder:expr)) => { $builder };
670    (@app ($builder:expr) (@arg ($name:expr): $($tail:tt)*) $($tt:tt)*) => {
671        $crate::clap_app!{ @app
672            ($builder.arg(
673                $crate::clap_app!{ @arg ($crate::Arg::with_name($name)) (-) $($tail)* }))
674            $($tt)*
675        }
676    };
677    (@app ($builder:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => {
678        $crate::clap_app!{ @app
679            ($builder.arg(
680                $crate::clap_app!{ @arg ($crate::Arg::with_name(stringify!($name))) (-) $($tail)* }))
681            $($tt)*
682        }
683    };
684    (@app ($builder:expr) (@setting $setting:ident) $($tt:tt)*) => {
685        $crate::clap_app!{ @app
686            ($builder.setting($crate::AppSettings::$setting))
687            $($tt)*
688        }
689    };
690// Treat the application builder as an argument to set its attributes
691    (@app ($builder:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => {
692        $crate::clap_app!{ @app ($crate::clap_app!{ @arg ($builder) $($attr)* }) $($tt)* }
693    };
694    (@app ($builder:expr) (@group $name:ident => $($tail:tt)*) $($tt:tt)*) => {
695        $crate::clap_app!{ @app
696            ($crate::clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name))) $($tail)* })
697            $($tt)*
698        }
699    };
700    (@app ($builder:expr) (@group $name:ident !$ident:ident => $($tail:tt)*) $($tt:tt)*) => {
701        $crate::clap_app!{ @app
702            ($crate::clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name)).$ident(false)) $($tail)* })
703            $($tt)*
704        }
705    };
706    (@app ($builder:expr) (@group $name:ident +$ident:ident => $($tail:tt)*) $($tt:tt)*) => {
707        $crate::clap_app!{ @app
708            ($crate::clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name)).$ident(true)) $($tail)* })
709            $($tt)*
710        }
711    };
712// Handle subcommand creation
713    (@app ($builder:expr) (@subcommand $name:ident => $($tail:tt)*) $($tt:tt)*) => {
714        $crate::clap_app!{ @app
715            ($builder.subcommand(
716                $crate::clap_app!{ @app ($crate::App::new(stringify!($name))) $($tail)* }
717            ))
718            $($tt)*
719        }
720    };
721    (@app ($builder:expr) (@subcommand ($name:expr) => $($tail:tt)*) $($tt:tt)*) => {
722        clap_app!{ @app
723            ($builder.subcommand(
724                $crate::clap_app!{ @app ($crate::App::new($name)) $($tail)* }
725            ))
726            $($tt)*
727        }
728    };
729// Yaml like function calls - used for setting various meta directly against the app
730    (@app ($builder:expr) ($ident:ident: $($v:expr),*) $($tt:tt)*) => {
731// clap_app!{ @app ($builder.$ident($($v),*)) $($tt)* }
732        $crate::clap_app!{ @app
733            ($builder.$ident($($v),*))
734            $($tt)*
735        }
736    };
737
738// Add members to group and continue argument handling with the parent builder
739    (@group ($builder:expr, $group:expr)) => { $builder.group($group) };
740    // Treat the group builder as an argument to set its attributes
741    (@group ($builder:expr, $group:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => {
742        $crate::clap_app!{ @group ($builder, $crate::clap_app!{ @arg ($group) (-) $($attr)* }) $($tt)* }
743    };
744    (@group ($builder:expr, $group:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => {
745        $crate::clap_app!{ @group
746            ($crate::clap_app!{ @app ($builder) (@arg $name: $($tail)*) },
747             $group.arg(stringify!($name)))
748            $($tt)*
749        }
750    };
751
752// No more tokens to munch
753    (@arg ($arg:expr) $modes:tt) => { $arg };
754// Shorthand tokens influenced by the usage_string
755    (@arg ($arg:expr) $modes:tt --($long:expr) $($tail:tt)*) => {
756        $crate::clap_app!{ @arg ($arg.long($long)) $modes $($tail)* }
757    };
758    (@arg ($arg:expr) $modes:tt --$long:ident $($tail:tt)*) => {
759        $crate::clap_app!{ @arg ($arg.long(stringify!($long))) $modes $($tail)* }
760    };
761    (@arg ($arg:expr) $modes:tt -$short:ident $($tail:tt)*) => {
762        $crate::clap_app!{ @arg ($arg.short(stringify!($short).chars().next().unwrap())) $modes $($tail)* }
763    };
764    (@arg ($arg:expr) (-) <$var:ident> $($tail:tt)*) => {
765        $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value +required $($tail)* }
766    };
767    (@arg ($arg:expr) (+) <$var:ident> $($tail:tt)*) => {
768        $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* }
769    };
770    (@arg ($arg:expr) (-) [$var:ident] $($tail:tt)*) => {
771        $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value $($tail)* }
772    };
773    (@arg ($arg:expr) (+) [$var:ident] $($tail:tt)*) => {
774        $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* }
775    };
776    (@arg ($arg:expr) $modes:tt ... $($tail:tt)*) => {
777        $crate::clap_app!{ @arg ($arg) $modes +multiple $($tail)* }
778    };
779// Shorthand magic
780    (@arg ($arg:expr) $modes:tt #{$n:expr, $m:expr} $($tail:tt)*) => {
781        $crate::clap_app!{ @arg ($arg) $modes min_values($n) max_values($m) $($tail)* }
782    };
783    (@arg ($arg:expr) $modes:tt * $($tail:tt)*) => {
784        $crate::clap_app!{ @arg ($arg) $modes +required $($tail)* }
785    };
786// !foo -> .foo(false)
787    (@arg ($arg:expr) $modes:tt !$ident:ident $($tail:tt)*) => {
788        $crate::clap_app!{ @arg ($arg.$ident(false)) $modes $($tail)* }
789    };
790// +foo -> .foo(true)
791    (@arg ($arg:expr) $modes:tt +$ident:ident $($tail:tt)*) => {
792        $crate::clap_app!{ @arg ($arg.$ident(true)) $modes $($tail)* }
793    };
794// Validator
795    (@arg ($arg:expr) $modes:tt {$fn_:expr} $($tail:tt)*) => {
796        $crate::clap_app!{ @arg ($arg.validator($fn_)) $modes $($tail)* }
797    };
798    (@as_expr $expr:expr) => { $expr };
799// Help
800    (@arg ($arg:expr) $modes:tt $desc:tt) => { $arg.help(clap_app!{ @as_expr $desc }) };
801// Handle functions that need to be called multiple times for each argument
802    (@arg ($arg:expr) $modes:tt $ident:ident[$($target:ident)*] $($tail:tt)*) => {
803        $crate::clap_app!{ @arg ($arg $( .$ident(stringify!($target)) )*) $modes $($tail)* }
804    };
805// Inherit builder's functions
806    (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr)*) $($tail:tt)*) => {
807        $crate::clap_app!{ @arg ($arg.$ident($($expr)*)) $modes $($tail)* }
808    };
809
810// Build a subcommand outside of an app.
811    (@subcommand $name:ident => $($tail:tt)*) => {
812        $crate::clap_app!{ @app ($crate::App::new(stringify!($name))) $($tail)* }
813    };
814    (@subcommand ($name:expr) => $($tail:tt)*) => {
815        $crate::clap_app!{ @app ($crate::App::new($name)) $($tail)* }
816    };
817// Start the magic
818    (($name:expr) => $($tail:tt)*) => {{
819        $crate::clap_app!{ @app ($crate::App::new($name)) $($tail)*}
820    }};
821
822    ($name:ident => $($tail:tt)*) => {{
823        $crate::clap_app!{ @app ($crate::App::new(stringify!($name))) $($tail)*}
824    }};
825}
826
827macro_rules! impl_settings {
828    ($settings:ident, $flags:ident,
829        $( $setting:ident($str:expr) => $flag:path ),+
830    ) => {
831        impl $flags {
832            pub(crate) fn set(&mut self, s: $settings) {
833                match s {
834                    $($settings::$setting => self.0.insert($flag)),*
835                }
836            }
837
838            pub(crate) fn unset(&mut self, s: $settings) {
839                match s {
840                    $($settings::$setting => self.0.remove($flag)),*
841                }
842            }
843
844            pub(crate) fn is_set(&self, s: $settings) -> bool {
845                match s {
846                    $($settings::$setting => self.0.contains($flag)),*
847                }
848            }
849        }
850
851        impl FromStr for $settings {
852            type Err = String;
853            fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
854                match &*s.to_ascii_lowercase() {
855                    $( $str => Ok($settings::$setting), )*
856                    _ => Err(format!("unknown AppSetting: `{}`", s)),
857                }
858            }
859        }
860    }
861}
862
863// Convenience for writing to stderr thanks to https://github.com/BurntSushi
864macro_rules! wlnerr(
865    ($($arg:tt)*) => ({
866        use std::io::{Write, stderr};
867        writeln!(&mut stderr(), $($arg)*).ok();
868    })
869);
870
871#[cfg(feature = "debug")]
872#[cfg_attr(feature = "debug", macro_use)]
873#[cfg_attr(feature = "debug", allow(unused_macros))]
874mod debug_macros {
875    macro_rules! debugln {
876        ($fmt:expr) => (println!(concat!("DEBUG:clap:", $fmt)));
877        ($fmt:expr, $($arg:tt)*) => (println!(concat!("DEBUG:clap:",$fmt), $($arg)*));
878    }
879    macro_rules! sdebugln {
880        ($fmt:expr) => (println!($fmt));
881        ($fmt:expr, $($arg:tt)*) => (println!($fmt, $($arg)*));
882    }
883    macro_rules! debug {
884        ($fmt:expr) => (print!(concat!("DEBUG:clap:", $fmt)));
885        ($fmt:expr, $($arg:tt)*) => (print!(concat!("DEBUG:clap:",$fmt), $($arg)*));
886    }
887    macro_rules! sdebug {
888        ($fmt:expr) => (print!($fmt));
889        ($fmt:expr, $($arg:tt)*) => (print!($fmt, $($arg)*));
890    }
891}
892
893#[cfg(not(feature = "debug"))]
894#[cfg_attr(not(feature = "debug"), macro_use)]
895mod debug_macros {
896    macro_rules! debugln {
897        ($fmt:expr) => {};
898        ($fmt:expr, $($arg:tt)*) => {};
899    }
900    macro_rules! sdebugln {
901        ($fmt:expr) => {};
902        ($fmt:expr, $($arg:tt)*) => {};
903    }
904    macro_rules! debug {
905        ($fmt:expr) => {};
906        ($fmt:expr, $($arg:tt)*) => {};
907    }
908}
909
910// Helper/deduplication macro for printing the correct number of spaces in help messages
911// used in:
912//    src/args/arg_builder/*.rs
913//    src/app/mod.rs
914macro_rules! write_nspaces {
915    ($dst:expr, $num:expr) => {{
916        debugln!("write_spaces!: num={}", $num);
917        for _ in 0..$num {
918            $dst.write_all(b" ")?;
919        }
920    }};
921}
922
923#[macro_export]
924#[doc(hidden)]
925macro_rules! flags {
926    ($app:expr, $how:ident) => {{
927        $app.args
928            .args
929            .$how()
930            .filter(|a| !a.is_set($crate::ArgSettings::TakesValue) && a.index.is_none())
931            .filter(|a| !a.help_heading.is_some())
932    }};
933    ($app:expr) => {
934        $crate::flags!($app, iter)
935    };
936}
937
938#[macro_export]
939#[doc(hidden)]
940macro_rules! opts {
941    ($app:expr, $how:ident) => {{
942        $app.args
943            .args
944            .$how()
945            .filter(|a| a.is_set($crate::ArgSettings::TakesValue) && a.index.is_none())
946            .filter(|a| !a.help_heading.is_some())
947    }};
948    ($app:expr) => {
949        opts!($app, iter)
950    };
951}
952
953#[macro_export]
954#[doc(hidden)]
955macro_rules! positionals {
956    ($app:expr, $how:ident) => {{
957        $app.args
958            .args
959            .$how()
960            .filter(|a| !(a.short.is_some() || a.long.is_some()))
961    }};
962    ($app:expr) => {
963        positionals!($app, iter)
964    };
965}
966
967#[macro_export]
968#[doc(hidden)]
969macro_rules! subcommands {
970    ($app:expr, $how:ident) => {
971        $app.subcommands.$how()
972    };
973    ($app:expr) => {
974        subcommands!($app, iter)
975    };
976}
977
978macro_rules! groups_for_arg {
979    ($app:expr, $grp:expr) => {{
980        debugln!("Parser::groups_for_arg: name={}", $grp);
981        $app.groups
982            .iter()
983            .filter(|grp| grp.args.iter().any(|&a| a == $grp))
984            .map(|grp| grp.id)
985    }};
986}
987
988macro_rules! find_subcmd_cloned {
989    ($app:expr, $sc:expr) => {{
990        subcommands!($app)
991            .cloned()
992            .find(|a| match_alias!(a, $sc, &*a.name))
993    }};
994}
995
996#[macro_export]
997#[doc(hidden)]
998macro_rules! find_subcmd {
999    ($app:expr, $sc:expr, $how:ident) => {{
1000        subcommands!($app, $how).find(|a| match_alias!(a, $sc, &*a.name))
1001    }};
1002    ($app:expr, $sc:expr) => {
1003        find_subcmd!($app, $sc, iter)
1004    };
1005}
1006
1007macro_rules! longs {
1008    ($app:expr, $how:ident) => {{
1009        use crate::mkeymap::KeyType;
1010        $app.args.keys.iter().map(|x| &x.key).filter_map(|a| {
1011            if let KeyType::Long(v) = a {
1012                Some(v)
1013            } else {
1014                None
1015            }
1016        })
1017    }};
1018    ($app:expr) => {
1019        longs!($app, iter)
1020    };
1021}
1022
1023#[macro_export]
1024#[doc(hidden)]
1025macro_rules! names {
1026    (@args $app:expr) => {{
1027        $app.args.args.iter().map(|a| &*a.name)
1028    }};
1029    (@sc $app:expr) => {{
1030        $app.subcommands.iter().map(|s| &*s.name).chain(
1031            $app.subcommands
1032                .iter()
1033                .filter(|s| s.aliases.is_some())
1034                .flat_map(|s| s.aliases.as_ref().unwrap().iter().map(|&(n, _)| n)),
1035        )
1036    }};
1037}
1038
1039#[macro_export]
1040#[doc(hidden)]
1041macro_rules! sc_names {
1042    ($app:expr) => {{
1043        names!(@sc $app)
1044    }};
1045}
1046
1047#[macro_export]
1048#[doc(hidden)]
1049macro_rules! match_alias {
1050    ($a:expr, $to:expr, $what:expr) => {{
1051        $what == $to
1052            || ($a.aliases.is_some()
1053                && $a
1054                    .aliases
1055                    .as_ref()
1056                    .unwrap()
1057                    .iter()
1058                    .any(|alias| alias.0 == $to))
1059    }};
1060}