bevy_reflect_derive/
registration.rs

1//! Contains code related specifically to Bevy's type registration.
2
3use crate::{
4    derive_data::ReflectMeta, serialization::SerializationDataDef,
5    where_clause_options::WhereClauseOptions,
6};
7use quote::quote;
8use syn::Type;
9
10/// Creates the `GetTypeRegistration` impl for the given type data.
11pub(crate) fn impl_get_type_registration<'a>(
12    meta: &ReflectMeta,
13    where_clause_options: &WhereClauseOptions,
14    serialization_data: Option<&SerializationDataDef>,
15    type_dependencies: Option<impl Iterator<Item = &'a Type>>,
16) -> proc_macro2::TokenStream {
17    let type_path = meta.type_path();
18    let bevy_reflect_path = meta.bevy_reflect_path();
19    let registration_data = meta.attrs().idents();
20
21    let type_deps_fn = type_dependencies.map(|deps| {
22        quote! {
23            #[inline(never)]
24            fn register_type_dependencies(registry: &mut #bevy_reflect_path::TypeRegistry) {
25                #(<#deps as #bevy_reflect_path::__macro_exports::RegisterForReflection>::__register(registry);)*
26            }
27        }
28    });
29
30    let (impl_generics, ty_generics, where_clause) = type_path.generics().split_for_impl();
31    let where_reflect_clause = where_clause_options.extend_where_clause(where_clause);
32
33    let from_reflect_data = if meta.from_reflect().should_auto_derive() {
34        Some(quote! {
35            registration.insert::<#bevy_reflect_path::ReflectFromReflect>(#bevy_reflect_path::FromType::<Self>::from_type());
36        })
37    } else {
38        None
39    };
40
41    let serialization_data = serialization_data.map(|data| {
42        let serialization_data = data.as_serialization_data(bevy_reflect_path);
43        quote! {
44            registration.insert::<#bevy_reflect_path::serde::SerializationData>(#serialization_data);
45        }
46    });
47
48    quote! {
49        #[allow(unused_mut)]
50        impl #impl_generics #bevy_reflect_path::GetTypeRegistration for #type_path #ty_generics #where_reflect_clause {
51            fn get_type_registration() -> #bevy_reflect_path::TypeRegistration {
52                let mut registration = #bevy_reflect_path::TypeRegistration::of::<Self>();
53                registration.insert::<#bevy_reflect_path::ReflectFromPtr>(#bevy_reflect_path::FromType::<Self>::from_type());
54                #from_reflect_data
55                #serialization_data
56                #(registration.insert::<#registration_data>(#bevy_reflect_path::FromType::<Self>::from_type());)*
57                registration
58            }
59
60            #type_deps_fn
61        }
62    }
63}