bytemuck_derive/
lib.rs

1//! Derive macros for [bytemuck](https://docs.rs/bytemuck) traits.
2
3extern crate proc_macro;
4
5mod traits;
6
7use proc_macro2::TokenStream;
8use quote::quote;
9use syn::{parse_macro_input, DeriveInput, Result};
10
11use crate::traits::{
12  bytemuck_crate_name, AnyBitPattern, CheckedBitPattern, Contiguous, Derivable,
13  NoUninit, Pod, TransparentWrapper, Zeroable,
14};
15
16/// Derive the `Pod` trait for a struct
17///
18/// The macro ensures that the struct follows all the the safety requirements
19/// for the `Pod` trait.
20///
21/// The following constraints need to be satisfied for the macro to succeed
22///
23/// - All fields in the struct must implement `Pod`
24/// - The struct must be `#[repr(C)]` or `#[repr(transparent)]`
25/// - The struct must not contain any padding bytes
26/// - The struct contains no generic parameters, if it is not
27///   `#[repr(transparent)]`
28///
29/// ## Examples
30///
31/// ```rust
32/// # use std::marker::PhantomData;
33/// # use bytemuck_derive::{Pod, Zeroable};
34/// #[derive(Copy, Clone, Pod, Zeroable)]
35/// #[repr(C)]
36/// struct Test {
37///   a: u16,
38///   b: u16,
39/// }
40///
41/// #[derive(Copy, Clone, Pod, Zeroable)]
42/// #[repr(transparent)]
43/// struct Generic<A, B> {
44///   a: A,
45///   b: PhantomData<B>,
46/// }
47/// ```
48///
49/// If the struct is generic, it must be `#[repr(transparent)]` also.
50///
51/// ```compile_fail
52/// # use bytemuck::{Pod, Zeroable};
53/// # use std::marker::PhantomData;
54/// #[derive(Copy, Clone, Pod, Zeroable)]
55/// #[repr(C)] // must be `#[repr(transparent)]`
56/// struct Generic<A> {
57///   a: A,
58/// }
59/// ```
60///
61/// If the struct is generic and `#[repr(transparent)]`, then it is only `Pod`
62/// when all of its generics are `Pod`, not just its fields.
63///
64/// ```
65/// # use bytemuck::{Pod, Zeroable};
66/// # use std::marker::PhantomData;
67/// #[derive(Copy, Clone, Pod, Zeroable)]
68/// #[repr(transparent)]
69/// struct Generic<A, B> {
70///   a: A,
71///   b: PhantomData<B>,
72/// }
73///
74/// let _: u32 = bytemuck::cast(Generic { a: 4u32, b: PhantomData::<u32> });
75/// ```
76///
77/// ```compile_fail
78/// # use bytemuck::{Pod, Zeroable};
79/// # use std::marker::PhantomData;
80/// # #[derive(Copy, Clone, Pod, Zeroable)]
81/// # #[repr(transparent)]
82/// # struct Generic<A, B> {
83/// #   a: A,
84/// #   b: PhantomData<B>,
85/// # }
86/// struct NotPod;
87///
88/// let _: u32 = bytemuck::cast(Generic { a: 4u32, b: PhantomData::<NotPod> });
89/// ```
90#[proc_macro_derive(Pod, attributes(bytemuck))]
91pub fn derive_pod(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
92  let expanded =
93    derive_marker_trait::<Pod>(parse_macro_input!(input as DeriveInput));
94
95  proc_macro::TokenStream::from(expanded)
96}
97
98/// Derive the `AnyBitPattern` trait for a struct
99///
100/// The macro ensures that the struct follows all the the safety requirements
101/// for the `AnyBitPattern` trait.
102///
103/// The following constraints need to be satisfied for the macro to succeed
104///
105/// - All fields in the struct must to implement `AnyBitPattern`
106#[proc_macro_derive(AnyBitPattern, attributes(bytemuck))]
107pub fn derive_anybitpattern(
108  input: proc_macro::TokenStream,
109) -> proc_macro::TokenStream {
110  let expanded = derive_marker_trait::<AnyBitPattern>(parse_macro_input!(
111    input as DeriveInput
112  ));
113
114  proc_macro::TokenStream::from(expanded)
115}
116
117/// Derive the `Zeroable` trait for a type.
118///
119/// The macro ensures that the type follows all the the safety requirements
120/// for the `Zeroable` trait.
121///
122/// The following constraints need to be satisfied for the macro to succeed on a
123/// struct:
124///
125/// - All fields in the struct must implement `Zeroable`
126///
127/// The following constraints need to be satisfied for the macro to succeed on
128/// an enum:
129///
130/// - The enum has an explicit `#[repr(Int)]`, `#[repr(C)]`, or `#[repr(C,
131///   Int)]`.
132/// - The enum has a variant with discriminant 0 (explicitly or implicitly).
133/// - All fields in the variant with discriminant 0 (if any) must implement
134///   `Zeroable`
135///
136/// The macro always succeeds on unions.
137///
138/// ## Example
139///
140/// ```rust
141/// # use bytemuck_derive::{Zeroable};
142/// #[derive(Copy, Clone, Zeroable)]
143/// #[repr(C)]
144/// struct Test {
145///   a: u16,
146///   b: u16,
147/// }
148/// ```
149/// ```rust
150/// # use bytemuck_derive::{Zeroable};
151/// #[derive(Copy, Clone, Zeroable)]
152/// #[repr(i32)]
153/// enum Values {
154///   A = 0,
155///   B = 1,
156///   C = 2,
157/// }
158/// #[derive(Clone, Zeroable)]
159/// #[repr(C)]
160/// enum Implicit {
161///   A(bool, u8, char),
162///   B(String),
163///   C(std::num::NonZeroU8),
164/// }
165/// ```
166///
167/// # Custom bounds
168///
169/// Custom bounds for the derived `Zeroable` impl can be given using the
170/// `#[zeroable(bound = "")]` helper attribute.
171///
172/// Using this attribute additionally opts-in to "perfect derive" semantics,
173/// where instead of adding bounds for each generic type parameter, bounds are
174/// added for each field's type.
175///
176/// ## Examples
177///
178/// ```rust
179/// # use bytemuck::Zeroable;
180/// # use std::marker::PhantomData;
181/// #[derive(Clone, Zeroable)]
182/// #[zeroable(bound = "")]
183/// struct AlwaysZeroable<T> {
184///   a: PhantomData<T>,
185/// }
186///
187/// AlwaysZeroable::<std::num::NonZeroU8>::zeroed();
188/// ```
189/// ```rust
190/// # use bytemuck::{Zeroable};
191/// #[derive(Copy, Clone, Zeroable)]
192/// #[repr(u8)]
193/// #[zeroable(bound = "")]
194/// enum MyOption<T> {
195///   None,
196///   Some(T),
197/// }
198///
199/// assert!(matches!(MyOption::<std::num::NonZeroU8>::zeroed(), MyOption::None));
200/// ```
201///
202/// ```rust,compile_fail
203/// # use bytemuck::Zeroable;
204/// # use std::marker::PhantomData;
205/// #[derive(Clone, Zeroable)]
206/// #[zeroable(bound = "T: Copy")]
207/// struct ZeroableWhenTIsCopy<T> {
208///   a: PhantomData<T>,
209/// }
210///
211/// ZeroableWhenTIsCopy::<String>::zeroed();
212/// ```
213///
214/// The restriction that all fields must be Zeroable is still applied, and this
215/// is enforced using the mentioned "perfect derive" semantics.
216///
217/// ```rust
218/// # use bytemuck::Zeroable;
219/// #[derive(Clone, Zeroable)]
220/// #[zeroable(bound = "")]
221/// struct ZeroableWhenTIsZeroable<T> {
222///   a: T,
223/// }
224/// ZeroableWhenTIsZeroable::<u32>::zeroed();
225/// ```
226///
227/// ```rust,compile_fail
228/// # use bytemuck::Zeroable;
229/// # #[derive(Clone, Zeroable)]
230/// # #[zeroable(bound = "")]
231/// # struct ZeroableWhenTIsZeroable<T> {
232/// #   a: T,
233/// # }
234/// ZeroableWhenTIsZeroable::<String>::zeroed();
235/// ```
236#[proc_macro_derive(Zeroable, attributes(bytemuck, zeroable))]
237pub fn derive_zeroable(
238  input: proc_macro::TokenStream,
239) -> proc_macro::TokenStream {
240  let expanded =
241    derive_marker_trait::<Zeroable>(parse_macro_input!(input as DeriveInput));
242
243  proc_macro::TokenStream::from(expanded)
244}
245
246/// Derive the `NoUninit` trait for a struct or enum
247///
248/// The macro ensures that the type follows all the the safety requirements
249/// for the `NoUninit` trait.
250///
251/// The following constraints need to be satisfied for the macro to succeed
252/// (the rest of the constraints are guaranteed by the `NoUninit` subtrait
253/// bounds, i.e. the type must be `Sized + Copy + 'static`):
254///
255/// If applied to a struct:
256/// - All fields in the struct must implement `NoUninit`
257/// - The struct must be `#[repr(C)]` or `#[repr(transparent)]`
258/// - The struct must not contain any padding bytes
259/// - The struct must contain no generic parameters
260///
261/// If applied to an enum:
262/// - The enum must be explicit `#[repr(Int)]`, `#[repr(C)]`, or both
263/// - If the enum has fields:
264///   - All fields must implement `NoUninit`
265///   - All variants must not contain any padding bytes
266///   - All variants must be of the the same size
267///   - There must be no padding bytes between the discriminant and any of the
268///     variant fields
269/// - The enum must contain no generic parameters
270#[proc_macro_derive(NoUninit, attributes(bytemuck))]
271pub fn derive_no_uninit(
272  input: proc_macro::TokenStream,
273) -> proc_macro::TokenStream {
274  let expanded =
275    derive_marker_trait::<NoUninit>(parse_macro_input!(input as DeriveInput));
276
277  proc_macro::TokenStream::from(expanded)
278}
279
280/// Derive the `CheckedBitPattern` trait for a struct or enum.
281///
282/// The macro ensures that the type follows all the the safety requirements
283/// for the `CheckedBitPattern` trait and derives the required `Bits` type
284/// definition and `is_valid_bit_pattern` method for the type automatically.
285///
286/// The following constraints need to be satisfied for the macro to succeed:
287///
288/// If applied to a struct:
289/// - All fields must implement `CheckedBitPattern`
290/// - The struct must be `#[repr(C)]` or `#[repr(transparent)]`
291/// - The struct must contain no generic parameters
292///
293/// If applied to an enum:
294/// - The enum must be explicit `#[repr(Int)]`
295/// - All fields in variants must implement `CheckedBitPattern`
296/// - The enum must contain no generic parameters
297#[proc_macro_derive(CheckedBitPattern)]
298pub fn derive_maybe_pod(
299  input: proc_macro::TokenStream,
300) -> proc_macro::TokenStream {
301  let expanded = derive_marker_trait::<CheckedBitPattern>(parse_macro_input!(
302    input as DeriveInput
303  ));
304
305  proc_macro::TokenStream::from(expanded)
306}
307
308/// Derive the `TransparentWrapper` trait for a struct
309///
310/// The macro ensures that the struct follows all the the safety requirements
311/// for the `TransparentWrapper` trait.
312///
313/// The following constraints need to be satisfied for the macro to succeed
314///
315/// - The struct must be `#[repr(transparent)]`
316/// - The struct must contain the `Wrapped` type
317/// - Any ZST fields must be [`Zeroable`][derive@Zeroable].
318///
319/// If the struct only contains a single field, the `Wrapped` type will
320/// automatically be determined. If there is more then one field in the struct,
321/// you need to specify the `Wrapped` type using `#[transparent(T)]`
322///
323/// ## Examples
324///
325/// ```rust
326/// # use bytemuck_derive::TransparentWrapper;
327/// # use std::marker::PhantomData;
328/// #[derive(Copy, Clone, TransparentWrapper)]
329/// #[repr(transparent)]
330/// #[transparent(u16)]
331/// struct Test<T> {
332///   inner: u16,
333///   extra: PhantomData<T>,
334/// }
335/// ```
336///
337/// If the struct contains more than one field, the `Wrapped` type must be
338/// explicitly specified.
339///
340/// ```rust,compile_fail
341/// # use bytemuck_derive::TransparentWrapper;
342/// # use std::marker::PhantomData;
343/// #[derive(Copy, Clone, TransparentWrapper)]
344/// #[repr(transparent)]
345/// // missing `#[transparent(u16)]`
346/// struct Test<T> {
347///   inner: u16,
348///   extra: PhantomData<T>,
349/// }
350/// ```
351///
352/// Any ZST fields must be `Zeroable`.
353///
354/// ```rust,compile_fail
355/// # use bytemuck_derive::TransparentWrapper;
356/// # use std::marker::PhantomData;
357/// struct NonTransparentSafeZST;
358///
359/// #[derive(TransparentWrapper)]
360/// #[repr(transparent)]
361/// #[transparent(u16)]
362/// struct Test<T> {
363///   inner: u16,
364///   extra: PhantomData<T>,
365///   another_extra: NonTransparentSafeZST, // not `Zeroable`
366/// }
367/// ```
368#[proc_macro_derive(TransparentWrapper, attributes(bytemuck, transparent))]
369pub fn derive_transparent(
370  input: proc_macro::TokenStream,
371) -> proc_macro::TokenStream {
372  let expanded = derive_marker_trait::<TransparentWrapper>(parse_macro_input!(
373    input as DeriveInput
374  ));
375
376  proc_macro::TokenStream::from(expanded)
377}
378
379/// Derive the `Contiguous` trait for an enum
380///
381/// The macro ensures that the enum follows all the the safety requirements
382/// for the `Contiguous` trait.
383///
384/// The following constraints need to be satisfied for the macro to succeed
385///
386/// - The enum must be `#[repr(Int)]`
387/// - The enum must be fieldless
388/// - The enum discriminants must form a contiguous range
389///
390/// ## Example
391///
392/// ```rust
393/// # use bytemuck_derive::{Contiguous};
394///
395/// #[derive(Copy, Clone, Contiguous)]
396/// #[repr(u8)]
397/// enum Test {
398///   A = 0,
399///   B = 1,
400///   C = 2,
401/// }
402/// ```
403#[proc_macro_derive(Contiguous)]
404pub fn derive_contiguous(
405  input: proc_macro::TokenStream,
406) -> proc_macro::TokenStream {
407  let expanded =
408    derive_marker_trait::<Contiguous>(parse_macro_input!(input as DeriveInput));
409
410  proc_macro::TokenStream::from(expanded)
411}
412
413/// Derive the `PartialEq` and `Eq` trait for a type
414///
415/// The macro implements `PartialEq` and `Eq` by casting both sides of the
416/// comparison to a byte slice and then compares those.
417///
418/// ## Warning
419///
420/// Since this implements a byte wise comparison, the behavior of floating point
421/// numbers does not match their usual comparison behavior. Additionally other
422/// custom comparison behaviors of the individual fields are also ignored. This
423/// also does not implement `StructuralPartialEq` / `StructuralEq` like
424/// `PartialEq` / `Eq` would. This means you can't pattern match on the values.
425///
426/// ## Examples
427///
428/// ```rust
429/// # use bytemuck_derive::{ByteEq, NoUninit};
430/// #[derive(Copy, Clone, NoUninit, ByteEq)]
431/// #[repr(C)]
432/// struct Test {
433///   a: u32,
434///   b: char,
435///   c: f32,
436/// }
437/// ```
438///
439/// ```rust
440/// # use bytemuck_derive::ByteEq;
441/// # use bytemuck::NoUninit;
442/// #[derive(Copy, Clone, ByteEq)]
443/// #[repr(C)]
444/// struct Test<const N: usize> {
445///   a: [u32; N],
446/// }
447/// unsafe impl<const N: usize> NoUninit for Test<N> {}
448/// ```
449#[proc_macro_derive(ByteEq)]
450pub fn derive_byte_eq(
451  input: proc_macro::TokenStream,
452) -> proc_macro::TokenStream {
453  let input = parse_macro_input!(input as DeriveInput);
454  let crate_name = bytemuck_crate_name(&input);
455  let ident = input.ident;
456  let (impl_generics, ty_generics, where_clause) =
457    input.generics.split_for_impl();
458
459  proc_macro::TokenStream::from(quote! {
460    impl #impl_generics ::core::cmp::PartialEq for #ident #ty_generics #where_clause {
461      #[inline]
462      #[must_use]
463      fn eq(&self, other: &Self) -> bool {
464        #crate_name::bytes_of(self) == #crate_name::bytes_of(other)
465      }
466    }
467    impl #impl_generics ::core::cmp::Eq for #ident #ty_generics #where_clause { }
468  })
469}
470
471/// Derive the `Hash` trait for a type
472///
473/// The macro implements `Hash` by casting the value to a byte slice and hashing
474/// that.
475///
476/// ## Warning
477///
478/// The hash does not match the standard library's `Hash` derive.
479///
480/// ## Examples
481///
482/// ```rust
483/// # use bytemuck_derive::{ByteHash, NoUninit};
484/// #[derive(Copy, Clone, NoUninit, ByteHash)]
485/// #[repr(C)]
486/// struct Test {
487///   a: u32,
488///   b: char,
489///   c: f32,
490/// }
491/// ```
492///
493/// ```rust
494/// # use bytemuck_derive::ByteHash;
495/// # use bytemuck::NoUninit;
496/// #[derive(Copy, Clone, ByteHash)]
497/// #[repr(C)]
498/// struct Test<const N: usize> {
499///   a: [u32; N],
500/// }
501/// unsafe impl<const N: usize> NoUninit for Test<N> {}
502/// ```
503#[proc_macro_derive(ByteHash)]
504pub fn derive_byte_hash(
505  input: proc_macro::TokenStream,
506) -> proc_macro::TokenStream {
507  let input = parse_macro_input!(input as DeriveInput);
508  let crate_name = bytemuck_crate_name(&input);
509  let ident = input.ident;
510  let (impl_generics, ty_generics, where_clause) =
511    input.generics.split_for_impl();
512
513  proc_macro::TokenStream::from(quote! {
514    impl #impl_generics ::core::hash::Hash for #ident #ty_generics #where_clause {
515      #[inline]
516      fn hash<H: ::core::hash::Hasher>(&self, state: &mut H) {
517        ::core::hash::Hash::hash_slice(#crate_name::bytes_of(self), state)
518      }
519
520      #[inline]
521      fn hash_slice<H: ::core::hash::Hasher>(data: &[Self], state: &mut H) {
522        ::core::hash::Hash::hash_slice(#crate_name::cast_slice::<_, u8>(data), state)
523      }
524    }
525  })
526}
527
528/// Basic wrapper for error handling
529fn derive_marker_trait<Trait: Derivable>(input: DeriveInput) -> TokenStream {
530  derive_marker_trait_inner::<Trait>(input)
531    .unwrap_or_else(|err| err.into_compile_error())
532}
533
534/// Find `#[name(key = "value")]` helper attributes on the struct, and return
535/// their `"value"`s parsed with `parser`.
536///
537/// Returns an error if any attributes with the given `name` do not match the
538/// expected format. Returns `Ok([])` if no attributes with `name` are found.
539fn find_and_parse_helper_attributes<P: syn::parse::Parser + Copy>(
540  attributes: &[syn::Attribute], name: &str, key: &str, parser: P,
541  example_value: &str, invalid_value_msg: &str,
542) -> Result<Vec<P::Output>> {
543  let invalid_format_msg =
544    format!("{name} attribute must be `{name}({key} = \"{example_value}\")`",);
545  let values_to_check = attributes.iter().filter_map(|attr| match &attr.meta {
546    // If a `Path` matches our `name`, return an error, else ignore it.
547    // e.g. `#[zeroable]`
548    syn::Meta::Path(path) => path
549      .is_ident(name)
550      .then(|| Err(syn::Error::new_spanned(path, &invalid_format_msg))),
551    // If a `NameValue` matches our `name`, return an error, else ignore it.
552    // e.g. `#[zeroable = "hello"]`
553    syn::Meta::NameValue(namevalue) => {
554      namevalue.path.is_ident(name).then(|| {
555        Err(syn::Error::new_spanned(&namevalue.path, &invalid_format_msg))
556      })
557    }
558    // If a `List` matches our `name`, match its contents to our format, else
559    // ignore it. If its contents match our format, return the value, else
560    // return an error.
561    syn::Meta::List(list) => list.path.is_ident(name).then(|| {
562      let namevalue: syn::MetaNameValue = syn::parse2(list.tokens.clone())
563        .map_err(|_| {
564          syn::Error::new_spanned(&list.tokens, &invalid_format_msg)
565        })?;
566      if namevalue.path.is_ident(key) {
567        match namevalue.value {
568          syn::Expr::Lit(syn::ExprLit {
569            lit: syn::Lit::Str(strlit), ..
570          }) => Ok(strlit),
571          _ => {
572            Err(syn::Error::new_spanned(&namevalue.path, &invalid_format_msg))
573          }
574        }
575      } else {
576        Err(syn::Error::new_spanned(&namevalue.path, &invalid_format_msg))
577      }
578    }),
579  });
580  // Parse each value found with the given parser, and return them if no errors
581  // occur.
582  values_to_check
583    .map(|lit| {
584      let lit = lit?;
585      lit.parse_with(parser).map_err(|err| {
586        syn::Error::new_spanned(&lit, format!("{invalid_value_msg}: {err}"))
587      })
588    })
589    .collect()
590}
591
592fn derive_marker_trait_inner<Trait: Derivable>(
593  mut input: DeriveInput,
594) -> Result<TokenStream> {
595  let crate_name = bytemuck_crate_name(&input);
596  let trait_ = Trait::ident(&input, &crate_name)?;
597  // If this trait allows explicit bounds, and any explicit bounds were given,
598  // then use those explicit bounds. Else, apply the default bounds (bound
599  // each generic type on this trait).
600  if let Some(name) = Trait::explicit_bounds_attribute_name() {
601    // See if any explicit bounds were given in attributes.
602    let explicit_bounds = find_and_parse_helper_attributes(
603      &input.attrs,
604      name,
605      "bound",
606      <syn::punctuated::Punctuated<syn::WherePredicate, syn::Token![,]>>::parse_terminated,
607      "Type: Trait",
608      "invalid where predicate",
609    )?;
610
611    if !explicit_bounds.is_empty() {
612      // Explicit bounds were given.
613      // Enforce explicitly given bounds, and emit "perfect derive" (i.e. add
614      // bounds for each field's type).
615      let explicit_bounds = explicit_bounds
616        .into_iter()
617        .flatten()
618        .collect::<Vec<syn::WherePredicate>>();
619
620      let fields = match (Trait::perfect_derive_fields(&input), &input.data) {
621        (Some(fields), _) => fields,
622        (None, syn::Data::Struct(syn::DataStruct { fields, .. })) => {
623          fields.clone()
624        }
625        (None, syn::Data::Union(_)) => {
626          return Err(syn::Error::new_spanned(
627            trait_,
628            &"perfect derive is not supported for unions",
629          ));
630        }
631        (None, syn::Data::Enum(_)) => {
632          return Err(syn::Error::new_spanned(
633            trait_,
634            &"perfect derive is not supported for enums",
635          ));
636        }
637      };
638
639      let predicates = &mut input.generics.make_where_clause().predicates;
640
641      predicates.extend(explicit_bounds);
642
643      for field in fields {
644        let ty = field.ty;
645        predicates.push(syn::parse_quote!(
646          #ty: #trait_
647        ));
648      }
649    } else {
650      // No explicit bounds were given.
651      // Enforce trait bound on all type generics.
652      add_trait_marker(&mut input.generics, &trait_);
653    }
654  } else {
655    // This trait does not allow explicit bounds.
656    // Enforce trait bound on all type generics.
657    add_trait_marker(&mut input.generics, &trait_);
658  }
659
660  let name = &input.ident;
661
662  let (impl_generics, ty_generics, where_clause) =
663    input.generics.split_for_impl();
664
665  Trait::check_attributes(&input.data, &input.attrs)?;
666  let asserts = Trait::asserts(&input, &crate_name)?;
667  let (trait_impl_extras, trait_impl) = Trait::trait_impl(&input, &crate_name)?;
668
669  let implies_trait = if let Some(implies_trait) =
670    Trait::implies_trait(&crate_name)
671  {
672    quote!(unsafe impl #impl_generics #implies_trait for #name #ty_generics #where_clause {})
673  } else {
674    quote!()
675  };
676
677  let where_clause =
678    if Trait::requires_where_clause() { where_clause } else { None };
679
680  Ok(quote! {
681    #asserts
682
683    #trait_impl_extras
684
685    unsafe impl #impl_generics #trait_ for #name #ty_generics #where_clause {
686      #trait_impl
687    }
688
689    #implies_trait
690  })
691}
692
693/// Add a trait marker to the generics if it is not already present
694fn add_trait_marker(generics: &mut syn::Generics, trait_name: &syn::Path) {
695  // Get each generic type parameter.
696  let type_params = generics
697    .type_params()
698    .map(|param| &param.ident)
699    .map(|param| {
700      syn::parse_quote!(
701        #param: #trait_name
702      )
703    })
704    .collect::<Vec<syn::WherePredicate>>();
705
706  generics.make_where_clause().predicates.extend(type_params);
707}