num_enum_derive/lib.rs
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 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
// Not supported by MSRV
#![allow(clippy::uninlined_format_args)]
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::{parse_macro_input, Expr, Ident};
mod enum_attributes;
mod parsing;
use parsing::{get_crate_name, EnumInfo};
mod utils;
mod variant_attributes;
/// Implements `Into<Primitive>` for a `#[repr(Primitive)] enum`.
///
/// (It actually implements `From<Enum> for Primitive`)
///
/// ## Allows turning an enum into a primitive.
///
/// ```rust
/// use num_enum::IntoPrimitive;
///
/// #[derive(IntoPrimitive)]
/// #[repr(u8)]
/// enum Number {
/// Zero,
/// One,
/// }
///
/// let zero: u8 = Number::Zero.into();
/// assert_eq!(zero, 0u8);
/// ```
#[proc_macro_derive(IntoPrimitive, attributes(num_enum, catch_all))]
pub fn derive_into_primitive(input: TokenStream) -> TokenStream {
let enum_info = parse_macro_input!(input as EnumInfo);
let catch_all = enum_info.catch_all();
let name = &enum_info.name;
let repr = &enum_info.repr;
let body = if let Some(catch_all_ident) = catch_all {
quote! {
match enum_value {
#name::#catch_all_ident(raw) => raw,
rest => unsafe { *(&rest as *const #name as *const Self) }
}
}
} else {
quote! { enum_value as Self }
};
TokenStream::from(quote! {
impl From<#name> for #repr {
#[inline]
fn from (enum_value: #name) -> Self
{
#body
}
}
})
}
/// Implements `From<Primitive>` for a `#[repr(Primitive)] enum`.
///
/// Turning a primitive into an enum with `from`.
/// ----------------------------------------------
///
/// ```rust
/// use num_enum::FromPrimitive;
///
/// #[derive(Debug, Eq, PartialEq, FromPrimitive)]
/// #[repr(u8)]
/// enum Number {
/// Zero,
/// #[num_enum(default)]
/// NonZero,
/// }
///
/// let zero = Number::from(0u8);
/// assert_eq!(zero, Number::Zero);
///
/// let one = Number::from(1u8);
/// assert_eq!(one, Number::NonZero);
///
/// let two = Number::from(2u8);
/// assert_eq!(two, Number::NonZero);
/// ```
#[proc_macro_derive(FromPrimitive, attributes(num_enum, default, catch_all))]
pub fn derive_from_primitive(input: TokenStream) -> TokenStream {
let enum_info: EnumInfo = parse_macro_input!(input);
let krate = Ident::new(&get_crate_name(), Span::call_site());
let is_naturally_exhaustive = enum_info.is_naturally_exhaustive();
let catch_all_body = match is_naturally_exhaustive {
Ok(is_naturally_exhaustive) => {
if is_naturally_exhaustive {
quote! { unreachable!("exhaustive enum") }
} else if let Some(default_ident) = enum_info.default() {
quote! { Self::#default_ident }
} else if let Some(catch_all_ident) = enum_info.catch_all() {
quote! { Self::#catch_all_ident(number) }
} else {
let span = Span::call_site();
let message =
"#[derive(num_enum::FromPrimitive)] requires enum to be exhaustive, or a variant marked with `#[default]`, `#[num_enum(default)]`, or `#[num_enum(catch_all)`";
return syn::Error::new(span, message).to_compile_error().into();
}
}
Err(err) => {
return err.to_compile_error().into();
}
};
let EnumInfo {
ref name, ref repr, ..
} = enum_info;
let variant_idents: Vec<Ident> = enum_info.variant_idents();
let expression_idents: Vec<Vec<Ident>> = enum_info.expression_idents();
let variant_expressions: Vec<Vec<Expr>> = enum_info.variant_expressions();
debug_assert_eq!(variant_idents.len(), variant_expressions.len());
TokenStream::from(quote! {
impl ::#krate::FromPrimitive for #name {
type Primitive = #repr;
fn from_primitive(number: Self::Primitive) -> Self {
// Use intermediate const(s) so that enums defined like
// `Two = ONE + 1u8` work properly.
#![allow(non_upper_case_globals)]
#(
#(
const #expression_idents: #repr = #variant_expressions;
)*
)*
#[deny(unreachable_patterns)]
match number {
#(
#( #expression_idents )|*
=> Self::#variant_idents,
)*
#[allow(unreachable_patterns)]
_ => #catch_all_body,
}
}
}
impl ::core::convert::From<#repr> for #name {
#[inline]
fn from (
number: #repr,
) -> Self {
::#krate::FromPrimitive::from_primitive(number)
}
}
#[doc(hidden)]
impl ::#krate::CannotDeriveBothFromPrimitiveAndTryFromPrimitive for #name {}
})
}
/// Implements `TryFrom<Primitive>` for a `#[repr(Primitive)] enum`.
///
/// Attempting to turn a primitive into an enum with `try_from`.
/// ----------------------------------------------
///
/// ```rust
/// use num_enum::TryFromPrimitive;
/// use std::convert::TryFrom;
///
/// #[derive(Debug, Eq, PartialEq, TryFromPrimitive)]
/// #[repr(u8)]
/// enum Number {
/// Zero,
/// One,
/// }
///
/// let zero = Number::try_from(0u8);
/// assert_eq!(zero, Ok(Number::Zero));
///
/// let three = Number::try_from(3u8);
/// assert_eq!(
/// three.unwrap_err().to_string(),
/// "No discriminant in enum `Number` matches the value `3`",
/// );
/// ```
#[proc_macro_derive(TryFromPrimitive, attributes(num_enum))]
pub fn derive_try_from_primitive(input: TokenStream) -> TokenStream {
let enum_info: EnumInfo = parse_macro_input!(input);
let krate = Ident::new(&get_crate_name(), Span::call_site());
let EnumInfo {
ref name,
ref repr,
ref error_type_info,
..
} = enum_info;
let variant_idents: Vec<Ident> = enum_info.variant_idents();
let expression_idents: Vec<Vec<Ident>> = enum_info.expression_idents();
let variant_expressions: Vec<Vec<Expr>> = enum_info.variant_expressions();
debug_assert_eq!(variant_idents.len(), variant_expressions.len());
let error_type = &error_type_info.name;
let error_constructor = &error_type_info.constructor;
TokenStream::from(quote! {
impl ::#krate::TryFromPrimitive for #name {
type Primitive = #repr;
type Error = #error_type;
const NAME: &'static str = stringify!(#name);
fn try_from_primitive (
number: Self::Primitive,
) -> ::core::result::Result<
Self,
#error_type
> {
// Use intermediate const(s) so that enums defined like
// `Two = ONE + 1u8` work properly.
#![allow(non_upper_case_globals)]
#(
#(
const #expression_idents: #repr = #variant_expressions;
)*
)*
#[deny(unreachable_patterns)]
match number {
#(
#( #expression_idents )|*
=> ::core::result::Result::Ok(Self::#variant_idents),
)*
#[allow(unreachable_patterns)]
_ => ::core::result::Result::Err(
#error_constructor ( number )
),
}
}
}
impl ::core::convert::TryFrom<#repr> for #name {
type Error = #error_type;
#[inline]
fn try_from (
number: #repr,
) -> ::core::result::Result<Self, #error_type>
{
::#krate::TryFromPrimitive::try_from_primitive(number)
}
}
#[doc(hidden)]
impl ::#krate::CannotDeriveBothFromPrimitiveAndTryFromPrimitive for #name {}
})
}
/// Generates a `unsafe fn unchecked_transmute_from(number: Primitive) -> Self`
/// associated function.
///
/// Allows unsafely turning a primitive into an enum with unchecked_transmute_from
/// ------------------------------------------------------------------------------
///
/// If you're really certain a conversion will succeed, and want to avoid a small amount of overhead, you can use unsafe
/// code to do this conversion. Unless you have data showing that the match statement generated in the `try_from` above is a
/// bottleneck for you, you should avoid doing this, as the unsafe code has potential to cause serious memory issues in
/// your program.
///
/// Note that this derive ignores any `default`, `catch_all`, and `alternatives` attributes on the enum.
/// If you need support for conversions from these values, you should use `TryFromPrimitive` or `FromPrimitive`.
///
/// ```rust
/// use num_enum::UnsafeFromPrimitive;
///
/// #[derive(Debug, Eq, PartialEq, UnsafeFromPrimitive)]
/// #[repr(u8)]
/// enum Number {
/// Zero,
/// One,
/// }
///
/// fn main() {
/// assert_eq!(
/// Number::Zero,
/// unsafe { Number::unchecked_transmute_from(0_u8) },
/// );
/// assert_eq!(
/// Number::One,
/// unsafe { Number::unchecked_transmute_from(1_u8) },
/// );
/// }
///
/// unsafe fn undefined_behavior() {
/// let _ = Number::unchecked_transmute_from(2); // 2 is not a valid discriminant!
/// }
/// ```
#[proc_macro_derive(UnsafeFromPrimitive, attributes(num_enum))]
pub fn derive_unsafe_from_primitive(stream: TokenStream) -> TokenStream {
let enum_info = parse_macro_input!(stream as EnumInfo);
let krate = Ident::new(&get_crate_name(), Span::call_site());
let EnumInfo {
ref name, ref repr, ..
} = enum_info;
TokenStream::from(quote! {
impl ::#krate::UnsafeFromPrimitive for #name {
type Primitive = #repr;
unsafe fn unchecked_transmute_from(number: Self::Primitive) -> Self {
::core::mem::transmute(number)
}
}
})
}
/// Implements `core::default::Default` for a `#[repr(Primitive)] enum`.
///
/// Whichever variant has the `#[default]` or `#[num_enum(default)]` attribute will be returned.
/// ----------------------------------------------
///
/// ```rust
/// #[derive(Debug, Eq, PartialEq, num_enum::Default)]
/// #[repr(u8)]
/// enum Number {
/// Zero,
/// #[default]
/// One,
/// }
///
/// assert_eq!(Number::One, Number::default());
/// assert_eq!(Number::One, <Number as ::core::default::Default>::default());
/// ```
#[proc_macro_derive(Default, attributes(num_enum, default))]
pub fn derive_default(stream: TokenStream) -> TokenStream {
let enum_info = parse_macro_input!(stream as EnumInfo);
let default_ident = match enum_info.default() {
Some(ident) => ident,
None => {
let span = Span::call_site();
let message =
"#[derive(num_enum::Default)] requires enum to be exhaustive, or a variant marked with `#[default]` or `#[num_enum(default)]`";
return syn::Error::new(span, message).to_compile_error().into();
}
};
let EnumInfo { ref name, .. } = enum_info;
TokenStream::from(quote! {
impl ::core::default::Default for #name {
#[inline]
fn default() -> Self {
Self::#default_ident
}
}
})
}