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