]> git.lizzy.rs Git - enumset.git/blob - enumset_derive/src/lib.rs
50fad1a6bd914d7100f37c58e24e1e8631610f9a
[enumset.git] / enumset_derive / src / lib.rs
1 #![recursion_limit="256"]
2
3 extern crate proc_macro;
4
5 use darling::*;
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;
11 use quote::*;
12
13 /// Helper function for emitting compile errors.
14 fn error<T>(span: Span, message: &str) -> Result<T> {
15     Err(Error::new(span, message))
16 }
17
18 /// Decodes the custom attributes for our custom derive.
19 #[derive(FromDeriveInput, Default)]
20 #[darling(attributes(enumset), default)]
21 struct EnumsetAttrs {
22     no_ops: bool,
23     no_super_impls: bool,
24     serialize_as_list: bool,
25     serialize_deny_unknown: bool,
26     #[darling(default)]
27     serialize_repr: Option<String>,
28     #[darling(default)]
29     crate_name: Option<String>,
30 }
31
32 /// An variant in the enum set type.
33 struct EnumSetValue {
34     /// The name of the variant.
35     name: Ident,
36     /// The discriminant of the variant.
37     variant_repr: u32,
38 }
39
40 /// Stores information about the enum set type.
41 #[allow(dead_code)]
42 struct EnumSetInfo {
43     /// The name of the enum.
44     name: Ident,
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.
52     has_large_repr: bool,
53     /// A list of variants in the enum.
54     variants: Vec<EnumSetValue>,
55
56     /// The highest encountered variant discriminant.
57     max_discrim: u32,
58     /// The current variant discriminant. Used to track, e.g. `A=10,B,C`.
59     cur_discrim: u32,
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>,
64
65     /// Avoid generating operator overloads on the enum type.
66     no_ops: bool,
67     /// Avoid generating implementations for `Clone`, `Copy`, `Eq`, and `PartialEq`.
68     no_super_impls: bool,
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,
73 }
74 impl EnumSetInfo {
75     fn new(input: &DeriveInput, attrs: EnumsetAttrs) -> EnumSetInfo {
76         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,
82             variants: Vec::new(),
83             max_discrim: 0,
84             cur_discrim: 0,
85             used_variant_names: HashSet::new(),
86             used_discriminants: HashSet::new(),
87             no_ops: attrs.no_ops,
88             no_super_impls: attrs.no_super_impls,
89             serialize_as_list: attrs.serialize_as_list,
90             serialize_deny_unknown: attrs.serialize_deny_unknown
91         }
92     }
93
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
97         // messages later on.
98         match repr {
99             "Rust" | "C" | "u8" | "u16" | "u32" => Ok(()),
100             "usize" | "u64" | "u128" => {
101                 self.has_large_repr = true;
102                 Ok(())
103             }
104             "i8" | "i16" | "i32" => {
105                 self.has_signed_repr = true;
106                 Ok(())
107             }
108             "isize" | "i64" | "i128" => {
109                 self.has_signed_repr = true;
110                 self.has_large_repr = true;
111                 Ok(())
112             }
113             _ => error(attr_span, "Unsupported repr.")
114         }
115     }
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 {
126                         format!(
127                             " ({} discrimiants are still unsupported with reprs that allow them.)",
128                             if self.has_large_repr {
129                                 "larger"
130                             } else if self.has_signed_repr {
131                                 "negative"
132                             } else {
133                                 "larger or negative"
134                             }
135                         )
136                     } else {
137                         String::new()
138                     },
139                 );
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)?,
144                     }
145                 } else {
146                     error(variant.span(), &discriminant_fail_message)?;
147                 }
148             }
149
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."
155                 } else {
156                     "`#[derive(EnumSetType)]` currently only supports enums up to 128 variants."
157                 };
158                 error(variant.span(), message)?;
159             }
160             if self.used_discriminants.contains(&discriminant) {
161                 error(variant.span(), "Duplicated enum discriminant.")?;
162             }
163
164             // Add the variant to the info.
165             self.cur_discrim += 1;
166             if discriminant > self.max_discrim {
167                 self.max_discrim = discriminant;
168             }
169             self.variants.push(EnumSetValue {
170                 name: variant.ident.clone(),
171                 variant_repr: discriminant,
172             });
173             self.used_variant_names.insert(variant.ident.to_string());
174             self.used_discriminants.insert(discriminant);
175
176             Ok(())
177         } else {
178             error(variant.span(), "`#[derive(EnumSetType)]` can only be used on fieldless enums.")
179         }
180     }
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,
191                 _ => error(
192                     Span::call_site(),
193                     "Only `u8`, `u16`, `u32`, `u64` and `u128` are supported for serde_repr."
194                 )?,
195             };
196             if is_overflowed {
197                 error(Span::call_site(), "serialize_repr cannot be smaller than bitset.")?;
198             }
199         }
200         Ok(())
201     }
202
203     /// Computes the underlying type used to store the enumset.
204     fn enumset_repr(&self) -> SynTokenStream {
205         if self.max_discrim <= 7 {
206             quote! { u8 }
207         } else if self.max_discrim <= 15 {
208             quote! { u16 }
209         } else if self.max_discrim <= 31 {
210             quote! { u32 }
211         } else if self.max_discrim <= 63 {
212             quote! { u64 }
213         } else if self.max_discrim <= 127 {
214             quote! { u128 }
215         } else {
216             panic!("max_variant > 127?")
217         }
218     }
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 }
224         } else {
225             self.enumset_repr()
226         }
227     }
228
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;
235         }
236         accum
237     }
238 }
239
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),
246     };
247     let typed_enumset = quote!(#enumset::EnumSet<#name>);
248     let core = quote!(#enumset::__internal::core_export);
249
250     let repr = info.enumset_repr();
251     let all_variants = Literal::u128_unsuffixed(info.all_variants());
252
253     let ops = if info.no_ops {
254         quote! {}
255     } else {
256         quote! {
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()
261                 }
262             }
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()
267                 }
268             }
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()
273                 }
274             }
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()
279                 }
280             }
281             impl #core::ops::Not for #name {
282                 type Output = #typed_enumset;
283                 fn not(self) -> Self::Output {
284                     !#enumset::EnumSet::only(self)
285                 }
286             }
287             impl #core::cmp::PartialEq<#typed_enumset> for #name {
288                 fn eq(&self, other: &#typed_enumset) -> bool {
289                     #enumset::EnumSet::only(*self) == *other
290                 }
291             }
292         }
293     };
294
295
296     #[cfg(feature = "serde")]
297     let serde = quote!(#enumset::__internal::serde);
298
299     #[cfg(feature = "serde")]
300     let serde_ops = if info.serialize_as_list {
301         let expecting_str = format!("a list of {}", name);
302         quote! {
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()))?;
308                 for bit in set {
309                     seq.serialize_element(&bit)?;
310                 }
311                 seq.end()
312             }
313             fn deserialize<'de, D: #serde::Deserializer<'de>>(
314                 de: D,
315             ) -> #core::result::Result<#enumset::EnumSet<#name>, D::Error> {
316                 struct Visitor;
317                 impl <'de> #serde::de::Visitor<'de> for Visitor {
318                     type Value = #enumset::EnumSet<#name>;
319                     fn expecting(
320                         &self, formatter: &mut #core::fmt::Formatter,
321                     ) -> #core::fmt::Result {
322                         write!(formatter, #expecting_str)
323                     }
324                     fn visit_seq<A>(
325                         mut self, mut seq: A,
326                     ) -> #core::result::Result<Self::Value, A::Error> where
327                         A: #serde::de::SeqAccess<'de>
328                     {
329                         let mut accum = #enumset::EnumSet::<#name>::new();
330                         while let #core::prelude::v1::Some(val) = seq.next_element::<#name>()? {
331                             accum |= val;
332                         }
333                         #core::prelude::v1::Ok(accum)
334                     }
335                 }
336                 de.deserialize_seq(Visitor)
337             }
338         }
339     } else {
340         let serialize_repr = info.serde_repr();
341         let check_unknown = if info.serialize_deny_unknown {
342             quote! {
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")
347                     )
348                 }
349             }
350         } else {
351             quote! { }
352         };
353         quote! {
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)
358             }
359             fn deserialize<'de, D: #serde::Deserializer<'de>>(
360                 de: D,
361             ) -> #core::result::Result<#enumset::EnumSet<#name>, D::Error> {
362                 let value = <#serialize_repr as #serde::Deserialize>::deserialize(de)?;
363                 #check_unknown
364                 #core::prelude::v1::Ok(#enumset::EnumSet {
365                     __priv_repr: (value & #all_variants) as #repr,
366                 })
367             }
368         }
369     };
370
371     #[cfg(not(feature = "serde"))]
372     let serde_ops = quote! { };
373
374     let is_uninhabited = info.variants.is_empty();
375     let is_zst = info.variants.len() == 1;
376     let into_impl = if is_uninhabited {
377         quote! {
378             fn enum_into_u32(self) -> u32 {
379                 panic!(concat!(stringify!(#name), " is uninhabited."))
380             }
381             unsafe fn enum_from_u32(val: u32) -> Self {
382                 panic!(concat!(stringify!(#name), " is uninhabited."))
383             }
384         }
385     } else if is_zst {
386         let variant = &info.variants[0].name;
387         quote! {
388             fn enum_into_u32(self) -> u32 {
389                 self as u32
390             }
391             unsafe fn enum_from_u32(val: u32) -> Self {
392                 #name::#variant
393             }
394         }
395     } else {
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();
398
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();
403
404         quote! {
405             fn enum_into_u32(self) -> u32 {
406                 self as u32
407             }
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
410                 // on -O0
411                 #(const #const_field: bool =
412                     #core::mem::size_of::<#name>() == #core::mem::size_of::<#int_type>();)*
413                 match val {
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)
423                     })*
424                     // Default case. Sometimes causes LLVM to generate a table instead of a simple
425                     // transmute, but, oh well.
426                     _ => #core::hint::unreachable_unchecked(),
427                 }
428             }
429         }
430     };
431
432     let eq_impl = if is_uninhabited {
433         quote!(panic!(concat!(stringify!(#name), " is uninhabited.")))
434     } else {
435         quote!((*self as u32) == (*other as u32))
436     };
437
438     // used in the enum_set! macro `const fn`s.
439     let self_as_repr_mask = if is_uninhabited {
440         quote! { 0 } // impossible anyway
441     } else {
442         quote! { 1 << self as #repr }
443     };
444
445     let super_impls = if info.no_super_impls {
446         quote! {}
447     } else {
448         quote! {
449             impl #core::cmp::PartialEq for #name {
450                 fn eq(&self, other: &Self) -> bool {
451                     #eq_impl
452                 }
453             }
454             impl #core::cmp::Eq for #name { }
455             impl #core::clone::Clone for #name {
456                 fn clone(&self) -> Self {
457                     *self
458                 }
459             }
460             impl #core::marker::Copy for #name { }
461         }
462     };
463
464     quote! {
465         unsafe impl #enumset::__internal::EnumSetTypePrivate for #name {
466             type Repr = #repr;
467             const ALL_BITS: Self::Repr = #all_variants;
468             #into_impl
469             #serde_ops
470         }
471
472         unsafe impl #enumset::EnumSetType for #name { }
473
474         #super_impls
475
476         impl #name {
477             /// Creates a new enumset with only this variant.
478             #[deprecated(note = "This method is an internal implementation detail generated by \
479                                  the `enumset` crate's procedural macro. It should not be used \
480                                  directly. Use `EnumSet::only` instead.")]
481             #[doc(hidden)]
482             pub const fn __impl_enumset_internal__const_only(self) -> #enumset::EnumSet<#name> {
483                 #enumset::EnumSet { __priv_repr: #self_as_repr_mask }
484             }
485
486             /// Creates a new enumset with this variant added.
487             #[deprecated(note = "This method is an internal implementation detail generated by \
488                                  the `enumset` crate's procedural macro. It should not be used \
489                                  directly. Use the `|` operator instead.")]
490             #[doc(hidden)]
491             pub const fn __impl_enumset_internal__const_merge(
492                 self, chain: #enumset::EnumSet<#name>,
493             ) -> #enumset::EnumSet<#name> {
494                 #enumset::EnumSet { __priv_repr: chain.__priv_repr | #self_as_repr_mask }
495             }
496         }
497
498         #ops
499     }
500 }
501
502 /// A wrapper that parses the input enum.
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) {
507         Ok(attrs) => attrs,
508         Err(e) => return e.write_errors().into(),
509     };
510     match derive_enum_set_type_0(input, attrs) {
511         Ok(v) => v,
512         Err(e) => e.to_compile_error().into(),
513     }
514 }
515 fn derive_enum_set_type_0(input: DeriveInput, attrs: EnumsetAttrs) -> Result<TokenStream> {
516     if !input.generics.params.is_empty() {
517         error(
518             input.generics.span(),
519             "`#[derive(EnumSetType)]` cannot be used on enums with type parameters.",
520         )
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())?;
527             }
528         }
529         for variant in &data.variants {
530             info.push_variant(variant)?;
531         }
532         info.validate()?;
533         Ok(enum_set_type_impl(info).into())
534     } else {
535         error(input.span(), "`#[derive(EnumSetType)]` may only be used on enums")
536     }
537 }