Debian Codegraph @

src/traits.rs

raw
1 #![allow(unused_imports)]
2 use std::{cmp, convert::TryFrom};
3
4 use proc_macro2::{Ident, Span, TokenStream, TokenTree};
5 use quote::{quote, ToTokens};
6 use syn::{
7 parse::{Parse, ParseStream, Parser},
8 punctuated::Punctuated,
9 spanned::Spanned,
10 Result, *,
11 };
12
13 macro_rules! bail {
14 ($msg:expr $(,)?) => {
15 return Err(Error::new(Span::call_site(), &$msg[..]))
16 };
17
18 ( $msg:expr => $span_to_blame:expr $(,)? ) => {
19 return Err(Error::new_spanned(&$span_to_blame, $msg))
20 };
21 }
22
23 pub trait Derivable {
24 fn ident(input: &DeriveInput, crate_name: &TokenStream) -> Result<syn::Path>;
25 fn implies_trait(_crate_name: &TokenStream) -> Option<TokenStream> {
26 None
27 }
28 fn asserts(
29 _input: &DeriveInput, _crate_name: &TokenStream,
30 ) -> Result<TokenStream> {
31 Ok(quote!())
32 }
33 fn check_attributes(_ty: &Data, _attributes: &[Attribute]) -> Result<()> {
34 Ok(())
35 }
36 fn trait_impl(
37 _input: &DeriveInput, _crate_name: &TokenStream,
38 ) -> Result<(TokenStream, TokenStream)> {
39 Ok((quote!(), quote!()))
40 }
41 fn requires_where_clause() -> bool {
42 true
43 }
44 fn explicit_bounds_attribute_name() -> Option<&'static str> {
45 None
46 }
47
48 /// If this trait has a custom meaning for "perfect derive", this function
49 /// should be overridden to return `Some`.
50 ///
51 /// The default is "the fields of a struct; unions and enums not supported".
52 fn perfect_derive_fields(_input: &DeriveInput) -> Option<Fields> {
53 None
54 }
55 }
56
57 pub struct Pod;
58
59 impl Derivable for Pod {
60 fn ident(_: &DeriveInput, crate_name: &TokenStream) -> Result<syn::Path> {
61 Ok(syn::parse_quote!(#crate_name::Pod))
62 }
63
64 fn asserts(
65 input: &DeriveInput, crate_name: &TokenStream,
66 ) -> Result<TokenStream> {
67 let repr = get_repr(&input.attrs)?;
68
69 let packed_or_transparent =
70 repr.packed == Some(1) || repr.repr == Repr::Transparent;
71
72 if !packed_or_transparent && !input.generics.params.is_empty() {
73 bail!("\
74 Pod cannot be derived for non-transparent/non-packed types containing \
75 generic parameters because the padding requirements can't be verified \
76 for generic structs\
77 " => input.generics.params.first().unwrap());
78 }
79
80 match &input.data {
81 Data::Struct(_) => {
82 let assert_no_padding = if !packed_or_transparent {
83 Some(generate_assert_no_padding(input, None, "Pod")?)
84 } else {
85 None
86 };
87 let assert_fields_are_pod = generate_fields_are_trait(
88 input,
89 None,
90 Self::ident(input, crate_name)?,
91 )?;
92
93 Ok(quote!(
94 #assert_no_padding
95 #assert_fields_are_pod
96 ))
97 }
98 Data::Enum(_) => bail!("Deriving Pod is not supported for enums"),
99 Data::Union(_) => bail!("Deriving Pod is not supported for unions"),
100 }
101 }
102
103 fn check_attributes(_ty: &Data, attributes: &[Attribute]) -> Result<()> {
104 let repr = get_repr(attributes)?;
105 match repr.repr {
106 Repr::C => Ok(()),
107 Repr::Transparent => Ok(()),
108 _ => {
109 bail!("Pod requires the type to be #[repr(C)] or #[repr(transparent)]")
110 }
111 }
112 }
113 }
114
115 pub struct AnyBitPattern;
116
117 impl Derivable for AnyBitPattern {
118 fn ident(_: &DeriveInput, crate_name: &TokenStream) -> Result<syn::Path> {
119 Ok(syn::parse_quote!(#crate_name::AnyBitPattern))
120 }
121
122 fn implies_trait(crate_name: &TokenStream) -> Option<TokenStream> {
123 Some(quote!(#crate_name::Zeroable))
124 }
125
126 fn asserts(
127 input: &DeriveInput, crate_name: &TokenStream,
128 ) -> Result<TokenStream> {
129 match &input.data {
130 Data::Union(_) => Ok(quote!()), // unions are always `AnyBitPattern`
131 Data::Struct(_) => {
132 generate_fields_are_trait(input, None, Self::ident(input, crate_name)?)
133 }
134 Data::Enum(_) => {
135 bail!("Deriving AnyBitPattern is not supported for enums")
136 }
137 }
138 }
139 }
140
141 pub struct Zeroable;
142
143 /// Helper function to get the variant with discriminant zero (implicit or
144 /// explicit).
145 fn get_zero_variant(enum_: &DataEnum) -> Result<Option<&Variant>> {
146 let iter = VariantDiscriminantIterator::new(enum_.variants.iter());
147 let mut zero_variant = None;
148 for res in iter {
149 let (discriminant, variant) = res?;
150 if discriminant == 0 {
151 zero_variant = Some(variant);
152 break;
153 }
154 }
155 Ok(zero_variant)
156 }
157
158 impl Derivable for Zeroable {
159 fn ident(_: &DeriveInput, crate_name: &TokenStream) -> Result<syn::Path> {
160 Ok(syn::parse_quote!(#crate_name::Zeroable))
161 }
162
163 fn check_attributes(ty: &Data, attributes: &[Attribute]) -> Result<()> {
164 let repr = get_repr(attributes)?;
165 match ty {
166 Data::Struct(_) => Ok(()),
167 Data::Enum(_) => {
168 if !matches!(
169 repr.repr,
170 Repr::C | Repr::Integer(_) | Repr::CWithDiscriminant(_)
171 ) {
172 bail!("Zeroable requires the enum to be an explicit #[repr(Int)] and/or #[repr(C)]")
173 }
174
175 // We ensure there is a zero variant in `asserts`, since it is needed
176 // there anyway.
177
178 Ok(())
179 }
180 Data::Union(_) => Ok(()),
181 }
182 }
183
184 fn asserts(
185 input: &DeriveInput, crate_name: &TokenStream,
186 ) -> Result<TokenStream> {
187 match &input.data {
188 Data::Union(_) => Ok(quote!()), // unions are always `Zeroable`
189 Data::Struct(_) => {
190 generate_fields_are_trait(input, None, Self::ident(input, crate_name)?)
191 }
192 Data::Enum(enum_) => {
193 let zero_variant = get_zero_variant(enum_)?;
194
195 if zero_variant.is_none() {
196 bail!("No variant's discriminant is 0")
197 };
198
199 generate_fields_are_trait(
200 input,
201 zero_variant,
202 Self::ident(input, crate_name)?,
203 )
204 }
205 }
206 }
207
208 fn explicit_bounds_attribute_name() -> Option<&'static str> {
209 Some("zeroable")
210 }
211
212 fn perfect_derive_fields(input: &DeriveInput) -> Option<Fields> {
213 match &input.data {
214 Data::Struct(struct_) => Some(struct_.fields.clone()),
215 Data::Enum(enum_) => {
216 // We handle `Err` returns from `get_zero_variant` in `asserts`, so it's
217 // fine to just ignore them here and return `None`.
218 // Otherwise, we clone the `fields` of the zero variant (if any).
219 Some(get_zero_variant(enum_).ok()??.fields.clone())
220 }
221 Data::Union(_) => None,
222 }
223 }
224 }
225
226 pub struct NoUninit;
227
228 impl Derivable for NoUninit {
229 fn ident(_: &DeriveInput, crate_name: &TokenStream) -> Result<syn::Path> {
230 Ok(syn::parse_quote!(#crate_name::NoUninit))
231 }
232
233 fn check_attributes(ty: &Data, attributes: &[Attribute]) -> Result<()> {
234 let repr = get_repr(attributes)?;
235 match ty {
236 Data::Struct(_) => match repr.repr {
237 Repr::C | Repr::Transparent => Ok(()),
238 _ if repr.packed.is_some() => Ok(()),
239 _ => bail!("NoUninit requires the struct to be #[repr(C)] or #[repr(transparent)]"),
240 },
241 Data::Enum(DataEnum { variants,.. }) => {
242 if !enum_has_fields(variants.iter()) {
243 if matches!(repr.repr, Repr::C | Repr::Integer(_)) {
244 Ok(())
245 } else {
246 bail!("NoUninit requires the enum to be #[repr(C)] or #[repr(Int)]")
247 }
248 } else if matches!(repr.repr, Repr::Rust) {
249 bail!("NoUninit requires an explicit repr annotation because `repr(Rust)` doesn't have a specified type layout")
250 } else {
251 Ok(())
252 }
253 },
254 Data::Union(_) => bail!("NoUninit can only be derived on enums and structs")
255 }
256 }
257
258 fn asserts(
259 input: &DeriveInput, crate_name: &TokenStream,
260 ) -> Result<TokenStream> {
261 let repr = get_repr(&input.attrs)?;
262
263 let packed_or_transparent =
264 repr.packed == Some(1) || repr.repr == Repr::Transparent;
265
266 if !packed_or_transparent && !input.generics.params.is_empty() {
267 bail!("\
268 NoUninit cannot be derived for non-transparent/non-packed types containing \
269 generic parameters because the padding requirements can't be verified \
270 for generic structs\
271 " => input.generics.params.first().unwrap());
272 }
273
274 match &input.data {
275 Data::Struct(DataStruct { .. }) => {
276 let assert_no_padding = if !packed_or_transparent {
277 Some(generate_assert_no_padding(&input, None, "NoUninit")?)
278 } else {
279 None
280 };
281 let assert_fields_are_no_padding = generate_fields_are_trait(
282 &input,
283 None,
284 Self::ident(input, crate_name)?,
285 )?;
286
287 Ok(quote!(
288 #assert_no_padding
289 #assert_fields_are_no_padding
290 ))
291 }
292 Data::Enum(DataEnum { variants, .. }) => {
293 if enum_has_fields(variants.iter()) {
294 // There are two different C representations for enums with fields:
295 // There's `#[repr(C)]`/`[repr(C, int)]` and `#[repr(int)]`.
296 // `#[repr(C)]` is equivalent to a struct containing the discriminant
297 // and a union of structs representing each variant's fields.
298 // `#[repr(int)]` is equivalent to a union containing structs of the
299 // discriminant and the fields.
300 //
301 // See https://doc.rust-lang.org/reference/type-layout.html#r-layout.repr.c.adt
302 // and https://doc.rust-lang.org/reference/type-layout.html#r-layout.repr.primitive.adt
303 //
304 // In practice the only difference between the two is whether and
305 // where padding bytes are placed. For `#[repr(C)]` enums, the first
306 // enum fields of all variants start at the same location (the first
307 // byte in the union). For `#[repr(int)]` enums, the structs
308 // representing each variant are layed out individually and padding
309 // does not depend on other variants, but only on the size of the
310 // discriminant and the alignment of the first field. The location of
311 // the first field might differ between variants, potentially
312 // resulting in less padding or padding placed later in the enum.
313 //
314 // The `NoUninit` derive macro asserts that no padding exists by
315 // removing all padding with `#[repr(packed)]` and checking that this
316 // doesn't change the size. Since the location and presence of
317 // padding bytes is the only difference between the two
318 // representations and we're removing all padding bytes, the resuling
319 // layout would identical for both representations. This means that
320 // we can just pick one of the representations and don't have to
321 // implement desugaring for both. We chose to implement the
322 // desugaring for `#[repr(int)]`.
323
324 let enum_discriminant = generate_enum_discriminant(input)?;
325 let variant_assertions = variants
326 .iter()
327 .map(|variant| {
328 let assert_no_padding =
329 generate_assert_no_padding(&input, Some(variant), "NoUninit")?;
330 let assert_fields_are_no_padding = generate_fields_are_trait(
331 &input,
332 Some(variant),
333 Self::ident(input, crate_name)?,
334 )?;
335
336 Ok(quote!(
337 #assert_no_padding
338 #assert_fields_are_no_padding
339 ))
340 })
341 .collect::<Result<Vec<_>>>()?;
342 Ok(quote! {
343 const _: () = {
344 #enum_discriminant
345 #(#variant_assertions)*
346 };
347 })
348 } else {
349 Ok(quote!())
350 }
351 }
352 Data::Union(_) => bail!("NoUninit cannot be derived for unions"), /* shouldn't be possible since we already error in attribute check for this case */
353 }
354 }
355
356 fn trait_impl(
357 _input: &DeriveInput, _crate_name: &TokenStream,
358 ) -> Result<(TokenStream, TokenStream)> {
359 Ok((quote!(), quote!()))
360 }
361 }
362
363 pub struct CheckedBitPattern;
364
365 impl Derivable for CheckedBitPattern {
366 fn ident(_: &DeriveInput, crate_name: &TokenStream) -> Result<syn::Path> {
367 Ok(syn::parse_quote!(#crate_name::CheckedBitPattern))
368 }
369
370 fn check_attributes(ty: &Data, attributes: &[Attribute]) -> Result<()> {
371 let repr = get_repr(attributes)?;
372 match ty {
373 Data::Struct(_) => match repr.repr {
374 Repr::C | Repr::Transparent => Ok(()),
375 _ => bail!("CheckedBitPattern derive requires the struct to be #[repr(C)] or #[repr(transparent)]"),
376 },
377 Data::Enum(DataEnum { variants,.. }) => {
378 if !enum_has_fields(variants.iter()){
379 if matches!(repr.repr, Repr::C | Repr::Integer(_)) {
380 Ok(())
381 } else {
382 bail!("CheckedBitPattern requires the enum to be #[repr(C)] or #[repr(Int)]")
383 }
384 } else if matches!(repr.repr, Repr::Rust) {
385 bail!("CheckedBitPattern requires an explicit repr annotation because `repr(Rust)` doesn't have a specified type layout")
386 } else {
387 Ok(())
388 }
389 }
390 Data::Union(_) => bail!("CheckedBitPattern can only be derived on enums and structs")
391 }
392 }
393
394 fn asserts(
395 input: &DeriveInput, crate_name: &TokenStream,
396 ) -> Result<TokenStream> {
397 if !input.generics.params.is_empty() {
398 bail!("CheckedBitPattern cannot be derived for structs containing generic parameters");
399 }
400
401 match &input.data {
402 Data::Struct(DataStruct { .. }) => {
403 let assert_fields_are_maybe_pod = generate_fields_are_trait(
404 &input,
405 None,
406 Self::ident(input, crate_name)?,
407 )?;
408
409 Ok(assert_fields_are_maybe_pod)
410 }
411 // nothing needed, already guaranteed OK by NoUninit.
412 Data::Enum(_) => Ok(quote!()),
413 Data::Union(_) => bail!("Internal error in CheckedBitPattern derive"), /* shouldn't be possible since we already error in attribute check for this case */
414 }
415 }
416
417 fn trait_impl(
418 input: &DeriveInput, crate_name: &TokenStream,
419 ) -> Result<(TokenStream, TokenStream)> {
420 match &input.data {
421 Data::Struct(DataStruct { fields, .. }) => {
422 generate_checked_bit_pattern_struct(
423 &input.ident,
424 fields,
425 &input.attrs,
426 crate_name,
427 )
428 }
429 Data::Enum(DataEnum { variants, .. }) => {
430 generate_checked_bit_pattern_enum(input, variants, crate_name)
431 }
432 Data::Union(_) => bail!("Internal error in CheckedBitPattern derive"), /* shouldn't be possible since we already error in attribute check for this case */
433 }
434 }
435 }
436
437 pub struct TransparentWrapper;
438
439 struct WrappedType {
440 wrapped_type: syn::Type,
441 /// Was the type given with a #[transparent(Type)] attribute.
442 explicit: bool,
443 }
444
445 impl TransparentWrapper {
446 fn get_wrapped_type(
447 attributes: &[Attribute], fields: &Fields,
448 ) -> Option<WrappedType> {
449 let transparent_param =
450 get_type_from_simple_attr(attributes, "transparent")
451 .map(|wrapped_type| WrappedType { wrapped_type, explicit: true });
452 transparent_param.or_else(|| {
453 let mut types = get_field_types(&fields);
454 let first_type = types.next();
455 if let Some(_) = types.next() {
456 // can't guess param type if there is more than one field
457 return None;
458 } else {
459 first_type
460 .cloned()
461 .map(|wrapped_type| WrappedType { wrapped_type, explicit: false })
462 }
463 })
464 }
465 }
466
467 impl Derivable for TransparentWrapper {
468 fn ident(input: &DeriveInput, crate_name: &TokenStream) -> Result<syn::Path> {
469 let fields = get_struct_fields(input)?;
470
471 let WrappedType { wrapped_type: ty, .. } =
472 match Self::get_wrapped_type(&input.attrs, &fields) {
473 Some(ty) => ty,
474 None => bail!("when deriving TransparentWrapper for a struct with more \
475 than one field, you need to specify the transparent field \
476 using #[transparent(T)]"),
477 };
478
479 Ok(syn::parse_quote!(#crate_name::TransparentWrapper<#ty>))
480 }
481
482 fn asserts(
483 input: &DeriveInput, crate_name: &TokenStream,
484 ) -> Result<TokenStream> {
485 let (impl_generics, _ty_generics, where_clause) =
486 input.generics.split_for_impl();
487 let fields = get_struct_fields(input)?;
488 let (wrapped_type, explicit) =
489 match Self::get_wrapped_type(&input.attrs, &fields) {
490 Some(WrappedType { wrapped_type, explicit }) => {
491 (wrapped_type.to_token_stream().to_string(), explicit)
492 }
493 None => unreachable!(), /* other code will already reject this derive */
494 };
495 let mut wrapped_field_ty = None;
496 let mut nonwrapped_field_tys = vec![];
497 for field in fields.iter() {
498 let field_ty = &field.ty;
499 if field_ty.to_token_stream().to_string() == wrapped_type {
500 if wrapped_field_ty.is_some() {
501 if explicit {
502 bail!("TransparentWrapper must have one field of the wrapped type. \
503 The type given in `#[transparent(Type)]` must match tokenwise \
504 with the type in the struct definition, not just be the same type. \
505 You may be able to use a type alias to work around this limitation.");
506 } else {
507 bail!("TransparentWrapper must have one field of the wrapped type");
508 }
509 }
510 wrapped_field_ty = Some(field_ty);
511 } else {
512 nonwrapped_field_tys.push(field_ty);
513 }
514 }
515 if let Some(wrapped_field_ty) = wrapped_field_ty {
516 Ok(quote!(
517 const _: () = {
518 #[repr(transparent)]
519 #[allow(clippy::multiple_bound_locations)]
520 struct AssertWrappedIsWrapped #impl_generics((u8, ::core::marker::PhantomData<#wrapped_field_ty>), #(#nonwrapped_field_tys),*) #where_clause;
521 fn assert_zeroable<Z: #crate_name::Zeroable>() {}
522 #[allow(clippy::multiple_bound_locations)]
523 fn check #impl_generics () #where_clause {
524 #(
525 assert_zeroable::<#nonwrapped_field_tys>();
526 )*
527 }
528 };
529 ))
530 } else {
531 bail!("TransparentWrapper must have one field of the wrapped type")
532 }
533 }
534
535 fn check_attributes(_ty: &Data, attributes: &[Attribute]) -> Result<()> {
536 let repr = get_repr(attributes)?;
537
538 match repr.repr {
539 Repr::Transparent => Ok(()),
540 _ => {
541 bail!(
542 "TransparentWrapper requires the struct to be #[repr(transparent)]"
543 )
544 }
545 }
546 }
547
548 fn requires_where_clause() -> bool {
549 false
550 }
551 }
552
553 pub struct Contiguous;
554
555 impl Derivable for Contiguous {
556 fn ident(_: &DeriveInput, crate_name: &TokenStream) -> Result<syn::Path> {
557 Ok(syn::parse_quote!(#crate_name::Contiguous))
558 }
559
560 fn trait_impl(
561 input: &DeriveInput, _crate_name: &TokenStream,
562 ) -> Result<(TokenStream, TokenStream)> {
563 let repr = get_repr(&input.attrs)?;
564
565 let integer_ty = if let Some(integer_ty) = repr.repr.as_integer() {
566 integer_ty
567 } else {
568 bail!("Contiguous requires the enum to be #[repr(Int)]");
569 };
570
571 let variants = get_enum_variants(input)?;
572 if enum_has_fields(variants.clone()) {
573 return Err(Error::new_spanned(
574 &input,
575 "Only fieldless enums are supported",
576 ));
577 }
578
579 let mut variants_with_discriminant =
580 VariantDiscriminantIterator::new(variants);
581
582 let (min, max, count) = variants_with_discriminant.try_fold(
583 (i128::MAX, i128::MIN, 0),
584 |(min, max, count), res| {
585 let (discriminant, _variant) = res?;
586 Ok::<_, Error>((
587 i128::min(min, discriminant),
588 i128::max(max, discriminant),
589 count + 1,
590 ))
591 },
592 )?;
593
594 if max - min != count - 1 {
595 bail! {
596 "Contiguous requires the enum discriminants to be contiguous",
597 }
598 }
599
600 let min_lit = LitInt::new(&format!("{}", min), input.span());
601 let max_lit = LitInt::new(&format!("{}", max), input.span());
602
603 // `from_integer` and `into_integer` are usually provided by the trait's
604 // default implementation. We override this implementation because it
605 // goes through `transmute_copy`, which can lead to inefficient assembly as seen in https://github.com/Lokathor/bytemuck/issues/175 .
606
607 Ok((
608 quote!(),
609 quote! {
610 type Int = #integer_ty;
611
612 #[allow(clippy::missing_docs_in_private_items)]
613 const MIN_VALUE: #integer_ty = #min_lit;
614
615 #[allow(clippy::missing_docs_in_private_items)]
616 const MAX_VALUE: #integer_ty = #max_lit;
617
618 #[inline]
619 fn from_integer(value: Self::Int) -> Option<Self> {
620 #[allow(clippy::manual_range_contains)]
621 if Self::MIN_VALUE <= value && value <= Self::MAX_VALUE {
622 Some(unsafe { ::core::mem::transmute(value) })
623 } else {
624 None
625 }
626 }
627
628 #[inline]
629 fn into_integer(self) -> Self::Int {
630 self as #integer_ty
631 }
632 },
633 ))
634 }
635 }
636
637 fn get_struct_fields(input: &DeriveInput) -> Result<&Fields> {
638 if let Data::Struct(DataStruct { fields, .. }) = &input.data {
639 Ok(fields)
640 } else {
641 bail!("deriving this trait is only supported for structs")
642 }
643 }
644
645 /// Extract the `Fields` off a `DeriveInput`, or, in the `enum` case, off
646 /// those of the `enum_variant`, when provided (e.g., for `Zeroable`).
647 ///
648 /// We purposely allow not providing an `enum_variant` for cases where
649 /// the caller wants to reject supporting `enum`s (e.g., `NoPadding`).
650 fn get_fields(
651 input: &DeriveInput, enum_variant: Option<&Variant>,
652 ) -> Result<Fields> {
653 match &input.data {
654 Data::Struct(DataStruct { fields, .. }) => Ok(fields.clone()),
655 Data::Union(DataUnion { fields, .. }) => Ok(Fields::Named(fields.clone())),
656 Data::Enum(_) => match enum_variant {
657 Some(variant) => Ok(variant.fields.clone()),
658 None => bail!("deriving this trait is not supported for enums"),
659 },
660 }
661 }
662
663 fn get_enum_variants<'a>(
664 input: &'a DeriveInput,
665 ) -> Result<impl Iterator<Item = &'a Variant> + Clone + 'a> {
666 if let Data::Enum(DataEnum { variants, .. }) = &input.data {
667 Ok(variants.iter())
668 } else {
669 bail!("deriving this trait is only supported for enums")
670 }
671 }
672
673 fn get_field_types<'a>(
674 fields: &'a Fields,
675 ) -> impl Iterator<Item = &'a Type> + 'a {
676 fields.iter().map(|field| &field.ty)
677 }
678
679 fn generate_checked_bit_pattern_struct(
680 input_ident: &Ident, fields: &Fields, attrs: &[Attribute],
681 crate_name: &TokenStream,
682 ) -> Result<(TokenStream, TokenStream)> {
683 let bits_ty = Ident::new(&format!("{}Bits", input_ident), input_ident.span());
684
685 let repr = get_repr(attrs)?;
686
687 let field_names = fields
688 .iter()
689 .enumerate()
690 .map(|(i, field)| {
691 field.ident.clone().unwrap_or_else(|| {
692 Ident::new(&format!("field{}", i), input_ident.span())
693 })
694 })
695 .collect::<Vec<_>>();
696 let field_tys = fields.iter().map(|field| &field.ty).collect::<Vec<_>>();
697
698 let field_name = &field_names[..];
699 let field_ty = &field_tys[..];
700
701 Ok((
702 quote! {
703 #[doc = #GENERATED_TYPE_DOCUMENTATION]
704 #repr
705 #[derive(Clone, Copy, #crate_name::AnyBitPattern)]
706 #[allow(missing_docs)]
707 pub struct #bits_ty {
708 #(#field_name: <#field_ty as #crate_name::CheckedBitPattern>::Bits,)*
709 }
710
711 #[allow(unexpected_cfgs)]
712 const _: () = {
713 #[cfg(not(target_arch = "spirv"))]
714 impl ::core::fmt::Debug for #bits_ty {
715 fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
716 let mut debug_struct = ::core::fmt::Formatter::debug_struct(f, ::core::stringify!(#bits_ty));
717 #(::core::fmt::DebugStruct::field(&mut debug_struct, ::core::stringify!(#field_name), &{ self.#field_name });)*
718 ::core::fmt::DebugStruct::finish(&mut debug_struct)
719 }
720 }
721 };
722 },
723 quote! {
724 type Bits = #bits_ty;
725
726 #[inline]
727 #[allow(clippy::double_comparisons, unused)]
728 fn is_valid_bit_pattern(bits: &#bits_ty) -> bool {
729 #(<#field_ty as #crate_name::CheckedBitPattern>::is_valid_bit_pattern(&{ bits.#field_name }) && )* true
730 }
731 },
732 ))
733 }
734
735 fn generate_checked_bit_pattern_enum(
736 input: &DeriveInput, variants: &Punctuated<Variant, Token![,]>,
737 crate_name: &TokenStream,
738 ) -> Result<(TokenStream, TokenStream)> {
739 if enum_has_fields(variants.iter()) {
740 generate_checked_bit_pattern_enum_with_fields(input, variants, crate_name)
741 } else {
742 generate_checked_bit_pattern_enum_without_fields(
743 input, variants, crate_name,
744 )
745 }
746 }
747
748 fn generate_checked_bit_pattern_enum_without_fields(
749 input: &DeriveInput, variants: &Punctuated<Variant, Token![,]>,
750 crate_name: &TokenStream,
751 ) -> Result<(TokenStream, TokenStream)> {
752 let span = input.span();
753 let mut variants_with_discriminant =
754 VariantDiscriminantIterator::new(variants.iter());
755
756 let (min, max, count) = variants_with_discriminant.try_fold(
757 (i128::MAX, i128::MIN, 0),
758 |(min, max, count), res| {
759 let (discriminant, _variant) = res?;
760 Ok::<_, Error>((
761 i128::min(min, discriminant),
762 i128::max(max, discriminant),
763 count + 1,
764 ))
765 },
766 )?;
767
768 let check = if count == 0 {
769 quote!(false)
770 } else if max - min == count - 1 {
771 // contiguous range
772 let min_lit = LitInt::new(&format!("{}", min), span);
773 let max_lit = LitInt::new(&format!("{}", max), span);
774
775 quote!(*bits >= #min_lit && *bits <= #max_lit)
776 } else {
777 // not contiguous range, check for each
778 let variant_discriminant_lits =
779 VariantDiscriminantIterator::new(variants.iter())
780 .map(|res| {
781 let (discriminant, _variant) = res?;
782 Ok(LitInt::new(&format!("{}", discriminant), span))
783 })
784 .collect::<Result<Vec<_>>>()?;
785
786 // count is at least 1
787 let first = &variant_discriminant_lits[0];
788 let rest = &variant_discriminant_lits[1..];
789
790 quote!(matches!(*bits, #first #(| #rest )*))
791 };
792
793 let (integer, defs) = get_enum_discriminant(input, crate_name)?;
794 Ok((
795 quote!(#defs),
796 quote! {
797 type Bits = #integer;
798
799 #[inline]
800 #[allow(clippy::double_comparisons)]
801 fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
802 #check
803 }
804 },
805 ))
806 }
807
808 fn generate_checked_bit_pattern_enum_with_fields(
809 input: &DeriveInput, variants: &Punctuated<Variant, Token![,]>,
810 crate_name: &TokenStream,
811 ) -> Result<(TokenStream, TokenStream)> {
812 let representation = get_repr(&input.attrs)?;
813 let vis = &input.vis;
814
815 match representation.repr {
816 Repr::Rust => unreachable!(),
817 Repr::C | Repr::CWithDiscriminant(_) => {
818 let (integer, defs) = get_enum_discriminant(input, crate_name)?;
819 let input_ident = &input.ident;
820
821 let bits_repr = Representation { repr: Repr::C, ..representation };
822
823 // the enum manually re-configured as the actual tagged union it
824 // represents, thus circumventing the requirements rust imposes on
825 // the tag even when using #[repr(C)] enum layout
826 // see: https://doc.rust-lang.org/reference/type-layout.html#reprc-enums-with-fields
827 let bits_ty_ident =
828 Ident::new(&format!("{input_ident}Bits"), input.span());
829
830 // the variants union part of the tagged union. These get put into a union
831 // which gets the AnyBitPattern derive applied to it, thus checking
832 // that the fields of the union obey the requriements of AnyBitPattern.
833 // The types that actually go in the union are one more level of
834 // indirection deep: we generate new structs for each variant
835 // (`variant_struct_definitions`) which themselves have the
836 // `CheckedBitPattern` derive applied, thus generating
837 // `{variant_struct_ident}Bits` structs, which are the ones that go
838 // into this union.
839 let variants_union_ident =
840 Ident::new(&format!("{}Variants", input.ident), input.span());
841
842 let variant_struct_idents = variants.iter().map(|v| {
843 Ident::new(&format!("{input_ident}Variant{}", v.ident), v.span())
844 });
845
846 let variant_struct_definitions =
847 variant_struct_idents.clone().zip(variants.iter()).map(|(variant_struct_ident, v)| {
848 let fields = v.fields.iter().map(|v| &v.ty);
849
850 quote! {
851 #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::CheckedBitPattern)]
852 #[repr(C)]
853 #vis struct #variant_struct_ident(#(#fields),*);
854 }
855 });
856
857 let union_fields = variant_struct_idents
858 .clone()
859 .zip(variants.iter())
860 .map(|(variant_struct_ident, v)| {
861 let variant_struct_bits_ident =
862 Ident::new(&format!("{variant_struct_ident}Bits"), input.span());
863 let field_ident = &v.ident;
864 quote! {
865 #field_ident: #variant_struct_bits_ident
866 }
867 });
868
869 let variant_checks = variant_struct_idents
870 .clone()
871 .zip(VariantDiscriminantIterator::new(variants.iter()))
872 .zip(variants.iter())
873 .map(|((variant_struct_ident, discriminant), v)| -> Result<_> {
874 let (discriminant, _variant) = discriminant?;
875 let discriminant = LitInt::new(&discriminant.to_string(), v.span());
876 let ident = &v.ident;
877 Ok(quote! {
878 #discriminant => {
879 let payload = unsafe { &bits.payload.#ident };
880 <#variant_struct_ident as #crate_name::CheckedBitPattern>::is_valid_bit_pattern(payload)
881 }
882 })
883 })
884 .collect::<Result<Vec<_>>>()?;
885
886 Ok((
887 quote! {
888 #defs
889
890 #[doc = #GENERATED_TYPE_DOCUMENTATION]
891 #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::AnyBitPattern)]
892 #bits_repr
893 #vis struct #bits_ty_ident {
894 tag: #integer,
895 payload: #variants_union_ident,
896 }
897
898 #[allow(unexpected_cfgs)]
899 const _: () = {
900 #[cfg(not(target_arch = "spirv"))]
901 impl ::core::fmt::Debug for #bits_ty_ident {
902 fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
903 let mut debug_struct = ::core::fmt::Formatter::debug_struct(f, ::core::stringify!(#bits_ty_ident));
904 ::core::fmt::DebugStruct::field(&mut debug_struct, "tag", &self.tag);
905 ::core::fmt::DebugStruct::field(&mut debug_struct, "payload", &self.payload);
906 ::core::fmt::DebugStruct::finish(&mut debug_struct)
907 }
908 }
909 };
910
911 #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::AnyBitPattern)]
912 #[repr(C)]
913 #[allow(non_snake_case)]
914 #vis union #variants_union_ident {
915 #(#union_fields,)*
916 }
917
918 #[allow(unexpected_cfgs)]
919 const _: () = {
920 #[cfg(not(target_arch = "spirv"))]
921 impl ::core::fmt::Debug for #variants_union_ident {
922 fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
923 let mut debug_struct = ::core::fmt::Formatter::debug_struct(f, ::core::stringify!(#variants_union_ident));
924 ::core::fmt::DebugStruct::finish_non_exhaustive(&mut debug_struct)
925 }
926 }
927 };
928
929 #(#variant_struct_definitions)*
930 },
931 quote! {
932 type Bits = #bits_ty_ident;
933
934 #[inline]
935 #[allow(clippy::double_comparisons)]
936 fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
937 match bits.tag {
938 #(#variant_checks)*
939 _ => false,
940 }
941 }
942 },
943 ))
944 }
945 Repr::Transparent => {
946 if variants.len() != 1 {
947 bail!("enums with more than one variant cannot be transparent")
948 }
949
950 let variant = &variants[0];
951
952 let bits_ty = Ident::new(&format!("{}Bits", input.ident), input.span());
953 let fields = variant.fields.iter().map(|v| &v.ty);
954
955 Ok((
956 quote! {
957 #[doc = #GENERATED_TYPE_DOCUMENTATION]
958 #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::CheckedBitPattern)]
959 #[repr(C)]
960 #vis struct #bits_ty(#(#fields),*);
961 },
962 quote! {
963 type Bits = <#bits_ty as #crate_name::CheckedBitPattern>::Bits;
964
965 #[inline]
966 #[allow(clippy::double_comparisons)]
967 fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
968 <#bits_ty as #crate_name::CheckedBitPattern>::is_valid_bit_pattern(bits)
969 }
970 },
971 ))
972 }
973 Repr::Integer(integer) => {
974 let bits_repr = Representation { repr: Repr::C, ..representation };
975 let input_ident = &input.ident;
976
977 // the enum manually re-configured as the union it represents. such a
978 // union is the union of variants as a repr(c) struct with the
979 // discriminator type inserted at the beginning. in our case we
980 // union the `Bits` representation of each variant rather than the variant
981 // itself, which we generate via a nested `CheckedBitPattern` derive
982 // on the `variant_struct_definitions` generated below.
983 //
984 // see: https://doc.rust-lang.org/reference/type-layout.html#primitive-representation-of-enums-with-fields
985 let bits_ty_ident =
986 Ident::new(&format!("{input_ident}Bits"), input.span());
987
988 let variant_struct_idents = variants.iter().map(|v| {
989 Ident::new(&format!("{input_ident}Variant{}", v.ident), v.span())
990 });
991
992 let variant_struct_definitions =
993 variant_struct_idents.clone().zip(variants.iter()).map(|(variant_struct_ident, v)| {
994 let fields = v.fields.iter().map(|v| &v.ty);
995
996 // adding the discriminant repr integer as first field, as described above
997 quote! {
998 #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::CheckedBitPattern)]
999 #[repr(C)]
1000 #vis struct #variant_struct_ident(#integer, #(#fields),*);
1001 }
1002 });
1003
1004 let union_fields = variant_struct_idents
1005 .clone()
1006 .zip(variants.iter())
1007 .map(|(variant_struct_ident, v)| {
1008 let variant_struct_bits_ident =
1009 Ident::new(&format!("{variant_struct_ident}Bits"), input.span());
1010 let field_ident = &v.ident;
1011 quote! {
1012 #field_ident: #variant_struct_bits_ident
1013 }
1014 });
1015
1016 let variant_checks = variant_struct_idents
1017 .clone()
1018 .zip(VariantDiscriminantIterator::new(variants.iter()))
1019 .zip(variants.iter())
1020 .map(|((variant_struct_ident, discriminant), v)| -> Result<_> {
1021 let (discriminant, _variant) = discriminant?;
1022 let discriminant = LitInt::new(&discriminant.to_string(), v.span());
1023 let ident = &v.ident;
1024 Ok(quote! {
1025 #discriminant => {
1026 let payload = unsafe { &bits.#ident };
1027 <#variant_struct_ident as #crate_name::CheckedBitPattern>::is_valid_bit_pattern(payload)
1028 }
1029 })
1030 })
1031 .collect::<Result<Vec<_>>>()?;
1032
1033 Ok((
1034 quote! {
1035 #[doc = #GENERATED_TYPE_DOCUMENTATION]
1036 #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::AnyBitPattern)]
1037 #bits_repr
1038 #[allow(non_snake_case)]
1039 #vis union #bits_ty_ident {
1040 __tag: #integer,
1041 #(#union_fields,)*
1042 }
1043
1044 #[allow(unexpected_cfgs)]
1045 const _: () = {
1046 #[cfg(not(target_arch = "spirv"))]
1047 impl ::core::fmt::Debug for #bits_ty_ident {
1048 fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
1049 let mut debug_struct = ::core::fmt::Formatter::debug_struct(f, ::core::stringify!(#bits_ty_ident));
1050 ::core::fmt::DebugStruct::field(&mut debug_struct, "tag", unsafe { &self.__tag });
1051 ::core::fmt::DebugStruct::finish_non_exhaustive(&mut debug_struct)
1052 }
1053 }
1054 };
1055
1056 #(#variant_struct_definitions)*
1057 },
1058 quote! {
1059 type Bits = #bits_ty_ident;
1060
1061 #[inline]
1062 #[allow(clippy::double_comparisons)]
1063 fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
1064 match unsafe { bits.__tag } {
1065 #(#variant_checks)*
1066 _ => false,
1067 }
1068 }
1069 },
1070 ))
1071 }
1072 }
1073 }
1074
1075 /// Check that a struct or enum has no padding by asserting that the size of
1076 /// the type is equal to the sum of the size of it's fields and discriminant
1077 /// (for enums, this must be asserted for each variant).
1078 fn generate_assert_no_padding(
1079 input: &DeriveInput, enum_variant: Option<&Variant>, for_trait: &str,
1080 ) -> Result<TokenStream> {
1081 let struct_type = &input.ident;
1082 let fields = get_fields(input, enum_variant)?;
1083
1084 // If the type is an enum, determine the type of its discriminant.
1085 let enum_discriminant = if matches!(input.data, Data::Enum(_)) {
1086 let ident =
1087 Ident::new(&format!("{}Discriminant", input.ident), input.ident.span());
1088 Some(ident.into_token_stream())
1089 } else {
1090 None
1091 };
1092
1093 // Prepend the type of the discriminant to the types of the fields.
1094 let mut field_types = enum_discriminant
1095 .into_iter()
1096 .chain(get_field_types(&fields).map(ToTokens::to_token_stream));
1097 let size_sum = if let Some(first) = field_types.next() {
1098 let size_first = quote!(::core::mem::size_of::<#first>());
1099 let size_rest = quote!(#( + ::core::mem::size_of::<#field_types>() )*);
1100
1101 quote!(#size_first #size_rest)
1102 } else {
1103 quote!(0)
1104 };
1105
1106 let message =
1107 format!("derive({for_trait}) was applied to a type with padding");
1108
1109 Ok(quote! {const _: () = {
1110 assert!(
1111 ::core::mem::size_of::<#struct_type>() == (#size_sum),
1112 #message,
1113 );
1114 };})
1115 }
1116
1117 /// Check that all fields implement a given trait
1118 fn generate_fields_are_trait(
1119 input: &DeriveInput, enum_variant: Option<&Variant>, trait_: syn::Path,
1120 ) -> Result<TokenStream> {
1121 let (impl_generics, _ty_generics, where_clause) =
1122 input.generics.split_for_impl();
1123 let fields = get_fields(input, enum_variant)?;
1124 let field_types = get_field_types(&fields);
1125 Ok(quote! {#(const _: fn() = || {
1126 #[allow(clippy::missing_const_for_fn)]
1127 #[doc(hidden)]
1128 fn check #impl_generics () #where_clause {
1129 fn assert_impl<T: #trait_>() {}
1130 assert_impl::<#field_types>();
1131 }
1132 };)*
1133 })
1134 }
1135
1136 /// Get the type of an enum's discriminant.
1137 ///
1138 /// For `repr(int)` and `repr(C, int)` enums, this will return the known bare
1139 /// integer type specified.
1140 ///
1141 /// For `repr(C)` enums, this will extract the underlying size chosen by rustc.
1142 /// It will return a token stream which is a type expression that evaluates to
1143 /// a primitive integer type of this size, using our `EnumTagIntegerBytes`
1144 /// trait.
1145 ///
1146 /// For fieldless `repr(C)` enums, we can feed the size of the enum directly
1147 /// into the trait.
1148 ///
1149 /// For `repr(C)` enums with fields, we generate a new fieldless `repr(C)` enum
1150 /// with the same variants, then use that in the calculation. This is the
1151 /// specified behavior, see https://doc.rust-lang.org/stable/reference/type-layout.html#reprc-enums-with-fields
1152 ///
1153 /// Returns a tuple of (type ident, auxiliary definitions)
1154 fn get_enum_discriminant(
1155 input: &DeriveInput, crate_name: &TokenStream,
1156 ) -> Result<(TokenStream, TokenStream)> {
1157 let repr = get_repr(&input.attrs)?;
1158 match repr.repr {
1159 Repr::C => {
1160 let e = if let Data::Enum(e) = &input.data { e } else { unreachable!() };
1161 if enum_has_fields(e.variants.iter()) {
1162 // If the enum has fields, we must first isolate the discriminant by
1163 // removing all the fields.
1164 let enum_discriminant = generate_enum_discriminant(input)?;
1165 let discriminant_ident = Ident::new(
1166 &format!("{}Discriminant", input.ident),
1167 input.ident.span(),
1168 );
1169 Ok((
1170 quote!(<[::core::primitive::u8; ::core::mem::size_of::<#discriminant_ident>()] as #crate_name::derive::EnumTagIntegerBytes>::Integer),
1171 quote! {
1172 #enum_discriminant
1173 },
1174 ))
1175 } else {
1176 // If the enum doesn't have fields, we can just use it directly.
1177 let ident = &input.ident;
1178 Ok((
1179 quote!(<[::core::primitive::u8; ::core::mem::size_of::<#ident>()] as #crate_name::derive::EnumTagIntegerBytes>::Integer),
1180 quote!(),
1181 ))
1182 }
1183 }
1184 Repr::Integer(integer) | Repr::CWithDiscriminant(integer) => {
1185 Ok((quote!(#integer), quote!()))
1186 }
1187 _ => unreachable!(),
1188 }
1189 }
1190
1191 fn generate_enum_discriminant(input: &DeriveInput) -> Result<TokenStream> {
1192 let e = if let Data::Enum(e) = &input.data { e } else { unreachable!() };
1193 let repr = get_repr(&input.attrs)?;
1194 let repr = match repr.repr {
1195 Repr::C => quote!(#[repr(C)]),
1196 Repr::Integer(int) | Repr::CWithDiscriminant(int) => quote!(#[repr(#int)]),
1197 Repr::Rust | Repr::Transparent => unreachable!(),
1198 };
1199 let ident =
1200 Ident::new(&format!("{}Discriminant", input.ident), input.ident.span());
1201 let variants = e.variants.iter().cloned().map(|mut e| {
1202 e.fields = Fields::Unit;
1203 e
1204 });
1205 Ok(quote! {
1206 #repr
1207 #[allow(dead_code)]
1208 enum #ident {
1209 #(#variants,)*
1210 }
1211 })
1212 }
1213
1214 fn get_wrapped_type_from_stream(tokens: TokenStream) -> Option<syn::Type> {
1215 let mut tokens = tokens.into_iter().peekable();
1216 match tokens.peek() {
1217 Some(TokenTree::Group(group)) => {
1218 let res = get_wrapped_type_from_stream(group.stream());
1219 tokens.next(); // remove the peeked token tree
1220 match tokens.next() {
1221 // If there were more tokens, the input was invalid
1222 Some(_) => None,
1223 None => res,
1224 }
1225 }
1226 _ => syn::parse2(tokens.collect()).ok(),
1227 }
1228 }
1229
1230 /// get a simple `#[foo(bar)]` attribute, returning `bar`
1231 fn get_type_from_simple_attr(
1232 attributes: &[Attribute], attr_name: &str,
1233 ) -> Option<syn::Type> {
1234 for attr in attributes {
1235 if let (AttrStyle::Outer, Meta::List(list)) = (&attr.style, &attr.meta) {
1236 if list.path.is_ident(attr_name) {
1237 if let Some(ty) = get_wrapped_type_from_stream(list.tokens.clone()) {
1238 return Some(ty);
1239 }
1240 }
1241 }
1242 }
1243
1244 None
1245 }
1246
1247 fn get_repr(attributes: &[Attribute]) -> Result<Representation> {
1248 attributes
1249 .iter()
1250 .filter_map(|attr| {
1251 if attr.path().is_ident("repr") {
1252 Some(attr.parse_args::<Representation>())
1253 } else {
1254 None
1255 }
1256 })
1257 .try_fold(Representation::default(), |a, b| {
1258 let b = b?;
1259 Ok(Representation {
1260 repr: match (a.repr, b.repr) {
1261 (a, Repr::Rust) => a,
1262 (Repr::Rust, b) => b,
1263 _ => bail!("conflicting representation hints"),
1264 },
1265 packed: match (a.packed, b.packed) {
1266 (a, None) => a,
1267 (None, b) => b,
1268 _ => bail!("conflicting representation hints"),
1269 },
1270 align: match (a.align, b.align) {
1271 (Some(a), Some(b)) => Some(cmp::max(a, b)),
1272 (a, None) => a,
1273 (None, b) => b,
1274 },
1275 })
1276 })
1277 }
1278
1279 mk_repr! {
1280 U8 => u8,
1281 I8 => i8,
1282 U16 => u16,
1283 I16 => i16,
1284 U32 => u32,
1285 I32 => i32,
1286 U64 => u64,
1287 I64 => i64,
1288 I128 => i128,
1289 U128 => u128,
1290 Usize => usize,
1291 Isize => isize,
1292 }
1293 // where
1294 macro_rules! mk_repr {(
1295 $(
1296 $Xn:ident => $xn:ident
1297 ),* $(,)?
1298 ) => (
1299 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1300 enum IntegerRepr {
1301 $($Xn),*
1302 }
1303
1304 impl<'a> TryFrom<&'a str> for IntegerRepr {
1305 type Error = &'a str;
1306
1307 fn try_from(value: &'a str) -> std::result::Result<Self, &'a str> {
1308 match value {
1309 $(
1310 stringify!($xn) => Ok(Self::$Xn),
1311 )*
1312 _ => Err(value),
1313 }
1314 }
1315 }
1316
1317 impl ToTokens for IntegerRepr {
1318 fn to_tokens(&self, tokens: &mut TokenStream) {
1319 match self {
1320 $(
1321 Self::$Xn => tokens.extend(quote!($xn)),
1322 )*
1323 }
1324 }
1325 }
1326 )}
1327 use mk_repr;
1328
1329 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1330 enum Repr {
1331 Rust,
1332 C,
1333 Transparent,
1334 Integer(IntegerRepr),
1335 CWithDiscriminant(IntegerRepr),
1336 }
1337
1338 impl Repr {
1339 fn as_integer(&self) -> Option<IntegerRepr> {
1340 if let Self::Integer(v) = self {
1341 Some(*v)
1342 } else {
1343 None
1344 }
1345 }
1346 }
1347
1348 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1349 struct Representation {
1350 packed: Option<u32>,
1351 align: Option<u32>,
1352 repr: Repr,
1353 }
1354
1355 impl Default for Representation {
1356 fn default() -> Self {
1357 Self { packed: None, align: None, repr: Repr::Rust }
1358 }
1359 }
1360
1361 impl Parse for Representation {
1362 fn parse(input: ParseStream<'_>) -> Result<Representation> {
1363 let mut ret = Representation::default();
1364 while !input.is_empty() {
1365 let keyword = input.parse::<Ident>()?;
1366 // preƫmptively call `.to_string()` *once* (rather than on `is_ident()`)
1367 let keyword_str = keyword.to_string();
1368 let new_repr = match keyword_str.as_str() {
1369 "C" => Repr::C,
1370 "transparent" => Repr::Transparent,
1371 "packed" => {
1372 ret.packed = Some(if input.peek(token::Paren) {
1373 let contents;
1374 parenthesized!(contents in input);
1375 LitInt::base10_parse::<u32>(&contents.parse()?)?
1376 } else {
1377 1
1378 });
1379 let _: Option<Token![,]> = input.parse()?;
1380 continue;
1381 }
1382 "align" => {
1383 let contents;
1384 parenthesized!(contents in input);
1385 let new_align = LitInt::base10_parse::<u32>(&contents.parse()?)?;
1386 ret.align = Some(
1387 ret
1388 .align
1389 .map_or(new_align, |old_align| cmp::max(old_align, new_align)),
1390 );
1391 let _: Option<Token![,]> = input.parse()?;
1392 continue;
1393 }
1394 ident => {
1395 let primitive = IntegerRepr::try_from(ident)
1396 .map_err(|_| input.error("unrecognized representation hint"))?;
1397 Repr::Integer(primitive)
1398 }
1399 };
1400 ret.repr = match (ret.repr, new_repr) {
1401 (Repr::Rust, new_repr) => {
1402 // This is the first explicit repr.
1403 new_repr
1404 }
1405 (Repr::C, Repr::Integer(integer))
1406 | (Repr::Integer(integer), Repr::C) => {
1407 // Both the C repr and an integer repr have been specified
1408 // -> merge into a C wit discriminant.
1409 Repr::CWithDiscriminant(integer)
1410 }
1411 (_, _) => {
1412 return Err(input.error("duplicate representation hint"));
1413 }
1414 };
1415 let _: Option<Token![,]> = input.parse()?;
1416 }
1417 Ok(ret)
1418 }
1419 }
1420
1421 impl ToTokens for Representation {
1422 fn to_tokens(&self, tokens: &mut TokenStream) {
1423 let mut meta = Punctuated::<_, Token![,]>::new();
1424
1425 match self.repr {
1426 Repr::Rust => {}
1427 Repr::C => meta.push(quote!(C)),
1428 Repr::Transparent => meta.push(quote!(transparent)),
1429 Repr::Integer(primitive) => meta.push(quote!(#primitive)),
1430 Repr::CWithDiscriminant(primitive) => {
1431 meta.push(quote!(C));
1432 meta.push(quote!(#primitive));
1433 }
1434 }
1435
1436 if let Some(packed) = self.packed.as_ref() {
1437 let lit = LitInt::new(&packed.to_string(), Span::call_site());
1438 meta.push(quote!(packed(#lit)));
1439 }
1440
1441 if let Some(align) = self.align.as_ref() {
1442 let lit = LitInt::new(&align.to_string(), Span::call_site());
1443 meta.push(quote!(align(#lit)));
1444 }
1445
1446 tokens.extend(quote!(
1447 #[repr(#meta)]
1448 ));
1449 }
1450 }
1451
1452 fn enum_has_fields<'a>(
1453 mut variants: impl Iterator<Item = &'a Variant>,
1454 ) -> bool {
1455 variants.any(|v| matches!(v.fields, Fields::Named(_) | Fields::Unnamed(_)))
1456 }
1457
1458 struct VariantDiscriminantIterator<'a, I: Iterator<Item = &'a Variant> + 'a> {
1459 inner: I,
1460 last_value: i128,
1461 }
1462
1463 impl<'a, I: Iterator<Item = &'a Variant> + 'a>
1464 VariantDiscriminantIterator<'a, I>
1465 {
1466 fn new(inner: I) -> Self {
1467 VariantDiscriminantIterator { inner, last_value: -1 }
1468 }
1469 }
1470
1471 impl<'a, I: Iterator<Item = &'a Variant> + 'a> Iterator
1472 for VariantDiscriminantIterator<'a, I>
1473 {
1474 type Item = Result<(i128, &'a Variant)>;
1475
1476 fn next(&mut self) -> Option<Self::Item> {
1477 let variant = self.inner.next()?;
1478
1479 if let Some((_, discriminant)) = &variant.discriminant {
1480 let discriminant_value = match parse_int_expr(discriminant) {
1481 Ok(value) => value,
1482 Err(e) => return Some(Err(e)),
1483 };
1484 self.last_value = discriminant_value;
1485 } else {
1486 // If this wraps, then either:
1487 // 1. the enum is using repr(u128), so wrapping is correct
1488 // 2. the enum is using repr(i<=128 or u<128), so the compiler will
1489 // already emit a "wrapping discriminant" E0370 error.
1490 self.last_value = self.last_value.wrapping_add(1);
1491 // Static assert that there is no integer repr > 128 bits. If that
1492 // changes, the above comment is inaccurate and needs to be updated!
1493 // FIXME(zachs18): maybe should also do something to ensure `isize::BITS
1494 // <= 128`?
1495 if let Some(repr) = None::<IntegerRepr> {
1496 match repr {
1497 IntegerRepr::U8
1498 | IntegerRepr::I8
1499 | IntegerRepr::U16
1500 | IntegerRepr::I16
1501 | IntegerRepr::U32
1502 | IntegerRepr::I32
1503 | IntegerRepr::U64
1504 | IntegerRepr::I64
1505 | IntegerRepr::I128
1506 | IntegerRepr::U128
1507 | IntegerRepr::Usize
1508 | IntegerRepr::Isize => (),
1509 }
1510 }
1511 }
1512
1513 Some(Ok((self.last_value, variant)))
1514 }
1515 }
1516
1517 fn parse_int_expr(expr: &Expr) -> Result<i128> {
1518 match expr {
1519 Expr::Unary(ExprUnary { op: UnOp::Neg(_), expr, .. }) => {
1520 parse_int_expr(expr).map(|int| -int)
1521 }
1522 Expr::Lit(ExprLit { lit: Lit::Int(int), .. }) => int.base10_parse(),
1523 Expr::Lit(ExprLit { lit: Lit::Byte(byte), .. }) => Ok(byte.value().into()),
1524 _ => bail!("Not an integer expression"),
1525 }
1526 }
1527
1528 #[cfg(test)]
1529 mod tests {
1530 use syn::parse_quote;
1531
1532 use super::{get_repr, IntegerRepr, Repr, Representation};
1533
1534 #[test]
1535 fn parse_basic_repr() {
1536 let attr = parse_quote!(#[repr(C)]);
1537 let repr = get_repr(&[attr]).unwrap();
1538 assert_eq!(repr, Representation { repr: Repr::C, ..Default::default() });
1539
1540 let attr = parse_quote!(#[repr(transparent)]);
1541 let repr = get_repr(&[attr]).unwrap();
1542 assert_eq!(
1543 repr,
1544 Representation { repr: Repr::Transparent, ..Default::default() }
1545 );
1546
1547 let attr = parse_quote!(#[repr(u8)]);
1548 let repr = get_repr(&[attr]).unwrap();
1549 assert_eq!(
1550 repr,
1551 Representation {
1552 repr: Repr::Integer(IntegerRepr::U8),
1553 ..Default::default()
1554 }
1555 );
1556
1557 let attr = parse_quote!(#[repr(packed)]);
1558 let repr = get_repr(&[attr]).unwrap();
1559 assert_eq!(repr, Representation { packed: Some(1), ..Default::default() });
1560
1561 let attr = parse_quote!(#[repr(packed(1))]);
1562 let repr = get_repr(&[attr]).unwrap();
1563 assert_eq!(repr, Representation { packed: Some(1), ..Default::default() });
1564
1565 let attr = parse_quote!(#[repr(packed(2))]);
1566 let repr = get_repr(&[attr]).unwrap();
1567 assert_eq!(repr, Representation { packed: Some(2), ..Default::default() });
1568
1569 let attr = parse_quote!(#[repr(align(2))]);
1570 let repr = get_repr(&[attr]).unwrap();
1571 assert_eq!(repr, Representation { align: Some(2), ..Default::default() });
1572 }
1573
1574 #[test]
1575 fn parse_advanced_repr() {
1576 let attr = parse_quote!(#[repr(align(4), align(2))]);
1577 let repr = get_repr(&[attr]).unwrap();
1578 assert_eq!(repr, Representation { align: Some(4), ..Default::default() });
1579
1580 let attr1 = parse_quote!(#[repr(align(1))]);
1581 let attr2 = parse_quote!(#[repr(align(4))]);
1582 let attr3 = parse_quote!(#[repr(align(2))]);
1583 let repr = get_repr(&[attr1, attr2, attr3]).unwrap();
1584 assert_eq!(repr, Representation { align: Some(4), ..Default::default() });
1585
1586 let attr = parse_quote!(#[repr(C, u8)]);
1587 let repr = get_repr(&[attr]).unwrap();
1588 assert_eq!(
1589 repr,
1590 Representation {
1591 repr: Repr::CWithDiscriminant(IntegerRepr::U8),
1592 ..Default::default()
1593 }
1594 );
1595
1596 let attr = parse_quote!(#[repr(u8, C)]);
1597 let repr = get_repr(&[attr]).unwrap();
1598 assert_eq!(
1599 repr,
1600 Representation {
1601 repr: Repr::CWithDiscriminant(IntegerRepr::U8),
1602 ..Default::default()
1603 }
1604 );
1605 }
1606 }
1607
1608 pub fn bytemuck_crate_name(input: &DeriveInput) -> TokenStream {
1609 const ATTR_NAME: &'static str = "crate";
1610
1611 let mut crate_name = quote!(::bytemuck);
1612 for attr in &input.attrs {
1613 if !attr.path().is_ident("bytemuck") {
1614 continue;
1615 }
1616
1617 attr.parse_nested_meta(|meta| {
1618 if meta.path.is_ident(ATTR_NAME) {
1619 let expr: syn::Expr = meta.value()?.parse()?;
1620 let mut value = &expr;
1621 while let syn::Expr::Group(e) = value {
1622 value = &e.expr;
1623 }
1624 if let syn::Expr::Lit(syn::ExprLit {
1625 lit: syn::Lit::Str(lit), ..
1626 }) = value
1627 {
1628 let suffix = lit.suffix();
1629 if !suffix.is_empty() {
1630 bail!(format!("Unexpected suffix `{}` on string literal", suffix))
1631 }
1632 let path: syn::Path = match lit.parse() {
1633 Ok(path) => path,
1634 Err(_) => {
1635 bail!(format!("Failed to parse path: {:?}", lit.value()))
1636 }
1637 };
1638 crate_name = path.into_token_stream();
1639 } else {
1640 bail!(
1641 "Expected bytemuck `crate` attribute to be a string: `crate = \"...\"`",
1642 )
1643 }
1644 }
1645 Ok(())
1646 }).unwrap();
1647 }
1648
1649 return crate_name;
1650 }
1651
1652 const GENERATED_TYPE_DOCUMENTATION: &str =
1653 " `bytemuck`-generated type for internal purposes only.";