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
//! Derive method that returns each variant of an enum
//!
//! # Sample usage
//!
//! ```rust
//! #[macro_use]
//! extern crate enum_each_variant_derive;
//!
//! # fn main() {
//! #[derive(EachVariant, Eq, PartialEq, Debug)]
//! enum Thing {
//!     One,
//!     Two,
//!     Three,
//!     Four,
//! }
//!
//! let all: Vec<Thing> = Thing::all_variants();
//!
//! assert_eq!(all, vec![Thing::One, Thing::Two, Thing::Three, Thing::Four]);
//! # }
//! ```
//!
//! # Gotcha
//!
//! Only works on enums where no variants have associated values. So we wouldn't be able to use it
//! for this enum:
//!
//! ```rust
//! # fn main() {
//! enum TrainStatus {
//!     OnTime,
//!     DelayedBy(std::time::Duration),
//! }
//! # }
//! ```

extern crate proc_macro;
extern crate syn;

#[macro_use]
extern crate quote;

use proc_macro::TokenStream;
use syn::*;

#[doc(hidden)]
#[proc_macro_derive(EachVariant)]
pub fn each_variant(input: TokenStream) -> TokenStream {
    let input: DeriveInput = parse(input).unwrap();
    let expanded = impl_enum_each(input);
    expanded.into()
}

fn impl_enum_each(ast: DeriveInput) -> quote::Tokens {
    let name: &Ident = &ast.ident;

    let enum_data: DataEnum = match ast.data {
        Data::Enum(data) => data,
        _ => panic!("#[derive(EachVariant)] is only defined for enums"),
    };

    let variants = enum_data.variants;
    let variant_names = variants.iter().map(|ref variant| {
        match variant.fields {
            Fields::Unit => {}
            _ => {
                panic!("#[derive(EachVariant)] is only defined on enums where all the variants have no associated values");
            }
        };

        variant.ident
    });

    let push_variants = variant_names
        .map(|variant_name| {
            quote! { acc.push(#name::#variant_name); }
        });

    quote! {
        impl #name {
            /// Build vector containing each variant of this enum
            pub fn all_variants() -> Vec<Self> {
                let mut acc: Vec<Self> = vec![];
                #(#push_variants);*
                acc
            }
        }
    }
}