Skip to content

Commit 37443e0

Browse files
authored
bevy_reflect: Add DynamicTyped trait (#15108)
# Objective Thanks to #7207, we now have a way to validate at the type-level that a reflected value is actually the type it says it is and not just a dynamic representation of that type. `dyn PartialReflect` values _might_ be a dynamic type, but `dyn Reflect` values are guaranteed to _not_ be a dynamic type. Therefore, we can start to add methods to `Reflect` that weren't really possible before. For example, we should now be able to always get a `&'static TypeInfo`, and not just an `Option<&'static TypeInfo>`. ## Solution Add the `DynamicTyped` trait. This trait is similar to `DynamicTypePath` in that it provides a way to use the non-object-safe `Typed` trait in an object-safe way. And since all types that derive `Reflect` will also derive `Typed`, we can safely add `DynamicTyped` as a supertrait of `Reflect`. This allows us to use it when just given a `dyn Reflect` trait object. ## Testing You can test locally by running: ``` cargo test --package bevy_reflect ``` --- ## Showcase `Reflect` now has a supertrait of `DynamicTyped`, allowing `TypeInfo` to be retrieved from a `dyn Reflect` trait object without having to unwrap anything! ```rust let value: Box<dyn Reflect> = Box::new(String::from("Hello!")); // BEFORE let info: &'static TypeInfo = value.get_represented_type_info().unwrap(); // AFTER let info: &'static TypeInfo = value.reflect_type_info(); ``` ## Migration Guide `Reflect` now has a supertrait of `DynamicTyped`. If you were manually implementing `Reflect` and did not implement `Typed`, you will now need to do so.
1 parent ae80a20 commit 37443e0

File tree

6 files changed

+40
-24
lines changed

6 files changed

+40
-24
lines changed

crates/bevy_reflect/src/lib.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1632,7 +1632,7 @@ mod tests {
16321632

16331633
// TypeInfo (instance)
16341634
let value: &dyn Reflect = &123_i32;
1635-
let info = value.get_represented_type_info().unwrap();
1635+
let info = value.reflect_type_info();
16361636
assert!(info.is::<i32>());
16371637

16381638
// Struct
@@ -1653,7 +1653,7 @@ mod tests {
16531653
assert_eq!(usize::type_path(), info.field_at(1).unwrap().type_path());
16541654

16551655
let value: &dyn Reflect = &MyStruct { foo: 123, bar: 321 };
1656-
let info = value.get_represented_type_info().unwrap();
1656+
let info = value.reflect_type_info();
16571657
assert!(info.is::<MyStruct>());
16581658

16591659
// Struct (generic)
@@ -1675,7 +1675,7 @@ mod tests {
16751675
foo: String::from("Hello!"),
16761676
bar: 321,
16771677
};
1678-
let info = value.get_represented_type_info().unwrap();
1678+
let info = value.reflect_type_info();
16791679
assert!(info.is::<MyGenericStruct<String>>());
16801680

16811681
// Struct (dynamic field)
@@ -1705,7 +1705,7 @@ mod tests {
17051705
foo: DynamicStruct::default(),
17061706
bar: 321,
17071707
};
1708-
let info = value.get_represented_type_info().unwrap();
1708+
let info = value.reflect_type_info();
17091709
assert!(info.is::<MyDynamicStruct>());
17101710

17111711
// Tuple Struct
@@ -1731,7 +1731,7 @@ mod tests {
17311731
assert!(info.field_at(1).unwrap().type_info().unwrap().is::<f32>());
17321732

17331733
let value: &dyn Reflect = &(123_u32, 1.23_f32, String::from("Hello!"));
1734-
let info = value.get_represented_type_info().unwrap();
1734+
let info = value.reflect_type_info();
17351735
assert!(info.is::<MyTuple>());
17361736

17371737
// List
@@ -1746,7 +1746,7 @@ mod tests {
17461746
assert_eq!(usize::type_path(), info.item_ty().path());
17471747

17481748
let value: &dyn Reflect = &vec![123_usize];
1749-
let info = value.get_represented_type_info().unwrap();
1749+
let info = value.reflect_type_info();
17501750
assert!(info.is::<MyList>());
17511751

17521752
// List (SmallVec)
@@ -1763,7 +1763,7 @@ mod tests {
17631763

17641764
let value: MySmallVec = smallvec::smallvec![String::default(); 2];
17651765
let value: &dyn Reflect = &value;
1766-
let info = value.get_represented_type_info().unwrap();
1766+
let info = value.reflect_type_info();
17671767
assert!(info.is::<MySmallVec>());
17681768
}
17691769

@@ -1779,7 +1779,7 @@ mod tests {
17791779
assert_eq!(3, info.capacity());
17801780

17811781
let value: &dyn Reflect = &[1usize, 2usize, 3usize];
1782-
let info = value.get_represented_type_info().unwrap();
1782+
let info = value.reflect_type_info();
17831783
assert!(info.is::<MyArray>());
17841784

17851785
// Cow<'static, str>
@@ -1791,7 +1791,7 @@ mod tests {
17911791
assert_eq!(std::any::type_name::<MyCowStr>(), info.type_path());
17921792

17931793
let value: &dyn Reflect = &Cow::<'static, str>::Owned("Hello!".to_string());
1794-
let info = value.get_represented_type_info().unwrap();
1794+
let info = value.reflect_type_info();
17951795
assert!(info.is::<MyCowStr>());
17961796

17971797
// Cow<'static, [u8]>
@@ -1806,7 +1806,7 @@ mod tests {
18061806
assert_eq!(std::any::type_name::<u8>(), info.item_ty().path());
18071807

18081808
let value: &dyn Reflect = &Cow::<'static, [u8]>::Owned(vec![0, 1, 2, 3]);
1809-
let info = value.get_represented_type_info().unwrap();
1809+
let info = value.reflect_type_info();
18101810
assert!(info.is::<MyCowSlice>());
18111811

18121812
// Map
@@ -1824,7 +1824,7 @@ mod tests {
18241824
assert_eq!(f32::type_path(), info.value_ty().path());
18251825

18261826
let value: &dyn Reflect = &MyMap::new();
1827-
let info = value.get_represented_type_info().unwrap();
1827+
let info = value.reflect_type_info();
18281828
assert!(info.is::<MyMap>());
18291829

18301830
// Value
@@ -1836,7 +1836,7 @@ mod tests {
18361836
assert_eq!(MyValue::type_path(), info.type_path());
18371837

18381838
let value: &dyn Reflect = &String::from("Hello!");
1839-
let info = value.get_represented_type_info().unwrap();
1839+
let info = value.reflect_type_info();
18401840
assert!(info.is::<MyValue>());
18411841
}
18421842

crates/bevy_reflect/src/reflect.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::{
22
array_debug, enum_debug, list_debug, map_debug, serde::Serializable, struct_debug, tuple_debug,
3-
tuple_struct_debug, Array, DynamicTypePath, Enum, List, Map, Set, Struct, Tuple, TupleStruct,
4-
TypeInfo, TypePath, Typed, ValueInfo,
3+
tuple_struct_debug, Array, DynamicTypePath, DynamicTyped, Enum, List, Map, Set, Struct, Tuple,
4+
TupleStruct, TypeInfo, TypePath, Typed, ValueInfo,
55
};
66
use std::{
77
any::{Any, TypeId},
@@ -408,7 +408,7 @@ where
408408
message = "`{Self}` does not implement `Reflect` so cannot be fully reflected",
409409
note = "consider annotating `{Self}` with `#[derive(Reflect)]`"
410410
)]
411-
pub trait Reflect: PartialReflect + Any {
411+
pub trait Reflect: PartialReflect + DynamicTyped + Any {
412412
/// Returns the value as a [`Box<dyn Any>`][std::any::Any].
413413
///
414414
/// For remote wrapper types, this will return the remote type instead.

crates/bevy_reflect/src/serde/ser/serializable.rs

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,7 @@ impl<'a> Serializable<'a> {
3030
))
3131
})?;
3232

33-
let info = value.get_represented_type_info().ok_or_else(|| {
34-
make_custom_error(format_args!(
35-
"type `{}` does not represent any type",
36-
value.reflect_type_path(),
37-
))
38-
})?;
33+
let info = value.reflect_type_info();
3934

4035
let registration = type_registry.get(info.type_id()).ok_or_else(|| {
4136
make_custom_error(format_args!(

crates/bevy_reflect/src/type_info.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,27 @@ impl MaybeTyped for DynamicArray {}
136136

137137
impl MaybeTyped for DynamicTuple {}
138138

139+
/// Dynamic dispatch for [`Typed`].
140+
///
141+
/// Since this is a supertrait of [`Reflect`] its methods can be called on a `dyn Reflect`.
142+
///
143+
/// [`Reflect`]: crate::Reflect
144+
#[diagnostic::on_unimplemented(
145+
message = "`{Self}` can not provide dynamic type information through reflection",
146+
note = "consider annotating `{Self}` with `#[derive(Reflect)]`"
147+
)]
148+
pub trait DynamicTyped {
149+
/// See [`Typed::type_info`].
150+
fn reflect_type_info(&self) -> &'static TypeInfo;
151+
}
152+
153+
impl<T: Typed> DynamicTyped for T {
154+
#[inline]
155+
fn reflect_type_info(&self) -> &'static TypeInfo {
156+
Self::type_info()
157+
}
158+
}
159+
139160
/// A [`TypeInfo`]-specific error.
140161
#[derive(Debug, Error)]
141162
pub enum TypeInfoError {

crates/bevy_reflect/src/utility.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ impl<T: TypedProperty> Default for NonGenericTypeCell<T> {
171171
/// # fn reflect_owned(self: Box<Self>) -> ReflectOwned { todo!() }
172172
/// # fn clone_value(&self) -> Box<dyn PartialReflect> { todo!() }
173173
/// # }
174-
/// # impl<T: Reflect + TypePath> Reflect for Foo<T> {
174+
/// # impl<T: Reflect + Typed + TypePath> Reflect for Foo<T> {
175175
/// # fn into_any(self: Box<Self>) -> Box<dyn Any> { todo!() }
176176
/// # fn as_any(&self) -> &dyn Any { todo!() }
177177
/// # fn as_any_mut(&mut self) -> &mut dyn Any { todo!() }

examples/reflection/type_data.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ fn main() {
8080
registry.register_type_data::<Zombie, ReflectDamageable>();
8181

8282
// Then at any point we can retrieve the type data from the registry:
83-
let type_id = value.get_represented_type_info().unwrap().type_id();
83+
let type_id = value.reflect_type_info().type_id();
8484
let reflect_damageable = registry
8585
.get_type_data::<ReflectDamageable>(type_id)
8686
.unwrap();
@@ -133,7 +133,7 @@ fn main() {
133133
// Now we can use `ReflectHealth` to convert `dyn Reflect` into `dyn Health`:
134134
let value: Box<dyn Reflect> = Box::new(Skeleton { health: 50 });
135135

136-
let type_id = value.get_represented_type_info().unwrap().type_id();
136+
let type_id = value.reflect_type_info().type_id();
137137
let reflect_health = registry.get_type_data::<ReflectHealth>(type_id).unwrap();
138138

139139
// Type data generated by `#[reflect_trait]` comes with a `get`, `get_mut`, and `get_boxed` method,

0 commit comments

Comments
 (0)