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 syn::{*, Result, Error};
10 use syn::spanned::Spanned;
13 /// Helper function for emitting compile errors.
14 fn error<T>(span: Span, message: &str) -> 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)]
24 serialize_as_list: bool,
25 serialize_deny_unknown: bool,
27 serialize_repr: Option<String>,
29 crate_name: Option<String>,
32 /// An variant in the enum set type.
34 /// The name of the variant.
36 /// The discriminant of the variant.
40 /// Stores information about the enum set type.
43 /// The name of the enum.
45 /// The crate name to use.
46 crate_name: Option<Ident>,
47 /// The numeric type to serialize the enum as.
48 explicit_serde_repr: Option<Ident>,
49 /// Whether the underlying repr of the enum supports negative values.
50 has_signed_repr: bool,
51 /// Whether the underlying repr of the enum supports values higher than 2^32.
53 /// A list of variants in the enum.
54 variants: Vec<EnumSetValue>,
56 /// The highest encountered variant discriminant.
58 /// The current variant discriminant. Used to track, e.g. `A=10,B,C`.
60 /// A list of variant names that are already in use.
61 used_variant_names: HashSet<String>,
62 /// A list of variant discriminants that are already in use.
63 used_discriminants: HashSet<u32>,
65 /// Avoid generating operator overloads on the enum type.
67 /// Avoid generating implementations for `Clone`, `Copy`, `Eq`, and `PartialEq`.
69 /// Serialize the enum as a list.
70 serialize_as_list: bool,
71 /// Disallow unknown bits while deserializing the enum.
72 serialize_deny_unknown: bool,
75 fn new(input: &DeriveInput, attrs: EnumsetAttrs) -> EnumSetInfo {
77 name: input.ident.clone(),
78 crate_name: attrs.crate_name.map(|x| Ident::new(&x, Span::call_site())),
79 explicit_serde_repr: attrs.serialize_repr.map(|x| Ident::new(&x, Span::call_site())),
80 has_signed_repr: false,
81 has_large_repr: false,
85 used_variant_names: HashSet::new(),
86 used_discriminants: HashSet::new(),
88 no_super_impls: attrs.no_super_impls,
89 serialize_as_list: attrs.serialize_as_list,
90 serialize_deny_unknown: attrs.serialize_deny_unknown
94 /// Sets an explicit repr for the enumset.
95 fn push_explicit_repr(&mut self, attr_span: Span, repr: &str) -> Result<()> {
96 // Check whether the repr is supported, and if so, set some flags for better error
99 "Rust" | "C" | "u8" | "u16" | "u32" => Ok(()),
100 "usize" | "u64" | "u128" => {
101 self.has_large_repr = true;
104 "i8" | "i16" | "i32" => {
105 self.has_signed_repr = true;
108 "isize" | "i64" | "i128" => {
109 self.has_signed_repr = true;
110 self.has_large_repr = true;
113 _ => error(attr_span, "Unsupported repr.")
116 /// Adds a variant to the enumset.
117 fn push_variant(&mut self, variant: &Variant) -> Result<()> {
118 if self.used_variant_names.contains(&variant.ident.to_string()) {
119 error(variant.span(), "Duplicated variant name.")
120 } else if let Fields::Unit = variant.fields {
121 // Parse the discriminant.
122 if let Some((_, expr)) = &variant.discriminant {
123 let discriminant_fail_message = format!(
124 "Enum set discriminants must be `u32`s.{}",
125 if self.has_signed_repr || self.has_large_repr {
127 " ({} discrimiants are still unsupported with reprs that allow them.)",
128 if self.has_large_repr {
130 } else if self.has_signed_repr {
140 if let Expr::Lit(ExprLit { lit: Lit::Int(i), .. }) = expr {
141 match i.base10_parse() {
142 Ok(val) => self.cur_discrim = val,
143 Err(_) => error(expr.span(), &discriminant_fail_message)?,
146 error(variant.span(), &discriminant_fail_message)?;
150 // Validate the discriminant.
151 let discriminant = self.cur_discrim;
152 if discriminant >= 128 {
153 let message = if self.variants.len() <= 127 {
154 "`#[derive(EnumSetType)]` currently only supports discriminants up to 127."
156 "`#[derive(EnumSetType)]` currently only supports enums up to 128 variants."
158 error(variant.span(), message)?;
160 if self.used_discriminants.contains(&discriminant) {
161 error(variant.span(), "Duplicated enum discriminant.")?;
164 // Add the variant to the info.
165 self.cur_discrim += 1;
166 if discriminant > self.max_discrim {
167 self.max_discrim = discriminant;
169 self.variants.push(EnumSetValue {
170 name: variant.ident.clone(),
171 variant_repr: discriminant,
173 self.used_variant_names.insert(variant.ident.to_string());
174 self.used_discriminants.insert(discriminant);
178 error(variant.span(), "`#[derive(EnumSetType)]` can only be used on fieldless enums.")
181 /// Validate the enumset type.
182 fn validate(&self) -> Result<()> {
183 // Check if all bits of the bitset can fit in the serialization representation.
184 if let Some(explicit_serde_repr) = &self.explicit_serde_repr {
185 let is_overflowed = match explicit_serde_repr.to_string().as_str() {
186 "u8" => self.max_discrim >= 8,
187 "u16" => self.max_discrim >= 16,
188 "u32" => self.max_discrim >= 32,
189 "u64" => self.max_discrim >= 64,
190 "u128" => self.max_discrim >= 128,
193 "Only `u8`, `u16`, `u32`, `u64` and `u128` are supported for serde_repr."
197 error(Span::call_site(), "serialize_repr cannot be smaller than bitset.")?;
203 /// Computes the underlying type used to store the enumset.
204 fn enumset_repr(&self) -> SynTokenStream {
205 if self.max_discrim <= 7 {
207 } else if self.max_discrim <= 15 {
209 } else if self.max_discrim <= 31 {
211 } else if self.max_discrim <= 63 {
213 } else if self.max_discrim <= 127 {
216 panic!("max_variant > 127?")
219 /// Computes the underlying type used to serialize the enumset.
220 #[cfg(feature = "serde")]
221 fn serde_repr(&self) -> SynTokenStream {
222 if let Some(serde_repr) = &self.explicit_serde_repr {
223 quote! { #serde_repr }
229 /// Returns a bitmask of all variants in the set.
230 fn all_variants(&self) -> u128 {
231 let mut accum = 0u128;
232 for variant in &self.variants {
233 assert!(variant.variant_repr <= 127);
234 accum |= 1u128 << variant.variant_repr as u128;
240 /// Generates the actual `EnumSetType` impl.
241 fn enum_set_type_impl(info: EnumSetInfo) -> SynTokenStream {
242 let name = &info.name;
243 let enumset = match &info.crate_name {
244 Some(crate_name) => quote!(::#crate_name),
245 None => quote!(::enumset),
247 let typed_enumset = quote!(#enumset::EnumSet<#name>);
248 let core = quote!(#enumset::__internal::core_export);
250 let repr = info.enumset_repr();
251 let all_variants = Literal::u128_unsuffixed(info.all_variants());
253 let ops = if info.no_ops {
257 impl <O : Into<#typed_enumset>> #core::ops::Sub<O> for #name {
258 type Output = #typed_enumset;
259 fn sub(self, other: O) -> Self::Output {
260 #enumset::EnumSet::only(self) - other.into()
263 impl <O : Into<#typed_enumset>> #core::ops::BitAnd<O> for #name {
264 type Output = #typed_enumset;
265 fn bitand(self, other: O) -> Self::Output {
266 #enumset::EnumSet::only(self) & other.into()
269 impl <O : Into<#typed_enumset>> #core::ops::BitOr<O> for #name {
270 type Output = #typed_enumset;
271 fn bitor(self, other: O) -> Self::Output {
272 #enumset::EnumSet::only(self) | other.into()
275 impl <O : Into<#typed_enumset>> #core::ops::BitXor<O> for #name {
276 type Output = #typed_enumset;
277 fn bitxor(self, other: O) -> Self::Output {
278 #enumset::EnumSet::only(self) ^ other.into()
281 impl #core::ops::Not for #name {
282 type Output = #typed_enumset;
283 fn not(self) -> Self::Output {
284 !#enumset::EnumSet::only(self)
287 impl #core::cmp::PartialEq<#typed_enumset> for #name {
288 fn eq(&self, other: &#typed_enumset) -> bool {
289 #enumset::EnumSet::only(*self) == *other
296 #[cfg(feature = "serde")]
297 let serde = quote!(#enumset::__internal::serde);
299 #[cfg(feature = "serde")]
300 let serde_ops = if info.serialize_as_list {
301 let expecting_str = format!("a list of {}", name);
303 fn serialize<S: #serde::Serializer>(
304 set: #enumset::EnumSet<#name>, ser: S,
305 ) -> #core::result::Result<S::Ok, S::Error> {
306 use #serde::ser::SerializeSeq;
307 let mut seq = ser.serialize_seq(#core::prelude::v1::Some(set.len()))?;
309 seq.serialize_element(&bit)?;
313 fn deserialize<'de, D: #serde::Deserializer<'de>>(
315 ) -> #core::result::Result<#enumset::EnumSet<#name>, D::Error> {
317 impl <'de> #serde::de::Visitor<'de> for Visitor {
318 type Value = #enumset::EnumSet<#name>;
320 &self, formatter: &mut #core::fmt::Formatter,
321 ) -> #core::fmt::Result {
322 write!(formatter, #expecting_str)
325 mut self, mut seq: A,
326 ) -> #core::result::Result<Self::Value, A::Error> where
327 A: #serde::de::SeqAccess<'de>
329 let mut accum = #enumset::EnumSet::<#name>::new();
330 while let #core::prelude::v1::Some(val) = seq.next_element::<#name>()? {
333 #core::prelude::v1::Ok(accum)
336 de.deserialize_seq(Visitor)
340 let serialize_repr = info.serde_repr();
341 let check_unknown = if info.serialize_deny_unknown {
343 if value & !#all_variants != 0 {
344 use #serde::de::Error;
345 return #core::prelude::v1::Err(
346 D::Error::custom("enumset contains unknown bits")
354 fn serialize<S: #serde::Serializer>(
355 set: #enumset::EnumSet<#name>, ser: S,
356 ) -> #core::result::Result<S::Ok, S::Error> {
357 #serde::Serialize::serialize(&(set.__priv_repr as #serialize_repr), ser)
359 fn deserialize<'de, D: #serde::Deserializer<'de>>(
361 ) -> #core::result::Result<#enumset::EnumSet<#name>, D::Error> {
362 let value = <#serialize_repr as #serde::Deserialize>::deserialize(de)?;
364 #core::prelude::v1::Ok(#enumset::EnumSet {
365 __priv_repr: (value & #all_variants) as #repr,
371 #[cfg(not(feature = "serde"))]
372 let serde_ops = quote! { };
374 let is_uninhabited = info.variants.is_empty();
375 let is_zst = info.variants.len() == 1;
376 let into_impl = if is_uninhabited {
378 fn enum_into_u32(self) -> u32 {
379 panic!(concat!(stringify!(#name), " is uninhabited."))
381 unsafe fn enum_from_u32(val: u32) -> Self {
382 panic!(concat!(stringify!(#name), " is uninhabited."))
386 let variant = &info.variants[0].name;
388 fn enum_into_u32(self) -> u32 {
391 unsafe fn enum_from_u32(val: u32) -> Self {
396 let variant_name: Vec<_> = info.variants.iter().map(|x| &x.name).collect();
397 let variant_value: Vec<_> = info.variants.iter().map(|x| x.variant_repr).collect();
399 let const_field: Vec<_> = ["IS_U8", "IS_U16", "IS_U32", "IS_U64", "IS_U128"]
400 .iter().map(|x| Ident::new(x, Span::call_site())).collect();
401 let int_type: Vec<_> = ["u8", "u16", "u32", "u64", "u128"]
402 .iter().map(|x| Ident::new(x, Span::call_site())).collect();
405 fn enum_into_u32(self) -> u32 {
408 unsafe fn enum_from_u32(val: u32) -> Self {
409 // We put these in const fields so the branches they guard aren't generated even
411 #(const #const_field: bool =
412 #core::mem::size_of::<#name>() == #core::mem::size_of::<#int_type>();)*
414 // Every valid variant value has an explicit branch. If they get optimized out,
415 // great. If the representation has changed somehow, and they don't, oh well,
416 // there's still no UB.
417 #(#variant_value => #name::#variant_name,)*
418 // Helps hint to the LLVM that this is a transmute. Note that this branch is
419 // still unreachable.
420 #(x if #const_field => {
421 let x = x as #int_type;
422 *(&x as *const _ as *const #name)
424 // Default case. Sometimes causes LLVM to generate a table instead of a simple
425 // transmute, but, oh well.
426 _ => #core::hint::unreachable_unchecked(),
432 let eq_impl = if is_uninhabited {
433 quote!(panic!(concat!(stringify!(#name), " is uninhabited.")))
435 quote!((*self as u32) == (*other as u32))
438 // used in the enum_set! macro `const fn`s.
439 let self_as_repr_mask = if is_uninhabited {
440 quote! { 0 } // impossible anyway
442 quote! { 1 << self as #repr }
445 let super_impls = if info.no_super_impls {
449 impl #core::cmp::PartialEq for #name {
450 fn eq(&self, other: &Self) -> bool {
454 impl #core::cmp::Eq for #name { }
455 #[allow(clippy::expl_impl_clone_on_copy)]
456 impl #core::clone::Clone for #name {
457 fn clone(&self) -> Self {
461 impl #core::marker::Copy for #name { }
466 unsafe impl #enumset::__internal::EnumSetTypePrivate for #name {
468 const ALL_BITS: Self::Repr = #all_variants;
473 unsafe impl #enumset::EnumSetType for #name { }
478 /// Creates a new enumset with only this variant.
479 #[deprecated(note = "This method is an internal implementation detail generated by \
480 the `enumset` crate's procedural macro. It should not be used \
481 directly. Use `EnumSet::only` instead.")]
483 pub const fn __impl_enumset_internal__const_only(self) -> #enumset::EnumSet<#name> {
484 #enumset::EnumSet { __priv_repr: #self_as_repr_mask }
487 /// Creates a new enumset with this variant added.
488 #[deprecated(note = "This method is an internal implementation detail generated by \
489 the `enumset` crate's procedural macro. It should not be used \
490 directly. Use the `|` operator instead.")]
492 pub const fn __impl_enumset_internal__const_merge(
493 self, chain: #enumset::EnumSet<#name>,
494 ) -> #enumset::EnumSet<#name> {
495 #enumset::EnumSet { __priv_repr: chain.__priv_repr | #self_as_repr_mask }
503 #[proc_macro_derive(EnumSetType, attributes(enumset))]
504 pub fn derive_enum_set_type(input: TokenStream) -> TokenStream {
505 let input: DeriveInput = parse_macro_input!(input);
506 let attrs: EnumsetAttrs = match EnumsetAttrs::from_derive_input(&input) {
508 Err(e) => return e.write_errors().into(),
510 match derive_enum_set_type_0(input, attrs) {
512 Err(e) => e.to_compile_error().into(),
515 fn derive_enum_set_type_0(input: DeriveInput, attrs: EnumsetAttrs) -> Result<TokenStream> {
516 if !input.generics.params.is_empty() {
518 input.generics.span(),
519 "`#[derive(EnumSetType)]` cannot be used on enums with type parameters.",
521 } else if let Data::Enum(data) = &input.data {
522 let mut info = EnumSetInfo::new(&input, attrs);
523 for attr in &input.attrs {
524 if attr.path.is_ident(&Ident::new("repr", Span::call_site())) {
525 let meta: Ident = attr.parse_args()?;
526 info.push_explicit_repr(attr.span(), meta.to_string().as_str())?;
529 for variant in &data.variants {
530 info.push_variant(variant)?;
533 Ok(enum_set_type_impl(info).into())
535 error(input.span(), "`#[derive(EnumSetType)]` may only be used on enums")