Skip to content

Commit

Permalink
bevy_reflect: Reflect remote types (#6042)
Browse files Browse the repository at this point in the history
# 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
  • Loading branch information
MrGVSV authored Aug 12, 2024
1 parent aab1f8e commit 6183b56
Show file tree
Hide file tree
Showing 30 changed files with 2,169 additions and 120 deletions.
4 changes: 4 additions & 0 deletions crates/bevy_reflect/compile_fail/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,7 @@ harness = false
[[test]]
name = "func"
harness = false

[[test]]
name = "remote"
harness = false
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
use bevy_reflect::Reflect;

mod external_crate {
pub struct TheirFoo {
pub value: u32,
}
}

#[repr(transparent)]
#[derive(Reflect)]
#[reflect(from_reflect = false)]
struct MyFoo(#[reflect(ignore)] pub external_crate::TheirFoo);

#[derive(Reflect)]
//~^ ERROR: the trait bound `MyFoo: ReflectRemote` is not satisfied
#[reflect(from_reflect = false)]
struct MyStruct {
// Reason: `MyFoo` does not implement `ReflectRemote` (from `#[reflect_remote]` attribute)
#[reflect(remote = MyFoo)]
//~^ ERROR: the trait bound `MyFoo: ReflectRemote` is not satisfied
foo: external_crate::TheirFoo,
}

fn main() {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//@check-pass
use bevy_reflect::{reflect_remote, Reflect};

mod external_crate {
pub struct TheirFoo {
pub value: u32,
}
}

#[reflect_remote(external_crate::TheirFoo)]
struct MyFoo {
pub value: u32,
}

#[derive(Reflect)]
struct MyStruct {
#[reflect(remote = MyFoo)]
foo: external_crate::TheirFoo,
}

fn main() {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
mod structs {
use bevy_reflect::reflect_remote;

mod external_crate {
pub struct TheirStruct {
pub value: u32,
}
}

#[reflect_remote(external_crate::TheirStruct)]
//~^ ERROR: `?` operator has incompatible types
struct MyStruct {
// Reason: Should be `u32`
pub value: bool,
//~^ ERROR: mismatched types
}
}

mod tuple_structs {
use bevy_reflect::reflect_remote;

mod external_crate {
pub struct TheirStruct(pub u32);
}

#[reflect_remote(external_crate::TheirStruct)]
//~^ ERROR: `?` operator has incompatible types
struct MyStruct(
// Reason: Should be `u32`
pub bool,
//~^ ERROR: mismatched types
);
}

mod enums {
use bevy_reflect::reflect_remote;

mod external_crate {
pub enum TheirStruct {
Unit,
Tuple(u32),
Struct { value: usize },
}
}

#[reflect_remote(external_crate::TheirStruct)]
//~^ ERROR: variant `enums::external_crate::TheirStruct::Unit` does not have a field named `0`
//~| ERROR: variant `enums::external_crate::TheirStruct::Unit` has no field named `0`
//~| ERROR: `?` operator has incompatible types
//~| ERROR: `?` operator has incompatible types
enum MyStruct {
// Reason: Should be unit variant
Unit(i32),
// Reason: Should be `u32`
Tuple(bool),
//~^ ERROR: mismatched types
// Reason: Should be `usize`
Struct { value: String },
//~^ ERROR: mismatched types
}
}

fn main() {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
//@check-pass

mod structs {
use bevy_reflect::reflect_remote;

mod external_crate {
pub struct TheirStruct {
pub value: u32,
}
}

#[reflect_remote(external_crate::TheirStruct)]
struct MyStruct {
pub value: u32,
}
}

mod tuple_structs {
use bevy_reflect::reflect_remote;

mod external_crate {
pub struct TheirStruct(pub u32);
}

#[reflect_remote(external_crate::TheirStruct)]
struct MyStruct(pub u32);
}

mod enums {
use bevy_reflect::reflect_remote;

mod external_crate {
pub enum TheirStruct {
Unit,
Tuple(u32),
Struct { value: usize },
}
}

#[reflect_remote(external_crate::TheirStruct)]
enum MyStruct {
Unit,
Tuple(u32),
Struct { value: usize },
}
}

fn main() {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use bevy_reflect::{reflect_remote, std_traits::ReflectDefault};

mod external_crate {
#[derive(Debug, Default)]
pub struct TheirType {
pub value: String,
}
}

#[derive(Debug, Default)]
#[reflect_remote(external_crate::TheirType)]
#[reflect(Debug, Default)]
struct MyType {
pub value: String,
//~^ ERROR: no field `value` on type `&MyType`
//~| ERROR: struct `MyType` has no field named `value`
}

fn main() {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//@check-pass
use bevy_reflect::{reflect_remote, std_traits::ReflectDefault};

mod external_crate {
#[derive(Debug, Default)]
pub struct TheirType {
pub value: String,
}
}

#[reflect_remote(external_crate::TheirType)]
#[derive(Debug, Default)]
#[reflect(Debug, Default)]
struct MyType {
pub value: String,
}

fn main() {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
mod external_crate {
pub struct TheirOuter<T> {
pub inner: TheirInner<T>,
}
pub struct TheirInner<T>(pub T);
}

mod missing_attribute {
use bevy_reflect::{FromReflect, GetTypeRegistration, reflect_remote};

#[reflect_remote(super::external_crate::TheirOuter<T>)]
struct MyOuter<T: FromReflect + GetTypeRegistration> {
// Reason: Missing `#[reflect(remote = ...)]` attribute
pub inner: super::external_crate::TheirInner<T>,
}

#[reflect_remote(super::external_crate::TheirInner<T>)]
struct MyInner<T>(pub T);
}

mod incorrect_inner_type {
use bevy_reflect::{FromReflect, GetTypeRegistration, reflect_remote};

#[reflect_remote(super::external_crate::TheirOuter<T>)]
//~^ ERROR: `TheirInner<T>` does not implement `PartialReflect` so cannot be introspected
//~| ERROR: `TheirInner<T>` does not implement `PartialReflect` so cannot be introspected
//~| ERROR: `TheirInner<T>` does not implement `PartialReflect` so cannot be introspected
//~| ERROR: `TheirInner<T>` can not be used as a dynamic type path
//~| ERROR: `?` operator has incompatible types
struct MyOuter<T: FromReflect + GetTypeRegistration> {
// Reason: Should not use `MyInner<T>` directly
pub inner: MyInner<T>,
//~^ ERROR: mismatched types
}

#[reflect_remote(super::external_crate::TheirInner<T>)]
struct MyInner<T>(pub T);
}

mod mismatched_remote_type {
use bevy_reflect::{FromReflect, GetTypeRegistration, reflect_remote};

#[reflect_remote(super::external_crate::TheirOuter<T>)]
//~^ ERROR: mismatched types
//~| ERROR: mismatched types
struct MyOuter<T: FromReflect + GetTypeRegistration> {
// Reason: Should be `MyInner<T>`
#[reflect(remote = MyOuter<T>)]
//~^ ERROR: mismatched types
pub inner: super::external_crate::TheirInner<T>,
}

#[reflect_remote(super::external_crate::TheirInner<T>)]
struct MyInner<T>(pub T);
}

mod mismatched_remote_generic {
use bevy_reflect::{FromReflect, GetTypeRegistration, reflect_remote};

#[reflect_remote(super::external_crate::TheirOuter<T>)]
//~^ ERROR: `?` operator has incompatible types
//~| ERROR: mismatched types
//~| ERROR: mismatched types
struct MyOuter<T: FromReflect + GetTypeRegistration> {
// Reason: `TheirOuter::inner` is not defined as `TheirInner<bool>`
#[reflect(remote = MyInner<bool>)]
pub inner: super::external_crate::TheirInner<bool>,
//~^ ERROR: mismatched types
}

#[reflect_remote(super::external_crate::TheirInner<T>)]
struct MyInner<T>(pub T);
}

fn main() {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//@check-pass
use bevy_reflect::{FromReflect, GetTypeRegistration, reflect_remote, Reflect, Typed};

mod external_crate {
pub struct TheirOuter<T> {
pub inner: TheirInner<T>,
}
pub struct TheirInner<T>(pub T);
}

#[reflect_remote(external_crate::TheirOuter<T>)]
struct MyOuter<T: FromReflect + Typed + GetTypeRegistration> {
#[reflect(remote = MyInner<T>)]
pub inner: external_crate::TheirInner<T>,
}

#[reflect_remote(external_crate::TheirInner<T>)]
struct MyInner<T: Reflect>(pub T);

fn main() {}
Loading

0 comments on commit 6183b56

Please sign in to comment.