| 1 | /* |
| 2 | Copyright ⓒ 2015 macro-attr contributors. |
| 3 | |
| 4 | Licensed under the MIT license (see LICENSE or <http://opensource.org |
| 5 | /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of |
| 6 | <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All |
| 7 | files in the project carrying such notice may not be copied, modified, |
| 8 | or distributed except according to those terms. |
| 9 | */ |
| 10 | #[macro_use] extern crate macro_attr; |
| 11 | |
| 12 | macro_rules! EnumIterator { |
| 13 | (() $(pub)* enum $name:ident { $($body:tt)* }) => { |
| 14 | EnumIterator! { |
| 15 | @collect_variants ($name), |
| 16 | ($($body)*,) -> () |
| 17 | } |
| 18 | }; |
| 19 | |
| 20 | ( |
| 21 | @collect_variants ($name:ident), |
| 22 | ($(,)*) -> ($($var_names:ident,)*) |
| 23 | ) => { |
| 24 | type NameIter = ::std::vec::IntoIter<&'static str>; |
| 25 | type VariantIter = ::std::vec::IntoIter<$name>; |
| 26 | |
| 27 | impl $name { |
| 28 | #[allow(dead_code)] |
| 29 | pub fn iter_variants() -> VariantIter { |
| 30 | vec![$($name::$var_names),*].into_iter() |
| 31 | } |
| 32 | |
| 33 | #[allow(dead_code)] |
| 34 | pub fn iter_variant_names() -> NameIter { |
| 35 | vec![$(stringify!($var_names)),*].into_iter() |
| 36 | } |
| 37 | } |
| 38 | }; |
| 39 | |
| 40 | ( |
| 41 | @collect_variants $fixed:tt, |
| 42 | ($var:ident $(= $_val:expr)*, $($tail:tt)*) -> ($($var_names:tt)*) |
| 43 | ) => { |
| 44 | EnumIterator! { |
| 45 | @collect_variants $fixed, |
| 46 | ($($tail)*) -> ($($var_names)* $var,) |
| 47 | } |
| 48 | }; |
| 49 | |
| 50 | ( |
| 51 | @collect_variants ($name:ident), |
| 52 | ($var:ident $_struct:tt, $($tail:tt)*) -> ($($var_names:tt)*) |
| 53 | ) => { |
| 54 | const _error: () = concat!( |
| 55 | "cannot derive EnumIterator for ", |
| 56 | stringify!($name), |
| 57 | ", due to non-unitary variant ", |
| 58 | stringify!($var), |
| 59 | "." |
| 60 | ); |
| 61 | }; |
| 62 | } |
| 63 | |
| 64 | macro_attr! { |
| 65 | #[derive(Debug, PartialEq, EnumIterator!)] |
| 66 | enum Get { Up, Down, AllAround } |
| 67 | } |
| 68 | |
| 69 | #[test] |
| 70 | fn test_enum_iterator() { |
| 71 | let vs: Vec<_> = Get::iter_variant_names().zip(Get::iter_variants()).collect(); |
| 72 | assert_eq!(&*vs, &[("Up", Get::Up), ("Down", Get::Down), ("AllAround", Get::AllAround)]); |
| 73 | } |