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
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#![no_std]
#![cfg_attr(feature = "external_doc", feature(external_doc))]
#![cfg_attr(feature = "external_doc", doc(include = "../README.md"))]

extern crate proc_macro;
extern crate proc_macro2;
extern crate alloc;

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Data, DeriveInput};
use alloc::{format, vec, vec::Vec, boxed::Box, string::String};

macro_rules! die {
    ($ident:expr, $($reason:expr),+) => {{
        let message = format!("Can't generate num_enum traits for {} because {}.", $ident, format!($($reason),+));
        panic!("{}", message);
    }}
}

#[proc_macro_derive(IntoPrimitive)]
pub fn derive_into_primitive(stream: TokenStream) -> TokenStream {
    let input = parse_macro_input!(stream as DeriveInput);
    let enum_info = parse_enum(input);

    let name = enum_info.name;
    let repr = enum_info.repr;

    let expanded = quote! {
        impl From<#name> for #repr {
            fn from(number: #name) -> Self {
                number as Self
            }
        }
    };

    TokenStream::from(expanded)
}

#[proc_macro_derive(TryFromPrimitive)]
pub fn derive_try_from_primitive(stream: TokenStream) -> TokenStream {
    let input = parse_macro_input!(stream as DeriveInput);
    let enum_info = parse_enum(input);

    let TryIntoEnumInfo {
        name,
        repr,
        match_const_names,
        match_const_exprs,
        enum_keys,
        no_match_message,
        ..
    } = TryIntoEnumInfo::from(enum_info);

    let match_const_names2 = match_const_names.clone();
    let repeated_repr = core::iter::repeat(repr.clone()).take(enum_keys.len());
    let repeated_name = core::iter::repeat(name.clone()).take(enum_keys.len());

    let expanded = quote! {
        impl ::core::convert::TryFrom<#repr> for #name {
            type Error=String;

            fn try_from(number: #repr) -> Result<Self, String> {
                #( const #match_const_names: #repeated_repr = #match_const_exprs; )*

                match number {
                    #( #match_const_names2 => Ok(#repeated_name::#enum_keys), )*
                    _ => Err(format!(#no_match_message, number)),
                }
            }
        }
    };

    TokenStream::from(expanded)
}

struct EnumInfo {
    name: syn::Ident,
    repr: proc_macro2::Ident,
    value_expressions_to_enum_keys: Vec<(syn::Expr, syn::Ident)>,
}

fn parse_enum(input: DeriveInput) -> EnumInfo {
    let mut repr = None;
    for attr in input.attrs {
        if attr.path.segments.len() == 1
            && format!("{}", attr.path.segments.first().unwrap().value().ident) == "repr"
        {
            let tokens: Vec<proc_macro2::TokenTree> = attr.tts.into_iter().collect();
            if tokens.len() == 1 {
                if let proc_macro2::TokenTree::Group(ref group) = tokens[0] {
                    match group.stream().into_iter().next().unwrap() {
                        proc_macro2::TokenTree::Ident(ident) => {
                            if &format!("{}", ident) == "C" {
                                die!(
                                    input.ident,
                                    "it has repr(C), which doesn't have a generally defined size"
                                )
                            }
                            repr = Some(ident);
                            break;
                        }
                        val => {
                            die!(input.ident, "it had unexpected repr: {}", val);
                        }
                    }
                }
            }
        }
    }

    let mut variants = vec![];

    let mut next_discriminant = literal(0);

    if let Data::Enum(data) = input.data {
        for variant in data.variants {
            let disc = if let Some(d) = variant.discriminant {
                d.1
            } else {
                next_discriminant
            };
            next_discriminant = syn::Expr::Binary(syn::ExprBinary {
                attrs: vec![],
                left: Box::new(disc.clone()),
                op: syn::BinOp::Add(syn::token::Add {
                    spans: [proc_macro2::Span::call_site()],
                }),
                right: Box::new(literal(1)),
            });
            variants.push((disc, variant.ident.clone()));
        }
    } else {
        die!(input.ident, "it was not an enum");
    }
    if let Some(repr) = repr {
        EnumInfo {
            name: input.ident,
            repr: repr,
            value_expressions_to_enum_keys: variants,
        }
    } else {
        die!(input.ident, "it does not have a valid `#[repr]` attribute");
    }
}

fn literal(i: u64) -> syn::Expr {
    syn::Expr::Lit(syn::ExprLit {
        attrs: vec![],
        lit: syn::Lit::Int(syn::LitInt::new(
            i,
            syn::IntSuffix::None,
            proc_macro2::Span::call_site(),
        )),
    })
}

struct TryIntoEnumInfo {
    name: proc_macro2::Ident,
    repr: proc_macro2::Ident,
    match_const_names: Vec<proc_macro2::Ident>,
    match_const_exprs: Vec<syn::Expr>,
    enum_keys: Vec<proc_macro2::Ident>,
    no_match_message: String,
}

impl TryIntoEnumInfo {
    fn from(enum_info: EnumInfo) -> TryIntoEnumInfo {
        let mut match_const_names =
            Vec::with_capacity(enum_info.value_expressions_to_enum_keys.len());
        let mut match_const_exprs =
            Vec::with_capacity(enum_info.value_expressions_to_enum_keys.len());
        let mut enum_keys = Vec::with_capacity(enum_info.value_expressions_to_enum_keys.len());

        for (enum_value_expression, enum_key) in enum_info.value_expressions_to_enum_keys {
            // Use an intermediate const so that enums defined like `Two = ONE + 1u8` work properly.
            let match_const = format!("__num_enum_match_{}", enum_key);
            match_const_names.push(proc_macro2::Ident::new(
                &match_const,
                proc_macro2::Span::call_site(),
            ));
            match_const_exprs.push(enum_value_expression.clone());
            enum_keys.push(enum_key);
        }

        let no_match_message = format!("No value in enum {} for value {{}}", enum_info.name);

        TryIntoEnumInfo {
            name: enum_info.name,
            repr: enum_info.repr,
            match_const_names: match_const_names,
            match_const_exprs: match_const_exprs,
            enum_keys: enum_keys,
            no_match_message: no_match_message,
        }
    }
}