1#![allow(unused_imports)]
2use std::{cmp, convert::TryFrom};
3
4use proc_macro2::{Ident, Span, TokenStream, TokenTree};
5use quote::{quote, quote_spanned, ToTokens};
6use syn::{
7 parse::{Parse, ParseStream, Parser},
8 punctuated::Punctuated,
9 spanned::Spanned,
10 Result, *,
11};
12
13macro_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
23pub 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 fn perfect_derive_fields(_input: &DeriveInput) -> Option<Fields> {
53 None
54 }
55}
56
57pub struct Pod;
58
59impl 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 completly_packed =
70 repr.packed == Some(1) || repr.repr == Repr::Transparent;
71
72 if !completly_packed && !input.generics.params.is_empty() {
73 bail!("\
74 Pod requires cannot be derived for non-packed types containing \
75 generic parameters because the padding requirements can't be verified \
76 for generic non-packed structs\
77 " => input.generics.params.first().unwrap());
78 }
79
80 match &input.data {
81 Data::Struct(_) => {
82 let assert_no_padding = if !completly_packed {
83 Some(generate_assert_no_padding(input)?)
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
115pub struct AnyBitPattern;
116
117impl 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!()), 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
141pub struct Zeroable;
142
143fn 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
158impl 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 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!()), 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 Some(get_zero_variant(enum_).ok()??.fields.clone())
220 }
221 Data::Union(_) => None,
222 }
223 }
224}
225
226pub struct NoUninit;
227
228impl 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 _ => bail!("NoUninit requires the struct to be #[repr(C)] or #[repr(transparent)]"),
239 },
240 Data::Enum(_) => if repr.repr.is_integer() {
241 Ok(())
242 } else {
243 bail!("NoUninit requires the enum to be an explicit #[repr(Int)]")
244 },
245 Data::Union(_) => bail!("NoUninit can only be derived on enums and structs")
246 }
247 }
248
249 fn asserts(
250 input: &DeriveInput, crate_name: &TokenStream,
251 ) -> Result<TokenStream> {
252 if !input.generics.params.is_empty() {
253 bail!("NoUninit cannot be derived for structs containing generic parameters because the padding requirements can't be verified for generic structs");
254 }
255
256 match &input.data {
257 Data::Struct(DataStruct { .. }) => {
258 let assert_no_padding = generate_assert_no_padding(&input)?;
259 let assert_fields_are_no_padding = generate_fields_are_trait(
260 &input,
261 None,
262 Self::ident(input, crate_name)?,
263 )?;
264
265 Ok(quote!(
266 #assert_no_padding
267 #assert_fields_are_no_padding
268 ))
269 }
270 Data::Enum(DataEnum { variants, .. }) => {
271 if variants.iter().any(|variant| !variant.fields.is_empty()) {
272 bail!("Only fieldless enums are supported for NoUninit")
273 } else {
274 Ok(quote!())
275 }
276 }
277 Data::Union(_) => bail!("NoUninit cannot be derived for unions"), }
279 }
280
281 fn trait_impl(
282 _input: &DeriveInput, _crate_name: &TokenStream,
283 ) -> Result<(TokenStream, TokenStream)> {
284 Ok((quote!(), quote!()))
285 }
286}
287
288pub struct CheckedBitPattern;
289
290impl Derivable for CheckedBitPattern {
291 fn ident(_: &DeriveInput, crate_name: &TokenStream) -> Result<syn::Path> {
292 Ok(syn::parse_quote!(#crate_name::CheckedBitPattern))
293 }
294
295 fn check_attributes(ty: &Data, attributes: &[Attribute]) -> Result<()> {
296 let repr = get_repr(attributes)?;
297 match ty {
298 Data::Struct(_) => match repr.repr {
299 Repr::C | Repr::Transparent => Ok(()),
300 _ => bail!("CheckedBitPattern derive requires the struct to be #[repr(C)] or #[repr(transparent)]"),
301 },
302 Data::Enum(DataEnum { variants,.. }) => {
303 if !enum_has_fields(variants.iter()){
304 if repr.repr.is_integer() {
305 Ok(())
306 } else {
307 bail!("CheckedBitPattern requires the enum to be an explicit #[repr(Int)]")
308 }
309 } else if matches!(repr.repr, Repr::Rust) {
310 bail!("CheckedBitPattern requires an explicit repr annotation because `repr(Rust)` doesn't have a specified type layout")
311 } else {
312 Ok(())
313 }
314 }
315 Data::Union(_) => bail!("CheckedBitPattern can only be derived on enums and structs")
316 }
317 }
318
319 fn asserts(
320 input: &DeriveInput, crate_name: &TokenStream,
321 ) -> Result<TokenStream> {
322 if !input.generics.params.is_empty() {
323 bail!("CheckedBitPattern cannot be derived for structs containing generic parameters");
324 }
325
326 match &input.data {
327 Data::Struct(DataStruct { .. }) => {
328 let assert_fields_are_maybe_pod = generate_fields_are_trait(
329 &input,
330 None,
331 Self::ident(input, crate_name)?,
332 )?;
333
334 Ok(assert_fields_are_maybe_pod)
335 }
336 Data::Enum(_) => Ok(quote!()),
338 Data::Union(_) => bail!("Internal error in CheckedBitPattern derive"), }
340 }
341
342 fn trait_impl(
343 input: &DeriveInput, crate_name: &TokenStream,
344 ) -> Result<(TokenStream, TokenStream)> {
345 match &input.data {
346 Data::Struct(DataStruct { fields, .. }) => {
347 generate_checked_bit_pattern_struct(
348 &input.ident,
349 fields,
350 &input.attrs,
351 crate_name,
352 )
353 }
354 Data::Enum(DataEnum { variants, .. }) => {
355 generate_checked_bit_pattern_enum(input, variants, crate_name)
356 }
357 Data::Union(_) => bail!("Internal error in CheckedBitPattern derive"), }
359 }
360}
361
362pub struct TransparentWrapper;
363
364impl TransparentWrapper {
365 fn get_wrapper_type(
366 attributes: &[Attribute], fields: &Fields,
367 ) -> Option<TokenStream> {
368 let transparent_param = get_simple_attr(attributes, "transparent");
369 transparent_param.map(|ident| ident.to_token_stream()).or_else(|| {
370 let mut types = get_field_types(&fields);
371 let first_type = types.next();
372 if let Some(_) = types.next() {
373 return None;
375 } else {
376 first_type.map(|ty| ty.to_token_stream())
377 }
378 })
379 }
380}
381
382impl Derivable for TransparentWrapper {
383 fn ident(input: &DeriveInput, crate_name: &TokenStream) -> Result<syn::Path> {
384 let fields = get_struct_fields(input)?;
385
386 let ty = match Self::get_wrapper_type(&input.attrs, &fields) {
387 Some(ty) => ty,
388 None => bail!(
389 "\
390 when deriving TransparentWrapper for a struct with more than one field \
391 you need to specify the transparent field using #[transparent(T)]\
392 "
393 ),
394 };
395
396 Ok(syn::parse_quote!(#crate_name::TransparentWrapper<#ty>))
397 }
398
399 fn asserts(
400 input: &DeriveInput, crate_name: &TokenStream,
401 ) -> Result<TokenStream> {
402 let (impl_generics, _ty_generics, where_clause) =
403 input.generics.split_for_impl();
404 let fields = get_struct_fields(input)?;
405 let wrapped_type = match Self::get_wrapper_type(&input.attrs, &fields) {
406 Some(wrapped_type) => wrapped_type.to_string(),
407 None => unreachable!(), };
409 let mut wrapped_field_ty = None;
410 let mut nonwrapped_field_tys = vec![];
411 for field in fields.iter() {
412 let field_ty = &field.ty;
413 if field_ty.to_token_stream().to_string() == wrapped_type {
414 if wrapped_field_ty.is_some() {
415 bail!(
416 "TransparentWrapper can only have one field of the wrapped type"
417 );
418 }
419 wrapped_field_ty = Some(field_ty);
420 } else {
421 nonwrapped_field_tys.push(field_ty);
422 }
423 }
424 if let Some(wrapped_field_ty) = wrapped_field_ty {
425 Ok(quote!(
426 const _: () = {
427 #[repr(transparent)]
428 #[allow(clippy::multiple_bound_locations)]
429 struct AssertWrappedIsWrapped #impl_generics((u8, ::core::marker::PhantomData<#wrapped_field_ty>), #(#nonwrapped_field_tys),*) #where_clause;
430 fn assert_zeroable<Z: #crate_name::Zeroable>() {}
431 #[allow(clippy::multiple_bound_locations)]
432 fn check #impl_generics () #where_clause {
433 #(
434 assert_zeroable::<#nonwrapped_field_tys>();
435 )*
436 }
437 };
438 ))
439 } else {
440 bail!("TransparentWrapper must have one field of the wrapped type")
441 }
442 }
443
444 fn check_attributes(_ty: &Data, attributes: &[Attribute]) -> Result<()> {
445 let repr = get_repr(attributes)?;
446
447 match repr.repr {
448 Repr::Transparent => Ok(()),
449 _ => {
450 bail!(
451 "TransparentWrapper requires the struct to be #[repr(transparent)]"
452 )
453 }
454 }
455 }
456
457 fn requires_where_clause() -> bool {
458 false
459 }
460}
461
462pub struct Contiguous;
463
464impl Derivable for Contiguous {
465 fn ident(_: &DeriveInput, crate_name: &TokenStream) -> Result<syn::Path> {
466 Ok(syn::parse_quote!(#crate_name::Contiguous))
467 }
468
469 fn trait_impl(
470 input: &DeriveInput, _crate_name: &TokenStream,
471 ) -> Result<(TokenStream, TokenStream)> {
472 let repr = get_repr(&input.attrs)?;
473
474 let integer_ty = if let Some(integer_ty) = repr.repr.as_integer() {
475 integer_ty
476 } else {
477 bail!("Contiguous requires the enum to be #[repr(Int)]");
478 };
479
480 let variants = get_enum_variants(input)?;
481 if enum_has_fields(variants.clone()) {
482 return Err(Error::new_spanned(
483 &input,
484 "Only fieldless enums are supported",
485 ));
486 }
487
488 let mut variants_with_discriminant =
489 VariantDiscriminantIterator::new(variants);
490
491 let (min, max, count) = variants_with_discriminant.try_fold(
492 (i128::MAX, i128::MIN, 0),
493 |(min, max, count), res| {
494 let (discriminant, _variant) = res?;
495 Ok::<_, Error>((
496 i128::min(min, discriminant),
497 i128::max(max, discriminant),
498 count + 1,
499 ))
500 },
501 )?;
502
503 if max - min != count - 1 {
504 bail! {
505 "Contiguous requires the enum discriminants to be contiguous",
506 }
507 }
508
509 let min_lit = LitInt::new(&format!("{}", min), input.span());
510 let max_lit = LitInt::new(&format!("{}", max), input.span());
511
512 Ok((
517 quote!(),
518 quote! {
519 type Int = #integer_ty;
520
521 #[allow(clippy::missing_docs_in_private_items)]
522 const MIN_VALUE: #integer_ty = #min_lit;
523
524 #[allow(clippy::missing_docs_in_private_items)]
525 const MAX_VALUE: #integer_ty = #max_lit;
526
527 #[inline]
528 fn from_integer(value: Self::Int) -> Option<Self> {
529 #[allow(clippy::manual_range_contains)]
530 if Self::MIN_VALUE <= value && value <= Self::MAX_VALUE {
531 Some(unsafe { ::core::mem::transmute(value) })
532 } else {
533 None
534 }
535 }
536
537 #[inline]
538 fn into_integer(self) -> Self::Int {
539 self as #integer_ty
540 }
541 },
542 ))
543 }
544}
545
546fn get_struct_fields(input: &DeriveInput) -> Result<&Fields> {
547 if let Data::Struct(DataStruct { fields, .. }) = &input.data {
548 Ok(fields)
549 } else {
550 bail!("deriving this trait is only supported for structs")
551 }
552}
553
554fn get_fields(
560 input: &DeriveInput, enum_variant: Option<&Variant>,
561) -> Result<Fields> {
562 match &input.data {
563 Data::Struct(DataStruct { fields, .. }) => Ok(fields.clone()),
564 Data::Union(DataUnion { fields, .. }) => Ok(Fields::Named(fields.clone())),
565 Data::Enum(_) => match enum_variant {
566 Some(variant) => Ok(variant.fields.clone()),
567 None => bail!("deriving this trait is not supported for enums"),
568 },
569 }
570}
571
572fn get_enum_variants<'a>(
573 input: &'a DeriveInput,
574) -> Result<impl Iterator<Item = &'a Variant> + Clone + 'a> {
575 if let Data::Enum(DataEnum { variants, .. }) = &input.data {
576 Ok(variants.iter())
577 } else {
578 bail!("deriving this trait is only supported for enums")
579 }
580}
581
582fn get_field_types<'a>(
583 fields: &'a Fields,
584) -> impl Iterator<Item = &'a Type> + 'a {
585 fields.iter().map(|field| &field.ty)
586}
587
588fn generate_checked_bit_pattern_struct(
589 input_ident: &Ident, fields: &Fields, attrs: &[Attribute],
590 crate_name: &TokenStream,
591) -> Result<(TokenStream, TokenStream)> {
592 let bits_ty = Ident::new(&format!("{}Bits", input_ident), input_ident.span());
593
594 let repr = get_repr(attrs)?;
595
596 let field_names = fields
597 .iter()
598 .enumerate()
599 .map(|(i, field)| {
600 field.ident.clone().unwrap_or_else(|| {
601 Ident::new(&format!("field{}", i), input_ident.span())
602 })
603 })
604 .collect::<Vec<_>>();
605 let field_tys = fields.iter().map(|field| &field.ty).collect::<Vec<_>>();
606
607 let field_name = &field_names[..];
608 let field_ty = &field_tys[..];
609
610 let derive_dbg =
611 quote!(#[cfg_attr(not(target_arch = "spirv"), derive(Debug))]);
612
613 Ok((
614 quote! {
615 #[doc = #GENERATED_TYPE_DOCUMENTATION]
616 #repr
617 #[derive(Clone, Copy, #crate_name::AnyBitPattern)]
618 #derive_dbg
619 #[allow(missing_docs)]
620 pub struct #bits_ty {
621 #(#field_name: <#field_ty as #crate_name::CheckedBitPattern>::Bits,)*
622 }
623 },
624 quote! {
625 type Bits = #bits_ty;
626
627 #[inline]
628 #[allow(clippy::double_comparisons, unused)]
629 fn is_valid_bit_pattern(bits: &#bits_ty) -> bool {
630 #(<#field_ty as #crate_name::CheckedBitPattern>::is_valid_bit_pattern(&{ bits.#field_name }) && )* true
631 }
632 },
633 ))
634}
635
636fn generate_checked_bit_pattern_enum(
637 input: &DeriveInput, variants: &Punctuated<Variant, Token![,]>,
638 crate_name: &TokenStream,
639) -> Result<(TokenStream, TokenStream)> {
640 if enum_has_fields(variants.iter()) {
641 generate_checked_bit_pattern_enum_with_fields(input, variants, crate_name)
642 } else {
643 generate_checked_bit_pattern_enum_without_fields(input, variants)
644 }
645}
646
647fn generate_checked_bit_pattern_enum_without_fields(
648 input: &DeriveInput, variants: &Punctuated<Variant, Token![,]>,
649) -> Result<(TokenStream, TokenStream)> {
650 let span = input.span();
651 let mut variants_with_discriminant =
652 VariantDiscriminantIterator::new(variants.iter());
653
654 let (min, max, count) = variants_with_discriminant.try_fold(
655 (i128::MAX, i128::MIN, 0),
656 |(min, max, count), res| {
657 let (discriminant, _variant) = res?;
658 Ok::<_, Error>((
659 i128::min(min, discriminant),
660 i128::max(max, discriminant),
661 count + 1,
662 ))
663 },
664 )?;
665
666 let check = if count == 0 {
667 quote_spanned!(span => false)
668 } else if max - min == count - 1 {
669 let min_lit = LitInt::new(&format!("{}", min), span);
671 let max_lit = LitInt::new(&format!("{}", max), span);
672
673 quote!(*bits >= #min_lit && *bits <= #max_lit)
674 } else {
675 let variant_discriminant_lits =
677 VariantDiscriminantIterator::new(variants.iter())
678 .map(|res| {
679 let (discriminant, _variant) = res?;
680 Ok(LitInt::new(&format!("{}", discriminant), span))
681 })
682 .collect::<Result<Vec<_>>>()?;
683
684 let first = &variant_discriminant_lits[0];
686 let rest = &variant_discriminant_lits[1..];
687
688 quote!(matches!(*bits, #first #(| #rest )*))
689 };
690
691 let repr = get_repr(&input.attrs)?;
692 let integer = repr.repr.as_integer().unwrap(); Ok((
694 quote!(),
695 quote! {
696 type Bits = #integer;
697
698 #[inline]
699 #[allow(clippy::double_comparisons)]
700 fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
701 #check
702 }
703 },
704 ))
705}
706
707fn generate_checked_bit_pattern_enum_with_fields(
708 input: &DeriveInput, variants: &Punctuated<Variant, Token![,]>,
709 crate_name: &TokenStream,
710) -> Result<(TokenStream, TokenStream)> {
711 let representation = get_repr(&input.attrs)?;
712 let vis = &input.vis;
713
714 let derive_dbg =
715 quote!(#[cfg_attr(not(target_arch = "spirv"), derive(Debug))]);
716
717 match representation.repr {
718 Repr::Rust => unreachable!(),
719 repr @ (Repr::C | Repr::CWithDiscriminant(_)) => {
720 let integer = match repr {
721 Repr::C => quote!(::core::ffi::c_int),
722 Repr::CWithDiscriminant(integer) => quote!(#integer),
723 _ => unreachable!(),
724 };
725 let input_ident = &input.ident;
726
727 let bits_repr = Representation { repr: Repr::C, ..representation };
728
729 let bits_ty_ident =
734 Ident::new(&format!("{input_ident}Bits"), input.span());
735
736 let variants_union_ident =
746 Ident::new(&format!("{}Variants", input.ident), input.span());
747
748 let variant_struct_idents = variants.iter().map(|v| {
749 Ident::new(&format!("{input_ident}Variant{}", v.ident), v.span())
750 });
751
752 let variant_struct_definitions =
753 variant_struct_idents.clone().zip(variants.iter()).map(|(variant_struct_ident, v)| {
754 let fields = v.fields.iter().map(|v| &v.ty);
755
756 quote! {
757 #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::CheckedBitPattern)]
758 #[repr(C)]
759 #vis struct #variant_struct_ident(#(#fields),*);
760 }
761 });
762
763 let union_fields = variant_struct_idents
764 .clone()
765 .zip(variants.iter())
766 .map(|(variant_struct_ident, v)| {
767 let variant_struct_bits_ident =
768 Ident::new(&format!("{variant_struct_ident}Bits"), input.span());
769 let field_ident = &v.ident;
770 quote! {
771 #field_ident: #variant_struct_bits_ident
772 }
773 });
774
775 let variant_checks = variant_struct_idents
776 .clone()
777 .zip(VariantDiscriminantIterator::new(variants.iter()))
778 .zip(variants.iter())
779 .map(|((variant_struct_ident, discriminant), v)| -> Result<_> {
780 let (discriminant, _variant) = discriminant?;
781 let discriminant = LitInt::new(&discriminant.to_string(), v.span());
782 let ident = &v.ident;
783 Ok(quote! {
784 #discriminant => {
785 let payload = unsafe { &bits.payload.#ident };
786 <#variant_struct_ident as #crate_name::CheckedBitPattern>::is_valid_bit_pattern(payload)
787 }
788 })
789 })
790 .collect::<Result<Vec<_>>>()?;
791
792 Ok((
793 quote! {
794 #[doc = #GENERATED_TYPE_DOCUMENTATION]
795 #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::AnyBitPattern)]
796 #derive_dbg
797 #bits_repr
798 #vis struct #bits_ty_ident {
799 tag: #integer,
800 payload: #variants_union_ident,
801 }
802
803 #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::AnyBitPattern)]
804 #[repr(C)]
805 #[allow(non_snake_case)]
806 #vis union #variants_union_ident {
807 #(#union_fields,)*
808 }
809
810 #[cfg(not(target_arch = "spirv"))]
811 impl ::core::fmt::Debug for #variants_union_ident {
812 fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
813 let mut debug_struct = ::core::fmt::Formatter::debug_struct(f, ::core::stringify!(#variants_union_ident));
814 ::core::fmt::DebugStruct::finish_non_exhaustive(&mut debug_struct)
815 }
816 }
817
818 #(#variant_struct_definitions)*
819 },
820 quote! {
821 type Bits = #bits_ty_ident;
822
823 #[inline]
824 #[allow(clippy::double_comparisons)]
825 fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
826 match bits.tag {
827 #(#variant_checks)*
828 _ => false,
829 }
830 }
831 },
832 ))
833 }
834 Repr::Transparent => {
835 if variants.len() != 1 {
836 bail!("enums with more than one variant cannot be transparent")
837 }
838
839 let variant = &variants[0];
840
841 let bits_ty = Ident::new(&format!("{}Bits", input.ident), input.span());
842 let fields = variant.fields.iter().map(|v| &v.ty);
843
844 Ok((
845 quote! {
846 #[doc = #GENERATED_TYPE_DOCUMENTATION]
847 #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::CheckedBitPattern)]
848 #[repr(C)]
849 #vis struct #bits_ty(#(#fields),*);
850 },
851 quote! {
852 type Bits = <#bits_ty as #crate_name::CheckedBitPattern>::Bits;
853
854 #[inline]
855 #[allow(clippy::double_comparisons)]
856 fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
857 <#bits_ty as #crate_name::CheckedBitPattern>::is_valid_bit_pattern(bits)
858 }
859 },
860 ))
861 }
862 Repr::Integer(integer) => {
863 let bits_repr = Representation { repr: Repr::C, ..representation };
864 let input_ident = &input.ident;
865
866 let bits_ty_ident =
875 Ident::new(&format!("{input_ident}Bits"), input.span());
876
877 let variant_struct_idents = variants.iter().map(|v| {
878 Ident::new(&format!("{input_ident}Variant{}", v.ident), v.span())
879 });
880
881 let variant_struct_definitions =
882 variant_struct_idents.clone().zip(variants.iter()).map(|(variant_struct_ident, v)| {
883 let fields = v.fields.iter().map(|v| &v.ty);
884
885 quote! {
887 #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::CheckedBitPattern)]
888 #[repr(C)]
889 #vis struct #variant_struct_ident(#integer, #(#fields),*);
890 }
891 });
892
893 let union_fields = variant_struct_idents
894 .clone()
895 .zip(variants.iter())
896 .map(|(variant_struct_ident, v)| {
897 let variant_struct_bits_ident =
898 Ident::new(&format!("{variant_struct_ident}Bits"), input.span());
899 let field_ident = &v.ident;
900 quote! {
901 #field_ident: #variant_struct_bits_ident
902 }
903 });
904
905 let variant_checks = variant_struct_idents
906 .clone()
907 .zip(VariantDiscriminantIterator::new(variants.iter()))
908 .zip(variants.iter())
909 .map(|((variant_struct_ident, discriminant), v)| -> Result<_> {
910 let (discriminant, _variant) = discriminant?;
911 let discriminant = LitInt::new(&discriminant.to_string(), v.span());
912 let ident = &v.ident;
913 Ok(quote! {
914 #discriminant => {
915 let payload = unsafe { &bits.#ident };
916 <#variant_struct_ident as #crate_name::CheckedBitPattern>::is_valid_bit_pattern(payload)
917 }
918 })
919 })
920 .collect::<Result<Vec<_>>>()?;
921
922 Ok((
923 quote! {
924 #[doc = #GENERATED_TYPE_DOCUMENTATION]
925 #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::AnyBitPattern)]
926 #bits_repr
927 #[allow(non_snake_case)]
928 #vis union #bits_ty_ident {
929 __tag: #integer,
930 #(#union_fields,)*
931 }
932
933 #[cfg(not(target_arch = "spirv"))]
934 impl ::core::fmt::Debug for #bits_ty_ident {
935 fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
936 let mut debug_struct = ::core::fmt::Formatter::debug_struct(f, ::core::stringify!(#bits_ty_ident));
937 ::core::fmt::DebugStruct::field(&mut debug_struct, "tag", unsafe { &self.__tag });
938 ::core::fmt::DebugStruct::finish_non_exhaustive(&mut debug_struct)
939 }
940 }
941
942 #(#variant_struct_definitions)*
943 },
944 quote! {
945 type Bits = #bits_ty_ident;
946
947 #[inline]
948 #[allow(clippy::double_comparisons)]
949 fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
950 match unsafe { bits.__tag } {
951 #(#variant_checks)*
952 _ => false,
953 }
954 }
955 },
956 ))
957 }
958 }
959}
960
961fn generate_assert_no_padding(input: &DeriveInput) -> Result<TokenStream> {
964 let struct_type = &input.ident;
965 let span = input.ident.span();
966 let enum_variant = None; let fields = get_fields(input, enum_variant)?;
968
969 let mut field_types = get_field_types(&fields);
970 let size_sum = if let Some(first) = field_types.next() {
971 let size_first = quote_spanned!(span => ::core::mem::size_of::<#first>());
972 let size_rest =
973 quote_spanned!(span => #( + ::core::mem::size_of::<#field_types>() )*);
974
975 quote_spanned!(span => #size_first #size_rest)
976 } else {
977 quote_spanned!(span => 0)
978 };
979
980 Ok(quote_spanned! {span => const _: fn() = || {
981 #[doc(hidden)]
982 struct TypeWithoutPadding([u8; #size_sum]);
983 let _ = ::core::mem::transmute::<#struct_type, TypeWithoutPadding>;
984 };})
985}
986
987fn generate_fields_are_trait(
989 input: &DeriveInput, enum_variant: Option<&Variant>, trait_: syn::Path,
990) -> Result<TokenStream> {
991 let (impl_generics, _ty_generics, where_clause) =
992 input.generics.split_for_impl();
993 let fields = get_fields(input, enum_variant)?;
994 let span = input.span();
995 let field_types = get_field_types(&fields);
996 Ok(quote_spanned! {span => #(const _: fn() = || {
997 #[allow(clippy::missing_const_for_fn)]
998 #[doc(hidden)]
999 fn check #impl_generics () #where_clause {
1000 fn assert_impl<T: #trait_>() {}
1001 assert_impl::<#field_types>();
1002 }
1003 };)*
1004 })
1005}
1006
1007fn get_ident_from_stream(tokens: TokenStream) -> Option<Ident> {
1008 match tokens.into_iter().next() {
1009 Some(TokenTree::Group(group)) => get_ident_from_stream(group.stream()),
1010 Some(TokenTree::Ident(ident)) => Some(ident),
1011 _ => None,
1012 }
1013}
1014
1015fn get_simple_attr(attributes: &[Attribute], attr_name: &str) -> Option<Ident> {
1017 for attr in attributes {
1018 if let (AttrStyle::Outer, Meta::List(list)) = (&attr.style, &attr.meta) {
1019 if list.path.is_ident(attr_name) {
1020 if let Some(ident) = get_ident_from_stream(list.tokens.clone()) {
1021 return Some(ident);
1022 }
1023 }
1024 }
1025 }
1026
1027 None
1028}
1029
1030fn get_repr(attributes: &[Attribute]) -> Result<Representation> {
1031 attributes
1032 .iter()
1033 .filter_map(|attr| {
1034 if attr.path().is_ident("repr") {
1035 Some(attr.parse_args::<Representation>())
1036 } else {
1037 None
1038 }
1039 })
1040 .try_fold(Representation::default(), |a, b| {
1041 let b = b?;
1042 Ok(Representation {
1043 repr: match (a.repr, b.repr) {
1044 (a, Repr::Rust) => a,
1045 (Repr::Rust, b) => b,
1046 _ => bail!("conflicting representation hints"),
1047 },
1048 packed: match (a.packed, b.packed) {
1049 (a, None) => a,
1050 (None, b) => b,
1051 _ => bail!("conflicting representation hints"),
1052 },
1053 align: match (a.align, b.align) {
1054 (Some(a), Some(b)) => Some(cmp::max(a, b)),
1055 (a, None) => a,
1056 (None, b) => b,
1057 },
1058 })
1059 })
1060}
1061
1062mk_repr! {
1063 U8 => u8,
1064 I8 => i8,
1065 U16 => u16,
1066 I16 => i16,
1067 U32 => u32,
1068 I32 => i32,
1069 U64 => u64,
1070 I64 => i64,
1071 I128 => i128,
1072 U128 => u128,
1073 Usize => usize,
1074 Isize => isize,
1075}
1076macro_rules! mk_repr {(
1078 $(
1079 $Xn:ident => $xn:ident
1080 ),* $(,)?
1081) => (
1082 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1083 enum IntegerRepr {
1084 $($Xn),*
1085 }
1086
1087 impl<'a> TryFrom<&'a str> for IntegerRepr {
1088 type Error = &'a str;
1089
1090 fn try_from(value: &'a str) -> std::result::Result<Self, &'a str> {
1091 match value {
1092 $(
1093 stringify!($xn) => Ok(Self::$Xn),
1094 )*
1095 _ => Err(value),
1096 }
1097 }
1098 }
1099
1100 impl ToTokens for IntegerRepr {
1101 fn to_tokens(&self, tokens: &mut TokenStream) {
1102 match self {
1103 $(
1104 Self::$Xn => tokens.extend(quote!($xn)),
1105 )*
1106 }
1107 }
1108 }
1109)}
1110use mk_repr;
1111
1112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1113enum Repr {
1114 Rust,
1115 C,
1116 Transparent,
1117 Integer(IntegerRepr),
1118 CWithDiscriminant(IntegerRepr),
1119}
1120
1121impl Repr {
1122 fn is_integer(&self) -> bool {
1123 matches!(self, Self::Integer(..))
1124 }
1125
1126 fn as_integer(&self) -> Option<IntegerRepr> {
1127 if let Self::Integer(v) = self {
1128 Some(*v)
1129 } else {
1130 None
1131 }
1132 }
1133}
1134
1135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1136struct Representation {
1137 packed: Option<u32>,
1138 align: Option<u32>,
1139 repr: Repr,
1140}
1141
1142impl Default for Representation {
1143 fn default() -> Self {
1144 Self { packed: None, align: None, repr: Repr::Rust }
1145 }
1146}
1147
1148impl Parse for Representation {
1149 fn parse(input: ParseStream<'_>) -> Result<Representation> {
1150 let mut ret = Representation::default();
1151 while !input.is_empty() {
1152 let keyword = input.parse::<Ident>()?;
1153 let keyword_str = keyword.to_string();
1155 let new_repr = match keyword_str.as_str() {
1156 "C" => Repr::C,
1157 "transparent" => Repr::Transparent,
1158 "packed" => {
1159 ret.packed = Some(if input.peek(token::Paren) {
1160 let contents;
1161 parenthesized!(contents in input);
1162 LitInt::base10_parse::<u32>(&contents.parse()?)?
1163 } else {
1164 1
1165 });
1166 let _: Option<Token![,]> = input.parse()?;
1167 continue;
1168 }
1169 "align" => {
1170 let contents;
1171 parenthesized!(contents in input);
1172 let new_align = LitInt::base10_parse::<u32>(&contents.parse()?)?;
1173 ret.align = Some(
1174 ret
1175 .align
1176 .map_or(new_align, |old_align| cmp::max(old_align, new_align)),
1177 );
1178 let _: Option<Token![,]> = input.parse()?;
1179 continue;
1180 }
1181 ident => {
1182 let primitive = IntegerRepr::try_from(ident)
1183 .map_err(|_| input.error("unrecognized representation hint"))?;
1184 Repr::Integer(primitive)
1185 }
1186 };
1187 ret.repr = match (ret.repr, new_repr) {
1188 (Repr::Rust, new_repr) => {
1189 new_repr
1191 }
1192 (Repr::C, Repr::Integer(integer))
1193 | (Repr::Integer(integer), Repr::C) => {
1194 Repr::CWithDiscriminant(integer)
1197 }
1198 (_, _) => {
1199 return Err(input.error("duplicate representation hint"));
1200 }
1201 };
1202 let _: Option<Token![,]> = input.parse()?;
1203 }
1204 Ok(ret)
1205 }
1206}
1207
1208impl ToTokens for Representation {
1209 fn to_tokens(&self, tokens: &mut TokenStream) {
1210 let mut meta = Punctuated::<_, Token![,]>::new();
1211
1212 match self.repr {
1213 Repr::Rust => {}
1214 Repr::C => meta.push(quote!(C)),
1215 Repr::Transparent => meta.push(quote!(transparent)),
1216 Repr::Integer(primitive) => meta.push(quote!(#primitive)),
1217 Repr::CWithDiscriminant(primitive) => {
1218 meta.push(quote!(C));
1219 meta.push(quote!(#primitive));
1220 }
1221 }
1222
1223 if let Some(packed) = self.packed.as_ref() {
1224 let lit = LitInt::new(&packed.to_string(), Span::call_site());
1225 meta.push(quote!(packed(#lit)));
1226 }
1227
1228 if let Some(align) = self.align.as_ref() {
1229 let lit = LitInt::new(&align.to_string(), Span::call_site());
1230 meta.push(quote!(align(#lit)));
1231 }
1232
1233 tokens.extend(quote!(
1234 #[repr(#meta)]
1235 ));
1236 }
1237}
1238
1239fn enum_has_fields<'a>(
1240 mut variants: impl Iterator<Item = &'a Variant>,
1241) -> bool {
1242 variants.any(|v| matches!(v.fields, Fields::Named(_) | Fields::Unnamed(_)))
1243}
1244
1245struct VariantDiscriminantIterator<'a, I: Iterator<Item = &'a Variant> + 'a> {
1246 inner: I,
1247 last_value: i128,
1248}
1249
1250impl<'a, I: Iterator<Item = &'a Variant> + 'a>
1251 VariantDiscriminantIterator<'a, I>
1252{
1253 fn new(inner: I) -> Self {
1254 VariantDiscriminantIterator { inner, last_value: -1 }
1255 }
1256}
1257
1258impl<'a, I: Iterator<Item = &'a Variant> + 'a> Iterator
1259 for VariantDiscriminantIterator<'a, I>
1260{
1261 type Item = Result<(i128, &'a Variant)>;
1262
1263 fn next(&mut self) -> Option<Self::Item> {
1264 let variant = self.inner.next()?;
1265
1266 if let Some((_, discriminant)) = &variant.discriminant {
1267 let discriminant_value = match parse_int_expr(discriminant) {
1268 Ok(value) => value,
1269 Err(e) => return Some(Err(e)),
1270 };
1271 self.last_value = discriminant_value;
1272 } else {
1273 self.last_value = self.last_value.wrapping_add(1);
1278 if let Some(repr) = None::<IntegerRepr> {
1283 match repr {
1284 IntegerRepr::U8
1285 | IntegerRepr::I8
1286 | IntegerRepr::U16
1287 | IntegerRepr::I16
1288 | IntegerRepr::U32
1289 | IntegerRepr::I32
1290 | IntegerRepr::U64
1291 | IntegerRepr::I64
1292 | IntegerRepr::I128
1293 | IntegerRepr::U128
1294 | IntegerRepr::Usize
1295 | IntegerRepr::Isize => (),
1296 }
1297 }
1298 }
1299
1300 Some(Ok((self.last_value, variant)))
1301 }
1302}
1303
1304fn parse_int_expr(expr: &Expr) -> Result<i128> {
1305 match expr {
1306 Expr::Unary(ExprUnary { op: UnOp::Neg(_), expr, .. }) => {
1307 parse_int_expr(expr).map(|int| -int)
1308 }
1309 Expr::Lit(ExprLit { lit: Lit::Int(int), .. }) => int.base10_parse(),
1310 Expr::Lit(ExprLit { lit: Lit::Byte(byte), .. }) => Ok(byte.value().into()),
1311 _ => bail!("Not an integer expression"),
1312 }
1313}
1314
1315#[cfg(test)]
1316mod tests {
1317 use syn::parse_quote;
1318
1319 use super::{get_repr, IntegerRepr, Repr, Representation};
1320
1321 #[test]
1322 fn parse_basic_repr() {
1323 let attr = parse_quote!(#[repr(C)]);
1324 let repr = get_repr(&[attr]).unwrap();
1325 assert_eq!(repr, Representation { repr: Repr::C, ..Default::default() });
1326
1327 let attr = parse_quote!(#[repr(transparent)]);
1328 let repr = get_repr(&[attr]).unwrap();
1329 assert_eq!(
1330 repr,
1331 Representation { repr: Repr::Transparent, ..Default::default() }
1332 );
1333
1334 let attr = parse_quote!(#[repr(u8)]);
1335 let repr = get_repr(&[attr]).unwrap();
1336 assert_eq!(
1337 repr,
1338 Representation {
1339 repr: Repr::Integer(IntegerRepr::U8),
1340 ..Default::default()
1341 }
1342 );
1343
1344 let attr = parse_quote!(#[repr(packed)]);
1345 let repr = get_repr(&[attr]).unwrap();
1346 assert_eq!(repr, Representation { packed: Some(1), ..Default::default() });
1347
1348 let attr = parse_quote!(#[repr(packed(1))]);
1349 let repr = get_repr(&[attr]).unwrap();
1350 assert_eq!(repr, Representation { packed: Some(1), ..Default::default() });
1351
1352 let attr = parse_quote!(#[repr(packed(2))]);
1353 let repr = get_repr(&[attr]).unwrap();
1354 assert_eq!(repr, Representation { packed: Some(2), ..Default::default() });
1355
1356 let attr = parse_quote!(#[repr(align(2))]);
1357 let repr = get_repr(&[attr]).unwrap();
1358 assert_eq!(repr, Representation { align: Some(2), ..Default::default() });
1359 }
1360
1361 #[test]
1362 fn parse_advanced_repr() {
1363 let attr = parse_quote!(#[repr(align(4), align(2))]);
1364 let repr = get_repr(&[attr]).unwrap();
1365 assert_eq!(repr, Representation { align: Some(4), ..Default::default() });
1366
1367 let attr1 = parse_quote!(#[repr(align(1))]);
1368 let attr2 = parse_quote!(#[repr(align(4))]);
1369 let attr3 = parse_quote!(#[repr(align(2))]);
1370 let repr = get_repr(&[attr1, attr2, attr3]).unwrap();
1371 assert_eq!(repr, Representation { align: Some(4), ..Default::default() });
1372
1373 let attr = parse_quote!(#[repr(C, u8)]);
1374 let repr = get_repr(&[attr]).unwrap();
1375 assert_eq!(
1376 repr,
1377 Representation {
1378 repr: Repr::CWithDiscriminant(IntegerRepr::U8),
1379 ..Default::default()
1380 }
1381 );
1382
1383 let attr = parse_quote!(#[repr(u8, C)]);
1384 let repr = get_repr(&[attr]).unwrap();
1385 assert_eq!(
1386 repr,
1387 Representation {
1388 repr: Repr::CWithDiscriminant(IntegerRepr::U8),
1389 ..Default::default()
1390 }
1391 );
1392 }
1393}
1394
1395pub fn bytemuck_crate_name(input: &DeriveInput) -> TokenStream {
1396 const ATTR_NAME: &'static str = "crate";
1397
1398 let mut crate_name = quote!(::bytemuck);
1399 for attr in &input.attrs {
1400 if !attr.path().is_ident("bytemuck") {
1401 continue;
1402 }
1403
1404 attr.parse_nested_meta(|meta| {
1405 if meta.path.is_ident(ATTR_NAME) {
1406 let expr: syn::Expr = meta.value()?.parse()?;
1407 let mut value = &expr;
1408 while let syn::Expr::Group(e) = value {
1409 value = &e.expr;
1410 }
1411 if let syn::Expr::Lit(syn::ExprLit {
1412 lit: syn::Lit::Str(lit), ..
1413 }) = value
1414 {
1415 let suffix = lit.suffix();
1416 if !suffix.is_empty() {
1417 bail!(format!("Unexpected suffix `{}` on string literal", suffix))
1418 }
1419 let path: syn::Path = match lit.parse() {
1420 Ok(path) => path,
1421 Err(_) => {
1422 bail!(format!("Failed to parse path: {:?}", lit.value()))
1423 }
1424 };
1425 crate_name = path.into_token_stream();
1426 } else {
1427 bail!(
1428 "Expected bytemuck `crate` attribute to be a string: `crate = \"...\"`",
1429 )
1430 }
1431 }
1432 Ok(())
1433 }).unwrap();
1434 }
1435
1436 return crate_name;
1437}
1438
1439const GENERATED_TYPE_DOCUMENTATION: &str =
1440 " `bytemuck`-generated type for internal purposes only.";