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;
9 use proc_macro_crate::FoundCrate;
10 use syn::{*, Result, Error};
11 use syn::spanned::Spanned;
14 /// Helper function for emitting compile errors.
15 fn error<T>(span: Span, message: &str) -> Result<T> {
16 Err(Error::new(span, message))
19 /// Decodes the custom attributes for our custom derive.
20 #[derive(FromDeriveInput, Default)]
21 #[darling(attributes(enumset), default)]
25 serialize_as_list: bool,
26 serialize_deny_unknown: bool,
28 serialize_repr: Option<String>,
30 crate_name: Option<String>,
33 /// An variant in the enum set type.
35 /// The name of the variant.
37 /// The discriminant of the variant.
41 /// Stores information about the enum set type.
44 /// The name of the enum.
46 /// The crate name to use.
47 crate_name: Option<Ident>,
48 /// The numeric type to serialize the enum as.
49 explicit_serde_repr: Option<Ident>,
50 /// Whether the underlying repr of the enum supports negative values.
51 has_signed_repr: bool,
52 /// Whether the underlying repr of the enum supports values higher than 2^32.
54 /// A list of variants in the enum.
55 variants: Vec<EnumSetValue>,
57 /// The highest encountered variant discriminant.
59 /// The current variant discriminant. Used to track, e.g. `A=10,B,C`.
61 /// A list of variant names that are already in use.
62 used_variant_names: HashSet<String>,
63 /// A list of variant discriminants that are already in use.
64 used_discriminants: HashSet<u32>,
66 /// Avoid generating operator overloads on the enum type.
68 /// Avoid generating implementations for `Clone`, `Copy`, `Eq`, and `PartialEq`.
70 /// Serialize the enum as a list.
71 serialize_as_list: bool,
72 /// Disallow unknown bits while deserializing the enum.
73 serialize_deny_unknown: bool,
76 fn new(input: &DeriveInput, attrs: EnumsetAttrs) -> EnumSetInfo {
78 name: input.ident.clone(),
79 crate_name: attrs.crate_name.map(|x| Ident::new(&x, Span::call_site())),
80 explicit_serde_repr: attrs.serialize_repr.map(|x| Ident::new(&x, Span::call_site())),
81 has_signed_repr: false,
82 has_large_repr: false,
86 used_variant_names: HashSet::new(),
87 used_discriminants: HashSet::new(),
89 no_super_impls: attrs.no_super_impls,
90 serialize_as_list: attrs.serialize_as_list,
91 serialize_deny_unknown: attrs.serialize_deny_unknown
95 /// Sets an explicit repr for the enumset.
96 fn push_explicit_repr(&mut self, attr_span: Span, repr: &str) -> Result<()> {
97 // Check whether the repr is supported, and if so, set some flags for better error
100 "Rust" | "C" | "u8" | "u16" | "u32" => Ok(()),
101 "usize" | "u64" | "u128" => {
102 self.has_large_repr = true;
105 "i8" | "i16" | "i32" => {
106 self.has_signed_repr = true;
109 "isize" | "i64" | "i128" => {
110 self.has_signed_repr = true;
111 self.has_large_repr = true;
114 _ => error(attr_span, "Unsupported repr.")
117 /// Adds a variant to the enumset.
118 fn push_variant(&mut self, variant: &Variant) -> Result<()> {
119 if self.used_variant_names.contains(&variant.ident.to_string()) {
120 error(variant.span(), "Duplicated variant name.")
121 } else if let Fields::Unit = variant.fields {
122 // Parse the discriminant.
123 if let Some((_, expr)) = &variant.discriminant {
124 let discriminant_fail_message = format!(
125 "Enum set discriminants must be `u32`s.{}",
126 if self.has_signed_repr || self.has_large_repr {
128 " ({} discrimiants are still unsupported with reprs that allow them.)",
129 if self.has_large_repr {
131 } else if self.has_signed_repr {
141 if let Expr::Lit(ExprLit { lit: Lit::Int(i), .. }) = expr {
142 match i.base10_parse() {
143 Ok(val) => self.cur_discrim = val,
144 Err(_) => error(expr.span(), &discriminant_fail_message)?,
147 error(variant.span(), &discriminant_fail_message)?;
151 // Validate the discriminant.
152 let discriminant = self.cur_discrim;
153 if discriminant >= 128 {
154 let message = if self.variants.len() <= 127 {
155 "`#[derive(EnumSetType)]` currently only supports discriminants up to 127."
157 "`#[derive(EnumSetType)]` currently only supports enums up to 128 variants."
159 error(variant.span(), message)?;
161 if self.used_discriminants.contains(&discriminant) {
162 error(variant.span(), "Duplicated enum discriminant.")?;
165 // Add the variant to the info.
166 self.cur_discrim += 1;
167 if discriminant > self.max_discrim {
168 self.max_discrim = discriminant;
170 self.variants.push(EnumSetValue {
171 name: variant.ident.clone(),
172 variant_repr: discriminant,
174 self.used_variant_names.insert(variant.ident.to_string());
175 self.used_discriminants.insert(discriminant);
179 error(variant.span(), "`#[derive(EnumSetType)]` can only be used on fieldless enums.")
182 /// Validate the enumset type.
183 fn validate(&self) -> Result<()> {
184 // Check if all bits of the bitset can fit in the serialization representation.
185 if let Some(explicit_serde_repr) = &self.explicit_serde_repr {
186 let is_overflowed = match explicit_serde_repr.to_string().as_str() {
187 "u8" => self.max_discrim >= 8,
188 "u16" => self.max_discrim >= 16,
189 "u32" => self.max_discrim >= 32,
190 "u64" => self.max_discrim >= 64,
191 "u128" => self.max_discrim >= 128,
194 "Only `u8`, `u16`, `u32`, `u64` and `u128` are supported for serde_repr."
198 error(Span::call_site(), "serialize_repr cannot be smaller than bitset.")?;
204 /// Computes the underlying type used to store the enumset.
205 fn enumset_repr(&self) -> SynTokenStream {
206 if self.max_discrim <= 7 {
208 } else if self.max_discrim <= 15 {
210 } else if self.max_discrim <= 31 {
212 } else if self.max_discrim <= 63 {
214 } else if self.max_discrim <= 127 {
217 panic!("max_variant > 127?")
220 /// Computes the underlying type used to serialize the enumset.
221 #[cfg(feature = "serde")]
222 fn serde_repr(&self) -> SynTokenStream {
223 if let Some(serde_repr) = &self.explicit_serde_repr {
224 quote! { #serde_repr }
230 /// Returns a bitmask of all variants in the set.
231 fn all_variants(&self) -> u128 {
232 let mut accum = 0u128;
233 for variant in &self.variants {
234 assert!(variant.variant_repr <= 127);
235 accum |= 1u128 << variant.variant_repr as u128;
241 /// Generates the actual `EnumSetType` impl.
242 fn enum_set_type_impl(info: EnumSetInfo) -> SynTokenStream {
243 let name = &info.name;
244 let enumset = match &info.crate_name {
245 Some(crate_name) => quote!(::#crate_name),
247 let crate_name = proc_macro_crate::crate_name("enumset");
249 Ok(FoundCrate::Name(name)) => {
250 let ident = Ident::new(&name, Span::call_site());
253 _ => quote!(::enumset),
257 let typed_enumset = quote!(#enumset::EnumSet<#name>);
258 let core = quote!(#enumset::__internal::core_export);
260 let repr = info.enumset_repr();
261 let all_variants = Literal::u128_unsuffixed(info.all_variants());
263 let ops = if info.no_ops {
267 impl <O : Into<#typed_enumset>> #core::ops::Sub<O> for #name {
268 type Output = #typed_enumset;
269 fn sub(self, other: O) -> Self::Output {
270 #enumset::EnumSet::only(self) - other.into()
273 impl <O : Into<#typed_enumset>> #core::ops::BitAnd<O> for #name {
274 type Output = #typed_enumset;
275 fn bitand(self, other: O) -> Self::Output {
276 #enumset::EnumSet::only(self) & other.into()
279 impl <O : Into<#typed_enumset>> #core::ops::BitOr<O> for #name {
280 type Output = #typed_enumset;
281 fn bitor(self, other: O) -> Self::Output {
282 #enumset::EnumSet::only(self) | other.into()
285 impl <O : Into<#typed_enumset>> #core::ops::BitXor<O> for #name {
286 type Output = #typed_enumset;
287 fn bitxor(self, other: O) -> Self::Output {
288 #enumset::EnumSet::only(self) ^ other.into()
291 impl #core::ops::Not for #name {
292 type Output = #typed_enumset;
293 fn not(self) -> Self::Output {
294 !#enumset::EnumSet::only(self)
297 impl #core::cmp::PartialEq<#typed_enumset> for #name {
298 fn eq(&self, other: &#typed_enumset) -> bool {
299 #enumset::EnumSet::only(*self) == *other
306 #[cfg(feature = "serde")]
307 let serde = quote!(#enumset::__internal::serde);
309 #[cfg(feature = "serde")]
310 let serde_ops = if info.serialize_as_list {
311 let expecting_str = format!("a list of {}", name);
313 fn serialize<S: #serde::Serializer>(
314 set: #enumset::EnumSet<#name>, ser: S,
315 ) -> #core::result::Result<S::Ok, S::Error> {
316 use #serde::ser::SerializeSeq;
317 let mut seq = ser.serialize_seq(#core::prelude::v1::Some(set.len()))?;
319 seq.serialize_element(&bit)?;
323 fn deserialize<'de, D: #serde::Deserializer<'de>>(
325 ) -> #core::result::Result<#enumset::EnumSet<#name>, D::Error> {
327 impl <'de> #serde::de::Visitor<'de> for Visitor {
328 type Value = #enumset::EnumSet<#name>;
330 &self, formatter: &mut #core::fmt::Formatter,
331 ) -> #core::fmt::Result {
332 write!(formatter, #expecting_str)
335 mut self, mut seq: A,
336 ) -> #core::result::Result<Self::Value, A::Error> where
337 A: #serde::de::SeqAccess<'de>
339 let mut accum = #enumset::EnumSet::<#name>::new();
340 while let #core::prelude::v1::Some(val) = seq.next_element::<#name>()? {
343 #core::prelude::v1::Ok(accum)
346 de.deserialize_seq(Visitor)
350 let serialize_repr = info.serde_repr();
351 let check_unknown = if info.serialize_deny_unknown {
353 if value & !#all_variants != 0 {
354 use #serde::de::Error;
355 return #core::prelude::v1::Err(
356 D::Error::custom("enumset contains unknown bits")
364 fn serialize<S: #serde::Serializer>(
365 set: #enumset::EnumSet<#name>, ser: S,
366 ) -> #core::result::Result<S::Ok, S::Error> {
367 #serde::Serialize::serialize(&(set.__priv_repr as #serialize_repr), ser)
369 fn deserialize<'de, D: #serde::Deserializer<'de>>(
371 ) -> #core::result::Result<#enumset::EnumSet<#name>, D::Error> {
372 let value = <#serialize_repr as #serde::Deserialize>::deserialize(de)?;
374 #core::prelude::v1::Ok(#enumset::EnumSet {
375 __priv_repr: (value & #all_variants) as #repr,
381 #[cfg(not(feature = "serde"))]
382 let serde_ops = quote! { };
384 let is_uninhabited = info.variants.is_empty();
385 let is_zst = info.variants.len() == 1;
386 let into_impl = if is_uninhabited {
388 fn enum_into_u32(self) -> u32 {
389 panic!(concat!(stringify!(#name), " is uninhabited."))
391 unsafe fn enum_from_u32(val: u32) -> Self {
392 panic!(concat!(stringify!(#name), " is uninhabited."))
396 let variant = &info.variants[0].name;
398 fn enum_into_u32(self) -> u32 {
401 unsafe fn enum_from_u32(val: u32) -> Self {
406 let variant_name: Vec<_> = info.variants.iter().map(|x| &x.name).collect();
407 let variant_value: Vec<_> = info.variants.iter().map(|x| x.variant_repr).collect();
409 let const_field: Vec<_> = ["IS_U8", "IS_U16", "IS_U32", "IS_U64", "IS_U128"]
410 .iter().map(|x| Ident::new(x, Span::call_site())).collect();
411 let int_type: Vec<_> = ["u8", "u16", "u32", "u64", "u128"]
412 .iter().map(|x| Ident::new(x, Span::call_site())).collect();
415 fn enum_into_u32(self) -> u32 {
418 unsafe fn enum_from_u32(val: u32) -> Self {
419 // We put these in const fields so the branches they guard aren't generated even
421 #(const #const_field: bool =
422 #core::mem::size_of::<#name>() == #core::mem::size_of::<#int_type>();)*
424 // Every valid variant value has an explicit branch. If they get optimized out,
425 // great. If the representation has changed somehow, and they don't, oh well,
426 // there's still no UB.
427 #(#variant_value => #name::#variant_name,)*
428 // Helps hint to the LLVM that this is a transmute. Note that this branch is
429 // still unreachable.
430 #(x if #const_field => {
431 let x = x as #int_type;
432 *(&x as *const _ as *const #name)
434 // Default case. Sometimes causes LLVM to generate a table instead of a simple
435 // transmute, but, oh well.
436 _ => #core::hint::unreachable_unchecked(),
442 let eq_impl = if is_uninhabited {
443 quote!(panic!(concat!(stringify!(#name), " is uninhabited.")))
445 quote!((*self as u32) == (*other as u32))
448 // used in the enum_set! macro `const fn`s.
449 let self_as_repr_mask = if is_uninhabited {
450 quote! { 0 } // impossible anyway
452 quote! { 1 << self as #repr }
455 let super_impls = if info.no_super_impls {
459 impl #core::cmp::PartialEq for #name {
460 fn eq(&self, other: &Self) -> bool {
464 impl #core::cmp::Eq for #name { }
465 #[allow(clippy::expl_impl_clone_on_copy)]
466 impl #core::clone::Clone for #name {
467 fn clone(&self) -> Self {
471 impl #core::marker::Copy for #name { }
476 unsafe impl #enumset::__internal::EnumSetTypePrivate for #name {
478 const ALL_BITS: Self::Repr = #all_variants;
483 unsafe impl #enumset::EnumSetType for #name { }
488 /// Creates a new enumset with only this variant.
489 #[deprecated(note = "This method is an internal implementation detail generated by \
490 the `enumset` crate's procedural macro. It should not be used \
491 directly. Use `EnumSet::only` instead.")]
493 pub const fn __impl_enumset_internal__const_only(self) -> #enumset::EnumSet<#name> {
494 #enumset::EnumSet { __priv_repr: #self_as_repr_mask }
497 /// Creates a new enumset with this variant added.
498 #[deprecated(note = "This method is an internal implementation detail generated by \
499 the `enumset` crate's procedural macro. It should not be used \
500 directly. Use the `|` operator instead.")]
502 pub const fn __impl_enumset_internal__const_merge(
503 self, chain: #enumset::EnumSet<#name>,
504 ) -> #enumset::EnumSet<#name> {
505 #enumset::EnumSet { __priv_repr: chain.__priv_repr | #self_as_repr_mask }
513 #[proc_macro_derive(EnumSetType, attributes(enumset))]
514 pub fn derive_enum_set_type(input: TokenStream) -> TokenStream {
515 let input: DeriveInput = parse_macro_input!(input);
516 let attrs: EnumsetAttrs = match EnumsetAttrs::from_derive_input(&input) {
518 Err(e) => return e.write_errors().into(),
520 match derive_enum_set_type_0(input, attrs) {
522 Err(e) => e.to_compile_error().into(),
525 fn derive_enum_set_type_0(input: DeriveInput, attrs: EnumsetAttrs) -> Result<TokenStream> {
526 if !input.generics.params.is_empty() {
528 input.generics.span(),
529 "`#[derive(EnumSetType)]` cannot be used on enums with type parameters.",
531 } else if let Data::Enum(data) = &input.data {
532 let mut info = EnumSetInfo::new(&input, attrs);
533 for attr in &input.attrs {
534 if attr.path.is_ident(&Ident::new("repr", Span::call_site())) {
535 let meta: Ident = attr.parse_args()?;
536 info.push_explicit_repr(attr.span(), meta.to_string().as_str())?;
539 for variant in &data.variants {
540 info.push_variant(variant)?;
543 Ok(enum_set_type_impl(info).into())
545 error(input.span(), "`#[derive(EnumSetType)]` may only be used on enums")