Modify derive_label to support no_std environments (#15465)

# Objective

- Contributes to #15460

## Solution

- Wrap `derive_label` `quote!` in an anonymous constant which contains
an `extern crate alloc` statement, allowing use of the `alloc` namespace
even when a user has not brought in the crate themselves.

## Testing

- CI passed locally.

## Notes

We can't generate code that uses `::std::boxed::Box` in `no_std`
environments, but we also can't rely on `::alloc::boxed::Box` either,
since the user might not have declared `extern crate alloc`. To resolve
this, the generated code is wrapped in an anonymous constant which
contains the `extern crate alloc` invocation.

This does mean the macro is no longer hygienic against cases where the
user provides an alternate `alloc` crate, however I believe this is an
acceptable compromise.

Additionally, this crate itself doesn't need to be `no_std`, it just
needs to _generate_ `no_std` compatible code.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
This commit is contained in:
Zachary Harrold 2024-09-28 06:23:26 +10:00 committed by GitHub
parent 60cf7ca025
commit 6963b58eba
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -81,9 +81,13 @@ pub fn derive_label(
.unwrap(), .unwrap(),
); );
quote! { quote! {
// To ensure alloc is available, but also prevent its name from clashing, we place the implementation inside an anonymous constant
const _: () = {
extern crate alloc;
impl #impl_generics #trait_path for #ident #ty_generics #where_clause { impl #impl_generics #trait_path for #ident #ty_generics #where_clause {
fn dyn_clone(&self) -> ::std::boxed::Box<dyn #trait_path> { fn dyn_clone(&self) -> alloc::boxed::Box<dyn #trait_path> {
::std::boxed::Box::new(::core::clone::Clone::clone(self)) alloc::boxed::Box::new(::core::clone::Clone::clone(self))
} }
fn as_dyn_eq(&self) -> &dyn #dyn_eq_path { fn as_dyn_eq(&self) -> &dyn #dyn_eq_path {
@ -96,6 +100,7 @@ pub fn derive_label(
::core::hash::Hash::hash(self, &mut state); ::core::hash::Hash::hash(self, &mut state);
} }
} }
};
} }
.into() .into()
} }