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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// Copyright (c) 2017 Doug Goldstein <cardoe@cardoe.com>

// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// “Software”), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

//! This crate provides a custom derive `Primitive` that helps people
//! providing native Rust bindings to C code by allowing a C-like `enum`
//! declaration to convert to its primitve values and back from them. You
//! can selectively include `num_traits::ToPrimitive` and
//! `num_traits::FromPrimitive` to get these features.
//!
//! # Example
//!
//! ```rust
//! use enum_primitive_derive::Primitive;
//! use num_traits::{FromPrimitive, ToPrimitive};
//!
//! #[derive(Debug, Eq, PartialEq, Primitive)]
//! enum Foo {
//!     Bar = 32,
//!     Dead = 42,
//!     Beef = 50,
//! }
//!
//! fn main() {
//!     assert_eq!(Foo::from_i32(32), Some(Foo::Bar));
//!     assert_eq!(Foo::from_i32(42), Some(Foo::Dead));
//!     assert_eq!(Foo::from_i64(50), Some(Foo::Beef));
//!     assert_eq!(Foo::from_isize(17), None);
//!
//!     let bar = Foo::Bar;
//!     assert_eq!(bar.to_i32(), Some(32));
//!
//!     let dead = Foo::Dead;
//!     assert_eq!(dead.to_isize(), Some(42));
//! }
//! ```
//!
//! # Complex Example
//!
//! ```rust
//! use enum_primitive_derive::Primitive;
//! use num_traits::{FromPrimitive, ToPrimitive};
//!
//! pub const ABC: ::std::os::raw::c_uint = 1;
//! pub const DEF: ::std::os::raw::c_uint = 2;
//! pub const GHI: ::std::os::raw::c_uint = 4;
//!
//! #[derive(Clone, Copy, Debug, Eq, PartialEq, Primitive)]
//! enum BindGenLike {
//!     ABC = ABC as isize,
//!     DEF = DEF as isize,
//!     GHI = GHI as isize,
//! }
//!
//! fn main() {
//!     assert_eq!(BindGenLike::from_isize(4), Some(BindGenLike::GHI));
//!     assert_eq!(BindGenLike::from_u32(2), Some(BindGenLike::DEF));
//!     assert_eq!(BindGenLike::from_u32(8), None);
//!
//!     let abc = BindGenLike::ABC;
//!     assert_eq!(abc.to_u32(), Some(1));
//! }
//! ```
//!
//! # TryFrom Example
//!
//! ```rust
//! use enum_primitive_derive::Primitive;
//! use core::convert::TryFrom;
//!
//! #[derive(Debug, Eq, PartialEq, Primitive)]
//! enum Foo {
//!     Bar = 32,
//!     Dead = 42,
//!     Beef = 50,
//! }
//!
//! fn main() {
//!     let bar = Foo::try_from(32);
//!     assert_eq!(bar, Ok(Foo::Bar));
//!
//!     let dead = Foo::try_from(42);
//!     assert_eq!(dead, Ok(Foo::Dead));
//!
//!     let unknown = Foo::try_from(12);
//!     assert!(unknown.is_err());
//! }
//! ```

extern crate proc_macro;

use proc_macro::TokenStream;

/// Provides implementation of `num_traits::ToPrimitive` and
/// `num_traits::FromPrimitive`
#[proc_macro_derive(Primitive)]
pub fn primitive(input: TokenStream) -> TokenStream {
    let ast = syn::parse_macro_input!(input as syn::DeriveInput);
    impl_primitive(&ast)
}

fn impl_primitive(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;

    // Check if derive(Primitive) was specified for a struct
    if let syn::Data::Enum(ref variant) = ast.data {
        let (var_u64, dis_u64): (Vec<_>, Vec<_>) = variant
            .variants
            .iter()
            .map(|v| {
                match v.fields {
                    syn::Fields::Unit => (),
                    _ => panic!("#[derive(Primitive) can only operate on C-like enums"),
                }
                if v.discriminant.is_none() {
                    panic!(
                        "#[derive(Primitive) requires C-like enums with \
                       discriminants for all enum variants"
                    );
                }

                let discrim = match v.discriminant.clone().map(|(_eq, expr)| expr).unwrap() {
                    syn::Expr::Cast(real) => *real.expr,
                    orig => orig,
                };
                (v.ident.clone(), discrim)
            })
            .unzip();

        // quote!{} needs this to be a vec since its in #( )*
        let enum_u64 = vec![name.clone(); variant.variants.len()];

        // can't reuse variables in quote!{} body
        let var_i64 = var_u64.clone();
        let dis_i64 = dis_u64.clone();
        let enum_i64 = enum_u64.clone();

        let to_name = name.clone();
        let to_enum_u64 = enum_u64.clone();
        let to_var_u64 = var_u64.clone();
        let to_dis_u64 = dis_u64.clone();

        let to_enum_i64 = enum_u64.clone();
        let to_var_i64 = var_u64.clone();
        let to_dis_i64 = dis_u64.clone();

        TokenStream::from(quote::quote! {
            impl ::num_traits::FromPrimitive for #name {
                fn from_u64(val: u64) -> Option<Self> {
                    match val as _ {
                        #( #dis_u64 => Some(#enum_u64::#var_u64), )*
                        _ => None,
                    }
                }

                fn from_i64(val: i64) -> Option<Self> {
                    match val as _ {
                        #( #dis_i64 => Some(#enum_i64::#var_i64), )*
                        _ => None,
                    }
                }
            }

            impl ::num_traits::ToPrimitive for #to_name {
                fn to_u64(&self) -> Option<u64> {
                    match *self {
                        #( #to_enum_u64::#to_var_u64 => Some(#to_dis_u64 as u64), )*
                    }
                }

                fn to_i64(&self) -> Option<i64> {
                    match *self {
                        #( #to_enum_i64::#to_var_i64 => Some(#to_dis_i64 as i64), )*
                    }
                }
            }

            impl ::core::convert::TryFrom<u64> for #to_name {
                type Error = &'static str;

                fn try_from(value: u64) -> Result<Self, Self::Error> {
                    use ::num_traits::FromPrimitive;

                    #to_name::from_u64(value).ok_or_else(|| "Unknown variant")
                }
            }

            impl ::core::convert::TryFrom<u32> for #to_name {
                type Error = &'static str;

                fn try_from(value: u32) -> Result<Self, Self::Error> {
                    use ::num_traits::FromPrimitive;

                    #to_name::from_u32(value).ok_or_else(|| "Unknown variant")
                }
            }

            impl ::core::convert::TryFrom<u16> for #to_name {
                type Error = &'static str;

                fn try_from(value: u16) -> Result<Self, Self::Error> {
                    use ::num_traits::FromPrimitive;

                    #to_name::from_u16(value).ok_or_else(|| "Unknown variant")
                }
            }

            impl ::core::convert::TryFrom<u8> for #to_name {
                type Error = &'static str;

                fn try_from(value: u8) -> Result<Self, Self::Error> {
                    use ::num_traits::FromPrimitive;

                    #to_name::from_u8(value).ok_or_else(|| "Unknown variant")
                }
            }

            impl ::core::convert::TryFrom<i64> for #name {
                type Error = &'static str;

                fn try_from(value: i64) -> Result<Self, Self::Error> {
                    use ::num_traits::FromPrimitive;

                    #to_name::from_i64(value).ok_or_else(|| "Unknown variant")
                }
            }

            impl ::core::convert::TryFrom<i32> for #name {
                type Error = &'static str;

                fn try_from(value: i32) -> Result<Self, Self::Error> {
                    use ::num_traits::FromPrimitive;

                    #to_name::from_i32(value).ok_or_else(|| "Unknown variant")
                }
            }

            impl ::core::convert::TryFrom<i16> for #name {
                type Error = &'static str;

                fn try_from(value: i16) -> Result<Self, Self::Error> {
                    use ::num_traits::FromPrimitive;

                    #to_name::from_i16(value).ok_or_else(|| "Unknown variant")
                }
            }

            impl ::core::convert::TryFrom<i8> for #name {
                type Error = &'static str;

                fn try_from(value: i8) -> Result<Self, Self::Error> {
                    use ::num_traits::FromPrimitive;

                    #to_name::from_i8(value).ok_or_else(|| "Unknown variant")
                }
            }
        })
    } else {
        panic!("#[derive(Primitive)] is only valid for C-like enums");
    }
}