Skip to content

Commit 6183b56

Browse files
authored
bevy_reflect: Reflect remote types (#6042)
# Objective The goal with this PR is to allow the use of types that don't implement `Reflect` within the reflection API. Rust's [orphan rule](https://doc.rust-lang.org/book/ch10-02-traits.html#implementing-a-trait-on-a-type) prevents implementing a trait on an external type when neither type nor trait are owned by the implementor. This means that if a crate, `cool_rust_lib`, defines a type, `Foo`, then a user cannot use it with reflection. What this means is that we have to ignore it most of the time: ```rust #[derive(Reflect)] struct SomeStruct { #[reflect(ignore)] data: cool_rust_lib::Foo } ``` Obviously, it's impossible to implement `Reflect` on `Foo`. But does it *have* to be? Most of reflection doesn't deal with concrete types— it's almost all using `dyn Reflect`. And being very metadata-driven, it should theoretically be possible. I mean, [`serde`](https://serde.rs/remote-derive.html) does it. ## Solution > Special thanks to @danielhenrymantilla for their help reviewing this PR and offering wisdom wrt safety. Taking a page out of `serde`'s book, this PR adds the ability to easily use "remote types" with reflection. In this context, a "remote type" is the external type for which we have no ability to implement `Reflect`. This adds the `#[reflect_remote(...)]` attribute macro, which is used to generate "remote type wrappers". All you have to do is define the wrapper exactly the same as the remote type's definition: ```rust // Pretend this is our external crate mod cool_rust_lib { #[derive(Default)] struct Foo { pub value: String } } #[reflect_remote(cool_rust_lib::Foo)] struct FooWrapper { pub value: String } ``` > **Note:** All fields in the external type *must* be public. This could be addressed with a separate getter/setter attribute either in this PR or in another one. The macro takes this user-defined item and transforms it into a newtype wrapper around the external type, marking it as `#[repr(transparent)]`. The fields/variants defined by the user are simply used to build out the reflection impls. Additionally, it generates an implementation of the new trait, `ReflectRemote`, which helps prevent accidental misuses of this API. Therefore, the output generated by the macro would look something like: ```rust #[repr(transparent)] struct FooWrapper(pub cool_rust_lib::Foo); impl ReflectRemote for FooWrapper { type Remote = cool_rust_lib::Foo; // transmutation methods... } // reflection impls... // these will acknowledge and make use of the `value` field ``` Internally, the reflection API will pass around the `FooWrapper` and [transmute](https://doc.rust-lang.org/std/mem/fn.transmute.html) it where necessary. All we have to do is then tell `Reflect` to do that. So rather than ignoring the field, we tell `Reflect` to use our wrapper using the `#[reflect(remote = ...)]` field attribute: ```rust #[derive(Reflect)] struct SomeStruct { #[reflect(remote = FooWrapper)] data: cool_rust_lib::Foo } ``` #### Other Macros & Type Data Because this macro consumes the defined item and generates a new one, we can't just put our macros anywhere. All macros that should be passed to the generated struct need to come *below* this macro. For example, to derive `Default` and register its associated type data: ```rust // ✅ GOOD #[reflect_remote(cool_rust_lib::Foo)] #[derive(Default)] #[reflect(Default)] struct FooWrapper { pub value: String } // ❌ BAD #[derive(Default)] #[reflect_remote(cool_rust_lib::Foo)] #[reflect(Default)] struct FooWrapper { pub value: String } ``` #### Generics Generics are forwarded to the generated struct as well. They should also be defined in the same order: ```rust #[reflect_remote(RemoteGeneric<'a, T1, T2>)] struct GenericWrapper<'a, T1, T2> { pub foo: &'a T1, pub bar: &'a T2, } ``` > Naming does *not* need to match the original definition's. Only order matters here. > Also note that the code above is just a demonstration and doesn't actually compile since we'd need to enforce certain bounds (e.g. `T1: Reflect`, `'a: 'static`, etc.) #### Nesting And, yes, you can nest remote types: ```rust #[reflect_remote(RemoteOuter)] struct OuterWrapper { #[reflect(remote = InnerWrapper)] pub inner: RemoteInner } #[reflect_remote(RemoteInner)] struct InnerWrapper(usize); ``` #### Assertions This macro will also generate some compile-time assertions to ensure that the correct types are used. It's important we catch this early so users don't have to wait for something to panic. And it also helps keep our `unsafe` a little safer. For example, a wrapper definition that does not match its corresponding remote type will result in an error: ```rust mod external_crate { pub struct TheirStruct(pub u32); } #[reflect_remote(external_crate::TheirStruct)] struct MyStruct(pub String); // ERROR: expected type `u32` but found `String` ``` <details> <summary>Generated Assertion</summary> ```rust const _: () = { #[allow(non_snake_case)] #[allow(unused_variables)] #[allow(unused_assignments)] #[allow(unreachable_patterns)] #[allow(clippy::multiple_bound_locations)] fn assert_wrapper_definition_matches_remote_type( mut __remote__: external_crate::TheirStruct, ) { __remote__.0 = (|| -> ::core::option::Option<String> { None })().unwrap(); } }; ``` </details> Additionally, using the incorrect type in a `#[reflect(remote = ...)]` attribute should result in an error: ```rust mod external_crate { pub struct TheirFoo(pub u32); pub struct TheirBar(pub i32); } #[reflect_remote(external_crate::TheirFoo)] struct MyFoo(pub u32); #[reflect_remote(external_crate::TheirBar)] struct MyBar(pub i32); #[derive(Reflect)] struct MyStruct { #[reflect(remote = MyBar)] // ERROR: expected type `TheirFoo` but found struct `TheirBar` foo: external_crate::TheirFoo } ``` <details> <summary>Generated Assertion</summary> ```rust const _: () = { struct RemoteFieldAssertions; impl RemoteFieldAssertions { #[allow(non_snake_case)] #[allow(clippy::multiple_bound_locations)] fn assert__foo__is_valid_remote() { let _: <MyBar as bevy_reflect::ReflectRemote>::Remote = (|| -> ::core::option::Option<external_crate::TheirFoo> { None })().unwrap(); } } }; ``` </details> ### Discussion There are a couple points that I think still need discussion or validation. - [x] 1. `Any` shenanigans ~~If we wanted to downcast our remote type from a `dyn Reflect`, we'd have to first downcast to the wrapper then extract the inner type. This PR has a [commit](b840db9) that addresses this by making all the `Reflect::*any` methods return the inner type rather than the wrapper type. This allows us to downcast directly to our remote type.~~ ~~However, I'm not sure if this is something we want to do. For unknowing users, it could be confusing and seemingly inconsistent. Is it worth keeping? Or should this behavior be removed?~~ I think this should be fine. The remote wrapper is an implementation detail and users should not need to downcast to the wrapper type. Feel free to let me know if there are other opinions on this though! - [x] 2. Implementing `Deref/DerefMut` and `From` ~~We don't currently do this, but should we implement other traits on the generated transparent struct? We could implement `Deref`/`DerefMut` to easily access the inner type. And we could implement `From` for easier conversion between the two types (e.g. `T: Into<Foo>`).~~ As mentioned in the comments, we probably don't need to do this. Again, the remote wrapper is an implementation detail, and should generally not be used directly. - [x] 3. ~~Should we define a getter/setter field attribute in this PR as well or leave it for a future one?~~ I think this should be saved for a future PR - [ ] 4. Any foreseeable issues with this implementation? #### Alternatives One alternative to defining our own `ReflectRemote` would be to use [bytemuck's `TransparentWrapper`](https://docs.rs/bytemuck/1.13.1/bytemuck/trait.TransparentWrapper.html) (as suggested by @danielhenrymantilla). This is definitely a viable option, as `ReflectRemote` is pretty much the same thing as `TransparentWrapper`. However, the cost would be bringing in a new crate— though, it is already in use in a few other sub-crates like bevy_render. I think we're okay just defining `ReflectRemote` ourselves, but we can go the bytemuck route if we'd prefer offloading that work to another crate. --- ## Changelog * Added the `#[reflect_remote(...)]` attribute macro to allow `Reflect` to be used on remote types * Added `ReflectRemote` trait for ensuring proper remote wrapper usage
1 parent aab1f8e commit 6183b56

30 files changed

+2169
-120
lines changed

crates/bevy_reflect/compile_fail/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,7 @@ harness = false
2020
[[test]]
2121
name = "func"
2222
harness = false
23+
24+
[[test]]
25+
name = "remote"
26+
harness = false
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
use bevy_reflect::Reflect;
2+
3+
mod external_crate {
4+
pub struct TheirFoo {
5+
pub value: u32,
6+
}
7+
}
8+
9+
#[repr(transparent)]
10+
#[derive(Reflect)]
11+
#[reflect(from_reflect = false)]
12+
struct MyFoo(#[reflect(ignore)] pub external_crate::TheirFoo);
13+
14+
#[derive(Reflect)]
15+
//~^ ERROR: the trait bound `MyFoo: ReflectRemote` is not satisfied
16+
#[reflect(from_reflect = false)]
17+
struct MyStruct {
18+
// Reason: `MyFoo` does not implement `ReflectRemote` (from `#[reflect_remote]` attribute)
19+
#[reflect(remote = MyFoo)]
20+
//~^ ERROR: the trait bound `MyFoo: ReflectRemote` is not satisfied
21+
foo: external_crate::TheirFoo,
22+
}
23+
24+
fn main() {}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
//@check-pass
2+
use bevy_reflect::{reflect_remote, Reflect};
3+
4+
mod external_crate {
5+
pub struct TheirFoo {
6+
pub value: u32,
7+
}
8+
}
9+
10+
#[reflect_remote(external_crate::TheirFoo)]
11+
struct MyFoo {
12+
pub value: u32,
13+
}
14+
15+
#[derive(Reflect)]
16+
struct MyStruct {
17+
#[reflect(remote = MyFoo)]
18+
foo: external_crate::TheirFoo,
19+
}
20+
21+
fn main() {}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
mod structs {
2+
use bevy_reflect::reflect_remote;
3+
4+
mod external_crate {
5+
pub struct TheirStruct {
6+
pub value: u32,
7+
}
8+
}
9+
10+
#[reflect_remote(external_crate::TheirStruct)]
11+
//~^ ERROR: `?` operator has incompatible types
12+
struct MyStruct {
13+
// Reason: Should be `u32`
14+
pub value: bool,
15+
//~^ ERROR: mismatched types
16+
}
17+
}
18+
19+
mod tuple_structs {
20+
use bevy_reflect::reflect_remote;
21+
22+
mod external_crate {
23+
pub struct TheirStruct(pub u32);
24+
}
25+
26+
#[reflect_remote(external_crate::TheirStruct)]
27+
//~^ ERROR: `?` operator has incompatible types
28+
struct MyStruct(
29+
// Reason: Should be `u32`
30+
pub bool,
31+
//~^ ERROR: mismatched types
32+
);
33+
}
34+
35+
mod enums {
36+
use bevy_reflect::reflect_remote;
37+
38+
mod external_crate {
39+
pub enum TheirStruct {
40+
Unit,
41+
Tuple(u32),
42+
Struct { value: usize },
43+
}
44+
}
45+
46+
#[reflect_remote(external_crate::TheirStruct)]
47+
//~^ ERROR: variant `enums::external_crate::TheirStruct::Unit` does not have a field named `0`
48+
//~| ERROR: variant `enums::external_crate::TheirStruct::Unit` has no field named `0`
49+
//~| ERROR: `?` operator has incompatible types
50+
//~| ERROR: `?` operator has incompatible types
51+
enum MyStruct {
52+
// Reason: Should be unit variant
53+
Unit(i32),
54+
// Reason: Should be `u32`
55+
Tuple(bool),
56+
//~^ ERROR: mismatched types
57+
// Reason: Should be `usize`
58+
Struct { value: String },
59+
//~^ ERROR: mismatched types
60+
}
61+
}
62+
63+
fn main() {}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
//@check-pass
2+
3+
mod structs {
4+
use bevy_reflect::reflect_remote;
5+
6+
mod external_crate {
7+
pub struct TheirStruct {
8+
pub value: u32,
9+
}
10+
}
11+
12+
#[reflect_remote(external_crate::TheirStruct)]
13+
struct MyStruct {
14+
pub value: u32,
15+
}
16+
}
17+
18+
mod tuple_structs {
19+
use bevy_reflect::reflect_remote;
20+
21+
mod external_crate {
22+
pub struct TheirStruct(pub u32);
23+
}
24+
25+
#[reflect_remote(external_crate::TheirStruct)]
26+
struct MyStruct(pub u32);
27+
}
28+
29+
mod enums {
30+
use bevy_reflect::reflect_remote;
31+
32+
mod external_crate {
33+
pub enum TheirStruct {
34+
Unit,
35+
Tuple(u32),
36+
Struct { value: usize },
37+
}
38+
}
39+
40+
#[reflect_remote(external_crate::TheirStruct)]
41+
enum MyStruct {
42+
Unit,
43+
Tuple(u32),
44+
Struct { value: usize },
45+
}
46+
}
47+
48+
fn main() {}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
use bevy_reflect::{reflect_remote, std_traits::ReflectDefault};
2+
3+
mod external_crate {
4+
#[derive(Debug, Default)]
5+
pub struct TheirType {
6+
pub value: String,
7+
}
8+
}
9+
10+
#[derive(Debug, Default)]
11+
#[reflect_remote(external_crate::TheirType)]
12+
#[reflect(Debug, Default)]
13+
struct MyType {
14+
pub value: String,
15+
//~^ ERROR: no field `value` on type `&MyType`
16+
//~| ERROR: struct `MyType` has no field named `value`
17+
}
18+
19+
fn main() {}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
//@check-pass
2+
use bevy_reflect::{reflect_remote, std_traits::ReflectDefault};
3+
4+
mod external_crate {
5+
#[derive(Debug, Default)]
6+
pub struct TheirType {
7+
pub value: String,
8+
}
9+
}
10+
11+
#[reflect_remote(external_crate::TheirType)]
12+
#[derive(Debug, Default)]
13+
#[reflect(Debug, Default)]
14+
struct MyType {
15+
pub value: String,
16+
}
17+
18+
fn main() {}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
mod external_crate {
2+
pub struct TheirOuter<T> {
3+
pub inner: TheirInner<T>,
4+
}
5+
pub struct TheirInner<T>(pub T);
6+
}
7+
8+
mod missing_attribute {
9+
use bevy_reflect::{FromReflect, GetTypeRegistration, reflect_remote};
10+
11+
#[reflect_remote(super::external_crate::TheirOuter<T>)]
12+
struct MyOuter<T: FromReflect + GetTypeRegistration> {
13+
// Reason: Missing `#[reflect(remote = ...)]` attribute
14+
pub inner: super::external_crate::TheirInner<T>,
15+
}
16+
17+
#[reflect_remote(super::external_crate::TheirInner<T>)]
18+
struct MyInner<T>(pub T);
19+
}
20+
21+
mod incorrect_inner_type {
22+
use bevy_reflect::{FromReflect, GetTypeRegistration, reflect_remote};
23+
24+
#[reflect_remote(super::external_crate::TheirOuter<T>)]
25+
//~^ ERROR: `TheirInner<T>` does not implement `PartialReflect` so cannot be introspected
26+
//~| ERROR: `TheirInner<T>` does not implement `PartialReflect` so cannot be introspected
27+
//~| ERROR: `TheirInner<T>` does not implement `PartialReflect` so cannot be introspected
28+
//~| ERROR: `TheirInner<T>` can not be used as a dynamic type path
29+
//~| ERROR: `?` operator has incompatible types
30+
struct MyOuter<T: FromReflect + GetTypeRegistration> {
31+
// Reason: Should not use `MyInner<T>` directly
32+
pub inner: MyInner<T>,
33+
//~^ ERROR: mismatched types
34+
}
35+
36+
#[reflect_remote(super::external_crate::TheirInner<T>)]
37+
struct MyInner<T>(pub T);
38+
}
39+
40+
mod mismatched_remote_type {
41+
use bevy_reflect::{FromReflect, GetTypeRegistration, reflect_remote};
42+
43+
#[reflect_remote(super::external_crate::TheirOuter<T>)]
44+
//~^ ERROR: mismatched types
45+
//~| ERROR: mismatched types
46+
struct MyOuter<T: FromReflect + GetTypeRegistration> {
47+
// Reason: Should be `MyInner<T>`
48+
#[reflect(remote = MyOuter<T>)]
49+
//~^ ERROR: mismatched types
50+
pub inner: super::external_crate::TheirInner<T>,
51+
}
52+
53+
#[reflect_remote(super::external_crate::TheirInner<T>)]
54+
struct MyInner<T>(pub T);
55+
}
56+
57+
mod mismatched_remote_generic {
58+
use bevy_reflect::{FromReflect, GetTypeRegistration, reflect_remote};
59+
60+
#[reflect_remote(super::external_crate::TheirOuter<T>)]
61+
//~^ ERROR: `?` operator has incompatible types
62+
//~| ERROR: mismatched types
63+
//~| ERROR: mismatched types
64+
struct MyOuter<T: FromReflect + GetTypeRegistration> {
65+
// Reason: `TheirOuter::inner` is not defined as `TheirInner<bool>`
66+
#[reflect(remote = MyInner<bool>)]
67+
pub inner: super::external_crate::TheirInner<bool>,
68+
//~^ ERROR: mismatched types
69+
}
70+
71+
#[reflect_remote(super::external_crate::TheirInner<T>)]
72+
struct MyInner<T>(pub T);
73+
}
74+
75+
fn main() {}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
//@check-pass
2+
use bevy_reflect::{FromReflect, GetTypeRegistration, reflect_remote, Reflect, Typed};
3+
4+
mod external_crate {
5+
pub struct TheirOuter<T> {
6+
pub inner: TheirInner<T>,
7+
}
8+
pub struct TheirInner<T>(pub T);
9+
}
10+
11+
#[reflect_remote(external_crate::TheirOuter<T>)]
12+
struct MyOuter<T: FromReflect + Typed + GetTypeRegistration> {
13+
#[reflect(remote = MyInner<T>)]
14+
pub inner: external_crate::TheirInner<T>,
15+
}
16+
17+
#[reflect_remote(external_crate::TheirInner<T>)]
18+
struct MyInner<T: Reflect>(pub T);
19+
20+
fn main() {}

0 commit comments

Comments
 (0)