Debian Codegraph @

third_party/rust/enumset_derive/src/lib.rs

raw
1 #![recursion_limit = "256"]
2
3 extern crate proc_macro;
4
5 use darling::util::SpannedValue;
6 use darling::*;
7 use proc_macro::TokenStream;
8 use proc_macro2::{Literal, Span, TokenStream as SynTokenStream};
9 use quote::*;
10 use std::{collections::HashSet, fmt::Display};
11 use syn::spanned::Spanned;
12 use syn::{Error, Result, *};
13
14 /// Helper function for emitting compile errors.
15 fn error<T>(span: Span, message: impl Display) -> Result<T> {
16 Err(Error::new(span, message))
17 }
18
19 /// Decodes the custom attributes for our custom derive.
20 #[derive(FromDeriveInput, Default)]
21 #[darling(attributes(enumset), default)]
22 struct EnumsetAttrs {
23 no_ops: bool,
24 no_super_impls: bool,
25 #[darling(default)]
26 repr: SpannedValue<Option<String>>,
27 #[darling(default)]
28 serialize_repr: SpannedValue<Option<String>>,
29 serialize_deny_unknown: bool,
30 #[darling(default)]
31 crate_name: Option<String>,
32
33 // legacy options
34 serialize_as_list: SpannedValue<bool>, // replaced with serialize_repr
35 serialize_as_map: SpannedValue<bool>, // replaced with serialize_repr
36 }
37
38 /// The internal representation of an enumset.
39 #[derive(Copy, Clone)]
40 enum InternalRepr {
41 /// internal repr: `u8`
42 U8,
43 /// internal repr: `u16`
44 U16,
45 /// internal repr: `u32`
46 U32,
47 /// internal repr: `u64`
48 U64,
49 /// internal repr: `u128`
50 U128,
51 /// internal repr: `[u64; size]`
52 Array(usize),
53 }
54 impl InternalRepr {
55 /// Determines the number of variants supported by this repr.
56 fn supported_variants(&self) -> usize {
57 match self {
58 InternalRepr::U8 => 8,
59 InternalRepr::U16 => 16,
60 InternalRepr::U32 => 32,
61 InternalRepr::U64 => 64,
62 InternalRepr::U128 => 128,
63 InternalRepr::Array(size) => size * 64,
64 }
65 }
66 }
67
68 /// The serde representation of the enumset.
69 #[derive(Copy, Clone)]
70 enum SerdeRepr {
71 /// serde type: `u8`
72 U8,
73 /// serde type: `u16`
74 U16,
75 /// serde type: `u32`
76 U32,
77 /// serde type: `u64`
78 U64,
79 /// serde type: `u128`
80 U128,
81 /// serde type: list of `T`
82 List,
83 /// serde type: map of `T` to `bool`
84 Map,
85 /// serde type: list of `u64`
86 Array,
87 }
88 impl SerdeRepr {
89 /// Determines the number of variants supported by this repr.
90 fn supported_variants(&self) -> Option<usize> {
91 match self {
92 SerdeRepr::U8 => Some(8),
93 SerdeRepr::U16 => Some(16),
94 SerdeRepr::U32 => Some(32),
95 SerdeRepr::U64 => Some(64),
96 SerdeRepr::U128 => Some(128),
97 SerdeRepr::List => None,
98 SerdeRepr::Map => None,
99 SerdeRepr::Array => None,
100 }
101 }
102 }
103
104 /// An variant in the enum set type.
105 struct EnumSetValue {
106 /// The name of the variant.
107 name: Ident,
108 /// The discriminant of the variant.
109 variant_repr: u32,
110 }
111
112 /// Stores information about the enum set type.
113 #[allow(dead_code)]
114 struct EnumSetInfo {
115 /// The name of the enum.
116 name: Ident,
117 /// The crate name to use.
118 crate_name: Option<Ident>,
119 /// The numeric type to represent the `EnumSet` as in memory.
120 explicit_internal_repr: Option<InternalRepr>,
121 /// Forces the internal numeric type of the `EnumSet` to be an array.
122 internal_repr_force_array: bool,
123 /// The numeric type to serialize the enum as.
124 explicit_serde_repr: Option<SerdeRepr>,
125 /// A list of variants in the enum.
126 variants: Vec<EnumSetValue>,
127
128 /// The highest encountered variant discriminant.
129 max_discrim: u32,
130 /// The span of the highest encountered variant.
131 max_discrim_span: Option<Span>,
132 /// The current variant discriminant. Used to track, e.g. `A=10,B,C`.
133 cur_discrim: u32,
134 /// A list of variant names that are already in use.
135 used_variant_names: HashSet<String>,
136 /// A list of variant discriminants that are already in use.
137 used_discriminants: HashSet<u32>,
138
139 /// Avoid generating operator overloads on the enum type.
140 no_ops: bool,
141 /// Avoid generating implementations for `Clone`, `Copy`, `Eq`, and `PartialEq`.
142 no_super_impls: bool,
143 /// Disallow unknown bits while deserializing the enum.
144 serialize_deny_unknown: bool,
145 }
146 impl EnumSetInfo {
147 fn new(input: &DeriveInput, attrs: &EnumsetAttrs) -> EnumSetInfo {
148 EnumSetInfo {
149 name: input.ident.clone(),
150 crate_name: attrs
151 .crate_name
152 .as_ref()
153 .map(|x| Ident::new(x, Span::call_site())),
154 explicit_internal_repr: None,
155 internal_repr_force_array: false,
156 explicit_serde_repr: None,
157 variants: Vec::new(),
158 max_discrim: 0,
159 max_discrim_span: None,
160 cur_discrim: 0,
161 used_variant_names: HashSet::new(),
162 used_discriminants: HashSet::new(),
163 no_ops: attrs.no_ops,
164 no_super_impls: attrs.no_super_impls,
165 serialize_deny_unknown: attrs.serialize_deny_unknown,
166 }
167 }
168
169 /// Explicits sets the serde representation of the enumset from a string.
170 fn push_serialize_repr(&mut self, span: Span, ty: &str) -> Result<()> {
171 match ty {
172 "u8" => self.explicit_serde_repr = Some(SerdeRepr::U8),
173 "u16" => self.explicit_serde_repr = Some(SerdeRepr::U16),
174 "u32" => self.explicit_serde_repr = Some(SerdeRepr::U32),
175 "u64" => self.explicit_serde_repr = Some(SerdeRepr::U64),
176 "u128" => self.explicit_serde_repr = Some(SerdeRepr::U128),
177 "list" => self.explicit_serde_repr = Some(SerdeRepr::List),
178 "map" => self.explicit_serde_repr = Some(SerdeRepr::Map),
179 "array" => self.explicit_serde_repr = Some(SerdeRepr::Array),
180 _ => error(span, format!("`{}` is not a valid serialized representation.", ty))?,
181 }
182 Ok(())
183 }
184
185 /// Explicitly sets the representation of the enumset from a string.
186 fn push_repr(&mut self, span: Span, ty: &str) -> Result<()> {
187 match ty {
188 "u8" => self.explicit_internal_repr = Some(InternalRepr::U8),
189 "u16" => self.explicit_internal_repr = Some(InternalRepr::U16),
190 "u32" => self.explicit_internal_repr = Some(InternalRepr::U32),
191 "u64" => self.explicit_internal_repr = Some(InternalRepr::U64),
192 "u128" => self.explicit_internal_repr = Some(InternalRepr::U128),
193 "array" => self.internal_repr_force_array = true,
194 _ => error(span, format!("`{}` is not a valid internal enumset representation.", ty))?,
195 }
196 Ok(())
197 }
198
199 /// Adds a variant to the enumset.
200 fn push_variant(&mut self, variant: &Variant) -> Result<()> {
201 if self.used_variant_names.contains(&variant.ident.to_string()) {
202 error(variant.span(), "Duplicated variant name.")
203 } else if let Fields::Unit = variant.fields {
204 // Parse the discriminant.
205 if let Some((_, expr)) = &variant.discriminant {
206 if let Expr::Lit(ExprLit { lit: Lit::Int(i), .. }) = expr {
207 match i.base10_parse() {
208 Ok(val) => self.cur_discrim = val,
209 Err(_) => error(expr.span(), "Enum discriminants must fit into `u32`.")?,
210 }
211 } else if let Expr::Unary(ExprUnary { op: UnOp::Neg(_), .. }) = expr {
212 error(expr.span(), "Enum discriminants must not be negative.")?;
213 } else {
214 error(variant.span(), "Enum discriminants must be literal expressions.")?;
215 }
216 }
217
218 // Validate the discriminant.
219 let discriminant = self.cur_discrim;
220 if discriminant >= 0xFFFFFFC0 {
221 error(variant.span(), "Maximum discriminant allowed is `0xFFFFFFBF`.")?;
222 }
223 if self.used_discriminants.contains(&discriminant) {
224 error(variant.span(), "Duplicated enum discriminant.")?;
225 }
226
227 // Add the variant to the info.
228 self.cur_discrim += 1;
229 if discriminant > self.max_discrim {
230 self.max_discrim = discriminant;
231 self.max_discrim_span = Some(variant.span());
232 }
233 self.variants
234 .push(EnumSetValue { name: variant.ident.clone(), variant_repr: discriminant });
235 self.used_variant_names.insert(variant.ident.to_string());
236 self.used_discriminants.insert(discriminant);
237
238 Ok(())
239 } else {
240 error(variant.span(), "`#[derive(EnumSetType)]` can only be used on fieldless enums.")
241 }
242 }
243
244 /// Returns the actual internal representation of the set.
245 fn internal_repr(&self) -> InternalRepr {
246 match self.explicit_internal_repr {
247 Some(x) => x,
248 None => match self.max_discrim {
249 x if x < 8 && !self.internal_repr_force_array => InternalRepr::U8,
250 x if x < 16 && !self.internal_repr_force_array => InternalRepr::U16,
251 x if x < 32 && !self.internal_repr_force_array => InternalRepr::U32,
252 x if x < 64 && !self.internal_repr_force_array => InternalRepr::U64,
253 x => InternalRepr::Array((x as usize + 64) / 64),
254 },
255 }
256 }
257
258 /// Returns the actual serde representation of the set.
259 fn serde_repr(&self) -> SerdeRepr {
260 match self.explicit_serde_repr {
261 Some(x) => x,
262 None => match self.max_discrim {
263 x if x < 8 => SerdeRepr::U8,
264 x if x < 16 => SerdeRepr::U16,
265 x if x < 32 => SerdeRepr::U32,
266 x if x < 64 => SerdeRepr::U64,
267 x if x < 128 => SerdeRepr::U128,
268 _ => SerdeRepr::Array,
269 },
270 }
271 }
272
273 /// Validate the enumset type.
274 fn validate(&self) -> Result<()> {
275 // Gets the span of the maximum value.
276 let largest_discriminant_span = match &self.max_discrim_span {
277 Some(x) => *x,
278 None => Span::call_site(),
279 };
280
281 // Check if all bits of the bitset can fit in the memory representation, if one was given.
282 if self.internal_repr().supported_variants() <= self.max_discrim as usize {
283 error(
284 largest_discriminant_span,
285 "`repr` is too small to contain the largest discriminant.",
286 )?;
287 }
288
289 // Check if all bits of the bitset can fit in the serialization representation.
290 if let Some(supported_variants) = self.serde_repr().supported_variants() {
291 if supported_variants <= self.max_discrim as usize {
292 error(
293 largest_discriminant_span,
294 "`serialize_repr` is too small to contain the largest discriminant.",
295 )?;
296 }
297 }
298
299 Ok(())
300 }
301
302 /// Returns a bitmask of all variants in the set.
303 fn variant_map(&self) -> Vec<u64> {
304 let mut vec = vec![0];
305 for variant in &self.variants {
306 let (idx, bit) = (variant.variant_repr as usize / 64, variant.variant_repr % 64);
307 while idx >= vec.len() {
308 vec.push(0);
309 }
310 vec[idx] |= 1u64 << bit;
311 }
312 vec
313 }
314 }
315
316 /// Generates the actual `EnumSetType` impl.
317 fn enum_set_type_impl(info: EnumSetInfo, warnings: Vec<(Span, &'static str)>) -> SynTokenStream {
318 let name = &info.name;
319
320 let enumset = match &info.crate_name {
321 Some(crate_name) => quote!(::#crate_name),
322 None => {
323 #[cfg(feature = "proc-macro-crate")]
324 {
325 use proc_macro_crate::FoundCrate;
326
327 let crate_name = proc_macro_crate::crate_name("enumset");
328 match crate_name {
329 Ok(FoundCrate::Name(name)) => {
330 let ident = Ident::new(&name, Span::call_site());
331 quote!(::#ident)
332 }
333 _ => quote!(::enumset),
334 }
335 }
336
337 #[cfg(not(feature = "proc-macro-crate"))]
338 {
339 quote!(::enumset)
340 }
341 }
342 };
343 let typed_enumset = quote!(#enumset::EnumSet<#name>);
344 let core = quote!(#enumset::__internal::core_export);
345 let internal = quote!(#enumset::__internal);
346 #[cfg(feature = "serde")]
347 let serde = quote!(#enumset::__internal::serde);
348
349 let repr = match info.internal_repr() {
350 InternalRepr::U8 => quote! { u8 },
351 InternalRepr::U16 => quote! { u16 },
352 InternalRepr::U32 => quote! { u32 },
353 InternalRepr::U64 => quote! { u64 },
354 InternalRepr::U128 => quote! { u128 },
355 InternalRepr::Array(size) => quote! { #internal::ArrayRepr<{ #size }> },
356 };
357 let variant_map = info.variant_map();
358 let all_variants = match info.internal_repr() {
359 InternalRepr::U8 | InternalRepr::U16 | InternalRepr::U32 | InternalRepr::U64 => {
360 let lit = Literal::u64_unsuffixed(variant_map[0]);
361 quote! { #lit }
362 }
363 InternalRepr::U128 => {
364 let lit = Literal::u128_unsuffixed(
365 variant_map[0] as u128 | variant_map.get(1).map_or(0, |x| (*x as u128) << 64),
366 );
367 quote! { #lit }
368 }
369 InternalRepr::Array(size) => {
370 let mut new = Vec::new();
371 for i in 0..size {
372 new.push(Literal::u64_unsuffixed(*variant_map.get(i).unwrap_or(&0)));
373 }
374 quote! { #internal::ArrayRepr::<{ #size }>([#(#new,)*]) }
375 }
376 };
377
378 let ops = if info.no_ops {
379 quote! {}
380 } else {
381 quote! {
382 #[automatically_derived]
383 impl<O: Into<#typed_enumset>> #core::ops::Sub<O> for #name {
384 type Output = #typed_enumset;
385 fn sub(self, other: O) -> Self::Output {
386 #enumset::EnumSet::only(self) - other.into()
387 }
388 }
389 #[automatically_derived]
390 impl<O: Into<#typed_enumset>> #core::ops::BitAnd<O> for #name {
391 type Output = #typed_enumset;
392 fn bitand(self, other: O) -> Self::Output {
393 #enumset::EnumSet::only(self) & other.into()
394 }
395 }
396 #[automatically_derived]
397 impl<O: Into<#typed_enumset>> #core::ops::BitOr<O> for #name {
398 type Output = #typed_enumset;
399 fn bitor(self, other: O) -> Self::Output {
400 #enumset::EnumSet::only(self) | other.into()
401 }
402 }
403 #[automatically_derived]
404 impl<O: Into<#typed_enumset>> #core::ops::BitXor<O> for #name {
405 type Output = #typed_enumset;
406 fn bitxor(self, other: O) -> Self::Output {
407 #enumset::EnumSet::only(self) ^ other.into()
408 }
409 }
410 #[automatically_derived]
411 impl #core::ops::Not for #name {
412 type Output = #typed_enumset;
413 fn not(self) -> Self::Output {
414 !#enumset::EnumSet::only(self)
415 }
416 }
417 #[automatically_derived]
418 impl #core::cmp::PartialEq<#typed_enumset> for #name {
419 fn eq(&self, other: &#typed_enumset) -> bool {
420 #enumset::EnumSet::only(*self) == *other
421 }
422 }
423 }
424 };
425
426 #[cfg(feature = "serde")]
427 let serde_repr = info.serde_repr();
428
429 #[cfg(feature = "serde")]
430 let serde_ops = match serde_repr {
431 SerdeRepr::U8 | SerdeRepr::U16 | SerdeRepr::U32 | SerdeRepr::U64 | SerdeRepr::U128 => {
432 let (serialize_repr, from_fn, to_fn) = match serde_repr {
433 SerdeRepr::U8 => (quote! { u8 }, quote! { from_u8 }, quote! { to_u8 }),
434 SerdeRepr::U16 => (quote! { u16 }, quote! { from_u16 }, quote! { to_u16 }),
435 SerdeRepr::U32 => (quote! { u32 }, quote! { from_u32 }, quote! { to_u32 }),
436 SerdeRepr::U64 => (quote! { u64 }, quote! { from_u64 }, quote! { to_u64 }),
437 SerdeRepr::U128 => (quote! { u128 }, quote! { from_u128 }, quote! { to_u128 }),
438 _ => unreachable!(),
439 };
440 let check_unknown = if info.serialize_deny_unknown {
441 quote! {
442 if value & !#all_variants != 0 {
443 use #serde::de::Error;
444 return #core::prelude::v1::Err(
445 D::Error::custom("enumset contains unknown bits")
446 )
447 }
448 }
449 } else {
450 quote! {}
451 };
452 quote! {
453 fn serialize<S: #serde::Serializer>(
454 set: #enumset::EnumSet<#name>, ser: S,
455 ) -> #core::result::Result<S::Ok, S::Error> {
456 let value =
457 <#repr as #enumset::__internal::EnumSetTypeRepr>::#to_fn(&set.__priv_repr);
458 #serde::Serialize::serialize(&value, ser)
459 }
460 fn deserialize<'de, D: #serde::Deserializer<'de>>(
461 de: D,
462 ) -> #core::result::Result<#enumset::EnumSet<#name>, D::Error> {
463 let value = <#serialize_repr as #serde::Deserialize>::deserialize(de)?;
464 #check_unknown
465 let value = <#repr as #enumset::__internal::EnumSetTypeRepr>::#from_fn(value);
466 #core::prelude::v1::Ok(#enumset::EnumSet {
467 __priv_repr: value & #all_variants,
468 })
469 }
470 }
471 }
472 SerdeRepr::List => {
473 let expecting_str = format!("a list of {}", name);
474 quote! {
475 fn serialize<S: #serde::Serializer>(
476 set: #enumset::EnumSet<#name>, ser: S,
477 ) -> #core::result::Result<S::Ok, S::Error> {
478 use #serde::ser::SerializeSeq;
479 let mut seq = ser.serialize_seq(#core::prelude::v1::Some(set.len()))?;
480 for bit in set {
481 seq.serialize_element(&bit)?;
482 }
483 seq.end()
484 }
485 fn deserialize<'de, D: #serde::Deserializer<'de>>(
486 de: D,
487 ) -> #core::result::Result<#enumset::EnumSet<#name>, D::Error> {
488 struct Visitor;
489 impl <'de> #serde::de::Visitor<'de> for Visitor {
490 type Value = #enumset::EnumSet<#name>;
491 fn expecting(
492 &self, formatter: &mut #core::fmt::Formatter,
493 ) -> #core::fmt::Result {
494 write!(formatter, #expecting_str)
495 }
496 fn visit_seq<A>(
497 mut self, mut seq: A,
498 ) -> #core::result::Result<Self::Value, A::Error> where
499 A: #serde::de::SeqAccess<'de>
500 {
501 let mut accum = #enumset::EnumSet::<#name>::new();
502 while let #core::prelude::v1::Some(val) = seq.next_element::<#name>()? {
503 accum |= val;
504 }
505 #core::prelude::v1::Ok(accum)
506 }
507 }
508 de.deserialize_seq(Visitor)
509 }
510 }
511 }
512 SerdeRepr::Map => {
513 let expecting_str = format!("a map from {} to bool", name);
514 quote! {
515 fn serialize<S: #serde::Serializer>(
516 set: #enumset::EnumSet<#name>, ser: S,
517 ) -> #core::result::Result<S::Ok, S::Error> {
518 use #serde::ser::SerializeMap;
519 let mut map = ser.serialize_map(#core::prelude::v1::Some(set.len()))?;
520 for bit in set {
521 map.serialize_entry(&bit, &true)?;
522 }
523 map.end()
524 }
525 fn deserialize<'de, D: #serde::Deserializer<'de>>(
526 de: D,
527 ) -> #core::result::Result<#enumset::EnumSet<#name>, D::Error> {
528 struct Visitor;
529 impl <'de> #serde::de::Visitor<'de> for Visitor {
530 type Value = #enumset::EnumSet<#name>;
531 fn expecting(
532 &self, formatter: &mut #core::fmt::Formatter,
533 ) -> #core::fmt::Result {
534 write!(formatter, #expecting_str)
535 }
536 fn visit_map<A>(
537 mut self, mut map: A,
538 ) -> #core::result::Result<Self::Value, A::Error> where
539 A: #serde::de::MapAccess<'de>
540 {
541 let mut accum = #enumset::EnumSet::<#name>::new();
542 while let #core::prelude::v1::Some((val, is_present)) =
543 map.next_entry::<#name, bool>()?
544 {
545 if is_present {
546 accum |= val;
547 }
548 }
549 #core::prelude::v1::Ok(accum)
550 }
551 }
552 de.deserialize_map(Visitor)
553 }
554 }
555 }
556 SerdeRepr::Array => {
557 let preferred_size = quote! {
558 <<#name as #internal::EnumSetTypePrivate>::Repr as #internal::EnumSetTypeRepr>
559 ::PREFERRED_ARRAY_LEN
560 };
561 let (check_extra, convert_array) = if info.serialize_deny_unknown {
562 (
563 quote! {
564 if _val != 0 {
565 return #core::prelude::v1::Err(
566 D::Error::custom("enumset contains unknown bits")
567 )
568 }
569 },
570 quote! {
571 match #enumset::EnumSet::<#name>::try_from_array(accum) {
572 Some(x) => x,
573 None => #core::prelude::v1::Err(
574 D::Error::custom("enumset contains unknown bits")
575 ),
576 }
577 },
578 )
579 } else {
580 (quote! {}, quote! {
581 #core::prelude::v1::Ok(#enumset::EnumSet::<#name>::from_array(accum))
582 })
583 };
584 quote! {
585 fn serialize<S: #serde::Serializer>(
586 set: #enumset::EnumSet<#name>, ser: S,
587 ) -> #core::result::Result<S::Ok, S::Error> {
588 // read the enum as an array
589 let array = set.as_array::<{ #preferred_size }>();
590
591 // find the last non-zero value in the array
592 let mut end = array.len();
593 for i in (0..array.len()).rev() {
594 if array[i] != 0 {
595 break;
596 }
597 end = i + 1;
598 }
599
600 // serialize the array
601 #serde::Serialize::serialize(&array[..end], ser)
602 }
603 fn deserialize<'de, D: #serde::Deserializer<'de>>(
604 de: D,
605 ) -> #core::result::Result<#enumset::EnumSet<#name>, D::Error> {
606 struct Visitor;
607 impl <'de> #serde::de::Visitor<'de> for Visitor {
608 type Value = #enumset::EnumSet<#name>;
609 fn expecting(
610 &self, formatter: &mut #core::fmt::Formatter,
611 ) -> #core::fmt::Result {
612 write!(formatter, "a list of u64")
613 }
614 fn visit_seq<A>(
615 mut self, mut seq: A,
616 ) -> #core::result::Result<Self::Value, A::Error> where
617 A: #serde::de::SeqAccess<'de>
618 {
619 let mut accum = [0; #preferred_size];
620
621 let mut i = 0;
622 while let #core::prelude::v1::Some(val) = seq.next_element::<u64>()? {
623 accum[i] = val;
624 i += 1;
625
626 if i == accum.len() {
627 break;
628 }
629 }
630 while let #core::prelude::v1::Some(_val) = seq.next_element::<u64>()? {
631 #check_extra
632 }
633
634 #convert_array
635 }
636 }
637 de.deserialize_seq(Visitor)
638 }
639 }
640 }
641 };
642
643 #[cfg(not(feature = "serde"))]
644 let serde_ops = quote! {};
645
646 let is_uninhabited = info.variants.is_empty();
647 let is_zst = info.variants.len() == 1;
648 let into_impl = if is_uninhabited {
649 quote! {
650 fn enum_into_u32(self) -> u32 {
651 panic!(concat!(stringify!(#name), " is uninhabited."))
652 }
653 unsafe fn enum_from_u32(val: u32) -> Self {
654 panic!(concat!(stringify!(#name), " is uninhabited."))
655 }
656 }
657 } else if is_zst {
658 let variant = &info.variants[0].name;
659 quote! {
660 fn enum_into_u32(self) -> u32 {
661 self as u32
662 }
663 unsafe fn enum_from_u32(val: u32) -> Self {
664 #name::#variant
665 }
666 }
667 } else {
668 let variant_name: Vec<_> = info.variants.iter().map(|x| &x.name).collect();
669 let variant_value: Vec<_> = info.variants.iter().map(|x| x.variant_repr).collect();
670
671 let const_field: Vec<_> = ["IS_U8", "IS_U16", "IS_U32", "IS_U64", "IS_U128"]
672 .iter()
673 .map(|x| Ident::new(x, Span::call_site()))
674 .collect();
675 let int_type: Vec<_> = ["u8", "u16", "u32", "u64", "u128"]
676 .iter()
677 .map(|x| Ident::new(x, Span::call_site()))
678 .collect();
679
680 quote! {
681 fn enum_into_u32(self) -> u32 {
682 self as u32
683 }
684 unsafe fn enum_from_u32(val: u32) -> Self {
685 // We put these in const fields so the branches they guard aren't generated even
686 // on -O0
687 #(const #const_field: bool =
688 #core::mem::size_of::<#name>() == #core::mem::size_of::<#int_type>();)*
689 match val {
690 // Every valid variant value has an explicit branch. If they get optimized out,
691 // great. If the representation has changed somehow, and they don't, oh well,
692 // there's still no UB.
693 #(#variant_value => #name::#variant_name,)*
694 // Helps hint to the LLVM that this is a transmute. Note that this branch is
695 // still unreachable.
696 #(x if #const_field => {
697 let x = x as #int_type;
698 *(&x as *const _ as *const #name)
699 })*
700 // Default case. Sometimes causes LLVM to generate a table instead of a simple
701 // transmute, but, oh well.
702 _ => #core::hint::unreachable_unchecked(),
703 }
704 }
705 }
706 };
707
708 let eq_impl = if is_uninhabited {
709 quote!(panic!(concat!(stringify!(#name), " is uninhabited.")))
710 } else {
711 quote!((*self as u32) == (*other as u32))
712 };
713
714 let super_impls = if info.no_super_impls {
715 quote! {}
716 } else {
717 quote! {
718 #[automatically_derived]
719 impl #core::cmp::PartialEq for #name {
720 fn eq(&self, other: &Self) -> bool {
721 #eq_impl
722 }
723 }
724 #[automatically_derived]
725 impl #core::cmp::Eq for #name { }
726 #[automatically_derived]
727 #[allow(clippy::expl_impl_clone_on_copy)]
728 impl #core::clone::Clone for #name {
729 fn clone(&self) -> Self {
730 *self
731 }
732 }
733 #[automatically_derived]
734 impl #core::marker::Copy for #name { }
735 }
736 };
737
738 let impl_with_repr = if info.explicit_internal_repr.is_some() {
739 quote! {
740 #[automatically_derived]
741 unsafe impl #enumset::EnumSetTypeWithRepr for #name {
742 type Repr = #repr;
743 }
744 }
745 } else {
746 quote! {}
747 };
748
749 let inherent_impl_blocks = match info.internal_repr() {
750 InternalRepr::U8
751 | InternalRepr::U16
752 | InternalRepr::U32
753 | InternalRepr::U64
754 | InternalRepr::U128 => {
755 let self_as_repr_mask = if is_uninhabited {
756 quote! { 0 } // impossible anyway
757 } else {
758 quote! { 1 << self as #repr }
759 };
760
761 quote! {
762 #[automatically_derived]
763 #[doc(hidden)]
764 impl #name {
765 /// Creates a new enumset with only this variant.
766 #[deprecated(note = "This method is an internal implementation detail \
767 generated by the `enumset` crate's procedural macro. It \
768 should not be used directly.")]
769 #[doc(hidden)]
770 pub const fn __impl_enumset_internal__const_only(
771 self,
772 ) -> #enumset::EnumSet<#name> {
773 #enumset::EnumSet { __priv_repr: #self_as_repr_mask }
774 }
775
776 /// Creates a new enumset with this variant added.
777 #[deprecated(note = "This method is an internal implementation detail \
778 generated by the `enumset` crate's procedural macro. It \
779 should not be used directly.")]
780 #[doc(hidden)]
781 pub const fn __impl_enumset_internal__const_merge(
782 self, chain: #enumset::EnumSet<#name>,
783 ) -> #enumset::EnumSet<#name> {
784 #enumset::EnumSet { __priv_repr: chain.__priv_repr | #self_as_repr_mask }
785 }
786 }
787 }
788 }
789 InternalRepr::Array(size) => {
790 quote! {
791 #[automatically_derived]
792 #[doc(hidden)]
793 impl #name {
794 /// Creates a new enumset with only this variant.
795 #[deprecated(note = "This method is an internal implementation detail \
796 generated by the `enumset` crate's procedural macro. It \
797 should not be used directly.")]
798 #[doc(hidden)]
799 pub const fn __impl_enumset_internal__const_only(
800 self,
801 ) -> #enumset::EnumSet<#name> {
802 let mut set = #enumset::EnumSet::<#name> {
803 __priv_repr: #internal::ArrayRepr::<{ #size }>([0; #size]),
804 };
805 let bit = self as u32;
806 let (idx, bit) = (bit as usize / 64, bit % 64);
807 set.__priv_repr.0[idx] |= 1u64 << bit;
808 set
809 }
810
811 /// Creates a new enumset with this variant added.
812 #[deprecated(note = "This method is an internal implementation detail \
813 generated by the `enumset` crate's procedural macro. It \
814 should not be used directly.")]
815 #[doc(hidden)]
816 pub const fn __impl_enumset_internal__const_merge(
817 self, mut chain: #enumset::EnumSet<#name>,
818 ) -> #enumset::EnumSet<#name> {
819 let bit = self as u32;
820 let (idx, bit) = (bit as usize / 64, bit % 64);
821 chain.__priv_repr.0[idx] |= 1u64 << bit;
822 chain
823 }
824 }
825 }
826 }
827 };
828
829 let mut generated_warnings = SynTokenStream::new();
830 for (span, warning) in warnings {
831 generated_warnings.extend(quote_spanned! {
832 span => {
833 #[deprecated(note = #warning)]
834 #[allow(non_upper_case_globals)]
835 const _w: () = ();
836 let _ = _w;
837 }
838 });
839 }
840
841 let bit_width = info.max_discrim + 1;
842 let variant_count = info.variants.len() as u32;
843 quote! {
844 #[automatically_derived]
845 unsafe impl #internal::EnumSetTypePrivate for #name {
846 type Repr = #repr;
847 const ALL_BITS: Self::Repr = #all_variants;
848 const BIT_WIDTH: u32 = #bit_width;
849 const VARIANT_COUNT: u32 = #variant_count;
850 #into_impl
851 #serde_ops
852 }
853
854 #[automatically_derived]
855 unsafe impl #enumset::EnumSetType for #name { }
856
857 #impl_with_repr
858 #super_impls
859 #inherent_impl_blocks
860
861 #ops
862
863 const _: () = {
864 fn __enumset_derive__generated_warnings() {
865 #generated_warnings
866 }
867 };
868 }
869 }
870
871 #[proc_macro_derive(EnumSetType, attributes(enumset))]
872 pub fn derive_enum_set_type(input: TokenStream) -> TokenStream {
873 let input: DeriveInput = parse_macro_input!(input);
874 let attrs: EnumsetAttrs = match EnumsetAttrs::from_derive_input(&input) {
875 Ok(attrs) => attrs,
876 Err(e) => return e.write_errors().into(),
877 };
878 match derive_enum_set_type_0(input, attrs) {
879 Ok(v) => v,
880 Err(e) => e.to_compile_error().into(),
881 }
882 }
883 fn derive_enum_set_type_0(input: DeriveInput, attrs: EnumsetAttrs) -> Result<TokenStream> {
884 if !input.generics.params.is_empty() {
885 error(
886 input.generics.span(),
887 "`#[derive(EnumSetType)]` cannot be used on enums with type parameters.",
888 )
889 } else if let Data::Enum(data) = &input.data {
890 let mut info = EnumSetInfo::new(&input, &attrs);
891 let mut warnings = Vec::new();
892
893 // Check enum repr
894 for attr in &input.attrs {
895 if attr.path().is_ident("repr") {
896 let meta: Ident = attr.parse_args()?;
897 match meta.to_string().as_str() {
898 "C" | "Rust" => {}
899 "u8" | "u16" | "u32" | "u64" | "u128" | "usize" => {}
900 "i8" | "i16" | "i32" | "i64" | "i128" | "isize" => {}
901 x => error(
902 attr.span(),
903 format!("`#[repr({})]` cannot be used on enumset variants.", x),
904 )?,
905 }
906 }
907 }
908
909 // Parse internal representations
910 if let Some(repr) = &*attrs.repr {
911 info.push_repr(attrs.repr.span(), repr)?;
912 }
913
914 // Parse serialization representations
915 if let Some(serialize_repr) = &*attrs.serialize_repr {
916 info.push_serialize_repr(attrs.serialize_repr.span(), serialize_repr)?;
917 }
918 if *attrs.serialize_as_map {
919 info.explicit_serde_repr = Some(SerdeRepr::Map);
920 warnings.push((
921 attrs.serialize_as_map.span(),
922 "#[enumset(serialize_as_map)] is deprecated. \
923 Use `#[enumset(serialize_repr = \"map\")]` instead.",
924 ));
925 }
926 if *attrs.serialize_as_list {
927 // in old versions, serialize_as_list will override serialize_as_map
928 info.explicit_serde_repr = Some(SerdeRepr::List);
929 warnings.push((
930 attrs.serialize_as_list.span(),
931 "#[enumset(serialize_as_list)] is deprecated. \
932 Use `#[enumset(serialize_repr = \"list\")]` instead.",
933 ));
934 }
935
936 // Parse enum variants
937 for variant in &data.variants {
938 info.push_variant(variant)?;
939 }
940
941 // Validate the enumset
942 info.validate()?;
943
944 // Generates the actual `EnumSetType` implementation
945 Ok(enum_set_type_impl(info, warnings).into())
946 } else {
947 error(input.span(), "`#[derive(EnumSetType)]` may only be used on enums")
948 }
949 }