Skip to main content

fyrox_core/
reflect.rs

1// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21//! Runtime reflection
22
23mod external_impls;
24mod std_impls;
25
26pub use fyrox_core_derive::Reflect;
27use std::ops::Deref;
28use std::{
29    any::{Any, TypeId},
30    fmt::{self, Debug, Display, Formatter},
31    mem::ManuallyDrop,
32};
33
34pub mod prelude {
35    pub use super::{
36        FieldMetadata, FieldMut, FieldRef, FieldValue, Reflect, ReflectArray, ReflectHashMap,
37        ReflectInheritableVariable, ReflectList, ResolvePath, SetFieldByPathError, SetFieldError,
38    };
39}
40
41/// A value of a field..
42pub trait FieldValue: Any + 'static {
43    /// Casts `self` to a `&dyn Any`
44    fn field_value_as_any_ref(&self) -> &dyn Any;
45
46    /// Casts `self` to a `&mut dyn Any`
47    fn field_value_as_any_mut(&mut self) -> &mut dyn Any;
48
49    fn field_value_as_reflect(&self) -> &dyn Reflect;
50    fn field_value_as_reflect_mut(&mut self) -> &mut dyn Reflect;
51
52    fn type_name(&self) -> &'static str;
53}
54
55impl<T: Reflect> FieldValue for T {
56    fn field_value_as_any_ref(&self) -> &dyn Any {
57        self
58    }
59
60    fn field_value_as_any_mut(&mut self) -> &mut dyn Any {
61        self
62    }
63
64    fn field_value_as_reflect(&self) -> &dyn Reflect {
65        self
66    }
67
68    fn field_value_as_reflect_mut(&mut self) -> &mut dyn Reflect {
69        self
70    }
71
72    fn type_name(&self) -> &'static str {
73        std::any::type_name::<T>()
74    }
75}
76
77/// An error that can occur during "type casting"
78#[derive(Debug)]
79pub enum CastError {
80    /// Given type does not match expected.
81    TypeMismatch {
82        /// A name of the field.
83        property_name: String,
84
85        /// Expected type identifier.
86        expected_type_id: TypeId,
87
88        /// Actual type identifier.
89        actual_type_id: TypeId,
90    },
91}
92
93impl std::error::Error for CastError {}
94
95impl Display for CastError {
96    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
97        match self {
98            CastError::TypeMismatch { property_name, .. } => {
99                write!(
100                    f,
101                    "Given type does not match expected for property {property_name:?}"
102                )
103            }
104        }
105    }
106}
107
108#[derive(Debug)]
109pub struct FieldMetadata<'s> {
110    /// A name of the property.
111    pub name: &'s str,
112
113    /// A human-readable name of the property.
114    pub display_name: &'s str,
115
116    /// Tag of the property. Could be used to group properties by a certain criteria or to find a
117    /// specific property by its tag.
118    pub tag: &'s str,
119
120    /// Doc comment content.
121    pub doc: &'s str,
122
123    /// A property is not meant to be edited.
124    pub read_only: bool,
125
126    /// Only for dynamic collections (Vec, etc) - means that its size cannot be changed, however the
127    /// _items_ of the collection can still be changed.
128    pub immutable_collection: bool,
129
130    /// A minimal value of the property. Works only with numeric properties!
131    pub min_value: Option<f64>,
132
133    /// A minimal value of the property. Works only with numeric properties!
134    pub max_value: Option<f64>,
135
136    /// A minimal value of the property. Works only with numeric properties!
137    pub step: Option<f64>,
138
139    /// Maximum amount of decimal places for a numeric property.
140    pub precision: Option<usize>,
141}
142
143pub struct FieldRef<'a, 'b> {
144    /// A reference to field's metadata.
145    pub metadata: &'a FieldMetadata<'b>,
146
147    /// An reference to the actual value of the property. This is "non-mangled" reference, which
148    /// means that while `field/fields/field_mut/fields_mut` might return a reference to other value,
149    /// than the actual field, the `value` is guaranteed to be a reference to the real value.
150    pub value: &'a dyn FieldValue,
151}
152
153impl<'b> Deref for FieldRef<'_, 'b> {
154    type Target = FieldMetadata<'b>;
155
156    fn deref(&self) -> &Self::Target {
157        self.metadata
158    }
159}
160
161impl FieldRef<'_, '_> {
162    /// Tries to cast a value to a given type.
163    pub fn cast_value<T: 'static>(&self) -> Result<&T, CastError> {
164        match self.value.field_value_as_any_ref().downcast_ref::<T>() {
165            Some(value) => Ok(value),
166            None => Err(CastError::TypeMismatch {
167                property_name: self.metadata.name.to_string(),
168                expected_type_id: TypeId::of::<T>(),
169                actual_type_id: self.value.type_id(),
170            }),
171        }
172    }
173}
174
175impl fmt::Debug for FieldRef<'_, '_> {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        f.debug_struct("FieldInfo")
178            .field("metadata", &self.metadata)
179            .field("value", &format_args!("{:?}", self.value as *const _))
180            .finish()
181    }
182}
183
184impl PartialEq<Self> for FieldRef<'_, '_> {
185    fn eq(&self, other: &Self) -> bool {
186        let value_ptr_a = self.value as *const _ as *const ();
187        let value_ptr_b = other.value as *const _ as *const ();
188
189        std::ptr::eq(value_ptr_a, value_ptr_b)
190    }
191}
192
193pub struct FieldMut<'a, 'b> {
194    /// A reference to field's metadata.
195    pub metadata: &'a FieldMetadata<'b>,
196
197    /// An reference to the actual value of the property. This is "non-mangled" reference, which
198    /// means that while `field/fields/field_mut/fields_mut` might return a reference to other value,
199    /// than the actual field, the `value` is guaranteed to be a reference to the real value.
200    pub value: &'a mut dyn FieldValue,
201}
202
203impl<'b> Deref for FieldMut<'_, 'b> {
204    type Target = FieldMetadata<'b>;
205
206    fn deref(&self) -> &Self::Target {
207        self.metadata
208    }
209}
210
211impl fmt::Debug for FieldMut<'_, '_> {
212    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213        f.debug_struct("FieldInfo")
214            .field("metadata", &self.metadata)
215            .field("value", &format_args!("{:?}", self.value as *const _))
216            .finish()
217    }
218}
219
220impl PartialEq<Self> for FieldMut<'_, '_> {
221    fn eq(&self, other: &Self) -> bool {
222        let value_ptr_a = self.value as *const _ as *const ();
223        let value_ptr_b = other.value as *const _ as *const ();
224
225        std::ptr::eq(value_ptr_a, value_ptr_b)
226    }
227}
228
229pub trait ReflectBase: Any + Debug {
230    fn as_any_raw(&self) -> &dyn Any;
231    fn as_any_raw_mut(&mut self) -> &mut dyn Any;
232}
233
234impl<T> ReflectBase for T
235where
236    T: Reflect,
237{
238    fn as_any_raw(&self) -> &dyn Any {
239        self
240    }
241
242    fn as_any_raw_mut(&mut self) -> &mut dyn Any {
243        self
244    }
245}
246
247/// A trait for runtime reflection.
248///
249/// ## Code Generation
250///
251/// The derive macro is available under `#[reflect(...)]` attribute that can be placed on both
252/// the type and its fields.
253///
254/// ### Type attributes
255///
256/// - `#[reflect(hide_all)]` - hide all fields from reflection.
257/// - `#[reflect(bounds)]` - add type boundary for `Reflect` impl, for example
258/// `#[reflect(bounds = "T: Reflect + Clone")]`
259/// - `#[reflect(non_cloneable)]` - prevent the macro from generating an implementation of
260/// [`Self::try_clone_box`] trait for your type. Could be useful for non-cloneable types.
261/// - `#[reflect(derived_type = "Type")]` - marks the type for which the attribute is added as a
262/// subtype for the `Type`.
263///
264/// ### Field attributes
265///
266/// - `#[reflect(hidden)]` - hides the field from reflection.
267/// - `#[reflect(setter = "foo")]` - set the desired method that will be used by [`Self::set_field`]
268/// default implementation.
269/// - `#[reflect(deref)]` - delegate the field access with `deref` + `deref_mut` calls. Could be
270/// useful for new-type objects.
271/// - `#[reflect(field = "foo")]` - sets the desired method, that will be used to access
272/// the field.
273/// - `#[reflect(field_mut = "foo")]` - sets the desired method, that will be used to access
274/// the field.
275/// - `#[reflect(name = "name")]` - overrides the name of the field.
276/// - `#[reflect(display_name = "name")]` - sets the human-readable name for the field.
277/// - `#[reflect(tag = "tag")]` - sets some arbitrary string tag of the field. It could be used to
278/// group properties by a certain criteria or to find a specific property by its tag.
279/// - `#[reflect(read_only)]` - the field is not meant to be editable. This flag does not prevent
280/// the reflection API from changing the actual value, it is just an instruction for external
281/// users (editors, tools, etc.)
282/// - `[#reflect(immutable_collection)]` - only for dynamic collections (`Vec`, etc.) - means that its
283/// size cannot be changed, however the _items_ of the collection can still be changed.
284/// - `#[reflect(min_value = "0.0")]` - minimal value of the field. Works only for numeric fields!
285/// - `#[reflect(max_value = "1.0")]` - maximal value of the field. Works only for numeric fields!
286/// - `#[reflect(step = "0.1")]` - increment/decrement step of the field. Works only for numeric fields!
287/// - `#[reflect(precision = "3")]` - maximum amount of decimal places for a numeric property.
288///
289/// ### Clone
290///
291/// By default, the proc macro adds an implementation of [`Self::try_clone_box`] with the assumption
292/// that your type implements the [`Clone`] trait. Not all types can implement this trait, in this
293/// case, add `#[reflect(non_cloneable)]` attribute for your type. This will force the implementation
294/// of [`Self::try_clone_box`] to return `None`.
295///
296/// ## Additional Trait Bounds
297///
298/// `Reflect` restricted to types that implement `Debug` trait, this is needed to convert the actual value
299/// to string. `Display` isn't used here, because it can't be derived and it is very tedious to implement it
300/// for every type that should support `Reflect` trait. It is a good compromise between development speed
301/// and the quality of the string output.
302pub trait Reflect: ReflectBase {
303    fn source_path() -> &'static str
304    where
305        Self: Sized;
306
307    fn derived_types() -> &'static [TypeId]
308    where
309        Self: Sized;
310
311    fn try_clone_box(&self) -> Option<Box<dyn Reflect>>;
312
313    fn query_derived_types(&self) -> &'static [TypeId];
314
315    fn type_name(&self) -> &'static str;
316
317    fn doc(&self) -> &'static str;
318
319    fn fields_ref(&self, func: &mut dyn FnMut(&[FieldRef]));
320
321    fn fields_mut(&mut self, func: &mut dyn FnMut(&mut [FieldMut]));
322
323    fn into_any(self: Box<Self>) -> Box<dyn Any>;
324
325    fn as_any(&self, func: &mut dyn FnMut(&dyn Any));
326
327    fn as_any_mut(&mut self, func: &mut dyn FnMut(&mut dyn Any));
328
329    fn as_reflect(&self, func: &mut dyn FnMut(&dyn Reflect));
330
331    fn as_reflect_mut(&mut self, func: &mut dyn FnMut(&mut dyn Reflect));
332
333    fn set(&mut self, value: Box<dyn Reflect>) -> Result<Box<dyn Reflect>, Box<dyn Reflect>>;
334
335    /// Returns a parent assembly name of the type that implements this trait. **WARNING:** You should use
336    /// proc-macro (`#[derive(Reflect)]`) to ensure that this method will return correct assembly
337    /// name. In other words - there's no guarantee, that any implementation other than proc-macro
338    /// will return a correct name of the assembly. Alternatively, you can use `env!("CARGO_PKG_NAME")`
339    /// as an implementation.
340    fn assembly_name(&self) -> &'static str;
341
342    /// Returns a parent assembly name of the type that implements this trait. **WARNING:** You should use
343    /// proc-macro (`#[derive(Reflect)]`) to ensure that this method will return correct assembly
344    /// name. In other words - there's no guarantee, that any implementation other than proc-macro
345    /// will return a correct name of the assembly. Alternatively, you can use `env!("CARGO_PKG_NAME")`
346    /// as an implementation.
347    fn type_assembly_name() -> &'static str
348    where
349        Self: Sized;
350
351    /// Calls user method specified with `#[reflect(setter = ..)]` or falls back to
352    /// [`Reflect::field_mut`]
353    #[allow(clippy::type_complexity)]
354    fn set_field(
355        &mut self,
356        field_name: &str,
357        value: Box<dyn Reflect>,
358        func: &mut dyn FnMut(Result<Box<dyn Reflect>, SetFieldError>),
359    ) {
360        let mut opt_value = Some(value);
361        self.field_mut(field_name, &mut move |field| {
362            let value = opt_value.take().unwrap();
363            match field {
364                Some(f) => func(f.set(value).map_err(|value| SetFieldError::InvalidValue {
365                    field_type_name: f.type_name(),
366                    value,
367                })),
368                None => func(Err(SetFieldError::NoSuchField {
369                    name: field_name.to_string(),
370                    value,
371                })),
372            };
373        });
374    }
375
376    fn field(&self, name: &str, func: &mut dyn FnMut(Option<&dyn Reflect>)) {
377        self.fields_ref(&mut |fields| {
378            func(
379                fields
380                    .iter()
381                    .find(|field| field.name == name)
382                    .map(|field| field.value.field_value_as_reflect()),
383            )
384        });
385    }
386
387    fn field_mut(&mut self, name: &str, func: &mut dyn FnMut(Option<&mut dyn Reflect>)) {
388        self.fields_mut(&mut |fields| {
389            func(
390                fields
391                    .iter_mut()
392                    .find(|field| field.name == name)
393                    .map(|field| field.value.field_value_as_reflect_mut()),
394            )
395        });
396    }
397
398    fn as_array(&self, func: &mut dyn FnMut(Option<&dyn ReflectArray>)) {
399        func(None)
400    }
401
402    fn as_array_mut(&mut self, func: &mut dyn FnMut(Option<&mut dyn ReflectArray>)) {
403        func(None)
404    }
405
406    fn as_list(&self, func: &mut dyn FnMut(Option<&dyn ReflectList>)) {
407        func(None)
408    }
409
410    fn as_list_mut(&mut self, func: &mut dyn FnMut(Option<&mut dyn ReflectList>)) {
411        func(None)
412    }
413
414    fn as_inheritable_variable(
415        &self,
416        func: &mut dyn FnMut(Option<&dyn ReflectInheritableVariable>),
417    ) {
418        func(None)
419    }
420
421    fn as_inheritable_variable_mut(
422        &mut self,
423        func: &mut dyn FnMut(Option<&mut dyn ReflectInheritableVariable>),
424    ) {
425        func(None)
426    }
427
428    fn as_hash_map(&self, func: &mut dyn FnMut(Option<&dyn ReflectHashMap>)) {
429        func(None)
430    }
431
432    fn as_hash_map_mut(&mut self, func: &mut dyn FnMut(Option<&mut dyn ReflectHashMap>)) {
433        func(None)
434    }
435
436    fn as_handle(&self, func: &mut dyn FnMut(Option<&dyn ReflectHandle>)) {
437        func(None)
438    }
439
440    fn as_handle_mut(&mut self, func: &mut dyn FnMut(Option<&mut dyn ReflectHandle>)) {
441        func(None)
442    }
443}
444
445pub trait ReflectHandle: Reflect {
446    fn reflect_inner_type_id(&self) -> TypeId;
447    fn reflect_inner_type_name(&self) -> &'static str;
448    fn reflect_is_some(&self) -> bool;
449    fn reflect_set_index(&mut self, index: u32);
450    fn reflect_index(&self) -> u32;
451    fn reflect_set_generation(&mut self, generation: u32);
452    fn reflect_generation(&self) -> u32;
453    fn reflect_as_erased(&self) -> ErasedHandle;
454}
455
456/// [`Reflect`] sub trait for working with slices.
457pub trait ReflectArray: Reflect {
458    fn reflect_index(&self, index: usize) -> Option<&dyn Reflect>;
459    fn reflect_index_mut(&mut self, index: usize) -> Option<&mut dyn Reflect>;
460    fn reflect_len(&self) -> usize;
461}
462
463/// [`Reflect`] sub trait for working with `Vec`-like types
464pub trait ReflectList: ReflectArray {
465    fn reflect_push(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>>;
466    fn reflect_pop(&mut self) -> Option<Box<dyn Reflect>>;
467    fn reflect_remove(&mut self, index: usize) -> Option<Box<dyn Reflect>>;
468    fn reflect_insert(
469        &mut self,
470        index: usize,
471        value: Box<dyn Reflect>,
472    ) -> Result<(), Box<dyn Reflect>>;
473}
474
475pub trait ReflectHashMap: Reflect {
476    fn reflect_insert(
477        &mut self,
478        key: Box<dyn Reflect>,
479        value: Box<dyn Reflect>,
480    ) -> Option<Box<dyn Reflect>>;
481    fn reflect_len(&self) -> usize;
482    fn reflect_get(&self, key: &dyn Reflect, func: &mut dyn FnMut(Option<&dyn Reflect>));
483    fn reflect_get_mut(
484        &mut self,
485        key: &dyn Reflect,
486        func: &mut dyn FnMut(Option<&mut dyn Reflect>),
487    );
488    fn reflect_get_nth_value_ref(&self, index: usize) -> Option<&dyn Reflect>;
489    fn reflect_get_nth_value_mut(&mut self, index: usize) -> Option<&mut dyn Reflect>;
490    fn reflect_get_at(&self, index: usize) -> Option<(&dyn Reflect, &dyn Reflect)>;
491    fn reflect_get_at_mut(&mut self, index: usize) -> Option<(&dyn Reflect, &mut dyn Reflect)>;
492    fn reflect_remove(&mut self, key: &dyn Reflect, func: &mut dyn FnMut(Option<Box<dyn Reflect>>));
493}
494
495pub trait ReflectInheritableVariable: Reflect {
496    /// Tries to inherit a value from parent. It will succeed only if the current variable is
497    /// not marked as modified.
498    fn try_inherit(
499        &mut self,
500        parent: &dyn ReflectInheritableVariable,
501        ignored_types: &[TypeId],
502    ) -> Result<Option<Box<dyn Reflect>>, InheritError>;
503
504    /// Resets modified flag from the variable.
505    fn reset_modified_flag(&mut self);
506
507    /// Returns current variable flags.
508    fn flags(&self) -> VariableFlags;
509
510    fn set_flags(&mut self, flags: VariableFlags);
511
512    /// Returns true if value was modified.
513    fn is_modified(&self) -> bool;
514
515    /// Returns true if value equals to other's value.
516    fn value_equals(&self, other: &dyn ReflectInheritableVariable) -> bool;
517
518    /// Clones self value.
519    fn clone_value_box(&self) -> Box<dyn Reflect>;
520
521    /// Marks value as modified, so its value won't be overwritten during property inheritance.
522    fn mark_modified(&mut self);
523
524    /// Returns a mutable reference to wrapped value without marking the variable itself as modified.
525    fn inner_value_mut(&mut self) -> &mut dyn Reflect;
526
527    /// Returns a shared reference to wrapped value without marking the variable itself as modified.
528    fn inner_value_ref(&self) -> &dyn Reflect;
529}
530
531/// An error returned from a failed path string query.
532#[derive(Debug, PartialEq, Eq)]
533pub enum ReflectPathError<'a> {
534    // syntax errors
535    UnclosedBrackets { s: &'a str },
536    InvalidIndexSyntax { s: &'a str },
537
538    // access errors
539    UnknownField { s: &'a str },
540    NoItemForIndex { s: &'a str },
541
542    // type cast errors
543    InvalidDowncast,
544    NotAnArray,
545}
546
547impl std::error::Error for ReflectPathError<'_> {}
548
549impl Display for ReflectPathError<'_> {
550    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
551        match self {
552            ReflectPathError::UnclosedBrackets { s } => {
553                write!(f, "unclosed brackets: `{s}`")
554            }
555            ReflectPathError::InvalidIndexSyntax { s } => {
556                write!(f, "not index syntax: `{s}`")
557            }
558            ReflectPathError::UnknownField { s } => {
559                write!(f, "given unknown field: `{s}`")
560            }
561            ReflectPathError::NoItemForIndex { s } => {
562                write!(f, "no item for index: `{s}`")
563            }
564            ReflectPathError::InvalidDowncast => {
565                write!(
566                    f,
567                    "failed to downcast to the target type after path resolution"
568                )
569            }
570            ReflectPathError::NotAnArray => {
571                write!(f, "tried to resolve index access, but the reflect type does not implement list API")
572            }
573        }
574    }
575}
576
577pub trait ResolvePath {
578    fn resolve_path<'p>(
579        &self,
580        path: &'p str,
581        func: &mut dyn FnMut(Result<&dyn Reflect, ReflectPathError<'p>>),
582    );
583
584    fn resolve_path_mut<'p>(
585        &mut self,
586        path: &'p str,
587        func: &mut dyn FnMut(Result<&mut dyn Reflect, ReflectPathError<'p>>),
588    );
589
590    fn get_resolve_path<'p, T: Reflect>(
591        &self,
592        path: &'p str,
593        func: &mut dyn FnMut(Result<&T, ReflectPathError<'p>>),
594    ) {
595        self.resolve_path(path, &mut |resolve_result| {
596            match resolve_result {
597                Ok(value) => {
598                    value.downcast_ref(&mut |result| {
599                        match result {
600                            Some(value) => {
601                                func(Ok(value));
602                            }
603                            None => {
604                                func(Err(ReflectPathError::InvalidDowncast));
605                            }
606                        };
607                    });
608                }
609                Err(err) => {
610                    func(Err(err));
611                }
612            };
613        })
614    }
615
616    fn get_resolve_path_mut<'p, T: Reflect>(
617        &mut self,
618        path: &'p str,
619        func: &mut dyn FnMut(Result<&mut T, ReflectPathError<'p>>),
620    ) {
621        self.resolve_path_mut(path, &mut |result| match result {
622            Ok(value) => value.downcast_mut(&mut |result| match result {
623                Some(value) => func(Ok(value)),
624                None => func(Err(ReflectPathError::InvalidDowncast)),
625            }),
626            Err(err) => func(Err(err)),
627        })
628    }
629}
630
631impl<T: Reflect> ResolvePath for T {
632    fn resolve_path<'p>(
633        &self,
634        path: &'p str,
635        func: &mut dyn FnMut(Result<&dyn Reflect, ReflectPathError<'p>>),
636    ) {
637        (self as &dyn Reflect).resolve_path(path, func)
638    }
639
640    fn resolve_path_mut<'p>(
641        &mut self,
642        path: &'p str,
643        func: &mut dyn FnMut(Result<&mut dyn Reflect, ReflectPathError<'p>>),
644    ) {
645        (self as &mut dyn Reflect).resolve_path_mut(path, func)
646    }
647}
648
649/// Splits property path into individual components.
650pub fn path_to_components(path: &str) -> Vec<Component> {
651    let mut components = Vec::new();
652    let mut current_path = path;
653    while let Ok((component, sub_path)) = Component::next(current_path) {
654        if let Component::Field(field) = component {
655            if field.is_empty() {
656                break;
657            }
658        }
659        current_path = sub_path;
660        components.push(component);
661    }
662    components
663}
664
665/// Helper methods over [`Reflect`] types
666pub trait GetField {
667    fn get_field<T: 'static>(&self, name: &str, func: &mut dyn FnMut(Option<&T>));
668
669    fn get_field_mut<T: 'static>(&mut self, _name: &str, func: &mut dyn FnMut(Option<&mut T>));
670}
671
672impl<R: Reflect> GetField for R {
673    fn get_field<T: 'static>(&self, name: &str, func: &mut dyn FnMut(Option<&T>)) {
674        self.field(name, &mut |field| match field {
675            None => func(None),
676            Some(reflect) => reflect.as_any(&mut |any| func(any.downcast_ref())),
677        })
678    }
679
680    fn get_field_mut<T: 'static>(&mut self, name: &str, func: &mut dyn FnMut(Option<&mut T>)) {
681        self.field_mut(name, &mut |field| match field {
682            None => func(None),
683            Some(reflect) => reflect.as_any_mut(&mut |any| func(any.downcast_mut())),
684        })
685    }
686}
687
688// --------------------------------------------------------------------------------
689// impl dyn Trait
690// --------------------------------------------------------------------------------
691
692// SAFETY: String usage is safe in immutable contexts only. Calling `ManuallyDrop::drop`
693// (running strings destructor) on the returned value will cause crash!
694unsafe fn make_fake_string_from_slice(string: &str) -> ManuallyDrop<String> {
695    ManuallyDrop::new(String::from_utf8_unchecked(Vec::from_raw_parts(
696        string.as_bytes().as_ptr() as *mut _,
697        string.len(),
698        string.len(),
699    )))
700}
701
702fn try_fetch_by_str_path_ref(
703    hash_map: &dyn ReflectHashMap,
704    path: &str,
705    func: &mut dyn FnMut(Option<&dyn Reflect>),
706) {
707    // Create fake string here first, this is needed to avoid memory allocations..
708    // SAFETY: We won't drop the fake string or mutate it.
709    let fake_string_key = unsafe { make_fake_string_from_slice(path) };
710
711    hash_map.reflect_get(&*fake_string_key, &mut |result| match result {
712        Some(value) => func(Some(value)),
713        None => hash_map.reflect_get(&ImmutableString::new(path) as &dyn Reflect, func),
714    });
715}
716
717fn try_fetch_by_str_path_mut(
718    hash_map: &mut dyn ReflectHashMap,
719    path: &str,
720    func: &mut dyn FnMut(Option<&mut dyn Reflect>),
721) {
722    // Create fake string here first, this is needed to avoid memory allocations..
723    // SAFETY: We won't drop the fake string or mutate it.
724    let fake_string_key = unsafe { make_fake_string_from_slice(path) };
725
726    let mut succeeded = true;
727
728    hash_map.reflect_get_mut(&*fake_string_key, &mut |result| match result {
729        Some(value) => func(Some(value)),
730        None => succeeded = false,
731    });
732
733    if !succeeded {
734        hash_map.reflect_get_mut(&ImmutableString::new(path) as &dyn Reflect, func)
735    }
736}
737
738/// Simple path parser / reflect path component
739pub enum Component<'p> {
740    Field(&'p str),
741    Index(&'p str),
742}
743
744impl<'p> Component<'p> {
745    fn next(mut path: &'p str) -> Result<(Self, &'p str), ReflectPathError<'p>> {
746        // Discard the first comma:
747        if path.bytes().next() == Some(b'.') {
748            path = &path[1..];
749        }
750
751        let mut bytes = path.bytes().enumerate();
752        while let Some((i, b)) = bytes.next() {
753            if b == b'.' {
754                let (l, r) = path.split_at(i);
755                return Ok((Self::Field(l), &r[1..]));
756            }
757
758            if b == b'[' {
759                if i != 0 {
760                    // delimit the field access
761                    let (l, r) = path.split_at(i);
762                    return Ok((Self::Field(l), r));
763                }
764
765                // find ']'
766                if let Some((end, _)) = bytes.find(|(_, b)| *b == b']') {
767                    let l = &path[1..end];
768                    let r = &path[end + 1..];
769                    return Ok((Self::Index(l), r));
770                } else {
771                    return Err(ReflectPathError::UnclosedBrackets { s: path });
772                }
773            }
774        }
775
776        // NOTE: the `path` can be empty
777        Ok((Self::Field(path), ""))
778    }
779
780    fn resolve(
781        &self,
782        reflect: &dyn Reflect,
783        func: &mut dyn FnMut(Result<&dyn Reflect, ReflectPathError<'p>>),
784    ) {
785        match self {
786            Self::Field(path) => reflect.field(path, &mut |field| {
787                func(field.ok_or(ReflectPathError::UnknownField { s: path }))
788            }),
789            Self::Index(path) => {
790                reflect.as_array(&mut |result| match result {
791                    Some(array) => match path.parse::<usize>() {
792                        Ok(index) => match array.reflect_index(index) {
793                            None => func(Err(ReflectPathError::NoItemForIndex { s: path })),
794                            Some(value) => func(Ok(value)),
795                        },
796                        Err(_) => func(Err(ReflectPathError::InvalidIndexSyntax { s: path })),
797                    },
798                    None => reflect.as_hash_map(&mut |result| match result {
799                        Some(hash_map) => {
800                            try_fetch_by_str_path_ref(hash_map, path, &mut |result| {
801                                func(result.ok_or(ReflectPathError::NoItemForIndex { s: path }))
802                            })
803                        }
804                        None => func(Err(ReflectPathError::NotAnArray)),
805                    }),
806                });
807            }
808        }
809    }
810
811    fn resolve_mut(
812        &self,
813        reflect: &mut dyn Reflect,
814        func: &mut dyn FnMut(Result<&mut dyn Reflect, ReflectPathError<'p>>),
815    ) {
816        match self {
817            Self::Field(path) => reflect.field_mut(path, &mut |field| {
818                func(field.ok_or(ReflectPathError::UnknownField { s: path }))
819            }),
820            Self::Index(path) => {
821                let mut succeeded = true;
822                reflect.as_array_mut(&mut |array| match array {
823                    Some(list) => match path.parse::<usize>() {
824                        Ok(index) => match list.reflect_index_mut(index) {
825                            None => func(Err(ReflectPathError::NoItemForIndex { s: path })),
826                            Some(value) => func(Ok(value)),
827                        },
828                        Err(_) => func(Err(ReflectPathError::InvalidIndexSyntax { s: path })),
829                    },
830                    None => succeeded = false,
831                });
832
833                if !succeeded {
834                    reflect.as_hash_map_mut(&mut |result| match result {
835                        Some(hash_map) => {
836                            try_fetch_by_str_path_mut(hash_map, path, &mut |result| {
837                                func(result.ok_or(ReflectPathError::NoItemForIndex { s: path }))
838                            })
839                        }
840                        None => func(Err(ReflectPathError::NotAnArray)),
841                    })
842                }
843            }
844        }
845    }
846}
847
848impl ResolvePath for dyn Reflect {
849    fn resolve_path<'p>(
850        &self,
851        path: &'p str,
852        func: &mut dyn FnMut(Result<&dyn Reflect, ReflectPathError<'p>>),
853    ) {
854        match Component::next(path) {
855            Ok((component, r)) => component.resolve(self, &mut |result| match result {
856                Ok(child) => {
857                    if r.is_empty() {
858                        func(Ok(child))
859                    } else {
860                        child.resolve_path(r, func)
861                    }
862                }
863                Err(err) => func(Err(err)),
864            }),
865            Err(err) => func(Err(err)),
866        }
867    }
868
869    fn resolve_path_mut<'p>(
870        &mut self,
871        path: &'p str,
872        func: &mut dyn FnMut(Result<&mut dyn Reflect, ReflectPathError<'p>>),
873    ) {
874        match Component::next(path) {
875            Ok((component, r)) => component.resolve_mut(self, &mut |result| match result {
876                Ok(child) => {
877                    if r.is_empty() {
878                        func(Ok(child))
879                    } else {
880                        child.resolve_path_mut(r, func)
881                    }
882                }
883                Err(err) => func(Err(err)),
884            }),
885            Err(err) => func(Err(err)),
886        }
887    }
888}
889
890#[derive(Debug)]
891pub enum SetFieldError {
892    NoSuchField {
893        name: String,
894        value: Box<dyn Reflect>,
895    },
896    InvalidValue {
897        field_type_name: &'static str,
898        value: Box<dyn Reflect>,
899    },
900}
901
902impl std::error::Error for SetFieldError {}
903
904impl Display for SetFieldError {
905    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
906        match self {
907            SetFieldError::NoSuchField { name, value } => {
908                write!(f, "No such field as {name:?} for value {value:?}")
909            }
910            SetFieldError::InvalidValue {
911                field_type_name,
912                value,
913            } => write!(
914                f,
915                "Invalid value for field type {field_type_name}: {value:?}"
916            ),
917        }
918    }
919}
920
921#[derive(Debug)]
922pub enum SetFieldByPathError<'p> {
923    InvalidPath {
924        value: Box<dyn Reflect>,
925        reason: ReflectPathError<'p>,
926    },
927    InvalidValue {
928        field_type_name: &'static str,
929        value: Box<dyn Reflect>,
930    },
931    SetFieldError(SetFieldError),
932}
933
934impl std::error::Error for SetFieldByPathError<'_> {}
935
936impl Display for SetFieldByPathError<'_> {
937    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
938        match self {
939            SetFieldByPathError::InvalidPath { value, reason } => {
940                write!(f, "Invalid path: {value:?}. Reason: {reason}")
941            }
942            SetFieldByPathError::InvalidValue {
943                field_type_name,
944                value,
945            } => {
946                write!(f, "Invalid value: {value:?}. Type: {field_type_name}")
947            }
948            SetFieldByPathError::SetFieldError(set_field_error) => Display::fmt(set_field_error, f),
949        }
950    }
951}
952
953/// Type-erased API
954impl dyn Reflect {
955    pub fn downcast<T: Reflect>(self: Box<dyn Reflect>) -> Result<Box<T>, Box<dyn Reflect>> {
956        if self.is::<T>() {
957            Ok(self.into_any().downcast().unwrap())
958        } else {
959            Err(self)
960        }
961    }
962
963    pub fn take<T: Reflect>(self: Box<dyn Reflect>) -> Result<T, Box<dyn Reflect>> {
964        self.downcast::<T>().map(|value| *value)
965    }
966
967    #[inline]
968    pub fn is<T: Reflect>(&self) -> bool {
969        self.type_id() == TypeId::of::<T>()
970    }
971
972    #[inline]
973    pub fn downcast_ref<T: Reflect>(&self, func: &mut dyn FnMut(Option<&T>)) {
974        self.as_any(&mut |any| func(any.downcast_ref::<T>()))
975    }
976
977    #[inline]
978    pub fn downcast_mut<T: Reflect>(&mut self, func: &mut dyn FnMut(Option<&mut T>)) {
979        self.as_any_mut(&mut |any| func(any.downcast_mut::<T>()))
980    }
981
982    /// Sets a field by its path in the given entity. This method always uses [`Reflect::set_field`] which means,
983    /// that it will always call custom property setters.
984    #[inline]
985    pub fn set_field_by_path<'p>(
986        &mut self,
987        path: &'p str,
988        value: Box<dyn Reflect>,
989        func: &mut dyn FnMut(Result<Box<dyn Reflect>, SetFieldByPathError<'p>>),
990    ) {
991        if let Some(separator_position) = path.rfind('.') {
992            let mut opt_value = Some(value);
993            let parent_path = &path[..separator_position];
994            let field = &path[(separator_position + 1)..];
995            self.resolve_path_mut(parent_path, &mut |result| match result {
996                Err(reason) => {
997                    func(Err(SetFieldByPathError::InvalidPath {
998                        reason,
999                        value: opt_value.take().unwrap(),
1000                    }));
1001                }
1002                Ok(property) => {
1003                    property.set_field(field, opt_value.take().unwrap(), &mut |result| match result
1004                    {
1005                        Ok(value) => func(Ok(value)),
1006                        Err(err) => func(Err(SetFieldByPathError::SetFieldError(err))),
1007                    })
1008                }
1009            });
1010        } else {
1011            self.set_field(path, value, &mut |result| match result {
1012                Ok(value) => func(Ok(value)),
1013                Err(err) => func(Err(SetFieldByPathError::SetFieldError(err))),
1014            });
1015        }
1016    }
1017
1018    pub fn enumerate_fields_recursively<F>(&self, func: &mut F, ignored_types: &[TypeId])
1019    where
1020        F: FnMut(&str, Option<&FieldRef>, &dyn Reflect),
1021    {
1022        self.enumerate_fields_recursively_internal("", None, func, ignored_types)
1023    }
1024
1025    fn enumerate_fields_recursively_internal<F>(
1026        &self,
1027        path: &str,
1028        field_info: Option<&FieldRef>,
1029        func: &mut F,
1030        ignored_types: &[TypeId],
1031    ) where
1032        F: FnMut(&str, Option<&FieldRef>, &dyn Reflect),
1033    {
1034        if ignored_types.contains(&self.type_id()) {
1035            return;
1036        }
1037
1038        func(path, field_info, self);
1039
1040        let mut done = false;
1041
1042        self.as_inheritable_variable(&mut |variable| {
1043            if let Some(variable) = variable {
1044                // Inner variable might also contain inheritable variables, so continue iterating.
1045                variable
1046                    .inner_value_ref()
1047                    .enumerate_fields_recursively_internal(path, field_info, func, ignored_types);
1048
1049                done = true;
1050            }
1051        });
1052
1053        if done {
1054            return;
1055        }
1056
1057        self.as_array(&mut |array| {
1058            if let Some(array) = array {
1059                for i in 0..array.reflect_len() {
1060                    if let Some(item) = array.reflect_index(i) {
1061                        let item_path = format!("{path}[{i}]");
1062
1063                        item.enumerate_fields_recursively_internal(
1064                            &item_path,
1065                            field_info,
1066                            func,
1067                            ignored_types,
1068                        );
1069                    }
1070                }
1071
1072                done = true;
1073            }
1074        });
1075
1076        if done {
1077            return;
1078        }
1079
1080        self.as_hash_map(&mut |hash_map| {
1081            if let Some(hash_map) = hash_map {
1082                for i in 0..hash_map.reflect_len() {
1083                    if let Some((key, value)) = hash_map.reflect_get_at(i) {
1084                        // TODO: Here we just using `Debug` impl to obtain string representation for keys. This is
1085                        // fine for most cases in the engine.
1086                        let mut key_str = format!("{key:?}");
1087
1088                        let mut is_key_string = false;
1089                        key.downcast_ref::<String>(&mut |string| is_key_string |= string.is_some());
1090                        key.downcast_ref::<ImmutableString>(&mut |string| {
1091                            is_key_string |= string.is_some()
1092                        });
1093
1094                        if is_key_string {
1095                            // Strip quotes at the beginning and the end, because Debug impl for String adds
1096                            // quotes at the beginning and the end, but we want raw value.
1097                            // TODO: This is unreliable mechanism.
1098                            key_str.remove(0);
1099                            key_str.pop();
1100                        }
1101
1102                        let item_path = format!("{path}[{key_str}]");
1103
1104                        value.enumerate_fields_recursively_internal(
1105                            &item_path,
1106                            field_info,
1107                            func,
1108                            ignored_types,
1109                        );
1110                    }
1111                }
1112
1113                done = true;
1114            }
1115        });
1116
1117        if done {
1118            return;
1119        }
1120
1121        self.fields_ref(&mut |fields| {
1122            for field in fields {
1123                let compound_path;
1124                let field_path = if path.is_empty() {
1125                    field.metadata.name
1126                } else {
1127                    compound_path = format!("{}.{}", path, field.metadata.name);
1128                    &compound_path
1129                };
1130
1131                field
1132                    .value
1133                    .field_value_as_reflect()
1134                    .enumerate_fields_recursively_internal(
1135                        field_path,
1136                        Some(field),
1137                        func,
1138                        ignored_types,
1139                    );
1140            }
1141        })
1142    }
1143
1144    pub fn apply_recursively<F>(&self, func: &mut F, ignored_types: &[TypeId])
1145    where
1146        F: FnMut(&dyn Reflect),
1147    {
1148        if ignored_types.contains(&(*self).type_id()) {
1149            return;
1150        }
1151
1152        func(self);
1153
1154        let mut done = false;
1155
1156        self.as_inheritable_variable(&mut |variable| {
1157            if let Some(variable) = variable {
1158                // Inner variable might also contain inheritable variables, so continue iterating.
1159                variable
1160                    .inner_value_ref()
1161                    .apply_recursively(func, ignored_types);
1162
1163                done = true;
1164            }
1165        });
1166
1167        if done {
1168            return;
1169        }
1170
1171        self.as_array(&mut |array| {
1172            if let Some(array) = array {
1173                for i in 0..array.reflect_len() {
1174                    if let Some(item) = array.reflect_index(i) {
1175                        item.apply_recursively(func, ignored_types);
1176                    }
1177                }
1178
1179                done = true;
1180            }
1181        });
1182
1183        if done {
1184            return;
1185        }
1186
1187        self.as_hash_map(&mut |hash_map| {
1188            if let Some(hash_map) = hash_map {
1189                for i in 0..hash_map.reflect_len() {
1190                    if let Some(item) = hash_map.reflect_get_nth_value_ref(i) {
1191                        item.apply_recursively(func, ignored_types);
1192                    }
1193                }
1194
1195                done = true;
1196            }
1197        });
1198
1199        if done {
1200            return;
1201        }
1202
1203        self.fields_ref(&mut |fields| {
1204            for field_info_ref in fields {
1205                field_info_ref
1206                    .value
1207                    .field_value_as_reflect()
1208                    .apply_recursively(func, ignored_types);
1209            }
1210        })
1211    }
1212
1213    pub fn apply_recursively_mut<F>(&mut self, func: &mut F, ignored_types: &[TypeId])
1214    where
1215        F: FnMut(&mut dyn Reflect),
1216    {
1217        if ignored_types.contains(&(*self).type_id()) {
1218            return;
1219        }
1220
1221        func(self);
1222
1223        let mut done = false;
1224
1225        self.as_inheritable_variable_mut(&mut |variable| {
1226            if let Some(variable) = variable {
1227                // Inner variable might also contain inheritable variables, so continue iterating.
1228                variable
1229                    .inner_value_mut()
1230                    .apply_recursively_mut(func, ignored_types);
1231
1232                done = true;
1233            }
1234        });
1235
1236        if done {
1237            return;
1238        }
1239
1240        self.as_array_mut(&mut |array| {
1241            if let Some(array) = array {
1242                for i in 0..array.reflect_len() {
1243                    if let Some(item) = array.reflect_index_mut(i) {
1244                        item.apply_recursively_mut(func, ignored_types);
1245                    }
1246                }
1247
1248                done = true;
1249            }
1250        });
1251
1252        if done {
1253            return;
1254        }
1255
1256        self.as_hash_map_mut(&mut |hash_map| {
1257            if let Some(hash_map) = hash_map {
1258                for i in 0..hash_map.reflect_len() {
1259                    if let Some(item) = hash_map.reflect_get_nth_value_mut(i) {
1260                        item.apply_recursively_mut(func, ignored_types);
1261                    }
1262                }
1263
1264                done = true;
1265            }
1266        });
1267
1268        if done {
1269            return;
1270        }
1271
1272        self.fields_mut(&mut |fields| {
1273            for field_info_mut in fields {
1274                (*field_info_mut.value.field_value_as_reflect_mut())
1275                    .apply_recursively_mut(func, ignored_types);
1276            }
1277        })
1278    }
1279}
1280
1281pub fn is_path_to_array_element(path: &str) -> bool {
1282    path.ends_with(']')
1283}
1284
1285// Make it a trait?
1286impl dyn ReflectList {
1287    pub fn get_reflect_index<T: Reflect>(&self, index: usize, func: &mut dyn FnMut(Option<&T>)) {
1288        if let Some(reflect) = self.reflect_index(index) {
1289            reflect.downcast_ref(func)
1290        } else {
1291            func(None)
1292        }
1293    }
1294
1295    pub fn get_reflect_index_mut<T: Reflect>(
1296        &mut self,
1297        index: usize,
1298        func: &mut dyn FnMut(Option<&mut T>),
1299    ) {
1300        if let Some(reflect) = self.reflect_index_mut(index) {
1301            reflect.downcast_mut(func)
1302        } else {
1303            func(None)
1304        }
1305    }
1306}
1307
1308#[macro_export]
1309macro_rules! blank_reflect {
1310    () => {
1311        fn source_path() -> &'static str {
1312            file!()
1313        }
1314
1315        fn derived_types() -> &'static [std::any::TypeId]
1316        where
1317            Self: Sized,
1318        {
1319            &[]
1320        }
1321
1322        fn try_clone_box(&self) -> Option<Box<dyn Reflect>> {
1323            Some(Box::new(self.clone()))
1324        }
1325
1326        fn query_derived_types(&self) -> &'static [std::any::TypeId] {
1327            Self::derived_types()
1328        }
1329
1330        fn type_name(&self) -> &'static str {
1331            std::any::type_name::<Self>()
1332        }
1333
1334        fn doc(&self) -> &'static str {
1335            ""
1336        }
1337
1338        fn assembly_name(&self) -> &'static str {
1339            env!("CARGO_PKG_NAME")
1340        }
1341
1342        fn type_assembly_name() -> &'static str {
1343            env!("CARGO_PKG_NAME")
1344        }
1345
1346        fn fields_ref(&self, func: &mut dyn FnMut(&[FieldRef])) {
1347            func(&[])
1348        }
1349
1350        #[inline]
1351        fn fields_mut(&mut self, func: &mut dyn FnMut(&mut [FieldMut])) {
1352            func(&mut [])
1353        }
1354
1355        fn into_any(self: Box<Self>) -> Box<dyn Any> {
1356            self
1357        }
1358
1359        fn as_any(&self, func: &mut dyn FnMut(&dyn Any)) {
1360            func(self)
1361        }
1362
1363        fn as_any_mut(&mut self, func: &mut dyn FnMut(&mut dyn Any)) {
1364            func(self)
1365        }
1366
1367        fn as_reflect(&self, func: &mut dyn FnMut(&dyn Reflect)) {
1368            func(self)
1369        }
1370
1371        fn as_reflect_mut(&mut self, func: &mut dyn FnMut(&mut dyn Reflect)) {
1372            func(self)
1373        }
1374
1375        fn field(&self, name: &str, func: &mut dyn FnMut(Option<&dyn Reflect>)) {
1376            func(if name == "self" { Some(self) } else { None })
1377        }
1378
1379        fn field_mut(&mut self, name: &str, func: &mut dyn FnMut(Option<&mut dyn Reflect>)) {
1380            func(if name == "self" { Some(self) } else { None })
1381        }
1382
1383        fn set(&mut self, value: Box<dyn Reflect>) -> Result<Box<dyn Reflect>, Box<dyn Reflect>> {
1384            let this = std::mem::replace(self, value.take()?);
1385            Ok(Box::new(this))
1386        }
1387    };
1388}
1389
1390#[macro_export]
1391macro_rules! delegate_reflect {
1392    () => {
1393        fn source_path() -> &'static str {
1394            file!()
1395        }
1396
1397        fn derived_types() -> &'static [std::any::TypeId] {
1398            // TODO
1399            &[]
1400        }
1401
1402        fn try_clone_box(&self) -> Option<Box<dyn Reflect>> {
1403            Some(Box::new(self.clone()))
1404        }
1405
1406        fn query_derived_types(&self) -> &'static [std::any::TypeId] {
1407            Self::derived_types()
1408        }
1409
1410        fn type_name(&self) -> &'static str {
1411            self.deref().type_name()
1412        }
1413
1414        fn doc(&self) -> &'static str {
1415            self.deref().doc()
1416        }
1417
1418        fn assembly_name(&self) -> &'static str {
1419            self.deref().assembly_name()
1420        }
1421
1422        fn type_assembly_name() -> &'static str {
1423            env!("CARGO_PKG_NAME")
1424        }
1425
1426        fn fields_ref(&self, func: &mut dyn FnMut(&[FieldRef])) {
1427            self.deref().fields_ref(func)
1428        }
1429
1430        fn fields_mut(&mut self, func: &mut dyn FnMut(&mut [FieldMut])) {
1431            self.deref_mut().fields_mut(func)
1432        }
1433
1434        fn into_any(self: Box<Self>) -> Box<dyn Any> {
1435            (*self).into_any()
1436        }
1437
1438        fn as_any(&self, func: &mut dyn FnMut(&dyn Any)) {
1439            self.deref().as_any(func)
1440        }
1441
1442        fn as_any_mut(&mut self, func: &mut dyn FnMut(&mut dyn Any)) {
1443            self.deref_mut().as_any_mut(func)
1444        }
1445
1446        fn as_reflect(&self, func: &mut dyn FnMut(&dyn Reflect)) {
1447            self.deref().as_reflect(func)
1448        }
1449
1450        fn as_reflect_mut(&mut self, func: &mut dyn FnMut(&mut dyn Reflect)) {
1451            self.deref_mut().as_reflect_mut(func)
1452        }
1453
1454        fn set(&mut self, value: Box<dyn Reflect>) -> Result<Box<dyn Reflect>, Box<dyn Reflect>> {
1455            self.deref_mut().set(value)
1456        }
1457
1458        fn field(&self, name: &str, func: &mut dyn FnMut(Option<&dyn Reflect>)) {
1459            self.deref().field(name, func)
1460        }
1461
1462        fn field_mut(&mut self, name: &str, func: &mut dyn FnMut(Option<&mut dyn Reflect>)) {
1463            self.deref_mut().field_mut(name, func)
1464        }
1465
1466        fn as_array(&self, func: &mut dyn FnMut(Option<&dyn ReflectArray>)) {
1467            self.deref().as_array(func)
1468        }
1469
1470        fn as_array_mut(&mut self, func: &mut dyn FnMut(Option<&mut dyn ReflectArray>)) {
1471            self.deref_mut().as_array_mut(func)
1472        }
1473
1474        fn as_list(&self, func: &mut dyn FnMut(Option<&dyn ReflectList>)) {
1475            self.deref().as_list(func)
1476        }
1477
1478        fn as_list_mut(&mut self, func: &mut dyn FnMut(Option<&mut dyn ReflectList>)) {
1479            self.deref_mut().as_list_mut(func)
1480        }
1481    };
1482}
1483
1484#[macro_export]
1485macro_rules! newtype_reflect {
1486    () => {
1487        fn type_name(&self) -> &'static str {
1488            self.0.type_name()
1489        }
1490
1491        fn doc(&self) -> &'static str {
1492            self.0.doc()
1493        }
1494
1495        fn fields_ref(&self, func: &mut dyn FnMut(&[FieldRef])) {
1496            self.0.fields_ref(func)
1497        }
1498
1499        fn into_any(self: Box<Self>) -> Box<dyn Any> {
1500            self
1501        }
1502
1503        fn as_any(&self, func: &mut dyn FnMut(&dyn Any)) {
1504            self.0.as_any(func)
1505        }
1506
1507        fn as_any_mut(&mut self, func: &mut dyn FnMut(&mut dyn Any)) {
1508            self.0.as_any_mut(func)
1509        }
1510
1511        fn as_reflect(&self, func: &mut dyn FnMut(&dyn Reflect)) {
1512            self.0.as_reflect(func)
1513        }
1514
1515        fn as_reflect_mut(&mut self, func: &mut dyn FnMut(&mut dyn Reflect)) {
1516            self.0.as_reflect_mut(func)
1517        }
1518
1519        fn set(&mut self, value: Box<dyn Reflect>) -> Result<Box<dyn Reflect>, Box<dyn Reflect>> {
1520            self.0.set(value)
1521        }
1522
1523        fn field(&self, name: &str, func: &mut dyn FnMut(Option<&dyn Reflect>)) {
1524            self.0.field(name, func)
1525        }
1526
1527        fn field_mut(&mut self, name: &str, func: &mut dyn FnMut(Option<&mut dyn Reflect>)) {
1528            self.0.field_mut(name, func)
1529        }
1530
1531        fn as_array(&self, func: &mut dyn FnMut(Option<&dyn ReflectArray>)) {
1532            self.0.as_array(func)
1533        }
1534
1535        fn as_array_mut(&mut self, func: &mut dyn FnMut(Option<&mut dyn ReflectArray>)) {
1536            self.0.as_array_mut(func)
1537        }
1538
1539        fn as_list(&self, func: &mut dyn FnMut(Option<&dyn ReflectList>)) {
1540            self.0.as_list(func)
1541        }
1542
1543        fn as_list_mut(&mut self, func: &mut dyn FnMut(Option<&mut dyn ReflectList>)) {
1544            self.0.as_list_mut(func)
1545        }
1546
1547        fn as_inheritable_variable(
1548            &self,
1549            func: &mut dyn FnMut(Option<&dyn ReflectInheritableVariable>),
1550        ) {
1551            self.0.as_inheritable_variable(func)
1552        }
1553
1554        fn as_inheritable_variable_mut(
1555            &mut self,
1556            func: &mut dyn FnMut(Option<&mut dyn ReflectInheritableVariable>),
1557        ) {
1558            self.0.as_inheritable_variable_mut(func)
1559        }
1560
1561        fn as_hash_map(&self, func: &mut dyn FnMut(Option<&dyn ReflectHashMap>)) {
1562            self.0.as_hash_map(func)
1563        }
1564
1565        fn as_hash_map_mut(&mut self, func: &mut dyn FnMut(Option<&mut dyn ReflectHashMap>)) {
1566            self.0.as_hash_map_mut(func)
1567        }
1568    };
1569}
1570
1571use crate::pool::ErasedHandle;
1572use crate::sstorage::ImmutableString;
1573use crate::variable::{InheritError, VariableFlags};
1574pub use blank_reflect;
1575pub use delegate_reflect;
1576
1577#[cfg(test)]
1578mod test {
1579    use super::prelude::*;
1580    use std::any::TypeId;
1581    use std::collections::HashMap;
1582
1583    #[derive(Reflect, Clone, Default, Debug)]
1584    struct Foo {
1585        bar: Bar,
1586        baz: f32,
1587        collection: Vec<Item>,
1588        hash_map: HashMap<String, Item>,
1589    }
1590
1591    #[derive(Reflect, Clone, Default, Debug)]
1592    struct Item {
1593        payload: u32,
1594    }
1595
1596    #[derive(Reflect, Clone, Default, Debug)]
1597    struct Bar {
1598        stuff: String,
1599    }
1600
1601    #[test]
1602    fn enumerate_fields_recursively() {
1603        let foo = Foo {
1604            bar: Default::default(),
1605            baz: 0.0,
1606            collection: vec![Item::default()],
1607            hash_map: [("Foobar".to_string(), Item::default())].into(),
1608        };
1609
1610        let mut names = Vec::new();
1611        (&foo as &dyn Reflect).enumerate_fields_recursively(
1612            &mut |path, _, _| {
1613                names.push(path.to_string());
1614            },
1615            &[],
1616        );
1617
1618        assert_eq!(names[0], "");
1619        assert_eq!(names[1], "bar");
1620        assert_eq!(names[2], "bar.stuff");
1621        assert_eq!(names[3], "baz");
1622        assert_eq!(names[4], "collection");
1623        assert_eq!(names[5], "collection[0]");
1624        assert_eq!(names[6], "collection[0].payload");
1625        assert_eq!(names[7], "hash_map");
1626        assert_eq!(names[8], "hash_map[Foobar]");
1627        assert_eq!(names[9], "hash_map[Foobar].payload");
1628    }
1629
1630    #[derive(Reflect, Clone, Debug)]
1631    #[reflect(derived_type = "Derived")]
1632    struct Base;
1633
1634    #[allow(dead_code)]
1635    struct Derived(Box<Base>);
1636
1637    #[test]
1638    fn test_derived() {
1639        let base = Base;
1640        assert_eq!(base.query_derived_types(), &[TypeId::of::<Derived>()])
1641    }
1642}