1 #![recursion_limit="256"]
3 extern crate proc_macro;
6 use proc_macro::TokenStream;
7 use proc_macro2::{TokenStream as SynTokenStream, Literal, Span};
8 use std::{collections::HashSet, fmt::Display};
9 use syn::{*, Result, Error};
10 use syn::spanned::Spanned;
13 /// Helper function for emitting compile errors.
14 fn error<T>(span: Span, message: impl Display) -> Result<T> {
15 Err(Error::new(span, message))
18 /// Decodes the custom attributes for our custom derive.
19 #[derive(FromDeriveInput, Default)]
20 #[darling(attributes(enumset), default)]
26 serialize_as_list: bool,
27 serialize_deny_unknown: bool,
29 serialize_repr: Option<String>,
31 crate_name: Option<String>,
34 /// An variant in the enum set type.
36 /// The name of the variant.
38 /// The discriminant of the variant.
42 /// Stores information about the enum set type.
45 /// The name of the enum.
47 /// The crate name to use.
48 crate_name: Option<Ident>,
49 /// The numeric type to represent the `EnumSet` as in memory.
50 explicit_mem_repr: Option<Ident>,
51 /// The numeric type to serialize the enum as.
52 explicit_serde_repr: Option<Ident>,
53 /// Whether the underlying repr of the enum supports negative values.
54 has_signed_repr: bool,
55 /// Whether the underlying repr of the enum supports values higher than 2^32.
57 /// A list of variants in the enum.
58 variants: Vec<EnumSetValue>,
60 /// The highest encountered variant discriminant.
62 /// The current variant discriminant. Used to track, e.g. `A=10,B,C`.
64 /// A list of variant names that are already in use.
65 used_variant_names: HashSet<String>,
66 /// A list of variant discriminants that are already in use.
67 used_discriminants: HashSet<u32>,
69 /// Avoid generating operator overloads on the enum type.
71 /// Avoid generating implementations for `Clone`, `Copy`, `Eq`, and `PartialEq`.
73 /// Serialize the enum as a list.
74 serialize_as_list: bool,
75 /// Disallow unknown bits while deserializing the enum.
76 serialize_deny_unknown: bool,
79 fn new(input: &DeriveInput, attrs: EnumsetAttrs) -> EnumSetInfo {
81 name: input.ident.clone(),
82 crate_name: attrs.crate_name.map(|x| Ident::new(&x, Span::call_site())),
83 explicit_mem_repr: attrs.repr.map(|x| Ident::new(&x, Span::call_site())),
84 explicit_serde_repr: attrs.serialize_repr.map(|x| Ident::new(&x, Span::call_site())),
85 has_signed_repr: false,
86 has_large_repr: false,
90 used_variant_names: HashSet::new(),
91 used_discriminants: HashSet::new(),
93 no_super_impls: attrs.no_super_impls,
94 serialize_as_list: attrs.serialize_as_list,
95 serialize_deny_unknown: attrs.serialize_deny_unknown
99 /// Sets an explicit repr for the enumset.
100 fn push_explicit_repr(&mut self, attr_span: Span, repr: &str) -> Result<()> {
101 // Check whether the repr is supported, and if so, set some flags for better error
102 // messages later on.
104 "Rust" | "C" | "u8" | "u16" | "u32" => Ok(()),
105 "usize" | "u64" | "u128" => {
106 self.has_large_repr = true;
109 "i8" | "i16" | "i32" => {
110 self.has_signed_repr = true;
113 "isize" | "i64" | "i128" => {
114 self.has_signed_repr = true;
115 self.has_large_repr = true;
118 _ => error(attr_span, "Unsupported repr.")
121 /// Adds a variant to the enumset.
122 fn push_variant(&mut self, variant: &Variant) -> Result<()> {
123 if self.used_variant_names.contains(&variant.ident.to_string()) {
124 error(variant.span(), "Duplicated variant name.")
125 } else if let Fields::Unit = variant.fields {
126 // Parse the discriminant.
127 if let Some((_, expr)) = &variant.discriminant {
128 let discriminant_fail_message = format!(
129 "Enum set discriminants must be `u32`s.{}",
130 if self.has_signed_repr || self.has_large_repr {
132 " ({} discrimiants are still unsupported with reprs that allow them.)",
133 if self.has_large_repr {
135 } else if self.has_signed_repr {
145 if let Expr::Lit(ExprLit { lit: Lit::Int(i), .. }) = expr {
146 match i.base10_parse() {
147 Ok(val) => self.cur_discrim = val,
148 Err(_) => error(expr.span(), &discriminant_fail_message)?,
151 error(variant.span(), &discriminant_fail_message)?;
155 // Validate the discriminant.
156 let discriminant = self.cur_discrim;
157 if discriminant >= 128 {
158 let message = if self.variants.len() <= 127 {
159 "`#[derive(EnumSetType)]` currently only supports discriminants up to 127."
161 "`#[derive(EnumSetType)]` currently only supports enums up to 128 variants."
163 error(variant.span(), message)?;
165 if self.used_discriminants.contains(&discriminant) {
166 error(variant.span(), "Duplicated enum discriminant.")?;
169 // Add the variant to the info.
170 self.cur_discrim += 1;
171 if discriminant > self.max_discrim {
172 self.max_discrim = discriminant;
174 self.variants.push(EnumSetValue {
175 name: variant.ident.clone(),
176 variant_repr: discriminant,
178 self.used_variant_names.insert(variant.ident.to_string());
179 self.used_discriminants.insert(discriminant);
183 error(variant.span(), "`#[derive(EnumSetType)]` can only be used on fieldless enums.")
186 /// Validate the enumset type.
187 fn validate(&self) -> Result<()> {
188 // Check if all bits of the bitset can fit in the serialization representation.
189 if let Some(explicit_serde_repr) = &self.explicit_serde_repr {
190 let is_overflowed = match explicit_serde_repr.to_string().as_str() {
191 "u8" => self.max_discrim >= 8,
192 "u16" => self.max_discrim >= 16,
193 "u32" => self.max_discrim >= 32,
194 "u64" => self.max_discrim >= 64,
195 "u128" => self.max_discrim >= 128,
198 "Only `u8`, `u16`, `u32`, `u64` and `u128` are supported for serde_repr."
202 error(Span::call_site(), "serialize_repr cannot be smaller than bitset.")?;
205 // Check if all bits of the bitset can fit in the memory representation, if one was given.
206 if let Some(explicit_mem_repr) = &self.explicit_mem_repr {
207 let is_overflowed = match explicit_mem_repr.to_string().as_str() {
208 "u8" => self.max_discrim >= 8,
209 "u16" => self.max_discrim >= 16,
210 "u32" => self.max_discrim >= 32,
211 "u64" => self.max_discrim >= 64,
212 "u128" => self.max_discrim >= 128,
215 "Only `u8`, `u16`, `u32`, `u64` and `u128` are supported for repr."
219 error(Span::call_site(), "repr cannot be smaller than bitset.")?;
225 /// Computes the underlying type used to store the enumset.
226 fn enumset_repr(&self) -> SynTokenStream {
227 if let Some(explicit_mem_repr) = &self.explicit_mem_repr {
228 explicit_mem_repr.to_token_stream()
229 } else if self.max_discrim <= 7 {
231 } else if self.max_discrim <= 15 {
233 } else if self.max_discrim <= 31 {
235 } else if self.max_discrim <= 63 {
237 } else if self.max_discrim <= 127 {
240 panic!("max_variant > 127?")
243 /// Computes the underlying type used to serialize the enumset.
244 #[cfg(feature = "serde")]
245 fn serde_repr(&self) -> SynTokenStream {
246 if let Some(serde_repr) = &self.explicit_serde_repr {
247 quote! { #serde_repr }
253 /// Returns a bitmask of all variants in the set.
254 fn all_variants(&self) -> u128 {
255 let mut accum = 0u128;
256 for variant in &self.variants {
257 assert!(variant.variant_repr <= 127);
258 accum |= 1u128 << variant.variant_repr as u128;
264 /// Generates the actual `EnumSetType` impl.
265 fn enum_set_type_impl(info: EnumSetInfo) -> SynTokenStream {
266 let name = &info.name;
268 let enumset = match &info.crate_name {
269 Some(crate_name) => quote!(::#crate_name),
271 #[cfg(feature = "proc-macro-crate")]
273 use proc_macro_crate::FoundCrate;
275 let crate_name = proc_macro_crate::crate_name("enumset");
277 Ok(FoundCrate::Name(name)) => {
278 let ident = Ident::new(&name, Span::call_site());
281 _ => quote!(::enumset),
285 #[cfg(not(feature = "proc-macro-crate"))]
291 let typed_enumset = quote!(#enumset::EnumSet<#name>);
292 let core = quote!(#enumset::__internal::core_export);
294 let repr = info.enumset_repr();
295 let all_variants = Literal::u128_unsuffixed(info.all_variants());
297 let ops = if info.no_ops {
301 impl <O : Into<#typed_enumset>> #core::ops::Sub<O> for #name {
302 type Output = #typed_enumset;
303 fn sub(self, other: O) -> Self::Output {
304 #enumset::EnumSet::only(self) - other.into()
307 impl <O : Into<#typed_enumset>> #core::ops::BitAnd<O> for #name {
308 type Output = #typed_enumset;
309 fn bitand(self, other: O) -> Self::Output {
310 #enumset::EnumSet::only(self) & other.into()
313 impl <O : Into<#typed_enumset>> #core::ops::BitOr<O> for #name {
314 type Output = #typed_enumset;
315 fn bitor(self, other: O) -> Self::Output {
316 #enumset::EnumSet::only(self) | other.into()
319 impl <O : Into<#typed_enumset>> #core::ops::BitXor<O> for #name {
320 type Output = #typed_enumset;
321 fn bitxor(self, other: O) -> Self::Output {
322 #enumset::EnumSet::only(self) ^ other.into()
325 impl #core::ops::Not for #name {
326 type Output = #typed_enumset;
327 fn not(self) -> Self::Output {
328 !#enumset::EnumSet::only(self)
331 impl #core::cmp::PartialEq<#typed_enumset> for #name {
332 fn eq(&self, other: &#typed_enumset) -> bool {
333 #enumset::EnumSet::only(*self) == *other
340 #[cfg(feature = "serde")]
341 let serde = quote!(#enumset::__internal::serde);
343 #[cfg(feature = "serde")]
344 let serde_ops = if info.serialize_as_list {
345 let expecting_str = format!("a list of {}", name);
347 fn serialize<S: #serde::Serializer>(
348 set: #enumset::EnumSet<#name>, ser: S,
349 ) -> #core::result::Result<S::Ok, S::Error> {
350 use #serde::ser::SerializeSeq;
351 let mut seq = ser.serialize_seq(#core::prelude::v1::Some(set.len()))?;
353 seq.serialize_element(&bit)?;
357 fn deserialize<'de, D: #serde::Deserializer<'de>>(
359 ) -> #core::result::Result<#enumset::EnumSet<#name>, D::Error> {
361 impl <'de> #serde::de::Visitor<'de> for Visitor {
362 type Value = #enumset::EnumSet<#name>;
364 &self, formatter: &mut #core::fmt::Formatter,
365 ) -> #core::fmt::Result {
366 write!(formatter, #expecting_str)
369 mut self, mut seq: A,
370 ) -> #core::result::Result<Self::Value, A::Error> where
371 A: #serde::de::SeqAccess<'de>
373 let mut accum = #enumset::EnumSet::<#name>::new();
374 while let #core::prelude::v1::Some(val) = seq.next_element::<#name>()? {
377 #core::prelude::v1::Ok(accum)
380 de.deserialize_seq(Visitor)
384 let serialize_repr = info.serde_repr();
385 let check_unknown = if info.serialize_deny_unknown {
387 if value & !#all_variants != 0 {
388 use #serde::de::Error;
389 return #core::prelude::v1::Err(
390 D::Error::custom("enumset contains unknown bits")
398 fn serialize<S: #serde::Serializer>(
399 set: #enumset::EnumSet<#name>, ser: S,
400 ) -> #core::result::Result<S::Ok, S::Error> {
401 #serde::Serialize::serialize(&(set.__priv_repr as #serialize_repr), ser)
403 fn deserialize<'de, D: #serde::Deserializer<'de>>(
405 ) -> #core::result::Result<#enumset::EnumSet<#name>, D::Error> {
406 let value = <#serialize_repr as #serde::Deserialize>::deserialize(de)?;
408 #core::prelude::v1::Ok(#enumset::EnumSet {
409 __priv_repr: (value & #all_variants) as #repr,
415 #[cfg(not(feature = "serde"))]
416 let serde_ops = quote! { };
418 let is_uninhabited = info.variants.is_empty();
419 let is_zst = info.variants.len() == 1;
420 let into_impl = if is_uninhabited {
422 fn enum_into_u32(self) -> u32 {
423 panic!(concat!(stringify!(#name), " is uninhabited."))
425 unsafe fn enum_from_u32(val: u32) -> Self {
426 panic!(concat!(stringify!(#name), " is uninhabited."))
430 let variant = &info.variants[0].name;
432 fn enum_into_u32(self) -> u32 {
435 unsafe fn enum_from_u32(val: u32) -> Self {
440 let variant_name: Vec<_> = info.variants.iter().map(|x| &x.name).collect();
441 let variant_value: Vec<_> = info.variants.iter().map(|x| x.variant_repr).collect();
443 let const_field: Vec<_> = ["IS_U8", "IS_U16", "IS_U32", "IS_U64", "IS_U128"]
444 .iter().map(|x| Ident::new(x, Span::call_site())).collect();
445 let int_type: Vec<_> = ["u8", "u16", "u32", "u64", "u128"]
446 .iter().map(|x| Ident::new(x, Span::call_site())).collect();
449 fn enum_into_u32(self) -> u32 {
452 unsafe fn enum_from_u32(val: u32) -> Self {
453 // We put these in const fields so the branches they guard aren't generated even
455 #(const #const_field: bool =
456 #core::mem::size_of::<#name>() == #core::mem::size_of::<#int_type>();)*
458 // Every valid variant value has an explicit branch. If they get optimized out,
459 // great. If the representation has changed somehow, and they don't, oh well,
460 // there's still no UB.
461 #(#variant_value => #name::#variant_name,)*
462 // Helps hint to the LLVM that this is a transmute. Note that this branch is
463 // still unreachable.
464 #(x if #const_field => {
465 let x = x as #int_type;
466 *(&x as *const _ as *const #name)
468 // Default case. Sometimes causes LLVM to generate a table instead of a simple
469 // transmute, but, oh well.
470 _ => #core::hint::unreachable_unchecked(),
476 let eq_impl = if is_uninhabited {
477 quote!(panic!(concat!(stringify!(#name), " is uninhabited.")))
479 quote!((*self as u32) == (*other as u32))
482 // used in the enum_set! macro `const fn`s.
483 let self_as_repr_mask = if is_uninhabited {
484 quote! { 0 } // impossible anyway
486 quote! { 1 << self as #repr }
489 let super_impls = if info.no_super_impls {
493 impl #core::cmp::PartialEq for #name {
494 fn eq(&self, other: &Self) -> bool {
498 impl #core::cmp::Eq for #name { }
499 #[allow(clippy::expl_impl_clone_on_copy)]
500 impl #core::clone::Clone for #name {
501 fn clone(&self) -> Self {
505 impl #core::marker::Copy for #name { }
509 let impl_with_repr = if info.explicit_mem_repr.is_some() {
511 unsafe impl #enumset::EnumSetTypeWithRepr for #name {
520 unsafe impl #enumset::__internal::EnumSetTypePrivate for #name {
522 const ALL_BITS: Self::Repr = #all_variants;
527 unsafe impl #enumset::EnumSetType for #name { }
533 /// Creates a new enumset with only this variant.
534 #[deprecated(note = "This method is an internal implementation detail generated by \
535 the `enumset` crate's procedural macro. It should not be used \
536 directly. Use `EnumSet::only` instead.")]
538 pub const fn __impl_enumset_internal__const_only(self) -> #enumset::EnumSet<#name> {
539 #enumset::EnumSet { __priv_repr: #self_as_repr_mask }
542 /// Creates a new enumset with this variant added.
543 #[deprecated(note = "This method is an internal implementation detail generated by \
544 the `enumset` crate's procedural macro. It should not be used \
545 directly. Use the `|` operator instead.")]
547 pub const fn __impl_enumset_internal__const_merge(
548 self, chain: #enumset::EnumSet<#name>,
549 ) -> #enumset::EnumSet<#name> {
550 #enumset::EnumSet { __priv_repr: chain.__priv_repr | #self_as_repr_mask }
558 #[proc_macro_derive(EnumSetType, attributes(enumset))]
559 pub fn derive_enum_set_type(input: TokenStream) -> TokenStream {
560 let input: DeriveInput = parse_macro_input!(input);
561 let attrs: EnumsetAttrs = match EnumsetAttrs::from_derive_input(&input) {
563 Err(e) => return e.write_errors().into(),
565 match derive_enum_set_type_0(input, attrs) {
567 Err(e) => e.to_compile_error().into(),
570 fn derive_enum_set_type_0(input: DeriveInput, attrs: EnumsetAttrs) -> Result<TokenStream> {
571 if !input.generics.params.is_empty() {
573 input.generics.span(),
574 "`#[derive(EnumSetType)]` cannot be used on enums with type parameters.",
576 } else if let Data::Enum(data) = &input.data {
577 let mut info = EnumSetInfo::new(&input, attrs);
578 for attr in &input.attrs {
579 if attr.path.is_ident(&Ident::new("repr", Span::call_site())) {
580 let meta: Ident = attr.parse_args()?;
581 info.push_explicit_repr(attr.span(), meta.to_string().as_str())?;
584 for variant in &data.variants {
585 info.push_variant(variant)?;
588 Ok(enum_set_type_impl(info).into())
590 error(input.span(), "`#[derive(EnumSetType)]` may only be used on enums")