Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FromType specialization #6055

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/bevy_reflect/bevy_reflect_derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ syn = { version = "1.0", features = ["full"] }
proc-macro2 = "1.0"
quote = "1.0"
uuid = { version = "1.1", features = ["v4"] }
bit-set = "0.5.2"
bit-set = "0.5.2"
32 changes: 31 additions & 1 deletion crates/bevy_reflect/bevy_reflect_derive/src/registration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,40 @@ pub(crate) fn impl_get_type_registration(
#[allow(unused_mut)]
impl #impl_generics #bevy_reflect_path::GetTypeRegistration for #type_name #ty_generics #where_clause {
fn get_type_registration() -> #bevy_reflect_path::TypeRegistration {
struct FromTypeCollector<S, T>(std::marker::PhantomData<S>, std::marker::PhantomData<T>);
impl<S, T: #bevy_reflect_path::FromType<S>> FromTypeCollector<S, T> {
#[inline]
fn new() -> Self {
Self(std::marker::PhantomData, std::marker::PhantomData)
}

#[inline]
fn collect(&self) -> T {
T::from_type()
}
}

trait CollectSpecialized {
type Data;
fn collect(self) -> Self::Data;
}

impl<S, T> CollectSpecialized for FromTypeCollector<S, T>
where
T: #bevy_reflect_path::SpecializedFromType<S>,
{
type Data = T;

#[inline]
fn collect(self) -> Self::Data {
T::specialized_from_type()
}
}

let mut registration = #bevy_reflect_path::TypeRegistration::of::<#type_name #ty_generics>();
registration.insert::<#bevy_reflect_path::ReflectFromPtr>(#bevy_reflect_path::FromType::<#type_name #ty_generics>::from_type());
#serialization_data
#(registration.insert::<#registration_data>(#bevy_reflect_path::FromType::<#type_name #ty_generics>::from_type());)*
#(registration.insert::<#registration_data>(FromTypeCollector::<#type_name #ty_generics, #registration_data>::new().collect());)*
registration
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/bevy_reflect/src/impls/glam.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#[cfg(not(doctest))]
use crate as bevy_reflect;
use crate::prelude::ReflectDefault;
use crate::reflect::Reflect;
Expand Down
1 change: 1 addition & 0 deletions crates/bevy_reflect/src/impls/rect.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#[cfg(not(doctest))]
use crate as bevy_reflect;
use crate::prelude::ReflectDefault;
use crate::reflect::Reflect;
Expand Down
4 changes: 3 additions & 1 deletion crates/bevy_reflect/src/impls/std.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use crate::{self as bevy_reflect, ReflectFromPtr};
#[cfg(not(doctest))]
use crate as bevy_reflect;
use crate::ReflectFromPtr;
use crate::{
map_apply, map_partial_eq, Array, ArrayInfo, ArrayIter, DynamicEnum, DynamicMap, Enum,
EnumInfo, FromReflect, FromType, GetTypeRegistration, List, ListInfo, Map, MapInfo, MapIter,
Expand Down
54 changes: 54 additions & 0 deletions crates/bevy_reflect/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ mod reflect;
mod struct_trait;
mod tuple;
mod tuple_struct;
mod type_data;
mod type_info;
mod type_registry;
mod type_uuid;
Expand Down Expand Up @@ -55,6 +56,7 @@ pub use reflect::*;
pub use struct_trait::*;
pub use tuple::*;
pub use tuple_struct::*;
pub use type_data::*;
pub use type_info::*;
pub use type_registry::*;
pub use type_uuid::*;
Expand Down Expand Up @@ -1045,4 +1047,56 @@ bevy_reflect::tests::should_reflect_debug::Test {
assert_eq!(v, vec3(4.0, 2.0, 1.0));
}
}

#[test]
fn type_data_specialization() {
#[derive(Reflect, Debug)]
#[reflect(MyTrait)]
struct HasGenericTypeData;

#[derive(Reflect, Debug)]
#[reflect(MyTrait)]
struct HasSpecializedTypeData;

#[derive(Clone, Debug, PartialEq, Eq)]
enum ReflectMyTrait {
Generic,
Specialized,
}

impl<T> FromType<T> for ReflectMyTrait {
fn from_type() -> Self {
Self::Generic
}
}

impl SpecializedFromType<HasSpecializedTypeData> for ReflectMyTrait {
fn specialized_from_type() -> Self {
Self::Specialized
}
}

let type_registry = {
let mut type_registry = TypeRegistry::new();
type_registry.register::<HasGenericTypeData>();
type_registry.register::<HasSpecializedTypeData>();
type_registry
};

assert_eq!(
type_registry
.get_type_data::<ReflectMyTrait>(std::any::TypeId::of::<HasGenericTypeData>())
.expect("Generic type data is missing!"),
&ReflectMyTrait::Generic,
"Got specialized type data instead of generic type data."
);

assert_eq!(
type_registry
.get_type_data::<ReflectMyTrait>(std::any::TypeId::of::<HasSpecializedTypeData>())
.expect("Specialized type data is missing!"),
&ReflectMyTrait::Specialized,
"Got generic type data instead of specialized type data."
);
}
}
35 changes: 35 additions & 0 deletions crates/bevy_reflect/src/type_data.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use downcast_rs::{impl_downcast, Downcast};

/// A trait for types generated by the [`#[reflect_trait]`][0] attribute macro.
///
/// [0]: crate::reflect_trait
pub trait TypeData: Downcast + Send + Sync {
fn clone_type_data(&self) -> Box<dyn TypeData>;
}
impl_downcast!(TypeData);

impl<T: 'static + Send + Sync> TypeData for T
where
T: Clone,
{
fn clone_type_data(&self) -> Box<dyn TypeData> {
Box::new(self.clone())
}
}

/// Trait used to generate [`TypeData`] for trait reflection.
///
/// This is used by the `#[derive(Reflect)]` macro to generate an implementation
/// of [`TypeData`] to pass to [`crate::TypeRegistration::insert`].
pub trait FromType<T> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would also be worthwhile to reference the other struct somewhere in the documentation here, briefly indicating how they can be used together.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are you thinking something like "to specialize an existing blanket implementation, see SpecializedFromType"?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Exactly 🙂

fn from_type() -> Self;
}

/// A trait which can be used to specialize a blanket `FromType` implementation.
///
/// If implemented, the `#[derive(Reflect)]` macro will use this trait's
/// `specialized_from_type` method instead of `FromType::<T>::from_type()` to
/// generate a corresponding [`TypeData`] for `T`.
pub trait SpecializedFromType<T>: FromType<T> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add docs explaining what this struct is and how to use it? Including documentation on the method as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

fn specialized_from_type() -> Self;
}
27 changes: 1 addition & 26 deletions crates/bevy_reflect/src/type_registry.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::{serde::Serializable, Reflect, TypeInfo, Typed};
use crate::{serde::Serializable, FromType, Reflect, TypeData, TypeInfo, Typed};
use bevy_ptr::{Ptr, PtrMut};
use bevy_utils::{HashMap, HashSet};
use downcast_rs::{impl_downcast, Downcast};
use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use serde::Deserialize;
use std::{any::TypeId, fmt::Debug, sync::Arc};
Expand Down Expand Up @@ -361,30 +360,6 @@ impl Clone for TypeRegistration {
}
}
}
/// A trait for types generated by the [`#[reflect_trait]`][0] attribute macro.
///
/// [0]: crate::reflect_trait
pub trait TypeData: Downcast + Send + Sync {
fn clone_type_data(&self) -> Box<dyn TypeData>;
}
impl_downcast!(TypeData);

impl<T: 'static + Send + Sync> TypeData for T
where
T: Clone,
{
fn clone_type_data(&self) -> Box<dyn TypeData> {
Box::new(self.clone())
}
}

/// Trait used to generate [`TypeData`] for trait reflection.
///
/// This is used by the `#[derive(Reflect)]` macro to generate an implementation
/// of [`TypeData`] to pass to [`TypeRegistration::insert`].
pub trait FromType<T> {
fn from_type() -> Self;
}

/// A struct used to serialize reflected instances of a type.
///
Expand Down