• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! [![github]](https://github.com/dtolnay/enumn) [![crates-io]](https://crates.io/crates/enumn) [![docs-rs]](https://docs.rs/enumn)
2 //!
3 //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4 //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5 //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
6 //!
7 //! <br>
8 //!
9 //! Convert number to enum.
10 //!
11 //! This crate provides a derive macro to generate a function for converting a
12 //! primitive integer into the corresponding variant of an enum.
13 //!
14 //! The generated function is named `n` and has the following signature:
15 //!
16 //! ```
17 //! # const IGNORE: &str = stringify! {
18 //! impl YourEnum {
19 //!     pub fn n(value: Repr) -> Option<Self>;
20 //! }
21 //! # };
22 //! ```
23 //!
24 //! where `Repr` is an integer type of the right size as described in more
25 //! detail below.
26 //!
27 //! # Example
28 //!
29 //! ```
30 //! use enumn::N;
31 //!
32 //! #[derive(PartialEq, Debug, N)]
33 //! enum Status {
34 //!     LegendaryTriumph,
35 //!     QualifiedSuccess,
36 //!     FortuitousRevival,
37 //!     IndeterminateStalemate,
38 //!     RecoverableSetback,
39 //!     DireMisadventure,
40 //!     AbjectFailure,
41 //! }
42 //!
43 //! fn main() {
44 //!     let s = Status::n(1);
45 //!     assert_eq!(s, Some(Status::QualifiedSuccess));
46 //!
47 //!     let s = Status::n(9);
48 //!     assert_eq!(s, None);
49 //! }
50 //! ```
51 //!
52 //! # Signature
53 //!
54 //! The generated signature depends on whether the enum has a `#[repr(..)]`
55 //! attribute. If a `repr` is specified, the input to `n` will be required to be
56 //! of that type.
57 //!
58 //! ```
59 //! #[derive(enumn::N)]
60 //! # enum E0 {
61 //! #     IGNORE
62 //! # }
63 //! #
64 //! #[repr(u8)]
65 //! enum E {
66 //!     /* ... */
67 //!     # IGNORE
68 //! }
69 //!
70 //! // expands to:
71 //! impl E {
72 //!     pub fn n(value: u8) -> Option<Self> {
73 //!         /* ... */
74 //!         # unimplemented!()
75 //!     }
76 //! }
77 //! ```
78 //!
79 //! On the other hand if no `repr` is specified then we get a signature that is
80 //! generic over a variety of possible types.
81 //!
82 //! ```
83 //! # enum E {}
84 //! #
85 //! impl E {
86 //!     pub fn n<REPR: Into<i64>>(value: REPR) -> Option<Self> {
87 //!         /* ... */
88 //!         # unimplemented!()
89 //!     }
90 //! }
91 //! ```
92 //!
93 //! # Discriminants
94 //!
95 //! The conversion respects explictly specified enum discriminants. Consider
96 //! this enum:
97 //!
98 //! ```
99 //! #[derive(enumn::N)]
100 //! enum Letter {
101 //!     A = 65,
102 //!     B = 66,
103 //! }
104 //! ```
105 //!
106 //! Here `Letter::n(65)` would return `Some(Letter::A)`.
107 
108 #![allow(
109     clippy::missing_panics_doc,
110     clippy::needless_doctest_main,
111     clippy::single_match_else
112 )]
113 
114 extern crate proc_macro;
115 
116 use proc_macro::TokenStream;
117 use quote::quote;
118 use syn::{parse_macro_input, Data, DeriveInput, Error, Fields, Ident};
119 
120 #[proc_macro_derive(N)]
derive(input: TokenStream) -> TokenStream121 pub fn derive(input: TokenStream) -> TokenStream {
122     let input = parse_macro_input!(input as DeriveInput);
123 
124     let variants = match input.data {
125         Data::Enum(data) => data.variants,
126         Data::Struct(_) | Data::Union(_) => panic!("input must be an enum"),
127     };
128 
129     for variant in &variants {
130         match variant.fields {
131             Fields::Unit => {}
132             Fields::Named(_) | Fields::Unnamed(_) => {
133                 let span = variant.ident.span();
134                 let err = Error::new(span, "enumn: variant with data is not supported");
135                 return err.to_compile_error().into();
136             }
137         }
138     }
139 
140     // Parse repr attribute like #[repr(u16)].
141     let mut repr = None;
142     for attr in input.attrs {
143         if attr.path.is_ident("repr") {
144             if let Ok(name) = attr.parse_args::<Ident>() {
145                 match name.to_string().as_str() {
146                     "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32"
147                     | "i64" | "i128" | "isize" => {
148                         repr = Some(quote!(#name));
149                     }
150                     _ => {}
151                 }
152             }
153         }
154     }
155 
156     let signature;
157     let value;
158     match repr {
159         Some(ref repr) => {
160             signature = quote! {
161                 fn n(value: #repr)
162             };
163             value = quote!(value);
164         }
165         None => {
166             repr = Some(quote!(i64));
167             signature = quote! {
168                 fn n<REPR: Into<i64>>(value: REPR)
169             };
170             value = quote! {
171                 <REPR as Into<i64>>::into(value)
172             };
173         }
174     }
175 
176     let ident = input.ident;
177     let declare_discriminants = variants.iter().map(|variant| {
178         let variant = &variant.ident;
179         quote! {
180             const #variant: #repr = #ident::#variant as #repr;
181         }
182     });
183     let match_discriminants = variants.iter().map(|variant| {
184         let variant = &variant.ident;
185         quote! {
186             discriminant::#variant => Some(#ident::#variant),
187         }
188     });
189 
190     TokenStream::from(quote! {
191         impl #ident {
192             pub #signature -> Option<Self> {
193                 struct discriminant;
194                 #[allow(non_upper_case_globals)]
195                 impl discriminant {
196                     #(#declare_discriminants)*
197                 }
198                 match #value {
199                     #(#match_discriminants)*
200                     _ => None,
201                 }
202             }
203         }
204     })
205 }
206