bevy_reflect_derive/impls/
structs.rs

1use crate::{
2    impls::{common_partial_reflect_methods, impl_full_reflect, impl_type_path, impl_typed},
3    struct_utility::FieldAccessors,
4    ReflectStruct,
5};
6use bevy_macro_utils::fq_std::{FQDefault, FQOption, FQResult};
7use quote::{quote, ToTokens};
8
9/// Implements `Struct`, `GetTypeRegistration`, and `Reflect` for the given derive data.
10pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> proc_macro2::TokenStream {
11    let fqoption = FQOption.into_token_stream();
12
13    let bevy_reflect_path = reflect_struct.meta().bevy_reflect_path();
14    let struct_path = reflect_struct.meta().type_path();
15
16    let field_names = reflect_struct
17        .active_fields()
18        .map(|field| {
19            field
20                .data
21                .ident
22                .as_ref()
23                .map(ToString::to_string)
24                .unwrap_or_else(|| field.declaration_index.to_string())
25        })
26        .collect::<Vec<String>>();
27
28    let FieldAccessors {
29        fields_ref,
30        fields_mut,
31        field_indices,
32        field_count,
33        ..
34    } = FieldAccessors::new(reflect_struct);
35
36    let where_clause_options = reflect_struct.where_clause_options();
37    let typed_impl = impl_typed(
38        reflect_struct.meta(),
39        &where_clause_options,
40        reflect_struct.to_info_tokens(false),
41    );
42
43    let type_path_impl = impl_type_path(reflect_struct.meta());
44    let full_reflect_impl = impl_full_reflect(reflect_struct.meta(), &where_clause_options);
45    let common_methods = common_partial_reflect_methods(
46        reflect_struct.meta(),
47        || Some(quote!(#bevy_reflect_path::struct_partial_eq)),
48        || None,
49    );
50    let clone_fn = reflect_struct.get_clone_impl();
51
52    #[cfg(not(feature = "functions"))]
53    let function_impls = None::<proc_macro2::TokenStream>;
54    #[cfg(feature = "functions")]
55    let function_impls =
56        crate::impls::impl_function_traits(reflect_struct.meta(), &where_clause_options);
57
58    let get_type_registration_impl = reflect_struct.get_type_registration(&where_clause_options);
59
60    let (impl_generics, ty_generics, where_clause) = reflect_struct
61        .meta()
62        .type_path()
63        .generics()
64        .split_for_impl();
65
66    let where_reflect_clause = where_clause_options.extend_where_clause(where_clause);
67
68    quote! {
69        #get_type_registration_impl
70
71        #typed_impl
72
73        #type_path_impl
74
75        #full_reflect_impl
76
77        #function_impls
78
79        impl #impl_generics #bevy_reflect_path::Struct for #struct_path #ty_generics #where_reflect_clause {
80            fn field(&self, name: &str) -> #FQOption<&dyn #bevy_reflect_path::PartialReflect> {
81                match name {
82                    #(#field_names => #fqoption::Some(#fields_ref),)*
83                    _ => #FQOption::None,
84                }
85            }
86
87            fn field_mut(&mut self, name: &str) -> #FQOption<&mut dyn #bevy_reflect_path::PartialReflect> {
88                match name {
89                    #(#field_names => #fqoption::Some(#fields_mut),)*
90                    _ => #FQOption::None,
91                }
92            }
93
94            fn field_at(&self, index: usize) -> #FQOption<&dyn #bevy_reflect_path::PartialReflect> {
95                match index {
96                    #(#field_indices => #fqoption::Some(#fields_ref),)*
97                    _ => #FQOption::None,
98                }
99            }
100
101            fn field_at_mut(&mut self, index: usize) -> #FQOption<&mut dyn #bevy_reflect_path::PartialReflect> {
102                match index {
103                    #(#field_indices => #fqoption::Some(#fields_mut),)*
104                    _ => #FQOption::None,
105                }
106            }
107
108            fn name_at(&self, index: usize) -> #FQOption<&str> {
109                match index {
110                    #(#field_indices => #fqoption::Some(#field_names),)*
111                    _ => #FQOption::None,
112                }
113            }
114
115            fn field_len(&self) -> usize {
116                #field_count
117            }
118
119            fn iter_fields(&self) -> #bevy_reflect_path::FieldIter {
120                #bevy_reflect_path::FieldIter::new(self)
121            }
122
123            fn to_dynamic_struct(&self) -> #bevy_reflect_path::DynamicStruct {
124                let mut dynamic: #bevy_reflect_path::DynamicStruct = #FQDefault::default();
125                dynamic.set_represented_type(#bevy_reflect_path::PartialReflect::get_represented_type_info(self));
126                #(dynamic.insert_boxed(#field_names, #bevy_reflect_path::PartialReflect::to_dynamic(#fields_ref));)*
127                dynamic
128            }
129        }
130
131        impl #impl_generics #bevy_reflect_path::PartialReflect for #struct_path #ty_generics #where_reflect_clause {
132            #[inline]
133            fn get_represented_type_info(&self) -> #FQOption<&'static #bevy_reflect_path::TypeInfo> {
134                #FQOption::Some(<Self as #bevy_reflect_path::Typed>::type_info())
135            }
136
137            #[inline]
138            fn try_apply(
139                &mut self,
140                value: &dyn #bevy_reflect_path::PartialReflect
141            ) -> #FQResult<(), #bevy_reflect_path::ApplyError> {
142                if let #bevy_reflect_path::ReflectRef::Struct(struct_value)
143                    = #bevy_reflect_path::PartialReflect::reflect_ref(value) {
144                    for (i, value) in ::core::iter::Iterator::enumerate(#bevy_reflect_path::Struct::iter_fields(struct_value)) {
145                        let name = #bevy_reflect_path::Struct::name_at(struct_value, i).unwrap();
146                        if let #FQOption::Some(v) = #bevy_reflect_path::Struct::field_mut(self, name) {
147                           #bevy_reflect_path::PartialReflect::try_apply(v, value)?;
148                        }
149                    }
150                } else {
151                    return #FQResult::Err(
152                        #bevy_reflect_path::ApplyError::MismatchedKinds {
153                            from_kind: #bevy_reflect_path::PartialReflect::reflect_kind(value),
154                            to_kind: #bevy_reflect_path::ReflectKind::Struct
155                        }
156                    );
157                }
158                #FQResult::Ok(())
159            }
160            #[inline]
161            fn reflect_kind(&self) -> #bevy_reflect_path::ReflectKind {
162                #bevy_reflect_path::ReflectKind::Struct
163            }
164            #[inline]
165            fn reflect_ref(&self) -> #bevy_reflect_path::ReflectRef {
166                #bevy_reflect_path::ReflectRef::Struct(self)
167            }
168            #[inline]
169            fn reflect_mut(&mut self) -> #bevy_reflect_path::ReflectMut {
170                #bevy_reflect_path::ReflectMut::Struct(self)
171            }
172            #[inline]
173            fn reflect_owned(self: #bevy_reflect_path::__macro_exports::alloc_utils::Box<Self>) -> #bevy_reflect_path::ReflectOwned {
174                #bevy_reflect_path::ReflectOwned::Struct(self)
175            }
176
177            #common_methods
178
179            #clone_fn
180        }
181    }
182}