unic_cli/
clap_macros.rs

1// Copyright 2017 The UNIC Project Developers.
2//
3// See the COPYRIGHT file at the top-level directory of this distribution.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11#[macro_export]
12macro_rules! unic_arg_enum {
13    (@as_item $($i:item)*) => ($($i)*);
14
15    (@impls ( $($tts:tt)* ) -> ($e:ident, $($v:ident),+)) => {
16        unic_arg_enum!(@as_item
17        $($tts)*
18
19        impl ::std::str::FromStr for $e {
20            type Err = String;
21
22            fn from_str(s: &str) -> ::std::result::Result<Self,Self::Err> {
23                match s {
24                    $(stringify!($v) |
25                    _ if s.replace("-", "").eq_ignore_ascii_case(stringify!($v)) => Ok($e::$v)),+,
26                    _ => Err({
27                        let v = vec![
28                            $(stringify!($v),)+
29                        ];
30                        format!("valid values: {}",
31                            v.join(" ,"))
32                    }),
33                }
34            }
35        }
36        impl ::std::fmt::Display for $e {
37            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
38                match *self {
39                    $($e::$v => write!(f, stringify!($v)),)+
40                }
41            }
42        }
43        impl $e {
44            #[allow(dead_code)]
45            pub fn variants() -> [&'static str; _clap_count_exprs!($(stringify!($v)),+)] {
46                [
47                    $(stringify!($v),)+
48                ]
49            }
50        });
51    };
52
53    ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
54        unic_arg_enum!(@impls
55            ($(#[$($m),+])+
56            pub enum $e {
57                $($v$(=$val)*),+
58            }) -> ($e, $($v),+)
59        );
60    };
61
62    ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*),+  } ) => {
63        unic_arg_enum!(@impls
64            ($(#[$($m),+])+
65            enum $e {
66                $($v$(=$val)*),+
67            }) -> ($e, $($v),+)
68        );
69    };
70
71    (pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
72        unic_arg_enum!(@impls
73            (pub enum $e {
74                $($v$(=$val)*),+
75            }) -> ($e, $($v),+)
76        );
77    };
78
79    (enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
80        unic_arg_enum!(@impls
81            (enum $e {
82                $($v$(=$val)*),+
83            }) -> ($e, $($v),+)
84        );
85    };
86}