Skip to content

Commit 6963b58

Browse files
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 <[email protected]>
1 parent 60cf7ca commit 6963b58

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed

crates/bevy_macro_utils/src/label.rs

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -81,21 +81,26 @@ pub fn derive_label(
8181
.unwrap(),
8282
);
8383
quote! {
84-
impl #impl_generics #trait_path for #ident #ty_generics #where_clause {
85-
fn dyn_clone(&self) -> ::std::boxed::Box<dyn #trait_path> {
86-
::std::boxed::Box::new(::core::clone::Clone::clone(self))
87-
}
84+
// To ensure alloc is available, but also prevent its name from clashing, we place the implementation inside an anonymous constant
85+
const _: () = {
86+
extern crate alloc;
8887

89-
fn as_dyn_eq(&self) -> &dyn #dyn_eq_path {
90-
self
91-
}
88+
impl #impl_generics #trait_path for #ident #ty_generics #where_clause {
89+
fn dyn_clone(&self) -> alloc::boxed::Box<dyn #trait_path> {
90+
alloc::boxed::Box::new(::core::clone::Clone::clone(self))
91+
}
9292

93-
fn dyn_hash(&self, mut state: &mut dyn ::core::hash::Hasher) {
94-
let ty_id = ::core::any::TypeId::of::<Self>();
95-
::core::hash::Hash::hash(&ty_id, &mut state);
96-
::core::hash::Hash::hash(self, &mut state);
93+
fn as_dyn_eq(&self) -> &dyn #dyn_eq_path {
94+
self
95+
}
96+
97+
fn dyn_hash(&self, mut state: &mut dyn ::core::hash::Hasher) {
98+
let ty_id = ::core::any::TypeId::of::<Self>();
99+
::core::hash::Hash::hash(&ty_id, &mut state);
100+
::core::hash::Hash::hash(self, &mut state);
101+
}
97102
}
98-
}
103+
};
99104
}
100105
.into()
101106
}

0 commit comments

Comments
 (0)