Reflection in Rust.
Reflection is a powerful tool provided within many programming languages
that allows for meta-programming: using information about the program to
affect the program.
In other words, reflection allows us to inspect the program itself, its
syntax, and its type information at runtime.
While Rust doesn't yet provide much built-in tooling for reflection,
this crate serves to help fill that role.
And while it was made with the Bevy game engine in mind,
it's a general-purpose solution that can be used in any Rust project.
At a very high level, this crate allows you to:
Reflect
TraitAt the core of bevy_reflect
is the [Reflect
] trait.
One of its primary purposes is to allow all implementors to be passed around
as a dyn Reflect
trait object.
This allows any such type to be operated upon completely dynamically (at a small runtime cost).
Implementing the trait is easily done using the provided derive macro:
This will automatically generate the implementation of Reflect
for any struct or enum.
It will also generate other very important trait implementations used for reflection:
GetTypeRegistration
]Typed
]Struct
], [TupleStruct
], or [Enum
] depending on the typeWe can implement Reflect
on any type that satisfies both of the following conditions:
Any
.'static
lifetime.Reflect
Additionally, using the derive macro on enums requires a third condition to be met:
FromReflect
]— another important reflection trait discussed in a later section.Reflect
SubtraitsSince [Reflect
] is meant to cover any and every type, this crate also comes with a few
more traits to accompany Reflect
and provide more specific interactions.
We refer to these traits as the reflection subtraits since they all have Reflect
as a supertrait.
The current list of reflection subtraits include:
Tuple
]Array
]List
]Map
]Struct
]TupleStruct
]Enum
]As mentioned previously, the last three are automatically implemented by the derive macro.
Each of these traits come with their own methods specific to their respective category.
For example, we can access our struct's fields by name using the [Struct::field
] method.
Since most data is passed around as dyn Reflect
,
the Reflect
trait has methods for going to and from these subtraits.
[Reflect::reflect_ref
], [Reflect::reflect_mut
], and [Reflect::reflect_owned
] all return
an enum that respectively contains immutable, mutable, and owned access to the type as a subtrait object.
For example, we can get out a dyn Tuple
from our reflected tuple type using one of these methods.
And to go back to a general-purpose dyn Reflect
,
we can just use of the matching [Reflect::as_reflect
], [Reflect::as_reflect_mut
],
or [Reflect::into_reflect
] methods.
Types that do not fall under one of the above subtraits,
such as for primitives (e.g. bool
, usize
, etc.)
and simple types (e.g. String
, Duration
),
are referred to as value types
since methods like [Reflect::reflect_ref
] return a [ReflectRef::Value
] variant.
While most other types contain their own dyn Reflect
fields and data,
these types generally cannot be broken down any further.
Each subtrait comes with a corresponding dynamic type.
The available dynamic types are:
DynamicTuple
]DynamicArray
]DynamicList
]DynamicMap
]DynamicStruct
]DynamicTupleStruct
]DynamicEnum
]These dynamic types may contain any arbitrary reflected data.
They are most commonly used as "proxies" for other types,
where they contain the same data as— and therefore, represent— a concrete type.
The [Reflect::clone_value
] will return a dynamic type for all non-value types,
allowing all types to essentially be "cloned".
And since dynamic types themselves implement [Reflect
],
we may pass them around just like any other reflected type.
These dynamic types come in handy when needing to apply multiple changes to another type.
This is known as "patching" and is done using the [Reflect::apply
] method.
FromReflect
It's important to remember that dynamics are not the concrete type they may be representing.
A common mistake is to treat them like such when trying to cast back to the original type
or when trying to make use of a reflected trait which expects the actual type.
To resolve this issue, we'll need to convert the dynamic type to the concrete one.
This is where [FromReflect
] comes in.
FromReflect
is a derivable trait that allows an instance of a type to be generated from a
dynamic representation— even partial ones.
And since the [FromReflect::from_reflect
] method takes the data by reference,
this can be used to effectively clone data (to an extent).
This trait can be derived on any type whose fields and sub-elements also implement FromReflect
.
With the derive macro, fields can be ignored or given default values for when a field is missing
in the passed value.
See the derive macro documentation for details.
All primitives and simple types implement FromReflect
by relying on their [Default
] implementation.
This crate also comes with a [TypeRegistry
] that can be used to store and retrieve additional data,
such as helper types and trait implementations.
The derive macro for [Reflect
] also generates an implementation of the [GetTypeRegistration
] trait,
which is used by the registry to generate a [TypeRegistration
] struct for that type.
We can then register additional type data we want associated with that type.
For example, we can register ReflectDefault
on our type so that its Default
implementation
may be used dynamically.
Because this operation is so common, the derive macro actually has a shorthand for it.
By using the #[reflect(Trait)]
attribute, the derive macro will automatically register a matching,
in-scope ReflectTrait
type within the GetTypeRegistration
implementation.
Type data doesn't have to be tied to a trait, but they it's often extremely useful to create trait type data.
These allow traits to be used directly on a dyn Reflect
while utilizing the underlying type's implementation.
For any object-safe trait, we can easily generate a corresponding ReflectTrait
type for our trait
using the [reflect_trait
] macro.
The generated type data can be used to convert a valid dyn Reflect
into a dyn MyTrait
.
See the trait reflection example
for more information and usage details.
By using reflection, we are also able to get serialization capabilities for free.
In fact, using bevy_reflect
can result in faster compile times and reduced code generation over
directly deriving the serde
traits.
The way it works is by moving the serialization logic into common serializers and deserializers:
All of these structs require a reference to the registry so that type information can be retrieved,
as well as registered type data, such as [ReflectSerialize
] and [ReflectDeserialize
].
The general entry point are the "untyped" versions of these structs.
These will automatically extract the type information and pass them into their respective "typed" version.
The output of the ReflectSerializer
will be a map, where the key is the type name
and the value is the serialized data.
The TypedReflectSerializer
will simply output the serialized data.
The UntypedReflectDeserializer
can be used to deserialize this map and return a Box<dyn Reflect>
,
where the underlying type will be a dynamic representing some concrete type (except for value types).
Again, it's important to remember that dynamics may need to be converted to their concrete counterparts
in order to be used in certain cases.
This can be achieved using [FromReflect
].