bevy_reflect/from_reflect.rs
1use crate::{FromType, Reflect};
2
3/// A trait that enables types to be dynamically constructed from reflected data.
4///
5/// It's recommended to use the [derive macro] rather than manually implementing this trait.
6///
7/// `FromReflect` allows dynamic proxy types, like [`DynamicStruct`], to be used to generate
8/// their concrete counterparts.
9/// It can also be used to partially or fully clone a type (depending on whether it has
10/// ignored fields or not).
11///
12/// In some cases, this trait may even be required.
13/// Deriving [`Reflect`] on an enum requires all its fields to implement `FromReflect`.
14/// Additionally, some complex types like `Vec<T>` require that their element types
15/// implement this trait.
16/// The reason for such requirements is that some operations require new data to be constructed,
17/// such as swapping to a new variant or pushing data to a homogeneous list.
18///
19/// See the [crate-level documentation] to see how this trait can be used.
20///
21/// [derive macro]: bevy_reflect_derive::FromReflect
22/// [`DynamicStruct`]: crate::DynamicStruct
23/// [crate-level documentation]: crate
24#[diagnostic::on_unimplemented(
25 message = "`{Self}` can not be created through reflection",
26 note = "consider annotating `{Self}` with `#[derive(FromReflect)]`"
27)]
28pub trait FromReflect: Reflect + Sized {
29 /// Constructs a concrete instance of `Self` from a reflected value.
30 fn from_reflect(reflect: &dyn Reflect) -> Option<Self>;
31
32 /// Attempts to downcast the given value to `Self` using,
33 /// constructing the value using [`from_reflect`] if that fails.
34 ///
35 /// This method is more efficient than using [`from_reflect`] for cases where
36 /// the given value is likely a boxed instance of `Self` (i.e. `Box<Self>`)
37 /// rather than a boxed dynamic type (e.g. [`DynamicStruct`], [`DynamicList`], etc.).
38 ///
39 /// [`from_reflect`]: Self::from_reflect
40 /// [`DynamicStruct`]: crate::DynamicStruct
41 /// [`DynamicList`]: crate::DynamicList
42 fn take_from_reflect(reflect: Box<dyn Reflect>) -> Result<Self, Box<dyn Reflect>> {
43 match reflect.take::<Self>() {
44 Ok(value) => Ok(value),
45 Err(value) => match Self::from_reflect(value.as_ref()) {
46 None => Err(value),
47 Some(value) => Ok(value),
48 },
49 }
50 }
51}
52
53/// Type data that represents the [`FromReflect`] trait and allows it to be used dynamically.
54///
55/// `FromReflect` allows dynamic types (e.g. [`DynamicStruct`], [`DynamicEnum`], etc.) to be converted
56/// to their full, concrete types. This is most important when it comes to deserialization where it isn't
57/// guaranteed that every field exists when trying to construct the final output.
58///
59/// However, to do this, you normally need to specify the exact concrete type:
60///
61/// ```
62/// # use bevy_reflect::{DynamicTupleStruct, FromReflect, Reflect};
63/// #[derive(Reflect, PartialEq, Eq, Debug)]
64/// struct Foo(#[reflect(default = "default_value")] usize);
65///
66/// fn default_value() -> usize { 123 }
67///
68/// let reflected = DynamicTupleStruct::default();
69///
70/// let concrete: Foo = <Foo as FromReflect>::from_reflect(&reflected).unwrap();
71///
72/// assert_eq!(Foo(123), concrete);
73/// ```
74///
75/// In a dynamic context where the type might not be known at compile-time, this is nearly impossible to do.
76/// That is why this type data struct exists— it allows us to construct the full type without knowing
77/// what the actual type is.
78///
79/// # Example
80///
81/// ```
82/// # use bevy_reflect::{DynamicTupleStruct, Reflect, ReflectFromReflect, Typed, TypeRegistry, TypePath};
83/// # #[derive(Reflect, PartialEq, Eq, Debug)]
84/// # struct Foo(#[reflect(default = "default_value")] usize);
85/// # fn default_value() -> usize { 123 }
86/// # let mut registry = TypeRegistry::new();
87/// # registry.register::<Foo>();
88///
89/// let mut reflected = DynamicTupleStruct::default();
90/// reflected.set_represented_type(Some(<Foo as Typed>::type_info()));
91///
92/// let registration = registry.get_with_type_path(<Foo as TypePath>::type_path()).unwrap();
93/// let rfr = registration.data::<ReflectFromReflect>().unwrap();
94///
95/// let concrete: Box<dyn Reflect> = rfr.from_reflect(&reflected).unwrap();
96///
97/// assert_eq!(Foo(123), concrete.take::<Foo>().unwrap());
98/// ```
99///
100/// [`DynamicStruct`]: crate::DynamicStruct
101/// [`DynamicEnum`]: crate::DynamicEnum
102#[derive(Clone)]
103pub struct ReflectFromReflect {
104 from_reflect: fn(&dyn Reflect) -> Option<Box<dyn Reflect>>,
105}
106
107impl ReflectFromReflect {
108 /// Perform a [`FromReflect::from_reflect`] conversion on the given reflection object.
109 ///
110 /// This will convert the object to a concrete type if it wasn't already, and return
111 /// the value as `Box<dyn Reflect>`.
112 #[allow(clippy::wrong_self_convention)]
113 pub fn from_reflect(&self, reflect_value: &dyn Reflect) -> Option<Box<dyn Reflect>> {
114 (self.from_reflect)(reflect_value)
115 }
116}
117
118impl<T: FromReflect> FromType<T> for ReflectFromReflect {
119 fn from_type() -> Self {
120 Self {
121 from_reflect: |reflect_value| {
122 T::from_reflect(reflect_value).map(|value| Box::new(value) as Box<dyn Reflect>)
123 },
124 }
125 }
126}