Skip to content

Commit ba3d9b3

Browse files
authored
bevy_reflect: Refactor serde module (#15107)
# Objective The `ser` and `de` modules in `bevy_reflect/serde` are very long and difficult to navigate. ## Solution Refactor both modules into many smaller modules that each have a single primary focus (i.e. a `structs` module that only handles struct serialization/deserialization). I chose to keep the `ser` and `de` modules separate. We could have instead broken it up kind (e.g. lists, maps, etc.), but I think this is a little cleaner. Serialization and deserialization, while related, can be very different. So keeping them separated makes sense for organizational purposes. That being said, if people disagree and think we should structure this a different way, I am open to changing it. Note that this PR's changes are mainly structural. There are a few places I refactored code to reduce duplication and to make things a bit cleaner, but these are largely cosmetic and shouldn't have any impact on behavior. ### Other Details This PR also hides a lot of the internal logic from being exported. These were originally public, but it's unlikely they really saw any use outside of these modules. In fact, you don't really gain anything by using them outside of this module either. By privatizing these fields and items, we also set ourselves up for more easily changing internal logic around without involving a breaking change. I also chose not to mess around with tests since that would really blow up the diff haha. ## Testing You can test locally by running: ``` cargo test --package bevy_reflect --all-features ``` --- ## Migration Guide The fields on `ReflectSerializer` and `TypedReflectSerializer` are now private. To instantiate, the corresponding constructor must be used: ```rust // BEFORE let serializer = ReflectSerializer { value: &my_value, registry: &type_registry, }; // AFTER let serializer = ReflectSerializer::new(&my_value, &type_registry); ``` Additionally, the following types are no longer public: - `ArraySerializer` - `EnumSerializer` - `ListSerializer` - `MapSerializer` - `ReflectValueSerializer` (fully removed) - `StructSerializer` - `TupleSerializer` - `TupleStructSerializer` As well as the following traits: - `DeserializeValue` (fully removed)
1 parent a0faf9c commit ba3d9b3

29 files changed

+2954
-2724
lines changed

crates/bevy_reflect/src/serde/de.rs

Lines changed: 0 additions & 1712 deletions
This file was deleted.
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
use crate::serde::de::registration_utils::try_get_registration;
2+
use crate::serde::TypedReflectDeserializer;
3+
use crate::{ArrayInfo, DynamicArray, TypeRegistry};
4+
use core::fmt::Formatter;
5+
use serde::de::{Error, SeqAccess, Visitor};
6+
use std::fmt;
7+
8+
/// A [`Visitor`] for deserializing [`Array`] values.
9+
///
10+
/// [`Array`]: crate::Array
11+
pub(super) struct ArrayVisitor<'a> {
12+
array_info: &'static ArrayInfo,
13+
registry: &'a TypeRegistry,
14+
}
15+
16+
impl<'a> ArrayVisitor<'a> {
17+
pub fn new(array_info: &'static ArrayInfo, registry: &'a TypeRegistry) -> Self {
18+
Self {
19+
array_info,
20+
registry,
21+
}
22+
}
23+
}
24+
25+
impl<'a, 'de> Visitor<'de> for ArrayVisitor<'a> {
26+
type Value = DynamicArray;
27+
28+
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
29+
formatter.write_str("reflected array value")
30+
}
31+
32+
fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
33+
where
34+
V: SeqAccess<'de>,
35+
{
36+
let mut vec = Vec::with_capacity(seq.size_hint().unwrap_or_default());
37+
let registration = try_get_registration(self.array_info.item_ty(), self.registry)?;
38+
while let Some(value) =
39+
seq.next_element_seed(TypedReflectDeserializer::new(registration, self.registry))?
40+
{
41+
vec.push(value);
42+
}
43+
44+
if vec.len() != self.array_info.capacity() {
45+
return Err(Error::invalid_length(
46+
vec.len(),
47+
&self.array_info.capacity().to_string().as_str(),
48+
));
49+
}
50+
51+
Ok(DynamicArray::new(vec.into_boxed_slice()))
52+
}
53+
}
Lines changed: 333 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,333 @@
1+
use crate::serde::de::arrays::ArrayVisitor;
2+
use crate::serde::de::enums::EnumVisitor;
3+
use crate::serde::de::lists::ListVisitor;
4+
use crate::serde::de::maps::MapVisitor;
5+
use crate::serde::de::options::OptionVisitor;
6+
use crate::serde::de::sets::SetVisitor;
7+
use crate::serde::de::structs::StructVisitor;
8+
use crate::serde::de::tuple_structs::TupleStructVisitor;
9+
use crate::serde::de::tuples::TupleVisitor;
10+
use crate::serde::TypeRegistrationDeserializer;
11+
use crate::{PartialReflect, ReflectDeserialize, TypeInfo, TypeRegistration, TypeRegistry};
12+
use core::fmt::Formatter;
13+
use serde::de::{DeserializeSeed, Error, IgnoredAny, MapAccess, Visitor};
14+
use std::fmt;
15+
16+
/// A general purpose deserializer for reflected types.
17+
///
18+
/// This is the deserializer counterpart to [`ReflectSerializer`].
19+
///
20+
/// See [`TypedReflectDeserializer`] for a deserializer that expects a known type.
21+
///
22+
/// # Input
23+
///
24+
/// This deserializer expects a map with a single entry,
25+
/// where the key is the _full_ [type path] of the reflected type
26+
/// and the value is the serialized data.
27+
///
28+
/// # Output
29+
///
30+
/// This deserializer will return a [`Box<dyn Reflect>`] containing the deserialized data.
31+
///
32+
/// For value types (i.e. [`ReflectKind::Value`]) or types that register [`ReflectDeserialize`] type data,
33+
/// this `Box` will contain the expected type.
34+
/// For example, deserializing an `i32` will return a `Box<i32>` (as a `Box<dyn Reflect>`).
35+
///
36+
/// Otherwise, this `Box` will contain the dynamic equivalent.
37+
/// For example, a deserialized struct might return a [`Box<DynamicStruct>`]
38+
/// and a deserialized `Vec` might return a [`Box<DynamicList>`].
39+
///
40+
/// This means that if the actual type is needed, these dynamic representations will need to
41+
/// be converted to the concrete type using [`FromReflect`] or [`ReflectFromReflect`].
42+
///
43+
/// # Example
44+
///
45+
/// ```
46+
/// # use serde::de::DeserializeSeed;
47+
/// # use bevy_reflect::prelude::*;
48+
/// # use bevy_reflect::{DynamicStruct, TypeRegistry, serde::ReflectDeserializer};
49+
/// #[derive(Reflect, PartialEq, Debug)]
50+
/// #[type_path = "my_crate"]
51+
/// struct MyStruct {
52+
/// value: i32
53+
/// }
54+
///
55+
/// let mut registry = TypeRegistry::default();
56+
/// registry.register::<MyStruct>();
57+
///
58+
/// let input = r#"{
59+
/// "my_crate::MyStruct": (
60+
/// value: 123
61+
/// )
62+
/// }"#;
63+
///
64+
/// let mut deserializer = ron::Deserializer::from_str(input).unwrap();
65+
/// let reflect_deserializer = ReflectDeserializer::new(&registry);
66+
///
67+
/// let output: Box<dyn PartialReflect> = reflect_deserializer.deserialize(&mut deserializer).unwrap();
68+
///
69+
/// // Since `MyStruct` is not a value type and does not register `ReflectDeserialize`,
70+
/// // we know that its deserialized value will be a `DynamicStruct`,
71+
/// // although it will represent `MyStruct`.
72+
/// assert!(output.as_partial_reflect().represents::<MyStruct>());
73+
///
74+
/// // We can convert back to `MyStruct` using `FromReflect`.
75+
/// let value: MyStruct = <MyStruct as FromReflect>::from_reflect(output.as_partial_reflect()).unwrap();
76+
/// assert_eq!(value, MyStruct { value: 123 });
77+
///
78+
/// // We can also do this dynamically with `ReflectFromReflect`.
79+
/// let type_id = output.get_represented_type_info().unwrap().type_id();
80+
/// let reflect_from_reflect = registry.get_type_data::<ReflectFromReflect>(type_id).unwrap();
81+
/// let value: Box<dyn Reflect> = reflect_from_reflect.from_reflect(output.as_partial_reflect()).unwrap();
82+
/// assert!(value.is::<MyStruct>());
83+
/// assert_eq!(value.take::<MyStruct>().unwrap(), MyStruct { value: 123 });
84+
/// ```
85+
///
86+
/// [`ReflectSerializer`]: crate::serde::ReflectSerializer
87+
/// [type path]: crate::TypePath::type_path
88+
/// [`Box<dyn Reflect>`]: crate::Reflect
89+
/// [`ReflectKind::Value`]: crate::ReflectKind::Value
90+
/// [`ReflectDeserialize`]: crate::ReflectDeserialize
91+
/// [`Box<DynamicStruct>`]: crate::DynamicStruct
92+
/// [`Box<DynamicList>`]: crate::DynamicList
93+
/// [`FromReflect`]: crate::FromReflect
94+
/// [`ReflectFromReflect`]: crate::ReflectFromReflect
95+
pub struct ReflectDeserializer<'a> {
96+
registry: &'a TypeRegistry,
97+
}
98+
99+
impl<'a> ReflectDeserializer<'a> {
100+
pub fn new(registry: &'a TypeRegistry) -> Self {
101+
Self { registry }
102+
}
103+
}
104+
105+
impl<'a, 'de> DeserializeSeed<'de> for ReflectDeserializer<'a> {
106+
type Value = Box<dyn PartialReflect>;
107+
108+
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
109+
where
110+
D: serde::Deserializer<'de>,
111+
{
112+
struct UntypedReflectDeserializerVisitor<'a> {
113+
registry: &'a TypeRegistry,
114+
}
115+
116+
impl<'a, 'de> Visitor<'de> for UntypedReflectDeserializerVisitor<'a> {
117+
type Value = Box<dyn PartialReflect>;
118+
119+
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
120+
formatter
121+
.write_str("map containing `type` and `value` entries for the reflected value")
122+
}
123+
124+
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
125+
where
126+
A: MapAccess<'de>,
127+
{
128+
let registration = map
129+
.next_key_seed(TypeRegistrationDeserializer::new(self.registry))?
130+
.ok_or_else(|| Error::invalid_length(0, &"a single entry"))?;
131+
132+
let value = map.next_value_seed(TypedReflectDeserializer {
133+
registration,
134+
registry: self.registry,
135+
})?;
136+
137+
if map.next_key::<IgnoredAny>()?.is_some() {
138+
return Err(Error::invalid_length(2, &"a single entry"));
139+
}
140+
141+
Ok(value)
142+
}
143+
}
144+
145+
deserializer.deserialize_map(UntypedReflectDeserializerVisitor {
146+
registry: self.registry,
147+
})
148+
}
149+
}
150+
151+
/// A deserializer for reflected types whose [`TypeRegistration`] is known.
152+
///
153+
/// This is the deserializer counterpart to [`TypedReflectSerializer`].
154+
///
155+
/// See [`ReflectDeserializer`] for a deserializer that expects an unknown type.
156+
///
157+
/// # Input
158+
///
159+
/// Since the type is already known, the input is just the serialized data.
160+
///
161+
/// # Output
162+
///
163+
/// This deserializer will return a [`Box<dyn Reflect>`] containing the deserialized data.
164+
///
165+
/// For value types (i.e. [`ReflectKind::Value`]) or types that register [`ReflectDeserialize`] type data,
166+
/// this `Box` will contain the expected type.
167+
/// For example, deserializing an `i32` will return a `Box<i32>` (as a `Box<dyn Reflect>`).
168+
///
169+
/// Otherwise, this `Box` will contain the dynamic equivalent.
170+
/// For example, a deserialized struct might return a [`Box<DynamicStruct>`]
171+
/// and a deserialized `Vec` might return a [`Box<DynamicList>`].
172+
///
173+
/// This means that if the actual type is needed, these dynamic representations will need to
174+
/// be converted to the concrete type using [`FromReflect`] or [`ReflectFromReflect`].
175+
///
176+
/// # Example
177+
///
178+
/// ```
179+
/// # use std::any::TypeId;
180+
/// # use serde::de::DeserializeSeed;
181+
/// # use bevy_reflect::prelude::*;
182+
/// # use bevy_reflect::{DynamicStruct, TypeRegistry, serde::TypedReflectDeserializer};
183+
/// #[derive(Reflect, PartialEq, Debug)]
184+
/// struct MyStruct {
185+
/// value: i32
186+
/// }
187+
///
188+
/// let mut registry = TypeRegistry::default();
189+
/// registry.register::<MyStruct>();
190+
///
191+
/// let input = r#"(
192+
/// value: 123
193+
/// )"#;
194+
///
195+
/// let registration = registry.get(TypeId::of::<MyStruct>()).unwrap();
196+
///
197+
/// let mut deserializer = ron::Deserializer::from_str(input).unwrap();
198+
/// let reflect_deserializer = TypedReflectDeserializer::new(registration, &registry);
199+
///
200+
/// let output: Box<dyn PartialReflect> = reflect_deserializer.deserialize(&mut deserializer).unwrap();
201+
///
202+
/// // Since `MyStruct` is not a value type and does not register `ReflectDeserialize`,
203+
/// // we know that its deserialized value will be a `DynamicStruct`,
204+
/// // although it will represent `MyStruct`.
205+
/// assert!(output.as_partial_reflect().represents::<MyStruct>());
206+
///
207+
/// // We can convert back to `MyStruct` using `FromReflect`.
208+
/// let value: MyStruct = <MyStruct as FromReflect>::from_reflect(output.as_partial_reflect()).unwrap();
209+
/// assert_eq!(value, MyStruct { value: 123 });
210+
///
211+
/// // We can also do this dynamically with `ReflectFromReflect`.
212+
/// let type_id = output.get_represented_type_info().unwrap().type_id();
213+
/// let reflect_from_reflect = registry.get_type_data::<ReflectFromReflect>(type_id).unwrap();
214+
/// let value: Box<dyn Reflect> = reflect_from_reflect.from_reflect(output.as_partial_reflect()).unwrap();
215+
/// assert!(value.is::<MyStruct>());
216+
/// assert_eq!(value.take::<MyStruct>().unwrap(), MyStruct { value: 123 });
217+
/// ```
218+
///
219+
/// [`TypedReflectSerializer`]: crate::serde::TypedReflectSerializer
220+
/// [`Box<dyn Reflect>`]: crate::Reflect
221+
/// [`ReflectKind::Value`]: crate::ReflectKind::Value
222+
/// [`ReflectDeserialize`]: crate::ReflectDeserialize
223+
/// [`Box<DynamicStruct>`]: crate::DynamicStruct
224+
/// [`Box<DynamicList>`]: crate::DynamicList
225+
/// [`FromReflect`]: crate::FromReflect
226+
/// [`ReflectFromReflect`]: crate::ReflectFromReflect
227+
pub struct TypedReflectDeserializer<'a> {
228+
registration: &'a TypeRegistration,
229+
registry: &'a TypeRegistry,
230+
}
231+
232+
impl<'a> TypedReflectDeserializer<'a> {
233+
pub fn new(registration: &'a TypeRegistration, registry: &'a TypeRegistry) -> Self {
234+
Self {
235+
registration,
236+
registry,
237+
}
238+
}
239+
}
240+
241+
impl<'a, 'de> DeserializeSeed<'de> for TypedReflectDeserializer<'a> {
242+
type Value = Box<dyn PartialReflect>;
243+
244+
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
245+
where
246+
D: serde::Deserializer<'de>,
247+
{
248+
let type_path = self.registration.type_info().type_path();
249+
250+
// Handle both Value case and types that have a custom `ReflectDeserialize`
251+
if let Some(deserialize_reflect) = self.registration.data::<ReflectDeserialize>() {
252+
let value = deserialize_reflect.deserialize(deserializer)?;
253+
return Ok(value.into_partial_reflect());
254+
}
255+
256+
match self.registration.type_info() {
257+
TypeInfo::Struct(struct_info) => {
258+
let mut dynamic_struct = deserializer.deserialize_struct(
259+
struct_info.type_path_table().ident().unwrap(),
260+
struct_info.field_names(),
261+
StructVisitor::new(struct_info, self.registration, self.registry),
262+
)?;
263+
dynamic_struct.set_represented_type(Some(self.registration.type_info()));
264+
Ok(Box::new(dynamic_struct))
265+
}
266+
TypeInfo::TupleStruct(tuple_struct_info) => {
267+
let mut dynamic_tuple_struct = deserializer.deserialize_tuple_struct(
268+
tuple_struct_info.type_path_table().ident().unwrap(),
269+
tuple_struct_info.field_len(),
270+
TupleStructVisitor::new(tuple_struct_info, self.registration, self.registry),
271+
)?;
272+
dynamic_tuple_struct.set_represented_type(Some(self.registration.type_info()));
273+
Ok(Box::new(dynamic_tuple_struct))
274+
}
275+
TypeInfo::List(list_info) => {
276+
let mut dynamic_list =
277+
deserializer.deserialize_seq(ListVisitor::new(list_info, self.registry))?;
278+
dynamic_list.set_represented_type(Some(self.registration.type_info()));
279+
Ok(Box::new(dynamic_list))
280+
}
281+
TypeInfo::Array(array_info) => {
282+
let mut dynamic_array = deserializer.deserialize_tuple(
283+
array_info.capacity(),
284+
ArrayVisitor::new(array_info, self.registry),
285+
)?;
286+
dynamic_array.set_represented_type(Some(self.registration.type_info()));
287+
Ok(Box::new(dynamic_array))
288+
}
289+
TypeInfo::Map(map_info) => {
290+
let mut dynamic_map =
291+
deserializer.deserialize_map(MapVisitor::new(map_info, self.registry))?;
292+
dynamic_map.set_represented_type(Some(self.registration.type_info()));
293+
Ok(Box::new(dynamic_map))
294+
}
295+
TypeInfo::Set(set_info) => {
296+
let mut dynamic_set =
297+
deserializer.deserialize_seq(SetVisitor::new(set_info, self.registry))?;
298+
dynamic_set.set_represented_type(Some(self.registration.type_info()));
299+
Ok(Box::new(dynamic_set))
300+
}
301+
TypeInfo::Tuple(tuple_info) => {
302+
let mut dynamic_tuple = deserializer.deserialize_tuple(
303+
tuple_info.field_len(),
304+
TupleVisitor::new(tuple_info, self.registration, self.registry),
305+
)?;
306+
dynamic_tuple.set_represented_type(Some(self.registration.type_info()));
307+
Ok(Box::new(dynamic_tuple))
308+
}
309+
TypeInfo::Enum(enum_info) => {
310+
let mut dynamic_enum = if enum_info.type_path_table().module_path()
311+
== Some("core::option")
312+
&& enum_info.type_path_table().ident() == Some("Option")
313+
{
314+
deserializer.deserialize_option(OptionVisitor::new(enum_info, self.registry))?
315+
} else {
316+
deserializer.deserialize_enum(
317+
enum_info.type_path_table().ident().unwrap(),
318+
enum_info.variant_names(),
319+
EnumVisitor::new(enum_info, self.registration, self.registry),
320+
)?
321+
};
322+
dynamic_enum.set_represented_type(Some(self.registration.type_info()));
323+
Ok(Box::new(dynamic_enum))
324+
}
325+
TypeInfo::Value(_) => {
326+
// This case should already be handled
327+
Err(Error::custom(format_args!(
328+
"Type `{type_path}` did not register the `ReflectDeserialize` type data. For certain types, this may need to be registered manually using `register_type_data`",
329+
)))
330+
}
331+
}
332+
}
333+
}

0 commit comments

Comments
 (0)