From c9ad9a548f0f3e519b2e5009f2f141137195c2e5 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Fri, 26 Aug 2022 21:10:57 +0200 Subject: [PATCH 01/87] add `TypeName` and `ReflectTypeName` --- crates/bevy_animation/src/lib.rs | 4 +- crates/bevy_asset/src/asset_server.rs | 5 +- crates/bevy_asset/src/assets.rs | 3 +- crates/bevy_asset/src/loader.rs | 5 +- crates/bevy_audio/src/audio_output.rs | 4 +- crates/bevy_audio/src/audio_source.rs | 4 +- crates/bevy_gltf/src/lib.rs | 10 +-- crates/bevy_pbr/src/material.rs | 6 +- crates/bevy_pbr/src/pbr_material.rs | 4 +- .../bevy_reflect_derive/src/derive_data.rs | 42 +++++++++- .../bevy_reflect_derive/src/impls/enums.rs | 9 ++- .../bevy_reflect_derive/src/impls/mod.rs | 2 + .../bevy_reflect_derive/src/impls/structs.rs | 11 ++- .../src/impls/tuple_structs.rs | 11 ++- .../src/impls/type_name.rs | 81 +++++++++++++++++++ .../bevy_reflect_derive/src/impls/values.rs | 11 ++- .../bevy_reflect_derive/src/lib.rs | 59 +++++++++++++- .../bevy_reflect_derive/src/type_name.rs | 20 +++++ crates/bevy_reflect/src/array.rs | 5 +- crates/bevy_reflect/src/enums/dynamic_enum.rs | 7 +- crates/bevy_reflect/src/enums/mod.rs | 2 +- crates/bevy_reflect/src/impls/smallvec.rs | 20 +++-- crates/bevy_reflect/src/impls/std.rs | 79 +++++++++++------- crates/bevy_reflect/src/lib.rs | 49 ++++++++++- crates/bevy_reflect/src/list.rs | 6 +- crates/bevy_reflect/src/map.rs | 6 +- crates/bevy_reflect/src/reflect.rs | 4 +- crates/bevy_reflect/src/struct_trait.rs | 7 +- crates/bevy_reflect/src/tuple.rs | 16 ++-- crates/bevy_reflect/src/tuple_struct.rs | 7 +- crates/bevy_reflect/src/type_info.rs | 5 +- crates/bevy_reflect/src/type_name.rs | 54 +++++++++++++ crates/bevy_reflect/src/utility.rs | 11 ++- crates/bevy_render/src/mesh/mesh/mod.rs | 4 +- crates/bevy_render/src/mesh/mesh/skinning.rs | 4 +- .../bevy_render/src/render_resource/shader.rs | 4 +- crates/bevy_render/src/texture/image.rs | 4 +- crates/bevy_scene/src/dynamic_scene.rs | 4 +- crates/bevy_scene/src/scene.rs | 4 +- .../bevy_sprite/src/mesh2d/color_material.rs | 4 +- crates/bevy_sprite/src/mesh2d/material.rs | 6 +- crates/bevy_sprite/src/texture_atlas.rs | 4 +- crates/bevy_text/src/font.rs | 4 +- crates/bevy_text/src/font_atlas_set.rs | 3 +- examples/3d/lines.rs | 2 +- examples/asset/custom_asset.rs | 2 +- examples/reflection/generic_reflection.rs | 2 +- examples/shader/array_texture.rs | 2 +- examples/shader/custom_vertex_attribute.rs | 2 +- examples/shader/post_processing.rs | 2 +- examples/shader/shader_defs.rs | 2 +- examples/shader/shader_material.rs | 2 +- examples/shader/shader_material_glsl.rs | 2 +- .../shader_material_screenspace_texture.rs | 2 +- 54 files changed, 508 insertions(+), 126 deletions(-) create mode 100644 crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs create mode 100644 crates/bevy_reflect/bevy_reflect_derive/src/type_name.rs create mode 100644 crates/bevy_reflect/src/type_name.rs diff --git a/crates/bevy_animation/src/lib.rs b/crates/bevy_animation/src/lib.rs index ee70d801ef952..c96cc55e53ace 100644 --- a/crates/bevy_animation/src/lib.rs +++ b/crates/bevy_animation/src/lib.rs @@ -17,7 +17,7 @@ use bevy_ecs::{ }; use bevy_hierarchy::Children; use bevy_math::{Quat, Vec3}; -use bevy_reflect::{Reflect, TypeUuid}; +use bevy_reflect::{Reflect, TypeName, TypeUuid}; use bevy_time::Time; use bevy_transform::{prelude::Transform, TransformSystem}; use bevy_utils::{tracing::warn, HashMap}; @@ -60,7 +60,7 @@ pub struct EntityPath { } /// A list of [`VariableCurve`], and the [`EntityPath`] to which they apply. -#[derive(Clone, TypeUuid, Debug, Default)] +#[derive(Clone, TypeUuid, Debug, Default, TypeName)] #[uuid = "d81b7179-0448-4eb0-89fe-c067222725bf"] pub struct AnimationClip { curves: HashMap>, diff --git a/crates/bevy_asset/src/asset_server.rs b/crates/bevy_asset/src/asset_server.rs index 3b1e2815c61ba..c0c8cde3470b4 100644 --- a/crates/bevy_asset/src/asset_server.rs +++ b/crates/bevy_asset/src/asset_server.rs @@ -647,10 +647,11 @@ mod test { use crate::{loader::LoadedAsset, update_asset_storage_system}; use bevy_app::App; use bevy_ecs::prelude::*; - use bevy_reflect::TypeUuid; + use bevy_reflect::{TypeName, TypeUuid}; use bevy_utils::BoxedFuture; - #[derive(Debug, TypeUuid)] + // FIXME: reflect only the type name + #[derive(Debug, TypeUuid, TypeName)] #[uuid = "a5189b72-0572-4290-a2e0-96f73a491c44"] struct PngAsset; diff --git a/crates/bevy_asset/src/assets.rs b/crates/bevy_asset/src/assets.rs index 154e20907954f..6f9a10bdd708a 100644 --- a/crates/bevy_asset/src/assets.rs +++ b/crates/bevy_asset/src/assets.rs @@ -420,12 +420,13 @@ macro_rules! load_internal_asset { #[cfg(test)] mod tests { use bevy_app::App; + use bevy_reflect::TypeName; use crate::{AddAsset, Assets}; #[test] fn asset_overwriting() { - #[derive(bevy_reflect::TypeUuid)] + #[derive(bevy_reflect::TypeUuid, TypeName)] #[uuid = "44115972-f31b-46e5-be5c-2b9aece6a52f"] struct MyAsset; let mut app = App::new(); diff --git a/crates/bevy_asset/src/loader.rs b/crates/bevy_asset/src/loader.rs index f6a5153b490d9..49fa776a943b6 100644 --- a/crates/bevy_asset/src/loader.rs +++ b/crates/bevy_asset/src/loader.rs @@ -5,6 +5,7 @@ use crate::{ use anyhow::Error; use anyhow::Result; use bevy_ecs::system::{Res, ResMut}; +use bevy_reflect::TypeName; use bevy_reflect::{TypeUuid, TypeUuidDynamic}; use bevy_utils::{BoxedFuture, HashMap}; use crossbeam_channel::{Receiver, Sender}; @@ -47,13 +48,13 @@ pub trait AssetLoader: Send + Sync + 'static { /// /// In order to load assets into your game you must either add them manually to an asset storage /// with [`Assets::add`] or load them from the filesystem with [`AssetServer::load`]. -pub trait Asset: TypeUuid + AssetDynamic {} +pub trait Asset: TypeUuid + AssetDynamic + TypeName {} /// An untyped version of the [`Asset`] trait. pub trait AssetDynamic: Downcast + TypeUuidDynamic + Send + Sync + 'static {} impl_downcast!(AssetDynamic); -impl Asset for T where T: TypeUuid + AssetDynamic + TypeUuidDynamic {} +impl Asset for T where T: TypeUuid + AssetDynamic + TypeUuidDynamic + TypeName {} impl AssetDynamic for T where T: Send + Sync + 'static + TypeUuidDynamic {} diff --git a/crates/bevy_audio/src/audio_output.rs b/crates/bevy_audio/src/audio_output.rs index e378a2c43f4c3..3d3ed482df5ea 100644 --- a/crates/bevy_audio/src/audio_output.rs +++ b/crates/bevy_audio/src/audio_output.rs @@ -1,7 +1,7 @@ use crate::{Audio, AudioSource, Decodable}; use bevy_asset::{Asset, Assets}; use bevy_ecs::system::{NonSend, Res, ResMut}; -use bevy_reflect::TypeUuid; +use bevy_reflect::{TypeName, TypeUuid}; use bevy_utils::tracing::warn; use rodio::{OutputStream, OutputStreamHandle, Sink, Source}; use std::marker::PhantomData; @@ -116,7 +116,7 @@ pub fn play_queued_audio_system( /// } /// ``` /// -#[derive(TypeUuid)] +#[derive(TypeUuid, TypeName)] #[uuid = "8BEE570C-57C2-4FC0-8CFB-983A22F7D981"] pub struct AudioSink { // This field is an Option in order to allow us to have a safe drop that will detach the sink. diff --git a/crates/bevy_audio/src/audio_source.rs b/crates/bevy_audio/src/audio_source.rs index 4fcf2a4c36a81..1edef6ee9ea63 100644 --- a/crates/bevy_audio/src/audio_source.rs +++ b/crates/bevy_audio/src/audio_source.rs @@ -1,11 +1,11 @@ use anyhow::Result; use bevy_asset::{AssetLoader, LoadContext, LoadedAsset}; -use bevy_reflect::TypeUuid; +use bevy_reflect::{TypeName, TypeUuid}; use bevy_utils::BoxedFuture; use std::{io::Cursor, sync::Arc}; /// A source of audio data -#[derive(Debug, Clone, TypeUuid)] +#[derive(Debug, Clone, TypeUuid, TypeName)] #[uuid = "7a14806a-672b-443b-8d16-4f18afefa463"] pub struct AudioSource { /// Raw data of the audio source diff --git a/crates/bevy_gltf/src/lib.rs b/crates/bevy_gltf/src/lib.rs index f86efd9732ffb..70e5e3f5c2e81 100644 --- a/crates/bevy_gltf/src/lib.rs +++ b/crates/bevy_gltf/src/lib.rs @@ -9,7 +9,7 @@ use bevy_app::prelude::*; use bevy_asset::{AddAsset, Handle}; use bevy_ecs::{prelude::Component, reflect::ReflectComponent}; use bevy_pbr::StandardMaterial; -use bevy_reflect::{Reflect, TypeUuid}; +use bevy_reflect::{Reflect, TypeName, TypeUuid}; use bevy_render::mesh::Mesh; use bevy_scene::Scene; @@ -29,7 +29,7 @@ impl Plugin for GltfPlugin { } /// Representation of a loaded glTF file. -#[derive(Debug, TypeUuid)] +#[derive(Debug, TypeUuid, TypeName)] #[uuid = "5c7d5f8a-f7b0-4e45-a09e-406c0372fea2"] pub struct Gltf { pub scenes: Vec>, @@ -49,7 +49,7 @@ pub struct Gltf { /// A glTF node with all of its child nodes, its [`GltfMesh`] and /// [`Transform`](bevy_transform::prelude::Transform). -#[derive(Debug, Clone, TypeUuid)] +#[derive(Debug, Clone, TypeUuid, TypeName)] #[uuid = "dad74750-1fd6-460f-ac51-0a7937563865"] pub struct GltfNode { pub children: Vec, @@ -58,14 +58,14 @@ pub struct GltfNode { } /// A glTF mesh, which may consist of multiple [`GltfPrimitives`](GltfPrimitive). -#[derive(Debug, Clone, TypeUuid)] +#[derive(Debug, Clone, TypeUuid, TypeName)] #[uuid = "8ceaec9a-926a-4f29-8ee3-578a69f42315"] pub struct GltfMesh { pub primitives: Vec, } /// Part of a [`GltfMesh`] that consists of a [`Mesh`] and an optional [`StandardMaterial`]. -#[derive(Debug, Clone, TypeUuid)] +#[derive(Debug, Clone, TypeUuid, TypeName)] #[uuid = "cbfca302-82fd-41cb-af77-cab6b3d50af1"] pub struct GltfPrimitive { pub mesh: Handle, diff --git a/crates/bevy_pbr/src/material.rs b/crates/bevy_pbr/src/material.rs index dddb27a887749..4ed804ab17c11 100644 --- a/crates/bevy_pbr/src/material.rs +++ b/crates/bevy_pbr/src/material.rs @@ -17,7 +17,7 @@ use bevy_ecs::{ }, world::FromWorld, }; -use bevy_reflect::TypeUuid; +use bevy_reflect::{TypeName, TypeUuid}; use bevy_render::{ extract_component::ExtractComponentPlugin, mesh::{Mesh, MeshVertexBufferLayout}, @@ -108,7 +108,9 @@ use std::marker::PhantomData; /// @group(1) @binding(2) /// var color_sampler: sampler; /// ``` -pub trait Material: AsBindGroup + Send + Sync + Clone + TypeUuid + Sized + 'static { +pub trait Material: + AsBindGroup + Send + Sync + Clone + TypeUuid + TypeName + Sized + 'static +{ /// Returns this material's vertex shader. If [`ShaderRef::Default`] is returned, the default mesh vertex shader /// will be used. fn vertex_shader() -> ShaderRef { diff --git a/crates/bevy_pbr/src/pbr_material.rs b/crates/bevy_pbr/src/pbr_material.rs index cf2076dae31d3..cc9bf1a31e99c 100644 --- a/crates/bevy_pbr/src/pbr_material.rs +++ b/crates/bevy_pbr/src/pbr_material.rs @@ -1,7 +1,7 @@ use crate::{AlphaMode, Material, MaterialPipeline, MaterialPipelineKey, PBR_SHADER_HANDLE}; use bevy_asset::Handle; use bevy_math::Vec4; -use bevy_reflect::TypeUuid; +use bevy_reflect::{TypeName, TypeUuid}; use bevy_render::{ color::Color, mesh::MeshVertexBufferLayout, render_asset::RenderAssets, render_resource::*, texture::Image, @@ -12,7 +12,7 @@ use bevy_render::{ /// . /// /// May be created directly from a [`Color`] or an [`Image`]. -#[derive(AsBindGroup, Debug, Clone, TypeUuid)] +#[derive(AsBindGroup, Debug, Clone, TypeUuid, TypeName)] #[uuid = "7494888b-c082-457b-aacf-517228cc0c22"] #[bind_group_data(StandardMaterialKey)] #[uniform(0, StandardMaterialUniform)] diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs index 422809d6db804..c107fc50b09ca 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs @@ -1,11 +1,17 @@ use crate::container_attributes::ReflectTraits; use crate::field_attributes::{parse_field_attrs, ReflectFieldAttr}; use quote::quote; +use syn::token::Comma; -use crate::{utility, REFLECT_ATTRIBUTE_NAME, REFLECT_VALUE_ATTRIBUTE_NAME}; +use crate::{ + utility, REFLECT_ATTRIBUTE_NAME, REFLECT_VALUE_ATTRIBUTE_NAME, TYPE_NAME_ATTRIBUTE_NAME, +}; use syn::punctuated::Punctuated; use syn::spanned::Spanned; -use syn::{Data, DeriveInput, Field, Fields, Generics, Ident, Meta, Path, Token, Type, Variant}; +use syn::{ + Data, DeriveInput, Field, Fields, Generics, Ident, Lit, Meta, NestedMeta, Path, Token, Type, + Variant, +}; pub(crate) enum ReflectDerive<'a> { Struct(ReflectStruct<'a>), @@ -35,6 +41,8 @@ pub(crate) struct ReflectMeta<'a> { type_name: &'a Ident, /// The generics defined on this type. generics: &'a Generics, + /// Override the default type name for `ReflectTypeName`. + reflected_type_name: Option, /// A cached instance of the path to the `bevy_reflect` crate. bevy_reflect_path: Path, } @@ -110,6 +118,8 @@ impl<'a> ReflectDerive<'a> { // Should indicate whether `#[reflect_value]` was used let mut force_reflect_value = false; + let mut reflected_type_name = None; + for attribute in input.attrs.iter().filter_map(|attr| attr.parse_meta().ok()) { let meta_list = if let Meta::List(meta_list) = attribute { meta_list @@ -123,11 +133,14 @@ impl<'a> ReflectDerive<'a> { } else if ident == REFLECT_VALUE_ATTRIBUTE_NAME { force_reflect_value = true; traits = ReflectTraits::from_nested_metas(&meta_list.nested); + } else if ident == TYPE_NAME_ATTRIBUTE_NAME { + let type_name = get_type_name_attribute(&meta_list.nested).ok_or_else(||syn::Error::new(meta_list.span(), format!("The attribute `{TYPE_NAME_ATTRIBUTE_NAME}` require a single literal string. \n\n #[{TYPE_NAME_ATTRIBUTE_NAME}(\"my_lib::foo\")]")) )?; + reflected_type_name = Some(type_name); } } } - let meta = ReflectMeta::new(&input.ident, &input.generics, traits); + let meta = ReflectMeta::new(&input.ident, &input.generics, traits, reflected_type_name); if force_reflect_value { return Ok(Self::Value(meta)); @@ -211,11 +224,17 @@ impl<'a> ReflectDerive<'a> { } impl<'a> ReflectMeta<'a> { - pub fn new(type_name: &'a Ident, generics: &'a Generics, traits: ReflectTraits) -> Self { + pub fn new( + type_name: &'a Ident, + generics: &'a Generics, + traits: ReflectTraits, + reflected_type_name: Option, + ) -> Self { Self { traits, type_name, generics, + reflected_type_name, bevy_reflect_path: utility::get_bevy_reflect_path(), } } @@ -235,6 +254,11 @@ impl<'a> ReflectMeta<'a> { self.generics } + /// Override the default type name for ReflectTypeName. + pub fn reflected_type_name(&self) -> Option<&str> { + self.reflected_type_name.as_ref().map(String::as_str) + } + /// The cached `bevy_reflect` path. pub fn bevy_reflect_path(&self) -> &Path { &self.bevy_reflect_path @@ -310,3 +334,13 @@ impl<'a> ReflectEnum<'a> { &self.variants } } + +/// Extracts the type name attribute or returns [`None`]. +fn get_type_name_attribute(nested_metas: &Punctuated) -> Option { + (nested_metas.len() == 1) + .then(|| match nested_metas.first().unwrap() { + NestedMeta::Lit(Lit::Str(s)) => Some(s.value()), + _ => None, + }) + .flatten() +} diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs index 6140f853eee69..1d4b7a922ff19 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs @@ -1,6 +1,6 @@ use crate::derive_data::{EnumVariantFields, ReflectEnum, StructField}; use crate::enum_utility::{get_variant_constructors, EnumVariantConstructors}; -use crate::impls::impl_typed; +use crate::impls::{impl_type_name, impl_typed}; use proc_macro::TokenStream; use proc_macro2::{Ident, Span}; use quote::quote; @@ -64,6 +64,11 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> TokenStream { bevy_reflect_path, ); + let type_name_impl = + impl_type_name(enum_name, reflect_enum.meta().generics(), + reflect_enum.meta().reflected_type_name(), + bevy_reflect_path); + let get_type_registration_impl = reflect_enum.meta().get_type_registration(); let (impl_generics, ty_generics, where_clause) = reflect_enum.meta().generics().split_for_impl(); @@ -73,6 +78,8 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> TokenStream { #typed_impl + #type_name_impl + impl #impl_generics #bevy_reflect_path::Enum for #enum_name #ty_generics #where_clause { fn field(&self, #ref_name: &str) -> Option<&dyn #bevy_reflect_path::Reflect> { match self { diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/mod.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/mod.rs index 19523fbf806ba..29519dabf8296 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/mod.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/mod.rs @@ -1,11 +1,13 @@ mod enums; mod structs; mod tuple_structs; +mod type_name; mod typed; mod values; pub(crate) use enums::impl_enum; pub(crate) use structs::impl_struct; pub(crate) use tuple_structs::impl_tuple_struct; +pub(crate) use type_name::impl_type_name; pub(crate) use typed::impl_typed; pub(crate) use values::impl_value; diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs index 4dca3a4feea16..7311e06aa0ff3 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs @@ -1,4 +1,4 @@ -use crate::impls::impl_typed; +use crate::impls::{impl_type_name, impl_typed}; use crate::ReflectStruct; use proc_macro::TokenStream; use quote::quote; @@ -64,6 +64,13 @@ pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> TokenStream { bevy_reflect_path, ); + let type_name_impl = impl_type_name( + struct_name, + reflect_struct.meta().generics(), + reflect_struct.meta().reflected_type_name(), + bevy_reflect_path, + ); + let get_type_registration_impl = reflect_struct.meta().get_type_registration(); let (impl_generics, ty_generics, where_clause) = reflect_struct.meta().generics().split_for_impl(); @@ -73,6 +80,8 @@ pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> TokenStream { #typed_impl + #type_name_impl + impl #impl_generics #bevy_reflect_path::Struct for #struct_name #ty_generics #where_clause { fn field(&self, name: &str) -> Option<&dyn #bevy_reflect_path::Reflect> { match name { diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs index 0ad33ba4bb8ce..ca0c38c044add 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs @@ -1,4 +1,4 @@ -use crate::impls::impl_typed; +use crate::impls::{impl_type_name, impl_typed}; use crate::ReflectStruct; use proc_macro::TokenStream; use quote::quote; @@ -48,6 +48,13 @@ pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> TokenStream { bevy_reflect_path, ); + let type_name_impl = impl_type_name( + struct_name, + reflect_struct.meta().generics(), + reflect_struct.meta().reflected_type_name(), + bevy_reflect_path, + ); + let (impl_generics, ty_generics, where_clause) = reflect_struct.meta().generics().split_for_impl(); @@ -56,6 +63,8 @@ pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> TokenStream { #typed_impl + #type_name_impl + impl #impl_generics #bevy_reflect_path::TupleStruct for #struct_name #ty_generics #where_clause { fn field(&self, index: usize) -> Option<&dyn #bevy_reflect_path::Reflect> { match index { diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs new file mode 100644 index 0000000000000..1f026d433fd77 --- /dev/null +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs @@ -0,0 +1,81 @@ +use proc_macro2::{Ident, TokenStream}; +use quote::quote; +use syn::{Generics, Path}; + +pub(crate) fn impl_type_name( + type_name: &Ident, + generics: &Generics, + reflected_type_name: Option<&str>, + bevy_reflect_path: &Path, +) -> proc_macro2::TokenStream { + let is_generic = !generics.params.is_empty(); + + let base_name = reflected_type_name + .map(|x| quote!(#x)) + .unwrap_or_else(|| quote!(concat!(module_path!(), "::", stringify!(#type_name)))); + + let get_type_name = if is_generic { + let values = { + let mut getters = generics.params.iter().map(|p| match p { + syn::GenericParam::Type(p) => { + let ty = &p.ident; + quote!(<#ty as #bevy_reflect_path::TypeName>::name()) + } + syn::GenericParam::Lifetime(p) => { + let name = &p.lifetime.ident; + quote!(concat!("'", stringify!(#name))) + } + syn::GenericParam::Const(p) => { + let name = &p.ident; + quote!(#name) + } + }); + + // FIXME: Iterator::intersperse can be used here + // currently unstable https://github.com/rust-lang/rust/issues/79524 + + let mut values = Vec::with_capacity(generics.params.len()); + for _ in 0..generics.params.len() - 1 { + // SAFETY: don't panic because we consume all but one item. + let x = getters.next().unwrap(); + values.push(quote! {#x,}); + } + // SAFETY: don't panic because the previous for loop didn't consume the last element + // and there is at least one generic parameter. + values.push(getters.next().unwrap()); + values.into_iter().collect::() + }; + + let brackets = { + // FIXME: Iterator::intersperse can be used here + // currently unstable https://github.com/rust-lang/rust/issues/79524 + + let mut brackets = Vec::with_capacity(generics.params.len()); + for _ in 0..generics.params.len() - 1 { + brackets.push("{}, "); + } + brackets.push("{}"); + brackets.into_iter().collect::() + }; + + quote! { + let name = format!(concat!("{}<", #brackets, ">"), BASE_NAME, #values); + std::borrow::Cow::Owned(name) + } + } else { + quote! { + std::borrow::Cow::Borrowed(BASE_NAME) + } + }; + + let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); + + quote! { + impl #impl_generics #bevy_reflect_path::TypeName for #type_name #ty_generics #where_clause { + fn name() -> std::borrow::Cow<'static, str> { + const BASE_NAME: &'static str = #base_name; + #get_type_name + } + } + } +} diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs index be01b2214fd11..84e848af95c53 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs @@ -1,4 +1,4 @@ -use crate::impls::impl_typed; +use crate::impls::{impl_type_name, impl_typed}; use crate::ReflectMeta; use proc_macro::TokenStream; use quote::quote; @@ -22,6 +22,13 @@ pub(crate) fn impl_value(meta: &ReflectMeta) -> TokenStream { bevy_reflect_path, ); + let type_name_impl = impl_type_name( + type_name, + meta.generics(), + meta.reflected_type_name(), + bevy_reflect_path, + ); + let (impl_generics, ty_generics, where_clause) = meta.generics().split_for_impl(); let get_type_registration_impl = meta.get_type_registration(); @@ -30,6 +37,8 @@ pub(crate) fn impl_value(meta: &ReflectMeta) -> TokenStream { #typed_impl + #type_name_impl + impl #impl_generics #bevy_reflect_path::Reflect for #type_name #ty_generics #where_clause { #[inline] fn type_name(&self) -> &str { diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index d7a7515683a11..898109ec166e2 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -23,6 +23,7 @@ mod impls; mod reflect_value; mod registration; mod trait_reflection; +mod type_name; mod type_uuid; mod utility; @@ -32,11 +33,13 @@ use quote::quote; use reflect_value::ReflectValueDef; use syn::spanned::Spanned; use syn::{parse_macro_input, DeriveInput}; +use type_name::TypeNameDef; pub(crate) static REFLECT_ATTRIBUTE_NAME: &str = "reflect"; pub(crate) static REFLECT_VALUE_ATTRIBUTE_NAME: &str = "reflect_value"; +pub(crate) static TYPE_NAME_ATTRIBUTE_NAME: &str = "type_name"; -#[proc_macro_derive(Reflect, attributes(reflect, reflect_value, module))] +#[proc_macro_derive(Reflect, attributes(reflect, reflect_value, module, type_name))] pub fn derive_reflect(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); @@ -55,6 +58,41 @@ pub fn derive_reflect(input: TokenStream) -> TokenStream { } } +#[proc_macro_derive(TypeName, attributes(module, type_name))] +pub fn derive_type_name(input: TokenStream) -> TokenStream { + let ast = parse_macro_input!(input as DeriveInput); + + let derive_data = match ReflectDerive::from_input(&ast) { + Ok(data) => data, + Err(err) => return err.into_compile_error().into(), + }; + + let s = match derive_data { + ReflectDerive::TupleStruct(struct_data) + | ReflectDerive::Struct(struct_data) + | ReflectDerive::UnitStruct(struct_data) => impls::impl_type_name( + struct_data.meta().type_name(), + struct_data.meta().generics(), + struct_data.meta().reflected_type_name(), + struct_data.meta().bevy_reflect_path(), + ), + ReflectDerive::Enum(meta) => impls::impl_type_name( + meta.meta().type_name(), + meta.meta().generics(), + meta.meta().reflected_type_name(), + meta.meta().bevy_reflect_path(), + ), + ReflectDerive::Value(meta) => impls::impl_type_name( + meta.type_name(), + meta.generics(), + meta.reflected_type_name(), + meta.bevy_reflect_path(), + ), + }; + + TokenStream::from(s) +} + /// Derives the `FromReflect` trait. /// /// This macro supports the following field attributes: @@ -99,6 +137,7 @@ pub fn impl_reflect_value(input: TokenStream) -> TokenStream { &def.type_name, &def.generics, def.traits.unwrap_or_default(), + None, // TODO )) } @@ -175,5 +214,23 @@ pub fn impl_from_reflect_value(input: TokenStream) -> TokenStream { &def.type_name, &def.generics, def.traits.unwrap_or_default(), + None, // TODO + )) +} + +#[proc_macro] +pub fn impl_type_name(input: TokenStream) -> TokenStream { + let def = parse_macro_input!(input as TypeNameDef); + let meta = ReflectMeta::new( + &def.type_name, + &def.generics, + Default::default(), + None, // TODO + ); + TokenStream::from(impls::impl_type_name( + meta.type_name(), + meta.generics(), + meta.reflected_type_name(), + meta.bevy_reflect_path(), )) } diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/type_name.rs b/crates/bevy_reflect/bevy_reflect_derive/src/type_name.rs new file mode 100644 index 0000000000000..4b66561a120a2 --- /dev/null +++ b/crates/bevy_reflect/bevy_reflect_derive/src/type_name.rs @@ -0,0 +1,20 @@ +use proc_macro2::Ident; +use syn::parse::{Parse, ParseStream}; +use syn::Generics; + +pub(crate) struct TypeNameDef { + pub type_name: Ident, + pub generics: Generics, +} + +impl Parse for TypeNameDef { + fn parse(input: ParseStream) -> syn::Result { + let type_name = input.parse::()?; + let generics = input.parse::()?; + + Ok(Self { + type_name, + generics, + }) + } +} diff --git a/crates/bevy_reflect/src/array.rs b/crates/bevy_reflect/src/array.rs index a7c1da4185b29..d91dd6f7847e5 100644 --- a/crates/bevy_reflect/src/array.rs +++ b/crates/bevy_reflect/src/array.rs @@ -1,5 +1,7 @@ +use crate::{self as bevy_reflect}; use crate::{ - utility::NonGenericTypeInfoCell, DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, Typed, + utility::NonGenericTypeInfoCell, DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, + TypeName, Typed, }; use std::{ any::{Any, TypeId}, @@ -115,6 +117,7 @@ impl ArrayInfo { /// can be mutated— just that the _number_ of items cannot change. /// /// [`DynamicList`]: crate::DynamicList +#[derive(TypeName)] pub struct DynamicArray { pub(crate) name: String, pub(crate) values: Box<[Box]>, diff --git a/crates/bevy_reflect/src/enums/dynamic_enum.rs b/crates/bevy_reflect/src/enums/dynamic_enum.rs index d0f097e977b1e..c24b0e3f24e05 100644 --- a/crates/bevy_reflect/src/enums/dynamic_enum.rs +++ b/crates/bevy_reflect/src/enums/dynamic_enum.rs @@ -1,7 +1,8 @@ use crate::utility::NonGenericTypeInfoCell; use crate::{ - enum_debug, enum_hash, enum_partial_eq, DynamicInfo, DynamicStruct, DynamicTuple, Enum, - Reflect, ReflectMut, ReflectRef, Struct, Tuple, TypeInfo, Typed, VariantFieldIter, VariantType, + self as bevy_reflect, enum_debug, enum_hash, enum_partial_eq, DynamicInfo, DynamicStruct, + DynamicTuple, Enum, Reflect, ReflectMut, ReflectRef, Struct, Tuple, TypeInfo, TypeName, Typed, + VariantFieldIter, VariantType, }; use std::any::Any; use std::fmt::Formatter; @@ -72,7 +73,7 @@ impl From<()> for DynamicVariant { /// // Tada! /// assert_eq!(None, value); /// ``` -#[derive(Default)] +#[derive(Default, TypeName)] pub struct DynamicEnum { name: String, variant_name: String, diff --git a/crates/bevy_reflect/src/enums/mod.rs b/crates/bevy_reflect/src/enums/mod.rs index 6a1f80fd38cf3..3493b799bb7e1 100644 --- a/crates/bevy_reflect/src/enums/mod.rs +++ b/crates/bevy_reflect/src/enums/mod.rs @@ -340,7 +340,7 @@ mod tests { #[test] fn enum_should_allow_generics() { #[derive(Reflect, Debug, PartialEq)] - enum TestEnum { + enum TestEnum { A, B(T), C { value: T }, diff --git a/crates/bevy_reflect/src/impls/smallvec.rs b/crates/bevy_reflect/src/impls/smallvec.rs index 918f74d40cc09..82fed4117e997 100644 --- a/crates/bevy_reflect/src/impls/smallvec.rs +++ b/crates/bevy_reflect/src/impls/smallvec.rs @@ -1,13 +1,17 @@ +use bevy_reflect_derive::impl_type_name; use smallvec::SmallVec; use std::any::Any; use crate::utility::GenericTypeInfoCell; use crate::{ - Array, ArrayIter, FromReflect, FromType, GetTypeRegistration, List, ListInfo, Reflect, - ReflectFromPtr, ReflectMut, ReflectRef, TypeInfo, TypeRegistration, Typed, + self as bevy_reflect, Array, ArrayIter, FromReflect, FromType, GetTypeRegistration, List, + ListInfo, Reflect, ReflectFromPtr, ReflectMut, ReflectRef, TypeInfo, TypeName, + TypeRegistration, Typed, }; -impl Array for SmallVec +impl_type_name!(SmallVec); + +impl Array for SmallVec where T::Item: FromReflect, { @@ -39,7 +43,7 @@ where } } -impl List for SmallVec +impl List for SmallVec where T::Item: FromReflect, { @@ -56,7 +60,7 @@ where } } -impl Reflect for SmallVec +impl Reflect for SmallVec where T::Item: FromReflect, { @@ -114,7 +118,7 @@ where } } -impl Typed for SmallVec +impl Typed for SmallVec where T::Item: FromReflect, { @@ -124,7 +128,7 @@ where } } -impl FromReflect for SmallVec +impl FromReflect for SmallVec where T::Item: FromReflect, { @@ -141,7 +145,7 @@ where } } -impl GetTypeRegistration for SmallVec +impl GetTypeRegistration for SmallVec where T::Item: FromReflect, { diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index f89c4855ccb36..8c720db89b08c 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -1,4 +1,4 @@ -use crate::{self as bevy_reflect, ReflectFromPtr}; +use crate::{self as bevy_reflect, ReflectFromPtr, TypeName}; use crate::{ map_apply, map_partial_eq, Array, ArrayInfo, ArrayIter, DynamicEnum, DynamicMap, Enum, EnumInfo, FromReflect, FromType, GetTypeRegistration, List, ListInfo, Map, MapInfo, MapIter, @@ -8,7 +8,7 @@ use crate::{ }; use crate::utility::{GenericTypeInfoCell, NonGenericTypeInfoCell}; -use bevy_reflect_derive::{impl_from_reflect_value, impl_reflect_value}; +use bevy_reflect_derive::{impl_from_reflect_value, impl_reflect_value, impl_type_name}; use bevy_utils::{Duration, HashMap, HashSet, Instant}; use std::{ any::Any, @@ -38,9 +38,9 @@ impl_reflect_value!(isize(Debug, Hash, PartialEq, Serialize, Deserialize)); impl_reflect_value!(f32(Debug, PartialEq, Serialize, Deserialize)); impl_reflect_value!(f64(Debug, PartialEq, Serialize, Deserialize)); impl_reflect_value!(String(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(Result()); -impl_reflect_value!(HashSet()); -impl_reflect_value!(Range()); +impl_reflect_value!(Result()); +impl_reflect_value!(HashSet()); +impl_reflect_value!(Range()); impl_reflect_value!(Duration(Debug, Hash, PartialEq, Serialize, Deserialize)); impl_reflect_value!(Instant(Debug, Hash, PartialEq)); impl_reflect_value!(NonZeroI128(Debug, Hash, PartialEq, Serialize, Deserialize)); @@ -73,8 +73,8 @@ impl_from_reflect_value!(isize); impl_from_reflect_value!(f32); impl_from_reflect_value!(f64); impl_from_reflect_value!(String); -impl_from_reflect_value!(HashSet); -impl_from_reflect_value!(Range); +impl_from_reflect_value!(HashSet); +impl_from_reflect_value!(Range); impl_from_reflect_value!(Duration); impl_from_reflect_value!(Instant); impl_from_reflect_value!(NonZeroI128); @@ -90,7 +90,26 @@ impl_from_reflect_value!(NonZeroU16); impl_from_reflect_value!(NonZeroU8); impl_from_reflect_value!(NonZeroI8); -impl Array for Vec { +impl_type_name!(Vec); +impl_type_name!(HashMap); +impl_type_name!(Option); + +// impl_type_name expecte a type name followed by generic between `<` and `>`. +// so array is manually implemented. +impl TypeName for [T; N] { + fn name() -> Cow<'static, str> { + let s = format!("[{}; {N}]", T::name()); + Cow::Owned(s) + } +} + +impl TypeName for Cow<'static, str> { + fn name() -> Cow<'static, str> { + Cow::Borrowed("Cow<'static, str>") + } +} + +impl Array for Vec { #[inline] fn get(&self, index: usize) -> Option<&dyn Reflect> { <[T]>::get(self, index).map(|value| value as &dyn Reflect) @@ -115,7 +134,7 @@ impl Array for Vec { } } -impl List for Vec { +impl List for Vec { fn push(&mut self, value: Box) { let value = value.take::().unwrap_or_else(|value| { T::from_reflect(&*value).unwrap_or_else(|| { @@ -129,7 +148,7 @@ impl List for Vec { } } -impl Reflect for Vec { +impl Reflect for Vec { fn type_name(&self) -> &str { std::any::type_name::() } @@ -188,14 +207,14 @@ impl Reflect for Vec { } } -impl Typed for Vec { +impl Typed for Vec { fn type_info() -> &'static TypeInfo { static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new(); CELL.get_or_insert::(|| TypeInfo::List(ListInfo::new::())) } } -impl GetTypeRegistration for Vec { +impl GetTypeRegistration for Vec { fn get_type_registration() -> TypeRegistration { let mut registration = TypeRegistration::of::>(); registration.insert::(FromType::>::from_type()); @@ -203,7 +222,7 @@ impl GetTypeRegistration for Vec { } } -impl FromReflect for Vec { +impl FromReflect for Vec { fn from_reflect(reflect: &dyn Reflect) -> Option { if let ReflectRef::List(ref_list) = reflect.reflect_ref() { let mut new_list = Self::with_capacity(ref_list.len()); @@ -217,7 +236,7 @@ impl FromReflect for Vec { } } -impl Map for HashMap { +impl Map for HashMap { fn get(&self, key: &dyn Reflect) -> Option<&dyn Reflect> { key.downcast_ref::() .and_then(|key| HashMap::get(self, key)) @@ -282,7 +301,7 @@ impl Map for HashMap { } } -impl Reflect for HashMap { +impl Reflect for HashMap { fn type_name(&self) -> &str { std::any::type_name::() } @@ -337,7 +356,7 @@ impl Reflect for HashMap { } } -impl Typed for HashMap { +impl Typed for HashMap { fn type_info() -> &'static TypeInfo { static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new(); CELL.get_or_insert::(|| TypeInfo::Map(MapInfo::new::())) @@ -346,8 +365,8 @@ impl Typed for HashMap { impl GetTypeRegistration for HashMap where - K: FromReflect + Eq + Hash, - V: FromReflect, + K: FromReflect + TypeName + Eq + Hash, + V: FromReflect + TypeName, { fn get_type_registration() -> TypeRegistration { let mut registration = TypeRegistration::of::>(); @@ -356,7 +375,9 @@ where } } -impl FromReflect for HashMap { +impl FromReflect + for HashMap +{ fn from_reflect(reflect: &dyn Reflect) -> Option { if let ReflectRef::Map(ref_map) = reflect.reflect_ref() { let mut new_map = Self::with_capacity(ref_map.len()); @@ -372,7 +393,7 @@ impl FromReflect for HashMap { } } -impl Array for [T; N] { +impl Array for [T; N] { #[inline] fn get(&self, index: usize) -> Option<&dyn Reflect> { <[T]>::get(self, index).map(|value| value as &dyn Reflect) @@ -397,7 +418,7 @@ impl Array for [T; N] { } } -impl Reflect for [T; N] { +impl Reflect for [T; N] { #[inline] fn type_name(&self) -> &str { std::any::type_name::() @@ -469,7 +490,7 @@ impl Reflect for [T; N] { } } -impl FromReflect for [T; N] { +impl FromReflect for [T; N] { fn from_reflect(reflect: &dyn Reflect) -> Option { if let ReflectRef::Array(ref_array) = reflect.reflect_ref() { let mut temp_vec = Vec::with_capacity(ref_array.len()); @@ -483,7 +504,7 @@ impl FromReflect for [T; N] { } } -impl Typed for [T; N] { +impl Typed for [T; N] { fn type_info() -> &'static TypeInfo { static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new(); CELL.get_or_insert::(|| TypeInfo::Array(ArrayInfo::new::(N))) @@ -498,7 +519,7 @@ impl Typed for [T; N] { macro_rules! impl_array_get_type_registration { ($($N:expr)+) => { $( - impl GetTypeRegistration for [T; $N] { + impl GetTypeRegistration for [T; $N] { fn get_type_registration() -> TypeRegistration { TypeRegistration::of::<[T; $N]>() } @@ -586,13 +607,13 @@ impl Reflect for Cow<'static, str> { } } -impl GetTypeRegistration for Option { +impl GetTypeRegistration for Option { fn get_type_registration() -> TypeRegistration { TypeRegistration::of::>() } } -impl Enum for Option { +impl Enum for Option { fn field(&self, _name: &str) -> Option<&dyn Reflect> { None } @@ -656,7 +677,7 @@ impl Enum for Option { } } -impl Reflect for Option { +impl Reflect for Option { #[inline] fn type_name(&self) -> &str { std::any::type_name::() @@ -762,7 +783,7 @@ impl Reflect for Option { } } -impl FromReflect for Option { +impl FromReflect for Option { fn from_reflect(reflect: &dyn Reflect) -> Option { if let ReflectRef::Enum(dyn_enum) = reflect.reflect_ref() { match dyn_enum.variant_name() { @@ -801,7 +822,7 @@ impl FromReflect for Option { } } -impl Typed for Option { +impl Typed for Option { fn type_info() -> &'static TypeInfo { static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new(); CELL.get_or_insert::(|| { diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index ef9e05ccd3cff..d9483e8684dff 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -10,6 +10,7 @@ mod struct_trait; mod tuple; mod tuple_struct; mod type_info; +mod type_name; mod type_registry; mod type_uuid; mod impls { @@ -36,7 +37,7 @@ pub mod prelude { #[doc(hidden)] pub use crate::{ reflect_trait, FromReflect, GetField, GetTupleStructField, Reflect, ReflectDeserialize, - ReflectSerialize, Struct, TupleStruct, + ReflectSerialize, ReflectTypeName, Struct, TupleStruct, TypeName, }; } @@ -52,6 +53,7 @@ pub use struct_trait::*; pub use tuple::*; pub use tuple_struct::*; pub use type_info::*; +pub use type_name::*; pub use type_registry::*; pub use type_uuid::*; @@ -628,7 +630,7 @@ mod tests { // Struct (generic) #[derive(Reflect)] - struct MyGenericStruct { + struct MyGenericStruct { foo: T, bar: usize, } @@ -915,6 +917,49 @@ bevy_reflect::tests::should_reflect_debug::Test { assert_eq!(expected, format!("\n{:#?}", reflected)); } + #[test] + fn reflect_type_name() { + use bevy_reflect::ReflectTypeName; + + #[derive(TypeName)] + struct Foo; + let foo = Foo; + let name = foo.type_name_(); + assert_eq!(name.as_ref(), "bevy_reflect::tests::Foo"); + + #[derive(TypeName)] + struct Goo { + _value: T, + } + let goo = Goo { _value: 42u32 }; + let name = goo.type_name_(); + assert_eq!( + name.as_ref(), + "bevy_reflect::tests::Goo" + ); + } + + #[test] + fn reflect_custom_type_name() { + use bevy_reflect::ReflectTypeName; + + #[derive(TypeName)] + #[type_name("Banane")] + struct Foo; + let foo = Foo; + let name = foo.type_name_(); + assert_eq!(name.as_ref(), "Banane"); + + #[derive(TypeName)] + #[type_name("MyType")] + struct Goo { + _value: T, + } + let goo = Goo { _value: 42u32 }; + let name = goo.type_name_(); + assert_eq!(name.as_ref(), "MyType"); + } + #[cfg(feature = "glam")] mod glam { use super::*; diff --git a/crates/bevy_reflect/src/list.rs b/crates/bevy_reflect/src/list.rs index 9e8c0c65f651b..9df6508ac5bfa 100644 --- a/crates/bevy_reflect/src/list.rs +++ b/crates/bevy_reflect/src/list.rs @@ -3,8 +3,8 @@ use std::fmt::{Debug, Formatter}; use crate::utility::NonGenericTypeInfoCell; use crate::{ - Array, ArrayIter, DynamicArray, DynamicInfo, FromReflect, Reflect, ReflectMut, ReflectRef, - TypeInfo, Typed, + self as bevy_reflect, Array, ArrayIter, DynamicArray, DynamicInfo, FromReflect, Reflect, + ReflectMut, ReflectRef, TypeInfo, TypeName, Typed, }; /// An ordered, mutable list of [Reflect] items. This corresponds to types like [`std::vec::Vec`]. @@ -80,7 +80,7 @@ impl ListInfo { } /// A list of reflected values. -#[derive(Default)] +#[derive(Default, TypeName)] pub struct DynamicList { name: String, values: Vec>, diff --git a/crates/bevy_reflect/src/map.rs b/crates/bevy_reflect/src/map.rs index 080b0770390b4..4586ce56afda4 100644 --- a/crates/bevy_reflect/src/map.rs +++ b/crates/bevy_reflect/src/map.rs @@ -5,7 +5,9 @@ use std::hash::Hash; use bevy_utils::{Entry, HashMap}; use crate::utility::NonGenericTypeInfoCell; -use crate::{DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, Typed}; +use crate::{ + self as bevy_reflect, DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, TypeName, Typed, +}; /// An ordered mapping between [`Reflect`] values. /// @@ -135,7 +137,7 @@ impl MapInfo { const HASH_ERROR: &str = "the given key does not support hashing"; /// An ordered mapping between reflected values. -#[derive(Default)] +#[derive(Default, TypeName)] pub struct DynamicMap { name: String, values: Vec<(Box, Box)>, diff --git a/crates/bevy_reflect/src/reflect.rs b/crates/bevy_reflect/src/reflect.rs index 3b3b7c274445a..677e0f68ac1f1 100644 --- a/crates/bevy_reflect/src/reflect.rs +++ b/crates/bevy_reflect/src/reflect.rs @@ -1,7 +1,7 @@ use crate::{ array_debug, enum_debug, list_debug, map_debug, serde::Serializable, struct_debug, tuple_debug, tuple_struct_debug, Array, Enum, List, Map, Struct, Tuple, TupleStruct, TypeInfo, Typed, - ValueInfo, + ValueInfo, ReflectTypeName, }; use std::{ any::{self, Any, TypeId}, @@ -52,7 +52,7 @@ pub enum ReflectMut<'a> { /// /// When using `#[derive(Reflect)]` with a struct or tuple struct, the suitable subtrait for that /// type (`Struct` or `TupleStruct`) is derived automatically. -pub trait Reflect: Any + Send + Sync { +pub trait Reflect: ReflectTypeName + Any + Send + Sync { /// Returns the [type name][std::any::type_name] of the underlying type. fn type_name(&self) -> &str; diff --git a/crates/bevy_reflect/src/struct_trait.rs b/crates/bevy_reflect/src/struct_trait.rs index 4f0b7819f258d..5b0dfe133e22c 100644 --- a/crates/bevy_reflect/src/struct_trait.rs +++ b/crates/bevy_reflect/src/struct_trait.rs @@ -1,5 +1,8 @@ use crate::utility::NonGenericTypeInfoCell; -use crate::{DynamicInfo, NamedField, Reflect, ReflectMut, ReflectRef, TypeInfo, Typed}; +use crate::{ + self as bevy_reflect, DynamicInfo, NamedField, Reflect, ReflectMut, ReflectRef, TypeInfo, + TypeName, Typed, +}; use bevy_utils::{Entry, HashMap}; use std::fmt::{Debug, Formatter}; use std::{ @@ -230,7 +233,7 @@ impl GetField for dyn Struct { } /// A struct type which allows fields to be added at runtime. -#[derive(Default)] +#[derive(Default, TypeName)] pub struct DynamicStruct { name: String, fields: Vec>, diff --git a/crates/bevy_reflect/src/tuple.rs b/crates/bevy_reflect/src/tuple.rs index 96386e85d6bbc..d00af60e78701 100644 --- a/crates/bevy_reflect/src/tuple.rs +++ b/crates/bevy_reflect/src/tuple.rs @@ -1,7 +1,7 @@ use crate::utility::NonGenericTypeInfoCell; use crate::{ - DynamicInfo, FromReflect, GetTypeRegistration, Reflect, ReflectMut, ReflectRef, TypeInfo, - TypeRegistration, Typed, UnnamedField, + self as bevy_reflect, DynamicInfo, FromReflect, GetTypeRegistration, Reflect, ReflectMut, + ReflectRef, TypeInfo, TypeName, TypeRegistration, Typed, UnnamedField, }; use std::any::{Any, TypeId}; use std::fmt::{Debug, Formatter}; @@ -182,7 +182,7 @@ impl TupleInfo { } /// A tuple which allows fields to be added at runtime. -#[derive(Default)] +#[derive(Default, TypeName)] pub struct DynamicTuple { name: String, fields: Vec>, @@ -420,7 +420,7 @@ pub fn tuple_debug(dyn_tuple: &dyn Tuple, f: &mut std::fmt::Formatter<'_>) -> st macro_rules! impl_reflect_tuple { {$($index:tt : $name:tt),*} => { - impl<$($name: Reflect),*> Tuple for ($($name,)*) { + impl<$($name: Reflect + TypeName),*> Tuple for ($($name,)*) { #[inline] fn field(&self, index: usize) -> Option<&dyn Reflect> { match index { @@ -465,7 +465,7 @@ macro_rules! impl_reflect_tuple { } } - impl<$($name: Reflect),*> Reflect for ($($name,)*) { + impl<$($name: Reflect + TypeName),*> Reflect for ($($name,)*) { fn type_name(&self) -> &str { std::any::type_name::() } @@ -520,7 +520,7 @@ macro_rules! impl_reflect_tuple { } } - impl <$($name: Reflect),*> Typed for ($($name,)*) { + impl <$($name: Reflect + TypeName),*> Typed for ($($name,)*) { fn type_info() -> &'static TypeInfo { static CELL: $crate::utility::GenericTypeInfoCell = $crate::utility::GenericTypeInfoCell::new(); CELL.get_or_insert::(|| { @@ -533,13 +533,13 @@ macro_rules! impl_reflect_tuple { } } - impl<$($name: Reflect + Typed),*> GetTypeRegistration for ($($name,)*) { + impl<$($name: Reflect + TypeName + Typed),*> GetTypeRegistration for ($($name,)*) { fn get_type_registration() -> TypeRegistration { TypeRegistration::of::<($($name,)*)>() } } - impl<$($name: FromReflect),*> FromReflect for ($($name,)*) + impl<$($name: FromReflect + TypeName),*> FromReflect for ($($name,)*) { fn from_reflect(reflect: &dyn Reflect) -> Option { if let ReflectRef::Tuple(_ref_tuple) = reflect.reflect_ref() { diff --git a/crates/bevy_reflect/src/tuple_struct.rs b/crates/bevy_reflect/src/tuple_struct.rs index 507b6b4bfd117..2db1b81f653f1 100644 --- a/crates/bevy_reflect/src/tuple_struct.rs +++ b/crates/bevy_reflect/src/tuple_struct.rs @@ -1,5 +1,8 @@ use crate::utility::NonGenericTypeInfoCell; -use crate::{DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, Typed, UnnamedField}; +use crate::{ + self as bevy_reflect, DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, TypeName, Typed, + UnnamedField, +}; use std::any::{Any, TypeId}; use std::fmt::{Debug, Formatter}; use std::slice::Iter; @@ -187,7 +190,7 @@ impl GetTupleStructField for dyn TupleStruct { } /// A tuple struct which allows fields to be added at runtime. -#[derive(Default)] +#[derive(Default, TypeName)] pub struct DynamicTupleStruct { name: String, fields: Vec>, diff --git a/crates/bevy_reflect/src/type_info.rs b/crates/bevy_reflect/src/type_info.rs index afbe037b7243d..57137a70fa2b7 100644 --- a/crates/bevy_reflect/src/type_info.rs +++ b/crates/bevy_reflect/src/type_info.rs @@ -23,7 +23,7 @@ use std::any::{Any, TypeId}; /// /// ``` /// # use std::any::Any; -/// # use bevy_reflect::{NamedField, Reflect, ReflectMut, ReflectRef, StructInfo, TypeInfo, ValueInfo}; +/// # use bevy_reflect::{NamedField, Reflect, ReflectMut, ReflectRef, StructInfo, TypeInfo, TypeName, ValueInfo}; /// # use bevy_reflect::utility::NonGenericTypeInfoCell; /// use bevy_reflect::Typed; /// @@ -46,6 +46,9 @@ use std::any::{Any, TypeId}; /// } /// } /// +/// # impl TypeName for MyStruct { +/// # fn name() -> std::borrow::Cow<'static, str> { todo!() } +/// # } /// # /// # impl Reflect for MyStruct { /// # fn type_name(&self) -> &str { todo!() } diff --git a/crates/bevy_reflect/src/type_name.rs b/crates/bevy_reflect/src/type_name.rs new file mode 100644 index 0000000000000..466f52f6ea7de --- /dev/null +++ b/crates/bevy_reflect/src/type_name.rs @@ -0,0 +1,54 @@ +use std::borrow::Cow; + +/// Provide the name of the type as string. +pub trait TypeName { + fn name() -> Cow<'static, str>; +} + +/// A object-safe version of [`TypeName`]. +/// Automatically implemented via blanket implementation. +pub trait ReflectTypeName { + // FIXME: named with a trailling underscore to avoid conflict + // with Reflect::type_name until it's replaced by this method. + fn type_name_(&self) -> Cow<'static, str>; +} + +impl ReflectTypeName for T { + #[inline] + fn type_name_(&self) -> Cow<'static, str> { + Self::name() + } +} + +macro_rules! impl_type_name_tuple { + ( + $($t:tt),* + ) => { + impl<$($t: TypeName),*> TypeName for ($($t,)*) { + #[allow(non_snake_case)] + fn name() -> Cow<'static, str> { + $(let $t = <$t as TypeName>::name();)* + let s = format!( + concat!($(impl_type_name_tuple!(@bracket $t),)*), + $($t,)* + ); + Cow::Owned(s) + } + } + }; + (@bracket $t:tt) => {"{}"} +} + +impl_type_name_tuple!(); +impl_type_name_tuple!(A); +impl_type_name_tuple!(A, B); +impl_type_name_tuple!(A, B, C); +impl_type_name_tuple!(A, B, C, D); +impl_type_name_tuple!(A, B, C, D, E); +impl_type_name_tuple!(A, B, C, D, E, F); +impl_type_name_tuple!(A, B, C, D, E, F, G); +impl_type_name_tuple!(A, B, C, D, E, F, G, H); +impl_type_name_tuple!(A, B, C, D, E, F, G, H, I); +impl_type_name_tuple!(A, B, C, D, E, F, G, H, I, J); +impl_type_name_tuple!(A, B, C, D, E, F, G, H, I, J, K); +impl_type_name_tuple!(A, B, C, D, E, F, G, H, I, J, K, L); diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index 3e38c6dc35932..40a41ada9de7b 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -16,7 +16,7 @@ use std::any::{Any, TypeId}; /// /// ``` /// # use std::any::Any; -/// # use bevy_reflect::{NamedField, Reflect, ReflectMut, ReflectRef, StructInfo, Typed, TypeInfo}; +/// # use bevy_reflect::{NamedField, Reflect, ReflectMut, ReflectRef, StructInfo, Typed, TypeInfo, TypeName}; /// use bevy_reflect::utility::NonGenericTypeInfoCell; /// /// struct Foo { @@ -33,6 +33,9 @@ use std::any::{Any, TypeId}; /// }) /// } /// } +/// # impl TypeName for Foo { +/// # fn name() -> std::borrow::Cow<'static, str> { todo!() } +/// # } /// # /// # impl Reflect for Foo { /// # fn type_name(&self) -> &str { todo!() } @@ -79,7 +82,7 @@ impl NonGenericTypeInfoCell { /// /// ``` /// # use std::any::Any; -/// # use bevy_reflect::{Reflect, ReflectMut, ReflectRef, TupleStructInfo, Typed, TypeInfo, UnnamedField}; +/// # use bevy_reflect::{Reflect, ReflectMut, ReflectRef, TupleStructInfo, Typed, TypeInfo, UnnamedField, TypeName}; /// use bevy_reflect::utility::GenericTypeInfoCell; /// /// struct Foo(T); @@ -94,6 +97,10 @@ impl NonGenericTypeInfoCell { /// }) /// } /// } +/// +/// # impl TypeName for Foo { +/// # fn name() -> std::borrow::Cow<'static, str> { todo!() } +/// # } /// # /// # impl Reflect for Foo { /// # fn type_name(&self) -> &str { todo!() } diff --git a/crates/bevy_render/src/mesh/mesh/mod.rs b/crates/bevy_render/src/mesh/mesh/mod.rs index 88a0ef1bc2659..674abcc015a57 100644 --- a/crates/bevy_render/src/mesh/mesh/mod.rs +++ b/crates/bevy_render/src/mesh/mesh/mod.rs @@ -12,7 +12,7 @@ use bevy_core::cast_slice; use bevy_derive::EnumVariantMeta; use bevy_ecs::system::{lifetimeless::SRes, SystemParamItem}; use bevy_math::*; -use bevy_reflect::TypeUuid; +use bevy_reflect::{TypeName, TypeUuid}; use bevy_utils::{tracing::error, Hashed}; use std::{collections::BTreeMap, hash::Hash, iter::FusedIterator}; use thiserror::Error; @@ -25,7 +25,7 @@ pub const INDEX_BUFFER_ASSET_INDEX: u64 = 0; pub const VERTEX_ATTRIBUTE_BUFFER_ID: u64 = 10; // TODO: allow values to be unloaded after been submitting to the GPU to conserve memory -#[derive(Debug, TypeUuid, Clone)] +#[derive(Debug, TypeUuid, Clone, TypeName)] #[uuid = "8ecbac0f-f545-4473-ad43-e1f4243af51e"] pub struct Mesh { primitive_topology: PrimitiveTopology, diff --git a/crates/bevy_render/src/mesh/mesh/skinning.rs b/crates/bevy_render/src/mesh/mesh/skinning.rs index 6d152689069ea..31837a51b7d77 100644 --- a/crates/bevy_render/src/mesh/mesh/skinning.rs +++ b/crates/bevy_render/src/mesh/mesh/skinning.rs @@ -6,7 +6,7 @@ use bevy_ecs::{ reflect::ReflectMapEntities, }; use bevy_math::Mat4; -use bevy_reflect::{Reflect, TypeUuid}; +use bevy_reflect::{Reflect, TypeName, TypeUuid}; use std::ops::Deref; #[derive(Component, Debug, Default, Clone, Reflect)] @@ -26,7 +26,7 @@ impl MapEntities for SkinnedMesh { } } -#[derive(Debug, TypeUuid)] +#[derive(Debug, TypeUuid, TypeName)] #[uuid = "b9f155a9-54ec-4026-988f-e0a03e99a76f"] pub struct SkinnedMeshInverseBindposes(Box<[Mat4]>); diff --git a/crates/bevy_render/src/render_resource/shader.rs b/crates/bevy_render/src/render_resource/shader.rs index 5913d44dd3aab..dd069aa7e5e28 100644 --- a/crates/bevy_render/src/render_resource/shader.rs +++ b/crates/bevy_render/src/render_resource/shader.rs @@ -1,5 +1,5 @@ use bevy_asset::{AssetLoader, AssetPath, Handle, LoadContext, LoadedAsset}; -use bevy_reflect::{TypeUuid, Uuid}; +use bevy_reflect::{TypeName, TypeUuid, Uuid}; use bevy_utils::{tracing::error, BoxedFuture, HashMap}; use naga::back::wgsl::WriterFlags; use naga::valid::Capabilities; @@ -36,7 +36,7 @@ pub enum ShaderReflectError { } /// A shader, as defined by its [`ShaderSource`] and [`ShaderStage`](naga::ShaderStage) /// This is an "unprocessed" shader. It can contain preprocessor directives. -#[derive(Debug, Clone, TypeUuid)] +#[derive(Debug, Clone, TypeUuid, TypeName)] #[uuid = "d95bc916-6c55-4de3-9622-37e7b6969fda"] pub struct Shader { source: Source, diff --git a/crates/bevy_render/src/texture/image.rs b/crates/bevy_render/src/texture/image.rs index bb7138bddf022..3c0b619a511ac 100644 --- a/crates/bevy_render/src/texture/image.rs +++ b/crates/bevy_render/src/texture/image.rs @@ -16,7 +16,7 @@ use bevy_asset::HandleUntyped; use bevy_derive::{Deref, DerefMut}; use bevy_ecs::system::{lifetimeless::SRes, Resource, SystemParamItem}; use bevy_math::Vec2; -use bevy_reflect::TypeUuid; +use bevy_reflect::{TypeName, TypeUuid}; use std::hash::Hash; use thiserror::Error; use wgpu::{ @@ -102,7 +102,7 @@ impl ImageFormat { } } -#[derive(Debug, Clone, TypeUuid)] +#[derive(Debug, Clone, TypeUuid, TypeName)] #[uuid = "6ea26da6-6cf8-4ea2-9986-1d7bf6c17d6f"] pub struct Image { pub data: Vec, diff --git a/crates/bevy_scene/src/dynamic_scene.rs b/crates/bevy_scene/src/dynamic_scene.rs index 1de7202bfab4e..2fd36bd1d09b0 100644 --- a/crates/bevy_scene/src/dynamic_scene.rs +++ b/crates/bevy_scene/src/dynamic_scene.rs @@ -6,7 +6,7 @@ use bevy_ecs::{ reflect::{ReflectComponent, ReflectMapEntities}, world::World, }; -use bevy_reflect::{Reflect, TypeRegistryArc, TypeUuid}; +use bevy_reflect::{Reflect, TypeName, TypeRegistryArc, TypeUuid}; use serde::Serialize; /// A collection of serializable dynamic entities, each with its own run-time defined set of components. @@ -16,7 +16,7 @@ use serde::Serialize; /// * adding the [`Handle`](bevy_asset::Handle) to an entity (the scene will only be /// visible if the entity already has [`Transform`](bevy_transform::components::Transform) and /// [`GlobalTransform`](bevy_transform::components::GlobalTransform) components) -#[derive(Default, TypeUuid)] +#[derive(Default, TypeUuid, TypeName)] #[uuid = "749479b1-fb8c-4ff8-a775-623aa76014f5"] pub struct DynamicScene { pub entities: Vec, diff --git a/crates/bevy_scene/src/scene.rs b/crates/bevy_scene/src/scene.rs index 4cd871fa7283a..ed2a2a527ec20 100644 --- a/crates/bevy_scene/src/scene.rs +++ b/crates/bevy_scene/src/scene.rs @@ -1,5 +1,5 @@ use bevy_ecs::world::World; -use bevy_reflect::TypeUuid; +use bevy_reflect::{TypeName, TypeUuid}; /// To spawn a scene, you can use either: /// * [`SceneSpawner::spawn`](crate::SceneSpawner::spawn) @@ -7,7 +7,7 @@ use bevy_reflect::TypeUuid; /// * adding the [`Handle`](bevy_asset::Handle) to an entity (the scene will only be /// visible if the entity already has [`Transform`](bevy_transform::components::Transform) and /// [`GlobalTransform`](bevy_transform::components::GlobalTransform) components) -#[derive(Debug, TypeUuid)] +#[derive(Debug, TypeUuid, TypeName)] #[uuid = "c156503c-edd9-4ec7-8d33-dab392df03cd"] pub struct Scene { pub world: World, diff --git a/crates/bevy_sprite/src/mesh2d/color_material.rs b/crates/bevy_sprite/src/mesh2d/color_material.rs index b0f68db9795e4..a66aab723e72f 100644 --- a/crates/bevy_sprite/src/mesh2d/color_material.rs +++ b/crates/bevy_sprite/src/mesh2d/color_material.rs @@ -1,7 +1,7 @@ use bevy_app::{App, Plugin}; use bevy_asset::{load_internal_asset, Assets, Handle, HandleUntyped}; use bevy_math::Vec4; -use bevy_reflect::TypeUuid; +use bevy_reflect::{TypeName, TypeUuid}; use bevy_render::{ color::Color, prelude::Shader, render_asset::RenderAssets, render_resource::*, texture::Image, }; @@ -38,7 +38,7 @@ impl Plugin for ColorMaterialPlugin { } /// A [2d material](Material2d) that renders [2d meshes](crate::Mesh2dHandle) with a texture tinted by a uniform color -#[derive(AsBindGroup, Debug, Clone, TypeUuid)] +#[derive(AsBindGroup, Debug, Clone, TypeUuid, TypeName)] #[uuid = "e228a544-e3ca-4e1e-bb9d-4d8bc1ad8c19"] #[uniform(0, ColorMaterialUniform)] pub struct ColorMaterial { diff --git a/crates/bevy_sprite/src/mesh2d/material.rs b/crates/bevy_sprite/src/mesh2d/material.rs index bef567f81c155..d7679f6a162c1 100644 --- a/crates/bevy_sprite/src/mesh2d/material.rs +++ b/crates/bevy_sprite/src/mesh2d/material.rs @@ -14,7 +14,7 @@ use bevy_ecs::{ world::FromWorld, }; use bevy_log::error; -use bevy_reflect::TypeUuid; +use bevy_reflect::{TypeName, TypeUuid}; use bevy_render::{ extract_component::ExtractComponentPlugin, mesh::{Mesh, MeshVertexBufferLayout}, @@ -111,7 +111,9 @@ use crate::{ /// @group(1) @binding(2) /// var color_sampler: sampler; /// ``` -pub trait Material2d: AsBindGroup + Send + Sync + Clone + TypeUuid + Sized + 'static { +pub trait Material2d: + AsBindGroup + Send + Sync + Clone + TypeUuid + TypeName + Sized + 'static +{ /// Returns this material's vertex shader. If [`ShaderRef::Default`] is returned, the default mesh vertex shader /// will be used. fn vertex_shader() -> ShaderRef { diff --git a/crates/bevy_sprite/src/texture_atlas.rs b/crates/bevy_sprite/src/texture_atlas.rs index bc3cea9400f87..d0a326648f533 100644 --- a/crates/bevy_sprite/src/texture_atlas.rs +++ b/crates/bevy_sprite/src/texture_atlas.rs @@ -2,14 +2,14 @@ use crate::{Anchor, Rect}; use bevy_asset::Handle; use bevy_ecs::component::Component; use bevy_math::Vec2; -use bevy_reflect::{Reflect, TypeUuid}; +use bevy_reflect::{Reflect, TypeName, TypeUuid}; use bevy_render::{color::Color, texture::Image}; use bevy_utils::HashMap; /// An atlas containing multiple textures (like a spritesheet or a tilemap). /// [Example usage animating sprite.](https://github.com/bevyengine/bevy/blob/latest/examples/2d/sprite_sheet.rs) /// [Example usage loading sprite sheet.](https://github.com/bevyengine/bevy/blob/latest/examples/2d/texture_atlas.rs) -#[derive(Debug, Clone, TypeUuid)] +#[derive(Debug, Clone, TypeUuid, TypeName)] #[uuid = "7233c597-ccfa-411f-bd59-9af349432ada"] pub struct TextureAtlas { /// The handle to the texture in which the sprites are stored diff --git a/crates/bevy_text/src/font.rs b/crates/bevy_text/src/font.rs index 56fe1e60fc0de..90d659f7d0ba3 100644 --- a/crates/bevy_text/src/font.rs +++ b/crates/bevy_text/src/font.rs @@ -1,11 +1,11 @@ use ab_glyph::{FontArc, FontVec, InvalidFont, OutlinedGlyph}; -use bevy_reflect::TypeUuid; +use bevy_reflect::{TypeName, TypeUuid}; use bevy_render::{ render_resource::{Extent3d, TextureDimension, TextureFormat}, texture::Image, }; -#[derive(Debug, TypeUuid)] +#[derive(Debug, TypeUuid, TypeName)] #[uuid = "97059ac6-c9ba-4da9-95b6-bed82c3ce198"] pub struct Font { pub font: FontArc, diff --git a/crates/bevy_text/src/font_atlas_set.rs b/crates/bevy_text/src/font_atlas_set.rs index 655ad7ccf3755..733484eb31782 100644 --- a/crates/bevy_text/src/font_atlas_set.rs +++ b/crates/bevy_text/src/font_atlas_set.rs @@ -2,6 +2,7 @@ use crate::{error::TextError, Font, FontAtlas}; use ab_glyph::{GlyphId, OutlinedGlyph, Point}; use bevy_asset::{Assets, Handle}; use bevy_math::Vec2; +use bevy_reflect::TypeName; use bevy_reflect::TypeUuid; use bevy_render::texture::Image; use bevy_sprite::TextureAtlas; @@ -10,7 +11,7 @@ use bevy_utils::HashMap; type FontSizeKey = FloatOrd; -#[derive(TypeUuid)] +#[derive(TypeUuid, TypeName)] #[uuid = "73ba778b-b6b5-4f45-982d-d21b6b86ace2"] pub struct FontAtlasSet { font_atlases: HashMap>, diff --git a/examples/3d/lines.rs b/examples/3d/lines.rs index 9e0da236bd001..6e75d9d2f32ee 100644 --- a/examples/3d/lines.rs +++ b/examples/3d/lines.rs @@ -62,7 +62,7 @@ fn setup( }); } -#[derive(Default, AsBindGroup, TypeUuid, Debug, Clone)] +#[derive(Default, AsBindGroup, TypeUuid, TypeName, Debug, Clone)] #[uuid = "050ce6ac-080a-4d8c-b6b5-b5bab7560d8f"] struct LineMaterial { #[uniform(0)] diff --git a/examples/asset/custom_asset.rs b/examples/asset/custom_asset.rs index 50089d5dfb5fb..19f9b91d5f536 100644 --- a/examples/asset/custom_asset.rs +++ b/examples/asset/custom_asset.rs @@ -8,7 +8,7 @@ use bevy::{ }; use serde::Deserialize; -#[derive(Debug, Deserialize, TypeUuid)] +#[derive(Debug, Deserialize, TypeUuid, TypeName)] #[uuid = "39cadc56-aa9c-4543-8640-a018b74b5052"] pub struct CustomAsset { pub value: i32, diff --git a/examples/reflection/generic_reflection.rs b/examples/reflection/generic_reflection.rs index b91a4fa0733bc..0ef588f4b0c52 100644 --- a/examples/reflection/generic_reflection.rs +++ b/examples/reflection/generic_reflection.rs @@ -13,7 +13,7 @@ fn main() { } #[derive(Reflect)] -struct MyType { +struct MyType { value: T, } diff --git a/examples/shader/array_texture.rs b/examples/shader/array_texture.rs index a5065559814c0..02d7207a7dd9d 100644 --- a/examples/shader/array_texture.rs +++ b/examples/shader/array_texture.rs @@ -89,7 +89,7 @@ fn create_array_texture( } } -#[derive(AsBindGroup, Debug, Clone, TypeUuid)] +#[derive(AsBindGroup, Debug, Clone, TypeUuid, TypeName)] #[uuid = "9c5a0ddf-1eaf-41b4-9832-ed736fd26af3"] struct ArrayTextureMaterial { #[texture(0, dimension = "2d_array")] diff --git a/examples/shader/custom_vertex_attribute.rs b/examples/shader/custom_vertex_attribute.rs index 100c60dbaa640..2db03c3b46203 100644 --- a/examples/shader/custom_vertex_attribute.rs +++ b/examples/shader/custom_vertex_attribute.rs @@ -57,7 +57,7 @@ fn setup( } // This is the struct that will be passed to your shader -#[derive(AsBindGroup, Debug, Clone, TypeUuid)] +#[derive(AsBindGroup, Debug, Clone, TypeUuid, TypeName)] #[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"] pub struct CustomMaterial { #[uniform(0)] diff --git a/examples/shader/post_processing.rs b/examples/shader/post_processing.rs index efe6d6fd7d814..b9ff8a225c8fe 100644 --- a/examples/shader/post_processing.rs +++ b/examples/shader/post_processing.rs @@ -165,7 +165,7 @@ fn main_camera_cube_rotator_system( // Region below declares of the custom material handling post processing effect /// Our custom post processing material -#[derive(AsBindGroup, TypeUuid, Clone)] +#[derive(AsBindGroup, TypeUuid, TypeName, Clone)] #[uuid = "bc2f08eb-a0fb-43f1-a908-54871ea597d5"] struct PostProcessingMaterial { /// In this example, this image will be the result of the main camera. diff --git a/examples/shader/shader_defs.rs b/examples/shader/shader_defs.rs index 6babb53243c85..40fe4d0ae34af 100644 --- a/examples/shader/shader_defs.rs +++ b/examples/shader/shader_defs.rs @@ -75,7 +75,7 @@ impl Material for CustomMaterial { } // This is the struct that will be passed to your shader -#[derive(AsBindGroup, TypeUuid, Debug, Clone)] +#[derive(AsBindGroup, TypeUuid, TypeName, Debug, Clone)] #[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"] #[bind_group_data(CustomMaterialKey)] pub struct CustomMaterial { diff --git a/examples/shader/shader_material.rs b/examples/shader/shader_material.rs index 17e02de8d53d9..7ede26b29ae7a 100644 --- a/examples/shader/shader_material.rs +++ b/examples/shader/shader_material.rs @@ -53,7 +53,7 @@ impl Material for CustomMaterial { } // This is the struct that will be passed to your shader -#[derive(AsBindGroup, TypeUuid, Debug, Clone)] +#[derive(AsBindGroup, TypeUuid, TypeName, Debug, Clone)] #[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"] pub struct CustomMaterial { #[uniform(0)] diff --git a/examples/shader/shader_material_glsl.rs b/examples/shader/shader_material_glsl.rs index 2af38adc30f74..4ab0868e9aa76 100644 --- a/examples/shader/shader_material_glsl.rs +++ b/examples/shader/shader_material_glsl.rs @@ -47,7 +47,7 @@ fn setup( } // This is the struct that will be passed to your shader -#[derive(AsBindGroup, Clone, TypeUuid)] +#[derive(AsBindGroup, Clone, TypeUuid, TypeName)] #[uuid = "4ee9c363-1124-4113-890e-199d81b00281"] pub struct CustomMaterial { #[uniform(0)] diff --git a/examples/shader/shader_material_screenspace_texture.rs b/examples/shader/shader_material_screenspace_texture.rs index 5f92fd060cda1..0d3017f5d9190 100644 --- a/examples/shader/shader_material_screenspace_texture.rs +++ b/examples/shader/shader_material_screenspace_texture.rs @@ -65,7 +65,7 @@ fn rotate_camera(mut camera: Query<&mut Transform, With>, time: Res< cam_transform.look_at(Vec3::ZERO, Vec3::Y); } -#[derive(AsBindGroup, Debug, Clone, TypeUuid)] +#[derive(AsBindGroup, Debug, Clone, TypeUuid, TypeName)] #[uuid = "b62bb455-a72c-4b56-87bb-81e0554e234f"] pub struct CustomMaterial { #[texture(0)] From bab4ae5c2340a12a453d7ddccdc6851d0a3571f6 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Fri, 26 Aug 2022 23:36:52 +0200 Subject: [PATCH 02/87] replace `Reflect::type_name` by `ReflectTypeName::type_name` --- crates/bevy_animation/src/lib.rs | 2 +- crates/bevy_asset/src/handle.rs | 2 +- crates/bevy_core/src/name.rs | 2 +- crates/bevy_core_pipeline/src/clear_color.rs | 2 +- .../src/core_2d/camera_2d.rs | 2 +- .../src/core_3d/camera_3d.rs | 2 +- crates/bevy_gltf/src/lib.rs | 2 +- .../bevy_hierarchy/src/components/children.rs | 2 +- .../bevy_hierarchy/src/components/parent.rs | 2 +- crates/bevy_pbr/src/bundle.rs | 2 +- crates/bevy_pbr/src/wireframe.rs | 2 +- .../bevy_reflect_derive/src/impls/enums.rs | 13 +++----- .../bevy_reflect_derive/src/impls/structs.rs | 5 --- .../src/impls/tuple_structs.rs | 5 --- .../bevy_reflect_derive/src/impls/values.rs | 5 --- crates/bevy_reflect/src/array.rs | 15 ++++----- crates/bevy_reflect/src/enums/dynamic_enum.rs | 27 ++++++++-------- crates/bevy_reflect/src/impls/glam.rs | 2 +- crates/bevy_reflect/src/impls/smallvec.rs | 4 --- crates/bevy_reflect/src/impls/std.rs | 32 +++---------------- crates/bevy_reflect/src/lib.rs | 8 ++--- crates/bevy_reflect/src/list.rs | 17 +++++----- crates/bevy_reflect/src/map.rs | 16 +++++----- crates/bevy_reflect/src/reflect.rs | 14 ++++---- crates/bevy_reflect/src/serde/ser.rs | 16 +++++----- crates/bevy_reflect/src/struct_trait.rs | 24 +++++++------- crates/bevy_reflect/src/tuple.rs | 23 ++++++------- crates/bevy_reflect/src/tuple_struct.rs | 24 +++++++------- crates/bevy_reflect/src/type_info.rs | 3 +- crates/bevy_reflect/src/type_name.rs | 6 ++-- crates/bevy_reflect/src/type_registry.rs | 4 +-- crates/bevy_reflect/src/utility.rs | 2 -- crates/bevy_render/src/camera/projection.rs | 2 +- crates/bevy_render/src/mesh/mesh/skinning.rs | 2 +- crates/bevy_render/src/primitives/mod.rs | 2 +- crates/bevy_render/src/view/mod.rs | 2 +- crates/bevy_render/src/view/visibility/mod.rs | 2 +- .../src/view/visibility/render_layers.rs | 2 +- crates/bevy_scene/src/dynamic_scene.rs | 2 +- crates/bevy_sprite/src/mesh2d/mesh.rs | 2 +- crates/bevy_sprite/src/rect.rs | 2 +- crates/bevy_sprite/src/sprite.rs | 2 +- crates/bevy_sprite/src/texture_atlas.rs | 2 +- crates/bevy_text/src/text2d.rs | 2 +- crates/bevy_time/src/time.rs | 2 +- .../src/components/global_transform.rs | 2 +- crates/bevy_ui/src/geometry.rs | 2 +- crates/bevy_ui/src/widget/button.rs | 2 +- 48 files changed, 134 insertions(+), 185 deletions(-) diff --git a/crates/bevy_animation/src/lib.rs b/crates/bevy_animation/src/lib.rs index c96cc55e53ace..bed3ac717c442 100644 --- a/crates/bevy_animation/src/lib.rs +++ b/crates/bevy_animation/src/lib.rs @@ -17,7 +17,7 @@ use bevy_ecs::{ }; use bevy_hierarchy::Children; use bevy_math::{Quat, Vec3}; -use bevy_reflect::{Reflect, TypeName, TypeUuid}; +use bevy_reflect::{Reflect, ReflectTypeName, TypeName, TypeUuid}; use bevy_time::Time; use bevy_transform::{prelude::Transform, TransformSystem}; use bevy_utils::{tracing::warn, HashMap}; diff --git a/crates/bevy_asset/src/handle.rs b/crates/bevy_asset/src/handle.rs index abd6e13a98b79..e0329281b58cf 100644 --- a/crates/bevy_asset/src/handle.rs +++ b/crates/bevy_asset/src/handle.rs @@ -10,7 +10,7 @@ use crate::{ Asset, Assets, }; use bevy_ecs::{component::Component, reflect::ReflectComponent}; -use bevy_reflect::{FromReflect, Reflect, ReflectDeserialize, ReflectSerialize}; +use bevy_reflect::{FromReflect, Reflect, ReflectDeserialize, ReflectSerialize, ReflectTypeName}; use bevy_utils::Uuid; use crossbeam_channel::{Receiver, Sender}; use serde::{Deserialize, Serialize}; diff --git a/crates/bevy_core/src/name.rs b/crates/bevy_core/src/name.rs index fe320300fd03d..56c65aadbd2ac 100644 --- a/crates/bevy_core/src/name.rs +++ b/crates/bevy_core/src/name.rs @@ -1,6 +1,6 @@ use bevy_ecs::{component::Component, reflect::ReflectComponent}; use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{Reflect, ReflectTypeName}; use bevy_utils::AHasher; use std::{ borrow::Cow, diff --git a/crates/bevy_core_pipeline/src/clear_color.rs b/crates/bevy_core_pipeline/src/clear_color.rs index 50861e1bebb1f..ec99fdc01cca3 100644 --- a/crates/bevy_core_pipeline/src/clear_color.rs +++ b/crates/bevy_core_pipeline/src/clear_color.rs @@ -1,6 +1,6 @@ use bevy_derive::{Deref, DerefMut}; use bevy_ecs::prelude::*; -use bevy_reflect::{Reflect, ReflectDeserialize, ReflectSerialize}; +use bevy_reflect::{Reflect, ReflectDeserialize, ReflectSerialize, ReflectTypeName}; use bevy_render::{color::Color, extract_resource::ExtractResource}; use serde::{Deserialize, Serialize}; diff --git a/crates/bevy_core_pipeline/src/core_2d/camera_2d.rs b/crates/bevy_core_pipeline/src/core_2d/camera_2d.rs index b94b59a0b6525..2fedae20e9c63 100644 --- a/crates/bevy_core_pipeline/src/core_2d/camera_2d.rs +++ b/crates/bevy_core_pipeline/src/core_2d/camera_2d.rs @@ -1,6 +1,6 @@ use crate::clear_color::ClearColorConfig; use bevy_ecs::{prelude::*, query::QueryItem}; -use bevy_reflect::Reflect; +use bevy_reflect::{Reflect, ReflectTypeName}; use bevy_render::{ camera::{Camera, CameraProjection, CameraRenderGraph, OrthographicProjection}, extract_component::ExtractComponent, diff --git a/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs b/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs index ce91c2d2e04a8..17291bd1a0d17 100644 --- a/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs +++ b/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs @@ -1,6 +1,6 @@ use crate::clear_color::ClearColorConfig; use bevy_ecs::{prelude::*, query::QueryItem}; -use bevy_reflect::{Reflect, ReflectDeserialize, ReflectSerialize}; +use bevy_reflect::{Reflect, ReflectDeserialize, ReflectSerialize, ReflectTypeName}; use bevy_render::{ camera::{Camera, CameraRenderGraph, Projection}, extract_component::ExtractComponent, diff --git a/crates/bevy_gltf/src/lib.rs b/crates/bevy_gltf/src/lib.rs index 70e5e3f5c2e81..fc0d9f63c7e52 100644 --- a/crates/bevy_gltf/src/lib.rs +++ b/crates/bevy_gltf/src/lib.rs @@ -9,7 +9,7 @@ use bevy_app::prelude::*; use bevy_asset::{AddAsset, Handle}; use bevy_ecs::{prelude::Component, reflect::ReflectComponent}; use bevy_pbr::StandardMaterial; -use bevy_reflect::{Reflect, TypeName, TypeUuid}; +use bevy_reflect::{Reflect, ReflectTypeName, TypeName, TypeUuid}; use bevy_render::mesh::Mesh; use bevy_scene::Scene; diff --git a/crates/bevy_hierarchy/src/components/children.rs b/crates/bevy_hierarchy/src/components/children.rs index e9e3b72654709..8d0bdebd9f387 100644 --- a/crates/bevy_hierarchy/src/components/children.rs +++ b/crates/bevy_hierarchy/src/components/children.rs @@ -5,7 +5,7 @@ use bevy_ecs::{ reflect::{ReflectComponent, ReflectMapEntities}, world::World, }; -use bevy_reflect::Reflect; +use bevy_reflect::{Reflect, ReflectTypeName}; use core::slice; use smallvec::SmallVec; use std::ops::Deref; diff --git a/crates/bevy_hierarchy/src/components/parent.rs b/crates/bevy_hierarchy/src/components/parent.rs index d4a5e2f3bec70..0c3a2f8ac976d 100644 --- a/crates/bevy_hierarchy/src/components/parent.rs +++ b/crates/bevy_hierarchy/src/components/parent.rs @@ -4,7 +4,7 @@ use bevy_ecs::{ reflect::{ReflectComponent, ReflectMapEntities}, world::{FromWorld, World}, }; -use bevy_reflect::Reflect; +use bevy_reflect::{Reflect, ReflectTypeName}; use std::ops::Deref; /// Holds a reference to the parent entity of this entity. diff --git a/crates/bevy_pbr/src/bundle.rs b/crates/bevy_pbr/src/bundle.rs index 0bd720d11ea06..b578d397742d4 100644 --- a/crates/bevy_pbr/src/bundle.rs +++ b/crates/bevy_pbr/src/bundle.rs @@ -1,7 +1,7 @@ use crate::{DirectionalLight, Material, PointLight, SpotLight, StandardMaterial}; use bevy_asset::Handle; use bevy_ecs::{bundle::Bundle, component::Component, reflect::ReflectComponent}; -use bevy_reflect::Reflect; +use bevy_reflect::{Reflect, ReflectTypeName}; use bevy_render::{ mesh::Mesh, primitives::{CubemapFrusta, Frustum}, diff --git a/crates/bevy_pbr/src/wireframe.rs b/crates/bevy_pbr/src/wireframe.rs index 6d08adb3025ad..ef0aed58b53b6 100644 --- a/crates/bevy_pbr/src/wireframe.rs +++ b/crates/bevy_pbr/src/wireframe.rs @@ -5,7 +5,7 @@ use bevy_asset::{load_internal_asset, Handle, HandleUntyped}; use bevy_core_pipeline::core_3d::Opaque3d; use bevy_ecs::{prelude::*, reflect::ReflectComponent}; use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::{Reflect, TypeUuid}; +use bevy_reflect::{Reflect, ReflectTypeName, TypeUuid}; use bevy_render::Extract; use bevy_render::{ extract_resource::{ExtractResource, ExtractResourcePlugin}, diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs index 1d4b7a922ff19..a00de24e9432f 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs @@ -64,10 +64,12 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> TokenStream { bevy_reflect_path, ); - let type_name_impl = - impl_type_name(enum_name, reflect_enum.meta().generics(), + let type_name_impl = impl_type_name( + enum_name, + reflect_enum.meta().generics(), reflect_enum.meta().reflected_type_name(), - bevy_reflect_path); + bevy_reflect_path, + ); let get_type_registration_impl = reflect_enum.meta().get_type_registration(); let (impl_generics, ty_generics, where_clause) = @@ -157,11 +159,6 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> TokenStream { } impl #impl_generics #bevy_reflect_path::Reflect for #enum_name #ty_generics #where_clause { - #[inline] - fn type_name(&self) -> &str { - std::any::type_name::() - } - #[inline] fn get_type_info(&self) -> &'static #bevy_reflect_path::TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs index 7311e06aa0ff3..3799719e4fe04 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs @@ -135,11 +135,6 @@ pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> TokenStream { } impl #impl_generics #bevy_reflect_path::Reflect for #struct_name #ty_generics #where_clause { - #[inline] - fn type_name(&self) -> &str { - std::any::type_name::() - } - #[inline] fn get_type_info(&self) -> &'static #bevy_reflect_path::TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs index ca0c38c044add..3ec009efa81d9 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs @@ -97,11 +97,6 @@ pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> TokenStream { } impl #impl_generics #bevy_reflect_path::Reflect for #struct_name #ty_generics #where_clause { - #[inline] - fn type_name(&self) -> &str { - std::any::type_name::() - } - #[inline] fn get_type_info(&self) -> &'static #bevy_reflect_path::TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs index 84e848af95c53..14dc09bd60b39 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs @@ -40,11 +40,6 @@ pub(crate) fn impl_value(meta: &ReflectMeta) -> TokenStream { #type_name_impl impl #impl_generics #bevy_reflect_path::Reflect for #type_name #ty_generics #where_clause { - #[inline] - fn type_name(&self) -> &str { - std::any::type_name::() - } - #[inline] fn get_type_info(&self) -> &'static #bevy_reflect_path::TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/src/array.rs b/crates/bevy_reflect/src/array.rs index d91dd6f7847e5..50753a1088763 100644 --- a/crates/bevy_reflect/src/array.rs +++ b/crates/bevy_reflect/src/array.rs @@ -1,7 +1,6 @@ -use crate::{self as bevy_reflect}; use crate::{ - utility::NonGenericTypeInfoCell, DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, - TypeName, Typed, + utility::NonGenericTypeInfoCell, DynamicInfo, Reflect, ReflectMut, ReflectRef, ReflectTypeName, + TypeInfo, Typed, }; use std::{ any::{Any, TypeId}, @@ -117,7 +116,6 @@ impl ArrayInfo { /// can be mutated— just that the _number_ of items cannot change. /// /// [`DynamicList`]: crate::DynamicList -#[derive(TypeName)] pub struct DynamicArray { pub(crate) name: String, pub(crate) values: Box<[Box]>, @@ -154,12 +152,13 @@ impl DynamicArray { } } -impl Reflect for DynamicArray { - #[inline] - fn type_name(&self) -> &str { - self.name.as_str() +impl ReflectTypeName for DynamicArray { + fn type_name(&self) -> std::borrow::Cow { + self.name.as_str().into() } +} +impl Reflect for DynamicArray { #[inline] fn get_type_info(&self) -> &'static TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/src/enums/dynamic_enum.rs b/crates/bevy_reflect/src/enums/dynamic_enum.rs index c24b0e3f24e05..583f852fa33f6 100644 --- a/crates/bevy_reflect/src/enums/dynamic_enum.rs +++ b/crates/bevy_reflect/src/enums/dynamic_enum.rs @@ -1,7 +1,7 @@ use crate::utility::NonGenericTypeInfoCell; use crate::{ - self as bevy_reflect, enum_debug, enum_hash, enum_partial_eq, DynamicInfo, DynamicStruct, - DynamicTuple, Enum, Reflect, ReflectMut, ReflectRef, Struct, Tuple, TypeInfo, TypeName, Typed, + enum_debug, enum_hash, enum_partial_eq, DynamicInfo, DynamicStruct, DynamicTuple, Enum, + Reflect, ReflectMut, ReflectRef, ReflectTypeName, Struct, Tuple, TypeInfo, Typed, VariantFieldIter, VariantType, }; use std::any::Any; @@ -55,14 +55,14 @@ impl From<()> for DynamicVariant { /// # Example /// /// ``` -/// # use bevy_reflect::{DynamicEnum, DynamicVariant, Reflect}; +/// # use bevy_reflect::{DynamicEnum, DynamicVariant, Reflect, ReflectTypeName}; /// /// // The original enum value /// let mut value: Option = Some(123); /// /// // Create a DynamicEnum to represent the new value /// let mut dyn_enum = DynamicEnum::new( -/// Reflect::type_name(&value), +/// ReflectTypeName::type_name(&value).as_ref(), /// "None", /// DynamicVariant::Unit /// ); @@ -73,7 +73,7 @@ impl From<()> for DynamicVariant { /// // Tada! /// assert_eq!(None, value); /// ``` -#[derive(Default, TypeName)] +#[derive(Default)] pub struct DynamicEnum { name: String, variant_name: String, @@ -130,7 +130,7 @@ impl DynamicEnum { pub fn from_ref(value: &TEnum) -> Self { match value.variant_type() { VariantType::Unit => DynamicEnum::new( - value.type_name(), + value.type_name().as_ref(), value.variant_name(), DynamicVariant::Unit, ), @@ -140,7 +140,7 @@ impl DynamicEnum { data.insert_boxed(field.value().clone_value()); } DynamicEnum::new( - value.type_name(), + value.type_name().as_ref(), value.variant_name(), DynamicVariant::Tuple(data), ) @@ -152,7 +152,7 @@ impl DynamicEnum { data.insert_boxed(name, field.value().clone_value()); } DynamicEnum::new( - value.type_name(), + value.type_name().as_ref(), value.variant_name(), DynamicVariant::Struct(data), ) @@ -161,6 +161,12 @@ impl DynamicEnum { } } +impl ReflectTypeName for DynamicEnum { + fn type_name(&self) -> std::borrow::Cow { + self.name.as_str().into() + } +} + impl Enum for DynamicEnum { fn field(&self, name: &str) -> Option<&dyn Reflect> { if let DynamicVariant::Struct(data) = &self.variant { @@ -244,11 +250,6 @@ impl Enum for DynamicEnum { } impl Reflect for DynamicEnum { - #[inline] - fn type_name(&self) -> &str { - &self.name - } - #[inline] fn get_type_info(&self) -> &'static TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/src/impls/glam.rs b/crates/bevy_reflect/src/impls/glam.rs index c84fcbffaaf27..c6a8fd3140ee6 100644 --- a/crates/bevy_reflect/src/impls/glam.rs +++ b/crates/bevy_reflect/src/impls/glam.rs @@ -1,7 +1,7 @@ use crate as bevy_reflect; use crate::prelude::ReflectDefault; use crate::reflect::Reflect; -use crate::{ReflectDeserialize, ReflectSerialize}; +use crate::{ReflectDeserialize, ReflectSerialize, ReflectTypeName}; use bevy_reflect_derive::{impl_from_reflect_value, impl_reflect_struct, impl_reflect_value}; use glam::*; diff --git a/crates/bevy_reflect/src/impls/smallvec.rs b/crates/bevy_reflect/src/impls/smallvec.rs index 82fed4117e997..dd04c2c2b9aec 100644 --- a/crates/bevy_reflect/src/impls/smallvec.rs +++ b/crates/bevy_reflect/src/impls/smallvec.rs @@ -64,10 +64,6 @@ impl Reflect for SmallVec where T::Item: FromReflect, { - fn type_name(&self) -> &str { - std::any::type_name::() - } - fn get_type_info(&self) -> &'static TypeInfo { ::type_info() } diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index 8c720db89b08c..72d5aacd62120 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -2,9 +2,9 @@ use crate::{self as bevy_reflect, ReflectFromPtr, TypeName}; use crate::{ map_apply, map_partial_eq, Array, ArrayInfo, ArrayIter, DynamicEnum, DynamicMap, Enum, EnumInfo, FromReflect, FromType, GetTypeRegistration, List, ListInfo, Map, MapInfo, MapIter, - Reflect, ReflectDeserialize, ReflectMut, ReflectRef, ReflectSerialize, TupleVariantInfo, - TypeInfo, TypeRegistration, Typed, UnitVariantInfo, UnnamedField, ValueInfo, VariantFieldIter, - VariantInfo, VariantType, + Reflect, ReflectDeserialize, ReflectMut, ReflectRef, ReflectSerialize, ReflectTypeName, + TupleVariantInfo, TypeInfo, TypeRegistration, Typed, UnitVariantInfo, UnnamedField, ValueInfo, + VariantFieldIter, VariantInfo, VariantType, }; use crate::utility::{GenericTypeInfoCell, NonGenericTypeInfoCell}; @@ -149,10 +149,6 @@ impl List for Vec { } impl Reflect for Vec { - fn type_name(&self) -> &str { - std::any::type_name::() - } - fn get_type_info(&self) -> &'static TypeInfo { ::type_info() } @@ -302,10 +298,6 @@ impl Map for H } impl Reflect for HashMap { - fn type_name(&self) -> &str { - std::any::type_name::() - } - fn get_type_info(&self) -> &'static TypeInfo { ::type_info() } @@ -419,11 +411,6 @@ impl Array for [T; N] { } impl Reflect for [T; N] { - #[inline] - fn type_name(&self) -> &str { - std::any::type_name::() - } - fn get_type_info(&self) -> &'static TypeInfo { ::type_info() } @@ -536,10 +523,6 @@ impl_array_get_type_registration! { } impl Reflect for Cow<'static, str> { - fn type_name(&self) -> &str { - std::any::type_name::() - } - fn get_type_info(&self) -> &'static TypeInfo { ::type_info() } @@ -678,11 +661,6 @@ impl Enum for Option { } impl Reflect for Option { - #[inline] - fn type_name(&self) -> &str { - std::any::type_name::() - } - #[inline] fn get_type_info(&self) -> &'static TypeInfo { ::type_info() @@ -868,8 +846,8 @@ impl FromReflect for Cow<'static, str> { mod tests { use crate as bevy_reflect; use crate::{ - Enum, FromReflect, Reflect, ReflectSerialize, TypeInfo, TypeRegistry, Typed, VariantInfo, - VariantType, + Enum, FromReflect, Reflect, ReflectSerialize, ReflectTypeName, TypeInfo, TypeRegistry, + Typed, VariantInfo, VariantType, }; use bevy_utils::{HashMap, Instant}; use std::f32::consts::{PI, TAU}; diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index d9483e8684dff..f465b35141fe5 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -924,7 +924,7 @@ bevy_reflect::tests::should_reflect_debug::Test { #[derive(TypeName)] struct Foo; let foo = Foo; - let name = foo.type_name_(); + let name = foo.type_name(); assert_eq!(name.as_ref(), "bevy_reflect::tests::Foo"); #[derive(TypeName)] @@ -932,7 +932,7 @@ bevy_reflect::tests::should_reflect_debug::Test { _value: T, } let goo = Goo { _value: 42u32 }; - let name = goo.type_name_(); + let name = goo.type_name(); assert_eq!( name.as_ref(), "bevy_reflect::tests::Goo" @@ -947,7 +947,7 @@ bevy_reflect::tests::should_reflect_debug::Test { #[type_name("Banane")] struct Foo; let foo = Foo; - let name = foo.type_name_(); + let name = foo.type_name(); assert_eq!(name.as_ref(), "Banane"); #[derive(TypeName)] @@ -956,7 +956,7 @@ bevy_reflect::tests::should_reflect_debug::Test { _value: T, } let goo = Goo { _value: 42u32 }; - let name = goo.type_name_(); + let name = goo.type_name(); assert_eq!(name.as_ref(), "MyType"); } diff --git a/crates/bevy_reflect/src/list.rs b/crates/bevy_reflect/src/list.rs index 9df6508ac5bfa..1a5be2da9ac07 100644 --- a/crates/bevy_reflect/src/list.rs +++ b/crates/bevy_reflect/src/list.rs @@ -3,8 +3,8 @@ use std::fmt::{Debug, Formatter}; use crate::utility::NonGenericTypeInfoCell; use crate::{ - self as bevy_reflect, Array, ArrayIter, DynamicArray, DynamicInfo, FromReflect, Reflect, - ReflectMut, ReflectRef, TypeInfo, TypeName, Typed, + Array, ArrayIter, DynamicArray, DynamicInfo, FromReflect, Reflect, ReflectMut, ReflectRef, + ReflectTypeName, TypeInfo, Typed, }; /// An ordered, mutable list of [Reflect] items. This corresponds to types like [`std::vec::Vec`]. @@ -80,7 +80,7 @@ impl ListInfo { } /// A list of reflected values. -#[derive(Default, TypeName)] +#[derive(Default)] pub struct DynamicList { name: String, values: Vec>, @@ -114,6 +114,12 @@ impl DynamicList { } } +impl ReflectTypeName for DynamicList { + fn type_name(&self) -> std::borrow::Cow { + self.name.as_str().into() + } +} + impl Array for DynamicList { fn get(&self, index: usize) -> Option<&dyn Reflect> { self.values.get(index).map(|value| &**value) @@ -164,11 +170,6 @@ impl List for DynamicList { } impl Reflect for DynamicList { - #[inline] - fn type_name(&self) -> &str { - self.name.as_str() - } - #[inline] fn get_type_info(&self) -> &'static TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/src/map.rs b/crates/bevy_reflect/src/map.rs index 4586ce56afda4..c198010b9e456 100644 --- a/crates/bevy_reflect/src/map.rs +++ b/crates/bevy_reflect/src/map.rs @@ -5,9 +5,7 @@ use std::hash::Hash; use bevy_utils::{Entry, HashMap}; use crate::utility::NonGenericTypeInfoCell; -use crate::{ - self as bevy_reflect, DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, TypeName, Typed, -}; +use crate::{DynamicInfo, Reflect, ReflectMut, ReflectRef, ReflectTypeName, TypeInfo, Typed}; /// An ordered mapping between [`Reflect`] values. /// @@ -137,7 +135,7 @@ impl MapInfo { const HASH_ERROR: &str = "the given key does not support hashing"; /// An ordered mapping between reflected values. -#[derive(Default, TypeName)] +#[derive(Default)] pub struct DynamicMap { name: String, values: Vec<(Box, Box)>, @@ -167,6 +165,12 @@ impl DynamicMap { } } +impl ReflectTypeName for DynamicMap { + fn type_name(&self) -> std::borrow::Cow { + self.name.as_str().into() + } +} + impl Map for DynamicMap { fn get(&self, key: &dyn Reflect) -> Option<&dyn Reflect> { self.indices @@ -231,10 +235,6 @@ impl Map for DynamicMap { } impl Reflect for DynamicMap { - fn type_name(&self) -> &str { - &self.name - } - #[inline] fn get_type_info(&self) -> &'static TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/src/reflect.rs b/crates/bevy_reflect/src/reflect.rs index 677e0f68ac1f1..60ef1e4f92778 100644 --- a/crates/bevy_reflect/src/reflect.rs +++ b/crates/bevy_reflect/src/reflect.rs @@ -1,10 +1,10 @@ use crate::{ array_debug, enum_debug, list_debug, map_debug, serde::Serializable, struct_debug, tuple_debug, - tuple_struct_debug, Array, Enum, List, Map, Struct, Tuple, TupleStruct, TypeInfo, Typed, - ValueInfo, ReflectTypeName, + tuple_struct_debug, Array, Enum, List, Map, ReflectTypeName, Struct, Tuple, TupleStruct, + TypeInfo, Typed, ValueInfo, }; use std::{ - any::{self, Any, TypeId}, + any::{Any, TypeId}, fmt::Debug, }; @@ -53,9 +53,6 @@ pub enum ReflectMut<'a> { /// When using `#[derive(Reflect)]` with a struct or tuple struct, the suitable subtrait for that /// type (`Struct` or `TupleStruct`) is derived automatically. pub trait Reflect: ReflectTypeName + Any + Send + Sync { - /// Returns the [type name][std::any::type_name] of the underlying type. - fn type_name(&self) -> &str; - /// Returns the [`TypeInfo`] of the underlying type. /// /// This method is great if you have an instance of a type or a `dyn Reflect`, @@ -240,7 +237,10 @@ impl dyn Reflect { /// Read `is` for more information on underlying values and represented types. #[inline] pub fn represents(&self) -> bool { - self.type_name() == any::type_name::() + // FIXME + // self.type_name() == any::type_name::() + + todo!() } /// Returns `true` if the underlying value is of type `T`, or `false` diff --git a/crates/bevy_reflect/src/serde/ser.rs b/crates/bevy_reflect/src/serde/ser.rs index 0dd239d6305a7..950bce407fa49 100644 --- a/crates/bevy_reflect/src/serde/ser.rs +++ b/crates/bevy_reflect/src/serde/ser.rs @@ -110,7 +110,7 @@ impl<'a> Serialize for ReflectValueSerializer<'a> { S: serde::Serializer, { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.value.type_name())?; + state.serialize_entry(type_fields::TYPE, self.value.type_name().as_ref())?; state.serialize_entry( type_fields::VALUE, get_serializable::(self.value, self.registry)?.borrow(), @@ -131,7 +131,7 @@ impl<'a> Serialize for StructSerializer<'a> { { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.struct_value.type_name())?; + state.serialize_entry(type_fields::TYPE, self.struct_value.type_name().as_ref())?; state.serialize_entry( type_fields::STRUCT, &StructValueSerializer { @@ -174,7 +174,7 @@ impl<'a> Serialize for TupleStructSerializer<'a> { { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.tuple_struct.type_name())?; + state.serialize_entry(type_fields::TYPE, self.tuple_struct.type_name().as_ref())?; state.serialize_entry( type_fields::TUPLE_STRUCT, &TupleStructValueSerializer { @@ -216,7 +216,7 @@ impl<'a> Serialize for EnumSerializer<'a> { { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.enum_value.type_name())?; + state.serialize_entry(type_fields::TYPE, self.enum_value.type_name().as_ref())?; state.serialize_entry( type_fields::ENUM, &EnumValueSerializer { @@ -327,7 +327,7 @@ impl<'a> Serialize for TupleSerializer<'a> { { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.tuple.type_name())?; + state.serialize_entry(type_fields::TYPE, self.tuple.type_name().as_ref())?; state.serialize_entry( type_fields::TUPLE, &TupleValueSerializer { @@ -369,7 +369,7 @@ impl<'a> Serialize for MapSerializer<'a> { { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.map.type_name())?; + state.serialize_entry(type_fields::TYPE, self.map.type_name().as_ref())?; state.serialize_entry( type_fields::MAP, &MapValueSerializer { @@ -413,7 +413,7 @@ impl<'a> Serialize for ListSerializer<'a> { S: serde::Serializer, { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.list.type_name())?; + state.serialize_entry(type_fields::TYPE, self.list.type_name().as_ref())?; state.serialize_entry( type_fields::LIST, &ListValueSerializer { @@ -454,7 +454,7 @@ impl<'a> Serialize for ArraySerializer<'a> { S: serde::Serializer, { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.array.type_name())?; + state.serialize_entry(type_fields::TYPE, self.array.type_name().as_ref())?; state.serialize_entry( type_fields::ARRAY, &ArrayValueSerializer { diff --git a/crates/bevy_reflect/src/struct_trait.rs b/crates/bevy_reflect/src/struct_trait.rs index 5b0dfe133e22c..aa8b021254577 100644 --- a/crates/bevy_reflect/src/struct_trait.rs +++ b/crates/bevy_reflect/src/struct_trait.rs @@ -1,7 +1,6 @@ use crate::utility::NonGenericTypeInfoCell; use crate::{ - self as bevy_reflect, DynamicInfo, NamedField, Reflect, ReflectMut, ReflectRef, TypeInfo, - TypeName, Typed, + DynamicInfo, NamedField, Reflect, ReflectMut, ReflectRef, ReflectTypeName, TypeInfo, Typed, }; use bevy_utils::{Entry, HashMap}; use std::fmt::{Debug, Formatter}; @@ -22,7 +21,7 @@ use std::{ /// # Example /// /// ``` -/// use bevy_reflect::{Reflect, Struct}; +/// use bevy_reflect::{Reflect, Struct, ReflectTypeName}; /// /// #[derive(Reflect)] /// struct Foo { @@ -186,7 +185,7 @@ impl<'a> ExactSizeIterator for FieldIter<'a> {} /// # Example /// /// ``` -/// use bevy_reflect::{GetField, Reflect}; +/// use bevy_reflect::{GetField, Reflect, ReflectTypeName}; /// /// #[derive(Reflect)] /// struct Foo { @@ -233,7 +232,7 @@ impl GetField for dyn Struct { } /// A struct type which allows fields to be added at runtime. -#[derive(Default, TypeName)] +#[derive(Default)] pub struct DynamicStruct { name: String, fields: Vec>, @@ -286,6 +285,12 @@ impl DynamicStruct { } } +impl ReflectTypeName for DynamicStruct { + fn type_name(&self) -> std::borrow::Cow { + self.name.as_str().into() + } +} + impl Struct for DynamicStruct { #[inline] fn field(&self, name: &str) -> Option<&dyn Reflect> { @@ -346,11 +351,6 @@ impl Struct for DynamicStruct { } impl Reflect for DynamicStruct { - #[inline] - fn type_name(&self) -> &str { - &self.name - } - #[inline] fn get_type_info(&self) -> &'static TypeInfo { ::type_info() @@ -478,7 +478,7 @@ pub fn struct_partial_eq(a: &S, b: &dyn Reflect) -> Option { /// /// # Example /// ``` -/// use bevy_reflect::Reflect; +/// use bevy_reflect::{Reflect, ReflectTypeName}; /// #[derive(Reflect)] /// struct MyStruct { /// foo: usize @@ -495,7 +495,7 @@ pub fn struct_partial_eq(a: &S, b: &dyn Reflect) -> Option { /// ``` #[inline] pub fn struct_debug(dyn_struct: &dyn Struct, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let mut debug = f.debug_struct(dyn_struct.type_name()); + let mut debug = f.debug_struct(dyn_struct.type_name().as_ref()); for field_index in 0..dyn_struct.field_len() { let field = dyn_struct.field_at(field_index).unwrap(); debug.field( diff --git a/crates/bevy_reflect/src/tuple.rs b/crates/bevy_reflect/src/tuple.rs index d00af60e78701..b46dbbd1a4f27 100644 --- a/crates/bevy_reflect/src/tuple.rs +++ b/crates/bevy_reflect/src/tuple.rs @@ -1,7 +1,7 @@ use crate::utility::NonGenericTypeInfoCell; use crate::{ - self as bevy_reflect, DynamicInfo, FromReflect, GetTypeRegistration, Reflect, ReflectMut, - ReflectRef, TypeInfo, TypeName, TypeRegistration, Typed, UnnamedField, + DynamicInfo, FromReflect, GetTypeRegistration, Reflect, ReflectMut, ReflectRef, + ReflectTypeName, TypeInfo, TypeName, TypeRegistration, Typed, UnnamedField, }; use std::any::{Any, TypeId}; use std::fmt::{Debug, Formatter}; @@ -182,7 +182,7 @@ impl TupleInfo { } /// A tuple which allows fields to be added at runtime. -#[derive(Default, TypeName)] +#[derive(Default)] pub struct DynamicTuple { name: String, fields: Vec>, @@ -223,12 +223,18 @@ impl DynamicTuple { if i > 0 { name.push_str(", "); } - name.push_str(field.type_name()); + name.push_str(field.type_name().as_ref()); } name.push(')'); } } +impl ReflectTypeName for DynamicTuple { + fn type_name(&self) -> std::borrow::Cow { + self.name.as_str().into() + } +} + impl Tuple for DynamicTuple { #[inline] fn field(&self, index: usize) -> Option<&dyn Reflect> { @@ -267,11 +273,6 @@ impl Tuple for DynamicTuple { } impl Reflect for DynamicTuple { - #[inline] - fn type_name(&self) -> &str { - self.name() - } - #[inline] fn get_type_info(&self) -> &'static TypeInfo { ::type_info() @@ -466,10 +467,6 @@ macro_rules! impl_reflect_tuple { } impl<$($name: Reflect + TypeName),*> Reflect for ($($name,)*) { - fn type_name(&self) -> &str { - std::any::type_name::() - } - fn get_type_info(&self) -> &'static TypeInfo { ::type_info() } diff --git a/crates/bevy_reflect/src/tuple_struct.rs b/crates/bevy_reflect/src/tuple_struct.rs index 2db1b81f653f1..9b7ec287b6d84 100644 --- a/crates/bevy_reflect/src/tuple_struct.rs +++ b/crates/bevy_reflect/src/tuple_struct.rs @@ -1,7 +1,6 @@ use crate::utility::NonGenericTypeInfoCell; use crate::{ - self as bevy_reflect, DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, TypeName, Typed, - UnnamedField, + DynamicInfo, Reflect, ReflectMut, ReflectRef, ReflectTypeName, TypeInfo, Typed, UnnamedField, }; use std::any::{Any, TypeId}; use std::fmt::{Debug, Formatter}; @@ -16,7 +15,7 @@ use std::slice::Iter; /// `#[derive(Reflect)]`. /// /// ``` -/// use bevy_reflect::{Reflect, TupleStruct}; +/// use bevy_reflect::{Reflect, ReflectTypeName, TupleStruct}; /// /// #[derive(Reflect)] /// struct Foo(String); @@ -143,7 +142,7 @@ impl<'a> ExactSizeIterator for TupleStructFieldIter<'a> {} /// # Example /// /// ``` -/// use bevy_reflect::{GetTupleStructField, Reflect}; +/// use bevy_reflect::{GetTupleStructField, Reflect, ReflectTypeName}; /// /// #[derive(Reflect)] /// struct Foo(String); @@ -190,7 +189,7 @@ impl GetTupleStructField for dyn TupleStruct { } /// A tuple struct which allows fields to be added at runtime. -#[derive(Default, TypeName)] +#[derive(Default)] pub struct DynamicTupleStruct { name: String, fields: Vec>, @@ -218,6 +217,12 @@ impl DynamicTupleStruct { } } +impl ReflectTypeName for DynamicTupleStruct { + fn type_name(&self) -> std::borrow::Cow { + self.name.as_str().into() + } +} + impl TupleStruct for DynamicTupleStruct { #[inline] fn field(&self, index: usize) -> Option<&dyn Reflect> { @@ -255,11 +260,6 @@ impl TupleStruct for DynamicTupleStruct { } impl Reflect for DynamicTupleStruct { - #[inline] - fn type_name(&self) -> &str { - self.name.as_str() - } - #[inline] fn get_type_info(&self) -> &'static TypeInfo { ::type_info() @@ -384,7 +384,7 @@ pub fn tuple_struct_partial_eq(a: &S, b: &dyn Reflect) -> Option /// /// # Example /// ``` -/// use bevy_reflect::Reflect; +/// use bevy_reflect::{Reflect, ReflectTypeName}; /// #[derive(Reflect)] /// struct MyTupleStruct(usize); /// @@ -402,7 +402,7 @@ pub fn tuple_struct_debug( dyn_tuple_struct: &dyn TupleStruct, f: &mut std::fmt::Formatter<'_>, ) -> std::fmt::Result { - let mut debug = f.debug_tuple(dyn_tuple_struct.type_name()); + let mut debug = f.debug_tuple(dyn_tuple_struct.type_name().as_ref()); for field in dyn_tuple_struct.iter_fields() { debug.field(&field as &dyn Debug); } diff --git a/crates/bevy_reflect/src/type_info.rs b/crates/bevy_reflect/src/type_info.rs index 57137a70fa2b7..e55aadc2baea8 100644 --- a/crates/bevy_reflect/src/type_info.rs +++ b/crates/bevy_reflect/src/type_info.rs @@ -23,7 +23,7 @@ use std::any::{Any, TypeId}; /// /// ``` /// # use std::any::Any; -/// # use bevy_reflect::{NamedField, Reflect, ReflectMut, ReflectRef, StructInfo, TypeInfo, TypeName, ValueInfo}; +/// # use bevy_reflect::{NamedField, Reflect, ReflectMut, ReflectRef, StructInfo, TypeInfo, TypeName, ValueInfo, ReflectTypeName}; /// # use bevy_reflect::utility::NonGenericTypeInfoCell; /// use bevy_reflect::Typed; /// @@ -51,7 +51,6 @@ use std::any::{Any, TypeId}; /// # } /// # /// # impl Reflect for MyStruct { -/// # fn type_name(&self) -> &str { todo!() } /// # fn get_type_info(&self) -> &'static TypeInfo { todo!() } /// # fn into_any(self: Box) -> Box { todo!() } /// # fn as_any(&self) -> &dyn Any { todo!() } diff --git a/crates/bevy_reflect/src/type_name.rs b/crates/bevy_reflect/src/type_name.rs index 466f52f6ea7de..0a13332be4467 100644 --- a/crates/bevy_reflect/src/type_name.rs +++ b/crates/bevy_reflect/src/type_name.rs @@ -8,14 +8,12 @@ pub trait TypeName { /// A object-safe version of [`TypeName`]. /// Automatically implemented via blanket implementation. pub trait ReflectTypeName { - // FIXME: named with a trailling underscore to avoid conflict - // with Reflect::type_name until it's replaced by this method. - fn type_name_(&self) -> Cow<'static, str>; + fn type_name(&self) -> Cow; } impl ReflectTypeName for T { #[inline] - fn type_name_(&self) -> Cow<'static, str> { + fn type_name(&self) -> Cow { Self::name() } } diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index 74865abeb0c91..29e6bb59998b5 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -452,7 +452,7 @@ impl Deserialize<'a> + Reflect> FromType for ReflectDeserialize { /// /// # Example /// ```rust -/// use bevy_reflect::{TypeRegistry, Reflect, ReflectFromPtr}; +/// use bevy_reflect::{TypeRegistry, Reflect, ReflectTypeName, ReflectFromPtr}; /// use bevy_ptr::Ptr; /// use std::ptr::NonNull; /// @@ -524,7 +524,7 @@ impl FromType for ReflectFromPtr { mod test { use std::ptr::NonNull; - use crate::{GetTypeRegistration, ReflectFromPtr, TypeRegistration}; + use crate::{GetTypeRegistration, ReflectFromPtr, ReflectTypeName, TypeRegistration}; use bevy_ptr::{Ptr, PtrMut}; use bevy_utils::HashMap; diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index 40a41ada9de7b..cbedd5aaff219 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -38,7 +38,6 @@ use std::any::{Any, TypeId}; /// # } /// # /// # impl Reflect for Foo { -/// # fn type_name(&self) -> &str { todo!() } /// # fn get_type_info(&self) -> &'static TypeInfo { todo!() } /// # fn into_any(self: Box) -> Box { todo!() } /// # fn as_any(&self) -> &dyn Any { todo!() } @@ -103,7 +102,6 @@ impl NonGenericTypeInfoCell { /// # } /// # /// # impl Reflect for Foo { -/// # fn type_name(&self) -> &str { todo!() } /// # fn get_type_info(&self) -> &'static TypeInfo { todo!() } /// # fn into_any(self: Box) -> Box { todo!() } /// # fn as_any(&self) -> &dyn Any { todo!() } diff --git a/crates/bevy_render/src/camera/projection.rs b/crates/bevy_render/src/camera/projection.rs index 592b4cc8f916b..fa6d6c4b8da82 100644 --- a/crates/bevy_render/src/camera/projection.rs +++ b/crates/bevy_render/src/camera/projection.rs @@ -5,7 +5,7 @@ use bevy_ecs::{prelude::*, reflect::ReflectComponent}; use bevy_math::Mat4; use bevy_reflect::{ std_traits::ReflectDefault, FromReflect, GetTypeRegistration, Reflect, ReflectDeserialize, - ReflectSerialize, + ReflectSerialize, ReflectTypeName, }; use bevy_window::ModifiesWindows; use serde::{Deserialize, Serialize}; diff --git a/crates/bevy_render/src/mesh/mesh/skinning.rs b/crates/bevy_render/src/mesh/mesh/skinning.rs index 31837a51b7d77..aa2e5c134f9cd 100644 --- a/crates/bevy_render/src/mesh/mesh/skinning.rs +++ b/crates/bevy_render/src/mesh/mesh/skinning.rs @@ -6,7 +6,7 @@ use bevy_ecs::{ reflect::ReflectMapEntities, }; use bevy_math::Mat4; -use bevy_reflect::{Reflect, TypeName, TypeUuid}; +use bevy_reflect::{Reflect, ReflectTypeName, TypeName, TypeUuid}; use std::ops::Deref; #[derive(Component, Debug, Default, Clone, Reflect)] diff --git a/crates/bevy_render/src/primitives/mod.rs b/crates/bevy_render/src/primitives/mod.rs index ae82c844be6ce..8c312d4f5d227 100644 --- a/crates/bevy_render/src/primitives/mod.rs +++ b/crates/bevy_render/src/primitives/mod.rs @@ -1,6 +1,6 @@ use bevy_ecs::{component::Component, reflect::ReflectComponent}; use bevy_math::{Mat4, Vec3, Vec3A, Vec4, Vec4Swizzles}; -use bevy_reflect::Reflect; +use bevy_reflect::{Reflect, ReflectTypeName}; /// An Axis-Aligned Bounding Box #[derive(Component, Clone, Debug, Default, Reflect)] diff --git a/crates/bevy_render/src/view/mod.rs b/crates/bevy_render/src/view/mod.rs index 55ca6a31b6c23..3535dbb03e4be 100644 --- a/crates/bevy_render/src/view/mod.rs +++ b/crates/bevy_render/src/view/mod.rs @@ -22,7 +22,7 @@ use crate::{ use bevy_app::{App, Plugin}; use bevy_ecs::prelude::*; use bevy_math::{Mat4, Vec3}; -use bevy_reflect::Reflect; +use bevy_reflect::{Reflect, ReflectTypeName}; use bevy_transform::components::GlobalTransform; use bevy_utils::HashMap; diff --git a/crates/bevy_render/src/view/visibility/mod.rs b/crates/bevy_render/src/view/visibility/mod.rs index bf7b110b1277e..5663379a5a4b0 100644 --- a/crates/bevy_render/src/view/visibility/mod.rs +++ b/crates/bevy_render/src/view/visibility/mod.rs @@ -7,7 +7,7 @@ use bevy_asset::{Assets, Handle}; use bevy_ecs::prelude::*; use bevy_hierarchy::{Children, Parent}; use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{Reflect, ReflectTypeName}; use bevy_transform::components::GlobalTransform; use bevy_transform::TransformSystem; use std::cell::Cell; diff --git a/crates/bevy_render/src/view/visibility/render_layers.rs b/crates/bevy_render/src/view/visibility/render_layers.rs index 677c0877777ba..b8774f9eb4fc3 100644 --- a/crates/bevy_render/src/view/visibility/render_layers.rs +++ b/crates/bevy_render/src/view/visibility/render_layers.rs @@ -1,6 +1,6 @@ use bevy_ecs::prelude::{Component, ReflectComponent}; use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{Reflect, ReflectTypeName}; type LayerMask = u32; diff --git a/crates/bevy_scene/src/dynamic_scene.rs b/crates/bevy_scene/src/dynamic_scene.rs index 2fd36bd1d09b0..e92445f7658b7 100644 --- a/crates/bevy_scene/src/dynamic_scene.rs +++ b/crates/bevy_scene/src/dynamic_scene.rs @@ -99,7 +99,7 @@ impl DynamicScene { // Apply/ add each component to the given entity. for component in &scene_entity.components { let registration = type_registry - .get_with_name(component.type_name()) + .get_with_name(component.type_name().as_ref()) .ok_or_else(|| SceneSpawnError::UnregisteredType { type_name: component.type_name().to_string(), })?; diff --git a/crates/bevy_sprite/src/mesh2d/mesh.rs b/crates/bevy_sprite/src/mesh2d/mesh.rs index 18513f0d5362d..73d3407f8a137 100644 --- a/crates/bevy_sprite/src/mesh2d/mesh.rs +++ b/crates/bevy_sprite/src/mesh2d/mesh.rs @@ -5,7 +5,7 @@ use bevy_ecs::{ system::{lifetimeless::*, SystemParamItem, SystemState}, }; use bevy_math::{Mat4, Vec2}; -use bevy_reflect::{Reflect, TypeUuid}; +use bevy_reflect::{Reflect, ReflectTypeName, TypeUuid}; use bevy_render::{ extract_component::{ComponentUniforms, DynamicUniformIndex, UniformComponentPlugin}, mesh::{GpuBufferInfo, Mesh, MeshVertexBufferLayout}, diff --git a/crates/bevy_sprite/src/rect.rs b/crates/bevy_sprite/src/rect.rs index 3a7fb2a04dd26..30cf2d2808eab 100644 --- a/crates/bevy_sprite/src/rect.rs +++ b/crates/bevy_sprite/src/rect.rs @@ -1,5 +1,5 @@ use bevy_math::Vec2; -use bevy_reflect::Reflect; +use bevy_reflect::{Reflect, ReflectTypeName}; /// A rectangle defined by two points. There is no defined origin, so 0,0 could be anywhere /// (top-left, bottom-left, etc) diff --git a/crates/bevy_sprite/src/sprite.rs b/crates/bevy_sprite/src/sprite.rs index 56dc1b86c935d..eaac2e9952dc9 100644 --- a/crates/bevy_sprite/src/sprite.rs +++ b/crates/bevy_sprite/src/sprite.rs @@ -1,6 +1,6 @@ use bevy_ecs::component::Component; use bevy_math::Vec2; -use bevy_reflect::Reflect; +use bevy_reflect::{Reflect, ReflectTypeName}; use bevy_render::color::Color; #[derive(Component, Debug, Default, Clone, Reflect)] diff --git a/crates/bevy_sprite/src/texture_atlas.rs b/crates/bevy_sprite/src/texture_atlas.rs index d0a326648f533..3dbd74edb6372 100644 --- a/crates/bevy_sprite/src/texture_atlas.rs +++ b/crates/bevy_sprite/src/texture_atlas.rs @@ -2,7 +2,7 @@ use crate::{Anchor, Rect}; use bevy_asset::Handle; use bevy_ecs::component::Component; use bevy_math::Vec2; -use bevy_reflect::{Reflect, TypeName, TypeUuid}; +use bevy_reflect::{Reflect, ReflectTypeName, TypeName, TypeUuid}; use bevy_render::{color::Color, texture::Image}; use bevy_utils::HashMap; diff --git a/crates/bevy_text/src/text2d.rs b/crates/bevy_text/src/text2d.rs index dd4a5b63f5a23..98b90aec27eb9 100644 --- a/crates/bevy_text/src/text2d.rs +++ b/crates/bevy_text/src/text2d.rs @@ -9,7 +9,7 @@ use bevy_ecs::{ system::{Local, Query, Res, ResMut}, }; use bevy_math::{Vec2, Vec3}; -use bevy_reflect::Reflect; +use bevy_reflect::{Reflect, ReflectTypeName}; use bevy_render::{ prelude::Color, texture::Image, diff --git a/crates/bevy_time/src/time.rs b/crates/bevy_time/src/time.rs index 1835f841c93a7..93d1722d4ffd8 100644 --- a/crates/bevy_time/src/time.rs +++ b/crates/bevy_time/src/time.rs @@ -1,5 +1,5 @@ use bevy_ecs::{reflect::ReflectResource, system::Resource}; -use bevy_reflect::{FromReflect, Reflect}; +use bevy_reflect::{FromReflect, Reflect, ReflectTypeName}; use bevy_utils::{Duration, Instant}; /// Tracks elapsed time since the last update and since the App has started diff --git a/crates/bevy_transform/src/components/global_transform.rs b/crates/bevy_transform/src/components/global_transform.rs index f1129f8681116..b20e8eaf0b4e0 100644 --- a/crates/bevy_transform/src/components/global_transform.rs +++ b/crates/bevy_transform/src/components/global_transform.rs @@ -3,7 +3,7 @@ use std::ops::Mul; use super::Transform; use bevy_ecs::{component::Component, reflect::ReflectComponent}; use bevy_math::{Affine3A, Mat4, Quat, Vec3, Vec3A}; -use bevy_reflect::Reflect; +use bevy_reflect::{Reflect, ReflectTypeName}; /// Describe the position of an entity relative to the reference frame. /// diff --git a/crates/bevy_ui/src/geometry.rs b/crates/bevy_ui/src/geometry.rs index bf0220eb3197d..fda47b3a5c4b6 100644 --- a/crates/bevy_ui/src/geometry.rs +++ b/crates/bevy_ui/src/geometry.rs @@ -1,6 +1,6 @@ use crate::Val; use bevy_math::Vec2; -use bevy_reflect::Reflect; +use bevy_reflect::{Reflect, ReflectTypeName}; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; /// A type which is commonly used to define positions, margins, paddings and borders. diff --git a/crates/bevy_ui/src/widget/button.rs b/crates/bevy_ui/src/widget/button.rs index 6c7dced0f3bb0..468d8e39f6700 100644 --- a/crates/bevy_ui/src/widget/button.rs +++ b/crates/bevy_ui/src/widget/button.rs @@ -1,7 +1,7 @@ use bevy_ecs::prelude::Component; use bevy_ecs::reflect::ReflectComponent; use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{Reflect, ReflectTypeName}; /// Marker struct for buttons #[derive(Component, Debug, Default, Clone, Copy, Reflect)] From 06e92587ff465cdabf81bbcb08c01ae0490398b4 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sat, 27 Aug 2022 00:23:40 +0200 Subject: [PATCH 03/87] fix tuple TypeName --- crates/bevy_reflect/src/type_name.rs | 29 ++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/bevy_reflect/src/type_name.rs b/crates/bevy_reflect/src/type_name.rs index 0a13332be4467..e347d40d8dce4 100644 --- a/crates/bevy_reflect/src/type_name.rs +++ b/crates/bevy_reflect/src/type_name.rs @@ -27,14 +27,16 @@ macro_rules! impl_type_name_tuple { fn name() -> Cow<'static, str> { $(let $t = <$t as TypeName>::name();)* let s = format!( - concat!($(impl_type_name_tuple!(@bracket $t),)*), + concat!("(", impl_type_name_tuple!(@bracket $($t),*), ")"), $($t,)* ); Cow::Owned(s) } } }; - (@bracket $t:tt) => {"{}"} + (@bracket $t:tt, $($rest:tt),*) => {concat!("{}, ", impl_type_name_tuple!(@bracket $($rest),*))}; + (@bracket $t:tt) => {"{}"}; + (@bracket) => {""}; } impl_type_name_tuple!(); @@ -50,3 +52,26 @@ impl_type_name_tuple!(A, B, C, D, E, F, G, H, I); impl_type_name_tuple!(A, B, C, D, E, F, G, H, I, J); impl_type_name_tuple!(A, B, C, D, E, F, G, H, I, J, K); impl_type_name_tuple!(A, B, C, D, E, F, G, H, I, J, K, L); + +#[cfg(test)] +mod tests { + use crate::{self as bevy_reflect, TypeName}; + + #[test] + fn tuple_name() { + #[derive(TypeName)] + #[type_name("Foo")] + struct Foo; + + #[derive(TypeName)] + #[type_name("Goo")] + struct Goo; + + #[derive(TypeName)] + #[type_name("Hoo")] + struct Hoo; + + let s = <(Foo, Goo, Hoo) as TypeName>::name(); + assert_eq!(s, "(Foo, Goo, Hoo)"); + } +} From 312659af5cecca8bd3ce6a7902e278da9998b939 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sat, 27 Aug 2022 00:24:28 +0200 Subject: [PATCH 04/87] impl_reflect_value use modul less name --- crates/bevy_reflect/bevy_reflect_derive/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index 898109ec166e2..ca2e905548bde 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -137,7 +137,7 @@ pub fn impl_reflect_value(input: TokenStream) -> TokenStream { &def.type_name, &def.generics, def.traits.unwrap_or_default(), - None, // TODO + Some(def.type_name.to_string()), )) } @@ -225,7 +225,7 @@ pub fn impl_type_name(input: TokenStream) -> TokenStream { &def.type_name, &def.generics, Default::default(), - None, // TODO + Some(def.type_name.to_string()), ); TokenStream::from(impls::impl_type_name( meta.type_name(), From 69823512ee126328f0b5283a690c66117400d6de Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sat, 27 Aug 2022 00:24:32 +0200 Subject: [PATCH 05/87] update tests --- crates/bevy_reflect/src/impls/std.rs | 2 +- crates/bevy_reflect/src/lib.rs | 25 +++++++++++-------------- crates/bevy_reflect/src/serde/ser.rs | 10 +++++----- 3 files changed, 17 insertions(+), 20 deletions(-) diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index 72d5aacd62120..0d31f22f4801b 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -942,7 +942,7 @@ mod tests { .unwrap_or_default()); assert_eq!("Some", value.variant_name()); - assert_eq!("core::option::Option::Some", value.variant_path()); + assert_eq!("Option::Some", value.variant_path()); if value.is_variant(VariantType::Tuple) { if let Some(field) = value diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index f465b35141fe5..0344974ea5f70 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -538,17 +538,17 @@ mod tests { fn dynamic_names() { let list = Vec::::new(); let dyn_list = List::clone_dynamic(&list); - assert_eq!(dyn_list.type_name(), std::any::type_name::>()); + assert_eq!(dyn_list.type_name(), as TypeName>::name()); let array = [b'0'; 4]; let dyn_array = Array::clone_dynamic(&array); - assert_eq!(dyn_array.type_name(), std::any::type_name::<[u8; 4]>()); + assert_eq!(dyn_array.type_name(), <[u8; 4] as TypeName>::name()); let map = HashMap::::default(); let dyn_map = map.clone_dynamic(); assert_eq!( dyn_map.type_name(), - std::any::type_name::>() + as TypeName>::name() ); let tuple = (0usize, "1".to_string(), 2.0f32); @@ -556,7 +556,7 @@ mod tests { dyn_tuple.insert::(3); assert_eq!( dyn_tuple.type_name(), - std::any::type_name::<(usize, String, f32, usize)>() + <(usize, String, f32, usize) as TypeName>::name() ); #[derive(Reflect)] @@ -565,7 +565,7 @@ mod tests { } let struct_ = TestStruct { a: 0 }; let dyn_struct = struct_.clone_dynamic(); - assert_eq!(dyn_struct.type_name(), std::any::type_name::()); + assert_eq!(dyn_struct.type_name(), ::name()); #[derive(Reflect)] struct TestTupleStruct(usize); @@ -573,7 +573,7 @@ mod tests { let dyn_tuple_struct = tuple_struct.clone_dynamic(); assert_eq!( dyn_tuple_struct.type_name(), - std::any::type_name::() + ::name() ); } @@ -883,7 +883,7 @@ mod tests { let reflected: &dyn Reflect = &test; let expected = r#" -bevy_reflect::tests::should_reflect_debug::Test { +bevy_reflect::tests::Test { value: 123, list: [ "A", @@ -898,10 +898,10 @@ bevy_reflect::tests::should_reflect_debug::Test { map: { 123: 1.23, }, - a_struct: bevy_reflect::tests::should_reflect_debug::SomeStruct { + a_struct: bevy_reflect::tests::SomeStruct { foo: "A Struct!", }, - a_tuple_struct: bevy_reflect::tests::should_reflect_debug::SomeTupleStruct( + a_tuple_struct: bevy_reflect::tests::SomeTupleStruct( "A Tuple Struct!", ), enum_unit: A, @@ -933,10 +933,7 @@ bevy_reflect::tests::should_reflect_debug::Test { } let goo = Goo { _value: 42u32 }; let name = goo.type_name(); - assert_eq!( - name.as_ref(), - "bevy_reflect::tests::Goo" - ); + assert_eq!(name.as_ref(), "bevy_reflect::tests::Goo"); } #[test] @@ -957,7 +954,7 @@ bevy_reflect::tests::should_reflect_debug::Test { } let goo = Goo { _value: 42u32 }; let name = goo.type_name(); - assert_eq!(name.as_ref(), "MyType"); + assert_eq!(name.as_ref(), "MyType"); } #[cfg(feature = "glam")] diff --git a/crates/bevy_reflect/src/serde/ser.rs b/crates/bevy_reflect/src/serde/ser.rs index 950bce407fa49..b72904a428b93 100644 --- a/crates/bevy_reflect/src/serde/ser.rs +++ b/crates/bevy_reflect/src/serde/ser.rs @@ -521,7 +521,7 @@ mod tests { let serializer = ReflectSerializer::new(&value, ®istry); let output = ron::ser::to_string_pretty(&serializer, config.clone()).unwrap(); let expected = r#"{ - "type": "bevy_reflect::serde::ser::tests::enum_should_serialize::MyEnum", + "type": "bevy_reflect::serde::ser::tests::MyEnum", "enum": { "variant": "Unit", }, @@ -533,7 +533,7 @@ mod tests { let serializer = ReflectSerializer::new(&value, ®istry); let output = ron::ser::to_string_pretty(&serializer, config.clone()).unwrap(); let expected = r#"{ - "type": "bevy_reflect::serde::ser::tests::enum_should_serialize::MyEnum", + "type": "bevy_reflect::serde::ser::tests::MyEnum", "enum": { "variant": "NewType", "tuple": [ @@ -551,7 +551,7 @@ mod tests { let serializer = ReflectSerializer::new(&value, ®istry); let output = ron::ser::to_string_pretty(&serializer, config.clone()).unwrap(); let expected = r#"{ - "type": "bevy_reflect::serde::ser::tests::enum_should_serialize::MyEnum", + "type": "bevy_reflect::serde::ser::tests::MyEnum", "enum": { "variant": "Tuple", "tuple": [ @@ -575,12 +575,12 @@ mod tests { let serializer = ReflectSerializer::new(&value, ®istry); let output = ron::ser::to_string_pretty(&serializer, config).unwrap(); let expected = r#"{ - "type": "bevy_reflect::serde::ser::tests::enum_should_serialize::MyEnum", + "type": "bevy_reflect::serde::ser::tests::MyEnum", "enum": { "variant": "Struct", "struct": { "value": { - "type": "alloc::string::String", + "type": "String", "value": "I <3 Enums", }, }, From 317372ff437c7528e88fa65d2db58c2ea039ab95 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sat, 27 Aug 2022 00:38:12 +0200 Subject: [PATCH 06/87] update `Reflect::represents` --- crates/bevy_reflect/src/reflect.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/crates/bevy_reflect/src/reflect.rs b/crates/bevy_reflect/src/reflect.rs index 60ef1e4f92778..7742555595a97 100644 --- a/crates/bevy_reflect/src/reflect.rs +++ b/crates/bevy_reflect/src/reflect.rs @@ -1,7 +1,7 @@ use crate::{ array_debug, enum_debug, list_debug, map_debug, serde::Serializable, struct_debug, tuple_debug, tuple_struct_debug, Array, Enum, List, Map, ReflectTypeName, Struct, Tuple, TupleStruct, - TypeInfo, Typed, ValueInfo, + TypeInfo, TypeName, Typed, ValueInfo, }; use std::{ any::{Any, TypeId}, @@ -236,11 +236,8 @@ impl dyn Reflect { /// /// Read `is` for more information on underlying values and represented types. #[inline] - pub fn represents(&self) -> bool { - // FIXME - // self.type_name() == any::type_name::() - - todo!() + pub fn represents(&self) -> bool { + self.type_name() == T::name() } /// Returns `true` if the underlying value is of type `T`, or `false` From 30a663f338c894459eedaf402e344b9f054342da Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sat, 27 Aug 2022 01:06:33 +0200 Subject: [PATCH 07/87] fix ci --- crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs | 4 ++-- .../bevy_reflect_derive/src/impls/type_name.rs | 7 ++----- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs index c107fc50b09ca..a46b70ebbbf08 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs @@ -254,9 +254,9 @@ impl<'a> ReflectMeta<'a> { self.generics } - /// Override the default type name for ReflectTypeName. + /// Override the default type name for `TypeName`. pub fn reflected_type_name(&self) -> Option<&str> { - self.reflected_type_name.as_ref().map(String::as_str) + self.reflected_type_name.as_deref() } /// The cached `bevy_reflect` path. diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs index 1f026d433fd77..ba34084618676 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs @@ -50,11 +50,8 @@ pub(crate) fn impl_type_name( // FIXME: Iterator::intersperse can be used here // currently unstable https://github.com/rust-lang/rust/issues/79524 - let mut brackets = Vec::with_capacity(generics.params.len()); - for _ in 0..generics.params.len() - 1 { - brackets.push("{}, "); - } - brackets.push("{}"); + let mut brackets = vec!["{}, "; generics.params.len()]; + *brackets.last_mut().unwrap() = "{}"; brackets.into_iter().collect::() }; From 3a8958a02a96c17bdd3cd503d1bd59bdb5d224c6 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sat, 27 Aug 2022 01:14:52 +0200 Subject: [PATCH 08/87] fix examples/3d/skybox --- examples/3d/skybox.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/3d/skybox.rs b/examples/3d/skybox.rs index ae6aa9a0f86c6..b595cd8bdeb64 100644 --- a/examples/3d/skybox.rs +++ b/examples/3d/skybox.rs @@ -196,7 +196,7 @@ fn animate_light_direction( } } -#[derive(Debug, Clone, TypeUuid)] +#[derive(Debug, Clone, TypeUuid, TypeName)] #[uuid = "9509a0f8-3c05-48ee-a13e-a93226c7f488"] struct CubemapMaterial { base_color_texture: Option>, From a710c17db9c0396408e961e52d9a3ce067ded812 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Sat, 27 Aug 2022 10:32:58 +0200 Subject: [PATCH 09/87] Update crates/bevy_reflect/src/type_name.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/src/type_name.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/src/type_name.rs b/crates/bevy_reflect/src/type_name.rs index e347d40d8dce4..32e9d6e7f79ba 100644 --- a/crates/bevy_reflect/src/type_name.rs +++ b/crates/bevy_reflect/src/type_name.rs @@ -5,7 +5,7 @@ pub trait TypeName { fn name() -> Cow<'static, str>; } -/// A object-safe version of [`TypeName`]. +/// An object-safe version of [`TypeName`]. /// Automatically implemented via blanket implementation. pub trait ReflectTypeName { fn type_name(&self) -> Cow; From 006c8e8cb449dc5a2d067b4d0c0144e50faf147b Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Sat, 27 Aug 2022 10:33:27 +0200 Subject: [PATCH 10/87] Update crates/bevy_reflect/src/type_name.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/src/type_name.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/bevy_reflect/src/type_name.rs b/crates/bevy_reflect/src/type_name.rs index 32e9d6e7f79ba..f7ac802a8a202 100644 --- a/crates/bevy_reflect/src/type_name.rs +++ b/crates/bevy_reflect/src/type_name.rs @@ -6,6 +6,7 @@ pub trait TypeName { } /// An object-safe version of [`TypeName`]. +/// /// Automatically implemented via blanket implementation. pub trait ReflectTypeName { fn type_name(&self) -> Cow; From a7e8dd60bdbda2b95dc2092d961aa8475d84937a Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sat, 27 Aug 2022 11:09:58 +0200 Subject: [PATCH 11/87] fix the requirement of importing `ReflectTypeName` --- crates/bevy_animation/src/lib.rs | 2 +- crates/bevy_asset/src/handle.rs | 2 +- crates/bevy_core/src/name.rs | 2 +- crates/bevy_core_pipeline/src/clear_color.rs | 2 +- crates/bevy_core_pipeline/src/core_2d/camera_2d.rs | 2 +- crates/bevy_core_pipeline/src/core_3d/camera_3d.rs | 2 +- crates/bevy_gltf/src/lib.rs | 2 +- crates/bevy_hierarchy/src/components/children.rs | 2 +- crates/bevy_hierarchy/src/components/parent.rs | 2 +- crates/bevy_pbr/src/bundle.rs | 2 +- crates/bevy_pbr/src/wireframe.rs | 2 +- crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs | 2 ++ .../bevy_reflect/bevy_reflect_derive/src/impls/structs.rs | 2 ++ .../bevy_reflect_derive/src/impls/tuple_structs.rs | 2 ++ crates/bevy_reflect/src/impls/glam.rs | 2 +- crates/bevy_reflect/src/impls/std.rs | 4 ++-- crates/bevy_reflect/src/struct_trait.rs | 6 +++--- crates/bevy_reflect/src/tuple_struct.rs | 6 +++--- crates/bevy_reflect/src/type_info.rs | 2 +- crates/bevy_reflect/src/type_registry.rs | 4 ++-- crates/bevy_render/src/camera/projection.rs | 2 +- crates/bevy_render/src/mesh/mesh/skinning.rs | 2 +- crates/bevy_render/src/primitives/mod.rs | 2 +- crates/bevy_render/src/view/mod.rs | 2 +- crates/bevy_render/src/view/visibility/mod.rs | 2 +- crates/bevy_render/src/view/visibility/render_layers.rs | 2 +- crates/bevy_sprite/src/mesh2d/mesh.rs | 2 +- crates/bevy_sprite/src/rect.rs | 2 +- crates/bevy_sprite/src/sprite.rs | 2 +- crates/bevy_sprite/src/texture_atlas.rs | 2 +- crates/bevy_text/src/text2d.rs | 2 +- crates/bevy_time/src/time.rs | 2 +- crates/bevy_transform/src/components/global_transform.rs | 2 +- crates/bevy_ui/src/geometry.rs | 2 +- crates/bevy_ui/src/widget/button.rs | 2 +- 35 files changed, 44 insertions(+), 38 deletions(-) diff --git a/crates/bevy_animation/src/lib.rs b/crates/bevy_animation/src/lib.rs index bed3ac717c442..c96cc55e53ace 100644 --- a/crates/bevy_animation/src/lib.rs +++ b/crates/bevy_animation/src/lib.rs @@ -17,7 +17,7 @@ use bevy_ecs::{ }; use bevy_hierarchy::Children; use bevy_math::{Quat, Vec3}; -use bevy_reflect::{Reflect, ReflectTypeName, TypeName, TypeUuid}; +use bevy_reflect::{Reflect, TypeName, TypeUuid}; use bevy_time::Time; use bevy_transform::{prelude::Transform, TransformSystem}; use bevy_utils::{tracing::warn, HashMap}; diff --git a/crates/bevy_asset/src/handle.rs b/crates/bevy_asset/src/handle.rs index e0329281b58cf..abd6e13a98b79 100644 --- a/crates/bevy_asset/src/handle.rs +++ b/crates/bevy_asset/src/handle.rs @@ -10,7 +10,7 @@ use crate::{ Asset, Assets, }; use bevy_ecs::{component::Component, reflect::ReflectComponent}; -use bevy_reflect::{FromReflect, Reflect, ReflectDeserialize, ReflectSerialize, ReflectTypeName}; +use bevy_reflect::{FromReflect, Reflect, ReflectDeserialize, ReflectSerialize}; use bevy_utils::Uuid; use crossbeam_channel::{Receiver, Sender}; use serde::{Deserialize, Serialize}; diff --git a/crates/bevy_core/src/name.rs b/crates/bevy_core/src/name.rs index 56c65aadbd2ac..fe320300fd03d 100644 --- a/crates/bevy_core/src/name.rs +++ b/crates/bevy_core/src/name.rs @@ -1,6 +1,6 @@ use bevy_ecs::{component::Component, reflect::ReflectComponent}; use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::{Reflect, ReflectTypeName}; +use bevy_reflect::Reflect; use bevy_utils::AHasher; use std::{ borrow::Cow, diff --git a/crates/bevy_core_pipeline/src/clear_color.rs b/crates/bevy_core_pipeline/src/clear_color.rs index ec99fdc01cca3..50861e1bebb1f 100644 --- a/crates/bevy_core_pipeline/src/clear_color.rs +++ b/crates/bevy_core_pipeline/src/clear_color.rs @@ -1,6 +1,6 @@ use bevy_derive::{Deref, DerefMut}; use bevy_ecs::prelude::*; -use bevy_reflect::{Reflect, ReflectDeserialize, ReflectSerialize, ReflectTypeName}; +use bevy_reflect::{Reflect, ReflectDeserialize, ReflectSerialize}; use bevy_render::{color::Color, extract_resource::ExtractResource}; use serde::{Deserialize, Serialize}; diff --git a/crates/bevy_core_pipeline/src/core_2d/camera_2d.rs b/crates/bevy_core_pipeline/src/core_2d/camera_2d.rs index 2fedae20e9c63..b94b59a0b6525 100644 --- a/crates/bevy_core_pipeline/src/core_2d/camera_2d.rs +++ b/crates/bevy_core_pipeline/src/core_2d/camera_2d.rs @@ -1,6 +1,6 @@ use crate::clear_color::ClearColorConfig; use bevy_ecs::{prelude::*, query::QueryItem}; -use bevy_reflect::{Reflect, ReflectTypeName}; +use bevy_reflect::Reflect; use bevy_render::{ camera::{Camera, CameraProjection, CameraRenderGraph, OrthographicProjection}, extract_component::ExtractComponent, diff --git a/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs b/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs index 17291bd1a0d17..ce91c2d2e04a8 100644 --- a/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs +++ b/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs @@ -1,6 +1,6 @@ use crate::clear_color::ClearColorConfig; use bevy_ecs::{prelude::*, query::QueryItem}; -use bevy_reflect::{Reflect, ReflectDeserialize, ReflectSerialize, ReflectTypeName}; +use bevy_reflect::{Reflect, ReflectDeserialize, ReflectSerialize}; use bevy_render::{ camera::{Camera, CameraRenderGraph, Projection}, extract_component::ExtractComponent, diff --git a/crates/bevy_gltf/src/lib.rs b/crates/bevy_gltf/src/lib.rs index fc0d9f63c7e52..70e5e3f5c2e81 100644 --- a/crates/bevy_gltf/src/lib.rs +++ b/crates/bevy_gltf/src/lib.rs @@ -9,7 +9,7 @@ use bevy_app::prelude::*; use bevy_asset::{AddAsset, Handle}; use bevy_ecs::{prelude::Component, reflect::ReflectComponent}; use bevy_pbr::StandardMaterial; -use bevy_reflect::{Reflect, ReflectTypeName, TypeName, TypeUuid}; +use bevy_reflect::{Reflect, TypeName, TypeUuid}; use bevy_render::mesh::Mesh; use bevy_scene::Scene; diff --git a/crates/bevy_hierarchy/src/components/children.rs b/crates/bevy_hierarchy/src/components/children.rs index 8d0bdebd9f387..e9e3b72654709 100644 --- a/crates/bevy_hierarchy/src/components/children.rs +++ b/crates/bevy_hierarchy/src/components/children.rs @@ -5,7 +5,7 @@ use bevy_ecs::{ reflect::{ReflectComponent, ReflectMapEntities}, world::World, }; -use bevy_reflect::{Reflect, ReflectTypeName}; +use bevy_reflect::Reflect; use core::slice; use smallvec::SmallVec; use std::ops::Deref; diff --git a/crates/bevy_hierarchy/src/components/parent.rs b/crates/bevy_hierarchy/src/components/parent.rs index 0c3a2f8ac976d..d4a5e2f3bec70 100644 --- a/crates/bevy_hierarchy/src/components/parent.rs +++ b/crates/bevy_hierarchy/src/components/parent.rs @@ -4,7 +4,7 @@ use bevy_ecs::{ reflect::{ReflectComponent, ReflectMapEntities}, world::{FromWorld, World}, }; -use bevy_reflect::{Reflect, ReflectTypeName}; +use bevy_reflect::Reflect; use std::ops::Deref; /// Holds a reference to the parent entity of this entity. diff --git a/crates/bevy_pbr/src/bundle.rs b/crates/bevy_pbr/src/bundle.rs index b578d397742d4..0bd720d11ea06 100644 --- a/crates/bevy_pbr/src/bundle.rs +++ b/crates/bevy_pbr/src/bundle.rs @@ -1,7 +1,7 @@ use crate::{DirectionalLight, Material, PointLight, SpotLight, StandardMaterial}; use bevy_asset::Handle; use bevy_ecs::{bundle::Bundle, component::Component, reflect::ReflectComponent}; -use bevy_reflect::{Reflect, ReflectTypeName}; +use bevy_reflect::Reflect; use bevy_render::{ mesh::Mesh, primitives::{CubemapFrusta, Frustum}, diff --git a/crates/bevy_pbr/src/wireframe.rs b/crates/bevy_pbr/src/wireframe.rs index ef0aed58b53b6..6d08adb3025ad 100644 --- a/crates/bevy_pbr/src/wireframe.rs +++ b/crates/bevy_pbr/src/wireframe.rs @@ -5,7 +5,7 @@ use bevy_asset::{load_internal_asset, Handle, HandleUntyped}; use bevy_core_pipeline::core_3d::Opaque3d; use bevy_ecs::{prelude::*, reflect::ReflectComponent}; use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::{Reflect, ReflectTypeName, TypeUuid}; +use bevy_reflect::{Reflect, TypeUuid}; use bevy_render::Extract; use bevy_render::{ extract_resource::{ExtractResource, ExtractResourcePlugin}, diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs index a00de24e9432f..3801a140bf6df 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs @@ -202,6 +202,8 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> TokenStream { #[inline] fn apply(&mut self, #ref_value: &dyn #bevy_reflect_path::Reflect) { + use #bevy_reflect_path::ReflectTypeName; + if let #bevy_reflect_path::ReflectRef::Enum(#ref_value) = #ref_value.reflect_ref() { if #bevy_reflect_path::Enum::variant_name(self) == #ref_value.variant_name() { // Same variant -> just update fields diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs index 3799719e4fe04..fbd709a84efd9 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs @@ -127,6 +127,8 @@ pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> TokenStream { } fn clone_dynamic(&self) -> #bevy_reflect_path::DynamicStruct { + use #bevy_reflect_path::ReflectTypeName; + let mut dynamic = #bevy_reflect_path::DynamicStruct::default(); dynamic.set_name(self.type_name().to_string()); #(dynamic.insert_boxed(#field_names, self.#field_idents.clone_value());)* diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs index 3ec009efa81d9..13534b9ff71fa 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs @@ -89,6 +89,8 @@ pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> TokenStream { } fn clone_dynamic(&self) -> #bevy_reflect_path::DynamicTupleStruct { + use #bevy_reflect_path::ReflectTypeName; + let mut dynamic = #bevy_reflect_path::DynamicTupleStruct::default(); dynamic.set_name(self.type_name().to_string()); #(dynamic.insert_boxed(self.#field_idents.clone_value());)* diff --git a/crates/bevy_reflect/src/impls/glam.rs b/crates/bevy_reflect/src/impls/glam.rs index c6a8fd3140ee6..c84fcbffaaf27 100644 --- a/crates/bevy_reflect/src/impls/glam.rs +++ b/crates/bevy_reflect/src/impls/glam.rs @@ -1,7 +1,7 @@ use crate as bevy_reflect; use crate::prelude::ReflectDefault; use crate::reflect::Reflect; -use crate::{ReflectDeserialize, ReflectSerialize, ReflectTypeName}; +use crate::{ReflectDeserialize, ReflectSerialize}; use bevy_reflect_derive::{impl_from_reflect_value, impl_reflect_struct, impl_reflect_value}; use glam::*; diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index 0d31f22f4801b..56a39c10b77d3 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -846,8 +846,8 @@ impl FromReflect for Cow<'static, str> { mod tests { use crate as bevy_reflect; use crate::{ - Enum, FromReflect, Reflect, ReflectSerialize, ReflectTypeName, TypeInfo, TypeRegistry, - Typed, VariantInfo, VariantType, + Enum, FromReflect, Reflect, ReflectSerialize, TypeInfo, TypeRegistry, Typed, VariantInfo, + VariantType, }; use bevy_utils::{HashMap, Instant}; use std::f32::consts::{PI, TAU}; diff --git a/crates/bevy_reflect/src/struct_trait.rs b/crates/bevy_reflect/src/struct_trait.rs index aa8b021254577..8b65be517ddb2 100644 --- a/crates/bevy_reflect/src/struct_trait.rs +++ b/crates/bevy_reflect/src/struct_trait.rs @@ -21,7 +21,7 @@ use std::{ /// # Example /// /// ``` -/// use bevy_reflect::{Reflect, Struct, ReflectTypeName}; +/// use bevy_reflect::{Reflect, Struct}; /// /// #[derive(Reflect)] /// struct Foo { @@ -185,7 +185,7 @@ impl<'a> ExactSizeIterator for FieldIter<'a> {} /// # Example /// /// ``` -/// use bevy_reflect::{GetField, Reflect, ReflectTypeName}; +/// use bevy_reflect::{GetField, Reflect}; /// /// #[derive(Reflect)] /// struct Foo { @@ -478,7 +478,7 @@ pub fn struct_partial_eq(a: &S, b: &dyn Reflect) -> Option { /// /// # Example /// ``` -/// use bevy_reflect::{Reflect, ReflectTypeName}; +/// use bevy_reflect::Reflect; /// #[derive(Reflect)] /// struct MyStruct { /// foo: usize diff --git a/crates/bevy_reflect/src/tuple_struct.rs b/crates/bevy_reflect/src/tuple_struct.rs index 9b7ec287b6d84..6823c52275dcc 100644 --- a/crates/bevy_reflect/src/tuple_struct.rs +++ b/crates/bevy_reflect/src/tuple_struct.rs @@ -15,7 +15,7 @@ use std::slice::Iter; /// `#[derive(Reflect)]`. /// /// ``` -/// use bevy_reflect::{Reflect, ReflectTypeName, TupleStruct}; +/// use bevy_reflect::{Reflect,TupleStruct}; /// /// #[derive(Reflect)] /// struct Foo(String); @@ -142,7 +142,7 @@ impl<'a> ExactSizeIterator for TupleStructFieldIter<'a> {} /// # Example /// /// ``` -/// use bevy_reflect::{GetTupleStructField, Reflect, ReflectTypeName}; +/// use bevy_reflect::{GetTupleStructField, Reflect}; /// /// #[derive(Reflect)] /// struct Foo(String); @@ -384,7 +384,7 @@ pub fn tuple_struct_partial_eq(a: &S, b: &dyn Reflect) -> Option /// /// # Example /// ``` -/// use bevy_reflect::{Reflect, ReflectTypeName}; +/// use bevy_reflect::Reflect; /// #[derive(Reflect)] /// struct MyTupleStruct(usize); /// diff --git a/crates/bevy_reflect/src/type_info.rs b/crates/bevy_reflect/src/type_info.rs index e55aadc2baea8..af71a09ac412c 100644 --- a/crates/bevy_reflect/src/type_info.rs +++ b/crates/bevy_reflect/src/type_info.rs @@ -23,7 +23,7 @@ use std::any::{Any, TypeId}; /// /// ``` /// # use std::any::Any; -/// # use bevy_reflect::{NamedField, Reflect, ReflectMut, ReflectRef, StructInfo, TypeInfo, TypeName, ValueInfo, ReflectTypeName}; +/// # use bevy_reflect::{NamedField, Reflect, ReflectMut, ReflectRef, StructInfo, TypeInfo, TypeName, ValueInfo}; /// # use bevy_reflect::utility::NonGenericTypeInfoCell; /// use bevy_reflect::Typed; /// diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index 29e6bb59998b5..74865abeb0c91 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -452,7 +452,7 @@ impl Deserialize<'a> + Reflect> FromType for ReflectDeserialize { /// /// # Example /// ```rust -/// use bevy_reflect::{TypeRegistry, Reflect, ReflectTypeName, ReflectFromPtr}; +/// use bevy_reflect::{TypeRegistry, Reflect, ReflectFromPtr}; /// use bevy_ptr::Ptr; /// use std::ptr::NonNull; /// @@ -524,7 +524,7 @@ impl FromType for ReflectFromPtr { mod test { use std::ptr::NonNull; - use crate::{GetTypeRegistration, ReflectFromPtr, ReflectTypeName, TypeRegistration}; + use crate::{GetTypeRegistration, ReflectFromPtr, TypeRegistration}; use bevy_ptr::{Ptr, PtrMut}; use bevy_utils::HashMap; diff --git a/crates/bevy_render/src/camera/projection.rs b/crates/bevy_render/src/camera/projection.rs index fa6d6c4b8da82..592b4cc8f916b 100644 --- a/crates/bevy_render/src/camera/projection.rs +++ b/crates/bevy_render/src/camera/projection.rs @@ -5,7 +5,7 @@ use bevy_ecs::{prelude::*, reflect::ReflectComponent}; use bevy_math::Mat4; use bevy_reflect::{ std_traits::ReflectDefault, FromReflect, GetTypeRegistration, Reflect, ReflectDeserialize, - ReflectSerialize, ReflectTypeName, + ReflectSerialize, }; use bevy_window::ModifiesWindows; use serde::{Deserialize, Serialize}; diff --git a/crates/bevy_render/src/mesh/mesh/skinning.rs b/crates/bevy_render/src/mesh/mesh/skinning.rs index aa2e5c134f9cd..31837a51b7d77 100644 --- a/crates/bevy_render/src/mesh/mesh/skinning.rs +++ b/crates/bevy_render/src/mesh/mesh/skinning.rs @@ -6,7 +6,7 @@ use bevy_ecs::{ reflect::ReflectMapEntities, }; use bevy_math::Mat4; -use bevy_reflect::{Reflect, ReflectTypeName, TypeName, TypeUuid}; +use bevy_reflect::{Reflect, TypeName, TypeUuid}; use std::ops::Deref; #[derive(Component, Debug, Default, Clone, Reflect)] diff --git a/crates/bevy_render/src/primitives/mod.rs b/crates/bevy_render/src/primitives/mod.rs index 8c312d4f5d227..ae82c844be6ce 100644 --- a/crates/bevy_render/src/primitives/mod.rs +++ b/crates/bevy_render/src/primitives/mod.rs @@ -1,6 +1,6 @@ use bevy_ecs::{component::Component, reflect::ReflectComponent}; use bevy_math::{Mat4, Vec3, Vec3A, Vec4, Vec4Swizzles}; -use bevy_reflect::{Reflect, ReflectTypeName}; +use bevy_reflect::Reflect; /// An Axis-Aligned Bounding Box #[derive(Component, Clone, Debug, Default, Reflect)] diff --git a/crates/bevy_render/src/view/mod.rs b/crates/bevy_render/src/view/mod.rs index 3535dbb03e4be..55ca6a31b6c23 100644 --- a/crates/bevy_render/src/view/mod.rs +++ b/crates/bevy_render/src/view/mod.rs @@ -22,7 +22,7 @@ use crate::{ use bevy_app::{App, Plugin}; use bevy_ecs::prelude::*; use bevy_math::{Mat4, Vec3}; -use bevy_reflect::{Reflect, ReflectTypeName}; +use bevy_reflect::Reflect; use bevy_transform::components::GlobalTransform; use bevy_utils::HashMap; diff --git a/crates/bevy_render/src/view/visibility/mod.rs b/crates/bevy_render/src/view/visibility/mod.rs index 5663379a5a4b0..bf7b110b1277e 100644 --- a/crates/bevy_render/src/view/visibility/mod.rs +++ b/crates/bevy_render/src/view/visibility/mod.rs @@ -7,7 +7,7 @@ use bevy_asset::{Assets, Handle}; use bevy_ecs::prelude::*; use bevy_hierarchy::{Children, Parent}; use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::{Reflect, ReflectTypeName}; +use bevy_reflect::Reflect; use bevy_transform::components::GlobalTransform; use bevy_transform::TransformSystem; use std::cell::Cell; diff --git a/crates/bevy_render/src/view/visibility/render_layers.rs b/crates/bevy_render/src/view/visibility/render_layers.rs index b8774f9eb4fc3..677c0877777ba 100644 --- a/crates/bevy_render/src/view/visibility/render_layers.rs +++ b/crates/bevy_render/src/view/visibility/render_layers.rs @@ -1,6 +1,6 @@ use bevy_ecs::prelude::{Component, ReflectComponent}; use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::{Reflect, ReflectTypeName}; +use bevy_reflect::Reflect; type LayerMask = u32; diff --git a/crates/bevy_sprite/src/mesh2d/mesh.rs b/crates/bevy_sprite/src/mesh2d/mesh.rs index 73d3407f8a137..18513f0d5362d 100644 --- a/crates/bevy_sprite/src/mesh2d/mesh.rs +++ b/crates/bevy_sprite/src/mesh2d/mesh.rs @@ -5,7 +5,7 @@ use bevy_ecs::{ system::{lifetimeless::*, SystemParamItem, SystemState}, }; use bevy_math::{Mat4, Vec2}; -use bevy_reflect::{Reflect, ReflectTypeName, TypeUuid}; +use bevy_reflect::{Reflect, TypeUuid}; use bevy_render::{ extract_component::{ComponentUniforms, DynamicUniformIndex, UniformComponentPlugin}, mesh::{GpuBufferInfo, Mesh, MeshVertexBufferLayout}, diff --git a/crates/bevy_sprite/src/rect.rs b/crates/bevy_sprite/src/rect.rs index 30cf2d2808eab..3a7fb2a04dd26 100644 --- a/crates/bevy_sprite/src/rect.rs +++ b/crates/bevy_sprite/src/rect.rs @@ -1,5 +1,5 @@ use bevy_math::Vec2; -use bevy_reflect::{Reflect, ReflectTypeName}; +use bevy_reflect::Reflect; /// A rectangle defined by two points. There is no defined origin, so 0,0 could be anywhere /// (top-left, bottom-left, etc) diff --git a/crates/bevy_sprite/src/sprite.rs b/crates/bevy_sprite/src/sprite.rs index eaac2e9952dc9..56dc1b86c935d 100644 --- a/crates/bevy_sprite/src/sprite.rs +++ b/crates/bevy_sprite/src/sprite.rs @@ -1,6 +1,6 @@ use bevy_ecs::component::Component; use bevy_math::Vec2; -use bevy_reflect::{Reflect, ReflectTypeName}; +use bevy_reflect::Reflect; use bevy_render::color::Color; #[derive(Component, Debug, Default, Clone, Reflect)] diff --git a/crates/bevy_sprite/src/texture_atlas.rs b/crates/bevy_sprite/src/texture_atlas.rs index 3dbd74edb6372..d0a326648f533 100644 --- a/crates/bevy_sprite/src/texture_atlas.rs +++ b/crates/bevy_sprite/src/texture_atlas.rs @@ -2,7 +2,7 @@ use crate::{Anchor, Rect}; use bevy_asset::Handle; use bevy_ecs::component::Component; use bevy_math::Vec2; -use bevy_reflect::{Reflect, ReflectTypeName, TypeName, TypeUuid}; +use bevy_reflect::{Reflect, TypeName, TypeUuid}; use bevy_render::{color::Color, texture::Image}; use bevy_utils::HashMap; diff --git a/crates/bevy_text/src/text2d.rs b/crates/bevy_text/src/text2d.rs index 98b90aec27eb9..dd4a5b63f5a23 100644 --- a/crates/bevy_text/src/text2d.rs +++ b/crates/bevy_text/src/text2d.rs @@ -9,7 +9,7 @@ use bevy_ecs::{ system::{Local, Query, Res, ResMut}, }; use bevy_math::{Vec2, Vec3}; -use bevy_reflect::{Reflect, ReflectTypeName}; +use bevy_reflect::Reflect; use bevy_render::{ prelude::Color, texture::Image, diff --git a/crates/bevy_time/src/time.rs b/crates/bevy_time/src/time.rs index 93d1722d4ffd8..1835f841c93a7 100644 --- a/crates/bevy_time/src/time.rs +++ b/crates/bevy_time/src/time.rs @@ -1,5 +1,5 @@ use bevy_ecs::{reflect::ReflectResource, system::Resource}; -use bevy_reflect::{FromReflect, Reflect, ReflectTypeName}; +use bevy_reflect::{FromReflect, Reflect}; use bevy_utils::{Duration, Instant}; /// Tracks elapsed time since the last update and since the App has started diff --git a/crates/bevy_transform/src/components/global_transform.rs b/crates/bevy_transform/src/components/global_transform.rs index b20e8eaf0b4e0..f1129f8681116 100644 --- a/crates/bevy_transform/src/components/global_transform.rs +++ b/crates/bevy_transform/src/components/global_transform.rs @@ -3,7 +3,7 @@ use std::ops::Mul; use super::Transform; use bevy_ecs::{component::Component, reflect::ReflectComponent}; use bevy_math::{Affine3A, Mat4, Quat, Vec3, Vec3A}; -use bevy_reflect::{Reflect, ReflectTypeName}; +use bevy_reflect::Reflect; /// Describe the position of an entity relative to the reference frame. /// diff --git a/crates/bevy_ui/src/geometry.rs b/crates/bevy_ui/src/geometry.rs index fda47b3a5c4b6..bf0220eb3197d 100644 --- a/crates/bevy_ui/src/geometry.rs +++ b/crates/bevy_ui/src/geometry.rs @@ -1,6 +1,6 @@ use crate::Val; use bevy_math::Vec2; -use bevy_reflect::{Reflect, ReflectTypeName}; +use bevy_reflect::Reflect; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; /// A type which is commonly used to define positions, margins, paddings and borders. diff --git a/crates/bevy_ui/src/widget/button.rs b/crates/bevy_ui/src/widget/button.rs index 468d8e39f6700..6c7dced0f3bb0 100644 --- a/crates/bevy_ui/src/widget/button.rs +++ b/crates/bevy_ui/src/widget/button.rs @@ -1,7 +1,7 @@ use bevy_ecs::prelude::Component; use bevy_ecs::reflect::ReflectComponent; use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::{Reflect, ReflectTypeName}; +use bevy_reflect::Reflect; /// Marker struct for buttons #[derive(Component, Debug, Default, Clone, Copy, Reflect)] From 140e0092b5ffdc85285e1204e9511133de2d1666 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sat, 27 Aug 2022 13:59:42 +0200 Subject: [PATCH 12/87] drop Cow in TypeName --- .../src/impls/type_name.rs | 10 +- crates/bevy_reflect/src/array.rs | 4 +- crates/bevy_reflect/src/enums/dynamic_enum.rs | 4 +- crates/bevy_reflect/src/impls/smallvec.rs | 2 +- crates/bevy_reflect/src/impls/std.rs | 20 +-- crates/bevy_reflect/src/lib.rs | 12 +- crates/bevy_reflect/src/list.rs | 4 +- crates/bevy_reflect/src/map.rs | 4 +- crates/bevy_reflect/src/serde/ser.rs | 16 +-- crates/bevy_reflect/src/struct_trait.rs | 4 +- crates/bevy_reflect/src/tuple.rs | 4 +- crates/bevy_reflect/src/tuple_struct.rs | 4 +- crates/bevy_reflect/src/type_name.rs | 28 +++-- crates/bevy_reflect/src/utility.rs | 115 ++++++++++-------- 14 files changed, 124 insertions(+), 107 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs index ba34084618676..2983455386cf1 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs @@ -56,12 +56,14 @@ pub(crate) fn impl_type_name( }; quote! { - let name = format!(concat!("{}<", #brackets, ">"), BASE_NAME, #values); - std::borrow::Cow::Owned(name) + static CELL: #bevy_reflect_path::utility::GenericTypeNameCell = #bevy_reflect_path::utility::GenericTypeNameCell::new(); + CELL.get_or_insert::(|| { + format!(concat!("{}<", #brackets, ">"), BASE_NAME, #values) + }) } } else { quote! { - std::borrow::Cow::Borrowed(BASE_NAME) + BASE_NAME } }; @@ -69,7 +71,7 @@ pub(crate) fn impl_type_name( quote! { impl #impl_generics #bevy_reflect_path::TypeName for #type_name #ty_generics #where_clause { - fn name() -> std::borrow::Cow<'static, str> { + fn name() -> &'static str { const BASE_NAME: &'static str = #base_name; #get_type_name } diff --git a/crates/bevy_reflect/src/array.rs b/crates/bevy_reflect/src/array.rs index 50753a1088763..a82d15c576757 100644 --- a/crates/bevy_reflect/src/array.rs +++ b/crates/bevy_reflect/src/array.rs @@ -153,8 +153,8 @@ impl DynamicArray { } impl ReflectTypeName for DynamicArray { - fn type_name(&self) -> std::borrow::Cow { - self.name.as_str().into() + fn type_name(&self) -> &str { + self.name.as_str() } } diff --git a/crates/bevy_reflect/src/enums/dynamic_enum.rs b/crates/bevy_reflect/src/enums/dynamic_enum.rs index 583f852fa33f6..a809b6520220d 100644 --- a/crates/bevy_reflect/src/enums/dynamic_enum.rs +++ b/crates/bevy_reflect/src/enums/dynamic_enum.rs @@ -162,8 +162,8 @@ impl DynamicEnum { } impl ReflectTypeName for DynamicEnum { - fn type_name(&self) -> std::borrow::Cow { - self.name.as_str().into() + fn type_name(&self) -> &str { + self.name.as_str() } } diff --git a/crates/bevy_reflect/src/impls/smallvec.rs b/crates/bevy_reflect/src/impls/smallvec.rs index dd04c2c2b9aec..1aa691b043bc1 100644 --- a/crates/bevy_reflect/src/impls/smallvec.rs +++ b/crates/bevy_reflect/src/impls/smallvec.rs @@ -9,7 +9,7 @@ use crate::{ TypeRegistration, Typed, }; -impl_type_name!(SmallVec); +impl_type_name!(SmallVec); impl Array for SmallVec where diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index 56a39c10b77d3..1da30c294f4d5 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -7,7 +7,7 @@ use crate::{ VariantFieldIter, VariantInfo, VariantType, }; -use crate::utility::{GenericTypeInfoCell, NonGenericTypeInfoCell}; +use crate::utility::{GenericTypeInfoCell, GenericTypeNameCell, NonGenericTypeInfoCell}; use bevy_reflect_derive::{impl_from_reflect_value, impl_reflect_value, impl_type_name}; use bevy_utils::{Duration, HashMap, HashSet, Instant}; use std::{ @@ -90,22 +90,22 @@ impl_from_reflect_value!(NonZeroU16); impl_from_reflect_value!(NonZeroU8); impl_from_reflect_value!(NonZeroI8); -impl_type_name!(Vec); -impl_type_name!(HashMap); -impl_type_name!(Option); +impl_type_name!(Vec); +impl_type_name!(HashMap); +impl_type_name!(Option); // impl_type_name expecte a type name followed by generic between `<` and `>`. // so array is manually implemented. -impl TypeName for [T; N] { - fn name() -> Cow<'static, str> { - let s = format!("[{}; {N}]", T::name()); - Cow::Owned(s) +impl TypeName for [T; N] { + fn name() -> &'static str { + static CELL: GenericTypeNameCell = GenericTypeNameCell::new(); + CELL.get_or_insert::(|| format!("[{}; {N}]", T::name())) } } impl TypeName for Cow<'static, str> { - fn name() -> Cow<'static, str> { - Cow::Borrowed("Cow<'static, str>") + fn name() -> &'static str { + "Cow<'static, str>" } } diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index 0344974ea5f70..8d11abffe2cb1 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -925,15 +925,15 @@ bevy_reflect::tests::Test { struct Foo; let foo = Foo; let name = foo.type_name(); - assert_eq!(name.as_ref(), "bevy_reflect::tests::Foo"); + assert_eq!(name, "bevy_reflect::tests::Foo"); #[derive(TypeName)] - struct Goo { + struct Goo { _value: T, } let goo = Goo { _value: 42u32 }; let name = goo.type_name(); - assert_eq!(name.as_ref(), "bevy_reflect::tests::Goo"); + assert_eq!(name, "bevy_reflect::tests::Goo"); } #[test] @@ -945,16 +945,16 @@ bevy_reflect::tests::Test { struct Foo; let foo = Foo; let name = foo.type_name(); - assert_eq!(name.as_ref(), "Banane"); + assert_eq!(name, "Banane"); #[derive(TypeName)] #[type_name("MyType")] - struct Goo { + struct Goo { _value: T, } let goo = Goo { _value: 42u32 }; let name = goo.type_name(); - assert_eq!(name.as_ref(), "MyType"); + assert_eq!(name, "MyType"); } #[cfg(feature = "glam")] diff --git a/crates/bevy_reflect/src/list.rs b/crates/bevy_reflect/src/list.rs index 1a5be2da9ac07..346f19502bbbf 100644 --- a/crates/bevy_reflect/src/list.rs +++ b/crates/bevy_reflect/src/list.rs @@ -115,8 +115,8 @@ impl DynamicList { } impl ReflectTypeName for DynamicList { - fn type_name(&self) -> std::borrow::Cow { - self.name.as_str().into() + fn type_name(&self) -> &str { + self.name.as_str() } } diff --git a/crates/bevy_reflect/src/map.rs b/crates/bevy_reflect/src/map.rs index c198010b9e456..f2ba01a1f51c8 100644 --- a/crates/bevy_reflect/src/map.rs +++ b/crates/bevy_reflect/src/map.rs @@ -166,8 +166,8 @@ impl DynamicMap { } impl ReflectTypeName for DynamicMap { - fn type_name(&self) -> std::borrow::Cow { - self.name.as_str().into() + fn type_name(&self) -> &str { + self.name.as_str() } } diff --git a/crates/bevy_reflect/src/serde/ser.rs b/crates/bevy_reflect/src/serde/ser.rs index b72904a428b93..0991ee045a7a7 100644 --- a/crates/bevy_reflect/src/serde/ser.rs +++ b/crates/bevy_reflect/src/serde/ser.rs @@ -110,7 +110,7 @@ impl<'a> Serialize for ReflectValueSerializer<'a> { S: serde::Serializer, { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.value.type_name().as_ref())?; + state.serialize_entry(type_fields::TYPE, self.value.type_name())?; state.serialize_entry( type_fields::VALUE, get_serializable::(self.value, self.registry)?.borrow(), @@ -131,7 +131,7 @@ impl<'a> Serialize for StructSerializer<'a> { { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.struct_value.type_name().as_ref())?; + state.serialize_entry(type_fields::TYPE, self.struct_value.type_name())?; state.serialize_entry( type_fields::STRUCT, &StructValueSerializer { @@ -174,7 +174,7 @@ impl<'a> Serialize for TupleStructSerializer<'a> { { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.tuple_struct.type_name().as_ref())?; + state.serialize_entry(type_fields::TYPE, self.tuple_struct.type_name())?; state.serialize_entry( type_fields::TUPLE_STRUCT, &TupleStructValueSerializer { @@ -216,7 +216,7 @@ impl<'a> Serialize for EnumSerializer<'a> { { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.enum_value.type_name().as_ref())?; + state.serialize_entry(type_fields::TYPE, self.enum_value.type_name())?; state.serialize_entry( type_fields::ENUM, &EnumValueSerializer { @@ -327,7 +327,7 @@ impl<'a> Serialize for TupleSerializer<'a> { { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.tuple.type_name().as_ref())?; + state.serialize_entry(type_fields::TYPE, self.tuple.type_name())?; state.serialize_entry( type_fields::TUPLE, &TupleValueSerializer { @@ -369,7 +369,7 @@ impl<'a> Serialize for MapSerializer<'a> { { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.map.type_name().as_ref())?; + state.serialize_entry(type_fields::TYPE, self.map.type_name())?; state.serialize_entry( type_fields::MAP, &MapValueSerializer { @@ -413,7 +413,7 @@ impl<'a> Serialize for ListSerializer<'a> { S: serde::Serializer, { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.list.type_name().as_ref())?; + state.serialize_entry(type_fields::TYPE, self.list.type_name())?; state.serialize_entry( type_fields::LIST, &ListValueSerializer { @@ -454,7 +454,7 @@ impl<'a> Serialize for ArraySerializer<'a> { S: serde::Serializer, { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.array.type_name().as_ref())?; + state.serialize_entry(type_fields::TYPE, self.array.type_name())?; state.serialize_entry( type_fields::ARRAY, &ArrayValueSerializer { diff --git a/crates/bevy_reflect/src/struct_trait.rs b/crates/bevy_reflect/src/struct_trait.rs index 8b65be517ddb2..be61b7606e364 100644 --- a/crates/bevy_reflect/src/struct_trait.rs +++ b/crates/bevy_reflect/src/struct_trait.rs @@ -286,8 +286,8 @@ impl DynamicStruct { } impl ReflectTypeName for DynamicStruct { - fn type_name(&self) -> std::borrow::Cow { - self.name.as_str().into() + fn type_name(&self) -> &str { + self.name.as_str() } } diff --git a/crates/bevy_reflect/src/tuple.rs b/crates/bevy_reflect/src/tuple.rs index b46dbbd1a4f27..bf09676657163 100644 --- a/crates/bevy_reflect/src/tuple.rs +++ b/crates/bevy_reflect/src/tuple.rs @@ -230,8 +230,8 @@ impl DynamicTuple { } impl ReflectTypeName for DynamicTuple { - fn type_name(&self) -> std::borrow::Cow { - self.name.as_str().into() + fn type_name(&self) -> &str { + self.name.as_str() } } diff --git a/crates/bevy_reflect/src/tuple_struct.rs b/crates/bevy_reflect/src/tuple_struct.rs index 6823c52275dcc..9f4bc68058ed2 100644 --- a/crates/bevy_reflect/src/tuple_struct.rs +++ b/crates/bevy_reflect/src/tuple_struct.rs @@ -218,8 +218,8 @@ impl DynamicTupleStruct { } impl ReflectTypeName for DynamicTupleStruct { - fn type_name(&self) -> std::borrow::Cow { - self.name.as_str().into() + fn type_name(&self) -> &str { + self.name.as_str() } } diff --git a/crates/bevy_reflect/src/type_name.rs b/crates/bevy_reflect/src/type_name.rs index f7ac802a8a202..16049cac45dd7 100644 --- a/crates/bevy_reflect/src/type_name.rs +++ b/crates/bevy_reflect/src/type_name.rs @@ -1,20 +1,20 @@ -use std::borrow::Cow; +use crate::utility::GenericTypeNameCell; /// Provide the name of the type as string. pub trait TypeName { - fn name() -> Cow<'static, str>; + fn name() -> &'static str; } /// An object-safe version of [`TypeName`]. -/// +/// /// Automatically implemented via blanket implementation. pub trait ReflectTypeName { - fn type_name(&self) -> Cow; + fn type_name(&self) -> &str; } impl ReflectTypeName for T { #[inline] - fn type_name(&self) -> Cow { + fn type_name(&self) -> &str { Self::name() } } @@ -23,15 +23,17 @@ macro_rules! impl_type_name_tuple { ( $($t:tt),* ) => { - impl<$($t: TypeName),*> TypeName for ($($t,)*) { + impl<$($t: TypeName + 'static),*> TypeName for ($($t,)*) { #[allow(non_snake_case)] - fn name() -> Cow<'static, str> { - $(let $t = <$t as TypeName>::name();)* - let s = format!( - concat!("(", impl_type_name_tuple!(@bracket $($t),*), ")"), - $($t,)* - ); - Cow::Owned(s) + fn name() -> &'static str { + static CELL: GenericTypeNameCell = GenericTypeNameCell::new(); + CELL.get_or_insert::(|| { + $(let $t = <$t as TypeName>::name();)* + format!( + concat!("(", impl_type_name_tuple!(@bracket $($t),*), ")"), + $($t,)* + ) + }) } } }; diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index cbedd5aaff219..b3957dd34eade 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -6,6 +6,67 @@ use once_cell::race::OnceBox; use parking_lot::RwLock; use std::any::{Any, TypeId}; +/// A container over non-generic types, allowing instances to be stored statically. +/// +/// This is specifically meant for use with _non_-generic types. If your type _is_ generic, +/// then use [`GenericDataCell`] instead. Otherwise, it will not take into account all +/// monomorphizations of your type. +pub struct NonGenericDataCell(OnceBox); + +impl NonGenericDataCell { + /// Initialize a [`NonGenericDataCell`] for non-generic types. + pub const fn new() -> Self { + Self(OnceBox::new()) + } + + /// Returns a reference to the `Data` stored in the cell. + /// + /// If there is no `Data` found, a new one will be generated from the given function. + pub fn get_or_set(&self, f: F) -> &Data + where + F: FnOnce() -> Data, + { + self.0.get_or_init(|| Box::new(f())) + } +} + +/// A container over generic types, allowing instances to be stored statically. +/// +/// This is specifically meant for use with generic types. If your type isn't generic, +/// then use [`NonGenericDataCell`] instead as it should be much more performant. +pub struct GenericDataCell(OnceBox>>); + +impl GenericDataCell { + /// Initialize a [`GenericDataCell`] for generic types. + pub const fn new() -> Self { + Self(OnceBox::new()) + } + + /// Returns a reference to the `Data` stored in the cell. + /// + /// This method will then return the correct `Data` reference for the given type `T`. + /// If there is no `Data` found, a new one will be generated from the given function. + pub fn get_or_insert(&self, f: F) -> &Data + where + T: Any + ?Sized, + F: FnOnce() -> Data, + { + let type_id = TypeId::of::(); + let mapping = self.0.get_or_init(|| Box::new(RwLock::default())); + if let Some(info) = mapping.read().get(&type_id) { + return info; + } + + mapping.write().entry(type_id).or_insert_with(|| { + // We leak here in order to obtain a `&'static` reference. + // Otherwise, we won't be able to return a reference due to the `RwLock`. + // This should be okay, though, since we expect it to remain statically + // available over the course of the application. + Box::leak(Box::new(f())) + }) + } +} + /// A container for [`TypeInfo`] over non-generic types, allowing instances to be stored statically. /// /// This is specifically meant for use with _non_-generic types. If your type _is_ generic, @@ -51,26 +112,7 @@ use std::any::{Any, TypeId}; /// # fn clone_value(&self) -> Box { todo!() } /// # } /// ``` -pub struct NonGenericTypeInfoCell(OnceBox); - -impl NonGenericTypeInfoCell { - /// Initialize a [`NonGenericTypeInfoCell`] for non-generic types. - pub const fn new() -> Self { - Self(OnceBox::new()) - } - - /// Returns a reference to the [`TypeInfo`] stored in the cell. - /// - /// If there is no [`TypeInfo`] found, a new one will be generated from the given function. - /// - /// [`TypeInfos`]: TypeInfo - pub fn get_or_set(&self, f: F) -> &TypeInfo - where - F: FnOnce() -> TypeInfo, - { - self.0.get_or_init(|| Box::new(f())) - } -} +pub type NonGenericTypeInfoCell = NonGenericDataCell; /// A container for [`TypeInfo`] over generic types, allowing instances to be stored statically. /// @@ -115,35 +157,6 @@ impl NonGenericTypeInfoCell { /// # fn clone_value(&self) -> Box { todo!() } /// # } /// ``` -pub struct GenericTypeInfoCell(OnceBox>>); - -impl GenericTypeInfoCell { - /// Initialize a [`GenericTypeInfoCell`] for generic types. - pub const fn new() -> Self { - Self(OnceBox::new()) - } +pub type GenericTypeInfoCell = GenericDataCell; - /// Returns a reference to the [`TypeInfo`] stored in the cell. - /// - /// This method will then return the correct [`TypeInfo`] reference for the given type `T`. - /// If there is no [`TypeInfo`] found, a new one will be generated from the given function. - pub fn get_or_insert(&self, f: F) -> &TypeInfo - where - T: Any + ?Sized, - F: FnOnce() -> TypeInfo, - { - let type_id = TypeId::of::(); - let mapping = self.0.get_or_init(|| Box::new(RwLock::default())); - if let Some(info) = mapping.read().get(&type_id) { - return info; - } - - mapping.write().entry(type_id).or_insert_with(|| { - // We leak here in order to obtain a `&'static` reference. - // Otherwise, we won't be able to return a reference due to the `RwLock`. - // This should be okay, though, since we expect it to remain statically - // available over the course of the application. - Box::leak(Box::new(f())) - }) - } -} +pub type GenericTypeNameCell = GenericDataCell; From 6fba583d809da89da21c0e2d2f4834a448dd8204 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sat, 27 Aug 2022 14:34:52 +0200 Subject: [PATCH 13/87] remove majority of `any::type_name` --- .../bevy_reflect_derive/src/from_reflect.rs | 2 +- .../bevy_reflect_derive/src/impls/enums.rs | 2 +- .../bevy_reflect_derive/src/impls/values.rs | 2 +- crates/bevy_reflect/src/array.rs | 12 ++-- crates/bevy_reflect/src/enums/enum_trait.rs | 8 +-- crates/bevy_reflect/src/enums/mod.rs | 14 ++--- crates/bevy_reflect/src/fields.rs | 14 ++--- crates/bevy_reflect/src/impls/smallvec.rs | 12 ++-- crates/bevy_reflect/src/impls/std.rs | 18 +++--- crates/bevy_reflect/src/lib.rs | 63 +++++++------------ crates/bevy_reflect/src/list.rs | 12 ++-- crates/bevy_reflect/src/map.rs | 22 ++++--- crates/bevy_reflect/src/reflect.rs | 1 + crates/bevy_reflect/src/struct_trait.rs | 9 +-- crates/bevy_reflect/src/tuple.rs | 6 +- crates/bevy_reflect/src/tuple_struct.rs | 9 +-- crates/bevy_reflect/src/type_info.rs | 7 ++- crates/bevy_reflect/src/type_registry.rs | 6 +- 18 files changed, 104 insertions(+), 115 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/from_reflect.rs b/crates/bevy_reflect/bevy_reflect_derive/src/from_reflect.rs index 73e4cb6451108..48800bb8ae846 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/from_reflect.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/from_reflect.rs @@ -51,7 +51,7 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> TokenStream { if let #bevy_reflect_path::ReflectRef::Enum(#ref_value) = #ref_value.reflect_ref() { match #ref_value.variant_name() { #(#variant_names => Some(#variant_constructors),)* - name => panic!("variant with name `{}` does not exist on enum `{}`", name, std::any::type_name::()), + name => panic!("variant with name `{}` does not exist on enum `{}`", name, ::name()), } } else { None diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs index 3801a140bf6df..436e59a21147b 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs @@ -227,7 +227,7 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> TokenStream { #(#variant_names => { *self = #variant_constructors })* - name => panic!("variant with name `{}` does not exist on enum `{}`", name, std::any::type_name::()), + name => panic!("variant with name `{}` does not exist on enum `{}`", name, ::name()), } } } else { diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs index 14dc09bd60b39..502adf6a97f30 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs @@ -81,7 +81,7 @@ pub(crate) fn impl_value(meta: &ReflectMeta) -> TokenStream { if let Some(value) = value.downcast_ref::() { *self = value.clone(); } else { - panic!("Value is not {}.", std::any::type_name::()); + panic!("Value is not {}.", ::name()); } } diff --git a/crates/bevy_reflect/src/array.rs b/crates/bevy_reflect/src/array.rs index a82d15c576757..fe32cf8fb6133 100644 --- a/crates/bevy_reflect/src/array.rs +++ b/crates/bevy_reflect/src/array.rs @@ -1,6 +1,6 @@ use crate::{ utility::NonGenericTypeInfoCell, DynamicInfo, Reflect, ReflectMut, ReflectRef, ReflectTypeName, - TypeInfo, Typed, + TypeInfo, TypeName, Typed, }; use std::{ any::{Any, TypeId}, @@ -57,11 +57,11 @@ impl ArrayInfo { /// /// * `capacity`: The maximum capacity of the underlying array. /// - pub fn new(capacity: usize) -> Self { + pub fn new(capacity: usize) -> Self { Self { - type_name: std::any::type_name::(), + type_name: TArray::name(), type_id: TypeId::of::(), - item_type_name: std::any::type_name::(), + item_type_name: TItem::name(), item_type_id: TypeId::of::(), capacity, } @@ -74,7 +74,7 @@ impl ArrayInfo { /// The [type name] of the array. /// - /// [type name]: std::any::type_name + /// [type name]: TypeName pub fn type_name(&self) -> &'static str { self.type_name } @@ -91,7 +91,7 @@ impl ArrayInfo { /// The [type name] of the array item. /// - /// [type name]: std::any::type_name + /// [type name]: TypeName pub fn item_type_name(&self) -> &'static str { self.item_type_name } diff --git a/crates/bevy_reflect/src/enums/enum_trait.rs b/crates/bevy_reflect/src/enums/enum_trait.rs index 9ee110d8f0a05..f924ef25a07ed 100644 --- a/crates/bevy_reflect/src/enums/enum_trait.rs +++ b/crates/bevy_reflect/src/enums/enum_trait.rs @@ -1,4 +1,4 @@ -use crate::{DynamicEnum, Reflect, VariantInfo, VariantType}; +use crate::{DynamicEnum, Reflect, TypeName, VariantInfo, VariantType}; use bevy_utils::HashMap; use std::any::{Any, TypeId}; use std::borrow::Cow; @@ -144,7 +144,7 @@ impl EnumInfo { /// /// * `variants`: The variants of this enum in the order they are defined /// - pub fn new(variants: &[VariantInfo]) -> Self { + pub fn new(variants: &[VariantInfo]) -> Self { let variant_indices = variants .iter() .enumerate() @@ -155,7 +155,7 @@ impl EnumInfo { .collect::>(); Self { - type_name: std::any::type_name::(), + type_name: TEnum::name(), type_id: TypeId::of::(), variants: variants.to_vec().into_boxed_slice(), variant_indices, @@ -203,7 +203,7 @@ impl EnumInfo { /// The [type name] of the enum. /// - /// [type name]: std::any::type_name + /// [type name]: crate::TypeName pub fn type_name(&self) -> &'static str { self.type_name } diff --git a/crates/bevy_reflect/src/enums/mod.rs b/crates/bevy_reflect/src/enums/mod.rs index 3493b799bb7e1..559ca94efa096 100644 --- a/crates/bevy_reflect/src/enums/mod.rs +++ b/crates/bevy_reflect/src/enums/mod.rs @@ -25,7 +25,7 @@ mod tests { let info = MyEnum::type_info(); if let TypeInfo::Enum(info) = info { assert!(info.is::(), "expected type to be `MyEnum`"); - assert_eq!(std::any::type_name::(), info.type_name()); + assert_eq!(MyEnum::name(), info.type_name()); // === MyEnum::A === // assert_eq!("A", info.variant_at(0).unwrap().name()); @@ -366,14 +366,14 @@ mod tests { // === Tuple === // let mut data = DynamicTuple::default(); data.insert(1.23_f32); - let dyn_enum = DynamicEnum::new(std::any::type_name::>(), "B", data); + let dyn_enum = DynamicEnum::new(TestEnum::::name(), "B", data); value.apply(&dyn_enum); assert_eq!(TestEnum::B(1.23), value); // === Struct === // let mut data = DynamicStruct::default(); data.insert("value", 1.23_f32); - let dyn_enum = DynamicEnum::new(std::any::type_name::>(), "C", data); + let dyn_enum = DynamicEnum::new(TestEnum::::name(), "C", data); value.apply(&dyn_enum); assert_eq!(TestEnum::C { value: 1.23 }, value); } @@ -395,14 +395,14 @@ mod tests { // === Tuple === // let mut data = DynamicTuple::default(); data.insert(TestStruct(123)); - let dyn_enum = DynamicEnum::new(std::any::type_name::(), "B", data); + let dyn_enum = DynamicEnum::new(TestEnum::name(), "B", data); value.apply(&dyn_enum); assert_eq!(TestEnum::B(TestStruct(123)), value); // === Struct === // let mut data = DynamicStruct::default(); data.insert("value", TestStruct(123)); - let dyn_enum = DynamicEnum::new(std::any::type_name::(), "C", data); + let dyn_enum = DynamicEnum::new(TestEnum::name(), "C", data); value.apply(&dyn_enum); assert_eq!( TestEnum::C { @@ -433,14 +433,14 @@ mod tests { // === Tuple === // let mut data = DynamicTuple::default(); data.insert(OtherEnum::B(123)); - let dyn_enum = DynamicEnum::new(std::any::type_name::(), "B", data); + let dyn_enum = DynamicEnum::new(TestEnum::name(), "B", data); value.apply(&dyn_enum); assert_eq!(TestEnum::B(OtherEnum::B(123)), value); // === Struct === // let mut data = DynamicStruct::default(); data.insert("value", OtherEnum::C { value: 1.23 }); - let dyn_enum = DynamicEnum::new(std::any::type_name::(), "C", data); + let dyn_enum = DynamicEnum::new(TestEnum::name(), "C", data); value.apply(&dyn_enum); assert_eq!( TestEnum::C { diff --git a/crates/bevy_reflect/src/fields.rs b/crates/bevy_reflect/src/fields.rs index 21dc9ec5f75e2..40f29b0ab9eed 100644 --- a/crates/bevy_reflect/src/fields.rs +++ b/crates/bevy_reflect/src/fields.rs @@ -1,4 +1,4 @@ -use crate::Reflect; +use crate::{Reflect, TypeName}; use std::any::{Any, TypeId}; use std::borrow::Cow; @@ -12,10 +12,10 @@ pub struct NamedField { impl NamedField { /// Create a new [`NamedField`]. - pub fn new>>(name: TName) -> Self { + pub fn new>>(name: TName) -> Self { Self { name: name.into(), - type_name: std::any::type_name::(), + type_name: T::name(), type_id: TypeId::of::(), } } @@ -27,7 +27,7 @@ impl NamedField { /// The [type name] of the field. /// - /// [type name]: std::any::type_name + /// [type name]: TypeName pub fn type_name(&self) -> &'static str { self.type_name } @@ -52,10 +52,10 @@ pub struct UnnamedField { } impl UnnamedField { - pub fn new(index: usize) -> Self { + pub fn new(index: usize) -> Self { Self { index, - type_name: std::any::type_name::(), + type_name: T::name(), type_id: TypeId::of::(), } } @@ -67,7 +67,7 @@ impl UnnamedField { /// The [type name] of the field. /// - /// [type name]: std::any::type_name + /// [type name]: TypeName pub fn type_name(&self) -> &'static str { self.type_name } diff --git a/crates/bevy_reflect/src/impls/smallvec.rs b/crates/bevy_reflect/src/impls/smallvec.rs index 1aa691b043bc1..f9916288d76f5 100644 --- a/crates/bevy_reflect/src/impls/smallvec.rs +++ b/crates/bevy_reflect/src/impls/smallvec.rs @@ -13,7 +13,7 @@ impl_type_name!(SmallVec); impl Array for SmallVec where - T::Item: FromReflect, + T::Item: FromReflect + TypeName, { fn get(&self, index: usize) -> Option<&dyn Reflect> { if index < SmallVec::len(self) { @@ -45,7 +45,7 @@ where impl List for SmallVec where - T::Item: FromReflect, + T::Item: FromReflect + TypeName, { fn push(&mut self, value: Box) { let value = value.take::().unwrap_or_else(|value| { @@ -62,7 +62,7 @@ where impl Reflect for SmallVec where - T::Item: FromReflect, + T::Item: FromReflect + TypeName, { fn get_type_info(&self) -> &'static TypeInfo { ::type_info() @@ -116,7 +116,7 @@ where impl Typed for SmallVec where - T::Item: FromReflect, + T::Item: FromReflect + TypeName, { fn type_info() -> &'static TypeInfo { static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new(); @@ -126,7 +126,7 @@ where impl FromReflect for SmallVec where - T::Item: FromReflect, + T::Item: FromReflect + TypeName, { fn from_reflect(reflect: &dyn Reflect) -> Option { if let ReflectRef::List(ref_list) = reflect.reflect_ref() { @@ -143,7 +143,7 @@ where impl GetTypeRegistration for SmallVec where - T::Item: FromReflect, + T::Item: FromReflect + TypeName, { fn get_type_registration() -> TypeRegistration { let mut registration = TypeRegistration::of::>(); diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index 1da30c294f4d5..8a84dff23fee9 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -552,7 +552,7 @@ impl Reflect for Cow<'static, str> { if let Some(value) = value.downcast_ref::() { *self = value.clone(); } else { - panic!("Value is not a {}.", std::any::type_name::()); + panic!("Value is not a {}.", Self::name()); } } @@ -708,7 +708,7 @@ impl Reflect for Option { .unwrap_or_else(|| { panic!( "Field in `Some` variant of {} should exist", - std::any::type_name::>() + Option::::name() ) }) .clone_value() @@ -717,8 +717,8 @@ impl Reflect for Option { T::from_reflect(&*value).unwrap_or_else(|| { panic!( "Field in `Some` variant of {} should be of type {}", - std::any::type_name::>(), - std::any::type_name::() + Option::::name(), + T::name() ) }) }); @@ -727,7 +727,7 @@ impl Reflect for Option { "None" => { *self = None; } - _ => panic!("Enum is not a {}.", std::any::type_name::()), + _ => panic!("Enum is not a {}.", Self::name()), } } } @@ -771,7 +771,7 @@ impl FromReflect for Option { .unwrap_or_else(|| { panic!( "Field in `Some` variant of {} should exist", - std::any::type_name::>() + Option::::name() ) }) .clone_value() @@ -780,8 +780,8 @@ impl FromReflect for Option { T::from_reflect(&*value).unwrap_or_else(|| { panic!( "Field in `Some` variant of {} should be of type {}", - std::any::type_name::>(), - std::any::type_name::() + Option::::name(), + T::name() ) }) }); @@ -791,7 +791,7 @@ impl FromReflect for Option { name => panic!( "variant with name `{}` does not exist on enum `{}`", name, - std::any::type_name::() + Self::name() ), } } else { diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index 8d11abffe2cb1..4982f213946df 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -581,7 +581,7 @@ mod tests { fn reflect_type_info() { // TypeInfo let info = i32::type_info(); - assert_eq!(std::any::type_name::(), info.type_name()); + assert_eq!(i32::name(), info.type_name()); assert_eq!(std::any::TypeId::of::(), info.type_id()); // TypeInfo (unsized) @@ -605,21 +605,15 @@ mod tests { let info = MyStruct::type_info(); if let TypeInfo::Struct(info) = info { assert!(info.is::()); - assert_eq!(std::any::type_name::(), info.type_name()); - assert_eq!( - std::any::type_name::(), - info.field("foo").unwrap().type_name() - ); + assert_eq!(MyStruct::name(), info.type_name()); + assert_eq!(i32::name(), info.field("foo").unwrap().type_name()); assert_eq!( std::any::TypeId::of::(), info.field("foo").unwrap().type_id() ); assert!(info.field("foo").unwrap().is::()); assert_eq!("foo", info.field("foo").unwrap().name()); - assert_eq!( - std::any::type_name::(), - info.field_at(1).unwrap().type_name() - ); + assert_eq!(usize::name(), info.field_at(1).unwrap().type_name()); } else { panic!("Expected `TypeInfo::Struct`"); } @@ -638,19 +632,10 @@ mod tests { let info = >::type_info(); if let TypeInfo::Struct(info) = info { assert!(info.is::>()); - assert_eq!( - std::any::type_name::>(), - info.type_name() - ); - assert_eq!( - std::any::type_name::(), - info.field("foo").unwrap().type_name() - ); + assert_eq!(MyGenericStruct::::name(), info.type_name()); + assert_eq!(i32::name(), info.field("foo").unwrap().type_name()); assert_eq!("foo", info.field("foo").unwrap().name()); - assert_eq!( - std::any::type_name::(), - info.field_at(1).unwrap().type_name() - ); + assert_eq!(usize::name(), info.field_at(1).unwrap().type_name()); } else { panic!("Expected `TypeInfo::Struct`"); } @@ -669,11 +654,8 @@ mod tests { let info = MyTupleStruct::type_info(); if let TypeInfo::TupleStruct(info) = info { assert!(info.is::()); - assert_eq!(std::any::type_name::(), info.type_name()); - assert_eq!( - std::any::type_name::(), - info.field_at(1).unwrap().type_name() - ); + assert_eq!(MyTupleStruct::name(), info.type_name()); + assert_eq!(i32::name(), info.field_at(1).unwrap().type_name()); assert!(info.field_at(1).unwrap().is::()); } else { panic!("Expected `TypeInfo::TupleStruct`"); @@ -685,11 +667,8 @@ mod tests { let info = MyTuple::type_info(); if let TypeInfo::Tuple(info) = info { assert!(info.is::()); - assert_eq!(std::any::type_name::(), info.type_name()); - assert_eq!( - std::any::type_name::(), - info.field_at(1).unwrap().type_name() - ); + assert_eq!(MyTuple::name(), info.type_name()); + assert_eq!(f32::name(), info.field_at(1).unwrap().type_name()); } else { panic!("Expected `TypeInfo::Tuple`"); } @@ -705,8 +684,8 @@ mod tests { if let TypeInfo::List(info) = info { assert!(info.is::()); assert!(info.item_is::()); - assert_eq!(std::any::type_name::(), info.type_name()); - assert_eq!(std::any::type_name::(), info.item_type_name()); + assert_eq!(MyList::name(), info.type_name()); + assert_eq!(usize::name(), info.item_type_name()); } else { panic!("Expected `TypeInfo::List`"); } @@ -724,8 +703,8 @@ mod tests { if let TypeInfo::List(info) = info { assert!(info.is::()); assert!(info.item_is::()); - assert_eq!(std::any::type_name::(), info.type_name()); - assert_eq!(std::any::type_name::(), info.item_type_name()); + assert_eq!(MySmallVec::name(), info.type_name()); + assert_eq!(String::name(), info.item_type_name()); } else { panic!("Expected `TypeInfo::List`"); } @@ -743,8 +722,8 @@ mod tests { if let TypeInfo::Array(info) = info { assert!(info.is::()); assert!(info.item_is::()); - assert_eq!(std::any::type_name::(), info.type_name()); - assert_eq!(std::any::type_name::(), info.item_type_name()); + assert_eq!(MyArray::name(), info.type_name()); + assert_eq!(usize::name(), info.item_type_name()); assert_eq!(3, info.capacity()); } else { panic!("Expected `TypeInfo::Array`"); @@ -762,9 +741,9 @@ mod tests { assert!(info.is::()); assert!(info.key_is::()); assert!(info.value_is::()); - assert_eq!(std::any::type_name::(), info.type_name()); - assert_eq!(std::any::type_name::(), info.key_type_name()); - assert_eq!(std::any::type_name::(), info.value_type_name()); + assert_eq!(MyMap::name(), info.type_name()); + assert_eq!(usize::name(), info.key_type_name()); + assert_eq!(f32::name(), info.value_type_name()); } else { panic!("Expected `TypeInfo::Map`"); } @@ -779,7 +758,7 @@ mod tests { let info = MyValue::type_info(); if let TypeInfo::Value(info) = info { assert!(info.is::()); - assert_eq!(std::any::type_name::(), info.type_name()); + assert_eq!(MyValue::name(), info.type_name()); } else { panic!("Expected `TypeInfo::Value`"); } diff --git a/crates/bevy_reflect/src/list.rs b/crates/bevy_reflect/src/list.rs index 346f19502bbbf..6dd8c4924a55c 100644 --- a/crates/bevy_reflect/src/list.rs +++ b/crates/bevy_reflect/src/list.rs @@ -4,7 +4,7 @@ use std::fmt::{Debug, Formatter}; use crate::utility::NonGenericTypeInfoCell; use crate::{ Array, ArrayIter, DynamicArray, DynamicInfo, FromReflect, Reflect, ReflectMut, ReflectRef, - ReflectTypeName, TypeInfo, Typed, + ReflectTypeName, TypeInfo, TypeName, Typed, }; /// An ordered, mutable list of [Reflect] items. This corresponds to types like [`std::vec::Vec`]. @@ -35,18 +35,18 @@ pub struct ListInfo { impl ListInfo { /// Create a new [`ListInfo`]. - pub fn new() -> Self { + pub fn new() -> Self { Self { - type_name: std::any::type_name::(), + type_name: TList::name(), type_id: TypeId::of::(), - item_type_name: std::any::type_name::(), + item_type_name: TItem::name(), item_type_id: TypeId::of::(), } } /// The [type name] of the list. /// - /// [type name]: std::any::type_name + /// [type name]: TypeName pub fn type_name(&self) -> &'static str { self.type_name } @@ -63,7 +63,7 @@ impl ListInfo { /// The [type name] of the list item. /// - /// [type name]: std::any::type_name + /// [type name]: TypeName pub fn item_type_name(&self) -> &'static str { self.item_type_name } diff --git a/crates/bevy_reflect/src/map.rs b/crates/bevy_reflect/src/map.rs index f2ba01a1f51c8..e37311c8df0a3 100644 --- a/crates/bevy_reflect/src/map.rs +++ b/crates/bevy_reflect/src/map.rs @@ -5,7 +5,9 @@ use std::hash::Hash; use bevy_utils::{Entry, HashMap}; use crate::utility::NonGenericTypeInfoCell; -use crate::{DynamicInfo, Reflect, ReflectMut, ReflectRef, ReflectTypeName, TypeInfo, Typed}; +use crate::{ + DynamicInfo, Reflect, ReflectMut, ReflectRef, ReflectTypeName, TypeInfo, TypeName, Typed, +}; /// An ordered mapping between [`Reflect`] values. /// @@ -69,20 +71,24 @@ pub struct MapInfo { impl MapInfo { /// Create a new [`MapInfo`]. - pub fn new() -> Self { + pub fn new< + TMap: Map + TypeName, + TKey: Hash + Reflect + TypeName, + TValue: Reflect + TypeName, + >() -> Self { Self { - type_name: std::any::type_name::(), + type_name: TMap::name(), type_id: TypeId::of::(), - key_type_name: std::any::type_name::(), + key_type_name: TKey::name(), key_type_id: TypeId::of::(), - value_type_name: std::any::type_name::(), + value_type_name: TValue::name(), value_type_id: TypeId::of::(), } } /// The [type name] of the map. /// - /// [type name]: std::any::type_name + /// [type name]: TypeName pub fn type_name(&self) -> &'static str { self.type_name } @@ -99,7 +105,7 @@ impl MapInfo { /// The [type name] of the key. /// - /// [type name]: std::any::type_name + /// [type name]: TypeName pub fn key_type_name(&self) -> &'static str { self.key_type_name } @@ -116,7 +122,7 @@ impl MapInfo { /// The [type name] of the value. /// - /// [type name]: std::any::type_name + /// [type name]: TypeName pub fn value_type_name(&self) -> &'static str { self.value_type_name } diff --git a/crates/bevy_reflect/src/reflect.rs b/crates/bevy_reflect/src/reflect.rs index 7742555595a97..28c787cbf2920 100644 --- a/crates/bevy_reflect/src/reflect.rs +++ b/crates/bevy_reflect/src/reflect.rs @@ -207,6 +207,7 @@ impl Debug for dyn Reflect { impl Typed for dyn Reflect { fn type_info() -> &'static TypeInfo { static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new(); + // FIXME : how to build ValueInfo here with TypeName ? CELL.get_or_set(|| TypeInfo::Value(ValueInfo::new::())) } } diff --git a/crates/bevy_reflect/src/struct_trait.rs b/crates/bevy_reflect/src/struct_trait.rs index be61b7606e364..4b6cc697e6f88 100644 --- a/crates/bevy_reflect/src/struct_trait.rs +++ b/crates/bevy_reflect/src/struct_trait.rs @@ -1,6 +1,7 @@ use crate::utility::NonGenericTypeInfoCell; use crate::{ - DynamicInfo, NamedField, Reflect, ReflectMut, ReflectRef, ReflectTypeName, TypeInfo, Typed, + DynamicInfo, NamedField, Reflect, ReflectMut, ReflectRef, ReflectTypeName, TypeInfo, TypeName, + Typed, }; use bevy_utils::{Entry, HashMap}; use std::fmt::{Debug, Formatter}; @@ -84,7 +85,7 @@ impl StructInfo { /// /// * `fields`: The fields of this struct in the order they are defined /// - pub fn new(fields: &[NamedField]) -> Self { + pub fn new(fields: &[NamedField]) -> Self { let field_indices = fields .iter() .enumerate() @@ -95,7 +96,7 @@ impl StructInfo { .collect::>(); Self { - type_name: std::any::type_name::(), + type_name: T::name(), type_id: TypeId::of::(), fields: fields.to_vec().into_boxed_slice(), field_indices, @@ -131,7 +132,7 @@ impl StructInfo { /// The [type name] of the struct. /// - /// [type name]: std::any::type_name + /// [type name]: TypeName pub fn type_name(&self) -> &'static str { self.type_name } diff --git a/crates/bevy_reflect/src/tuple.rs b/crates/bevy_reflect/src/tuple.rs index bf09676657163..3063d81dc6555 100644 --- a/crates/bevy_reflect/src/tuple.rs +++ b/crates/bevy_reflect/src/tuple.rs @@ -140,9 +140,9 @@ impl TupleInfo { /// /// * `fields`: The fields of this tuple in the order they are defined /// - pub fn new(fields: &[UnnamedField]) -> Self { + pub fn new(fields: &[UnnamedField]) -> Self { Self { - type_name: std::any::type_name::(), + type_name: T::name(), type_id: TypeId::of::(), fields: fields.to_vec().into_boxed_slice(), } @@ -165,7 +165,7 @@ impl TupleInfo { /// The [type name] of the tuple. /// - /// [type name]: std::any::type_name + /// [type name]: TypeName pub fn type_name(&self) -> &'static str { self.type_name } diff --git a/crates/bevy_reflect/src/tuple_struct.rs b/crates/bevy_reflect/src/tuple_struct.rs index 9f4bc68058ed2..e0352268145c6 100644 --- a/crates/bevy_reflect/src/tuple_struct.rs +++ b/crates/bevy_reflect/src/tuple_struct.rs @@ -1,6 +1,7 @@ use crate::utility::NonGenericTypeInfoCell; use crate::{ - DynamicInfo, Reflect, ReflectMut, ReflectRef, ReflectTypeName, TypeInfo, Typed, UnnamedField, + DynamicInfo, Reflect, ReflectMut, ReflectRef, ReflectTypeName, TypeInfo, TypeName, Typed, + UnnamedField, }; use std::any::{Any, TypeId}; use std::fmt::{Debug, Formatter}; @@ -63,9 +64,9 @@ impl TupleStructInfo { /// /// * `fields`: The fields of this struct in the order they are defined /// - pub fn new(fields: &[UnnamedField]) -> Self { + pub fn new(fields: &[UnnamedField]) -> Self { Self { - type_name: std::any::type_name::(), + type_name: T::name(), type_id: TypeId::of::(), fields: fields.to_vec().into_boxed_slice(), } @@ -88,7 +89,7 @@ impl TupleStructInfo { /// The [type name] of the tuple struct. /// - /// [type name]: std::any::type_name + /// [type name]: TypeName pub fn type_name(&self) -> &'static str { self.type_name } diff --git a/crates/bevy_reflect/src/type_info.rs b/crates/bevy_reflect/src/type_info.rs index af71a09ac412c..16491689295a3 100644 --- a/crates/bevy_reflect/src/type_info.rs +++ b/crates/bevy_reflect/src/type_info.rs @@ -94,7 +94,7 @@ pub trait Typed: Reflect { /// [`Reflect::get_type_info`]: crate::Reflect::get_type_info /// [`TypeRegistry::get_type_info`]: crate::TypeRegistry::get_type_info /// [`TypeId`]: std::any::TypeId -/// [type name]: std::any::type_name +/// [type name]: crate::TypeName #[derive(Debug, Clone)] pub enum TypeInfo { Struct(StructInfo), @@ -129,7 +129,7 @@ impl TypeInfo { /// The [name] of the underlying type. /// - /// [name]: std::any::type_name + /// [name]: crate::TypeName pub fn type_name(&self) -> &'static str { match self { Self::Struct(info) => info.type_name(), @@ -166,6 +166,7 @@ pub struct ValueInfo { impl ValueInfo { pub fn new() -> Self { + // FIXME: use TypeName instead of any::type_name. Self { type_name: std::any::type_name::(), type_id: TypeId::of::(), @@ -174,7 +175,7 @@ impl ValueInfo { /// The [type name] of the value. /// - /// [type name]: std::any::type_name + /// [type name]: crate::TypeName pub fn type_name(&self) -> &'static str { self.type_name } diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index 74865abeb0c91..408cf245efeab 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -1,4 +1,4 @@ -use crate::{serde::Serializable, Reflect, TypeInfo, Typed}; +use crate::{serde::Serializable, Reflect, TypeInfo, TypeName, Typed}; use bevy_ptr::{Ptr, PtrMut}; use bevy_utils::{HashMap, HashSet}; use downcast_rs::{impl_downcast, Downcast}; @@ -314,8 +314,8 @@ impl TypeRegistration { } /// Creates type registration information for `T`. - pub fn of() -> Self { - let type_name = std::any::type_name::(); + pub fn of() -> Self { + let type_name = T::name(); Self { data: HashMap::default(), short_name: bevy_utils::get_short_name(type_name), From 4f17b0c3564e3b8efe26252b5519991c8d82e75a Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sat, 27 Aug 2022 17:31:27 +0200 Subject: [PATCH 14/87] fix ci + doc --- crates/bevy_asset/src/asset_server.rs | 2 +- crates/bevy_pbr/src/material.rs | 4 ++-- crates/bevy_reflect/src/enums/dynamic_enum.rs | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/bevy_asset/src/asset_server.rs b/crates/bevy_asset/src/asset_server.rs index c0c8cde3470b4..cf64e1e39455b 100644 --- a/crates/bevy_asset/src/asset_server.rs +++ b/crates/bevy_asset/src/asset_server.rs @@ -88,7 +88,7 @@ pub struct AssetServerInternal { /// use bevy_asset::{AssetServer, Handle}; /// use bevy_ecs::prelude::{Commands, Res}; /// -/// # #[derive(Debug, bevy_reflect::TypeUuid)] +/// # #[derive(Debug, bevy_reflect::TypeUuid, bevy_reflect::TypeName)] /// # #[uuid = "00000000-0000-0000-0000-000000000000"] /// # struct Image; /// diff --git a/crates/bevy_pbr/src/material.rs b/crates/bevy_pbr/src/material.rs index 4ed804ab17c11..8b1ce63707158 100644 --- a/crates/bevy_pbr/src/material.rs +++ b/crates/bevy_pbr/src/material.rs @@ -57,11 +57,11 @@ use std::marker::PhantomData; /// ``` /// # use bevy_pbr::{Material, MaterialMeshBundle}; /// # use bevy_ecs::prelude::*; -/// # use bevy_reflect::TypeUuid; +/// # use bevy_reflect::{TypeUuid, TypeName}; /// # use bevy_render::{render_resource::{AsBindGroup, ShaderRef}, texture::Image, color::Color}; /// # use bevy_asset::{Handle, AssetServer, Assets}; /// -/// #[derive(AsBindGroup, TypeUuid, Debug, Clone)] +/// #[derive(AsBindGroup, TypeUuid, TypeName, Debug, Clone)] /// #[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"] /// pub struct CustomMaterial { /// // Uniform bindings must implement `ShaderType`, which will be used to convert the value to diff --git a/crates/bevy_reflect/src/enums/dynamic_enum.rs b/crates/bevy_reflect/src/enums/dynamic_enum.rs index a809b6520220d..f955735c86617 100644 --- a/crates/bevy_reflect/src/enums/dynamic_enum.rs +++ b/crates/bevy_reflect/src/enums/dynamic_enum.rs @@ -130,7 +130,7 @@ impl DynamicEnum { pub fn from_ref(value: &TEnum) -> Self { match value.variant_type() { VariantType::Unit => DynamicEnum::new( - value.type_name().as_ref(), + value.type_name(), value.variant_name(), DynamicVariant::Unit, ), @@ -140,7 +140,7 @@ impl DynamicEnum { data.insert_boxed(field.value().clone_value()); } DynamicEnum::new( - value.type_name().as_ref(), + value.type_name(), value.variant_name(), DynamicVariant::Tuple(data), ) @@ -152,7 +152,7 @@ impl DynamicEnum { data.insert_boxed(name, field.value().clone_value()); } DynamicEnum::new( - value.type_name().as_ref(), + value.type_name(), value.variant_name(), DynamicVariant::Struct(data), ) From c135dae342840f423dfb4f3e877355a6a71f67fc Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sat, 27 Aug 2022 18:44:20 +0200 Subject: [PATCH 15/87] remove `ReflectTypeName` --- .../bevy_reflect_derive/src/derive_data.rs | 2 +- .../bevy_reflect_derive/src/impls/enums.rs | 9 ++++--- .../bevy_reflect_derive/src/impls/structs.rs | 7 +++-- .../src/impls/tuple_structs.rs | 7 +++-- .../bevy_reflect_derive/src/impls/values.rs | 7 ++++- crates/bevy_reflect/src/array.rs | 11 ++++---- crates/bevy_reflect/src/enums/dynamic_enum.rs | 14 +++++----- crates/bevy_reflect/src/impls/smallvec.rs | 5 ++++ crates/bevy_reflect/src/impls/std.rs | 26 ++++++++++++++++--- crates/bevy_reflect/src/lib.rs | 18 ++++--------- crates/bevy_reflect/src/list.rs | 13 +++++----- crates/bevy_reflect/src/map.rs | 15 +++++------ crates/bevy_reflect/src/reflect.rs | 9 ++++--- crates/bevy_reflect/src/struct_trait.rs | 16 +++++------- crates/bevy_reflect/src/tuple.rs | 20 ++++++++------ crates/bevy_reflect/src/tuple_struct.rs | 14 +++++----- crates/bevy_reflect/src/type_name.rs | 14 ---------- 17 files changed, 109 insertions(+), 98 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs index a46b70ebbbf08..d9dd2422af48b 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs @@ -41,7 +41,7 @@ pub(crate) struct ReflectMeta<'a> { type_name: &'a Ident, /// The generics defined on this type. generics: &'a Generics, - /// Override the default type name for `ReflectTypeName`. + /// Override the default type name for `TypeName`. reflected_type_name: Option, /// A cached instance of the path to the `bevy_reflect` crate. bevy_reflect_path: Path, diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs index 436e59a21147b..3f89ac4ca7c17 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs @@ -159,6 +159,11 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> TokenStream { } impl #impl_generics #bevy_reflect_path::Reflect for #enum_name #ty_generics #where_clause { + #[inline] + fn type_name(&self) -> &str { + ::name() + } + #[inline] fn get_type_info(&self) -> &'static #bevy_reflect_path::TypeInfo { ::type_info() @@ -202,8 +207,6 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> TokenStream { #[inline] fn apply(&mut self, #ref_value: &dyn #bevy_reflect_path::Reflect) { - use #bevy_reflect_path::ReflectTypeName; - if let #bevy_reflect_path::ReflectRef::Enum(#ref_value) = #ref_value.reflect_ref() { if #bevy_reflect_path::Enum::variant_name(self) == #ref_value.variant_name() { // Same variant -> just update fields @@ -227,7 +230,7 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> TokenStream { #(#variant_names => { *self = #variant_constructors })* - name => panic!("variant with name `{}` does not exist on enum `{}`", name, ::name()), + name => panic!("variant with name `{}` does not exist on enum `{}`", name, self.type_name()), } } } else { diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs index fbd709a84efd9..29d36b6b24262 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs @@ -127,8 +127,6 @@ pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> TokenStream { } fn clone_dynamic(&self) -> #bevy_reflect_path::DynamicStruct { - use #bevy_reflect_path::ReflectTypeName; - let mut dynamic = #bevy_reflect_path::DynamicStruct::default(); dynamic.set_name(self.type_name().to_string()); #(dynamic.insert_boxed(#field_names, self.#field_idents.clone_value());)* @@ -137,6 +135,11 @@ pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> TokenStream { } impl #impl_generics #bevy_reflect_path::Reflect for #struct_name #ty_generics #where_clause { + #[inline] + fn type_name(&self) -> &str { + ::name() + } + #[inline] fn get_type_info(&self) -> &'static #bevy_reflect_path::TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs index 13534b9ff71fa..150093c3e5758 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs @@ -89,8 +89,6 @@ pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> TokenStream { } fn clone_dynamic(&self) -> #bevy_reflect_path::DynamicTupleStruct { - use #bevy_reflect_path::ReflectTypeName; - let mut dynamic = #bevy_reflect_path::DynamicTupleStruct::default(); dynamic.set_name(self.type_name().to_string()); #(dynamic.insert_boxed(self.#field_idents.clone_value());)* @@ -99,6 +97,11 @@ pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> TokenStream { } impl #impl_generics #bevy_reflect_path::Reflect for #struct_name #ty_generics #where_clause { + #[inline] + fn type_name(&self) -> &str { + ::name() + } + #[inline] fn get_type_info(&self) -> &'static #bevy_reflect_path::TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs index 502adf6a97f30..c254b828f3478 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs @@ -40,6 +40,11 @@ pub(crate) fn impl_value(meta: &ReflectMeta) -> TokenStream { #type_name_impl impl #impl_generics #bevy_reflect_path::Reflect for #type_name #ty_generics #where_clause { + #[inline] + fn type_name(&self) -> &str { + ::name() + } + #[inline] fn get_type_info(&self) -> &'static #bevy_reflect_path::TypeInfo { ::type_info() @@ -81,7 +86,7 @@ pub(crate) fn impl_value(meta: &ReflectMeta) -> TokenStream { if let Some(value) = value.downcast_ref::() { *self = value.clone(); } else { - panic!("Value is not {}.", ::name()); + panic!("Value is not {}.", self.type_name()); } } diff --git a/crates/bevy_reflect/src/array.rs b/crates/bevy_reflect/src/array.rs index fe32cf8fb6133..3ae28d2fe87c0 100644 --- a/crates/bevy_reflect/src/array.rs +++ b/crates/bevy_reflect/src/array.rs @@ -1,6 +1,6 @@ use crate::{ - utility::NonGenericTypeInfoCell, DynamicInfo, Reflect, ReflectMut, ReflectRef, ReflectTypeName, - TypeInfo, TypeName, Typed, + utility::NonGenericTypeInfoCell, DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, + TypeName, Typed, }; use std::{ any::{Any, TypeId}, @@ -152,13 +152,12 @@ impl DynamicArray { } } -impl ReflectTypeName for DynamicArray { +impl Reflect for DynamicArray { + #[inline] fn type_name(&self) -> &str { - self.name.as_str() + &self.name } -} -impl Reflect for DynamicArray { #[inline] fn get_type_info(&self) -> &'static TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/src/enums/dynamic_enum.rs b/crates/bevy_reflect/src/enums/dynamic_enum.rs index f955735c86617..34e6834bd036c 100644 --- a/crates/bevy_reflect/src/enums/dynamic_enum.rs +++ b/crates/bevy_reflect/src/enums/dynamic_enum.rs @@ -1,8 +1,7 @@ use crate::utility::NonGenericTypeInfoCell; use crate::{ enum_debug, enum_hash, enum_partial_eq, DynamicInfo, DynamicStruct, DynamicTuple, Enum, - Reflect, ReflectMut, ReflectRef, ReflectTypeName, Struct, Tuple, TypeInfo, Typed, - VariantFieldIter, VariantType, + Reflect, ReflectMut, ReflectRef, Struct, Tuple, TypeInfo, Typed, VariantFieldIter, VariantType, }; use std::any::Any; use std::fmt::Formatter; @@ -161,12 +160,6 @@ impl DynamicEnum { } } -impl ReflectTypeName for DynamicEnum { - fn type_name(&self) -> &str { - self.name.as_str() - } -} - impl Enum for DynamicEnum { fn field(&self, name: &str) -> Option<&dyn Reflect> { if let DynamicVariant::Struct(data) = &self.variant { @@ -250,6 +243,11 @@ impl Enum for DynamicEnum { } impl Reflect for DynamicEnum { + #[inline] + fn type_name(&self) -> &str { + &self.name + } + #[inline] fn get_type_info(&self) -> &'static TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/src/impls/smallvec.rs b/crates/bevy_reflect/src/impls/smallvec.rs index f9916288d76f5..e634f9e1967a9 100644 --- a/crates/bevy_reflect/src/impls/smallvec.rs +++ b/crates/bevy_reflect/src/impls/smallvec.rs @@ -64,6 +64,11 @@ impl Reflect for SmallVec where T::Item: FromReflect + TypeName, { + #[inline] + fn type_name(&self) -> &str { + ::name() + } + fn get_type_info(&self) -> &'static TypeInfo { ::type_info() } diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index 8a84dff23fee9..0faf4685e43da 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -2,9 +2,9 @@ use crate::{self as bevy_reflect, ReflectFromPtr, TypeName}; use crate::{ map_apply, map_partial_eq, Array, ArrayInfo, ArrayIter, DynamicEnum, DynamicMap, Enum, EnumInfo, FromReflect, FromType, GetTypeRegistration, List, ListInfo, Map, MapInfo, MapIter, - Reflect, ReflectDeserialize, ReflectMut, ReflectRef, ReflectSerialize, ReflectTypeName, - TupleVariantInfo, TypeInfo, TypeRegistration, Typed, UnitVariantInfo, UnnamedField, ValueInfo, - VariantFieldIter, VariantInfo, VariantType, + Reflect, ReflectDeserialize, ReflectMut, ReflectRef, ReflectSerialize, TupleVariantInfo, + TypeInfo, TypeRegistration, Typed, UnitVariantInfo, UnnamedField, ValueInfo, VariantFieldIter, + VariantInfo, VariantType, }; use crate::utility::{GenericTypeInfoCell, GenericTypeNameCell, NonGenericTypeInfoCell}; @@ -149,6 +149,10 @@ impl List for Vec { } impl Reflect for Vec { + fn type_name(&self) -> &str { + ::name() + } + fn get_type_info(&self) -> &'static TypeInfo { ::type_info() } @@ -298,6 +302,10 @@ impl Map for H } impl Reflect for HashMap { + fn type_name(&self) -> &str { + ::name() + } + fn get_type_info(&self) -> &'static TypeInfo { ::type_info() } @@ -411,6 +419,10 @@ impl Array for [T; N] { } impl Reflect for [T; N] { + fn type_name(&self) -> &str { + ::name() + } + fn get_type_info(&self) -> &'static TypeInfo { ::type_info() } @@ -523,6 +535,10 @@ impl_array_get_type_registration! { } impl Reflect for Cow<'static, str> { + fn type_name(&self) -> &str { + ::name() + } + fn get_type_info(&self) -> &'static TypeInfo { ::type_info() } @@ -661,6 +677,10 @@ impl Enum for Option { } impl Reflect for Option { + fn type_name(&self) -> &str { + ::name() + } + #[inline] fn get_type_info(&self) -> &'static TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index 4982f213946df..f18d84fb09b67 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -37,7 +37,7 @@ pub mod prelude { #[doc(hidden)] pub use crate::{ reflect_trait, FromReflect, GetField, GetTupleStructField, Reflect, ReflectDeserialize, - ReflectSerialize, ReflectTypeName, Struct, TupleStruct, TypeName, + ReflectSerialize, Struct, TupleStruct, TypeName, }; } @@ -898,32 +898,25 @@ bevy_reflect::tests::Test { #[test] fn reflect_type_name() { - use bevy_reflect::ReflectTypeName; - #[derive(TypeName)] struct Foo; - let foo = Foo; - let name = foo.type_name(); + let name = Foo::name(); assert_eq!(name, "bevy_reflect::tests::Foo"); #[derive(TypeName)] struct Goo { _value: T, } - let goo = Goo { _value: 42u32 }; - let name = goo.type_name(); + let name = Goo::::name(); assert_eq!(name, "bevy_reflect::tests::Goo"); } #[test] fn reflect_custom_type_name() { - use bevy_reflect::ReflectTypeName; - #[derive(TypeName)] #[type_name("Banane")] struct Foo; - let foo = Foo; - let name = foo.type_name(); + let name = Foo::name(); assert_eq!(name, "Banane"); #[derive(TypeName)] @@ -931,8 +924,7 @@ bevy_reflect::tests::Test { struct Goo { _value: T, } - let goo = Goo { _value: 42u32 }; - let name = goo.type_name(); + let name = Goo::::name(); assert_eq!(name, "MyType"); } diff --git a/crates/bevy_reflect/src/list.rs b/crates/bevy_reflect/src/list.rs index 6dd8c4924a55c..950f49c9ec115 100644 --- a/crates/bevy_reflect/src/list.rs +++ b/crates/bevy_reflect/src/list.rs @@ -4,7 +4,7 @@ use std::fmt::{Debug, Formatter}; use crate::utility::NonGenericTypeInfoCell; use crate::{ Array, ArrayIter, DynamicArray, DynamicInfo, FromReflect, Reflect, ReflectMut, ReflectRef, - ReflectTypeName, TypeInfo, TypeName, Typed, + TypeInfo, TypeName, Typed, }; /// An ordered, mutable list of [Reflect] items. This corresponds to types like [`std::vec::Vec`]. @@ -114,12 +114,6 @@ impl DynamicList { } } -impl ReflectTypeName for DynamicList { - fn type_name(&self) -> &str { - self.name.as_str() - } -} - impl Array for DynamicList { fn get(&self, index: usize) -> Option<&dyn Reflect> { self.values.get(index).map(|value| &**value) @@ -170,6 +164,11 @@ impl List for DynamicList { } impl Reflect for DynamicList { + #[inline] + fn type_name(&self) -> &str { + &self.name + } + #[inline] fn get_type_info(&self) -> &'static TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/src/map.rs b/crates/bevy_reflect/src/map.rs index e37311c8df0a3..b62002c12b474 100644 --- a/crates/bevy_reflect/src/map.rs +++ b/crates/bevy_reflect/src/map.rs @@ -5,9 +5,7 @@ use std::hash::Hash; use bevy_utils::{Entry, HashMap}; use crate::utility::NonGenericTypeInfoCell; -use crate::{ - DynamicInfo, Reflect, ReflectMut, ReflectRef, ReflectTypeName, TypeInfo, TypeName, Typed, -}; +use crate::{DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, TypeName, Typed}; /// An ordered mapping between [`Reflect`] values. /// @@ -171,12 +169,6 @@ impl DynamicMap { } } -impl ReflectTypeName for DynamicMap { - fn type_name(&self) -> &str { - self.name.as_str() - } -} - impl Map for DynamicMap { fn get(&self, key: &dyn Reflect) -> Option<&dyn Reflect> { self.indices @@ -241,6 +233,11 @@ impl Map for DynamicMap { } impl Reflect for DynamicMap { + #[inline] + fn type_name(&self) -> &str { + &self.name + } + #[inline] fn get_type_info(&self) -> &'static TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/src/reflect.rs b/crates/bevy_reflect/src/reflect.rs index 28c787cbf2920..4c84458db4839 100644 --- a/crates/bevy_reflect/src/reflect.rs +++ b/crates/bevy_reflect/src/reflect.rs @@ -1,7 +1,7 @@ use crate::{ array_debug, enum_debug, list_debug, map_debug, serde::Serializable, struct_debug, tuple_debug, - tuple_struct_debug, Array, Enum, List, Map, ReflectTypeName, Struct, Tuple, TupleStruct, - TypeInfo, TypeName, Typed, ValueInfo, + tuple_struct_debug, Array, Enum, List, Map, Struct, Tuple, TupleStruct, TypeInfo, TypeName, + Typed, ValueInfo, }; use std::{ any::{Any, TypeId}, @@ -52,7 +52,10 @@ pub enum ReflectMut<'a> { /// /// When using `#[derive(Reflect)]` with a struct or tuple struct, the suitable subtrait for that /// type (`Struct` or `TupleStruct`) is derived automatically. -pub trait Reflect: ReflectTypeName + Any + Send + Sync { +pub trait Reflect: Any + Send + Sync { + /// Returns the [type name][crate::TypeName] of the underlying type. + fn type_name(&self) -> &str; + /// Returns the [`TypeInfo`] of the underlying type. /// /// This method is great if you have an instance of a type or a `dyn Reflect`, diff --git a/crates/bevy_reflect/src/struct_trait.rs b/crates/bevy_reflect/src/struct_trait.rs index 4b6cc697e6f88..8b330f7f2f146 100644 --- a/crates/bevy_reflect/src/struct_trait.rs +++ b/crates/bevy_reflect/src/struct_trait.rs @@ -1,8 +1,5 @@ use crate::utility::NonGenericTypeInfoCell; -use crate::{ - DynamicInfo, NamedField, Reflect, ReflectMut, ReflectRef, ReflectTypeName, TypeInfo, TypeName, - Typed, -}; +use crate::{DynamicInfo, NamedField, Reflect, ReflectMut, ReflectRef, TypeInfo, TypeName, Typed}; use bevy_utils::{Entry, HashMap}; use std::fmt::{Debug, Formatter}; use std::{ @@ -286,12 +283,6 @@ impl DynamicStruct { } } -impl ReflectTypeName for DynamicStruct { - fn type_name(&self) -> &str { - self.name.as_str() - } -} - impl Struct for DynamicStruct { #[inline] fn field(&self, name: &str) -> Option<&dyn Reflect> { @@ -352,6 +343,11 @@ impl Struct for DynamicStruct { } impl Reflect for DynamicStruct { + #[inline] + fn type_name(&self) -> &str { + &self.name + } + #[inline] fn get_type_info(&self) -> &'static TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/src/tuple.rs b/crates/bevy_reflect/src/tuple.rs index 3063d81dc6555..d931f7c4be041 100644 --- a/crates/bevy_reflect/src/tuple.rs +++ b/crates/bevy_reflect/src/tuple.rs @@ -1,7 +1,7 @@ use crate::utility::NonGenericTypeInfoCell; use crate::{ - DynamicInfo, FromReflect, GetTypeRegistration, Reflect, ReflectMut, ReflectRef, - ReflectTypeName, TypeInfo, TypeName, TypeRegistration, Typed, UnnamedField, + DynamicInfo, FromReflect, GetTypeRegistration, Reflect, ReflectMut, ReflectRef, TypeInfo, + TypeName, TypeRegistration, Typed, UnnamedField, }; use std::any::{Any, TypeId}; use std::fmt::{Debug, Formatter}; @@ -229,12 +229,6 @@ impl DynamicTuple { } } -impl ReflectTypeName for DynamicTuple { - fn type_name(&self) -> &str { - self.name.as_str() - } -} - impl Tuple for DynamicTuple { #[inline] fn field(&self, index: usize) -> Option<&dyn Reflect> { @@ -273,6 +267,11 @@ impl Tuple for DynamicTuple { } impl Reflect for DynamicTuple { + #[inline] + fn type_name(&self) -> &str { + &self.name + } + #[inline] fn get_type_info(&self) -> &'static TypeInfo { ::type_info() @@ -467,6 +466,11 @@ macro_rules! impl_reflect_tuple { } impl<$($name: Reflect + TypeName),*> Reflect for ($($name,)*) { + #[inline] + fn type_name(&self) -> &str { + ::name() + } + fn get_type_info(&self) -> &'static TypeInfo { ::type_info() } diff --git a/crates/bevy_reflect/src/tuple_struct.rs b/crates/bevy_reflect/src/tuple_struct.rs index e0352268145c6..92e58ba4a9687 100644 --- a/crates/bevy_reflect/src/tuple_struct.rs +++ b/crates/bevy_reflect/src/tuple_struct.rs @@ -1,7 +1,6 @@ use crate::utility::NonGenericTypeInfoCell; use crate::{ - DynamicInfo, Reflect, ReflectMut, ReflectRef, ReflectTypeName, TypeInfo, TypeName, Typed, - UnnamedField, + DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, TypeName, Typed, UnnamedField, }; use std::any::{Any, TypeId}; use std::fmt::{Debug, Formatter}; @@ -218,12 +217,6 @@ impl DynamicTupleStruct { } } -impl ReflectTypeName for DynamicTupleStruct { - fn type_name(&self) -> &str { - self.name.as_str() - } -} - impl TupleStruct for DynamicTupleStruct { #[inline] fn field(&self, index: usize) -> Option<&dyn Reflect> { @@ -261,6 +254,11 @@ impl TupleStruct for DynamicTupleStruct { } impl Reflect for DynamicTupleStruct { + #[inline] + fn type_name(&self) -> &str { + &self.name + } + #[inline] fn get_type_info(&self) -> &'static TypeInfo { ::type_info() diff --git a/crates/bevy_reflect/src/type_name.rs b/crates/bevy_reflect/src/type_name.rs index 16049cac45dd7..55b643559e705 100644 --- a/crates/bevy_reflect/src/type_name.rs +++ b/crates/bevy_reflect/src/type_name.rs @@ -5,20 +5,6 @@ pub trait TypeName { fn name() -> &'static str; } -/// An object-safe version of [`TypeName`]. -/// -/// Automatically implemented via blanket implementation. -pub trait ReflectTypeName { - fn type_name(&self) -> &str; -} - -impl ReflectTypeName for T { - #[inline] - fn type_name(&self) -> &str { - Self::name() - } -} - macro_rules! impl_type_name_tuple { ( $($t:tt),* From 11889a19a1cca4491e7fcc04ea77c3de828b890e Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sat, 27 Aug 2022 20:01:47 +0200 Subject: [PATCH 16/87] allow custom type name for impl_reflect_value --- .../bevy_reflect_derive/src/lib.rs | 19 +++++++----- .../bevy_reflect_derive/src/reflect_value.rs | 31 ++++++++++++++++++- 2 files changed, 42 insertions(+), 8 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index ca2e905548bde..45a7a742e5c72 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -30,7 +30,7 @@ mod utility; use crate::derive_data::{ReflectDerive, ReflectMeta, ReflectStruct}; use proc_macro::TokenStream; use quote::quote; -use reflect_value::ReflectValueDef; +use reflect_value::{NamedReflectValueDef, ReflectValueDef}; use syn::spanned::Spanned; use syn::{parse_macro_input, DeriveInput}; use type_name::TypeNameDef; @@ -132,12 +132,17 @@ pub fn reflect_trait(args: TokenStream, input: TokenStream) -> TokenStream { #[proc_macro] pub fn impl_reflect_value(input: TokenStream) -> TokenStream { - let def = parse_macro_input!(input as ReflectValueDef); + let def = parse_macro_input!(input as NamedReflectValueDef); + + let reflected_type_name = def + .reflected_type_name + .unwrap_or_else(|| def.def.type_name.to_string()); + impls::impl_value(&ReflectMeta::new( - &def.type_name, - &def.generics, - def.traits.unwrap_or_default(), - Some(def.type_name.to_string()), + &def.def.type_name, + &def.def.generics, + def.def.traits.unwrap_or_default(), + Some(reflected_type_name), )) } @@ -214,7 +219,7 @@ pub fn impl_from_reflect_value(input: TokenStream) -> TokenStream { &def.type_name, &def.generics, def.traits.unwrap_or_default(), - None, // TODO + None, )) } diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs b/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs index ec54b99a6f404..37d98ef303a89 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs @@ -2,7 +2,7 @@ use crate::container_attributes::ReflectTraits; use proc_macro2::Ident; use syn::parse::{Parse, ParseStream}; use syn::token::{Paren, Where}; -use syn::{parenthesized, Generics}; +use syn::{parenthesized, Generics, LitStr, Token}; /// A struct used to define a simple reflected value type (such as primitives). /// @@ -52,3 +52,32 @@ impl Parse for ReflectValueDef { }) } } + +/// A [`ReflectValueDef`] that allow an optional custom type name in front. +/// +/// ```ignore +/// @"my_lib::MyType" foo where T1: Bar (TraitA, TraitB) +/// ``` +pub(crate) struct NamedReflectValueDef { + pub reflected_type_name: Option, + pub def: ReflectValueDef, +} + +impl Parse for NamedReflectValueDef { + fn parse(input: ParseStream) -> syn::Result { + let lookahead = input.lookahead1(); + let mut reflected_type_name = None; + if lookahead.peek(Token![@]) { + let _at: Token![@] = input.parse()?; + let name: LitStr = input.parse()?; + reflected_type_name = Some(name.value()); + } + + let def = input.parse()?; + + Ok(Self { + reflected_type_name, + def, + }) + } +} From fe2ff0b50868390de8ec9e2e1b0e3ae3ced27239 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sat, 27 Aug 2022 20:02:05 +0200 Subject: [PATCH 17/87] glam type name --- crates/bevy_reflect/src/impls/glam.rs | 88 +++++++++++++++++++++++++-- 1 file changed, 83 insertions(+), 5 deletions(-) diff --git a/crates/bevy_reflect/src/impls/glam.rs b/crates/bevy_reflect/src/impls/glam.rs index c84fcbffaaf27..e9f8e5b8580c2 100644 --- a/crates/bevy_reflect/src/impls/glam.rs +++ b/crates/bevy_reflect/src/impls/glam.rs @@ -7,6 +7,7 @@ use glam::*; impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::IVec2")] struct IVec2 { x: i32, y: i32, @@ -14,6 +15,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::IVec3")] struct IVec3 { x: i32, y: i32, @@ -22,6 +24,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::IVec4")] struct IVec4 { x: i32, y: i32, @@ -32,6 +35,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::UVec2")] struct UVec2 { x: u32, y: u32, @@ -39,6 +43,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::UVec3")] struct UVec3 { x: u32, y: u32, @@ -47,6 +52,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::UVec4")] struct UVec4 { x: u32, y: u32, @@ -57,6 +63,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::Vec2")] struct Vec2 { x: f32, y: f32, @@ -64,6 +71,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::Vec3")] struct Vec3 { x: f32, y: f32, @@ -72,6 +80,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::Vec3A")] struct Vec3A { x: f32, y: f32, @@ -80,6 +89,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::Vec4")] struct Vec4 { x: f32, y: f32, @@ -90,6 +100,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Default)] + #[type_name("glam::BVec2")] struct BVec2 { x: bool, y: bool, @@ -97,6 +108,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Default)] + #[type_name("glam::BVec3")] struct BVec3 { x: bool, y: bool, @@ -105,6 +117,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Default)] + #[type_name("glam::BVec4")] struct BVec4 { x: bool, y: bool, @@ -115,6 +128,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::DVec2")] struct DVec2 { x: f64, y: f64, @@ -122,6 +136,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::DVec3")] struct DVec3 { x: f64, y: f64, @@ -130,6 +145,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::DVec4")] struct DVec4 { x: f64, y: f64, @@ -140,6 +156,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::Mat2")] struct Mat2 { x_axis: Vec2, y_axis: Vec2, @@ -147,6 +164,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::Mat3")] struct Mat3 { x_axis: Vec3, y_axis: Vec3, @@ -155,6 +173,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::Mat3A")] struct Mat3A { x_axis: Vec3A, y_axis: Vec3A, @@ -163,6 +182,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::Mat4")] struct Mat4 { x_axis: Vec4, y_axis: Vec4, @@ -173,6 +193,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::DMat2")] struct DMat2 { x_axis: DVec2, y_axis: DVec2, @@ -180,6 +201,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::DMat3")] struct DMat3 { x_axis: DVec3, y_axis: DVec3, @@ -188,6 +210,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::DMat4")] struct DMat4 { x_axis: DVec4, y_axis: DVec4, @@ -198,6 +221,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::Affine2")] struct Affine2 { matrix2: Mat2, translation: Vec2, @@ -205,6 +229,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::Affine3A")] struct Affine3A { matrix3: Mat3A, translation: Vec3A, @@ -213,6 +238,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::DAffine2")] struct DAffine2 { matrix2: DMat2, translation: DVec2, @@ -220,6 +246,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] + #[type_name("glam::DAffine3")] struct DAffine3 { matrix3: DMat3, translation: DVec3, @@ -230,18 +257,69 @@ impl_reflect_struct!( // mechanisms for read-only fields. I doubt those mechanisms would be added, // so for now quaternions will remain as values. They are represented identically // to Vec4 and DVec4, so you may use those instead and convert between. -impl_reflect_value!(Quat(Debug, PartialEq, Serialize, Deserialize, Default)); -impl_reflect_value!(DQuat(Debug, PartialEq, Serialize, Deserialize, Default)); +impl_reflect_value!(@"glam::Quat" Quat(Debug, PartialEq, Serialize, Deserialize, Default)); +impl_reflect_value!(@"glam::DQuat" DQuat(Debug, PartialEq, Serialize, Deserialize, Default)); impl_from_reflect_value!(Quat); impl_from_reflect_value!(DQuat); -impl_reflect_value!(EulerRot(Debug, Default)); +impl_reflect_value!(@"glam::EulerRot" EulerRot(Debug, Default)); // glam type aliases these to the non simd versions when there is no support (this breaks wasm builds for example) // ideally it shouldn't do that and there's an issue on glam for this // https://github.com/bitshifter/glam-rs/issues/306 #[cfg(any(target_feature = "sse2", target_feature = "simd128"))] -impl_reflect_value!(BVec3A(Debug, PartialEq, Default)); +impl_reflect_value!(@"glam::BVec3A" BVec3A(Debug, PartialEq, Default)); #[cfg(any(target_feature = "sse2", target_feature = "simd128"))] -impl_reflect_value!(BVec4A(Debug, PartialEq, Default)); +impl_reflect_value!(@"glam::BVec4A" BVec4A(Debug, PartialEq, Default)); + +#[cfg(test)] +mod tests { + use glam::*; + + use crate::TypeName; + + #[test] + fn type_name_should_be_prefixed_with_glam() { + macro_rules! assert_name { + ($t:ty) => { + assert_eq!(<$t as TypeName>::name(), concat!("glam::", stringify!($t))) + }; + } + + assert_name!(IVec2); + assert_name!(IVec3); + assert_name!(IVec4); + assert_name!(UVec2); + assert_name!(UVec3); + assert_name!(UVec4); + assert_name!(Vec2); + assert_name!(Vec3); + assert_name!(Vec3A); + assert_name!(Vec4); + assert_name!(BVec2); + assert_name!(BVec3); + assert_name!(BVec4); + assert_name!(DVec2); + assert_name!(DVec3); + assert_name!(DVec4); + assert_name!(Mat2); + assert_name!(Mat3); + assert_name!(Mat3A); + assert_name!(Mat4); + assert_name!(DMat2); + assert_name!(DMat3); + assert_name!(DMat4); + assert_name!(Affine2); + assert_name!(Affine3A); + assert_name!(DAffine2); + assert_name!(DAffine2); + assert_name!(Quat); + assert_name!(DQuat); + assert_name!(EulerRot); + #[cfg(any(target_feature = "sse2", target_feature = "simd128"))] + assert_name!(BVec3A); + #[cfg(any(target_feature = "sse2", target_feature = "simd128"))] + assert_name!(BVec4A); + } +} From e7fc22212eb12cfe8bf47ef4872f62fea711e4cd Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sat, 27 Aug 2022 20:05:15 +0200 Subject: [PATCH 18/87] fix glam tests --- crates/bevy_reflect/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index f18d84fb09b67..cf3663d0b66b9 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -946,13 +946,13 @@ bevy_reflect::tests::Test { assert_eq!( result, - r#"{"type":"glam::f32::vec3::Vec3","struct":{"x":{"type":"f32","value":12.0},"y":{"type":"f32","value":3.0},"z":{"type":"f32","value":-6.9}}}"# + r#"{"type":"glam::Vec3","struct":{"x":{"type":"f32","value":12.0},"y":{"type":"f32","value":3.0},"z":{"type":"f32","value":-6.9}}}"# ); } #[test] fn vec3_deserialization() { - let data = r#"{"type":"glam::vec3::Vec3","struct":{"x":{"type":"f32","value":12},"y":{"type":"f32","value":3},"z":{"type":"f32","value":-6.9}}}"#; + let data = r#"{"type":"glam::Vec3","struct":{"x":{"type":"f32","value":12},"y":{"type":"f32","value":3},"z":{"type":"f32","value":-6.9}}}"#; let mut registry = TypeRegistry::default(); registry.add_registration(Vec3::get_type_registration()); From ca5e875682f90d88f83ed78d915e262c66a10d1b Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sat, 27 Aug 2022 20:15:04 +0200 Subject: [PATCH 19/87] fix GenericDataCell soft lock --- crates/bevy_reflect/src/utility.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index b3957dd34eade..e5efb23506a7c 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -57,13 +57,13 @@ impl GenericDataCell { return info; } - mapping.write().entry(type_id).or_insert_with(|| { - // We leak here in order to obtain a `&'static` reference. - // Otherwise, we won't be able to return a reference due to the `RwLock`. - // This should be okay, though, since we expect it to remain statically - // available over the course of the application. - Box::leak(Box::new(f())) - }) + // We leak here in order to obtain a `&'static` reference. + // Otherwise, we won't be able to return a reference due to the `RwLock`. + // This should be okay, though, since we expect it to remain statically + // available over the course of the application. + let value = Box::leak(Box::new(f())); + + mapping.write().entry(type_id).or_insert(value) } } From 0563cf9d05999487d1002580bf1dce571e82f2c9 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Sun, 28 Aug 2022 14:06:41 +0200 Subject: [PATCH 20/87] Update crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs index d9dd2422af48b..0d3289f9f75cf 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs @@ -134,7 +134,7 @@ impl<'a> ReflectDerive<'a> { force_reflect_value = true; traits = ReflectTraits::from_nested_metas(&meta_list.nested); } else if ident == TYPE_NAME_ATTRIBUTE_NAME { - let type_name = get_type_name_attribute(&meta_list.nested).ok_or_else(||syn::Error::new(meta_list.span(), format!("The attribute `{TYPE_NAME_ATTRIBUTE_NAME}` require a single literal string. \n\n #[{TYPE_NAME_ATTRIBUTE_NAME}(\"my_lib::foo\")]")) )?; + let type_name = get_type_name_attribute(&meta_list.nested).ok_or_else(|| syn::Error::new(meta_list.span(), format!("the attribute `{TYPE_NAME_ATTRIBUTE_NAME}` requires a single string literal. For example: `#[{TYPE_NAME_ATTRIBUTE_NAME}(\"my_lib::foo\")]`")) )?; reflected_type_name = Some(type_name); } } From be2b3d5477d60d5b2de6080892199fbcc2aae896 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Sun, 28 Aug 2022 14:07:57 +0200 Subject: [PATCH 21/87] Update crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs b/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs index 37d98ef303a89..a37cf4057528f 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs @@ -55,8 +55,10 @@ impl Parse for ReflectValueDef { /// A [`ReflectValueDef`] that allow an optional custom type name in front. /// +/// # Example +/// /// ```ignore -/// @"my_lib::MyType" foo where T1: Bar (TraitA, TraitB) +/// impl_reflect_value!(@"my_lib::MyType" Foo where T1: Bar (TraitA, TraitB)); /// ``` pub(crate) struct NamedReflectValueDef { pub reflected_type_name: Option, From 8cd535abccfaf61baeeeaba60a6508958d0cfbf3 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Sun, 28 Aug 2022 14:14:00 +0200 Subject: [PATCH 22/87] Update crates/bevy_reflect/src/impls/std.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/src/impls/std.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index 0faf4685e43da..11b034656040c 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -94,7 +94,7 @@ impl_type_name!(Vec); impl_type_name!(HashMap); impl_type_name!(Option); -// impl_type_name expecte a type name followed by generic between `<` and `>`. +// impl_type_name expects a type name followed by generic between `<` and `>`. // so array is manually implemented. impl TypeName for [T; N] { fn name() -> &'static str { From 8af97fc3d2ad5da00dff54213ab92759c815b8a3 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Sun, 28 Aug 2022 14:19:01 +0200 Subject: [PATCH 23/87] Update crates/bevy_reflect/src/type_info.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/src/type_info.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/src/type_info.rs b/crates/bevy_reflect/src/type_info.rs index 16491689295a3..670ae22be8ab7 100644 --- a/crates/bevy_reflect/src/type_info.rs +++ b/crates/bevy_reflect/src/type_info.rs @@ -47,7 +47,7 @@ use std::any::{Any, TypeId}; /// } /// /// # impl TypeName for MyStruct { -/// # fn name() -> std::borrow::Cow<'static, str> { todo!() } +/// # fn name() -> &'static str { "MyStruct" } /// # } /// # /// # impl Reflect for MyStruct { From eb1e2f6c90cbd4d50e05b4cadb0c64b07f82ea15 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Sun, 28 Aug 2022 14:20:02 +0200 Subject: [PATCH 24/87] Update crates/bevy_reflect/src/utility.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/src/utility.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index e5efb23506a7c..6bed9379ee013 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -95,7 +95,7 @@ impl GenericDataCell { /// } /// } /// # impl TypeName for Foo { -/// # fn name() -> std::borrow::Cow<'static, str> { todo!() } +/// # fn name() -> &'static str { "Foo" } /// # } /// # /// # impl Reflect for Foo { From 80b22d8d2b73660f876af8c0a13ccf13211400d3 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Sun, 28 Aug 2022 14:21:01 +0200 Subject: [PATCH 25/87] Update crates/bevy_reflect/src/utility.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/src/utility.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index 6bed9379ee013..4db1afcee7258 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -140,7 +140,7 @@ pub type NonGenericTypeInfoCell = NonGenericDataCell; /// } /// /// # impl TypeName for Foo { -/// # fn name() -> std::borrow::Cow<'static, str> { todo!() } +/// # fn name() -> &'static str { todo!() } /// # } /// # /// # impl Reflect for Foo { From 9682cec10be33a49452263c426920b279cba5a63 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 14:25:03 +0200 Subject: [PATCH 26/87] remove unnecessary `as_ref()` --- crates/bevy_reflect/src/enums/dynamic_enum.rs | 2 +- crates/bevy_reflect/src/struct_trait.rs | 2 +- crates/bevy_reflect/src/tuple.rs | 2 +- crates/bevy_reflect/src/tuple_struct.rs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/bevy_reflect/src/enums/dynamic_enum.rs b/crates/bevy_reflect/src/enums/dynamic_enum.rs index 34e6834bd036c..b4385a509ccc3 100644 --- a/crates/bevy_reflect/src/enums/dynamic_enum.rs +++ b/crates/bevy_reflect/src/enums/dynamic_enum.rs @@ -61,7 +61,7 @@ impl From<()> for DynamicVariant { /// /// // Create a DynamicEnum to represent the new value /// let mut dyn_enum = DynamicEnum::new( -/// ReflectTypeName::type_name(&value).as_ref(), +/// ReflectTypeName::type_name(&value), /// "None", /// DynamicVariant::Unit /// ); diff --git a/crates/bevy_reflect/src/struct_trait.rs b/crates/bevy_reflect/src/struct_trait.rs index 8b330f7f2f146..41b2caaac2571 100644 --- a/crates/bevy_reflect/src/struct_trait.rs +++ b/crates/bevy_reflect/src/struct_trait.rs @@ -492,7 +492,7 @@ pub fn struct_partial_eq(a: &S, b: &dyn Reflect) -> Option { /// ``` #[inline] pub fn struct_debug(dyn_struct: &dyn Struct, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let mut debug = f.debug_struct(dyn_struct.type_name().as_ref()); + let mut debug = f.debug_struct(dyn_struct.type_name()); for field_index in 0..dyn_struct.field_len() { let field = dyn_struct.field_at(field_index).unwrap(); debug.field( diff --git a/crates/bevy_reflect/src/tuple.rs b/crates/bevy_reflect/src/tuple.rs index d931f7c4be041..6e95b036a9efe 100644 --- a/crates/bevy_reflect/src/tuple.rs +++ b/crates/bevy_reflect/src/tuple.rs @@ -223,7 +223,7 @@ impl DynamicTuple { if i > 0 { name.push_str(", "); } - name.push_str(field.type_name().as_ref()); + name.push_str(field.type_name()); } name.push(')'); } diff --git a/crates/bevy_reflect/src/tuple_struct.rs b/crates/bevy_reflect/src/tuple_struct.rs index 92e58ba4a9687..5b6dffe44fb3d 100644 --- a/crates/bevy_reflect/src/tuple_struct.rs +++ b/crates/bevy_reflect/src/tuple_struct.rs @@ -401,7 +401,7 @@ pub fn tuple_struct_debug( dyn_tuple_struct: &dyn TupleStruct, f: &mut std::fmt::Formatter<'_>, ) -> std::fmt::Result { - let mut debug = f.debug_tuple(dyn_tuple_struct.type_name().as_ref()); + let mut debug = f.debug_tuple(dyn_tuple_struct.type_name()); for field in dyn_tuple_struct.iter_fields() { debug.field(&field as &dyn Debug); } From d9d3afa82cea2b72b94df6af5248cf409920813f Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 14:26:45 +0200 Subject: [PATCH 27/87] rm last usage of `ReflectTypeName` --- crates/bevy_reflect/src/enums/dynamic_enum.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/bevy_reflect/src/enums/dynamic_enum.rs b/crates/bevy_reflect/src/enums/dynamic_enum.rs index b4385a509ccc3..d0f097e977b1e 100644 --- a/crates/bevy_reflect/src/enums/dynamic_enum.rs +++ b/crates/bevy_reflect/src/enums/dynamic_enum.rs @@ -54,14 +54,14 @@ impl From<()> for DynamicVariant { /// # Example /// /// ``` -/// # use bevy_reflect::{DynamicEnum, DynamicVariant, Reflect, ReflectTypeName}; +/// # use bevy_reflect::{DynamicEnum, DynamicVariant, Reflect}; /// /// // The original enum value /// let mut value: Option = Some(123); /// /// // Create a DynamicEnum to represent the new value /// let mut dyn_enum = DynamicEnum::new( -/// ReflectTypeName::type_name(&value), +/// Reflect::type_name(&value), /// "None", /// DynamicVariant::Unit /// ); From 329f248486f9c1d240f3d65a7268b70375061a7c Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 14:29:52 +0200 Subject: [PATCH 28/87] rm old comment --- crates/bevy_asset/src/asset_server.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/bevy_asset/src/asset_server.rs b/crates/bevy_asset/src/asset_server.rs index cf64e1e39455b..8bdfc81502333 100644 --- a/crates/bevy_asset/src/asset_server.rs +++ b/crates/bevy_asset/src/asset_server.rs @@ -650,7 +650,6 @@ mod test { use bevy_reflect::{TypeName, TypeUuid}; use bevy_utils::BoxedFuture; - // FIXME: reflect only the type name #[derive(Debug, TypeUuid, TypeName)] #[uuid = "a5189b72-0572-4290-a2e0-96f73a491c44"] struct PngAsset; From e6a3ce867e0731434a7c5b53af94ff31e9a2c857 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 14:39:06 +0200 Subject: [PATCH 29/87] refactor(reflect_derive): if-else into match --- .../bevy_reflect_derive/src/derive_data.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs index 0d3289f9f75cf..36d16de2f7236 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs @@ -127,16 +127,19 @@ impl<'a> ReflectDerive<'a> { continue; }; - if let Some(ident) = meta_list.path.get_ident() { - if ident == REFLECT_ATTRIBUTE_NAME { + match meta_list.path.get_ident() { + Some(ident) if ident == REFLECT_ATTRIBUTE_NAME => { traits = ReflectTraits::from_nested_metas(&meta_list.nested); - } else if ident == REFLECT_VALUE_ATTRIBUTE_NAME { + } + Some(ident) if ident == REFLECT_VALUE_ATTRIBUTE_NAME => { force_reflect_value = true; traits = ReflectTraits::from_nested_metas(&meta_list.nested); - } else if ident == TYPE_NAME_ATTRIBUTE_NAME { + } + Some(ident) if ident == TYPE_NAME_ATTRIBUTE_NAME => { let type_name = get_type_name_attribute(&meta_list.nested).ok_or_else(|| syn::Error::new(meta_list.span(), format!("the attribute `{TYPE_NAME_ATTRIBUTE_NAME}` requires a single string literal. For example: `#[{TYPE_NAME_ATTRIBUTE_NAME}(\"my_lib::foo\")]`")) )?; reflected_type_name = Some(type_name); } + _ => {} } } From 4722a19096f5510892667123ea1dd8c02f99537a Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Sun, 28 Aug 2022 14:44:58 +0200 Subject: [PATCH 30/87] Update crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- .../bevy_reflect_derive/src/impls/type_name.rs | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs index 2983455386cf1..389440ef832a0 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs @@ -34,16 +34,7 @@ pub(crate) fn impl_type_name( // FIXME: Iterator::intersperse can be used here // currently unstable https://github.com/rust-lang/rust/issues/79524 - let mut values = Vec::with_capacity(generics.params.len()); - for _ in 0..generics.params.len() - 1 { - // SAFETY: don't panic because we consume all but one item. - let x = getters.next().unwrap(); - values.push(quote! {#x,}); - } - // SAFETY: don't panic because the previous for loop didn't consume the last element - // and there is at least one generic parameter. - values.push(getters.next().unwrap()); - values.into_iter().collect::() + quote!(#(#getters),*) }; let brackets = { From aecba7702e5f0d18964640a349e717b2165d3b19 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Sun, 28 Aug 2022 14:47:00 +0200 Subject: [PATCH 31/87] Update crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- .../bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs index 389440ef832a0..f932aa921f827 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs @@ -41,9 +41,8 @@ pub(crate) fn impl_type_name( // FIXME: Iterator::intersperse can be used here // currently unstable https://github.com/rust-lang/rust/issues/79524 - let mut brackets = vec!["{}, "; generics.params.len()]; - *brackets.last_mut().unwrap() = "{}"; - brackets.into_iter().collect::() + let mut brackets = "{}".repeat(generics.params.len()); + quote!(#(#brackets),*) }; quote! { From b2be7e9bf3388822aa30561505b328c3a41848b5 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 14:54:49 +0200 Subject: [PATCH 32/87] reflect_derive: cleanup impl_type_name --- .../bevy_reflect_derive/src/impls/type_name.rs | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs index f932aa921f827..9cd94e7dcc052 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs @@ -1,4 +1,4 @@ -use proc_macro2::{Ident, TokenStream}; +use proc_macro2::Ident; use quote::quote; use syn::{Generics, Path}; @@ -16,7 +16,7 @@ pub(crate) fn impl_type_name( let get_type_name = if is_generic { let values = { - let mut getters = generics.params.iter().map(|p| match p { + let getters = generics.params.iter().map(|p| match p { syn::GenericParam::Type(p) => { let ty = &p.ident; quote!(<#ty as #bevy_reflect_path::TypeName>::name()) @@ -31,18 +31,12 @@ pub(crate) fn impl_type_name( } }); - // FIXME: Iterator::intersperse can be used here - // currently unstable https://github.com/rust-lang/rust/issues/79524 - quote!(#(#getters),*) }; let brackets = { - // FIXME: Iterator::intersperse can be used here - // currently unstable https://github.com/rust-lang/rust/issues/79524 - - let mut brackets = "{}".repeat(generics.params.len()); - quote!(#(#brackets),*) + let brackets = vec![quote!({}); generics.params.len()]; + quote!(#(#brackets),*).to_string() }; quote! { From 9ea7f9a8b32f31b682cf7f25db4caf686a7bca9a Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 14:59:45 +0200 Subject: [PATCH 33/87] reflect_derive: impl_type_name accept ReflectMeta as argument --- .../bevy_reflect_derive/src/impls/enums.rs | 7 +---- .../bevy_reflect_derive/src/impls/structs.rs | 7 +---- .../src/impls/tuple_structs.rs | 7 +---- .../src/impls/type_name.rs | 18 ++++++------ .../bevy_reflect_derive/src/impls/values.rs | 7 +---- .../bevy_reflect_derive/src/lib.rs | 28 +++---------------- 6 files changed, 17 insertions(+), 57 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs index 3f89ac4ca7c17..74acd84a8c58c 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs @@ -64,12 +64,7 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> TokenStream { bevy_reflect_path, ); - let type_name_impl = impl_type_name( - enum_name, - reflect_enum.meta().generics(), - reflect_enum.meta().reflected_type_name(), - bevy_reflect_path, - ); + let type_name_impl = impl_type_name(reflect_enum.meta()); let get_type_registration_impl = reflect_enum.meta().get_type_registration(); let (impl_generics, ty_generics, where_clause) = diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs index 29d36b6b24262..48d730c7a7f01 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs @@ -64,12 +64,7 @@ pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> TokenStream { bevy_reflect_path, ); - let type_name_impl = impl_type_name( - struct_name, - reflect_struct.meta().generics(), - reflect_struct.meta().reflected_type_name(), - bevy_reflect_path, - ); + let type_name_impl = impl_type_name(reflect_struct.meta()); let get_type_registration_impl = reflect_struct.meta().get_type_registration(); let (impl_generics, ty_generics, where_clause) = diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs index 150093c3e5758..78b63bc40aa46 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs @@ -48,12 +48,7 @@ pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> TokenStream { bevy_reflect_path, ); - let type_name_impl = impl_type_name( - struct_name, - reflect_struct.meta().generics(), - reflect_struct.meta().reflected_type_name(), - bevy_reflect_path, - ); + let type_name_impl = impl_type_name(reflect_struct.meta()); let (impl_generics, ty_generics, where_clause) = reflect_struct.meta().generics().split_for_impl(); diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs index 9cd94e7dcc052..7031c95026a2f 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs @@ -1,16 +1,16 @@ -use proc_macro2::Ident; use quote::quote; -use syn::{Generics, Path}; -pub(crate) fn impl_type_name( - type_name: &Ident, - generics: &Generics, - reflected_type_name: Option<&str>, - bevy_reflect_path: &Path, -) -> proc_macro2::TokenStream { +use crate::derive_data::ReflectMeta; + +pub(crate) fn impl_type_name(reflect_meta: &ReflectMeta) -> proc_macro2::TokenStream { + let generics = reflect_meta.generics(); + let type_name = reflect_meta.type_name(); + let bevy_reflect_path = reflect_meta.bevy_reflect_path(); + let is_generic = !generics.params.is_empty(); - let base_name = reflected_type_name + let base_name = reflect_meta + .reflected_type_name() .map(|x| quote!(#x)) .unwrap_or_else(|| quote!(concat!(module_path!(), "::", stringify!(#type_name)))); diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs index c254b828f3478..31bcf29182f69 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs @@ -22,12 +22,7 @@ pub(crate) fn impl_value(meta: &ReflectMeta) -> TokenStream { bevy_reflect_path, ); - let type_name_impl = impl_type_name( - type_name, - meta.generics(), - meta.reflected_type_name(), - bevy_reflect_path, - ); + let type_name_impl = impl_type_name(meta); let (impl_generics, ty_generics, where_clause) = meta.generics().split_for_impl(); let get_type_registration_impl = meta.get_type_registration(); diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index 45a7a742e5c72..8e42d80ce147b 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -70,24 +70,9 @@ pub fn derive_type_name(input: TokenStream) -> TokenStream { let s = match derive_data { ReflectDerive::TupleStruct(struct_data) | ReflectDerive::Struct(struct_data) - | ReflectDerive::UnitStruct(struct_data) => impls::impl_type_name( - struct_data.meta().type_name(), - struct_data.meta().generics(), - struct_data.meta().reflected_type_name(), - struct_data.meta().bevy_reflect_path(), - ), - ReflectDerive::Enum(meta) => impls::impl_type_name( - meta.meta().type_name(), - meta.meta().generics(), - meta.meta().reflected_type_name(), - meta.meta().bevy_reflect_path(), - ), - ReflectDerive::Value(meta) => impls::impl_type_name( - meta.type_name(), - meta.generics(), - meta.reflected_type_name(), - meta.bevy_reflect_path(), - ), + | ReflectDerive::UnitStruct(struct_data) => impls::impl_type_name(struct_data.meta()), + ReflectDerive::Enum(meta) => impls::impl_type_name(meta.meta()), + ReflectDerive::Value(meta) => impls::impl_type_name(&meta), }; TokenStream::from(s) @@ -232,10 +217,5 @@ pub fn impl_type_name(input: TokenStream) -> TokenStream { Default::default(), Some(def.type_name.to_string()), ); - TokenStream::from(impls::impl_type_name( - meta.type_name(), - meta.generics(), - meta.reflected_type_name(), - meta.bevy_reflect_path(), - )) + TokenStream::from(impls::impl_type_name(&meta)) } From b697bc3e1dc4cb58358b86c578071a42dca7981c Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 15:06:10 +0200 Subject: [PATCH 34/87] NamedReflectValueDef::get_reflected_type_name --- crates/bevy_reflect/bevy_reflect_derive/src/lib.rs | 4 +--- .../bevy_reflect_derive/src/reflect_value.rs | 11 +++++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index 8e42d80ce147b..2844cfef67cbc 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -119,9 +119,7 @@ pub fn reflect_trait(args: TokenStream, input: TokenStream) -> TokenStream { pub fn impl_reflect_value(input: TokenStream) -> TokenStream { let def = parse_macro_input!(input as NamedReflectValueDef); - let reflected_type_name = def - .reflected_type_name - .unwrap_or_else(|| def.def.type_name.to_string()); + let reflected_type_name = def.get_reflected_type_name(); impls::impl_value(&ReflectMeta::new( &def.def.type_name, diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs b/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs index a37cf4057528f..5a7aa46b27d07 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs @@ -65,6 +65,17 @@ pub(crate) struct NamedReflectValueDef { pub def: ReflectValueDef, } +impl NamedReflectValueDef { + /// Returns the string to use as the reflected type name. + /// + /// Use `reflected_type_name` if avaible otherwise use the `type_name` ident. + pub fn get_reflected_type_name(&self) -> String { + self.reflected_type_name + .clone() + .unwrap_or_else(|| self.def.type_name.to_string()) + } +} + impl Parse for NamedReflectValueDef { fn parse(input: ParseStream) -> syn::Result { let lookahead = input.lookahead1(); From a6654c1a67d5c7d41e33dd6dd3254efb063b24d4 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 15:07:42 +0200 Subject: [PATCH 35/87] reflect_derive: refactoring --- crates/bevy_reflect/bevy_reflect_derive/src/lib.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index 2844cfef67cbc..4e472d5889331 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -67,15 +67,14 @@ pub fn derive_type_name(input: TokenStream) -> TokenStream { Err(err) => return err.into_compile_error().into(), }; - let s = match derive_data { + match derive_data { ReflectDerive::TupleStruct(struct_data) | ReflectDerive::Struct(struct_data) | ReflectDerive::UnitStruct(struct_data) => impls::impl_type_name(struct_data.meta()), ReflectDerive::Enum(meta) => impls::impl_type_name(meta.meta()), ReflectDerive::Value(meta) => impls::impl_type_name(&meta), - }; - - TokenStream::from(s) + } + .into() } /// Derives the `FromReflect` trait. From 34f57b7e850d71cb38be5882fd62f69766bf7ce4 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 15:09:24 +0200 Subject: [PATCH 36/87] avoid usage of `stringify!` --- .../bevy_reflect_derive/src/impls/type_name.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs index 7031c95026a2f..1e70624633cc6 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs @@ -12,7 +12,10 @@ pub(crate) fn impl_type_name(reflect_meta: &ReflectMeta) -> proc_macro2::TokenSt let base_name = reflect_meta .reflected_type_name() .map(|x| quote!(#x)) - .unwrap_or_else(|| quote!(concat!(module_path!(), "::", stringify!(#type_name)))); + .unwrap_or_else(|| { + let type_name = type_name.to_string(); + quote!(concat!(module_path!(), "::", #type_name)) + }); let get_type_name = if is_generic { let values = { @@ -22,8 +25,8 @@ pub(crate) fn impl_type_name(reflect_meta: &ReflectMeta) -> proc_macro2::TokenSt quote!(<#ty as #bevy_reflect_path::TypeName>::name()) } syn::GenericParam::Lifetime(p) => { - let name = &p.lifetime.ident; - quote!(concat!("'", stringify!(#name))) + let name = &p.lifetime.ident.to_string(); + quote!(concat!("'", #name)) } syn::GenericParam::Const(p) => { let name = &p.ident; From 26460ddbacf113cd0fd3e9ed78c53bacebb39234 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 15:14:46 +0200 Subject: [PATCH 37/87] fix fmt in doc code --- crates/bevy_reflect/src/tuple_struct.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/src/tuple_struct.rs b/crates/bevy_reflect/src/tuple_struct.rs index 5b6dffe44fb3d..51726e3867338 100644 --- a/crates/bevy_reflect/src/tuple_struct.rs +++ b/crates/bevy_reflect/src/tuple_struct.rs @@ -15,7 +15,7 @@ use std::slice::Iter; /// `#[derive(Reflect)]`. /// /// ``` -/// use bevy_reflect::{Reflect,TupleStruct}; +/// use bevy_reflect::{Reflect, TupleStruct}; /// /// #[derive(Reflect)] /// struct Foo(String); From f4a665523af2d2fb10f19179f9f6f444bfd8dffa Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 15:16:35 +0200 Subject: [PATCH 38/87] fix utility doc --- crates/bevy_reflect/src/utility.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index 4db1afcee7258..30feaecb43987 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -99,6 +99,7 @@ impl GenericDataCell { /// # } /// # /// # impl Reflect for Foo { +/// # fn type_name(&self) -> &str { todo!() } /// # fn get_type_info(&self) -> &'static TypeInfo { todo!() } /// # fn into_any(self: Box) -> Box { todo!() } /// # fn as_any(&self) -> &dyn Any { todo!() } @@ -144,6 +145,7 @@ pub type NonGenericTypeInfoCell = NonGenericDataCell; /// # } /// # /// # impl Reflect for Foo { +/// # fn type_name(&self) -> &str { todo!() } /// # fn get_type_info(&self) -> &'static TypeInfo { todo!() } /// # fn into_any(self: Box) -> Box { todo!() } /// # fn as_any(&self) -> &dyn Any { todo!() } From 45eca48e97ad60d454bdd8766c04704d10cb0d66 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 15:17:43 +0200 Subject: [PATCH 39/87] rm useless `as_ref()` --- crates/bevy_scene/src/dynamic_scene.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_scene/src/dynamic_scene.rs b/crates/bevy_scene/src/dynamic_scene.rs index e92445f7658b7..2fd36bd1d09b0 100644 --- a/crates/bevy_scene/src/dynamic_scene.rs +++ b/crates/bevy_scene/src/dynamic_scene.rs @@ -99,7 +99,7 @@ impl DynamicScene { // Apply/ add each component to the given entity. for component in &scene_entity.components { let registration = type_registry - .get_with_name(component.type_name().as_ref()) + .get_with_name(component.type_name()) .ok_or_else(|| SceneSpawnError::UnregisteredType { type_name: component.type_name().to_string(), })?; From e2e3a02369f144f0cf5dbd8932e5a0241d92561f Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 15:20:07 +0200 Subject: [PATCH 40/87] example: add comment --- examples/reflection/generic_reflection.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/reflection/generic_reflection.rs b/examples/reflection/generic_reflection.rs index 0ef588f4b0c52..3c2c057deca15 100644 --- a/examples/reflection/generic_reflection.rs +++ b/examples/reflection/generic_reflection.rs @@ -13,6 +13,8 @@ fn main() { } #[derive(Reflect)] +// Because `#[derive(Reflect)]` also derive `TypeName` for `MyType`, +// the generic parameter must also implement `TypeName`. struct MyType { value: T, } From 3f2ee5da0ab94428dae8a62f7bc57f3bb8f6523c Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 15:23:16 +0200 Subject: [PATCH 41/87] reflect_derive: cleanup get_type_name_attribute --- .../bevy_reflect_derive/src/derive_data.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs index 36d16de2f7236..9269c96496906 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs @@ -340,10 +340,13 @@ impl<'a> ReflectEnum<'a> { /// Extracts the type name attribute or returns [`None`]. fn get_type_name_attribute(nested_metas: &Punctuated) -> Option { - (nested_metas.len() == 1) - .then(|| match nested_metas.first().unwrap() { - NestedMeta::Lit(Lit::Str(s)) => Some(s.value()), + // Having more than 1 element in nested_metas is invalid. + if nested_metas.len() == 1 { + match nested_metas.first() { + Some(NestedMeta::Lit(Lit::Str(s))) => Some(s.value()), _ => None, - }) - .flatten() + } + } else { + None + } } From ba4da305c5c50c3235cb97313a53ddedcfa34a74 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 15:29:38 +0200 Subject: [PATCH 42/87] doc: impl_type_name --- crates/bevy_reflect/bevy_reflect_derive/src/lib.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index 4e472d5889331..f16c279688d06 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -205,6 +205,18 @@ pub fn impl_from_reflect_value(input: TokenStream) -> TokenStream { )) } +/// A replacement for `#[derive(TypeName)]` to be used with foreign types which +/// the definitions of cannot be altered. +/// +/// But unlike `#[derive(TypeName)]` that prefix the type name with the module path +/// using the macro [`module_path`], `impl_type_name` use only the ident of the type +/// as type name. +/// +/// # Example +/// Implementing `TypeName` for `Vec`: +/// ```ignore +/// impl_type_name!(Vec); +/// ``` #[proc_macro] pub fn impl_type_name(input: TokenStream) -> TokenStream { let def = parse_macro_input!(input as TypeNameDef); From d8987f42bbc5ba73fdac85b2c1fbea19b512d975 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 15:54:31 +0200 Subject: [PATCH 43/87] doc: derive_type_name --- .../bevy_reflect_derive/src/lib.rs | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index f16c279688d06..cf7011dd18927 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -58,6 +58,89 @@ pub fn derive_reflect(input: TokenStream) -> TokenStream { } } +/// Implement [`TypeName`] on a type. The type name is automatically deducted following a +/// specific convention. +/// +/// ## Type name convetion +/// +/// The type name is the module path followed by the ident of the type. +/// If the type is generic the type name of it's generic parameter is included between `<` and `>`. +/// +/// See examples. +/// +/// ## Custom type name +/// +/// It's possible to override the default behaviour and choosing a custom type name by using +/// the `type_name` attribute after the `derive` attribute. +/// +/// A common usage is to using your crate name instead of the complete module path. +/// +/// It's highly discouraged to using unprefixed type name that could collide with another type +/// or an malformed type name (e.g. `BlAH@blah blah`). +/// +/// ## Manual implementation +/// +/// For some reason you may need to manually implement [`TypeName`]. +/// +/// ```ignore +/// bevy_reflect::TypeName; +/// +/// struct MyType; +/// +/// impl TypeName for MyType{ +/// fn name() -> &'static str { +/// concat!(module_path!(), "::", "MyType") +/// } +/// } +/// ``` +/// +/// If your type is generic you must use +/// [`GenericTypeNameCell`][bevy_reflect::utility::GenericTypeNameCell]. +/// +/// ```ignore +/// bevy_reflect::{TypeName, utility::GenericTypeNameCell}; +/// +/// struct MyType(T); +/// +/// impl TypeName for MyType { +/// fn name() -> &'static str { +/// static CELL: GenericTypeNameCell = GenericTypeNameCell::new(); +/// CELL.get_or_insert::(|| { +/// format!(concat!(module_path!(), "::MyType<{}>"), T::name()) +/// }) +/// } +/// } +/// ``` +/// +/// ## Example +/// +/// ```ignore +/// # bevy_reflect::TypeName; +/// +/// mod a { +/// pub mod b { +/// pub mod c { +/// #[derive(TypeName)] +/// pub struct ABC; +/// } +/// +/// #[derive(TypeName)] +/// #[type_name("my_lib::AB")] +/// pub struct AB(T); +/// } +/// +/// #[derive(TypeName)] +/// pub struct A(N); +/// } +/// +/// # use a::A; +/// # use a::b::AB; +/// # use a::b::c::ABC; +/// +/// assert_eq!(ABC::name(), "a::b::c::ABC"); +/// assert_eq!(AB::::name(), "my_lib::AB"); +/// assert_eq!(A::<5>::name(), "a::A<5>"); +/// ``` #[proc_macro_derive(TypeName, attributes(module, type_name))] pub fn derive_type_name(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); From d1555295d449b3617f95d5e1290db7e69efc1fa3 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 17:27:56 +0200 Subject: [PATCH 44/87] TypeName is 'static --- .../bevy_reflect_derive/src/lib.rs | 2 +- crates/bevy_reflect/src/impls/smallvec.rs | 2 +- crates/bevy_reflect/src/impls/std.rs | 21 +++++++++++-------- crates/bevy_reflect/src/lib.rs | 4 ++-- crates/bevy_reflect/src/type_name.rs | 4 ++-- 5 files changed, 18 insertions(+), 15 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index cf7011dd18927..23d133a0107cc 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -298,7 +298,7 @@ pub fn impl_from_reflect_value(input: TokenStream) -> TokenStream { /// # Example /// Implementing `TypeName` for `Vec`: /// ```ignore -/// impl_type_name!(Vec); +/// impl_type_name!(Vec); /// ``` #[proc_macro] pub fn impl_type_name(input: TokenStream) -> TokenStream { diff --git a/crates/bevy_reflect/src/impls/smallvec.rs b/crates/bevy_reflect/src/impls/smallvec.rs index e634f9e1967a9..9bff4f7865ac1 100644 --- a/crates/bevy_reflect/src/impls/smallvec.rs +++ b/crates/bevy_reflect/src/impls/smallvec.rs @@ -9,7 +9,7 @@ use crate::{ TypeRegistration, Typed, }; -impl_type_name!(SmallVec); +impl_type_name!(SmallVec); impl Array for SmallVec where diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index 11b034656040c..84978aee3c58f 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -38,9 +38,12 @@ impl_reflect_value!(isize(Debug, Hash, PartialEq, Serialize, Deserialize)); impl_reflect_value!(f32(Debug, PartialEq, Serialize, Deserialize)); impl_reflect_value!(f64(Debug, PartialEq, Serialize, Deserialize)); impl_reflect_value!(String(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(Result()); -impl_reflect_value!(HashSet()); -impl_reflect_value!(Range()); +impl_reflect_value!( + Result < T: Clone + Reflect + TypeName, + E: Clone + Reflect + TypeName > () +); +impl_reflect_value!(HashSet()); +impl_reflect_value!(Range()); impl_reflect_value!(Duration(Debug, Hash, PartialEq, Serialize, Deserialize)); impl_reflect_value!(Instant(Debug, Hash, PartialEq)); impl_reflect_value!(NonZeroI128(Debug, Hash, PartialEq, Serialize, Deserialize)); @@ -73,8 +76,8 @@ impl_from_reflect_value!(isize); impl_from_reflect_value!(f32); impl_from_reflect_value!(f64); impl_from_reflect_value!(String); -impl_from_reflect_value!(HashSet); -impl_from_reflect_value!(Range); +impl_from_reflect_value!(HashSet); +impl_from_reflect_value!(Range); impl_from_reflect_value!(Duration); impl_from_reflect_value!(Instant); impl_from_reflect_value!(NonZeroI128); @@ -90,13 +93,13 @@ impl_from_reflect_value!(NonZeroU16); impl_from_reflect_value!(NonZeroU8); impl_from_reflect_value!(NonZeroI8); -impl_type_name!(Vec); -impl_type_name!(HashMap); -impl_type_name!(Option); +impl_type_name!(Vec); +impl_type_name!(HashMap); +impl_type_name!(Option); // impl_type_name expects a type name followed by generic between `<` and `>`. // so array is manually implemented. -impl TypeName for [T; N] { +impl TypeName for [T; N] { fn name() -> &'static str { static CELL: GenericTypeNameCell = GenericTypeNameCell::new(); CELL.get_or_insert::(|| format!("[{}; {N}]", T::name())) diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index cf3663d0b66b9..e2a05840b308b 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -904,7 +904,7 @@ bevy_reflect::tests::Test { assert_eq!(name, "bevy_reflect::tests::Foo"); #[derive(TypeName)] - struct Goo { + struct Goo { _value: T, } let name = Goo::::name(); @@ -921,7 +921,7 @@ bevy_reflect::tests::Test { #[derive(TypeName)] #[type_name("MyType")] - struct Goo { + struct Goo { _value: T, } let name = Goo::::name(); diff --git a/crates/bevy_reflect/src/type_name.rs b/crates/bevy_reflect/src/type_name.rs index 55b643559e705..47eeda16df974 100644 --- a/crates/bevy_reflect/src/type_name.rs +++ b/crates/bevy_reflect/src/type_name.rs @@ -1,7 +1,7 @@ use crate::utility::GenericTypeNameCell; /// Provide the name of the type as string. -pub trait TypeName { +pub trait TypeName: 'static { fn name() -> &'static str; } @@ -9,7 +9,7 @@ macro_rules! impl_type_name_tuple { ( $($t:tt),* ) => { - impl<$($t: TypeName + 'static),*> TypeName for ($($t,)*) { + impl<$($t: TypeName),*> TypeName for ($($t,)*) { #[allow(non_snake_case)] fn name() -> &'static str { static CELL: GenericTypeNameCell = GenericTypeNameCell::new(); From 0c25180ab4d9aa0eac06ea89aacc65b06d560dd6 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 17:45:17 +0200 Subject: [PATCH 45/87] doc: TypeName --- crates/bevy_reflect/src/type_name.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/bevy_reflect/src/type_name.rs b/crates/bevy_reflect/src/type_name.rs index 47eeda16df974..7b80f2fe9f554 100644 --- a/crates/bevy_reflect/src/type_name.rs +++ b/crates/bevy_reflect/src/type_name.rs @@ -1,7 +1,18 @@ use crate::utility::GenericTypeNameCell; -/// Provide the name of the type as string. +/// Provide the name of the type as a string slice. +/// +/// This is a stable alternative to [`std::any::type_name`] whose output isn't guarentee +/// and may change between versions of the compiler. +/// +/// This trait may be derived via `#[derive(TypeName)]`. +/// Checkout the [derive macro documentation][bevy_reflect_derive::TypeName] for more details +/// about how this trait must be implemented. pub trait TypeName: 'static { + /// Returns the name of the type. + /// + /// This is a stable alternative to [`std::any::type_name`] whose output isn't guarentee + /// and may change between versions of the compiler. fn name() -> &'static str; } From b0a660415391c4fd0b5f1d99548d6e68c9a3693a Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 17:52:30 +0200 Subject: [PATCH 46/87] doc: GenericTypeNameCell --- crates/bevy_reflect/src/utility.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index 30feaecb43987..7ce33fe907e2d 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -161,4 +161,25 @@ pub type NonGenericTypeInfoCell = NonGenericDataCell; /// ``` pub type GenericTypeInfoCell = GenericDataCell; +/// A container for [`String`] over generic types, allowing instances to be stored statically. +/// +/// Used when implementing [`TypeName`][crate::TypeName] for generic type to store the type name. +/// +/// ## Example +/// +/// ``` +/// # use bevy_reflect::TypeName; +/// use bevy_reflect::utility::GenericTypeNameCell; +/// +/// struct Foo(T); +/// +/// impl TypeName for Foo { +/// fn name() -> &'static str { +/// static CELL: GenericTypeNameCell = GenericTypeNameCell::new(); +/// CELL.get_or_insert::(|| { +/// format!(concat!(module_path!(), "::Foo<{}>"), T::name()) +/// }) +/// } +/// } +/// ``` pub type GenericTypeNameCell = GenericDataCell; From 9ef14548cde6313394298b529ca8c98412d06a92 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 17:57:51 +0200 Subject: [PATCH 47/87] impl TypeName on `dyn Reflect` --- crates/bevy_reflect/src/reflect.rs | 7 ++++++- crates/bevy_reflect/src/type_info.rs | 6 +++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/bevy_reflect/src/reflect.rs b/crates/bevy_reflect/src/reflect.rs index 4c84458db4839..baf780ff6b5c6 100644 --- a/crates/bevy_reflect/src/reflect.rs +++ b/crates/bevy_reflect/src/reflect.rs @@ -210,11 +210,16 @@ impl Debug for dyn Reflect { impl Typed for dyn Reflect { fn type_info() -> &'static TypeInfo { static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new(); - // FIXME : how to build ValueInfo here with TypeName ? CELL.get_or_set(|| TypeInfo::Value(ValueInfo::new::())) } } +impl TypeName for dyn Reflect { + fn name() -> &'static str { + "dyn Reflect" + } +} + #[deny(rustdoc::broken_intra_doc_links)] impl dyn Reflect { /// Downcasts the value to type `T`, consuming the trait object. diff --git a/crates/bevy_reflect/src/type_info.rs b/crates/bevy_reflect/src/type_info.rs index 670ae22be8ab7..8308c4e7ddce9 100644 --- a/crates/bevy_reflect/src/type_info.rs +++ b/crates/bevy_reflect/src/type_info.rs @@ -1,5 +1,6 @@ use crate::{ ArrayInfo, EnumInfo, ListInfo, MapInfo, Reflect, StructInfo, TupleInfo, TupleStructInfo, + TypeName, }; use std::any::{Any, TypeId}; @@ -165,10 +166,9 @@ pub struct ValueInfo { } impl ValueInfo { - pub fn new() -> Self { - // FIXME: use TypeName instead of any::type_name. + pub fn new() -> Self { Self { - type_name: std::any::type_name::(), + type_name: T::name(), type_id: TypeId::of::(), } } From 83e3500d8ff168a79d5de8d30080437a5df975e4 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 18:19:29 +0200 Subject: [PATCH 48/87] fix docs --- .../bevy_reflect_derive/src/lib.rs | 34 ----------------- crates/bevy_reflect/src/type_info.rs | 1 + crates/bevy_reflect/src/type_name.rs | 38 +++++++++++++++++-- crates/bevy_reflect/src/utility.rs | 2 +- crates/bevy_sprite/src/mesh2d/material.rs | 4 +- 5 files changed, 39 insertions(+), 40 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index 23d133a0107cc..80c2b83f4df92 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -78,40 +78,6 @@ pub fn derive_reflect(input: TokenStream) -> TokenStream { /// It's highly discouraged to using unprefixed type name that could collide with another type /// or an malformed type name (e.g. `BlAH@blah blah`). /// -/// ## Manual implementation -/// -/// For some reason you may need to manually implement [`TypeName`]. -/// -/// ```ignore -/// bevy_reflect::TypeName; -/// -/// struct MyType; -/// -/// impl TypeName for MyType{ -/// fn name() -> &'static str { -/// concat!(module_path!(), "::", "MyType") -/// } -/// } -/// ``` -/// -/// If your type is generic you must use -/// [`GenericTypeNameCell`][bevy_reflect::utility::GenericTypeNameCell]. -/// -/// ```ignore -/// bevy_reflect::{TypeName, utility::GenericTypeNameCell}; -/// -/// struct MyType(T); -/// -/// impl TypeName for MyType { -/// fn name() -> &'static str { -/// static CELL: GenericTypeNameCell = GenericTypeNameCell::new(); -/// CELL.get_or_insert::(|| { -/// format!(concat!(module_path!(), "::MyType<{}>"), T::name()) -/// }) -/// } -/// } -/// ``` -/// /// ## Example /// /// ```ignore diff --git a/crates/bevy_reflect/src/type_info.rs b/crates/bevy_reflect/src/type_info.rs index 8308c4e7ddce9..656bb379fd4aa 100644 --- a/crates/bevy_reflect/src/type_info.rs +++ b/crates/bevy_reflect/src/type_info.rs @@ -52,6 +52,7 @@ use std::any::{Any, TypeId}; /// # } /// # /// # impl Reflect for MyStruct { +/// # fn type_name(&self) -> &str { todo!() } /// # fn get_type_info(&self) -> &'static TypeInfo { todo!() } /// # fn into_any(self: Box) -> Box { todo!() } /// # fn as_any(&self) -> &dyn Any { todo!() } diff --git a/crates/bevy_reflect/src/type_name.rs b/crates/bevy_reflect/src/type_name.rs index 7b80f2fe9f554..74d9391a86ecd 100644 --- a/crates/bevy_reflect/src/type_name.rs +++ b/crates/bevy_reflect/src/type_name.rs @@ -5,9 +5,41 @@ use crate::utility::GenericTypeNameCell; /// This is a stable alternative to [`std::any::type_name`] whose output isn't guarentee /// and may change between versions of the compiler. /// -/// This trait may be derived via `#[derive(TypeName)]`. -/// Checkout the [derive macro documentation][bevy_reflect_derive::TypeName] for more details -/// about how this trait must be implemented. +/// This trait may be derived via [`#[derive(TypeName)]`][bevy_reflect_derive::TypeName]. +/// +/// ## Manual implementation +/// +/// For some reason you may need to manually implement [`TypeName`]. +/// +/// ```ignore +/// bevy_reflect::TypeName; +/// +/// struct MyType; +/// +/// impl TypeName for MyType{ +/// fn name() -> &'static str { +/// concat!(module_path!(), "::", "MyType") +/// } +/// } +/// ``` +/// +/// If your type is generic you must use +/// [`GenericTypeNameCell`][crate::utility::GenericTypeNameCell]. +/// +/// ```ignore +/// bevy_reflect::{TypeName, utility::GenericTypeNameCell}; +/// +/// struct MyType(T); +/// +/// impl TypeName for MyType { +/// fn name() -> &'static str { +/// static CELL: GenericTypeNameCell = GenericTypeNameCell::new(); +/// CELL.get_or_insert::(|| { +/// format!(concat!(module_path!(), "::MyType<{}>"), T::name()) +/// }) +/// } +/// } +/// ``` pub trait TypeName: 'static { /// Returns the name of the type. /// diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index 7ce33fe907e2d..bf8719fd90f48 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -129,7 +129,7 @@ pub type NonGenericTypeInfoCell = NonGenericDataCell; /// /// struct Foo(T); /// -/// impl Typed for Foo { +/// impl Typed for Foo { /// fn type_info() -> &'static TypeInfo { /// static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new(); /// CELL.get_or_insert::(|| { diff --git a/crates/bevy_sprite/src/mesh2d/material.rs b/crates/bevy_sprite/src/mesh2d/material.rs index d7679f6a162c1..a8e76cd15e8b7 100644 --- a/crates/bevy_sprite/src/mesh2d/material.rs +++ b/crates/bevy_sprite/src/mesh2d/material.rs @@ -60,11 +60,11 @@ use crate::{ /// ``` /// # use bevy_sprite::{Material2d, MaterialMesh2dBundle}; /// # use bevy_ecs::prelude::*; -/// # use bevy_reflect::TypeUuid; +/// # use bevy_reflect::{TypeUuid, TypeName}; /// # use bevy_render::{render_resource::{AsBindGroup, ShaderRef}, texture::Image, color::Color}; /// # use bevy_asset::{Handle, AssetServer, Assets}; /// -/// #[derive(AsBindGroup, TypeUuid, Debug, Clone)] +/// #[derive(AsBindGroup, TypeUuid, TypeName, Debug, Clone)] /// #[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"] /// pub struct CustomMaterial { /// // Uniform bindings must implement `ShaderType`, which will be used to convert the value to From b1411ab3823f561fa5a0f8797e346d7e57f76b89 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 28 Aug 2022 18:38:01 +0200 Subject: [PATCH 49/87] fix test --- crates/bevy_reflect/src/serde/de.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/src/serde/de.rs b/crates/bevy_reflect/src/serde/de.rs index ad24185de15f3..3d2fb6111cd6b 100644 --- a/crates/bevy_reflect/src/serde/de.rs +++ b/crates/bevy_reflect/src/serde/de.rs @@ -685,7 +685,7 @@ mod tests { "variant": "Struct", "struct": { "value": { - "type": "alloc::string::String", + "type": "String", "value": "I <3 Enums", }, }, From 86ab916e1d72d80383bd697afe869431dc72c51f Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Mon, 29 Aug 2022 10:05:53 +0200 Subject: [PATCH 50/87] Update crates/bevy_reflect/bevy_reflect_derive/src/lib.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/bevy_reflect_derive/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index 80c2b83f4df92..8a5e1e07fbce5 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -61,7 +61,7 @@ pub fn derive_reflect(input: TokenStream) -> TokenStream { /// Implement [`TypeName`] on a type. The type name is automatically deducted following a /// specific convention. /// -/// ## Type name convetion +/// ## Type name convention /// /// The type name is the module path followed by the ident of the type. /// If the type is generic the type name of it's generic parameter is included between `<` and `>`. From 5e87d132e85b304ab82ffb261a986b289cb02574 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Mon, 29 Aug 2022 10:06:07 +0200 Subject: [PATCH 51/87] Update crates/bevy_reflect/bevy_reflect_derive/src/lib.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/bevy_reflect_derive/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index 8a5e1e07fbce5..e6c1cb38f2947 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -64,7 +64,7 @@ pub fn derive_reflect(input: TokenStream) -> TokenStream { /// ## Type name convention /// /// The type name is the module path followed by the ident of the type. -/// If the type is generic the type name of it's generic parameter is included between `<` and `>`. +/// If the type is generic the type name of its generic parameters are included between `<` and `>`. /// /// See examples. /// From 72955835dff257646b283c37b97f954a5648fe8c Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Mon, 29 Aug 2022 10:06:18 +0200 Subject: [PATCH 52/87] Update crates/bevy_reflect/bevy_reflect_derive/src/lib.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/bevy_reflect_derive/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index e6c1cb38f2947..6c9a849468d3b 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -70,7 +70,7 @@ pub fn derive_reflect(input: TokenStream) -> TokenStream { /// /// ## Custom type name /// -/// It's possible to override the default behaviour and choosing a custom type name by using +/// It's possible to override the default behaviour and choose a custom type name by using /// the `type_name` attribute after the `derive` attribute. /// /// A common usage is to using your crate name instead of the complete module path. From 85739b82de0e0a6c8aeeb231d6e31178c2219455 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Mon, 29 Aug 2022 10:06:42 +0200 Subject: [PATCH 53/87] Update crates/bevy_reflect/src/type_name.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/src/type_name.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/src/type_name.rs b/crates/bevy_reflect/src/type_name.rs index 74d9391a86ecd..6822935a74836 100644 --- a/crates/bevy_reflect/src/type_name.rs +++ b/crates/bevy_reflect/src/type_name.rs @@ -2,7 +2,7 @@ use crate::utility::GenericTypeNameCell; /// Provide the name of the type as a string slice. /// -/// This is a stable alternative to [`std::any::type_name`] whose output isn't guarentee +/// This is a stable alternative to [`std::any::type_name`] whose output isn't guarenteed /// and may change between versions of the compiler. /// /// This trait may be derived via [`#[derive(TypeName)]`][bevy_reflect_derive::TypeName]. From c9ec3e89c82fa93df9215336ec7b92b6a9280122 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Mon, 29 Aug 2022 10:06:55 +0200 Subject: [PATCH 54/87] Update crates/bevy_reflect/src/type_name.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/src/type_name.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/bevy_reflect/src/type_name.rs b/crates/bevy_reflect/src/type_name.rs index 6822935a74836..f97fca0194ddb 100644 --- a/crates/bevy_reflect/src/type_name.rs +++ b/crates/bevy_reflect/src/type_name.rs @@ -9,7 +9,8 @@ use crate::utility::GenericTypeNameCell; /// /// ## Manual implementation /// -/// For some reason you may need to manually implement [`TypeName`]. +/// If you need to manually implement [`TypeName`], it's recommended to follow +/// the example below (unless specifying a custom name). /// /// ```ignore /// bevy_reflect::TypeName; From ef4986e3b52e3eb9af23fc78028a5f9d108a51c4 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Mon, 29 Aug 2022 10:07:04 +0200 Subject: [PATCH 55/87] Update crates/bevy_reflect/src/type_name.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/src/type_name.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/src/type_name.rs b/crates/bevy_reflect/src/type_name.rs index f97fca0194ddb..4e977594100ac 100644 --- a/crates/bevy_reflect/src/type_name.rs +++ b/crates/bevy_reflect/src/type_name.rs @@ -44,7 +44,7 @@ use crate::utility::GenericTypeNameCell; pub trait TypeName: 'static { /// Returns the name of the type. /// - /// This is a stable alternative to [`std::any::type_name`] whose output isn't guarentee + /// This is a stable alternative to [`std::any::type_name`] whose output isn't guarenteed /// and may change between versions of the compiler. fn name() -> &'static str; } From 4feef51073dcaf1a423aa5c0e39d3b2a3f0e0053 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Mon, 29 Aug 2022 10:07:13 +0200 Subject: [PATCH 56/87] Update crates/bevy_reflect/src/utility.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/src/utility.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index bf8719fd90f48..cfb40de8c9362 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -163,7 +163,7 @@ pub type GenericTypeInfoCell = GenericDataCell; /// A container for [`String`] over generic types, allowing instances to be stored statically. /// -/// Used when implementing [`TypeName`][crate::TypeName] for generic type to store the type name. +/// Used when implementing [`TypeName`][crate::TypeName] for generic types to store the type name. /// /// ## Example /// From 6f750c607fb614fc9ceddfd60bd259693d0ff360 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Mon, 29 Aug 2022 10:08:09 +0200 Subject: [PATCH 57/87] Update crates/bevy_reflect/bevy_reflect_derive/src/lib.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/bevy_reflect_derive/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index 6c9a849468d3b..edf118a192b62 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -71,7 +71,7 @@ pub fn derive_reflect(input: TokenStream) -> TokenStream { /// ## Custom type name /// /// It's possible to override the default behaviour and choose a custom type name by using -/// the `type_name` attribute after the `derive` attribute. +/// the `type_name` attribute. /// /// A common usage is to using your crate name instead of the complete module path. /// From 563cb7590b72c3d5bfcb4171b6b33a847ae4ba45 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Mon, 29 Aug 2022 10:08:30 +0200 Subject: [PATCH 58/87] Update crates/bevy_reflect/bevy_reflect_derive/src/lib.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/bevy_reflect_derive/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index edf118a192b62..3de5dcd4d7833 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -73,7 +73,7 @@ pub fn derive_reflect(input: TokenStream) -> TokenStream { /// It's possible to override the default behaviour and choose a custom type name by using /// the `type_name` attribute. /// -/// A common usage is to using your crate name instead of the complete module path. +/// If specifying a custom type name, it's recommended to prefix it with the name of your crate. /// /// It's highly discouraged to using unprefixed type name that could collide with another type /// or an malformed type name (e.g. `BlAH@blah blah`). From 9c3a034590633221efb39fd9fcb627780cc2dbf6 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Mon, 29 Aug 2022 10:09:00 +0200 Subject: [PATCH 59/87] Update crates/bevy_reflect/bevy_reflect_derive/src/lib.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/bevy_reflect_derive/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index 3de5dcd4d7833..44ddad3c19a24 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -75,8 +75,8 @@ pub fn derive_reflect(input: TokenStream) -> TokenStream { /// /// If specifying a custom type name, it's recommended to prefix it with the name of your crate. /// -/// It's highly discouraged to using unprefixed type name that could collide with another type -/// or an malformed type name (e.g. `BlAH@blah blah`). +/// It's highly discouraged to use an unprefixed type name that could collide with another type +/// or a malformed type name (e.g. `BlAH@blah blah`). /// /// ## Example /// From dbd4bde4d8d4685ad6e24b5f0b70e543fc27f0f9 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Mon, 29 Aug 2022 10:09:35 +0200 Subject: [PATCH 60/87] Update crates/bevy_reflect/bevy_reflect_derive/src/lib.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/bevy_reflect_derive/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index 44ddad3c19a24..537b41ff97108 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -258,8 +258,8 @@ pub fn impl_from_reflect_value(input: TokenStream) -> TokenStream { /// the definitions of cannot be altered. /// /// But unlike `#[derive(TypeName)]` that prefix the type name with the module path -/// using the macro [`module_path`], `impl_type_name` use only the ident of the type -/// as type name. +/// using the macro [`module_path`], by default `impl_type_name` only uses the ident of the type +/// as the type name. /// /// # Example /// Implementing `TypeName` for `Vec`: From f67f1af135772558a6bd3f30edd30bc6ca21ec79 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com> Date: Mon, 29 Aug 2022 10:09:53 +0200 Subject: [PATCH 61/87] Update crates/bevy_reflect/src/type_name.rs Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com> --- crates/bevy_reflect/src/type_name.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/src/type_name.rs b/crates/bevy_reflect/src/type_name.rs index 4e977594100ac..e7dc4364b6428 100644 --- a/crates/bevy_reflect/src/type_name.rs +++ b/crates/bevy_reflect/src/type_name.rs @@ -1,6 +1,6 @@ use crate::utility::GenericTypeNameCell; -/// Provide the name of the type as a string slice. +/// Provides the name of the type as a string slice. /// /// This is a stable alternative to [`std::any::type_name`] whose output isn't guarenteed /// and may change between versions of the compiler. From 3aa805a23fb23490ff253bbd106212e5b5f5f7e7 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Mon, 29 Aug 2022 10:12:32 +0200 Subject: [PATCH 62/87] reflect_derive: update derive_type_name doc --- crates/bevy_reflect/bevy_reflect_derive/src/lib.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index 537b41ff97108..9fd39e38fcab1 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -58,8 +58,7 @@ pub fn derive_reflect(input: TokenStream) -> TokenStream { } } -/// Implement [`TypeName`] on a type. The type name is automatically deducted following a -/// specific convention. +/// Implement `TypeName` on a type. /// /// ## Type name convention /// From 188b2f3e54bda238e51ce0d6faee41d4d4179a66 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Mon, 29 Aug 2022 10:13:10 +0200 Subject: [PATCH 63/87] update TypeName doc --- crates/bevy_reflect/src/type_name.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/src/type_name.rs b/crates/bevy_reflect/src/type_name.rs index e7dc4364b6428..88b493d66c4b9 100644 --- a/crates/bevy_reflect/src/type_name.rs +++ b/crates/bevy_reflect/src/type_name.rs @@ -1,6 +1,6 @@ use crate::utility::GenericTypeNameCell; -/// Provides the name of the type as a string slice. +/// Provides the name of the type as a string. /// /// This is a stable alternative to [`std::any::type_name`] whose output isn't guarenteed /// and may change between versions of the compiler. From 08e2c8f6f108307538bcded32a4f43c8520c9143 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Mon, 29 Aug 2022 10:14:59 +0200 Subject: [PATCH 64/87] fix example comment --- examples/reflection/generic_reflection.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/reflection/generic_reflection.rs b/examples/reflection/generic_reflection.rs index 3c2c057deca15..a6425e93e14be 100644 --- a/examples/reflection/generic_reflection.rs +++ b/examples/reflection/generic_reflection.rs @@ -12,9 +12,9 @@ fn main() { .run(); } +/// Because `#[derive(Reflect)]` also derives `TypeName` for `MyType`, +/// the generic parameter must also implement `TypeName`. #[derive(Reflect)] -// Because `#[derive(Reflect)]` also derive `TypeName` for `MyType`, -// the generic parameter must also implement `TypeName`. struct MyType { value: T, } From a7aa4de5f17a0681187089141bf6e58a572e3957 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Mon, 29 Aug 2022 10:54:50 +0200 Subject: [PATCH 65/87] impl TypeName on Dynamic* structs --- crates/bevy_reflect/src/array.rs | 5 +++-- crates/bevy_reflect/src/enums/dynamic_enum.rs | 9 ++++++--- crates/bevy_reflect/src/list.rs | 6 +++--- crates/bevy_reflect/src/map.rs | 6 ++++-- crates/bevy_reflect/src/struct_trait.rs | 7 +++++-- crates/bevy_reflect/src/tuple.rs | 6 +++--- crates/bevy_reflect/src/tuple_struct.rs | 5 +++-- crates/bevy_reflect/src/type_info.rs | 4 ++-- 8 files changed, 29 insertions(+), 19 deletions(-) diff --git a/crates/bevy_reflect/src/array.rs b/crates/bevy_reflect/src/array.rs index 3ae28d2fe87c0..16394926e4b39 100644 --- a/crates/bevy_reflect/src/array.rs +++ b/crates/bevy_reflect/src/array.rs @@ -1,6 +1,6 @@ use crate::{ - utility::NonGenericTypeInfoCell, DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, - TypeName, Typed, + self as bevy_reflect, utility::NonGenericTypeInfoCell, DynamicInfo, Reflect, ReflectMut, + ReflectRef, TypeInfo, TypeName, Typed, }; use std::{ any::{Any, TypeId}, @@ -116,6 +116,7 @@ impl ArrayInfo { /// can be mutated— just that the _number_ of items cannot change. /// /// [`DynamicList`]: crate::DynamicList +#[derive(TypeName)] pub struct DynamicArray { pub(crate) name: String, pub(crate) values: Box<[Box]>, diff --git a/crates/bevy_reflect/src/enums/dynamic_enum.rs b/crates/bevy_reflect/src/enums/dynamic_enum.rs index d0f097e977b1e..da8173c708f03 100644 --- a/crates/bevy_reflect/src/enums/dynamic_enum.rs +++ b/crates/bevy_reflect/src/enums/dynamic_enum.rs @@ -1,7 +1,10 @@ +use bevy_reflect_derive::TypeName; + use crate::utility::NonGenericTypeInfoCell; use crate::{ - enum_debug, enum_hash, enum_partial_eq, DynamicInfo, DynamicStruct, DynamicTuple, Enum, - Reflect, ReflectMut, ReflectRef, Struct, Tuple, TypeInfo, Typed, VariantFieldIter, VariantType, + self as bevy_reflect, enum_debug, enum_hash, enum_partial_eq, DynamicInfo, DynamicStruct, + DynamicTuple, Enum, Reflect, ReflectMut, ReflectRef, Struct, Tuple, TypeInfo, Typed, + VariantFieldIter, VariantType, }; use std::any::Any; use std::fmt::Formatter; @@ -72,7 +75,7 @@ impl From<()> for DynamicVariant { /// // Tada! /// assert_eq!(None, value); /// ``` -#[derive(Default)] +#[derive(Default, TypeName)] pub struct DynamicEnum { name: String, variant_name: String, diff --git a/crates/bevy_reflect/src/list.rs b/crates/bevy_reflect/src/list.rs index 950f49c9ec115..6864d99aec197 100644 --- a/crates/bevy_reflect/src/list.rs +++ b/crates/bevy_reflect/src/list.rs @@ -3,8 +3,8 @@ use std::fmt::{Debug, Formatter}; use crate::utility::NonGenericTypeInfoCell; use crate::{ - Array, ArrayIter, DynamicArray, DynamicInfo, FromReflect, Reflect, ReflectMut, ReflectRef, - TypeInfo, TypeName, Typed, + self as bevy_reflect, Array, ArrayIter, DynamicArray, DynamicInfo, FromReflect, Reflect, + ReflectMut, ReflectRef, TypeInfo, TypeName, Typed, }; /// An ordered, mutable list of [Reflect] items. This corresponds to types like [`std::vec::Vec`]. @@ -80,7 +80,7 @@ impl ListInfo { } /// A list of reflected values. -#[derive(Default)] +#[derive(Default, TypeName)] pub struct DynamicList { name: String, values: Vec>, diff --git a/crates/bevy_reflect/src/map.rs b/crates/bevy_reflect/src/map.rs index b62002c12b474..2860ed2e049b5 100644 --- a/crates/bevy_reflect/src/map.rs +++ b/crates/bevy_reflect/src/map.rs @@ -5,7 +5,9 @@ use std::hash::Hash; use bevy_utils::{Entry, HashMap}; use crate::utility::NonGenericTypeInfoCell; -use crate::{DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, TypeName, Typed}; +use crate::{ + self as bevy_reflect, DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, TypeName, Typed, +}; /// An ordered mapping between [`Reflect`] values. /// @@ -139,7 +141,7 @@ impl MapInfo { const HASH_ERROR: &str = "the given key does not support hashing"; /// An ordered mapping between reflected values. -#[derive(Default)] +#[derive(Default, TypeName)] pub struct DynamicMap { name: String, values: Vec<(Box, Box)>, diff --git a/crates/bevy_reflect/src/struct_trait.rs b/crates/bevy_reflect/src/struct_trait.rs index 41b2caaac2571..40ee985cdf39e 100644 --- a/crates/bevy_reflect/src/struct_trait.rs +++ b/crates/bevy_reflect/src/struct_trait.rs @@ -1,5 +1,8 @@ use crate::utility::NonGenericTypeInfoCell; -use crate::{DynamicInfo, NamedField, Reflect, ReflectMut, ReflectRef, TypeInfo, TypeName, Typed}; +use crate::{ + self as bevy_reflect, DynamicInfo, NamedField, Reflect, ReflectMut, ReflectRef, TypeInfo, + TypeName, Typed, +}; use bevy_utils::{Entry, HashMap}; use std::fmt::{Debug, Formatter}; use std::{ @@ -230,7 +233,7 @@ impl GetField for dyn Struct { } /// A struct type which allows fields to be added at runtime. -#[derive(Default)] +#[derive(Default, TypeName)] pub struct DynamicStruct { name: String, fields: Vec>, diff --git a/crates/bevy_reflect/src/tuple.rs b/crates/bevy_reflect/src/tuple.rs index 6e95b036a9efe..92ec3290a2fa2 100644 --- a/crates/bevy_reflect/src/tuple.rs +++ b/crates/bevy_reflect/src/tuple.rs @@ -1,7 +1,7 @@ use crate::utility::NonGenericTypeInfoCell; use crate::{ - DynamicInfo, FromReflect, GetTypeRegistration, Reflect, ReflectMut, ReflectRef, TypeInfo, - TypeName, TypeRegistration, Typed, UnnamedField, + self as bevy_reflect, DynamicInfo, FromReflect, GetTypeRegistration, Reflect, ReflectMut, + ReflectRef, TypeInfo, TypeName, TypeRegistration, Typed, UnnamedField, }; use std::any::{Any, TypeId}; use std::fmt::{Debug, Formatter}; @@ -182,7 +182,7 @@ impl TupleInfo { } /// A tuple which allows fields to be added at runtime. -#[derive(Default)] +#[derive(Default, TypeName)] pub struct DynamicTuple { name: String, fields: Vec>, diff --git a/crates/bevy_reflect/src/tuple_struct.rs b/crates/bevy_reflect/src/tuple_struct.rs index 51726e3867338..817777f9ee96a 100644 --- a/crates/bevy_reflect/src/tuple_struct.rs +++ b/crates/bevy_reflect/src/tuple_struct.rs @@ -1,6 +1,7 @@ use crate::utility::NonGenericTypeInfoCell; use crate::{ - DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, TypeName, Typed, UnnamedField, + self as bevy_reflect, DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, TypeName, Typed, + UnnamedField, }; use std::any::{Any, TypeId}; use std::fmt::{Debug, Formatter}; @@ -189,7 +190,7 @@ impl GetTupleStructField for dyn TupleStruct { } /// A tuple struct which allows fields to be added at runtime. -#[derive(Default)] +#[derive(Default, TypeName)] pub struct DynamicTupleStruct { name: String, fields: Vec>, diff --git a/crates/bevy_reflect/src/type_info.rs b/crates/bevy_reflect/src/type_info.rs index 656bb379fd4aa..dae32a79adc67 100644 --- a/crates/bevy_reflect/src/type_info.rs +++ b/crates/bevy_reflect/src/type_info.rs @@ -207,9 +207,9 @@ pub struct DynamicInfo { } impl DynamicInfo { - pub fn new() -> Self { + pub fn new() -> Self { Self { - type_name: std::any::type_name::(), + type_name: T::name(), type_id: TypeId::of::(), } } From 184d3353cefa5369d714ac2d6734c24d63715b5d Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Tue, 30 Aug 2022 18:45:50 +0200 Subject: [PATCH 66/87] register_type_data : use TypeName --- crates/bevy_app/src/app.rs | 4 ++-- crates/bevy_reflect/src/type_registry.rs | 17 +++++++++++------ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/crates/bevy_app/src/app.rs b/crates/bevy_app/src/app.rs index 7d6c027da0cdf..28999312bf61d 100644 --- a/crates/bevy_app/src/app.rs +++ b/crates/bevy_app/src/app.rs @@ -911,8 +911,8 @@ impl App { /// See [`bevy_reflect::TypeRegistry::register_type_data`]. #[cfg(feature = "bevy_reflect")] pub fn register_type_data< - T: bevy_reflect::Reflect + 'static, - D: bevy_reflect::TypeData + bevy_reflect::FromType, + T: bevy_reflect::Reflect + bevy_reflect::TypeName + 'static, + D: bevy_reflect::TypeData + bevy_reflect::TypeName + bevy_reflect::FromType, >( &mut self, ) -> &mut Self { diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index 408cf245efeab..5558e1e44c26e 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -1,4 +1,4 @@ -use crate::{serde::Serializable, Reflect, TypeInfo, TypeName, Typed}; +use crate::{self as bevy_reflect, serde::Serializable, Reflect, TypeInfo, TypeName, Typed}; use bevy_ptr::{Ptr, PtrMut}; use bevy_utils::{HashMap, HashSet}; use downcast_rs::{impl_downcast, Downcast}; @@ -120,12 +120,17 @@ impl TypeRegistry { /// type_registry.register_type_data::, ReflectSerialize>(); /// type_registry.register_type_data::, ReflectDeserialize>(); /// ``` - pub fn register_type_data>(&mut self) { + pub fn register_type_data< + T: Reflect + TypeName + 'static, + D: TypeData + TypeName + FromType, + >( + &mut self, + ) { let data = self.get_mut(TypeId::of::()).unwrap_or_else(|| { panic!( "attempted to call `TypeRegistry::register_type_data` for type `{T}` with data `{D}` without registering `{T}` first", - T = std::any::type_name::(), - D = std::any::type_name::(), + T = T::name(), + D = D::name(), ) }); data.insert(D::from_type()); @@ -382,7 +387,7 @@ pub trait FromType { /// /// A `ReflectSerialize` for type `T` can be obtained via /// [`FromType::from_type`]. -#[derive(Clone)] +#[derive(Clone, TypeName)] pub struct ReflectSerialize { get_serializable: for<'a> fn(value: &'a dyn Reflect) -> Serializable, } @@ -411,7 +416,7 @@ impl ReflectSerialize { /// /// A `ReflectDeserialize` for type `T` can be obtained via /// [`FromType::from_type`]. -#[derive(Clone)] +#[derive(Clone, TypeName)] pub struct ReflectDeserialize { pub func: fn( deserializer: &mut dyn erased_serde::Deserializer, From fa9bdb41df9717d937feb05fe1fdba61bed2ba58 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Tue, 30 Aug 2022 18:47:49 +0200 Subject: [PATCH 67/87] update some doc links --- crates/bevy_reflect/src/type_info.rs | 2 +- crates/bevy_reflect/src/type_registry.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/bevy_reflect/src/type_info.rs b/crates/bevy_reflect/src/type_info.rs index dae32a79adc67..6957cb9425ed5 100644 --- a/crates/bevy_reflect/src/type_info.rs +++ b/crates/bevy_reflect/src/type_info.rs @@ -216,7 +216,7 @@ impl DynamicInfo { /// The [type name] of the dynamic value. /// - /// [type name]: std::any::type_name + /// [type name]: crate::TypeName pub fn type_name(&self) -> &'static str { self.type_name } diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index 5558e1e44c26e..7d52a3e64d0d0 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -337,7 +337,7 @@ impl TypeRegistration { /// Returns the [name] of the type. /// - /// [name]: std::any::type_name + /// [name]: crate::TypeName pub fn type_name(&self) -> &'static str { self.type_info.type_name() } From 9dda49410b736a5ca7aadece501a6929a2ac85d9 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Tue, 30 Aug 2022 18:49:22 +0200 Subject: [PATCH 68/87] TypeUuidDynamic : use TypeName --- crates/bevy_reflect/src/type_uuid.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/bevy_reflect/src/type_uuid.rs b/crates/bevy_reflect/src/type_uuid.rs index 5cfd46ab6a771..f91c49be81512 100644 --- a/crates/bevy_reflect/src/type_uuid.rs +++ b/crates/bevy_reflect/src/type_uuid.rs @@ -1,6 +1,8 @@ pub use bevy_reflect_derive::TypeUuid; pub use bevy_utils::Uuid; +use crate::TypeName; + /// A trait for types with a statically associated UUID. pub trait TypeUuid { const TYPE_UUID: Uuid; @@ -14,7 +16,7 @@ pub trait TypeUuidDynamic { impl TypeUuidDynamic for T where - T: TypeUuid, + T: TypeUuid + TypeName, { /// Returns the UUID associated with this value's type. fn type_uuid(&self) -> Uuid { @@ -23,9 +25,9 @@ where /// Returns the [type name] of this value's type. /// - /// [type name]: std::any::type_name + /// [type name]: crate::TypeName fn type_name(&self) -> &'static str { - std::any::type_name::() + Self::name() } } From 366840700070b7c27e20d4898e148bff1bb704d5 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Tue, 30 Aug 2022 18:52:16 +0200 Subject: [PATCH 69/87] relive last std::any::type_name --- crates/bevy_reflect/src/lib.rs | 2 +- crates/bevy_reflect/src/type_registry.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index e2a05840b308b..d12b9329a16e2 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -773,7 +773,7 @@ mod tests { let info = MyDynamic::type_info(); if let TypeInfo::Dynamic(info) = info { assert!(info.is::()); - assert_eq!(std::any::type_name::(), info.type_name()); + assert_eq!(::name(), info.type_name()); } else { panic!("Expected `TypeInfo::Dynamic`"); } diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index 7d52a3e64d0d0..393241b7da1a8 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -392,12 +392,12 @@ pub struct ReflectSerialize { get_serializable: for<'a> fn(value: &'a dyn Reflect) -> Serializable, } -impl FromType for ReflectSerialize { +impl FromType for ReflectSerialize { fn from_type() -> Self { ReflectSerialize { get_serializable: |value| { let value = value.downcast_ref::().unwrap_or_else(|| { - panic!("ReflectSerialize::get_serialize called with type `{}`, even though it was created for `{}`", value.type_name(), std::any::type_name::()) + panic!("ReflectSerialize::get_serialize called with type `{}`, even though it was created for `{}`", value.type_name(), T::name()) }); Serializable::Borrowed(value) }, From b449fbe685b69fcd6d7007a851e58dd486963a42 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Tue, 30 Aug 2022 19:00:38 +0200 Subject: [PATCH 70/87] update std types TypeName --- crates/bevy_reflect/src/impls/std.rs | 32 ++++++++++++++-------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index 84978aee3c58f..7826a3dab4dcb 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -43,21 +43,21 @@ impl_reflect_value!( E: Clone + Reflect + TypeName > () ); impl_reflect_value!(HashSet()); -impl_reflect_value!(Range()); -impl_reflect_value!(Duration(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(Instant(Debug, Hash, PartialEq)); -impl_reflect_value!(NonZeroI128(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(NonZeroU128(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(NonZeroIsize(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(NonZeroUsize(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(NonZeroI64(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(NonZeroU64(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(NonZeroU32(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(NonZeroI32(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(NonZeroI16(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(NonZeroU16(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(NonZeroU8(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(NonZeroI8(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std::Range" Range()); +impl_reflect_value!(@"std::Duration" Duration(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std::Instant" Instant(Debug, Hash, PartialEq)); +impl_reflect_value!(@"std::NonZeroI128" NonZeroI128(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std::NonZeroU128" NonZeroU128(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std::NonZeroIsize" NonZeroIsize(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std::NonZeroUsize" NonZeroUsize(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std::NonZeroI64" NonZeroI64(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std::NonZeroU64" NonZeroU64(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std::NonZeroU32" NonZeroU32(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std::NonZeroI32" NonZeroI32(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std::NonZeroI16" NonZeroI16(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std::NonZeroU16" NonZeroU16(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std::NonZeroU8" NonZeroU8(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std::NonZeroI8" NonZeroI8(Debug, Hash, PartialEq, Serialize, Deserialize)); impl_from_reflect_value!(bool); impl_from_reflect_value!(char); @@ -94,7 +94,7 @@ impl_from_reflect_value!(NonZeroU8); impl_from_reflect_value!(NonZeroI8); impl_type_name!(Vec); -impl_type_name!(HashMap); +impl_type_name!(HashMap); impl_type_name!(Option); // impl_type_name expects a type name followed by generic between `<` and `>`. From a4c93cf13db3f4ccfe166a1ead6f8712ea8e466e Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Tue, 30 Aug 2022 23:49:19 +0200 Subject: [PATCH 71/87] remove extra spaces --- crates/bevy_reflect/src/impls/std.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index 1467d2ad45f5a..617b1e2e85d59 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -43,11 +43,11 @@ impl_reflect_value!( E: Clone + Reflect + TypeName > () ); impl_reflect_value!(HashSet()); -impl_reflect_value!(@"std::Range" Range()); -impl_reflect_value!(@"std::RangeInclusive" RangeInclusive()); -impl_reflect_value!(@"std::RangeFrom" RangeFrom()); -impl_reflect_value!(@"std::RangeTo" RangeTo()); -impl_reflect_value!(@"std::RangeToInclusive" RangeToInclusive()); +impl_reflect_value!(@"std::Range" Range()); +impl_reflect_value!(@"std::RangeInclusive" RangeInclusive()); +impl_reflect_value!(@"std::RangeFrom" RangeFrom()); +impl_reflect_value!(@"std::RangeTo" RangeTo()); +impl_reflect_value!(@"std::RangeToInclusive" RangeToInclusive()); impl_reflect_value!(@"std::RangeFull" RangeFull()); impl_reflect_value!(@"std::Duration" Duration(Debug, Hash, PartialEq, Serialize, Deserialize)); impl_reflect_value!(@"std::Instant" Instant(Debug, Hash, PartialEq)); From c914af06742b39fd19a1f114bce4511920912894 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Mon, 5 Sep 2022 13:43:28 +0200 Subject: [PATCH 72/87] rename `TypeName` into `TypePath` --- crates/bevy_animation/src/lib.rs | 4 +- crates/bevy_app/src/app.rs | 4 +- crates/bevy_asset/src/asset_server.rs | 8 +- crates/bevy_asset/src/assets.rs | 4 +- crates/bevy_asset/src/loader.rs | 6 +- crates/bevy_audio/src/audio_output.rs | 4 +- crates/bevy_audio/src/audio_source.rs | 4 +- crates/bevy_gltf/src/lib.rs | 10 +- crates/bevy_pbr/src/material.rs | 8 +- crates/bevy_pbr/src/pbr_material.rs | 4 +- .../bevy_reflect_derive/src/derive_data.rs | 30 ++-- .../bevy_reflect_derive/src/from_reflect.rs | 2 +- .../bevy_reflect_derive/src/impls/enums.rs | 14 +- .../bevy_reflect_derive/src/impls/mod.rs | 4 +- .../bevy_reflect_derive/src/impls/structs.rs | 12 +- .../src/impls/tuple_structs.rs | 12 +- .../src/impls/{type_name.rs => type_path.rs} | 10 +- .../bevy_reflect_derive/src/impls/values.rs | 12 +- .../bevy_reflect_derive/src/lib.rs | 74 ++++----- .../bevy_reflect_derive/src/reflect_value.rs | 18 +-- .../src/{type_name.rs => type_path.rs} | 4 +- crates/bevy_reflect/src/array.rs | 34 ++--- crates/bevy_reflect/src/enums/dynamic_enum.rs | 22 +-- crates/bevy_reflect/src/enums/enum_trait.rs | 20 +-- crates/bevy_reflect/src/enums/mod.rs | 16 +- crates/bevy_reflect/src/fields.rs | 30 ++-- crates/bevy_reflect/src/impls/glam.rs | 61 ++++---- crates/bevy_reflect/src/impls/smallvec.rs | 36 ++--- crates/bevy_reflect/src/impls/std.rs | 140 +++++++++--------- crates/bevy_reflect/src/lib.rs | 97 ++++++------ crates/bevy_reflect/src/list.rs | 44 +++--- crates/bevy_reflect/src/map.rs | 57 +++---- crates/bevy_reflect/src/reflect.rs | 22 +-- crates/bevy_reflect/src/serde/ser.rs | 18 +-- crates/bevy_reflect/src/struct_trait.rs | 28 ++-- crates/bevy_reflect/src/tuple.rs | 42 +++--- crates/bevy_reflect/src/tuple_struct.rs | 28 ++-- crates/bevy_reflect/src/type_info.rs | 64 ++++---- .../src/{type_name.rs => type_path.rs} | 51 ++++--- crates/bevy_reflect/src/type_registry.rs | 36 ++--- crates/bevy_reflect/src/type_uuid.rs | 14 +- crates/bevy_reflect/src/utility.rs | 20 +-- crates/bevy_render/src/mesh/mesh/mod.rs | 4 +- crates/bevy_render/src/mesh/mesh/skinning.rs | 4 +- .../bevy_render/src/render_resource/shader.rs | 4 +- crates/bevy_render/src/texture/image.rs | 4 +- crates/bevy_scene/src/dynamic_scene.rs | 10 +- crates/bevy_scene/src/scene.rs | 4 +- .../bevy_sprite/src/mesh2d/color_material.rs | 4 +- crates/bevy_sprite/src/mesh2d/material.rs | 8 +- crates/bevy_sprite/src/texture_atlas.rs | 4 +- crates/bevy_text/src/font.rs | 4 +- crates/bevy_text/src/font_atlas_set.rs | 4 +- crates/bevy_utils/src/short_names.rs | 2 +- examples/3d/lines.rs | 2 +- examples/3d/skybox.rs | 2 +- examples/asset/custom_asset.rs | 2 +- examples/reflection/generic_reflection.rs | 6 +- examples/shader/array_texture.rs | 2 +- examples/shader/custom_vertex_attribute.rs | 2 +- examples/shader/post_processing.rs | 2 +- examples/shader/shader_defs.rs | 2 +- examples/shader/shader_material.rs | 2 +- examples/shader/shader_material_glsl.rs | 2 +- .../shader_material_screenspace_texture.rs | 2 +- 65 files changed, 613 insertions(+), 597 deletions(-) rename crates/bevy_reflect/bevy_reflect_derive/src/impls/{type_name.rs => type_path.rs} (87%) rename crates/bevy_reflect/bevy_reflect_derive/src/{type_name.rs => type_path.rs} (86%) rename crates/bevy_reflect/src/{type_name.rs => type_path.rs} (68%) diff --git a/crates/bevy_animation/src/lib.rs b/crates/bevy_animation/src/lib.rs index c96cc55e53ace..12570dba0b744 100644 --- a/crates/bevy_animation/src/lib.rs +++ b/crates/bevy_animation/src/lib.rs @@ -17,7 +17,7 @@ use bevy_ecs::{ }; use bevy_hierarchy::Children; use bevy_math::{Quat, Vec3}; -use bevy_reflect::{Reflect, TypeName, TypeUuid}; +use bevy_reflect::{Reflect, TypePath, TypeUuid}; use bevy_time::Time; use bevy_transform::{prelude::Transform, TransformSystem}; use bevy_utils::{tracing::warn, HashMap}; @@ -60,7 +60,7 @@ pub struct EntityPath { } /// A list of [`VariableCurve`], and the [`EntityPath`] to which they apply. -#[derive(Clone, TypeUuid, Debug, Default, TypeName)] +#[derive(Clone, TypeUuid, Debug, Default, TypePath)] #[uuid = "d81b7179-0448-4eb0-89fe-c067222725bf"] pub struct AnimationClip { curves: HashMap>, diff --git a/crates/bevy_app/src/app.rs b/crates/bevy_app/src/app.rs index 8ab8cceff29e9..f430b90d75be9 100644 --- a/crates/bevy_app/src/app.rs +++ b/crates/bevy_app/src/app.rs @@ -923,8 +923,8 @@ impl App { /// See [`bevy_reflect::TypeRegistry::register_type_data`]. #[cfg(feature = "bevy_reflect")] pub fn register_type_data< - T: bevy_reflect::Reflect + bevy_reflect::TypeName + 'static, - D: bevy_reflect::TypeData + bevy_reflect::TypeName + bevy_reflect::FromType, + T: bevy_reflect::Reflect + bevy_reflect::TypePath + 'static, + D: bevy_reflect::TypeData + bevy_reflect::TypePath + bevy_reflect::FromType, >( &mut self, ) -> &mut Self { diff --git a/crates/bevy_asset/src/asset_server.rs b/crates/bevy_asset/src/asset_server.rs index 8bdfc81502333..f92577ebe37b5 100644 --- a/crates/bevy_asset/src/asset_server.rs +++ b/crates/bevy_asset/src/asset_server.rs @@ -88,7 +88,7 @@ pub struct AssetServerInternal { /// use bevy_asset::{AssetServer, Handle}; /// use bevy_ecs::prelude::{Commands, Res}; /// -/// # #[derive(Debug, bevy_reflect::TypeUuid, bevy_reflect::TypeName)] +/// # #[derive(Debug, bevy_reflect::TypeUuid, bevy_reflect::TypePath)] /// # #[uuid = "00000000-0000-0000-0000-000000000000"] /// # struct Image; /// @@ -575,7 +575,7 @@ impl AssetServer { "Failed to find AssetLifecycle for label '{:?}', which has an asset type {} (UUID {:?}). \ Are you sure this asset type has been added to your app builder?", label, - asset_value.type_name(), + asset_value.type_path(), asset_value.type_uuid(), ); } @@ -647,10 +647,10 @@ mod test { use crate::{loader::LoadedAsset, update_asset_storage_system}; use bevy_app::App; use bevy_ecs::prelude::*; - use bevy_reflect::{TypeName, TypeUuid}; + use bevy_reflect::{TypePath, TypeUuid}; use bevy_utils::BoxedFuture; - #[derive(Debug, TypeUuid, TypeName)] + #[derive(Debug, TypeUuid, TypePath)] #[uuid = "a5189b72-0572-4290-a2e0-96f73a491c44"] struct PngAsset; diff --git a/crates/bevy_asset/src/assets.rs b/crates/bevy_asset/src/assets.rs index 6f9a10bdd708a..23d7483f26a74 100644 --- a/crates/bevy_asset/src/assets.rs +++ b/crates/bevy_asset/src/assets.rs @@ -420,13 +420,13 @@ macro_rules! load_internal_asset { #[cfg(test)] mod tests { use bevy_app::App; - use bevy_reflect::TypeName; + use bevy_reflect::TypePath; use crate::{AddAsset, Assets}; #[test] fn asset_overwriting() { - #[derive(bevy_reflect::TypeUuid, TypeName)] + #[derive(bevy_reflect::TypeUuid, TypePath)] #[uuid = "44115972-f31b-46e5-be5c-2b9aece6a52f"] struct MyAsset; let mut app = App::new(); diff --git a/crates/bevy_asset/src/loader.rs b/crates/bevy_asset/src/loader.rs index 49fa776a943b6..cd3bf7d778507 100644 --- a/crates/bevy_asset/src/loader.rs +++ b/crates/bevy_asset/src/loader.rs @@ -5,7 +5,7 @@ use crate::{ use anyhow::Error; use anyhow::Result; use bevy_ecs::system::{Res, ResMut}; -use bevy_reflect::TypeName; +use bevy_reflect::TypePath; use bevy_reflect::{TypeUuid, TypeUuidDynamic}; use bevy_utils::{BoxedFuture, HashMap}; use crossbeam_channel::{Receiver, Sender}; @@ -48,13 +48,13 @@ pub trait AssetLoader: Send + Sync + 'static { /// /// In order to load assets into your game you must either add them manually to an asset storage /// with [`Assets::add`] or load them from the filesystem with [`AssetServer::load`]. -pub trait Asset: TypeUuid + AssetDynamic + TypeName {} +pub trait Asset: TypeUuid + AssetDynamic + TypePath {} /// An untyped version of the [`Asset`] trait. pub trait AssetDynamic: Downcast + TypeUuidDynamic + Send + Sync + 'static {} impl_downcast!(AssetDynamic); -impl Asset for T where T: TypeUuid + AssetDynamic + TypeUuidDynamic + TypeName {} +impl Asset for T where T: TypeUuid + AssetDynamic + TypeUuidDynamic + TypePath {} impl AssetDynamic for T where T: Send + Sync + 'static + TypeUuidDynamic {} diff --git a/crates/bevy_audio/src/audio_output.rs b/crates/bevy_audio/src/audio_output.rs index 3d3ed482df5ea..025fad8c2acf0 100644 --- a/crates/bevy_audio/src/audio_output.rs +++ b/crates/bevy_audio/src/audio_output.rs @@ -1,7 +1,7 @@ use crate::{Audio, AudioSource, Decodable}; use bevy_asset::{Asset, Assets}; use bevy_ecs::system::{NonSend, Res, ResMut}; -use bevy_reflect::{TypeName, TypeUuid}; +use bevy_reflect::{TypePath, TypeUuid}; use bevy_utils::tracing::warn; use rodio::{OutputStream, OutputStreamHandle, Sink, Source}; use std::marker::PhantomData; @@ -116,7 +116,7 @@ pub fn play_queued_audio_system( /// } /// ``` /// -#[derive(TypeUuid, TypeName)] +#[derive(TypeUuid, TypePath)] #[uuid = "8BEE570C-57C2-4FC0-8CFB-983A22F7D981"] pub struct AudioSink { // This field is an Option in order to allow us to have a safe drop that will detach the sink. diff --git a/crates/bevy_audio/src/audio_source.rs b/crates/bevy_audio/src/audio_source.rs index 6f5a99d1fa287..80f5a72564c51 100644 --- a/crates/bevy_audio/src/audio_source.rs +++ b/crates/bevy_audio/src/audio_source.rs @@ -1,11 +1,11 @@ use anyhow::Result; use bevy_asset::{AssetLoader, LoadContext, LoadedAsset}; -use bevy_reflect::{TypeName, TypeUuid}; +use bevy_reflect::{TypePath, TypeUuid}; use bevy_utils::BoxedFuture; use std::{io::Cursor, sync::Arc}; /// A source of audio data -#[derive(Debug, Clone, TypeUuid, TypeName)] +#[derive(Debug, Clone, TypeUuid, TypePath)] #[uuid = "7a14806a-672b-443b-8d16-4f18afefa463"] pub struct AudioSource { /// Raw data of the audio source diff --git a/crates/bevy_gltf/src/lib.rs b/crates/bevy_gltf/src/lib.rs index 70e5e3f5c2e81..c5f40a3de9f55 100644 --- a/crates/bevy_gltf/src/lib.rs +++ b/crates/bevy_gltf/src/lib.rs @@ -9,7 +9,7 @@ use bevy_app::prelude::*; use bevy_asset::{AddAsset, Handle}; use bevy_ecs::{prelude::Component, reflect::ReflectComponent}; use bevy_pbr::StandardMaterial; -use bevy_reflect::{Reflect, TypeName, TypeUuid}; +use bevy_reflect::{Reflect, TypePath, TypeUuid}; use bevy_render::mesh::Mesh; use bevy_scene::Scene; @@ -29,7 +29,7 @@ impl Plugin for GltfPlugin { } /// Representation of a loaded glTF file. -#[derive(Debug, TypeUuid, TypeName)] +#[derive(Debug, TypeUuid, TypePath)] #[uuid = "5c7d5f8a-f7b0-4e45-a09e-406c0372fea2"] pub struct Gltf { pub scenes: Vec>, @@ -49,7 +49,7 @@ pub struct Gltf { /// A glTF node with all of its child nodes, its [`GltfMesh`] and /// [`Transform`](bevy_transform::prelude::Transform). -#[derive(Debug, Clone, TypeUuid, TypeName)] +#[derive(Debug, Clone, TypeUuid, TypePath)] #[uuid = "dad74750-1fd6-460f-ac51-0a7937563865"] pub struct GltfNode { pub children: Vec, @@ -58,14 +58,14 @@ pub struct GltfNode { } /// A glTF mesh, which may consist of multiple [`GltfPrimitives`](GltfPrimitive). -#[derive(Debug, Clone, TypeUuid, TypeName)] +#[derive(Debug, Clone, TypeUuid, TypePath)] #[uuid = "8ceaec9a-926a-4f29-8ee3-578a69f42315"] pub struct GltfMesh { pub primitives: Vec, } /// Part of a [`GltfMesh`] that consists of a [`Mesh`] and an optional [`StandardMaterial`]. -#[derive(Debug, Clone, TypeUuid, TypeName)] +#[derive(Debug, Clone, TypeUuid, TypePath)] #[uuid = "cbfca302-82fd-41cb-af77-cab6b3d50af1"] pub struct GltfPrimitive { pub mesh: Handle, diff --git a/crates/bevy_pbr/src/material.rs b/crates/bevy_pbr/src/material.rs index 8b1ce63707158..34378cd53f7ef 100644 --- a/crates/bevy_pbr/src/material.rs +++ b/crates/bevy_pbr/src/material.rs @@ -17,7 +17,7 @@ use bevy_ecs::{ }, world::FromWorld, }; -use bevy_reflect::{TypeName, TypeUuid}; +use bevy_reflect::{TypePath, TypeUuid}; use bevy_render::{ extract_component::ExtractComponentPlugin, mesh::{Mesh, MeshVertexBufferLayout}, @@ -57,11 +57,11 @@ use std::marker::PhantomData; /// ``` /// # use bevy_pbr::{Material, MaterialMeshBundle}; /// # use bevy_ecs::prelude::*; -/// # use bevy_reflect::{TypeUuid, TypeName}; +/// # use bevy_reflect::{TypeUuid, TypePath}; /// # use bevy_render::{render_resource::{AsBindGroup, ShaderRef}, texture::Image, color::Color}; /// # use bevy_asset::{Handle, AssetServer, Assets}; /// -/// #[derive(AsBindGroup, TypeUuid, TypeName, Debug, Clone)] +/// #[derive(AsBindGroup, TypeUuid, TypePath, Debug, Clone)] /// #[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"] /// pub struct CustomMaterial { /// // Uniform bindings must implement `ShaderType`, which will be used to convert the value to @@ -109,7 +109,7 @@ use std::marker::PhantomData; /// var color_sampler: sampler; /// ``` pub trait Material: - AsBindGroup + Send + Sync + Clone + TypeUuid + TypeName + Sized + 'static + AsBindGroup + Send + Sync + Clone + TypeUuid + TypePath + Sized + 'static { /// Returns this material's vertex shader. If [`ShaderRef::Default`] is returned, the default mesh vertex shader /// will be used. diff --git a/crates/bevy_pbr/src/pbr_material.rs b/crates/bevy_pbr/src/pbr_material.rs index cc9bf1a31e99c..de2c450295a5a 100644 --- a/crates/bevy_pbr/src/pbr_material.rs +++ b/crates/bevy_pbr/src/pbr_material.rs @@ -1,7 +1,7 @@ use crate::{AlphaMode, Material, MaterialPipeline, MaterialPipelineKey, PBR_SHADER_HANDLE}; use bevy_asset::Handle; use bevy_math::Vec4; -use bevy_reflect::{TypeName, TypeUuid}; +use bevy_reflect::{TypePath, TypeUuid}; use bevy_render::{ color::Color, mesh::MeshVertexBufferLayout, render_asset::RenderAssets, render_resource::*, texture::Image, @@ -12,7 +12,7 @@ use bevy_render::{ /// . /// /// May be created directly from a [`Color`] or an [`Image`]. -#[derive(AsBindGroup, Debug, Clone, TypeUuid, TypeName)] +#[derive(AsBindGroup, Debug, Clone, TypeUuid, TypePath)] #[uuid = "7494888b-c082-457b-aacf-517228cc0c22"] #[bind_group_data(StandardMaterialKey)] #[uniform(0, StandardMaterialUniform)] diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs index 9269c96496906..5092ee753c9dd 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs @@ -4,7 +4,7 @@ use quote::quote; use syn::token::Comma; use crate::{ - utility, REFLECT_ATTRIBUTE_NAME, REFLECT_VALUE_ATTRIBUTE_NAME, TYPE_NAME_ATTRIBUTE_NAME, + utility, REFLECT_ATTRIBUTE_NAME, REFLECT_VALUE_ATTRIBUTE_NAME, TYPE_PATH_ATTRIBUTE_NAME, }; use syn::punctuated::Punctuated; use syn::spanned::Spanned; @@ -41,8 +41,8 @@ pub(crate) struct ReflectMeta<'a> { type_name: &'a Ident, /// The generics defined on this type. generics: &'a Generics, - /// Override the default type name for `TypeName`. - reflected_type_name: Option, + /// Override the default type path for `TypePath`. + reflected_type_path: Option, /// A cached instance of the path to the `bevy_reflect` crate. bevy_reflect_path: Path, } @@ -118,7 +118,7 @@ impl<'a> ReflectDerive<'a> { // Should indicate whether `#[reflect_value]` was used let mut force_reflect_value = false; - let mut reflected_type_name = None; + let mut reflected_type_path = None; for attribute in input.attrs.iter().filter_map(|attr| attr.parse_meta().ok()) { let meta_list = if let Meta::List(meta_list) = attribute { @@ -135,15 +135,15 @@ impl<'a> ReflectDerive<'a> { force_reflect_value = true; traits = ReflectTraits::from_nested_metas(&meta_list.nested); } - Some(ident) if ident == TYPE_NAME_ATTRIBUTE_NAME => { - let type_name = get_type_name_attribute(&meta_list.nested).ok_or_else(|| syn::Error::new(meta_list.span(), format!("the attribute `{TYPE_NAME_ATTRIBUTE_NAME}` requires a single string literal. For example: `#[{TYPE_NAME_ATTRIBUTE_NAME}(\"my_lib::foo\")]`")) )?; - reflected_type_name = Some(type_name); + Some(ident) if ident == TYPE_PATH_ATTRIBUTE_NAME => { + let type_path = get_type_path_attribute(&meta_list.nested).ok_or_else(|| syn::Error::new(meta_list.span(), format!("the attribute `{TYPE_PATH_ATTRIBUTE_NAME}` requires a single string literal. For example: `#[{TYPE_PATH_ATTRIBUTE_NAME}(\"my_lib::foo\")]`")) )?; + reflected_type_path = Some(type_path); } _ => {} } } - let meta = ReflectMeta::new(&input.ident, &input.generics, traits, reflected_type_name); + let meta = ReflectMeta::new(&input.ident, &input.generics, traits, reflected_type_path); if force_reflect_value { return Ok(Self::Value(meta)); @@ -231,13 +231,13 @@ impl<'a> ReflectMeta<'a> { type_name: &'a Ident, generics: &'a Generics, traits: ReflectTraits, - reflected_type_name: Option, + reflected_type_path: Option, ) -> Self { Self { traits, type_name, generics, - reflected_type_name, + reflected_type_path, bevy_reflect_path: utility::get_bevy_reflect_path(), } } @@ -257,9 +257,9 @@ impl<'a> ReflectMeta<'a> { self.generics } - /// Override the default type name for `TypeName`. - pub fn reflected_type_name(&self) -> Option<&str> { - self.reflected_type_name.as_deref() + /// Override the default type path for `TypePath`. + pub fn reflected_type_path(&self) -> Option<&str> { + self.reflected_type_path.as_deref() } /// The cached `bevy_reflect` path. @@ -338,8 +338,8 @@ impl<'a> ReflectEnum<'a> { } } -/// Extracts the type name attribute or returns [`None`]. -fn get_type_name_attribute(nested_metas: &Punctuated) -> Option { +/// Extracts the type path attribute or returns [`None`]. +fn get_type_path_attribute(nested_metas: &Punctuated) -> Option { // Having more than 1 element in nested_metas is invalid. if nested_metas.len() == 1 { match nested_metas.first() { diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/from_reflect.rs b/crates/bevy_reflect/bevy_reflect_derive/src/from_reflect.rs index 48800bb8ae846..83662172fe70a 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/from_reflect.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/from_reflect.rs @@ -51,7 +51,7 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> TokenStream { if let #bevy_reflect_path::ReflectRef::Enum(#ref_value) = #ref_value.reflect_ref() { match #ref_value.variant_name() { #(#variant_names => Some(#variant_constructors),)* - name => panic!("variant with name `{}` does not exist on enum `{}`", name, ::name()), + name => panic!("variant with name `{}` does not exist on enum `{}`", name, ::type_path()), } } else { None diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs index 74acd84a8c58c..1c18b2b86c4a3 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/enums.rs @@ -1,6 +1,6 @@ use crate::derive_data::{EnumVariantFields, ReflectEnum, StructField}; use crate::enum_utility::{get_variant_constructors, EnumVariantConstructors}; -use crate::impls::{impl_type_name, impl_typed}; +use crate::impls::{impl_type_path, impl_typed}; use proc_macro::TokenStream; use proc_macro2::{Ident, Span}; use quote::quote; @@ -64,7 +64,7 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> TokenStream { bevy_reflect_path, ); - let type_name_impl = impl_type_name(reflect_enum.meta()); + let type_path_impl = impl_type_path(reflect_enum.meta()); let get_type_registration_impl = reflect_enum.meta().get_type_registration(); let (impl_generics, ty_generics, where_clause) = @@ -75,7 +75,7 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> TokenStream { #typed_impl - #type_name_impl + #type_path_impl impl #impl_generics #bevy_reflect_path::Enum for #enum_name #ty_generics #where_clause { fn field(&self, #ref_name: &str) -> Option<&dyn #bevy_reflect_path::Reflect> { @@ -155,8 +155,8 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> TokenStream { impl #impl_generics #bevy_reflect_path::Reflect for #enum_name #ty_generics #where_clause { #[inline] - fn type_name(&self) -> &str { - ::name() + fn type_path(&self) -> &str { + ::type_path() } #[inline] @@ -225,11 +225,11 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> TokenStream { #(#variant_names => { *self = #variant_constructors })* - name => panic!("variant with name `{}` does not exist on enum `{}`", name, self.type_name()), + name => panic!("variant with name `{}` does not exist on enum `{}`", name, self.type_path()), } } } else { - panic!("`{}` is not an enum", #ref_value.type_name()); + panic!("`{}` is not an enum", #ref_value.type_path()); } } diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/mod.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/mod.rs index 29519dabf8296..8cda6b79644f8 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/mod.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/mod.rs @@ -1,13 +1,13 @@ mod enums; mod structs; mod tuple_structs; -mod type_name; +mod type_path; mod typed; mod values; pub(crate) use enums::impl_enum; pub(crate) use structs::impl_struct; pub(crate) use tuple_structs::impl_tuple_struct; -pub(crate) use type_name::impl_type_name; +pub(crate) use type_path::impl_type_path; pub(crate) use typed::impl_typed; pub(crate) use values::impl_value; diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs index 48d730c7a7f01..4d50a25cfc1e2 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/structs.rs @@ -1,4 +1,4 @@ -use crate::impls::{impl_type_name, impl_typed}; +use crate::impls::{impl_type_path, impl_typed}; use crate::ReflectStruct; use proc_macro::TokenStream; use quote::quote; @@ -64,7 +64,7 @@ pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> TokenStream { bevy_reflect_path, ); - let type_name_impl = impl_type_name(reflect_struct.meta()); + let type_path_impl = impl_type_path(reflect_struct.meta()); let get_type_registration_impl = reflect_struct.meta().get_type_registration(); let (impl_generics, ty_generics, where_clause) = @@ -75,7 +75,7 @@ pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> TokenStream { #typed_impl - #type_name_impl + #type_path_impl impl #impl_generics #bevy_reflect_path::Struct for #struct_name #ty_generics #where_clause { fn field(&self, name: &str) -> Option<&dyn #bevy_reflect_path::Reflect> { @@ -123,7 +123,7 @@ pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> TokenStream { fn clone_dynamic(&self) -> #bevy_reflect_path::DynamicStruct { let mut dynamic = #bevy_reflect_path::DynamicStruct::default(); - dynamic.set_name(self.type_name().to_string()); + dynamic.set_name(self.type_path().to_string()); #(dynamic.insert_boxed(#field_names, self.#field_idents.clone_value());)* dynamic } @@ -131,8 +131,8 @@ pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> TokenStream { impl #impl_generics #bevy_reflect_path::Reflect for #struct_name #ty_generics #where_clause { #[inline] - fn type_name(&self) -> &str { - ::name() + fn type_path(&self) -> &str { + ::type_path() } #[inline] diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs index 78b63bc40aa46..5bc3d1ba8131f 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs @@ -1,4 +1,4 @@ -use crate::impls::{impl_type_name, impl_typed}; +use crate::impls::{impl_type_path, impl_typed}; use crate::ReflectStruct; use proc_macro::TokenStream; use quote::quote; @@ -48,7 +48,7 @@ pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> TokenStream { bevy_reflect_path, ); - let type_name_impl = impl_type_name(reflect_struct.meta()); + let type_path_impl = impl_type_path(reflect_struct.meta()); let (impl_generics, ty_generics, where_clause) = reflect_struct.meta().generics().split_for_impl(); @@ -58,7 +58,7 @@ pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> TokenStream { #typed_impl - #type_name_impl + #type_path_impl impl #impl_generics #bevy_reflect_path::TupleStruct for #struct_name #ty_generics #where_clause { fn field(&self, index: usize) -> Option<&dyn #bevy_reflect_path::Reflect> { @@ -85,7 +85,7 @@ pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> TokenStream { fn clone_dynamic(&self) -> #bevy_reflect_path::DynamicTupleStruct { let mut dynamic = #bevy_reflect_path::DynamicTupleStruct::default(); - dynamic.set_name(self.type_name().to_string()); + dynamic.set_name(self.type_path().to_string()); #(dynamic.insert_boxed(self.#field_idents.clone_value());)* dynamic } @@ -93,8 +93,8 @@ pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> TokenStream { impl #impl_generics #bevy_reflect_path::Reflect for #struct_name #ty_generics #where_clause { #[inline] - fn type_name(&self) -> &str { - ::name() + fn type_path(&self) -> &str { + ::type_path() } #[inline] diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs similarity index 87% rename from crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs rename to crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs index 1e70624633cc6..31793e7ddfcba 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_name.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs @@ -2,7 +2,7 @@ use quote::quote; use crate::derive_data::ReflectMeta; -pub(crate) fn impl_type_name(reflect_meta: &ReflectMeta) -> proc_macro2::TokenStream { +pub(crate) fn impl_type_path(reflect_meta: &ReflectMeta) -> proc_macro2::TokenStream { let generics = reflect_meta.generics(); let type_name = reflect_meta.type_name(); let bevy_reflect_path = reflect_meta.bevy_reflect_path(); @@ -10,7 +10,7 @@ pub(crate) fn impl_type_name(reflect_meta: &ReflectMeta) -> proc_macro2::TokenSt let is_generic = !generics.params.is_empty(); let base_name = reflect_meta - .reflected_type_name() + .reflected_type_path() .map(|x| quote!(#x)) .unwrap_or_else(|| { let type_name = type_name.to_string(); @@ -22,7 +22,7 @@ pub(crate) fn impl_type_name(reflect_meta: &ReflectMeta) -> proc_macro2::TokenSt let getters = generics.params.iter().map(|p| match p { syn::GenericParam::Type(p) => { let ty = &p.ident; - quote!(<#ty as #bevy_reflect_path::TypeName>::name()) + quote!(<#ty as #bevy_reflect_path::TypePath>::type_path()) } syn::GenericParam::Lifetime(p) => { let name = &p.lifetime.ident.to_string(); @@ -57,8 +57,8 @@ pub(crate) fn impl_type_name(reflect_meta: &ReflectMeta) -> proc_macro2::TokenSt let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); quote! { - impl #impl_generics #bevy_reflect_path::TypeName for #type_name #ty_generics #where_clause { - fn name() -> &'static str { + impl #impl_generics #bevy_reflect_path::TypePath for #type_name #ty_generics #where_clause { + fn type_path() -> &'static str { const BASE_NAME: &'static str = #base_name; #get_type_name } diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs index 31bcf29182f69..843316a663ccf 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/values.rs @@ -1,4 +1,4 @@ -use crate::impls::{impl_type_name, impl_typed}; +use crate::impls::{impl_type_path, impl_typed}; use crate::ReflectMeta; use proc_macro::TokenStream; use quote::quote; @@ -22,7 +22,7 @@ pub(crate) fn impl_value(meta: &ReflectMeta) -> TokenStream { bevy_reflect_path, ); - let type_name_impl = impl_type_name(meta); + let type_path_impl = impl_type_path(meta); let (impl_generics, ty_generics, where_clause) = meta.generics().split_for_impl(); let get_type_registration_impl = meta.get_type_registration(); @@ -32,12 +32,12 @@ pub(crate) fn impl_value(meta: &ReflectMeta) -> TokenStream { #typed_impl - #type_name_impl + #type_path_impl impl #impl_generics #bevy_reflect_path::Reflect for #type_name #ty_generics #where_clause { #[inline] - fn type_name(&self) -> &str { - ::name() + fn type_path(&self) -> &str { + ::type_path() } #[inline] @@ -81,7 +81,7 @@ pub(crate) fn impl_value(meta: &ReflectMeta) -> TokenStream { if let Some(value) = value.downcast_ref::() { *self = value.clone(); } else { - panic!("Value is not {}.", self.type_name()); + panic!("Value is not {}.", self.type_path()); } } diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index 9fd39e38fcab1..44aab38b55edd 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -23,7 +23,7 @@ mod impls; mod reflect_value; mod registration; mod trait_reflection; -mod type_name; +mod type_path; mod type_uuid; mod utility; @@ -33,13 +33,13 @@ use quote::quote; use reflect_value::{NamedReflectValueDef, ReflectValueDef}; use syn::spanned::Spanned; use syn::{parse_macro_input, DeriveInput}; -use type_name::TypeNameDef; +use type_path::TypePathDef; pub(crate) static REFLECT_ATTRIBUTE_NAME: &str = "reflect"; pub(crate) static REFLECT_VALUE_ATTRIBUTE_NAME: &str = "reflect_value"; -pub(crate) static TYPE_NAME_ATTRIBUTE_NAME: &str = "type_name"; +pub(crate) static TYPE_PATH_ATTRIBUTE_NAME: &str = "type_path"; -#[proc_macro_derive(Reflect, attributes(reflect, reflect_value, module, type_name))] +#[proc_macro_derive(Reflect, attributes(reflect, reflect_value, module, type_path))] pub fn derive_reflect(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); @@ -58,43 +58,43 @@ pub fn derive_reflect(input: TokenStream) -> TokenStream { } } -/// Implement `TypeName` on a type. +/// Implement `TypePath` on a type. /// /// ## Type name convention /// -/// The type name is the module path followed by the ident of the type. -/// If the type is generic the type name of its generic parameters are included between `<` and `>`. +/// The type path is the module path followed by the ident of the type. +/// If the type is generic the type path of its generic parameters are included between `<` and `>`. /// /// See examples. /// -/// ## Custom type name +/// ## Custom type path /// -/// It's possible to override the default behaviour and choose a custom type name by using -/// the `type_name` attribute. +/// It's possible to override the default behaviour and choose a custom type path by using +/// the `type_path` attribute. /// -/// If specifying a custom type name, it's recommended to prefix it with the name of your crate. +/// If specifying a custom type path, it's recommended to prefix it with the name of your crate. /// -/// It's highly discouraged to use an unprefixed type name that could collide with another type -/// or a malformed type name (e.g. `BlAH@blah blah`). +/// It's highly discouraged to use an unprefixed type path that could collide with another type +/// or a malformed type path (e.g. `BlAH@blah blah`). /// /// ## Example /// /// ```ignore -/// # bevy_reflect::TypeName; +/// # bevy_reflect::TypePath; /// /// mod a { /// pub mod b { /// pub mod c { -/// #[derive(TypeName)] +/// #[derive(TypePath)] /// pub struct ABC; /// } /// -/// #[derive(TypeName)] -/// #[type_name("my_lib::AB")] +/// #[derive(TypePath)] +/// #[type_path("my_lib::AB")] /// pub struct AB(T); /// } /// -/// #[derive(TypeName)] +/// #[derive(TypePath)] /// pub struct A(N); /// } /// @@ -102,12 +102,12 @@ pub fn derive_reflect(input: TokenStream) -> TokenStream { /// # use a::b::AB; /// # use a::b::c::ABC; /// -/// assert_eq!(ABC::name(), "a::b::c::ABC"); -/// assert_eq!(AB::::name(), "my_lib::AB"); -/// assert_eq!(A::<5>::name(), "a::A<5>"); +/// assert_eq!(ABC::type_path(), "a::b::c::ABC"); +/// assert_eq!(AB::::type_path(), "my_lib::AB"); +/// assert_eq!(A::<5>::type_path(), "a::A<5>"); /// ``` -#[proc_macro_derive(TypeName, attributes(module, type_name))] -pub fn derive_type_name(input: TokenStream) -> TokenStream { +#[proc_macro_derive(TypePath, attributes(module, type_path))] +pub fn derive_type_path(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let derive_data = match ReflectDerive::from_input(&ast) { @@ -118,9 +118,9 @@ pub fn derive_type_name(input: TokenStream) -> TokenStream { match derive_data { ReflectDerive::TupleStruct(struct_data) | ReflectDerive::Struct(struct_data) - | ReflectDerive::UnitStruct(struct_data) => impls::impl_type_name(struct_data.meta()), - ReflectDerive::Enum(meta) => impls::impl_type_name(meta.meta()), - ReflectDerive::Value(meta) => impls::impl_type_name(&meta), + | ReflectDerive::UnitStruct(struct_data) => impls::impl_type_path(struct_data.meta()), + ReflectDerive::Enum(meta) => impls::impl_type_path(meta.meta()), + ReflectDerive::Value(meta) => impls::impl_type_path(&meta), } .into() } @@ -166,13 +166,13 @@ pub fn reflect_trait(args: TokenStream, input: TokenStream) -> TokenStream { pub fn impl_reflect_value(input: TokenStream) -> TokenStream { let def = parse_macro_input!(input as NamedReflectValueDef); - let reflected_type_name = def.get_reflected_type_name(); + let reflected_type_path = def.get_reflected_type_path(); impls::impl_value(&ReflectMeta::new( &def.def.type_name, &def.def.generics, def.def.traits.unwrap_or_default(), - Some(reflected_type_name), + Some(reflected_type_path), )) } @@ -253,26 +253,26 @@ pub fn impl_from_reflect_value(input: TokenStream) -> TokenStream { )) } -/// A replacement for `#[derive(TypeName)]` to be used with foreign types which +/// A replacement for `#[derive(TypePath)]` to be used with foreign types which /// the definitions of cannot be altered. /// -/// But unlike `#[derive(TypeName)]` that prefix the type name with the module path -/// using the macro [`module_path`], by default `impl_type_name` only uses the ident of the type -/// as the type name. +/// But unlike `#[derive(TypePath)]` that prefix the type path with the module path +/// using the macro [`module_path`], by default `impl_type_path` only uses the ident of the type +/// as the type path. /// /// # Example -/// Implementing `TypeName` for `Vec`: +/// Implementing `TypePath` for `Vec`: /// ```ignore -/// impl_type_name!(Vec); +/// impl_type_path!(Vec); /// ``` #[proc_macro] -pub fn impl_type_name(input: TokenStream) -> TokenStream { - let def = parse_macro_input!(input as TypeNameDef); +pub fn impl_type_path(input: TokenStream) -> TokenStream { + let def = parse_macro_input!(input as TypePathDef); let meta = ReflectMeta::new( &def.type_name, &def.generics, Default::default(), Some(def.type_name.to_string()), ); - TokenStream::from(impls::impl_type_name(&meta)) + TokenStream::from(impls::impl_type_path(&meta)) } diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs b/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs index 5a7aa46b27d07..26d68e8d7a68e 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs @@ -53,7 +53,7 @@ impl Parse for ReflectValueDef { } } -/// A [`ReflectValueDef`] that allow an optional custom type name in front. +/// A [`ReflectValueDef`] that allow an optional custom type path in front. /// /// # Example /// @@ -61,16 +61,16 @@ impl Parse for ReflectValueDef { /// impl_reflect_value!(@"my_lib::MyType" Foo where T1: Bar (TraitA, TraitB)); /// ``` pub(crate) struct NamedReflectValueDef { - pub reflected_type_name: Option, + pub reflected_type_path: Option, pub def: ReflectValueDef, } impl NamedReflectValueDef { - /// Returns the string to use as the reflected type name. + /// Returns the string to use as the reflected type path. /// - /// Use `reflected_type_name` if avaible otherwise use the `type_name` ident. - pub fn get_reflected_type_name(&self) -> String { - self.reflected_type_name + /// Use `reflected_type_path` if avaible otherwise use the `type_name` ident. + pub fn get_reflected_type_path(&self) -> String { + self.reflected_type_path .clone() .unwrap_or_else(|| self.def.type_name.to_string()) } @@ -79,17 +79,17 @@ impl NamedReflectValueDef { impl Parse for NamedReflectValueDef { fn parse(input: ParseStream) -> syn::Result { let lookahead = input.lookahead1(); - let mut reflected_type_name = None; + let mut reflected_type_path = None; if lookahead.peek(Token![@]) { let _at: Token![@] = input.parse()?; let name: LitStr = input.parse()?; - reflected_type_name = Some(name.value()); + reflected_type_path = Some(name.value()); } let def = input.parse()?; Ok(Self { - reflected_type_name, + reflected_type_path, def, }) } diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/type_name.rs b/crates/bevy_reflect/bevy_reflect_derive/src/type_path.rs similarity index 86% rename from crates/bevy_reflect/bevy_reflect_derive/src/type_name.rs rename to crates/bevy_reflect/bevy_reflect_derive/src/type_path.rs index 4b66561a120a2..f288d2678e957 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/type_name.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/type_path.rs @@ -2,12 +2,12 @@ use proc_macro2::Ident; use syn::parse::{Parse, ParseStream}; use syn::Generics; -pub(crate) struct TypeNameDef { +pub(crate) struct TypePathDef { pub type_name: Ident, pub generics: Generics, } -impl Parse for TypeNameDef { +impl Parse for TypePathDef { fn parse(input: ParseStream) -> syn::Result { let type_name = input.parse::()?; let generics = input.parse::()?; diff --git a/crates/bevy_reflect/src/array.rs b/crates/bevy_reflect/src/array.rs index 97ae9e0305429..d3833f646caea 100644 --- a/crates/bevy_reflect/src/array.rs +++ b/crates/bevy_reflect/src/array.rs @@ -1,6 +1,6 @@ use crate::{ self as bevy_reflect, utility::NonGenericTypeInfoCell, DynamicInfo, Reflect, ReflectMut, - ReflectRef, TypeInfo, TypeName, Typed, + ReflectRef, TypeInfo, TypePath, Typed, }; use std::{ any::{Any, TypeId}, @@ -36,7 +36,7 @@ pub trait Array: Reflect { fn clone_dynamic(&self) -> DynamicArray { DynamicArray { - name: self.type_name().to_string(), + name: self.type_path().to_string(), values: self.iter().map(|value| value.clone_value()).collect(), } } @@ -45,9 +45,9 @@ pub trait Array: Reflect { /// A container for compile-time array info. #[derive(Clone, Debug)] pub struct ArrayInfo { - type_name: &'static str, + type_path: &'static str, type_id: TypeId, - item_type_name: &'static str, + item_type_path: &'static str, item_type_id: TypeId, capacity: usize, } @@ -59,11 +59,11 @@ impl ArrayInfo { /// /// * `capacity`: The maximum capacity of the underlying array. /// - pub fn new(capacity: usize) -> Self { + pub fn new(capacity: usize) -> Self { Self { - type_name: TArray::name(), + type_path: ::type_path(), type_id: TypeId::of::(), - item_type_name: TItem::name(), + item_type_path: ::type_path(), item_type_id: TypeId::of::(), capacity, } @@ -74,11 +74,11 @@ impl ArrayInfo { self.capacity } - /// The [type name] of the array. + /// The [type path] of the array. /// - /// [type name]: TypeName - pub fn type_name(&self) -> &'static str { - self.type_name + /// [type path]: TypePath + pub fn type_path(&self) -> &'static str { + self.type_path } /// The [`TypeId`] of the array. @@ -91,11 +91,11 @@ impl ArrayInfo { TypeId::of::() == self.type_id } - /// The [type name] of the array item. + /// The [type path] of the array item. /// - /// [type name]: TypeName - pub fn item_type_name(&self) -> &'static str { - self.item_type_name + /// [type path]: TypePath + pub fn item_type_path(&self) -> &'static str { + self.item_type_path } /// The [`TypeId`] of the array item. @@ -118,7 +118,7 @@ impl ArrayInfo { /// can be mutated— just that the _number_ of items cannot change. /// /// [`DynamicList`]: crate::DynamicList -#[derive(TypeName)] +#[derive(TypePath)] pub struct DynamicArray { pub(crate) name: String, pub(crate) values: Box<[Box]>, @@ -157,7 +157,7 @@ impl DynamicArray { impl Reflect for DynamicArray { #[inline] - fn type_name(&self) -> &str { + fn type_path(&self) -> &str { &self.name } diff --git a/crates/bevy_reflect/src/enums/dynamic_enum.rs b/crates/bevy_reflect/src/enums/dynamic_enum.rs index da8173c708f03..a99fa04653871 100644 --- a/crates/bevy_reflect/src/enums/dynamic_enum.rs +++ b/crates/bevy_reflect/src/enums/dynamic_enum.rs @@ -1,4 +1,4 @@ -use bevy_reflect_derive::TypeName; +use bevy_reflect_derive::TypePath; use crate::utility::NonGenericTypeInfoCell; use crate::{ @@ -64,7 +64,7 @@ impl From<()> for DynamicVariant { /// /// // Create a DynamicEnum to represent the new value /// let mut dyn_enum = DynamicEnum::new( -/// Reflect::type_name(&value), +/// Reflect::type_path(&value), /// "None", /// DynamicVariant::Unit /// ); @@ -75,7 +75,7 @@ impl From<()> for DynamicVariant { /// // Tada! /// assert_eq!(None, value); /// ``` -#[derive(Default, TypeName)] +#[derive(Default, TypePath)] pub struct DynamicEnum { name: String, variant_name: String, @@ -87,7 +87,7 @@ impl DynamicEnum { /// /// # Arguments /// - /// * `name`: The type name of the enum + /// * `name`: The type path of the enum /// * `variant_name`: The name of the variant to set /// * `variant`: The variant data /// @@ -103,12 +103,12 @@ impl DynamicEnum { } } - /// Returns the type name of the enum. + /// Returns the type path of the enum. pub fn name(&self) -> &str { &self.name } - /// Sets the type name of the enum. + /// Sets the type path of the enum. pub fn set_name(&mut self, name: String) { self.name = name; } @@ -132,7 +132,7 @@ impl DynamicEnum { pub fn from_ref(value: &TEnum) -> Self { match value.variant_type() { VariantType::Unit => DynamicEnum::new( - value.type_name(), + value.type_path(), value.variant_name(), DynamicVariant::Unit, ), @@ -142,7 +142,7 @@ impl DynamicEnum { data.insert_boxed(field.value().clone_value()); } DynamicEnum::new( - value.type_name(), + value.type_path(), value.variant_name(), DynamicVariant::Tuple(data), ) @@ -154,7 +154,7 @@ impl DynamicEnum { data.insert_boxed(name, field.value().clone_value()); } DynamicEnum::new( - value.type_name(), + value.type_path(), value.variant_name(), DynamicVariant::Struct(data), ) @@ -247,7 +247,7 @@ impl Enum for DynamicEnum { impl Reflect for DynamicEnum { #[inline] - fn type_name(&self) -> &str { + fn type_path(&self) -> &str { &self.name } @@ -327,7 +327,7 @@ impl Reflect for DynamicEnum { self.set_variant(value.variant_name(), dyn_variant); } } else { - panic!("`{}` is not an enum", value.type_name()); + panic!("`{}` is not an enum", value.type_path()); } } diff --git a/crates/bevy_reflect/src/enums/enum_trait.rs b/crates/bevy_reflect/src/enums/enum_trait.rs index f924ef25a07ed..ff8aa9b107990 100644 --- a/crates/bevy_reflect/src/enums/enum_trait.rs +++ b/crates/bevy_reflect/src/enums/enum_trait.rs @@ -1,4 +1,4 @@ -use crate::{DynamicEnum, Reflect, TypeName, VariantInfo, VariantType}; +use crate::{type_path, DynamicEnum, Reflect, TypePath, VariantInfo, VariantType}; use bevy_utils::HashMap; use std::any::{Any, TypeId}; use std::borrow::Cow; @@ -124,14 +124,14 @@ pub trait Enum: Reflect { } /// Returns the full path to the current variant. fn variant_path(&self) -> String { - format!("{}::{}", self.type_name(), self.variant_name()) + format!("{}::{}", self.type_path(), self.variant_name()) } } /// A container for compile-time enum info, used by [`TypeInfo`](crate::TypeInfo). #[derive(Clone, Debug)] pub struct EnumInfo { - type_name: &'static str, + type_path: &'static str, type_id: TypeId, variants: Box<[VariantInfo]>, variant_indices: HashMap, usize>, @@ -144,7 +144,7 @@ impl EnumInfo { /// /// * `variants`: The variants of this enum in the order they are defined /// - pub fn new(variants: &[VariantInfo]) -> Self { + pub fn new(variants: &[VariantInfo]) -> Self { let variant_indices = variants .iter() .enumerate() @@ -155,7 +155,7 @@ impl EnumInfo { .collect::>(); Self { - type_name: TEnum::name(), + type_path: type_path::(), type_id: TypeId::of::(), variants: variants.to_vec().into_boxed_slice(), variant_indices, @@ -183,7 +183,7 @@ impl EnumInfo { /// /// This does _not_ check if the given variant exists. pub fn variant_path(&self, name: &str) -> String { - format!("{}::{}", self.type_name(), name) + format!("{}::{}", self.type_path(), name) } /// Checks if a variant with the given name exists within this enum. @@ -201,11 +201,11 @@ impl EnumInfo { self.variants.len() } - /// The [type name] of the enum. + /// The [type path] of the enum. /// - /// [type name]: crate::TypeName - pub fn type_name(&self) -> &'static str { - self.type_name + /// [type path]: crate::TypePath + pub fn type_path(&self) -> &'static str { + self.type_path } /// The [`TypeId`] of the enum. diff --git a/crates/bevy_reflect/src/enums/mod.rs b/crates/bevy_reflect/src/enums/mod.rs index 559ca94efa096..889b978a0c9fe 100644 --- a/crates/bevy_reflect/src/enums/mod.rs +++ b/crates/bevy_reflect/src/enums/mod.rs @@ -25,7 +25,7 @@ mod tests { let info = MyEnum::type_info(); if let TypeInfo::Enum(info) = info { assert!(info.is::(), "expected type to be `MyEnum`"); - assert_eq!(MyEnum::name(), info.type_name()); + assert_eq!(::type_path(), info.type_path()); // === MyEnum::A === // assert_eq!("A", info.variant_at(0).unwrap().name()); @@ -340,7 +340,7 @@ mod tests { #[test] fn enum_should_allow_generics() { #[derive(Reflect, Debug, PartialEq)] - enum TestEnum { + enum TestEnum { A, B(T), C { value: T }, @@ -366,14 +366,14 @@ mod tests { // === Tuple === // let mut data = DynamicTuple::default(); data.insert(1.23_f32); - let dyn_enum = DynamicEnum::new(TestEnum::::name(), "B", data); + let dyn_enum = DynamicEnum::new( as TypePath>::type_path(), "B", data); value.apply(&dyn_enum); assert_eq!(TestEnum::B(1.23), value); // === Struct === // let mut data = DynamicStruct::default(); data.insert("value", 1.23_f32); - let dyn_enum = DynamicEnum::new(TestEnum::::name(), "C", data); + let dyn_enum = DynamicEnum::new( as TypePath>::type_path(), "C", data); value.apply(&dyn_enum); assert_eq!(TestEnum::C { value: 1.23 }, value); } @@ -395,14 +395,14 @@ mod tests { // === Tuple === // let mut data = DynamicTuple::default(); data.insert(TestStruct(123)); - let dyn_enum = DynamicEnum::new(TestEnum::name(), "B", data); + let dyn_enum = DynamicEnum::new(::type_path(), "B", data); value.apply(&dyn_enum); assert_eq!(TestEnum::B(TestStruct(123)), value); // === Struct === // let mut data = DynamicStruct::default(); data.insert("value", TestStruct(123)); - let dyn_enum = DynamicEnum::new(TestEnum::name(), "C", data); + let dyn_enum = DynamicEnum::new(::type_path(), "C", data); value.apply(&dyn_enum); assert_eq!( TestEnum::C { @@ -433,14 +433,14 @@ mod tests { // === Tuple === // let mut data = DynamicTuple::default(); data.insert(OtherEnum::B(123)); - let dyn_enum = DynamicEnum::new(TestEnum::name(), "B", data); + let dyn_enum = DynamicEnum::new(::type_path(), "B", data); value.apply(&dyn_enum); assert_eq!(TestEnum::B(OtherEnum::B(123)), value); // === Struct === // let mut data = DynamicStruct::default(); data.insert("value", OtherEnum::C { value: 1.23 }); - let dyn_enum = DynamicEnum::new(TestEnum::name(), "C", data); + let dyn_enum = DynamicEnum::new(::type_path(), "C", data); value.apply(&dyn_enum); assert_eq!( TestEnum::C { diff --git a/crates/bevy_reflect/src/fields.rs b/crates/bevy_reflect/src/fields.rs index 40f29b0ab9eed..67ee85a01eef8 100644 --- a/crates/bevy_reflect/src/fields.rs +++ b/crates/bevy_reflect/src/fields.rs @@ -1,4 +1,4 @@ -use crate::{Reflect, TypeName}; +use crate::{type_path, Reflect, TypePath}; use std::any::{Any, TypeId}; use std::borrow::Cow; @@ -6,16 +6,16 @@ use std::borrow::Cow; #[derive(Clone, Debug)] pub struct NamedField { name: Cow<'static, str>, - type_name: &'static str, + type_path: &'static str, type_id: TypeId, } impl NamedField { /// Create a new [`NamedField`]. - pub fn new>>(name: TName) -> Self { + pub fn new>>(name: TName) -> Self { Self { name: name.into(), - type_name: T::name(), + type_path: type_path::(), type_id: TypeId::of::(), } } @@ -25,11 +25,11 @@ impl NamedField { &self.name } - /// The [type name] of the field. + /// The [type path] of the field. /// - /// [type name]: TypeName - pub fn type_name(&self) -> &'static str { - self.type_name + /// [type path]: TypePath + pub fn type_path(&self) -> &'static str { + self.type_path } /// The [`TypeId`] of the field. @@ -47,15 +47,15 @@ impl NamedField { #[derive(Clone, Debug)] pub struct UnnamedField { index: usize, - type_name: &'static str, + type_path: &'static str, type_id: TypeId, } impl UnnamedField { - pub fn new(index: usize) -> Self { + pub fn new(index: usize) -> Self { Self { index, - type_name: T::name(), + type_path: type_path::(), type_id: TypeId::of::(), } } @@ -65,11 +65,11 @@ impl UnnamedField { self.index } - /// The [type name] of the field. + /// The [type path] of the field. /// - /// [type name]: TypeName - pub fn type_name(&self) -> &'static str { - self.type_name + /// [type path]: TypePath + pub fn type_path(&self) -> &'static str { + self.type_path } /// The [`TypeId`] of the field. diff --git a/crates/bevy_reflect/src/impls/glam.rs b/crates/bevy_reflect/src/impls/glam.rs index e9f8e5b8580c2..03c93becbcd45 100644 --- a/crates/bevy_reflect/src/impls/glam.rs +++ b/crates/bevy_reflect/src/impls/glam.rs @@ -7,7 +7,7 @@ use glam::*; impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::IVec2")] + #[type_path("glam::IVec2")] struct IVec2 { x: i32, y: i32, @@ -15,7 +15,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::IVec3")] + #[type_path("glam::IVec3")] struct IVec3 { x: i32, y: i32, @@ -24,7 +24,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::IVec4")] + #[type_path("glam::IVec4")] struct IVec4 { x: i32, y: i32, @@ -35,7 +35,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::UVec2")] + #[type_path("glam::UVec2")] struct UVec2 { x: u32, y: u32, @@ -43,7 +43,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::UVec3")] + #[type_path("glam::UVec3")] struct UVec3 { x: u32, y: u32, @@ -52,7 +52,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::UVec4")] + #[type_path("glam::UVec4")] struct UVec4 { x: u32, y: u32, @@ -63,7 +63,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::Vec2")] + #[type_path("glam::Vec2")] struct Vec2 { x: f32, y: f32, @@ -71,7 +71,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::Vec3")] + #[type_path("glam::Vec3")] struct Vec3 { x: f32, y: f32, @@ -80,7 +80,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::Vec3A")] + #[type_path("glam::Vec3A")] struct Vec3A { x: f32, y: f32, @@ -89,7 +89,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::Vec4")] + #[type_path("glam::Vec4")] struct Vec4 { x: f32, y: f32, @@ -100,7 +100,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Default)] - #[type_name("glam::BVec2")] + #[type_path("glam::BVec2")] struct BVec2 { x: bool, y: bool, @@ -108,7 +108,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Default)] - #[type_name("glam::BVec3")] + #[type_path("glam::BVec3")] struct BVec3 { x: bool, y: bool, @@ -117,7 +117,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Default)] - #[type_name("glam::BVec4")] + #[type_path("glam::BVec4")] struct BVec4 { x: bool, y: bool, @@ -128,7 +128,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::DVec2")] + #[type_path("glam::DVec2")] struct DVec2 { x: f64, y: f64, @@ -136,7 +136,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::DVec3")] + #[type_path("glam::DVec3")] struct DVec3 { x: f64, y: f64, @@ -145,7 +145,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::DVec4")] + #[type_path("glam::DVec4")] struct DVec4 { x: f64, y: f64, @@ -156,7 +156,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::Mat2")] + #[type_path("glam::Mat2")] struct Mat2 { x_axis: Vec2, y_axis: Vec2, @@ -164,7 +164,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::Mat3")] + #[type_path("glam::Mat3")] struct Mat3 { x_axis: Vec3, y_axis: Vec3, @@ -173,7 +173,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::Mat3A")] + #[type_path("glam::Mat3A")] struct Mat3A { x_axis: Vec3A, y_axis: Vec3A, @@ -182,7 +182,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::Mat4")] + #[type_path("glam::Mat4")] struct Mat4 { x_axis: Vec4, y_axis: Vec4, @@ -193,7 +193,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::DMat2")] + #[type_path("glam::DMat2")] struct DMat2 { x_axis: DVec2, y_axis: DVec2, @@ -201,7 +201,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::DMat3")] + #[type_path("glam::DMat3")] struct DMat3 { x_axis: DVec3, y_axis: DVec3, @@ -210,7 +210,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::DMat4")] + #[type_path("glam::DMat4")] struct DMat4 { x_axis: DVec4, y_axis: DVec4, @@ -221,7 +221,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::Affine2")] + #[type_path("glam::Affine2")] struct Affine2 { matrix2: Mat2, translation: Vec2, @@ -229,7 +229,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::Affine3A")] + #[type_path("glam::Affine3A")] struct Affine3A { matrix3: Mat3A, translation: Vec3A, @@ -238,7 +238,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::DAffine2")] + #[type_path("glam::DAffine2")] struct DAffine2 { matrix2: DMat2, translation: DVec2, @@ -246,7 +246,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_name("glam::DAffine3")] + #[type_path("glam::DAffine3")] struct DAffine3 { matrix3: DMat3, translation: DVec3, @@ -277,13 +277,16 @@ impl_reflect_value!(@"glam::BVec4A" BVec4A(Debug, PartialEq, Default)); mod tests { use glam::*; - use crate::TypeName; + use crate::TypePath; #[test] fn type_name_should_be_prefixed_with_glam() { macro_rules! assert_name { ($t:ty) => { - assert_eq!(<$t as TypeName>::name(), concat!("glam::", stringify!($t))) + assert_eq!( + <$t as TypePath>::type_path(), + concat!("glam::", stringify!($t)) + ) }; } diff --git a/crates/bevy_reflect/src/impls/smallvec.rs b/crates/bevy_reflect/src/impls/smallvec.rs index 9827c2eff8e6f..3951b9801d8a1 100644 --- a/crates/bevy_reflect/src/impls/smallvec.rs +++ b/crates/bevy_reflect/src/impls/smallvec.rs @@ -1,19 +1,19 @@ -use bevy_reflect_derive::impl_type_name; +use bevy_reflect_derive::impl_type_path; use smallvec::SmallVec; use std::any::Any; use crate::utility::GenericTypeInfoCell; use crate::{ self as bevy_reflect, Array, ArrayIter, FromReflect, FromType, GetTypeRegistration, List, - ListInfo, Reflect, ReflectFromPtr, ReflectMut, ReflectRef, TypeInfo, TypeName, + ListInfo, Reflect, ReflectFromPtr, ReflectMut, ReflectRef, TypeInfo, TypePath, TypeRegistration, Typed, }; -impl_type_name!(SmallVec); +impl_type_path!(SmallVec); -impl Array for SmallVec +impl Array for SmallVec where - T::Item: FromReflect + TypeName, + T::Item: FromReflect + TypePath, { fn get(&self, index: usize) -> Option<&dyn Reflect> { if index < SmallVec::len(self) { @@ -49,16 +49,16 @@ where } } -impl List for SmallVec +impl List for SmallVec where - T::Item: FromReflect + TypeName, + T::Item: FromReflect + TypePath, { fn push(&mut self, value: Box) { let value = value.take::().unwrap_or_else(|value| { ::Item::from_reflect(&*value).unwrap_or_else(|| { panic!( "Attempted to push invalid value of type {}.", - value.type_name() + value.type_path() ) }) }); @@ -70,13 +70,13 @@ where } } -impl Reflect for SmallVec +impl Reflect for SmallVec where - T::Item: FromReflect + TypeName, + T::Item: FromReflect + TypePath, { #[inline] - fn type_name(&self) -> &str { - ::name() + fn type_path(&self) -> &str { + ::type_path() } fn get_type_info(&self) -> &'static TypeInfo { @@ -129,9 +129,9 @@ where } } -impl Typed for SmallVec +impl Typed for SmallVec where - T::Item: FromReflect + TypeName, + T::Item: FromReflect + TypePath, { fn type_info() -> &'static TypeInfo { static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new(); @@ -139,9 +139,9 @@ where } } -impl FromReflect for SmallVec +impl FromReflect for SmallVec where - T::Item: FromReflect + TypeName, + T::Item: FromReflect + TypePath, { fn from_reflect(reflect: &dyn Reflect) -> Option { if let ReflectRef::List(ref_list) = reflect.reflect_ref() { @@ -156,9 +156,9 @@ where } } -impl GetTypeRegistration for SmallVec +impl GetTypeRegistration for SmallVec where - T::Item: FromReflect + TypeName, + T::Item: FromReflect + TypePath, { fn get_type_registration() -> TypeRegistration { let mut registration = TypeRegistration::of::>(); diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index 0a539b4ce8103..e8a8ab14ef540 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -1,4 +1,4 @@ -use crate::{self as bevy_reflect, ReflectFromPtr, TypeName}; +use crate::{self as bevy_reflect, ReflectFromPtr, TypePath}; use crate::{ map_apply, map_partial_eq, Array, ArrayInfo, ArrayIter, DynamicEnum, DynamicMap, Enum, EnumInfo, FromReflect, FromType, GetTypeRegistration, List, ListInfo, Map, MapInfo, MapIter, @@ -8,7 +8,7 @@ use crate::{ }; use crate::utility::{GenericTypeInfoCell, GenericTypeNameCell, NonGenericTypeInfoCell}; -use bevy_reflect_derive::{impl_from_reflect_value, impl_reflect_value, impl_type_name}; +use bevy_reflect_derive::{impl_from_reflect_value, impl_reflect_value, impl_type_path}; use bevy_utils::{Duration, HashMap, HashSet, Instant}; use std::{ any::Any, @@ -39,15 +39,15 @@ impl_reflect_value!(f32(Debug, PartialEq, Serialize, Deserialize)); impl_reflect_value!(f64(Debug, PartialEq, Serialize, Deserialize)); impl_reflect_value!(String(Debug, Hash, PartialEq, Serialize, Deserialize)); impl_reflect_value!( - Result < T: Clone + Reflect + TypeName, - E: Clone + Reflect + TypeName > () + Result < T: Clone + Reflect + TypePath, + E: Clone + Reflect + TypePath > () ); -impl_reflect_value!(HashSet()); -impl_reflect_value!(@"std::Range" Range()); -impl_reflect_value!(@"std::RangeInclusive" RangeInclusive()); -impl_reflect_value!(@"std::RangeFrom" RangeFrom()); -impl_reflect_value!(@"std::RangeTo" RangeTo()); -impl_reflect_value!(@"std::RangeToInclusive" RangeToInclusive()); +impl_reflect_value!(HashSet()); +impl_reflect_value!(@"std::Range" Range()); +impl_reflect_value!(@"std::RangeInclusive" RangeInclusive()); +impl_reflect_value!(@"std::RangeFrom" RangeFrom()); +impl_reflect_value!(@"std::RangeTo" RangeTo()); +impl_reflect_value!(@"std::RangeToInclusive" RangeToInclusive()); impl_reflect_value!(@"std::RangeFull" RangeFull()); impl_reflect_value!(@"std::Duration" Duration(Debug, Hash, PartialEq, Serialize, Deserialize)); impl_reflect_value!(@"std::Instant" Instant(Debug, Hash, PartialEq)); @@ -81,12 +81,12 @@ impl_from_reflect_value!(isize); impl_from_reflect_value!(f32); impl_from_reflect_value!(f64); impl_from_reflect_value!(String); -impl_from_reflect_value!(HashSet); -impl_from_reflect_value!(Range); -impl_from_reflect_value!(RangeInclusive); -impl_from_reflect_value!(RangeFrom); -impl_from_reflect_value!(RangeTo); -impl_from_reflect_value!(RangeToInclusive); +impl_from_reflect_value!(HashSet); +impl_from_reflect_value!(Range); +impl_from_reflect_value!(RangeInclusive); +impl_from_reflect_value!(RangeFrom); +impl_from_reflect_value!(RangeTo); +impl_from_reflect_value!(RangeToInclusive); impl_from_reflect_value!(RangeFull); impl_from_reflect_value!(Duration); impl_from_reflect_value!(Instant); @@ -103,26 +103,26 @@ impl_from_reflect_value!(NonZeroU16); impl_from_reflect_value!(NonZeroU8); impl_from_reflect_value!(NonZeroI8); -impl_type_name!(Vec); -impl_type_name!(HashMap); -impl_type_name!(Option); +impl_type_path!(Vec); +impl_type_path!(HashMap); +impl_type_path!(Option); -// impl_type_name expects a type name followed by generic between `<` and `>`. +// impl_type_name expects a type path followed by generic between `<` and `>`. // so array is manually implemented. -impl TypeName for [T; N] { - fn name() -> &'static str { +impl TypePath for [T; N] { + fn type_path() -> &'static str { static CELL: GenericTypeNameCell = GenericTypeNameCell::new(); - CELL.get_or_insert::(|| format!("[{}; {N}]", T::name())) + CELL.get_or_insert::(|| format!("[{}; {N}]", T::type_path())) } } -impl TypeName for Cow<'static, str> { - fn name() -> &'static str { +impl TypePath for Cow<'static, str> { + fn type_path() -> &'static str { "Cow<'static, str>" } } -impl Array for Vec { +impl Array for Vec { #[inline] fn get(&self, index: usize) -> Option<&dyn Reflect> { <[T]>::get(self, index).map(|value| value as &dyn Reflect) @@ -154,13 +154,13 @@ impl Array for Vec { } } -impl List for Vec { +impl List for Vec { fn push(&mut self, value: Box) { let value = value.take::().unwrap_or_else(|value| { T::from_reflect(&*value).unwrap_or_else(|| { panic!( "Attempted to push invalid value of type {}.", - value.type_name() + value.type_path() ) }) }); @@ -172,9 +172,9 @@ impl List for Vec { } } -impl Reflect for Vec { - fn type_name(&self) -> &str { - ::name() +impl Reflect for Vec { + fn type_path(&self) -> &str { + ::type_path() } fn get_type_info(&self) -> &'static TypeInfo { @@ -231,14 +231,14 @@ impl Reflect for Vec { } } -impl Typed for Vec { +impl Typed for Vec { fn type_info() -> &'static TypeInfo { static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new(); CELL.get_or_insert::(|| TypeInfo::List(ListInfo::new::())) } } -impl GetTypeRegistration for Vec { +impl GetTypeRegistration for Vec { fn get_type_registration() -> TypeRegistration { let mut registration = TypeRegistration::of::>(); registration.insert::(FromType::>::from_type()); @@ -246,7 +246,7 @@ impl GetTypeRegistration for Vec { } } -impl FromReflect for Vec { +impl FromReflect for Vec { fn from_reflect(reflect: &dyn Reflect) -> Option { if let ReflectRef::List(ref_list) = reflect.reflect_ref() { let mut new_list = Self::with_capacity(ref_list.len()); @@ -260,7 +260,7 @@ impl FromReflect for Vec { } } -impl Map for HashMap { +impl Map for HashMap { fn get(&self, key: &dyn Reflect) -> Option<&dyn Reflect> { key.downcast_ref::() .and_then(|key| HashMap::get(self, key)) @@ -303,7 +303,7 @@ impl Map for H fn clone_dynamic(&self) -> DynamicMap { let mut dynamic_map = DynamicMap::default(); - dynamic_map.set_name(self.type_name().to_string()); + dynamic_map.set_name(self.type_path().to_string()); for (k, v) in self { dynamic_map.insert_boxed(k.clone_value(), v.clone_value()); } @@ -319,7 +319,7 @@ impl Map for H K::from_reflect(&*key).unwrap_or_else(|| { panic!( "Attempted to insert invalid key of type {}.", - key.type_name() + key.type_path() ) }) }); @@ -327,7 +327,7 @@ impl Map for H V::from_reflect(&*value).unwrap_or_else(|| { panic!( "Attempted to insert invalid value of type {}.", - value.type_name() + value.type_path() ) }) }); @@ -336,9 +336,9 @@ impl Map for H } } -impl Reflect for HashMap { - fn type_name(&self) -> &str { - ::name() +impl Reflect for HashMap { + fn type_path(&self) -> &str { + ::type_path() } fn get_type_info(&self) -> &'static TypeInfo { @@ -391,7 +391,7 @@ impl Reflect f } } -impl Typed for HashMap { +impl Typed for HashMap { fn type_info() -> &'static TypeInfo { static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new(); CELL.get_or_insert::(|| TypeInfo::Map(MapInfo::new::())) @@ -400,8 +400,8 @@ impl Typed for impl GetTypeRegistration for HashMap where - K: FromReflect + TypeName + Eq + Hash, - V: FromReflect + TypeName, + K: FromReflect + TypePath + Eq + Hash, + V: FromReflect + TypePath, { fn get_type_registration() -> TypeRegistration { let mut registration = TypeRegistration::of::>(); @@ -410,7 +410,7 @@ where } } -impl FromReflect +impl FromReflect for HashMap { fn from_reflect(reflect: &dyn Reflect) -> Option { @@ -428,7 +428,7 @@ impl FromRefle } } -impl Array for [T; N] { +impl Array for [T; N] { #[inline] fn get(&self, index: usize) -> Option<&dyn Reflect> { <[T]>::get(self, index).map(|value| value as &dyn Reflect) @@ -460,9 +460,9 @@ impl Array for [T; N] { } } -impl Reflect for [T; N] { - fn type_name(&self) -> &str { - ::name() +impl Reflect for [T; N] { + fn type_path(&self) -> &str { + ::type_path() } fn get_type_info(&self) -> &'static TypeInfo { @@ -531,7 +531,7 @@ impl Reflect for [T; N] { } } -impl FromReflect for [T; N] { +impl FromReflect for [T; N] { fn from_reflect(reflect: &dyn Reflect) -> Option { if let ReflectRef::Array(ref_array) = reflect.reflect_ref() { let mut temp_vec = Vec::with_capacity(ref_array.len()); @@ -545,7 +545,7 @@ impl FromReflect for [T; N] { } } -impl Typed for [T; N] { +impl Typed for [T; N] { fn type_info() -> &'static TypeInfo { static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new(); CELL.get_or_insert::(|| TypeInfo::Array(ArrayInfo::new::(N))) @@ -560,7 +560,7 @@ impl Typed for [T; N] { macro_rules! impl_array_get_type_registration { ($($N:expr)+) => { $( - impl GetTypeRegistration for [T; $N] { + impl GetTypeRegistration for [T; $N] { fn get_type_registration() -> TypeRegistration { TypeRegistration::of::<[T; $N]>() } @@ -577,8 +577,8 @@ impl_array_get_type_registration! { } impl Reflect for Cow<'static, str> { - fn type_name(&self) -> &str { - ::name() + fn type_path(&self) -> &str { + ::type_path() } fn get_type_info(&self) -> &'static TypeInfo { @@ -610,7 +610,7 @@ impl Reflect for Cow<'static, str> { if let Some(value) = value.downcast_ref::() { *self = value.clone(); } else { - panic!("Value is not a {}.", Self::name()); + panic!("Value is not a {}.", ::type_path()); } } @@ -648,13 +648,13 @@ impl Reflect for Cow<'static, str> { } } -impl GetTypeRegistration for Option { +impl GetTypeRegistration for Option { fn get_type_registration() -> TypeRegistration { TypeRegistration::of::>() } } -impl Enum for Option { +impl Enum for Option { fn field(&self, _name: &str) -> Option<&dyn Reflect> { None } @@ -718,9 +718,9 @@ impl Enum for Option { } } -impl Reflect for Option { - fn type_name(&self) -> &str { - ::name() +impl Reflect for Option { + fn type_path(&self) -> &str { + ::type_path() } #[inline] @@ -770,7 +770,7 @@ impl Reflect for Option { .unwrap_or_else(|| { panic!( "Field in `Some` variant of {} should exist", - Option::::name() + as TypePath>::type_path() ) }) .clone_value() @@ -779,8 +779,8 @@ impl Reflect for Option { T::from_reflect(&*value).unwrap_or_else(|| { panic!( "Field in `Some` variant of {} should be of type {}", - Option::::name(), - T::name() + as TypePath>::type_path(), + ::type_path() ) }) }); @@ -789,7 +789,7 @@ impl Reflect for Option { "None" => { *self = None; } - _ => panic!("Enum is not a {}.", Self::name()), + _ => panic!("Enum is not a {}.", ::type_path()), } } } @@ -823,7 +823,7 @@ impl Reflect for Option { } } -impl FromReflect for Option { +impl FromReflect for Option { fn from_reflect(reflect: &dyn Reflect) -> Option { if let ReflectRef::Enum(dyn_enum) = reflect.reflect_ref() { match dyn_enum.variant_name() { @@ -833,7 +833,7 @@ impl FromReflect for Option { .unwrap_or_else(|| { panic!( "Field in `Some` variant of {} should exist", - Option::::name() + as TypePath>::type_path() ) }) .clone_value() @@ -842,8 +842,8 @@ impl FromReflect for Option { T::from_reflect(&*value).unwrap_or_else(|| { panic!( "Field in `Some` variant of {} should be of type {}", - Option::::name(), - T::name() + as TypePath>::type_path(), + ::type_path() ) }) }); @@ -853,7 +853,7 @@ impl FromReflect for Option { name => panic!( "variant with name `{}` does not exist on enum `{}`", name, - Self::name() + ::type_path() ), } } else { @@ -862,7 +862,7 @@ impl FromReflect for Option { } } -impl Typed for Option { +impl Typed for Option { fn type_info() -> &'static TypeInfo { static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new(); CELL.get_or_insert::(|| { diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index 9cea84d880bb2..4da416bc1dbfa 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -10,7 +10,7 @@ mod struct_trait; mod tuple; mod tuple_struct; mod type_info; -mod type_name; +mod type_path; mod type_registry; mod type_uuid; mod impls { @@ -41,7 +41,7 @@ pub mod prelude { #[doc(hidden)] pub use crate::{ reflect_trait, FromReflect, GetField, GetTupleStructField, Reflect, ReflectDeserialize, - ReflectSerialize, Struct, TupleStruct, TypeName, + ReflectSerialize, Struct, TupleStruct, TypePath, }; } @@ -57,7 +57,7 @@ pub use struct_trait::*; pub use tuple::*; pub use tuple_struct::*; pub use type_info::*; -pub use type_name::*; +pub use type_path::*; pub use type_registry::*; pub use type_uuid::*; @@ -565,25 +565,25 @@ mod tests { fn dynamic_names() { let list = Vec::::new(); let dyn_list = List::clone_dynamic(&list); - assert_eq!(dyn_list.type_name(), as TypeName>::name()); + assert_eq!(dyn_list.type_path(), as TypePath>::type_path()); let array = [b'0'; 4]; let dyn_array = Array::clone_dynamic(&array); - assert_eq!(dyn_array.type_name(), <[u8; 4] as TypeName>::name()); + assert_eq!(dyn_array.type_path(), <[u8; 4] as TypePath>::type_path()); let map = HashMap::::default(); let dyn_map = map.clone_dynamic(); assert_eq!( - dyn_map.type_name(), - as TypeName>::name() + dyn_map.type_path(), + as TypePath>::type_path() ); let tuple = (0usize, "1".to_string(), 2.0f32); let mut dyn_tuple = tuple.clone_dynamic(); dyn_tuple.insert::(3); assert_eq!( - dyn_tuple.type_name(), - <(usize, String, f32, usize) as TypeName>::name() + dyn_tuple.type_path(), + <(usize, String, f32, usize) as TypePath>::type_path() ); #[derive(Reflect)] @@ -592,15 +592,18 @@ mod tests { } let struct_ = TestStruct { a: 0 }; let dyn_struct = struct_.clone_dynamic(); - assert_eq!(dyn_struct.type_name(), ::name()); + assert_eq!( + dyn_struct.type_path(), + ::type_path() + ); #[derive(Reflect)] struct TestTupleStruct(usize); let tuple_struct = TestTupleStruct(0); let dyn_tuple_struct = tuple_struct.clone_dynamic(); assert_eq!( - dyn_tuple_struct.type_name(), - ::name() + dyn_tuple_struct.type_path(), + ::type_path() ); } @@ -608,7 +611,7 @@ mod tests { fn reflect_type_info() { // TypeInfo let info = i32::type_info(); - assert_eq!(i32::name(), info.type_name()); + assert_eq!(type_path::(), info.type_path()); assert_eq!(std::any::TypeId::of::(), info.type_id()); // TypeInfo (unsized) @@ -632,15 +635,15 @@ mod tests { let info = MyStruct::type_info(); if let TypeInfo::Struct(info) = info { assert!(info.is::()); - assert_eq!(MyStruct::name(), info.type_name()); - assert_eq!(i32::name(), info.field("foo").unwrap().type_name()); + assert_eq!(type_path::(), info.type_path()); + assert_eq!(type_path::(), info.field("foo").unwrap().type_path()); assert_eq!( std::any::TypeId::of::(), info.field("foo").unwrap().type_id() ); assert!(info.field("foo").unwrap().is::()); assert_eq!("foo", info.field("foo").unwrap().name()); - assert_eq!(usize::name(), info.field_at(1).unwrap().type_name()); + assert_eq!(type_path::(), info.field_at(1).unwrap().type_path()); } else { panic!("Expected `TypeInfo::Struct`"); } @@ -651,7 +654,7 @@ mod tests { // Struct (generic) #[derive(Reflect)] - struct MyGenericStruct { + struct MyGenericStruct { foo: T, bar: usize, } @@ -659,10 +662,10 @@ mod tests { let info = >::type_info(); if let TypeInfo::Struct(info) = info { assert!(info.is::>()); - assert_eq!(MyGenericStruct::::name(), info.type_name()); - assert_eq!(i32::name(), info.field("foo").unwrap().type_name()); + assert_eq!(type_path::>(), info.type_path()); + assert_eq!(type_path::(), info.field("foo").unwrap().type_path()); assert_eq!("foo", info.field("foo").unwrap().name()); - assert_eq!(usize::name(), info.field_at(1).unwrap().type_name()); + assert_eq!(type_path::(), info.field_at(1).unwrap().type_path()); } else { panic!("Expected `TypeInfo::Struct`"); } @@ -681,8 +684,8 @@ mod tests { let info = MyTupleStruct::type_info(); if let TypeInfo::TupleStruct(info) = info { assert!(info.is::()); - assert_eq!(MyTupleStruct::name(), info.type_name()); - assert_eq!(i32::name(), info.field_at(1).unwrap().type_name()); + assert_eq!(type_path::(), info.type_path()); + assert_eq!(type_path::(), info.field_at(1).unwrap().type_path()); assert!(info.field_at(1).unwrap().is::()); } else { panic!("Expected `TypeInfo::TupleStruct`"); @@ -694,8 +697,8 @@ mod tests { let info = MyTuple::type_info(); if let TypeInfo::Tuple(info) = info { assert!(info.is::()); - assert_eq!(MyTuple::name(), info.type_name()); - assert_eq!(f32::name(), info.field_at(1).unwrap().type_name()); + assert_eq!(type_path::(), info.type_path()); + assert_eq!(type_path::(), info.field_at(1).unwrap().type_path()); } else { panic!("Expected `TypeInfo::Tuple`"); } @@ -711,8 +714,8 @@ mod tests { if let TypeInfo::List(info) = info { assert!(info.is::()); assert!(info.item_is::()); - assert_eq!(MyList::name(), info.type_name()); - assert_eq!(usize::name(), info.item_type_name()); + assert_eq!(type_path::(), info.type_path()); + assert_eq!(type_path::(), info.item_type_path()); } else { panic!("Expected `TypeInfo::List`"); } @@ -730,8 +733,8 @@ mod tests { if let TypeInfo::List(info) = info { assert!(info.is::()); assert!(info.item_is::()); - assert_eq!(MySmallVec::name(), info.type_name()); - assert_eq!(String::name(), info.item_type_name()); + assert_eq!(type_path::(), info.type_path()); + assert_eq!(type_path::(), info.item_type_path()); } else { panic!("Expected `TypeInfo::List`"); } @@ -749,8 +752,8 @@ mod tests { if let TypeInfo::Array(info) = info { assert!(info.is::()); assert!(info.item_is::()); - assert_eq!(MyArray::name(), info.type_name()); - assert_eq!(usize::name(), info.item_type_name()); + assert_eq!(type_path::(), info.type_path()); + assert_eq!(type_path::(), info.item_type_path()); assert_eq!(3, info.capacity()); } else { panic!("Expected `TypeInfo::Array`"); @@ -768,9 +771,9 @@ mod tests { assert!(info.is::()); assert!(info.key_is::()); assert!(info.value_is::()); - assert_eq!(MyMap::name(), info.type_name()); - assert_eq!(usize::name(), info.key_type_name()); - assert_eq!(f32::name(), info.value_type_name()); + assert_eq!(type_path::(), info.type_path()); + assert_eq!(type_path::(), info.key_type_path()); + assert_eq!(type_path::(), info.value_type_path()); } else { panic!("Expected `TypeInfo::Map`"); } @@ -785,7 +788,7 @@ mod tests { let info = MyValue::type_info(); if let TypeInfo::Value(info) = info { assert!(info.is::()); - assert_eq!(MyValue::name(), info.type_name()); + assert_eq!(type_path::(), info.type_path()); } else { panic!("Expected `TypeInfo::Value`"); } @@ -800,7 +803,7 @@ mod tests { let info = MyDynamic::type_info(); if let TypeInfo::Dynamic(info) = info { assert!(info.is::()); - assert_eq!(::name(), info.type_name()); + assert_eq!(::type_path(), info.type_path()); } else { panic!("Expected `TypeInfo::Dynamic`"); } @@ -925,33 +928,33 @@ bevy_reflect::tests::Test { #[test] fn reflect_type_name() { - #[derive(TypeName)] + #[derive(TypePath)] struct Foo; - let name = Foo::name(); + let name = Foo::type_path(); assert_eq!(name, "bevy_reflect::tests::Foo"); - #[derive(TypeName)] - struct Goo { + #[derive(TypePath)] + struct Goo { _value: T, } - let name = Goo::::name(); + let name = Goo::::type_path(); assert_eq!(name, "bevy_reflect::tests::Goo"); } #[test] fn reflect_custom_type_name() { - #[derive(TypeName)] - #[type_name("Banane")] + #[derive(TypePath)] + #[type_path("Banane")] struct Foo; - let name = Foo::name(); + let name = Foo::type_path(); assert_eq!(name, "Banane"); - #[derive(TypeName)] - #[type_name("MyType")] - struct Goo { + #[derive(TypePath)] + #[type_path("MyType")] + struct Goo { _value: T, } - let name = Goo::::name(); + let name = Goo::::type_path(); assert_eq!(name, "MyType"); } diff --git a/crates/bevy_reflect/src/list.rs b/crates/bevy_reflect/src/list.rs index 1257d9b7d1763..ac5b16df46488 100644 --- a/crates/bevy_reflect/src/list.rs +++ b/crates/bevy_reflect/src/list.rs @@ -3,8 +3,8 @@ use std::fmt::{Debug, Formatter}; use crate::utility::NonGenericTypeInfoCell; use crate::{ - self as bevy_reflect, Array, ArrayIter, DynamicArray, DynamicInfo, FromReflect, Reflect, - ReflectMut, ReflectRef, TypeInfo, TypeName, Typed, + self as bevy_reflect, type_path, Array, ArrayIter, DynamicArray, DynamicInfo, FromReflect, + Reflect, ReflectMut, ReflectRef, TypeInfo, TypePath, Typed, }; /// An ordered, mutable list of [Reflect] items. This corresponds to types like [`std::vec::Vec`]. @@ -21,7 +21,7 @@ pub trait List: Reflect + Array { /// Clones the list, producing a [`DynamicList`]. fn clone_dynamic(&self) -> DynamicList { DynamicList { - name: self.type_name().to_string(), + name: self.type_path().to_string(), values: self.iter().map(|value| value.clone_value()).collect(), } } @@ -30,28 +30,28 @@ pub trait List: Reflect + Array { /// A container for compile-time list info. #[derive(Clone, Debug)] pub struct ListInfo { - type_name: &'static str, + type_path: &'static str, type_id: TypeId, - item_type_name: &'static str, + item_type_path: &'static str, item_type_id: TypeId, } impl ListInfo { /// Create a new [`ListInfo`]. - pub fn new() -> Self { + pub fn new() -> Self { Self { - type_name: TList::name(), + type_path: type_path::(), type_id: TypeId::of::(), - item_type_name: TItem::name(), + item_type_path: type_path::(), item_type_id: TypeId::of::(), } } - /// The [type name] of the list. + /// The [type path] of the list. /// - /// [type name]: TypeName - pub fn type_name(&self) -> &'static str { - self.type_name + /// [type path]: TypePath + pub fn type_path(&self) -> &'static str { + self.type_path } /// The [`TypeId`] of the list. @@ -64,11 +64,11 @@ impl ListInfo { TypeId::of::() == self.type_id } - /// The [type name] of the list item. + /// The [type path] of the list item. /// - /// [type name]: TypeName - pub fn item_type_name(&self) -> &'static str { - self.item_type_name + /// [type path]: TypePath + pub fn item_type_path(&self) -> &'static str { + self.item_type_path } /// The [`TypeId`] of the list item. @@ -83,25 +83,25 @@ impl ListInfo { } /// A list of reflected values. -#[derive(Default, TypeName)] +#[derive(Default, TypePath)] pub struct DynamicList { name: String, values: Vec>, } impl DynamicList { - /// Returns the type name of the list. + /// Returns the type path of the list. /// /// The value returned by this method is the same value returned by - /// [`Reflect::type_name`]. + /// [`Reflect::type_path`]. pub fn name(&self) -> &str { &self.name } - /// Sets the type name of the list. + /// Sets the type path of the list. /// /// The value set by this method is the value returned by - /// [`Reflect::type_name`]. + /// [`Reflect::type_path`]. pub fn set_name(&mut self, name: String) { self.name = name; } @@ -176,7 +176,7 @@ impl List for DynamicList { impl Reflect for DynamicList { #[inline] - fn type_name(&self) -> &str { + fn type_path(&self) -> &str { &self.name } diff --git a/crates/bevy_reflect/src/map.rs b/crates/bevy_reflect/src/map.rs index 7bb313ea04357..1ffc46a4a6445 100644 --- a/crates/bevy_reflect/src/map.rs +++ b/crates/bevy_reflect/src/map.rs @@ -6,7 +6,8 @@ use bevy_utils::{Entry, HashMap}; use crate::utility::NonGenericTypeInfoCell; use crate::{ - self as bevy_reflect, DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, TypeName, Typed, + self as bevy_reflect, type_path, DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, + TypePath, Typed, }; /// An ordered mapping between [`Reflect`] values. @@ -64,36 +65,36 @@ pub trait Map: Reflect { /// A container for compile-time map info. #[derive(Clone, Debug)] pub struct MapInfo { - type_name: &'static str, + type_path: &'static str, type_id: TypeId, - key_type_name: &'static str, + key_type_path: &'static str, key_type_id: TypeId, - value_type_name: &'static str, + value_type_path: &'static str, value_type_id: TypeId, } impl MapInfo { /// Create a new [`MapInfo`]. pub fn new< - TMap: Map + TypeName, - TKey: Hash + Reflect + TypeName, - TValue: Reflect + TypeName, + TMap: Map + TypePath, + TKey: Hash + Reflect + TypePath, + TValue: Reflect + TypePath, >() -> Self { Self { - type_name: TMap::name(), + type_path: type_path::(), type_id: TypeId::of::(), - key_type_name: TKey::name(), + key_type_path: type_path::(), key_type_id: TypeId::of::(), - value_type_name: TValue::name(), + value_type_path: type_path::(), value_type_id: TypeId::of::(), } } - /// The [type name] of the map. + /// The [type path] of the map. /// - /// [type name]: TypeName - pub fn type_name(&self) -> &'static str { - self.type_name + /// [type path]: TypePath + pub fn type_path(&self) -> &'static str { + self.type_path } /// The [`TypeId`] of the map. @@ -106,11 +107,11 @@ impl MapInfo { TypeId::of::() == self.type_id } - /// The [type name] of the key. + /// The [type path] of the key. /// - /// [type name]: TypeName - pub fn key_type_name(&self) -> &'static str { - self.key_type_name + /// [type path]: TypePath + pub fn key_type_path(&self) -> &'static str { + self.key_type_path } /// The [`TypeId`] of the key. @@ -123,11 +124,11 @@ impl MapInfo { TypeId::of::() == self.key_type_id } - /// The [type name] of the value. + /// The [type path] of the value. /// - /// [type name]: TypeName - pub fn value_type_name(&self) -> &'static str { - self.value_type_name + /// [type path]: TypePath + pub fn value_type_path(&self) -> &'static str { + self.value_type_path } /// The [`TypeId`] of the value. @@ -144,7 +145,7 @@ impl MapInfo { const HASH_ERROR: &str = "the given key does not support hashing"; /// An ordered mapping between reflected values. -#[derive(Default, TypeName)] +#[derive(Default, TypePath)] pub struct DynamicMap { name: String, values: Vec<(Box, Box)>, @@ -152,18 +153,18 @@ pub struct DynamicMap { } impl DynamicMap { - /// Returns the type name of the map. + /// Returns the type path of the map. /// /// The value returned by this method is the same value returned by - /// [`Reflect::type_name`]. + /// [`Reflect::type_path`]. pub fn name(&self) -> &str { &self.name } - /// Sets the type name of the map. + /// Sets the type path of the map. /// /// The value set by this method is the same value returned by - /// [`Reflect::type_name`]. + /// [`Reflect::type_path`]. pub fn set_name(&mut self, name: String) { self.name = name; } @@ -243,7 +244,7 @@ impl Map for DynamicMap { impl Reflect for DynamicMap { #[inline] - fn type_name(&self) -> &str { + fn type_path(&self) -> &str { &self.name } diff --git a/crates/bevy_reflect/src/reflect.rs b/crates/bevy_reflect/src/reflect.rs index e068417b03122..a8e196c1d5268 100644 --- a/crates/bevy_reflect/src/reflect.rs +++ b/crates/bevy_reflect/src/reflect.rs @@ -1,6 +1,6 @@ use crate::{ array_debug, enum_debug, list_debug, map_debug, serde::Serializable, struct_debug, tuple_debug, - tuple_struct_debug, Array, Enum, List, Map, Struct, Tuple, TupleStruct, TypeInfo, TypeName, + tuple_struct_debug, Array, Enum, List, Map, Struct, Tuple, TupleStruct, TypeInfo, TypePath, Typed, ValueInfo, }; use std::{ @@ -53,8 +53,8 @@ pub enum ReflectMut<'a> { /// When using `#[derive(Reflect)]` on a struct, tuple struct or enum, the suitable subtrait for that /// type (`Struct`, `TupleStruct` or `Enum`) is derived automatically. pub trait Reflect: Any + Send + Sync { - /// Returns the [type name][crate::TypeName] of the underlying type. - fn type_name(&self) -> &str; + /// Returns the [type path][crate::TypePath] of the underlying type. + fn type_path(&self) -> &str; /// Returns the [`TypeInfo`] of the underlying type. /// @@ -165,10 +165,10 @@ pub trait Reflect: Any + Send + Sync { /// Debug formatter for the value. /// /// Any value that is not an implementor of other `Reflect` subtraits - /// (e.g. [`List`], [`Map`]), will default to the format: `"Reflect(type_name)"`, - /// where `type_name` is the [type name] of the underlying type. + /// (e.g. [`List`], [`Map`]), will default to the format: `"Reflect(type_path)"`, + /// where `type_path` is the [type path] of the underlying type. /// - /// [type name]: Self::type_name + /// [type path]: Self::type_path fn debug(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self.reflect_ref() { ReflectRef::Struct(dyn_struct) => struct_debug(dyn_struct, f), @@ -178,7 +178,7 @@ pub trait Reflect: Any + Send + Sync { ReflectRef::Array(dyn_array) => array_debug(dyn_array, f), ReflectRef::Map(dyn_map) => map_debug(dyn_map, f), ReflectRef::Enum(dyn_enum) => enum_debug(dyn_enum, f), - _ => write!(f, "Reflect({})", self.type_name()), + _ => write!(f, "Reflect({})", self.type_path()), } } @@ -218,8 +218,8 @@ impl Typed for dyn Reflect { } } -impl TypeName for dyn Reflect { - fn name() -> &'static str { +impl TypePath for dyn Reflect { + fn type_path() -> &'static str { "dyn Reflect" } } @@ -249,8 +249,8 @@ impl dyn Reflect { /// /// Read `is` for more information on underlying values and represented types. #[inline] - pub fn represents(&self) -> bool { - self.type_name() == T::name() + pub fn represents(&self) -> bool { + self.type_path() == ::type_path() } /// Returns `true` if the underlying value is of type `T`, or `false` diff --git a/crates/bevy_reflect/src/serde/ser.rs b/crates/bevy_reflect/src/serde/ser.rs index 0991ee045a7a7..50c2c7a9f9811 100644 --- a/crates/bevy_reflect/src/serde/ser.rs +++ b/crates/bevy_reflect/src/serde/ser.rs @@ -32,7 +32,7 @@ fn get_serializable<'a, E: serde::ser::Error>( .ok_or_else(|| { serde::ser::Error::custom(format_args!( "Type '{}' did not register ReflectSerialize", - reflect_value.type_name() + reflect_value.type_path() )) })?; Ok(reflect_serialize.get_serializable(reflect_value)) @@ -110,7 +110,7 @@ impl<'a> Serialize for ReflectValueSerializer<'a> { S: serde::Serializer, { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.value.type_name())?; + state.serialize_entry(type_fields::TYPE, self.value.type_path())?; state.serialize_entry( type_fields::VALUE, get_serializable::(self.value, self.registry)?.borrow(), @@ -131,7 +131,7 @@ impl<'a> Serialize for StructSerializer<'a> { { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.struct_value.type_name())?; + state.serialize_entry(type_fields::TYPE, self.struct_value.type_path())?; state.serialize_entry( type_fields::STRUCT, &StructValueSerializer { @@ -174,7 +174,7 @@ impl<'a> Serialize for TupleStructSerializer<'a> { { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.tuple_struct.type_name())?; + state.serialize_entry(type_fields::TYPE, self.tuple_struct.type_path())?; state.serialize_entry( type_fields::TUPLE_STRUCT, &TupleStructValueSerializer { @@ -216,7 +216,7 @@ impl<'a> Serialize for EnumSerializer<'a> { { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.enum_value.type_name())?; + state.serialize_entry(type_fields::TYPE, self.enum_value.type_path())?; state.serialize_entry( type_fields::ENUM, &EnumValueSerializer { @@ -327,7 +327,7 @@ impl<'a> Serialize for TupleSerializer<'a> { { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.tuple.type_name())?; + state.serialize_entry(type_fields::TYPE, self.tuple.type_path())?; state.serialize_entry( type_fields::TUPLE, &TupleValueSerializer { @@ -369,7 +369,7 @@ impl<'a> Serialize for MapSerializer<'a> { { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.map.type_name())?; + state.serialize_entry(type_fields::TYPE, self.map.type_path())?; state.serialize_entry( type_fields::MAP, &MapValueSerializer { @@ -413,7 +413,7 @@ impl<'a> Serialize for ListSerializer<'a> { S: serde::Serializer, { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.list.type_name())?; + state.serialize_entry(type_fields::TYPE, self.list.type_path())?; state.serialize_entry( type_fields::LIST, &ListValueSerializer { @@ -454,7 +454,7 @@ impl<'a> Serialize for ArraySerializer<'a> { S: serde::Serializer, { let mut state = serializer.serialize_map(Some(2))?; - state.serialize_entry(type_fields::TYPE, self.array.type_name())?; + state.serialize_entry(type_fields::TYPE, self.array.type_path())?; state.serialize_entry( type_fields::ARRAY, &ArrayValueSerializer { diff --git a/crates/bevy_reflect/src/struct_trait.rs b/crates/bevy_reflect/src/struct_trait.rs index 40ee985cdf39e..a5e6880de8978 100644 --- a/crates/bevy_reflect/src/struct_trait.rs +++ b/crates/bevy_reflect/src/struct_trait.rs @@ -1,7 +1,7 @@ use crate::utility::NonGenericTypeInfoCell; use crate::{ - self as bevy_reflect, DynamicInfo, NamedField, Reflect, ReflectMut, ReflectRef, TypeInfo, - TypeName, Typed, + self as bevy_reflect, type_path, DynamicInfo, NamedField, Reflect, ReflectMut, ReflectRef, + TypeInfo, TypePath, Typed, }; use bevy_utils::{Entry, HashMap}; use std::fmt::{Debug, Formatter}; @@ -72,7 +72,7 @@ pub trait Struct: Reflect { /// A container for compile-time struct info. #[derive(Clone, Debug)] pub struct StructInfo { - type_name: &'static str, + type_path: &'static str, type_id: TypeId, fields: Box<[NamedField]>, field_indices: HashMap, usize>, @@ -85,7 +85,7 @@ impl StructInfo { /// /// * `fields`: The fields of this struct in the order they are defined /// - pub fn new(fields: &[NamedField]) -> Self { + pub fn new(fields: &[NamedField]) -> Self { let field_indices = fields .iter() .enumerate() @@ -96,7 +96,7 @@ impl StructInfo { .collect::>(); Self { - type_name: T::name(), + type_path: type_path::(), type_id: TypeId::of::(), fields: fields.to_vec().into_boxed_slice(), field_indices, @@ -130,11 +130,11 @@ impl StructInfo { self.fields.len() } - /// The [type name] of the struct. + /// The [type path] of the struct. /// - /// [type name]: TypeName - pub fn type_name(&self) -> &'static str { - self.type_name + /// [type path]: TypePath + pub fn type_path(&self) -> &'static str { + self.type_path } /// The [`TypeId`] of the struct. @@ -233,7 +233,7 @@ impl GetField for dyn Struct { } /// A struct type which allows fields to be added at runtime. -#[derive(Default, TypeName)] +#[derive(Default, TypePath)] pub struct DynamicStruct { name: String, fields: Vec>, @@ -242,12 +242,12 @@ pub struct DynamicStruct { } impl DynamicStruct { - /// Returns the type name of the struct. + /// Returns the type path of the struct. pub fn name(&self) -> &str { &self.name } - /// Sets the type name of the struct. + /// Sets the type path of the struct. pub fn set_name(&mut self, name: String) { self.name = name; } @@ -347,7 +347,7 @@ impl Struct for DynamicStruct { impl Reflect for DynamicStruct { #[inline] - fn type_name(&self) -> &str { + fn type_path(&self) -> &str { &self.name } @@ -495,7 +495,7 @@ pub fn struct_partial_eq(a: &S, b: &dyn Reflect) -> Option { /// ``` #[inline] pub fn struct_debug(dyn_struct: &dyn Struct, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let mut debug = f.debug_struct(dyn_struct.type_name()); + let mut debug = f.debug_struct(dyn_struct.type_path()); for field_index in 0..dyn_struct.field_len() { let field = dyn_struct.field_at(field_index).unwrap(); debug.field( diff --git a/crates/bevy_reflect/src/tuple.rs b/crates/bevy_reflect/src/tuple.rs index 45cb2b3ba9b2e..a6452a840ee65 100644 --- a/crates/bevy_reflect/src/tuple.rs +++ b/crates/bevy_reflect/src/tuple.rs @@ -1,7 +1,7 @@ use crate::utility::NonGenericTypeInfoCell; use crate::{ - self as bevy_reflect, DynamicInfo, FromReflect, GetTypeRegistration, Reflect, ReflectMut, - ReflectRef, TypeInfo, TypeName, TypeRegistration, Typed, UnnamedField, + self as bevy_reflect, type_path, DynamicInfo, FromReflect, GetTypeRegistration, Reflect, + ReflectMut, ReflectRef, TypeInfo, TypePath, TypeRegistration, Typed, UnnamedField, }; use std::any::{Any, TypeId}; use std::fmt::{Debug, Formatter}; @@ -131,7 +131,7 @@ impl GetTupleField for dyn Tuple { /// A container for compile-time tuple info. #[derive(Clone, Debug)] pub struct TupleInfo { - type_name: &'static str, + type_path: &'static str, type_id: TypeId, fields: Box<[UnnamedField]>, } @@ -143,9 +143,9 @@ impl TupleInfo { /// /// * `fields`: The fields of this tuple in the order they are defined /// - pub fn new(fields: &[UnnamedField]) -> Self { + pub fn new(fields: &[UnnamedField]) -> Self { Self { - type_name: T::name(), + type_path: type_path::(), type_id: TypeId::of::(), fields: fields.to_vec().into_boxed_slice(), } @@ -166,11 +166,11 @@ impl TupleInfo { self.fields.len() } - /// The [type name] of the tuple. + /// The [type path] of the tuple. /// - /// [type name]: TypeName - pub fn type_name(&self) -> &'static str { - self.type_name + /// [type path]: TypePath + pub fn type_path(&self) -> &'static str { + self.type_path } /// The [`TypeId`] of the tuple. @@ -185,21 +185,21 @@ impl TupleInfo { } /// A tuple which allows fields to be added at runtime. -#[derive(Default, TypeName)] +#[derive(Default, TypePath)] pub struct DynamicTuple { name: String, fields: Vec>, } impl DynamicTuple { - /// Returns the type name of the tuple. + /// Returns the type path of the tuple. /// /// The tuple's name is automatically generated from its element types. pub fn name(&self) -> &str { &self.name } - /// Manually sets the type name of the tuple. + /// Manually sets the type path of the tuple. /// /// Note that the tuple name will be overwritten when elements are added. pub fn set_name(&mut self, name: String) { @@ -226,7 +226,7 @@ impl DynamicTuple { if i > 0 { name.push_str(", "); } - name.push_str(field.type_name()); + name.push_str(field.type_path()); } name.push(')'); } @@ -276,7 +276,7 @@ impl Tuple for DynamicTuple { impl Reflect for DynamicTuple { #[inline] - fn type_name(&self) -> &str { + fn type_path(&self) -> &str { &self.name } @@ -428,7 +428,7 @@ pub fn tuple_debug(dyn_tuple: &dyn Tuple, f: &mut std::fmt::Formatter<'_>) -> st macro_rules! impl_reflect_tuple { {$($index:tt : $name:tt),*} => { - impl<$($name: Reflect + TypeName),*> Tuple for ($($name,)*) { + impl<$($name: Reflect + TypePath),*> Tuple for ($($name,)*) { #[inline] fn field(&self, index: usize) -> Option<&dyn Reflect> { match index { @@ -480,10 +480,10 @@ macro_rules! impl_reflect_tuple { } } - impl<$($name: Reflect + TypeName),*> Reflect for ($($name,)*) { + impl<$($name: Reflect + TypePath),*> Reflect for ($($name,)*) { #[inline] - fn type_name(&self) -> &str { - ::name() + fn type_path(&self) -> &str { + ::type_path() } fn get_type_info(&self) -> &'static TypeInfo { @@ -536,7 +536,7 @@ macro_rules! impl_reflect_tuple { } } - impl <$($name: Reflect + TypeName),*> Typed for ($($name,)*) { + impl <$($name: Reflect + TypePath),*> Typed for ($($name,)*) { fn type_info() -> &'static TypeInfo { static CELL: $crate::utility::GenericTypeInfoCell = $crate::utility::GenericTypeInfoCell::new(); CELL.get_or_insert::(|| { @@ -549,13 +549,13 @@ macro_rules! impl_reflect_tuple { } } - impl<$($name: Reflect + TypeName + Typed),*> GetTypeRegistration for ($($name,)*) { + impl<$($name: Reflect + TypePath + Typed),*> GetTypeRegistration for ($($name,)*) { fn get_type_registration() -> TypeRegistration { TypeRegistration::of::<($($name,)*)>() } } - impl<$($name: FromReflect + TypeName),*> FromReflect for ($($name,)*) + impl<$($name: FromReflect + TypePath),*> FromReflect for ($($name,)*) { fn from_reflect(reflect: &dyn Reflect) -> Option { if let ReflectRef::Tuple(_ref_tuple) = reflect.reflect_ref() { diff --git a/crates/bevy_reflect/src/tuple_struct.rs b/crates/bevy_reflect/src/tuple_struct.rs index 817777f9ee96a..f47dfb4f3c53c 100644 --- a/crates/bevy_reflect/src/tuple_struct.rs +++ b/crates/bevy_reflect/src/tuple_struct.rs @@ -1,7 +1,7 @@ use crate::utility::NonGenericTypeInfoCell; use crate::{ - self as bevy_reflect, DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, TypeName, Typed, - UnnamedField, + self as bevy_reflect, type_path, DynamicInfo, Reflect, ReflectMut, ReflectRef, TypeInfo, + TypePath, Typed, UnnamedField, }; use std::any::{Any, TypeId}; use std::fmt::{Debug, Formatter}; @@ -52,7 +52,7 @@ pub trait TupleStruct: Reflect { /// A container for compile-time tuple struct info. #[derive(Clone, Debug)] pub struct TupleStructInfo { - type_name: &'static str, + type_path: &'static str, type_id: TypeId, fields: Box<[UnnamedField]>, } @@ -64,9 +64,9 @@ impl TupleStructInfo { /// /// * `fields`: The fields of this struct in the order they are defined /// - pub fn new(fields: &[UnnamedField]) -> Self { + pub fn new(fields: &[UnnamedField]) -> Self { Self { - type_name: T::name(), + type_path: type_path::(), type_id: TypeId::of::(), fields: fields.to_vec().into_boxed_slice(), } @@ -87,11 +87,11 @@ impl TupleStructInfo { self.fields.len() } - /// The [type name] of the tuple struct. + /// The [type path] of the tuple struct. /// - /// [type name]: TypeName - pub fn type_name(&self) -> &'static str { - self.type_name + /// [type path]: TypePath + pub fn type_path(&self) -> &'static str { + self.type_path } /// The [`TypeId`] of the tuple struct. @@ -190,19 +190,19 @@ impl GetTupleStructField for dyn TupleStruct { } /// A tuple struct which allows fields to be added at runtime. -#[derive(Default, TypeName)] +#[derive(Default, TypePath)] pub struct DynamicTupleStruct { name: String, fields: Vec>, } impl DynamicTupleStruct { - /// Returns the type name of the tuple struct. + /// Returns the type path of the tuple struct. pub fn name(&self) -> &str { &self.name } - /// Sets the type name of the tuple struct. + /// Sets the type path of the tuple struct. pub fn set_name(&mut self, name: String) { self.name = name; } @@ -256,7 +256,7 @@ impl TupleStruct for DynamicTupleStruct { impl Reflect for DynamicTupleStruct { #[inline] - fn type_name(&self) -> &str { + fn type_path(&self) -> &str { &self.name } @@ -402,7 +402,7 @@ pub fn tuple_struct_debug( dyn_tuple_struct: &dyn TupleStruct, f: &mut std::fmt::Formatter<'_>, ) -> std::fmt::Result { - let mut debug = f.debug_tuple(dyn_tuple_struct.type_name()); + let mut debug = f.debug_tuple(dyn_tuple_struct.type_path()); for field in dyn_tuple_struct.iter_fields() { debug.field(&field as &dyn Debug); } diff --git a/crates/bevy_reflect/src/type_info.rs b/crates/bevy_reflect/src/type_info.rs index 6957cb9425ed5..d6db1b18a55e1 100644 --- a/crates/bevy_reflect/src/type_info.rs +++ b/crates/bevy_reflect/src/type_info.rs @@ -1,6 +1,6 @@ use crate::{ - ArrayInfo, EnumInfo, ListInfo, MapInfo, Reflect, StructInfo, TupleInfo, TupleStructInfo, - TypeName, + type_path, ArrayInfo, EnumInfo, ListInfo, MapInfo, Reflect, StructInfo, TupleInfo, + TupleStructInfo, TypePath, }; use std::any::{Any, TypeId}; @@ -24,7 +24,7 @@ use std::any::{Any, TypeId}; /// /// ``` /// # use std::any::Any; -/// # use bevy_reflect::{NamedField, Reflect, ReflectMut, ReflectRef, StructInfo, TypeInfo, TypeName, ValueInfo}; +/// # use bevy_reflect::{NamedField, Reflect, ReflectMut, ReflectRef, StructInfo, TypeInfo, TypePath, ValueInfo}; /// # use bevy_reflect::utility::NonGenericTypeInfoCell; /// use bevy_reflect::Typed; /// @@ -47,12 +47,12 @@ use std::any::{Any, TypeId}; /// } /// } /// -/// # impl TypeName for MyStruct { +/// # impl TypePath for MyStruct { /// # fn name() -> &'static str { "MyStruct" } /// # } /// # /// # impl Reflect for MyStruct { -/// # fn type_name(&self) -> &str { todo!() } +/// # fn type_path(&self) -> &str { todo!() } /// # fn get_type_info(&self) -> &'static TypeInfo { todo!() } /// # fn into_any(self: Box) -> Box { todo!() } /// # fn as_any(&self) -> &dyn Any { todo!() } @@ -86,7 +86,7 @@ pub trait Typed: Reflect { /// Each return a static reference to [`TypeInfo`], but they all have their own use cases. /// For example, if you know the type at compile time, [`Typed::type_info`] is probably /// the simplest. If all you have is a `dyn Reflect`, you'll probably want [`Reflect::get_type_info`]. -/// Lastly, if all you have is a [`TypeId`] or [type name], you will need to go through +/// Lastly, if all you have is a [`TypeId`] or [type path], you will need to go through /// [`TypeRegistry::get_type_info`]. /// /// You may also opt to use [`TypeRegistry::get_type_info`] in place of the other methods simply because @@ -96,7 +96,7 @@ pub trait Typed: Reflect { /// [`Reflect::get_type_info`]: crate::Reflect::get_type_info /// [`TypeRegistry::get_type_info`]: crate::TypeRegistry::get_type_info /// [`TypeId`]: std::any::TypeId -/// [type name]: crate::TypeName +/// [type path]: crate::TypePath #[derive(Debug, Clone)] pub enum TypeInfo { Struct(StructInfo), @@ -131,18 +131,18 @@ impl TypeInfo { /// The [name] of the underlying type. /// - /// [name]: crate::TypeName - pub fn type_name(&self) -> &'static str { + /// [name]: crate::TypePath + pub fn type_path(&self) -> &'static str { match self { - Self::Struct(info) => info.type_name(), - Self::TupleStruct(info) => info.type_name(), - Self::Tuple(info) => info.type_name(), - Self::List(info) => info.type_name(), - Self::Array(info) => info.type_name(), - Self::Map(info) => info.type_name(), - Self::Enum(info) => info.type_name(), - Self::Value(info) => info.type_name(), - Self::Dynamic(info) => info.type_name(), + Self::Struct(info) => info.type_path(), + Self::TupleStruct(info) => info.type_path(), + Self::Tuple(info) => info.type_path(), + Self::List(info) => info.type_path(), + Self::Array(info) => info.type_path(), + Self::Map(info) => info.type_path(), + Self::Enum(info) => info.type_path(), + Self::Value(info) => info.type_path(), + Self::Dynamic(info) => info.type_path(), } } @@ -162,23 +162,23 @@ impl TypeInfo { /// it _as_ a struct. It therefore makes more sense to represent it as a [`ValueInfo`]. #[derive(Debug, Clone)] pub struct ValueInfo { - type_name: &'static str, + type_path: &'static str, type_id: TypeId, } impl ValueInfo { - pub fn new() -> Self { + pub fn new() -> Self { Self { - type_name: T::name(), + type_path: type_path::(), type_id: TypeId::of::(), } } - /// The [type name] of the value. + /// The [type path] of the value. /// - /// [type name]: crate::TypeName - pub fn type_name(&self) -> &'static str { - self.type_name + /// [type path]: crate::TypePath + pub fn type_path(&self) -> &'static str { + self.type_path } /// The [`TypeId`] of the value. @@ -202,23 +202,23 @@ impl ValueInfo { /// [`DynamicList`]: crate::DynamicList #[derive(Debug, Clone)] pub struct DynamicInfo { - type_name: &'static str, + type_path: &'static str, type_id: TypeId, } impl DynamicInfo { - pub fn new() -> Self { + pub fn new() -> Self { Self { - type_name: T::name(), + type_path: type_path::(), type_id: TypeId::of::(), } } - /// The [type name] of the dynamic value. + /// The [type path] of the dynamic value. /// - /// [type name]: crate::TypeName - pub fn type_name(&self) -> &'static str { - self.type_name + /// [type path]: crate::TypePath + pub fn type_path(&self) -> &'static str { + self.type_path } /// The [`TypeId`] of the dynamic value. diff --git a/crates/bevy_reflect/src/type_name.rs b/crates/bevy_reflect/src/type_path.rs similarity index 68% rename from crates/bevy_reflect/src/type_name.rs rename to crates/bevy_reflect/src/type_path.rs index 88b493d66c4b9..90d74b9eef2b6 100644 --- a/crates/bevy_reflect/src/type_name.rs +++ b/crates/bevy_reflect/src/type_path.rs @@ -1,24 +1,24 @@ use crate::utility::GenericTypeNameCell; -/// Provides the name of the type as a string. +/// Provides the path of the type as a string. /// /// This is a stable alternative to [`std::any::type_name`] whose output isn't guarenteed /// and may change between versions of the compiler. /// -/// This trait may be derived via [`#[derive(TypeName)]`][bevy_reflect_derive::TypeName]. +/// This trait may be derived via [`#[derive(TypePath)]`][bevy_reflect_derive::TypePath]. /// /// ## Manual implementation /// -/// If you need to manually implement [`TypeName`], it's recommended to follow +/// If you need to manually implement [`TypePath`], it's recommended to follow /// the example below (unless specifying a custom name). /// /// ```ignore -/// bevy_reflect::TypeName; +/// bevy_reflect::TypePath; /// /// struct MyType; /// -/// impl TypeName for MyType{ -/// fn name() -> &'static str { +/// impl TypePath for MyType{ +/// fn type_path() -> &'static str { /// concat!(module_path!(), "::", "MyType") /// } /// } @@ -28,11 +28,11 @@ use crate::utility::GenericTypeNameCell; /// [`GenericTypeNameCell`][crate::utility::GenericTypeNameCell]. /// /// ```ignore -/// bevy_reflect::{TypeName, utility::GenericTypeNameCell}; +/// bevy_reflect::{TypePath, utility::GenericTypeNameCell}; /// /// struct MyType(T); /// -/// impl TypeName for MyType { +/// impl TypePath for MyType { /// fn name() -> &'static str { /// static CELL: GenericTypeNameCell = GenericTypeNameCell::new(); /// CELL.get_or_insert::(|| { @@ -41,24 +41,31 @@ use crate::utility::GenericTypeNameCell; /// } /// } /// ``` -pub trait TypeName: 'static { - /// Returns the name of the type. +pub trait TypePath: 'static { + /// Returns the path of the type. /// /// This is a stable alternative to [`std::any::type_name`] whose output isn't guarenteed /// and may change between versions of the compiler. - fn name() -> &'static str; + fn type_path() -> &'static str; +} + +/// Returns the [type path] of `T`. +/// +/// [type path]: TypePath +pub fn type_path() -> &'static str { + T::type_path() } macro_rules! impl_type_name_tuple { ( $($t:tt),* ) => { - impl<$($t: TypeName),*> TypeName for ($($t,)*) { + impl<$($t: TypePath),*> TypePath for ($($t,)*) { #[allow(non_snake_case)] - fn name() -> &'static str { + fn type_path() -> &'static str { static CELL: GenericTypeNameCell = GenericTypeNameCell::new(); CELL.get_or_insert::(|| { - $(let $t = <$t as TypeName>::name();)* + $(let $t = <$t as TypePath>::type_path();)* format!( concat!("(", impl_type_name_tuple!(@bracket $($t),*), ")"), $($t,)* @@ -88,23 +95,23 @@ impl_type_name_tuple!(A, B, C, D, E, F, G, H, I, J, K, L); #[cfg(test)] mod tests { - use crate::{self as bevy_reflect, TypeName}; + use crate::{self as bevy_reflect, TypePath}; #[test] fn tuple_name() { - #[derive(TypeName)] - #[type_name("Foo")] + #[derive(TypePath)] + #[type_path("Foo")] struct Foo; - #[derive(TypeName)] - #[type_name("Goo")] + #[derive(TypePath)] + #[type_path("Goo")] struct Goo; - #[derive(TypeName)] - #[type_name("Hoo")] + #[derive(TypePath)] + #[type_path("Hoo")] struct Hoo; - let s = <(Foo, Goo, Hoo) as TypeName>::name(); + let s = <(Foo, Goo, Hoo) as TypePath>::type_path(); assert_eq!(s, "(Foo, Goo, Hoo)"); } } diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index 393241b7da1a8..6d57d9a870235 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -1,4 +1,6 @@ -use crate::{self as bevy_reflect, serde::Serializable, Reflect, TypeInfo, TypeName, Typed}; +use crate::{ + self as bevy_reflect, serde::Serializable, type_path, Reflect, TypeInfo, TypePath, Typed, +}; use bevy_ptr::{Ptr, PtrMut}; use bevy_utils::{HashMap, HashSet}; use downcast_rs::{impl_downcast, Downcast}; @@ -99,7 +101,7 @@ impl TypeRegistry { .insert(short_name, registration.type_id()); } self.full_name_to_id - .insert(registration.type_name().to_string(), registration.type_id()); + .insert(registration.type_path().to_string(), registration.type_id()); self.registrations .insert(registration.type_id(), registration); } @@ -121,16 +123,16 @@ impl TypeRegistry { /// type_registry.register_type_data::, ReflectDeserialize>(); /// ``` pub fn register_type_data< - T: Reflect + TypeName + 'static, - D: TypeData + TypeName + FromType, + T: Reflect + TypePath + 'static, + D: TypeData + TypePath + FromType, >( &mut self, ) { let data = self.get_mut(TypeId::of::()).unwrap_or_else(|| { panic!( "attempted to call `TypeRegistry::register_type_data` for type `{T}` with data `{D}` without registering `{T}` first", - T = T::name(), - D = D::name(), + T = type_path::(), + D = type_path::(), ) }); data.insert(D::from_type()); @@ -319,11 +321,11 @@ impl TypeRegistration { } /// Creates type registration information for `T`. - pub fn of() -> Self { - let type_name = T::name(); + pub fn of() -> Self { + let type_path = type_path::(); Self { data: HashMap::default(), - short_name: bevy_utils::get_short_name(type_name), + short_name: bevy_utils::get_short_name(type_path), type_info: T::type_info(), } } @@ -335,11 +337,11 @@ impl TypeRegistration { &self.short_name } - /// Returns the [name] of the type. + /// Returns the [type path] of the type. /// - /// [name]: crate::TypeName - pub fn type_name(&self) -> &'static str { - self.type_info.type_name() + /// [type path]: crate::TypePath + pub fn type_path(&self) -> &'static str { + self.type_info.type_path() } } @@ -387,17 +389,17 @@ pub trait FromType { /// /// A `ReflectSerialize` for type `T` can be obtained via /// [`FromType::from_type`]. -#[derive(Clone, TypeName)] +#[derive(Clone, TypePath)] pub struct ReflectSerialize { get_serializable: for<'a> fn(value: &'a dyn Reflect) -> Serializable, } -impl FromType for ReflectSerialize { +impl FromType for ReflectSerialize { fn from_type() -> Self { ReflectSerialize { get_serializable: |value| { let value = value.downcast_ref::().unwrap_or_else(|| { - panic!("ReflectSerialize::get_serialize called with type `{}`, even though it was created for `{}`", value.type_name(), T::name()) + panic!("ReflectSerialize::get_serialize called with type `{}`, even though it was created for `{}`", value.type_path(), type_path::()) }); Serializable::Borrowed(value) }, @@ -416,7 +418,7 @@ impl ReflectSerialize { /// /// A `ReflectDeserialize` for type `T` can be obtained via /// [`FromType::from_type`]. -#[derive(Clone, TypeName)] +#[derive(Clone, TypePath)] pub struct ReflectDeserialize { pub func: fn( deserializer: &mut dyn erased_serde::Deserializer, diff --git a/crates/bevy_reflect/src/type_uuid.rs b/crates/bevy_reflect/src/type_uuid.rs index f91c49be81512..d0bd30d686453 100644 --- a/crates/bevy_reflect/src/type_uuid.rs +++ b/crates/bevy_reflect/src/type_uuid.rs @@ -1,7 +1,7 @@ pub use bevy_reflect_derive::TypeUuid; pub use bevy_utils::Uuid; -use crate::TypeName; +use crate::TypePath; /// A trait for types with a statically associated UUID. pub trait TypeUuid { @@ -11,23 +11,23 @@ pub trait TypeUuid { /// A trait for types with an associated UUID. pub trait TypeUuidDynamic { fn type_uuid(&self) -> Uuid; - fn type_name(&self) -> &'static str; + fn type_path(&self) -> &'static str; } impl TypeUuidDynamic for T where - T: TypeUuid + TypeName, + T: TypeUuid + TypePath, { /// Returns the UUID associated with this value's type. fn type_uuid(&self) -> Uuid { Self::TYPE_UUID } - /// Returns the [type name] of this value's type. + /// Returns the [type path] of this value's type. /// - /// [type name]: crate::TypeName - fn type_name(&self) -> &'static str { - Self::name() + /// [type path]: crate::TypePath + fn type_path(&self) -> &'static str { + Self::type_path() } } diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index cfb40de8c9362..a8d60d7a0e31e 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -77,7 +77,7 @@ impl GenericDataCell { /// /// ``` /// # use std::any::Any; -/// # use bevy_reflect::{NamedField, Reflect, ReflectMut, ReflectRef, StructInfo, Typed, TypeInfo, TypeName}; +/// # use bevy_reflect::{NamedField, Reflect, ReflectMut, ReflectRef, StructInfo, Typed, TypeInfo, TypePath}; /// use bevy_reflect::utility::NonGenericTypeInfoCell; /// /// struct Foo { @@ -94,12 +94,12 @@ impl GenericDataCell { /// }) /// } /// } -/// # impl TypeName for Foo { +/// # impl TypePath for Foo { /// # fn name() -> &'static str { "Foo" } /// # } /// # /// # impl Reflect for Foo { -/// # fn type_name(&self) -> &str { todo!() } +/// # fn type_path(&self) -> &str { todo!() } /// # fn get_type_info(&self) -> &'static TypeInfo { todo!() } /// # fn into_any(self: Box) -> Box { todo!() } /// # fn as_any(&self) -> &dyn Any { todo!() } @@ -124,12 +124,12 @@ pub type NonGenericTypeInfoCell = NonGenericDataCell; /// /// ``` /// # use std::any::Any; -/// # use bevy_reflect::{Reflect, ReflectMut, ReflectRef, TupleStructInfo, Typed, TypeInfo, UnnamedField, TypeName}; +/// # use bevy_reflect::{Reflect, ReflectMut, ReflectRef, TupleStructInfo, Typed, TypeInfo, UnnamedField, TypePath}; /// use bevy_reflect::utility::GenericTypeInfoCell; /// /// struct Foo(T); /// -/// impl Typed for Foo { +/// impl Typed for Foo { /// fn type_info() -> &'static TypeInfo { /// static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new(); /// CELL.get_or_insert::(|| { @@ -140,12 +140,12 @@ pub type NonGenericTypeInfoCell = NonGenericDataCell; /// } /// } /// -/// # impl TypeName for Foo { +/// # impl TypePath for Foo { /// # fn name() -> &'static str { todo!() } /// # } /// # /// # impl Reflect for Foo { -/// # fn type_name(&self) -> &str { todo!() } +/// # fn type_path(&self) -> &str { todo!() } /// # fn get_type_info(&self) -> &'static TypeInfo { todo!() } /// # fn into_any(self: Box) -> Box { todo!() } /// # fn as_any(&self) -> &dyn Any { todo!() } @@ -163,17 +163,17 @@ pub type GenericTypeInfoCell = GenericDataCell; /// A container for [`String`] over generic types, allowing instances to be stored statically. /// -/// Used when implementing [`TypeName`][crate::TypeName] for generic types to store the type name. +/// Used when implementing [`TypePath`][crate::TypePath] for generic types to store the type path. /// /// ## Example /// /// ``` -/// # use bevy_reflect::TypeName; +/// # use bevy_reflect::TypePath; /// use bevy_reflect::utility::GenericTypeNameCell; /// /// struct Foo(T); /// -/// impl TypeName for Foo { +/// impl TypePath for Foo { /// fn name() -> &'static str { /// static CELL: GenericTypeNameCell = GenericTypeNameCell::new(); /// CELL.get_or_insert::(|| { diff --git a/crates/bevy_render/src/mesh/mesh/mod.rs b/crates/bevy_render/src/mesh/mesh/mod.rs index ef5ce94945879..7d64c34355fa8 100644 --- a/crates/bevy_render/src/mesh/mesh/mod.rs +++ b/crates/bevy_render/src/mesh/mesh/mod.rs @@ -12,7 +12,7 @@ use bevy_core::cast_slice; use bevy_derive::EnumVariantMeta; use bevy_ecs::system::{lifetimeless::SRes, SystemParamItem}; use bevy_math::*; -use bevy_reflect::{TypeName, TypeUuid}; +use bevy_reflect::{TypePath, TypeUuid}; use bevy_utils::{tracing::error, Hashed}; use std::{collections::BTreeMap, hash::Hash, iter::FusedIterator}; use thiserror::Error; @@ -25,7 +25,7 @@ pub const INDEX_BUFFER_ASSET_INDEX: u64 = 0; pub const VERTEX_ATTRIBUTE_BUFFER_ID: u64 = 10; // TODO: allow values to be unloaded after been submitting to the GPU to conserve memory -#[derive(Debug, TypeUuid, Clone, TypeName)] +#[derive(Debug, TypeUuid, Clone, TypePath)] #[uuid = "8ecbac0f-f545-4473-ad43-e1f4243af51e"] pub struct Mesh { primitive_topology: PrimitiveTopology, diff --git a/crates/bevy_render/src/mesh/mesh/skinning.rs b/crates/bevy_render/src/mesh/mesh/skinning.rs index 31837a51b7d77..44cca8d773454 100644 --- a/crates/bevy_render/src/mesh/mesh/skinning.rs +++ b/crates/bevy_render/src/mesh/mesh/skinning.rs @@ -6,7 +6,7 @@ use bevy_ecs::{ reflect::ReflectMapEntities, }; use bevy_math::Mat4; -use bevy_reflect::{Reflect, TypeName, TypeUuid}; +use bevy_reflect::{Reflect, TypePath, TypeUuid}; use std::ops::Deref; #[derive(Component, Debug, Default, Clone, Reflect)] @@ -26,7 +26,7 @@ impl MapEntities for SkinnedMesh { } } -#[derive(Debug, TypeUuid, TypeName)] +#[derive(Debug, TypeUuid, TypePath)] #[uuid = "b9f155a9-54ec-4026-988f-e0a03e99a76f"] pub struct SkinnedMeshInverseBindposes(Box<[Mat4]>); diff --git a/crates/bevy_render/src/render_resource/shader.rs b/crates/bevy_render/src/render_resource/shader.rs index dd069aa7e5e28..416640a9977ea 100644 --- a/crates/bevy_render/src/render_resource/shader.rs +++ b/crates/bevy_render/src/render_resource/shader.rs @@ -1,5 +1,5 @@ use bevy_asset::{AssetLoader, AssetPath, Handle, LoadContext, LoadedAsset}; -use bevy_reflect::{TypeName, TypeUuid, Uuid}; +use bevy_reflect::{TypePath, TypeUuid, Uuid}; use bevy_utils::{tracing::error, BoxedFuture, HashMap}; use naga::back::wgsl::WriterFlags; use naga::valid::Capabilities; @@ -36,7 +36,7 @@ pub enum ShaderReflectError { } /// A shader, as defined by its [`ShaderSource`] and [`ShaderStage`](naga::ShaderStage) /// This is an "unprocessed" shader. It can contain preprocessor directives. -#[derive(Debug, Clone, TypeUuid, TypeName)] +#[derive(Debug, Clone, TypeUuid, TypePath)] #[uuid = "d95bc916-6c55-4de3-9622-37e7b6969fda"] pub struct Shader { source: Source, diff --git a/crates/bevy_render/src/texture/image.rs b/crates/bevy_render/src/texture/image.rs index 966659d19639e..0f13ccd6892a6 100644 --- a/crates/bevy_render/src/texture/image.rs +++ b/crates/bevy_render/src/texture/image.rs @@ -15,7 +15,7 @@ use bevy_asset::HandleUntyped; use bevy_derive::{Deref, DerefMut}; use bevy_ecs::system::{lifetimeless::SRes, Resource, SystemParamItem}; use bevy_math::Vec2; -use bevy_reflect::{TypeName, TypeUuid}; +use bevy_reflect::{TypePath, TypeUuid}; use std::hash::Hash; use thiserror::Error; use wgpu::{ @@ -101,7 +101,7 @@ impl ImageFormat { } } -#[derive(Debug, Clone, TypeUuid, TypeName)] +#[derive(Debug, Clone, TypeUuid, TypePath)] #[uuid = "6ea26da6-6cf8-4ea2-9986-1d7bf6c17d6f"] pub struct Image { pub data: Vec, diff --git a/crates/bevy_scene/src/dynamic_scene.rs b/crates/bevy_scene/src/dynamic_scene.rs index 6c369c8032584..2afca356202d5 100644 --- a/crates/bevy_scene/src/dynamic_scene.rs +++ b/crates/bevy_scene/src/dynamic_scene.rs @@ -6,7 +6,7 @@ use bevy_ecs::{ reflect::{ReflectComponent, ReflectMapEntities}, world::World, }; -use bevy_reflect::{Reflect, TypeName, TypeRegistryArc, TypeUuid}; +use bevy_reflect::{Reflect, TypePath, TypeRegistryArc, TypeUuid}; use serde::Serialize; /// A collection of serializable dynamic entities, each with its own run-time defined set of components. @@ -16,7 +16,7 @@ use serde::Serialize; /// * adding the [`Handle`](bevy_asset::Handle) to an entity (the scene will only be /// visible if the entity already has [`Transform`](bevy_transform::components::Transform) and /// [`GlobalTransform`](bevy_transform::components::GlobalTransform) components) -#[derive(Default, TypeUuid, TypeName)] +#[derive(Default, TypeUuid, TypePath)] #[uuid = "749479b1-fb8c-4ff8-a775-623aa76014f5"] pub struct DynamicScene { pub entities: Vec, @@ -99,14 +99,14 @@ impl DynamicScene { // Apply/ add each component to the given entity. for component in &scene_entity.components { let registration = type_registry - .get_with_name(component.type_name()) + .get_with_name(component.type_path()) .ok_or_else(|| SceneSpawnError::UnregisteredType { - type_name: component.type_name().to_string(), + type_name: component.type_path().to_string(), })?; let reflect_component = registration.data::().ok_or_else(|| { SceneSpawnError::UnregisteredComponent { - type_name: component.type_name().to_string(), + type_name: component.type_path().to_string(), } })?; diff --git a/crates/bevy_scene/src/scene.rs b/crates/bevy_scene/src/scene.rs index 2c4294938813b..1fb407f5e4061 100644 --- a/crates/bevy_scene/src/scene.rs +++ b/crates/bevy_scene/src/scene.rs @@ -4,7 +4,7 @@ use bevy_ecs::{ reflect::{ReflectComponent, ReflectMapEntities}, world::World, }; -use bevy_reflect::{TypeName, TypeUuid}; +use bevy_reflect::{TypePath, TypeUuid}; use crate::{InstanceInfo, SceneSpawnError}; @@ -14,7 +14,7 @@ use crate::{InstanceInfo, SceneSpawnError}; /// * adding the [`Handle`](bevy_asset::Handle) to an entity (the scene will only be /// visible if the entity already has [`Transform`](bevy_transform::components::Transform) and /// [`GlobalTransform`](bevy_transform::components::GlobalTransform) components) -#[derive(Debug, TypeUuid, TypeName)] +#[derive(Debug, TypeUuid, TypePath)] #[uuid = "c156503c-edd9-4ec7-8d33-dab392df03cd"] pub struct Scene { pub world: World, diff --git a/crates/bevy_sprite/src/mesh2d/color_material.rs b/crates/bevy_sprite/src/mesh2d/color_material.rs index a66aab723e72f..3f89ab3675c8d 100644 --- a/crates/bevy_sprite/src/mesh2d/color_material.rs +++ b/crates/bevy_sprite/src/mesh2d/color_material.rs @@ -1,7 +1,7 @@ use bevy_app::{App, Plugin}; use bevy_asset::{load_internal_asset, Assets, Handle, HandleUntyped}; use bevy_math::Vec4; -use bevy_reflect::{TypeName, TypeUuid}; +use bevy_reflect::{TypePath, TypeUuid}; use bevy_render::{ color::Color, prelude::Shader, render_asset::RenderAssets, render_resource::*, texture::Image, }; @@ -38,7 +38,7 @@ impl Plugin for ColorMaterialPlugin { } /// A [2d material](Material2d) that renders [2d meshes](crate::Mesh2dHandle) with a texture tinted by a uniform color -#[derive(AsBindGroup, Debug, Clone, TypeUuid, TypeName)] +#[derive(AsBindGroup, Debug, Clone, TypeUuid, TypePath)] #[uuid = "e228a544-e3ca-4e1e-bb9d-4d8bc1ad8c19"] #[uniform(0, ColorMaterialUniform)] pub struct ColorMaterial { diff --git a/crates/bevy_sprite/src/mesh2d/material.rs b/crates/bevy_sprite/src/mesh2d/material.rs index a8e76cd15e8b7..990a7101c0b9f 100644 --- a/crates/bevy_sprite/src/mesh2d/material.rs +++ b/crates/bevy_sprite/src/mesh2d/material.rs @@ -14,7 +14,7 @@ use bevy_ecs::{ world::FromWorld, }; use bevy_log::error; -use bevy_reflect::{TypeName, TypeUuid}; +use bevy_reflect::{TypePath, TypeUuid}; use bevy_render::{ extract_component::ExtractComponentPlugin, mesh::{Mesh, MeshVertexBufferLayout}, @@ -60,11 +60,11 @@ use crate::{ /// ``` /// # use bevy_sprite::{Material2d, MaterialMesh2dBundle}; /// # use bevy_ecs::prelude::*; -/// # use bevy_reflect::{TypeUuid, TypeName}; +/// # use bevy_reflect::{TypeUuid, TypePath}; /// # use bevy_render::{render_resource::{AsBindGroup, ShaderRef}, texture::Image, color::Color}; /// # use bevy_asset::{Handle, AssetServer, Assets}; /// -/// #[derive(AsBindGroup, TypeUuid, TypeName, Debug, Clone)] +/// #[derive(AsBindGroup, TypeUuid, TypePath, Debug, Clone)] /// #[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"] /// pub struct CustomMaterial { /// // Uniform bindings must implement `ShaderType`, which will be used to convert the value to @@ -112,7 +112,7 @@ use crate::{ /// var color_sampler: sampler; /// ``` pub trait Material2d: - AsBindGroup + Send + Sync + Clone + TypeUuid + TypeName + Sized + 'static + AsBindGroup + Send + Sync + Clone + TypeUuid + TypePath + Sized + 'static { /// Returns this material's vertex shader. If [`ShaderRef::Default`] is returned, the default mesh vertex shader /// will be used. diff --git a/crates/bevy_sprite/src/texture_atlas.rs b/crates/bevy_sprite/src/texture_atlas.rs index 46bf16892e649..f9b8908dcf632 100644 --- a/crates/bevy_sprite/src/texture_atlas.rs +++ b/crates/bevy_sprite/src/texture_atlas.rs @@ -2,14 +2,14 @@ use crate::Anchor; use bevy_asset::Handle; use bevy_ecs::component::Component; use bevy_math::{Rect, Vec2}; -use bevy_reflect::{Reflect, TypeName, TypeUuid}; +use bevy_reflect::{Reflect, TypePath, TypeUuid}; use bevy_render::{color::Color, texture::Image}; use bevy_utils::HashMap; /// An atlas containing multiple textures (like a spritesheet or a tilemap). /// [Example usage animating sprite.](https://github.com/bevyengine/bevy/blob/latest/examples/2d/sprite_sheet.rs) /// [Example usage loading sprite sheet.](https://github.com/bevyengine/bevy/blob/latest/examples/2d/texture_atlas.rs) -#[derive(Debug, Clone, TypeUuid, TypeName)] +#[derive(Debug, Clone, TypeUuid, TypePath)] #[uuid = "7233c597-ccfa-411f-bd59-9af349432ada"] pub struct TextureAtlas { /// The handle to the texture in which the sprites are stored diff --git a/crates/bevy_text/src/font.rs b/crates/bevy_text/src/font.rs index 90d659f7d0ba3..72d65b6e2a4e2 100644 --- a/crates/bevy_text/src/font.rs +++ b/crates/bevy_text/src/font.rs @@ -1,11 +1,11 @@ use ab_glyph::{FontArc, FontVec, InvalidFont, OutlinedGlyph}; -use bevy_reflect::{TypeName, TypeUuid}; +use bevy_reflect::{TypePath, TypeUuid}; use bevy_render::{ render_resource::{Extent3d, TextureDimension, TextureFormat}, texture::Image, }; -#[derive(Debug, TypeUuid, TypeName)] +#[derive(Debug, TypeUuid, TypePath)] #[uuid = "97059ac6-c9ba-4da9-95b6-bed82c3ce198"] pub struct Font { pub font: FontArc, diff --git a/crates/bevy_text/src/font_atlas_set.rs b/crates/bevy_text/src/font_atlas_set.rs index 733484eb31782..d6641ca99169c 100644 --- a/crates/bevy_text/src/font_atlas_set.rs +++ b/crates/bevy_text/src/font_atlas_set.rs @@ -2,7 +2,7 @@ use crate::{error::TextError, Font, FontAtlas}; use ab_glyph::{GlyphId, OutlinedGlyph, Point}; use bevy_asset::{Assets, Handle}; use bevy_math::Vec2; -use bevy_reflect::TypeName; +use bevy_reflect::TypePath; use bevy_reflect::TypeUuid; use bevy_render::texture::Image; use bevy_sprite::TextureAtlas; @@ -11,7 +11,7 @@ use bevy_utils::HashMap; type FontSizeKey = FloatOrd; -#[derive(TypeUuid, TypeName)] +#[derive(TypeUuid, TypePath)] #[uuid = "73ba778b-b6b5-4f45-982d-d21b6b86ace2"] pub struct FontAtlasSet { font_atlases: HashMap>, diff --git a/crates/bevy_utils/src/short_names.rs b/crates/bevy_utils/src/short_names.rs index 1c30bf61f9d0f..950edc8033b08 100644 --- a/crates/bevy_utils/src/short_names.rs +++ b/crates/bevy_utils/src/short_names.rs @@ -1,4 +1,4 @@ -/// Shortens a type name to remove all module paths. +/// Shortens a type path to remove all module paths. /// /// The short name of a type is its full name as returned by /// [`std::any::type_name`], but with the prefix of all paths removed. For diff --git a/examples/3d/lines.rs b/examples/3d/lines.rs index 6e75d9d2f32ee..0a852d5884831 100644 --- a/examples/3d/lines.rs +++ b/examples/3d/lines.rs @@ -62,7 +62,7 @@ fn setup( }); } -#[derive(Default, AsBindGroup, TypeUuid, TypeName, Debug, Clone)] +#[derive(Default, AsBindGroup, TypeUuid, TypePath, Debug, Clone)] #[uuid = "050ce6ac-080a-4d8c-b6b5-b5bab7560d8f"] struct LineMaterial { #[uniform(0)] diff --git a/examples/3d/skybox.rs b/examples/3d/skybox.rs index 3f68b0d325c5c..01c5f397380dc 100644 --- a/examples/3d/skybox.rs +++ b/examples/3d/skybox.rs @@ -195,7 +195,7 @@ fn animate_light_direction( } } -#[derive(Debug, Clone, TypeUuid, TypeName)] +#[derive(Debug, Clone, TypeUuid, TypePath)] #[uuid = "9509a0f8-3c05-48ee-a13e-a93226c7f488"] struct CubemapMaterial { base_color_texture: Option>, diff --git a/examples/asset/custom_asset.rs b/examples/asset/custom_asset.rs index 19f9b91d5f536..4f97f1a24547a 100644 --- a/examples/asset/custom_asset.rs +++ b/examples/asset/custom_asset.rs @@ -8,7 +8,7 @@ use bevy::{ }; use serde::Deserialize; -#[derive(Debug, Deserialize, TypeUuid, TypeName)] +#[derive(Debug, Deserialize, TypeUuid, TypePath)] #[uuid = "39cadc56-aa9c-4543-8640-a018b74b5052"] pub struct CustomAsset { pub value: i32, diff --git a/examples/reflection/generic_reflection.rs b/examples/reflection/generic_reflection.rs index a6425e93e14be..47f3473b83ca8 100644 --- a/examples/reflection/generic_reflection.rs +++ b/examples/reflection/generic_reflection.rs @@ -12,10 +12,10 @@ fn main() { .run(); } -/// Because `#[derive(Reflect)]` also derives `TypeName` for `MyType`, -/// the generic parameter must also implement `TypeName`. +/// Because `#[derive(Reflect)]` also derives `TypePath` for `MyType`, +/// the generic parameter must also implement `TypePath`. #[derive(Reflect)] -struct MyType { +struct MyType { value: T, } diff --git a/examples/shader/array_texture.rs b/examples/shader/array_texture.rs index 02d7207a7dd9d..92ffa43ac666f 100644 --- a/examples/shader/array_texture.rs +++ b/examples/shader/array_texture.rs @@ -89,7 +89,7 @@ fn create_array_texture( } } -#[derive(AsBindGroup, Debug, Clone, TypeUuid, TypeName)] +#[derive(AsBindGroup, Debug, Clone, TypeUuid, TypePath)] #[uuid = "9c5a0ddf-1eaf-41b4-9832-ed736fd26af3"] struct ArrayTextureMaterial { #[texture(0, dimension = "2d_array")] diff --git a/examples/shader/custom_vertex_attribute.rs b/examples/shader/custom_vertex_attribute.rs index 2db03c3b46203..9312f1170b44a 100644 --- a/examples/shader/custom_vertex_attribute.rs +++ b/examples/shader/custom_vertex_attribute.rs @@ -57,7 +57,7 @@ fn setup( } // This is the struct that will be passed to your shader -#[derive(AsBindGroup, Debug, Clone, TypeUuid, TypeName)] +#[derive(AsBindGroup, Debug, Clone, TypeUuid, TypePath)] #[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"] pub struct CustomMaterial { #[uniform(0)] diff --git a/examples/shader/post_processing.rs b/examples/shader/post_processing.rs index b9ff8a225c8fe..063c8fb7797f3 100644 --- a/examples/shader/post_processing.rs +++ b/examples/shader/post_processing.rs @@ -165,7 +165,7 @@ fn main_camera_cube_rotator_system( // Region below declares of the custom material handling post processing effect /// Our custom post processing material -#[derive(AsBindGroup, TypeUuid, TypeName, Clone)] +#[derive(AsBindGroup, TypeUuid, TypePath, Clone)] #[uuid = "bc2f08eb-a0fb-43f1-a908-54871ea597d5"] struct PostProcessingMaterial { /// In this example, this image will be the result of the main camera. diff --git a/examples/shader/shader_defs.rs b/examples/shader/shader_defs.rs index 40fe4d0ae34af..6aecc945f273f 100644 --- a/examples/shader/shader_defs.rs +++ b/examples/shader/shader_defs.rs @@ -75,7 +75,7 @@ impl Material for CustomMaterial { } // This is the struct that will be passed to your shader -#[derive(AsBindGroup, TypeUuid, TypeName, Debug, Clone)] +#[derive(AsBindGroup, TypeUuid, TypePath, Debug, Clone)] #[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"] #[bind_group_data(CustomMaterialKey)] pub struct CustomMaterial { diff --git a/examples/shader/shader_material.rs b/examples/shader/shader_material.rs index 7ede26b29ae7a..7af3d7e2c73a2 100644 --- a/examples/shader/shader_material.rs +++ b/examples/shader/shader_material.rs @@ -53,7 +53,7 @@ impl Material for CustomMaterial { } // This is the struct that will be passed to your shader -#[derive(AsBindGroup, TypeUuid, TypeName, Debug, Clone)] +#[derive(AsBindGroup, TypeUuid, TypePath, Debug, Clone)] #[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"] pub struct CustomMaterial { #[uniform(0)] diff --git a/examples/shader/shader_material_glsl.rs b/examples/shader/shader_material_glsl.rs index 4ab0868e9aa76..f3bee794c66b5 100644 --- a/examples/shader/shader_material_glsl.rs +++ b/examples/shader/shader_material_glsl.rs @@ -47,7 +47,7 @@ fn setup( } // This is the struct that will be passed to your shader -#[derive(AsBindGroup, Clone, TypeUuid, TypeName)] +#[derive(AsBindGroup, Clone, TypeUuid, TypePath)] #[uuid = "4ee9c363-1124-4113-890e-199d81b00281"] pub struct CustomMaterial { #[uniform(0)] diff --git a/examples/shader/shader_material_screenspace_texture.rs b/examples/shader/shader_material_screenspace_texture.rs index 0d3017f5d9190..6151384a4895d 100644 --- a/examples/shader/shader_material_screenspace_texture.rs +++ b/examples/shader/shader_material_screenspace_texture.rs @@ -65,7 +65,7 @@ fn rotate_camera(mut camera: Query<&mut Transform, With>, time: Res< cam_transform.look_at(Vec3::ZERO, Vec3::Y); } -#[derive(AsBindGroup, Debug, Clone, TypeUuid, TypeName)] +#[derive(AsBindGroup, Debug, Clone, TypeUuid, TypePath)] #[uuid = "b62bb455-a72c-4b56-87bb-81e0554e234f"] pub struct CustomMaterial { #[texture(0)] From 86e12d2b37d45d8e2abd27caf14491b85bb57dae Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Mon, 5 Sep 2022 13:45:27 +0200 Subject: [PATCH 73/87] rename `GenericTypeNameCell` into `GenericTypePathCell` --- .../bevy_reflect_derive/src/impls/type_path.rs | 2 +- crates/bevy_reflect/src/impls/std.rs | 4 ++-- crates/bevy_reflect/src/type_path.rs | 10 +++++----- crates/bevy_reflect/src/utility.rs | 6 +++--- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs index 31793e7ddfcba..6899e83325316 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs @@ -43,7 +43,7 @@ pub(crate) fn impl_type_path(reflect_meta: &ReflectMeta) -> proc_macro2::TokenSt }; quote! { - static CELL: #bevy_reflect_path::utility::GenericTypeNameCell = #bevy_reflect_path::utility::GenericTypeNameCell::new(); + static CELL: #bevy_reflect_path::utility::GenericTypePathCell = #bevy_reflect_path::utility::GenericTypePathCell::new(); CELL.get_or_insert::(|| { format!(concat!("{}<", #brackets, ">"), BASE_NAME, #values) }) diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index e8a8ab14ef540..1a00b04f1bc66 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -7,7 +7,7 @@ use crate::{ VariantInfo, VariantType, }; -use crate::utility::{GenericTypeInfoCell, GenericTypeNameCell, NonGenericTypeInfoCell}; +use crate::utility::{GenericTypeInfoCell, GenericTypePathCell, NonGenericTypeInfoCell}; use bevy_reflect_derive::{impl_from_reflect_value, impl_reflect_value, impl_type_path}; use bevy_utils::{Duration, HashMap, HashSet, Instant}; use std::{ @@ -111,7 +111,7 @@ impl_type_path!(Option); // so array is manually implemented. impl TypePath for [T; N] { fn type_path() -> &'static str { - static CELL: GenericTypeNameCell = GenericTypeNameCell::new(); + static CELL: GenericTypePathCell = GenericTypePathCell::new(); CELL.get_or_insert::(|| format!("[{}; {N}]", T::type_path())) } } diff --git a/crates/bevy_reflect/src/type_path.rs b/crates/bevy_reflect/src/type_path.rs index 90d74b9eef2b6..bab8a355f487c 100644 --- a/crates/bevy_reflect/src/type_path.rs +++ b/crates/bevy_reflect/src/type_path.rs @@ -1,4 +1,4 @@ -use crate::utility::GenericTypeNameCell; +use crate::utility::GenericTypePathCell; /// Provides the path of the type as a string. /// @@ -25,16 +25,16 @@ use crate::utility::GenericTypeNameCell; /// ``` /// /// If your type is generic you must use -/// [`GenericTypeNameCell`][crate::utility::GenericTypeNameCell]. +/// [`GenericTypePathCell`][crate::utility::GenericTypePathCell]. /// /// ```ignore -/// bevy_reflect::{TypePath, utility::GenericTypeNameCell}; +/// bevy_reflect::{TypePath, utility::GenericTypePathCell}; /// /// struct MyType(T); /// /// impl TypePath for MyType { /// fn name() -> &'static str { -/// static CELL: GenericTypeNameCell = GenericTypeNameCell::new(); +/// static CELL: GenericTypePathCell = GenericTypePathCell::new(); /// CELL.get_or_insert::(|| { /// format!(concat!(module_path!(), "::MyType<{}>"), T::name()) /// }) @@ -63,7 +63,7 @@ macro_rules! impl_type_name_tuple { impl<$($t: TypePath),*> TypePath for ($($t,)*) { #[allow(non_snake_case)] fn type_path() -> &'static str { - static CELL: GenericTypeNameCell = GenericTypeNameCell::new(); + static CELL: GenericTypePathCell = GenericTypePathCell::new(); CELL.get_or_insert::(|| { $(let $t = <$t as TypePath>::type_path();)* format!( diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index a8d60d7a0e31e..1b0d059ae87b7 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -169,17 +169,17 @@ pub type GenericTypeInfoCell = GenericDataCell; /// /// ``` /// # use bevy_reflect::TypePath; -/// use bevy_reflect::utility::GenericTypeNameCell; +/// use bevy_reflect::utility::GenericTypePathCell; /// /// struct Foo(T); /// /// impl TypePath for Foo { /// fn name() -> &'static str { -/// static CELL: GenericTypeNameCell = GenericTypeNameCell::new(); +/// static CELL: GenericTypePathCell = GenericTypePathCell::new(); /// CELL.get_or_insert::(|| { /// format!(concat!(module_path!(), "::Foo<{}>"), T::name()) /// }) /// } /// } /// ``` -pub type GenericTypeNameCell = GenericDataCell; +pub type GenericTypePathCell = GenericDataCell; From cb84e1e5052543ec258ad8870ffe40e008f3738e Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Mon, 5 Sep 2022 15:14:44 +0200 Subject: [PATCH 74/87] add other methods on `TypePath` --- .../bevy_reflect_derive/src/derive_data.rs | 132 +++++++++++++++--- .../src/impls/type_path.rs | 56 ++++++-- .../bevy_reflect_derive/src/lib.rs | 16 ++- .../bevy_reflect_derive/src/reflect_value.rs | 25 ++-- crates/bevy_reflect/src/impls/glam.rs | 64 ++++----- crates/bevy_reflect/src/impls/std.rs | 80 ++++++++--- crates/bevy_reflect/src/lib.rs | 6 +- crates/bevy_reflect/src/reflect.rs | 21 +++ crates/bevy_reflect/src/type_path.rs | 48 ++++++- crates/bevy_reflect/src/utility.rs | 14 ++ 10 files changed, 347 insertions(+), 115 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs index 5092ee753c9dd..71de0f80e353a 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs @@ -1,7 +1,6 @@ use crate::container_attributes::ReflectTraits; use crate::field_attributes::{parse_field_attrs, ReflectFieldAttr}; use quote::quote; -use syn::token::Comma; use crate::{ utility, REFLECT_ATTRIBUTE_NAME, REFLECT_VALUE_ATTRIBUTE_NAME, TYPE_PATH_ATTRIBUTE_NAME, @@ -9,8 +8,8 @@ use crate::{ use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{ - Data, DeriveInput, Field, Fields, Generics, Ident, Lit, Meta, NestedMeta, Path, Token, Type, - Variant, + Data, DeriveInput, Field, Fields, Generics, Ident, Lit, Meta, MetaList, NestedMeta, Path, + Token, Type, Variant, }; pub(crate) enum ReflectDerive<'a> { @@ -41,8 +40,8 @@ pub(crate) struct ReflectMeta<'a> { type_name: &'a Ident, /// The generics defined on this type. generics: &'a Generics, - /// Override the default type path for `TypePath`. - reflected_type_path: Option, + /// User defined options for the impl of `TypePath`. + type_path_options: TypePathOptions, /// A cached instance of the path to the `bevy_reflect` crate. bevy_reflect_path: Path, } @@ -118,7 +117,7 @@ impl<'a> ReflectDerive<'a> { // Should indicate whether `#[reflect_value]` was used let mut force_reflect_value = false; - let mut reflected_type_path = None; + let mut type_path_options = None; for attribute in input.attrs.iter().filter_map(|attr| attr.parse_meta().ok()) { let meta_list = if let Meta::List(meta_list) = attribute { @@ -136,14 +135,18 @@ impl<'a> ReflectDerive<'a> { traits = ReflectTraits::from_nested_metas(&meta_list.nested); } Some(ident) if ident == TYPE_PATH_ATTRIBUTE_NAME => { - let type_path = get_type_path_attribute(&meta_list.nested).ok_or_else(|| syn::Error::new(meta_list.span(), format!("the attribute `{TYPE_PATH_ATTRIBUTE_NAME}` requires a single string literal. For example: `#[{TYPE_PATH_ATTRIBUTE_NAME}(\"my_lib::foo\")]`")) )?; - reflected_type_path = Some(type_path); + type_path_options = Some(TypePathOptions::parse_meta_list(meta_list)?); } _ => {} } } - let meta = ReflectMeta::new(&input.ident, &input.generics, traits, reflected_type_path); + let meta = ReflectMeta::new( + &input.ident, + &input.generics, + traits, + type_path_options.unwrap_or_default(), + ); if force_reflect_value { return Ok(Self::Value(meta)); @@ -231,13 +234,13 @@ impl<'a> ReflectMeta<'a> { type_name: &'a Ident, generics: &'a Generics, traits: ReflectTraits, - reflected_type_path: Option, + type_path_options: TypePathOptions, ) -> Self { Self { traits, type_name, generics, - reflected_type_path, + type_path_options, bevy_reflect_path: utility::get_bevy_reflect_path(), } } @@ -257,9 +260,9 @@ impl<'a> ReflectMeta<'a> { self.generics } - /// Override the default type path for `TypePath`. - pub fn reflected_type_path(&self) -> Option<&str> { - self.reflected_type_path.as_deref() + /// User defined options for the impl of `TypePath`. + pub fn type_path_options(&self) -> &TypePathOptions { + &self.type_path_options } /// The cached `bevy_reflect` path. @@ -338,15 +341,98 @@ impl<'a> ReflectEnum<'a> { } } -/// Extracts the type path attribute or returns [`None`]. -fn get_type_path_attribute(nested_metas: &Punctuated) -> Option { - // Having more than 1 element in nested_metas is invalid. - if nested_metas.len() == 1 { - match nested_metas.first() { - Some(NestedMeta::Lit(Lit::Str(s))) => Some(s.value()), - _ => None, +/// User defined options for the impl of `TypePath`. +#[derive(Default)] +pub(crate) struct TypePathOptions { + /// If set, the custom module path. + pub module_path: Option, + /// If set, the custom type ident. + pub type_ident: Option, +} + +impl TypePathOptions { + fn parse_meta_list(meta_list: MetaList) -> Result { + fn parse_module_path(lit: Lit) -> Result { + fn is_valid_module_path(_module_path: &str) -> bool { + // FIXME: what conditions here ? + true + } + + match lit { + Lit::Str(lit_str) => { + let path = lit_str.value(); + if is_valid_module_path(&path) { + Ok(path) + } else { + Err(syn::Error::new( + lit_str.span(), + format!("Expected a valid module path"), + )) + } + } + other => Err(syn::Error::new( + other.span(), + format!("Expected a str literal"), + )), + } } - } else { - None + + fn parse_tpye_ident(lit: Lit) -> Result { + fn is_valid_type_ident(_type_ident: &str) -> bool { + // FIXME: what conditions here ? + true + } + + match lit { + Lit::Str(lit_str) => { + let type_ident = lit_str.value(); + if is_valid_type_ident(&type_ident) { + Ok(type_ident) + } else { + Err(syn::Error::new( + lit_str.span(), + format!("Expected a valid type ident"), + )) + } + } + other => Err(syn::Error::new( + other.span(), + format!("Expected a str literal"), + )), + } + } + + let mut module_path = None; + let mut type_ident = None; + + for attribute in meta_list.nested { + match attribute { + NestedMeta::Meta(Meta::NameValue(name_value)) => { + if let Some(ident) = name_value.path.get_ident() { + if ident == "path" { + module_path = Some(parse_module_path(name_value.lit)?); + } else if ident == "ident" { + type_ident = Some(parse_tpye_ident(name_value.lit)?); + } + } else { + return Err(syn::Error::new( + name_value.path.span(), + format!("Unexpected entry for the `{TYPE_PATH_ATTRIBUTE_NAME}` attribute. Usage: #[{TYPE_PATH_ATTRIBUTE_NAME}(path = \"my_crate::my_module\", ident = \"MyType\")]"), + )); + } + } + other => { + return Err(syn::Error::new( + other.span(), + format!("Unexpected entry for the `{TYPE_PATH_ATTRIBUTE_NAME}` attribute. Usage: #[{TYPE_PATH_ATTRIBUTE_NAME}(path = \"my_crate::my_module\", ident = \"MyType\")]"), + )); + } + } + } + + Ok(Self { + module_path, + type_ident, + }) } } diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs index 6899e83325316..17206e23464b9 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs @@ -6,18 +6,26 @@ pub(crate) fn impl_type_path(reflect_meta: &ReflectMeta) -> proc_macro2::TokenSt let generics = reflect_meta.generics(); let type_name = reflect_meta.type_name(); let bevy_reflect_path = reflect_meta.bevy_reflect_path(); + let type_path_options = reflect_meta.type_path_options(); let is_generic = !generics.params.is_empty(); - let base_name = reflect_meta - .reflected_type_path() + let module_path = type_path_options + .module_path + .as_ref() + .map(|x| quote!(#x)) + .unwrap_or_else(|| quote!(module_path!())); + + let type_ident = type_path_options + .type_ident + .as_ref() .map(|x| quote!(#x)) .unwrap_or_else(|| { let type_name = type_name.to_string(); - quote!(concat!(module_path!(), "::", #type_name)) + quote!(#type_name) }); - let get_type_name = if is_generic { + let get_type_path = if is_generic { let values = { let getters = generics.params.iter().map(|p| match p { syn::GenericParam::Type(p) => { @@ -25,8 +33,8 @@ pub(crate) fn impl_type_path(reflect_meta: &ReflectMeta) -> proc_macro2::TokenSt quote!(<#ty as #bevy_reflect_path::TypePath>::type_path()) } syn::GenericParam::Lifetime(p) => { - let name = &p.lifetime.ident.to_string(); - quote!(concat!("'", #name)) + let name = format!("'{}", p.lifetime.ident.to_string()); + quote!(#name) } syn::GenericParam::Const(p) => { let name = &p.ident; @@ -45,12 +53,12 @@ pub(crate) fn impl_type_path(reflect_meta: &ReflectMeta) -> proc_macro2::TokenSt quote! { static CELL: #bevy_reflect_path::utility::GenericTypePathCell = #bevy_reflect_path::utility::GenericTypePathCell::new(); CELL.get_or_insert::(|| { - format!(concat!("{}<", #brackets, ">"), BASE_NAME, #values) + format!(concat!(#module_path, "::", #type_ident, "<", #brackets, ">"), #values) }) } } else { quote! { - BASE_NAME + concat!(#module_path, "::", #type_ident) } }; @@ -58,9 +66,37 @@ pub(crate) fn impl_type_path(reflect_meta: &ReflectMeta) -> proc_macro2::TokenSt quote! { impl #impl_generics #bevy_reflect_path::TypePath for #type_name #ty_generics #where_clause { + #[inline] fn type_path() -> &'static str { - const BASE_NAME: &'static str = #base_name; - #get_type_name + #get_type_path + } + + #[inline] + fn short_type_name_base() -> &'static str { + const PATH_LEN: usize = #module_path.len(); + const IDENT_LEN: usize = #type_ident.len(); + const IDENT_POS: usize = PATH_LEN + 2; + const GENERIC_POS: usize = IDENT_POS + IDENT_LEN; + &::type_path()[IDENT_POS..GENERIC_POS] + } + + #[inline] + fn short_type_name() -> &'static str { + const PATH_LEN: usize = #module_path.len(); + const IDENT_POS: usize = PATH_LEN + 2; + &::type_path()[IDENT_POS..] + } + + #[inline] + fn module_path() -> &'static str { + const PATH_LEN: usize = #module_path.len(); + &::type_path()[..PATH_LEN] + } + + #[inline] + fn crate_name() -> &'static str { + const CRATE_NAME_LEN: usize = #bevy_reflect_path::utility::crate_name_len(#module_path); + &::type_path()[..CRATE_NAME_LEN] } } } diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index 44aab38b55edd..3e17ef28fedbf 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -28,6 +28,7 @@ mod type_uuid; mod utility; use crate::derive_data::{ReflectDerive, ReflectMeta, ReflectStruct}; +use derive_data::TypePathOptions; use proc_macro::TokenStream; use quote::quote; use reflect_value::{NamedReflectValueDef, ReflectValueDef}; @@ -90,7 +91,7 @@ pub fn derive_reflect(input: TokenStream) -> TokenStream { /// } /// /// #[derive(TypePath)] -/// #[type_path("my_lib::AB")] +/// #[type_path(path = "my_lib")] /// pub struct AB(T); /// } /// @@ -166,13 +167,11 @@ pub fn reflect_trait(args: TokenStream, input: TokenStream) -> TokenStream { pub fn impl_reflect_value(input: TokenStream) -> TokenStream { let def = parse_macro_input!(input as NamedReflectValueDef); - let reflected_type_path = def.get_reflected_type_path(); - impls::impl_value(&ReflectMeta::new( &def.def.type_name, &def.def.generics, def.def.traits.unwrap_or_default(), - Some(reflected_type_path), + def.type_path_options, )) } @@ -249,7 +248,7 @@ pub fn impl_from_reflect_value(input: TokenStream) -> TokenStream { &def.type_name, &def.generics, def.traits.unwrap_or_default(), - None, + TypePathOptions::default(), )) } @@ -257,7 +256,7 @@ pub fn impl_from_reflect_value(input: TokenStream) -> TokenStream { /// the definitions of cannot be altered. /// /// But unlike `#[derive(TypePath)]` that prefix the type path with the module path -/// using the macro [`module_path`], by default `impl_type_path` only uses the ident of the type +/// using the macro [`module_path`], `impl_type_path` only uses the ident of the type /// as the type path. /// /// # Example @@ -272,7 +271,10 @@ pub fn impl_type_path(input: TokenStream) -> TokenStream { &def.type_name, &def.generics, Default::default(), - Some(def.type_name.to_string()), + TypePathOptions { + module_path: Some("".to_string()), + type_ident: None, + }, ); TokenStream::from(impls::impl_type_path(&meta)) } diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs b/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs index 26d68e8d7a68e..43a8494f51e34 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs @@ -1,4 +1,5 @@ use crate::container_attributes::ReflectTraits; +use crate::derive_data::TypePathOptions; use proc_macro2::Ident; use syn::parse::{Parse, ParseStream}; use syn::token::{Paren, Where}; @@ -58,38 +59,30 @@ impl Parse for ReflectValueDef { /// # Example /// /// ```ignore -/// impl_reflect_value!(@"my_lib::MyType" Foo where T1: Bar (TraitA, TraitB)); +/// impl_reflect_value!(@"my_lib::my_module" Foo where T1: Bar (TraitA, TraitB)); /// ``` pub(crate) struct NamedReflectValueDef { - pub reflected_type_path: Option, + pub type_path_options: TypePathOptions, pub def: ReflectValueDef, } -impl NamedReflectValueDef { - /// Returns the string to use as the reflected type path. - /// - /// Use `reflected_type_path` if avaible otherwise use the `type_name` ident. - pub fn get_reflected_type_path(&self) -> String { - self.reflected_type_path - .clone() - .unwrap_or_else(|| self.def.type_name.to_string()) - } -} - impl Parse for NamedReflectValueDef { fn parse(input: ParseStream) -> syn::Result { let lookahead = input.lookahead1(); - let mut reflected_type_path = None; + let mut module_path = None; if lookahead.peek(Token![@]) { let _at: Token![@] = input.parse()?; let name: LitStr = input.parse()?; - reflected_type_path = Some(name.value()); + module_path = Some(name.value()); } let def = input.parse()?; Ok(Self { - reflected_type_path, + type_path_options: TypePathOptions { + module_path, + type_ident: None, + }, def, }) } diff --git a/crates/bevy_reflect/src/impls/glam.rs b/crates/bevy_reflect/src/impls/glam.rs index 03c93becbcd45..819a38cc1eb2b 100644 --- a/crates/bevy_reflect/src/impls/glam.rs +++ b/crates/bevy_reflect/src/impls/glam.rs @@ -7,7 +7,7 @@ use glam::*; impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::IVec2")] + #[type_path(path = "glam")] struct IVec2 { x: i32, y: i32, @@ -15,7 +15,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::IVec3")] + #[type_path(path = "glam")] struct IVec3 { x: i32, y: i32, @@ -24,7 +24,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::IVec4")] + #[type_path(path = "glam")] struct IVec4 { x: i32, y: i32, @@ -35,7 +35,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::UVec2")] + #[type_path(path = "glam")] struct UVec2 { x: u32, y: u32, @@ -43,7 +43,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::UVec3")] + #[type_path(path = "glam")] struct UVec3 { x: u32, y: u32, @@ -52,7 +52,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::UVec4")] + #[type_path(path = "glam")] struct UVec4 { x: u32, y: u32, @@ -63,7 +63,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::Vec2")] + #[type_path(path = "glam")] struct Vec2 { x: f32, y: f32, @@ -71,7 +71,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::Vec3")] + #[type_path(path = "glam")] struct Vec3 { x: f32, y: f32, @@ -80,7 +80,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::Vec3A")] + #[type_path(path = "glam")] struct Vec3A { x: f32, y: f32, @@ -89,7 +89,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::Vec4")] + #[type_path(path = "glam")] struct Vec4 { x: f32, y: f32, @@ -100,7 +100,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Default)] - #[type_path("glam::BVec2")] + #[type_path(path = "glam")] struct BVec2 { x: bool, y: bool, @@ -108,7 +108,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Default)] - #[type_path("glam::BVec3")] + #[type_path(path = "glam")] struct BVec3 { x: bool, y: bool, @@ -117,7 +117,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Default)] - #[type_path("glam::BVec4")] + #[type_path(path = "glam")] struct BVec4 { x: bool, y: bool, @@ -128,7 +128,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::DVec2")] + #[type_path(path = "glam")] struct DVec2 { x: f64, y: f64, @@ -136,7 +136,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::DVec3")] + #[type_path(path = "glam")] struct DVec3 { x: f64, y: f64, @@ -145,7 +145,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::DVec4")] + #[type_path(path = "glam")] struct DVec4 { x: f64, y: f64, @@ -156,7 +156,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::Mat2")] + #[type_path(path = "glam")] struct Mat2 { x_axis: Vec2, y_axis: Vec2, @@ -164,7 +164,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::Mat3")] + #[type_path(path = "glam")] struct Mat3 { x_axis: Vec3, y_axis: Vec3, @@ -173,7 +173,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::Mat3A")] + #[type_path(path = "glam")] struct Mat3A { x_axis: Vec3A, y_axis: Vec3A, @@ -182,7 +182,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::Mat4")] + #[type_path(path = "glam")] struct Mat4 { x_axis: Vec4, y_axis: Vec4, @@ -193,7 +193,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::DMat2")] + #[type_path(path = "glam")] struct DMat2 { x_axis: DVec2, y_axis: DVec2, @@ -201,7 +201,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::DMat3")] + #[type_path(path = "glam")] struct DMat3 { x_axis: DVec3, y_axis: DVec3, @@ -210,7 +210,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::DMat4")] + #[type_path(path = "glam")] struct DMat4 { x_axis: DVec4, y_axis: DVec4, @@ -221,7 +221,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::Affine2")] + #[type_path(path = "glam")] struct Affine2 { matrix2: Mat2, translation: Vec2, @@ -229,7 +229,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::Affine3A")] + #[type_path(path = "glam")] struct Affine3A { matrix3: Mat3A, translation: Vec3A, @@ -238,7 +238,7 @@ impl_reflect_struct!( impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::DAffine2")] + #[type_path(path = "glam")] struct DAffine2 { matrix2: DMat2, translation: DVec2, @@ -246,7 +246,7 @@ impl_reflect_struct!( ); impl_reflect_struct!( #[reflect(Debug, PartialEq, Serialize, Deserialize, Default)] - #[type_path("glam::DAffine3")] + #[type_path(path = "glam")] struct DAffine3 { matrix3: DMat3, translation: DVec3, @@ -257,21 +257,21 @@ impl_reflect_struct!( // mechanisms for read-only fields. I doubt those mechanisms would be added, // so for now quaternions will remain as values. They are represented identically // to Vec4 and DVec4, so you may use those instead and convert between. -impl_reflect_value!(@"glam::Quat" Quat(Debug, PartialEq, Serialize, Deserialize, Default)); -impl_reflect_value!(@"glam::DQuat" DQuat(Debug, PartialEq, Serialize, Deserialize, Default)); +impl_reflect_value!(@"glam" Quat(Debug, PartialEq, Serialize, Deserialize, Default)); +impl_reflect_value!(@"glam" DQuat(Debug, PartialEq, Serialize, Deserialize, Default)); impl_from_reflect_value!(Quat); impl_from_reflect_value!(DQuat); -impl_reflect_value!(@"glam::EulerRot" EulerRot(Debug, Default)); +impl_reflect_value!(@"glam" EulerRot(Debug, Default)); // glam type aliases these to the non simd versions when there is no support (this breaks wasm builds for example) // ideally it shouldn't do that and there's an issue on glam for this // https://github.com/bitshifter/glam-rs/issues/306 #[cfg(any(target_feature = "sse2", target_feature = "simd128"))] -impl_reflect_value!(@"glam::BVec3A" BVec3A(Debug, PartialEq, Default)); +impl_reflect_value!(@"glam" BVec3A(Debug, PartialEq, Default)); #[cfg(any(target_feature = "sse2", target_feature = "simd128"))] -impl_reflect_value!(@"glam::BVec4A" BVec4A(Debug, PartialEq, Default)); +impl_reflect_value!(@"glam" BVec4A(Debug, PartialEq, Default)); #[cfg(test)] mod tests { diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index 1a00b04f1bc66..1822c0f2c5399 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -43,26 +43,26 @@ impl_reflect_value!( E: Clone + Reflect + TypePath > () ); impl_reflect_value!(HashSet()); -impl_reflect_value!(@"std::Range" Range()); -impl_reflect_value!(@"std::RangeInclusive" RangeInclusive()); -impl_reflect_value!(@"std::RangeFrom" RangeFrom()); -impl_reflect_value!(@"std::RangeTo" RangeTo()); -impl_reflect_value!(@"std::RangeToInclusive" RangeToInclusive()); -impl_reflect_value!(@"std::RangeFull" RangeFull()); -impl_reflect_value!(@"std::Duration" Duration(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(@"std::Instant" Instant(Debug, Hash, PartialEq)); -impl_reflect_value!(@"std::NonZeroI128" NonZeroI128(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(@"std::NonZeroU128" NonZeroU128(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(@"std::NonZeroIsize" NonZeroIsize(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(@"std::NonZeroUsize" NonZeroUsize(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(@"std::NonZeroI64" NonZeroI64(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(@"std::NonZeroU64" NonZeroU64(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(@"std::NonZeroU32" NonZeroU32(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(@"std::NonZeroI32" NonZeroI32(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(@"std::NonZeroI16" NonZeroI16(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(@"std::NonZeroU16" NonZeroU16(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(@"std::NonZeroU8" NonZeroU8(Debug, Hash, PartialEq, Serialize, Deserialize)); -impl_reflect_value!(@"std::NonZeroI8" NonZeroI8(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std" Range()); +impl_reflect_value!(@"std" RangeInclusive()); +impl_reflect_value!(@"std" RangeFrom()); +impl_reflect_value!(@"std" RangeTo()); +impl_reflect_value!(@"std" RangeToInclusive()); +impl_reflect_value!(@"std" RangeFull()); +impl_reflect_value!(@"std" Duration(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std" Instant(Debug, Hash, PartialEq)); +impl_reflect_value!(@"std" NonZeroI128(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std" NonZeroU128(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std" NonZeroIsize(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std" NonZeroUsize(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std" NonZeroI64(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std" NonZeroU64(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std" NonZeroU32(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std" NonZeroI32(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std" NonZeroI16(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std" NonZeroU16(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std" NonZeroU8(Debug, Hash, PartialEq, Serialize, Deserialize)); +impl_reflect_value!(@"std" NonZeroI8(Debug, Hash, PartialEq, Serialize, Deserialize)); impl_from_reflect_value!(bool); impl_from_reflect_value!(char); @@ -114,12 +114,52 @@ impl TypePath for [T; N] { static CELL: GenericTypePathCell = GenericTypePathCell::new(); CELL.get_or_insert::(|| format!("[{}; {N}]", T::type_path())) } + #[inline] + fn short_type_name_base() -> &'static str { + ::type_path() + } + + #[inline] + fn short_type_name() -> &'static str { + ::type_path() + } + + #[inline] + fn module_path() -> &'static str { + "" + } + + #[inline] + fn crate_name() -> &'static str { + "" + } } impl TypePath for Cow<'static, str> { + #[inline] fn type_path() -> &'static str { "Cow<'static, str>" } + + #[inline] + fn short_type_name_base() -> &'static str { + "Cow" + } + + #[inline] + fn short_type_name() -> &'static str { + ::type_path() + } + + #[inline] + fn module_path() -> &'static str { + "" + } + + #[inline] + fn crate_name() -> &'static str { + "" + } } impl Array for Vec { diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index 4da416bc1dbfa..7ad8f9973e16d 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -942,15 +942,15 @@ bevy_reflect::tests::Test { } #[test] - fn reflect_custom_type_name() { + fn reflect_custom_type_path() { #[derive(TypePath)] - #[type_path("Banane")] + #[type_path(path = "", ident = "Banane")] struct Foo; let name = Foo::type_path(); assert_eq!(name, "Banane"); #[derive(TypePath)] - #[type_path("MyType")] + #[type_path(path = "", ident = "MyType")] struct Goo { _value: T, } diff --git a/crates/bevy_reflect/src/reflect.rs b/crates/bevy_reflect/src/reflect.rs index a8e196c1d5268..fa8445d64277a 100644 --- a/crates/bevy_reflect/src/reflect.rs +++ b/crates/bevy_reflect/src/reflect.rs @@ -219,9 +219,30 @@ impl Typed for dyn Reflect { } impl TypePath for dyn Reflect { + #[inline] fn type_path() -> &'static str { "dyn Reflect" } + + #[inline] + fn short_type_name_base() -> &'static str { + ::type_path() + } + + #[inline] + fn short_type_name() -> &'static str { + ::type_path() + } + + #[inline] + fn module_path() -> &'static str { + "" + } + + #[inline] + fn crate_name() -> &'static str { + "" + } } #[deny(rustdoc::broken_intra_doc_links)] diff --git a/crates/bevy_reflect/src/type_path.rs b/crates/bevy_reflect/src/type_path.rs index bab8a355f487c..5407533ef07ee 100644 --- a/crates/bevy_reflect/src/type_path.rs +++ b/crates/bevy_reflect/src/type_path.rs @@ -42,11 +42,31 @@ use crate::utility::GenericTypePathCell; /// } /// ``` pub trait TypePath: 'static { - /// Returns the path of the type. + /// Returns the full path of the type. /// /// This is a stable alternative to [`std::any::type_name`] whose output isn't guarenteed /// and may change between versions of the compiler. fn type_path() -> &'static str; + + /// The short type name, without generics. + /// + /// e.g. `MyType` + fn short_type_name_base() -> &'static str; + + /// The short type name, with generics. + /// + /// e.g. `MyType` + fn short_type_name() -> &'static str; + + /// The full type path, minus the actual type. + /// + /// e.g. `my_crate::my_mod` + fn module_path() -> &'static str; + + /// The crate name. + /// + /// e.g. `"my_crate` + fn crate_name() -> &'static str; } /// Returns the [type path] of `T`. @@ -72,6 +92,26 @@ macro_rules! impl_type_name_tuple { ) }) } + + fn short_type_name_base() -> &'static str { + // FIXME: how to handle tuple ? + Self::type_path() + } + + fn short_type_name() -> &'static str { + // FIXME: how to handle tuple ? + Self::type_path() + } + + fn module_path() -> &'static str { + // FIXME: how to handle tuple ? + Self::type_path() + } + + fn crate_name() -> &'static str { + // FIXME: how to handle tuple ? + "" + } } }; (@bracket $t:tt, $($rest:tt),*) => {concat!("{}, ", impl_type_name_tuple!(@bracket $($rest),*))}; @@ -100,15 +140,15 @@ mod tests { #[test] fn tuple_name() { #[derive(TypePath)] - #[type_path("Foo")] + #[type_path(path = "")] struct Foo; #[derive(TypePath)] - #[type_path("Goo")] + #[type_path(path = "")] struct Goo; #[derive(TypePath)] - #[type_path("Hoo")] + #[type_path(path = "")] struct Hoo; let s = <(Foo, Goo, Hoo) as TypePath>::type_path(); diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index 1b0d059ae87b7..16ae303dc7a6e 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -183,3 +183,17 @@ pub type GenericTypeInfoCell = GenericDataCell; /// } /// ``` pub type GenericTypePathCell = GenericDataCell; + +pub const fn crate_name_len(type_path: &str) -> usize { + const SEPARATOR: u8 = ':' as u8; + let bytes = type_path.as_bytes(); + let end = bytes.len().saturating_sub(1); + let mut i = 0; + while i < end { + if bytes[i] == SEPARATOR && bytes[i + 1] == SEPARATOR { + return i; + } + i += 1; + } + return bytes.len(); +} From 60ff2b755a91c9f85cc41b1e450d5d83ef5b75f3 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Mon, 5 Sep 2022 15:29:41 +0200 Subject: [PATCH 75/87] fix type path generation --- .../src/impls/type_path.rs | 44 ++++++++++++------- .../bevy_reflect_derive/src/reflect_value.rs | 2 +- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs index 17206e23464b9..6ce939aa3b527 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs @@ -10,11 +10,26 @@ pub(crate) fn impl_type_path(reflect_meta: &ReflectMeta) -> proc_macro2::TokenSt let is_generic = !generics.params.is_empty(); - let module_path = type_path_options - .module_path - .as_ref() - .map(|x| quote!(#x)) - .unwrap_or_else(|| quote!(module_path!())); + let module_path = match type_path_options.module_path.as_ref() { + Some(x) if x.is_empty() => None, + Some(x) => Some(quote!(#x)), + None => Some(quote!(module_path!())), + }; + + let module_path_len = match module_path.as_ref() { + Some(module_path) => quote!(#module_path.len()), + None => quote!(0), + }; + + let module_path_2columns = match module_path.as_ref() { + Some(module_path) => quote!(concat!(#module_path, "::")), + None => quote!(""), + }; + + let crate_name_len = match module_path { + Some(module_path) => quote!(#bevy_reflect_path::utility::crate_name_len(#module_path)), + None => quote!(0), + }; let type_ident = type_path_options .type_ident @@ -53,12 +68,12 @@ pub(crate) fn impl_type_path(reflect_meta: &ReflectMeta) -> proc_macro2::TokenSt quote! { static CELL: #bevy_reflect_path::utility::GenericTypePathCell = #bevy_reflect_path::utility::GenericTypePathCell::new(); CELL.get_or_insert::(|| { - format!(concat!(#module_path, "::", #type_ident, "<", #brackets, ">"), #values) + format!(concat!(#module_path_2columns, #type_ident, "<", #brackets, ">"), #values) }) } } else { quote! { - concat!(#module_path, "::", #type_ident) + concat!(#module_path_2columns, #type_ident) } }; @@ -73,30 +88,25 @@ pub(crate) fn impl_type_path(reflect_meta: &ReflectMeta) -> proc_macro2::TokenSt #[inline] fn short_type_name_base() -> &'static str { - const PATH_LEN: usize = #module_path.len(); - const IDENT_LEN: usize = #type_ident.len(); - const IDENT_POS: usize = PATH_LEN + 2; - const GENERIC_POS: usize = IDENT_POS + IDENT_LEN; + const IDENT_POS: usize = #module_path_len + 2; + const GENERIC_POS: usize = IDENT_POS + #type_ident.len(); &::type_path()[IDENT_POS..GENERIC_POS] } #[inline] fn short_type_name() -> &'static str { - const PATH_LEN: usize = #module_path.len(); - const IDENT_POS: usize = PATH_LEN + 2; + const IDENT_POS: usize = #module_path_len + 2; &::type_path()[IDENT_POS..] } #[inline] fn module_path() -> &'static str { - const PATH_LEN: usize = #module_path.len(); - &::type_path()[..PATH_LEN] + &::type_path()[..#module_path_len] } #[inline] fn crate_name() -> &'static str { - const CRATE_NAME_LEN: usize = #bevy_reflect_path::utility::crate_name_len(#module_path); - &::type_path()[..CRATE_NAME_LEN] + &::type_path()[..#crate_name_len] } } } diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs b/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs index 43a8494f51e34..965d5be9eb04f 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs @@ -80,7 +80,7 @@ impl Parse for NamedReflectValueDef { Ok(Self { type_path_options: TypePathOptions { - module_path, + module_path: module_path.or(Some("".to_string())), type_ident: None, }, def, From e4efa1b901917e0296c8c73040cda27929773f8f Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Mon, 5 Sep 2022 15:46:08 +0200 Subject: [PATCH 76/87] fix ci & doc --- .../bevy_reflect_derive/src/derive_data.rs | 14 ++++---------- .../bevy_reflect_derive/src/impls/type_path.rs | 2 +- .../bevy_reflect_derive/src/reflect_value.rs | 2 +- crates/bevy_reflect/src/type_info.rs | 6 +++++- crates/bevy_reflect/src/type_path.rs | 16 ++++++++++++++++ crates/bevy_reflect/src/utility.rs | 8 ++++++-- 6 files changed, 33 insertions(+), 15 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs index 71de0f80e353a..18418d80bf3b7 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs @@ -366,14 +366,11 @@ impl TypePathOptions { } else { Err(syn::Error::new( lit_str.span(), - format!("Expected a valid module path"), + "Expected a valid module path", )) } } - other => Err(syn::Error::new( - other.span(), - format!("Expected a str literal"), - )), + other => Err(syn::Error::new(other.span(), "Expected a str literal")), } } @@ -391,14 +388,11 @@ impl TypePathOptions { } else { Err(syn::Error::new( lit_str.span(), - format!("Expected a valid type ident"), + "Expected a valid type ident", )) } } - other => Err(syn::Error::new( - other.span(), - format!("Expected a str literal"), - )), + other => Err(syn::Error::new(other.span(), "Expected a str literal")), } } diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs index 6ce939aa3b527..1ad2d9e61abff 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/impls/type_path.rs @@ -48,7 +48,7 @@ pub(crate) fn impl_type_path(reflect_meta: &ReflectMeta) -> proc_macro2::TokenSt quote!(<#ty as #bevy_reflect_path::TypePath>::type_path()) } syn::GenericParam::Lifetime(p) => { - let name = format!("'{}", p.lifetime.ident.to_string()); + let name = format!("'{}", p.lifetime.ident); quote!(#name) } syn::GenericParam::Const(p) => { diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs b/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs index 965d5be9eb04f..7ecf69f25c81f 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/reflect_value.rs @@ -80,7 +80,7 @@ impl Parse for NamedReflectValueDef { Ok(Self { type_path_options: TypePathOptions { - module_path: module_path.or(Some("".to_string())), + module_path: module_path.or_else(|| Some(String::new())), type_ident: None, }, def, diff --git a/crates/bevy_reflect/src/type_info.rs b/crates/bevy_reflect/src/type_info.rs index d6db1b18a55e1..5d1c9606278b0 100644 --- a/crates/bevy_reflect/src/type_info.rs +++ b/crates/bevy_reflect/src/type_info.rs @@ -48,7 +48,11 @@ use std::any::{Any, TypeId}; /// } /// /// # impl TypePath for MyStruct { -/// # fn name() -> &'static str { "MyStruct" } +/// # fn type_path() -> &'static str { todo!() } +/// # fn short_type_name_base() -> &'static str { todo!() } +/// # fn short_type_name() -> &'static str { todo!() } +/// # fn module_path() -> &'static str { todo!() } +/// # fn crate_name() -> &'static str { todo!() } /// # } /// # /// # impl Reflect for MyStruct { diff --git a/crates/bevy_reflect/src/type_path.rs b/crates/bevy_reflect/src/type_path.rs index 5407533ef07ee..76cab25a004a9 100644 --- a/crates/bevy_reflect/src/type_path.rs +++ b/crates/bevy_reflect/src/type_path.rs @@ -21,6 +21,22 @@ use crate::utility::GenericTypePathCell; /// fn type_path() -> &'static str { /// concat!(module_path!(), "::", "MyType") /// } +/// +/// fn short_type_name_base() -> &'static str { +/// "MyType" +/// } +/// +/// fn short_type_name() -> &'static str { +/// "MyType" +/// } +/// +/// fn module_path() -> &'static str { +/// module_path!() +/// } +/// +/// fn crate_name() -> &'static str { +/// "my_crate" +/// } /// } /// ``` /// diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index 16ae303dc7a6e..9edb7e8c949a7 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -94,8 +94,12 @@ impl GenericDataCell { /// }) /// } /// } -/// # impl TypePath for Foo { -/// # fn name() -> &'static str { "Foo" } +/// # impl TypePath for MyStruct { +/// # fn type_path() -> &'static str { todo!() } +/// # fn short_type_name_base() -> &'static str { todo!() } +/// # fn short_type_name() -> &'static str { todo!() } +/// # fn module_path() -> &'static str { todo!() } +/// # fn crate_name() -> &'static str { todo!() } /// # } /// # /// # impl Reflect for Foo { From 02aabfae84939716a667b7d6b130c697b75fd7ed Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Mon, 5 Sep 2022 15:56:33 +0200 Subject: [PATCH 77/87] refix ci & doc --- crates/bevy_reflect/src/type_path.rs | 23 +++++++++++++-- crates/bevy_reflect/src/utility.rs | 42 +++++++++++++++++++++------- 2 files changed, 53 insertions(+), 12 deletions(-) diff --git a/crates/bevy_reflect/src/type_path.rs b/crates/bevy_reflect/src/type_path.rs index 76cab25a004a9..1b8d7640fb21d 100644 --- a/crates/bevy_reflect/src/type_path.rs +++ b/crates/bevy_reflect/src/type_path.rs @@ -49,12 +49,31 @@ use crate::utility::GenericTypePathCell; /// struct MyType(T); /// /// impl TypePath for MyType { -/// fn name() -> &'static str { +/// fn type_path() -> &'static str { /// static CELL: GenericTypePathCell = GenericTypePathCell::new(); /// CELL.get_or_insert::(|| { -/// format!(concat!(module_path!(), "::MyType<{}>"), T::name()) +/// format!(concat!(module_path!(), "::MyType<{}>"), T::type_path()) /// }) /// } +/// +/// fn short_type_name_base() -> &'static str { +/// const IDENT_POS: usize = module_path!().len() + 2; +/// const GENERIC_POS: usize = IDENT_POS + "MyType".len(); +/// &::type_path()[IDENT_POS..GENERIC_POS] +/// } +/// +/// fn short_type_name() -> &'static str { +/// const IDENT_POS: usize = module_path!().len() + 2; +/// &::type_path()[IDENT_POS..] +/// } +/// +/// fn module_path() -> &'static str { +/// &::type_path()[..module_path!().len()] +/// } +/// +/// fn crate_name() -> &'static str { +/// "my_crate" +/// } /// } /// ``` pub trait TypePath: 'static { diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index 9edb7e8c949a7..5dd3c1d5f48e6 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -94,7 +94,7 @@ impl GenericDataCell { /// }) /// } /// } -/// # impl TypePath for MyStruct { +/// # impl TypePath for Foo { /// # fn type_path() -> &'static str { todo!() } /// # fn short_type_name_base() -> &'static str { todo!() } /// # fn short_type_name() -> &'static str { todo!() } @@ -145,7 +145,11 @@ pub type NonGenericTypeInfoCell = NonGenericDataCell; /// } /// /// # impl TypePath for Foo { -/// # fn name() -> &'static str { todo!() } +/// # fn type_path() -> &'static str { todo!() } +/// # fn short_type_name_base() -> &'static str { todo!() } +/// # fn short_type_name() -> &'static str { todo!() } +/// # fn module_path() -> &'static str { todo!() } +/// # fn crate_name() -> &'static str { todo!() } /// # } /// # /// # impl Reflect for Foo { @@ -172,24 +176,42 @@ pub type GenericTypeInfoCell = GenericDataCell; /// ## Example /// /// ``` -/// # use bevy_reflect::TypePath; -/// use bevy_reflect::utility::GenericTypePathCell; +/// bevy_reflect::{TypePath, utility::GenericTypePathCell}; /// -/// struct Foo(T); +/// struct MyType(T); /// -/// impl TypePath for Foo { -/// fn name() -> &'static str { +/// impl TypePath for MyType { +/// fn type_path() -> &'static str { /// static CELL: GenericTypePathCell = GenericTypePathCell::new(); /// CELL.get_or_insert::(|| { -/// format!(concat!(module_path!(), "::Foo<{}>"), T::name()) +/// format!(concat!(module_path!(), "::MyType<{}>"), T::type_path()) /// }) /// } +/// +/// fn short_type_name_base() -> &'static str { +/// const IDENT_POS: usize = module_path!().len() + 2; +/// const GENERIC_POS: usize = IDENT_POS + "MyType".len(); +/// &::type_path()[IDENT_POS..GENERIC_POS] +/// } +/// +/// fn short_type_name() -> &'static str { +/// const IDENT_POS: usize = module_path!().len() + 2; +/// &::type_path()[IDENT_POS..] +/// } +/// +/// fn module_path() -> &'static str { +/// &::type_path()[..module_path!().len()] +/// } +/// +/// fn crate_name() -> &'static str { +/// "my_crate" +/// } /// } /// ``` pub type GenericTypePathCell = GenericDataCell; pub const fn crate_name_len(type_path: &str) -> usize { - const SEPARATOR: u8 = ':' as u8; + const SEPARATOR: u8 = b':'; let bytes = type_path.as_bytes(); let end = bytes.len().saturating_sub(1); let mut i = 0; @@ -199,5 +221,5 @@ pub const fn crate_name_len(type_path: &str) -> usize { } i += 1; } - return bytes.len(); + bytes.len() } From afda7b37c66ceb7d293e39149c24dd07353a0684 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Mon, 5 Sep 2022 16:52:16 +0200 Subject: [PATCH 78/87] fix doc --- crates/bevy_reflect/src/utility.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index 5dd3c1d5f48e6..fc4c87b663d11 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -176,7 +176,7 @@ pub type GenericTypeInfoCell = GenericDataCell; /// ## Example /// /// ``` -/// bevy_reflect::{TypePath, utility::GenericTypePathCell}; +/// use bevy_reflect::{TypePath, utility::GenericTypePathCell}; /// /// struct MyType(T); /// @@ -196,11 +196,11 @@ pub type GenericTypeInfoCell = GenericDataCell; /// /// fn short_type_name() -> &'static str { /// const IDENT_POS: usize = module_path!().len() + 2; -/// &::type_path()[IDENT_POS..] +/// &::type_path()[IDENT_POS..] /// } /// /// fn module_path() -> &'static str { -/// &::type_path()[..module_path!().len()] +/// &::type_path()[..module_path!().len()] /// } /// /// fn crate_name() -> &'static str { From ddf4726e161ee8248b600b2debeb818685d27ed8 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Wed, 14 Sep 2022 14:11:45 +0200 Subject: [PATCH 79/87] refactor: TypePathOptions::parse_meta_list --- .../bevy_reflect_derive/src/derive_data.rs | 75 ++++++++----------- 1 file changed, 30 insertions(+), 45 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs index f48206e825dee..0caa791123951 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs @@ -349,48 +349,21 @@ pub(crate) struct TypePathOptions { impl TypePathOptions { fn parse_meta_list(meta_list: MetaList) -> Result { - fn parse_module_path(lit: Lit) -> Result { - fn is_valid_module_path(_module_path: &str) -> bool { - // FIXME: what conditions here ? - true - } - + fn expected_literal_string(lit: &Lit) -> Result { match lit { - Lit::Str(lit_str) => { - let path = lit_str.value(); - if is_valid_module_path(&path) { - Ok(path) - } else { - Err(syn::Error::new( - lit_str.span(), - "Expected a valid module path", - )) - } - } + Lit::Str(lit_str) => Ok(lit_str.value()), other => Err(syn::Error::new(other.span(), "Expected a str literal")), } } - fn parse_tpye_ident(lit: Lit) -> Result { - fn is_valid_type_ident(_type_ident: &str) -> bool { - // FIXME: what conditions here ? - true - } + fn is_valid_module_path(_module_path: &str) -> bool { + // FIXME: what conditions here ? + true + } - match lit { - Lit::Str(lit_str) => { - let type_ident = lit_str.value(); - if is_valid_type_ident(&type_ident) { - Ok(type_ident) - } else { - Err(syn::Error::new( - lit_str.span(), - "Expected a valid type ident", - )) - } - } - other => Err(syn::Error::new(other.span(), "Expected a str literal")), - } + fn is_valid_type_ident(_type_ident: &str) -> bool { + // FIXME: what conditions here ? + true } let mut module_path = None; @@ -398,17 +371,29 @@ impl TypePathOptions { for attribute in meta_list.nested { match attribute { - NestedMeta::Meta(Meta::NameValue(name_value)) => { - if let Some(ident) = name_value.path.get_ident() { - if ident == "path" { - module_path = Some(parse_module_path(name_value.lit)?); - } else if ident == "ident" { - type_ident = Some(parse_tpye_ident(name_value.lit)?); - } + NestedMeta::Meta(Meta::NameValue(name_value)) + if name_value.path.is_ident("path") => + { + let name = expected_literal_string(&name_value.lit)?; + if is_valid_module_path(&name) { + module_path = Some(name); } else { return Err(syn::Error::new( - name_value.path.span(), - format!("Unexpected entry for the `{TYPE_PATH_ATTRIBUTE_NAME}` attribute. Usage: #[{TYPE_PATH_ATTRIBUTE_NAME}(path = \"my_crate::my_module\", ident = \"MyType\")]"), + name_value.lit.span(), + "Expected a valid module path", + )); + } + } + NestedMeta::Meta(Meta::NameValue(name_value)) + if name_value.path.is_ident("ident") => + { + let name = expected_literal_string(&name_value.lit)?; + if is_valid_type_ident(&name) { + type_ident = Some(name); + } else { + return Err(syn::Error::new( + name_value.lit.span(), + "Expected a valid type ident", )); } } From 0b0cf93bdd4a2afd19138363874924cca7dc2418 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Wed, 14 Sep 2022 14:12:43 +0200 Subject: [PATCH 80/87] fix tuple impl --- crates/bevy_reflect/src/type_path.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/src/type_path.rs b/crates/bevy_reflect/src/type_path.rs index 1b8d7640fb21d..ff9b12ea0faa0 100644 --- a/crates/bevy_reflect/src/type_path.rs +++ b/crates/bevy_reflect/src/type_path.rs @@ -140,7 +140,7 @@ macro_rules! impl_type_name_tuple { fn module_path() -> &'static str { // FIXME: how to handle tuple ? - Self::type_path() + "" } fn crate_name() -> &'static str { From 88d20825cd001de11515f9845b08cf80869b8e6f Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Wed, 14 Sep 2022 14:31:26 +0200 Subject: [PATCH 81/87] fix ci --- crates/bevy_input/src/gamepad.rs | 3 ++- crates/bevy_input/src/input.rs | 12 +++++++----- crates/bevy_input/src/mouse.rs | 3 ++- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/bevy_input/src/gamepad.rs b/crates/bevy_input/src/gamepad.rs index 1a2734df0cc60..21a635e5165e1 100644 --- a/crates/bevy_input/src/gamepad.rs +++ b/crates/bevy_input/src/gamepad.rs @@ -1,6 +1,7 @@ use crate::{Axis, Input}; use bevy_ecs::event::{EventReader, EventWriter}; use bevy_ecs::system::{Res, ResMut, Resource}; +use bevy_reflect::TypePath; use bevy_utils::{tracing::info, HashMap, HashSet}; /// A gamepad with an associated `ID`. @@ -291,7 +292,7 @@ pub enum GamepadButtonType { /// ## Updating /// /// The resources are updated inside of the [`gamepad_event_system`]. -#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, TypePath)] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] pub struct GamepadButton { /// The gamepad on which the button is located on. diff --git a/crates/bevy_input/src/input.rs b/crates/bevy_input/src/input.rs index 90e783ef9723d..58bc41a9b3e06 100644 --- a/crates/bevy_input/src/input.rs +++ b/crates/bevy_input/src/input.rs @@ -1,5 +1,5 @@ use bevy_ecs::system::Resource; -use bevy_reflect::Reflect; +use bevy_reflect::{Reflect, TypePath}; use bevy_utils::HashSet; use std::hash::Hash; @@ -36,7 +36,7 @@ use bevy_ecs::schedule::State; /// * Call the [`Input::clear`] method at each frame start, before processing events. #[derive(Debug, Clone, Resource, Reflect)] #[reflect_value] -pub struct Input { +pub struct Input { /// A collection of every button that is currently being pressed. pressed: HashSet, /// A collection of every button that has just been pressed. @@ -45,7 +45,7 @@ pub struct Input { just_released: HashSet, } -impl Default for Input { +impl Default for Input { fn default() -> Self { Self { pressed: Default::default(), @@ -57,7 +57,7 @@ impl Default for Input { impl Input where - T: Copy + Eq + Hash + Send + Sync + 'static, + T: Copy + Eq + Hash + Send + Sync + TypePath + 'static, { /// Registers a press for the given `input`. pub fn press(&mut self, input: T) { @@ -167,10 +167,12 @@ where #[cfg(test)] mod test { + use bevy_reflect::TypePath; + use crate::Input; /// Used for testing the functionality of [`Input`]. - #[derive(Copy, Clone, Eq, PartialEq, Hash)] + #[derive(Copy, Clone, Eq, PartialEq, Hash, TypePath)] enum DummyInput { Input1, Input2, diff --git a/crates/bevy_input/src/mouse.rs b/crates/bevy_input/src/mouse.rs index b06a5c2ae355a..415c1e7f11892 100644 --- a/crates/bevy_input/src/mouse.rs +++ b/crates/bevy_input/src/mouse.rs @@ -1,6 +1,7 @@ use crate::{ButtonState, Input}; use bevy_ecs::{event::EventReader, system::ResMut}; use bevy_math::Vec2; +use bevy_reflect::TypePath; /// A mouse button input event. /// @@ -28,7 +29,7 @@ pub struct MouseButtonInput { /// ## Updating /// /// The resource is updated inside of the [`mouse_button_input_system`](crate::mouse::mouse_button_input_system). -#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] +#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, TypePath)] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] pub enum MouseButton { /// The left mouse button. From 4f9d95347adce32ce845f39ce83271b43bf4044a Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Thu, 15 Sep 2022 09:14:21 +0200 Subject: [PATCH 82/87] minor doc fix --- crates/bevy_reflect/src/type_path.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/bevy_reflect/src/type_path.rs b/crates/bevy_reflect/src/type_path.rs index ff9b12ea0faa0..efcd98b1c9213 100644 --- a/crates/bevy_reflect/src/type_path.rs +++ b/crates/bevy_reflect/src/type_path.rs @@ -5,7 +5,7 @@ use crate::utility::GenericTypePathCell; /// This is a stable alternative to [`std::any::type_name`] whose output isn't guarenteed /// and may change between versions of the compiler. /// -/// This trait may be derived via [`#[derive(TypePath)]`][bevy_reflect_derive::TypePath]. +/// This trait may be derived via [`#[derive(TypePath)]`]. /// /// ## Manual implementation /// @@ -17,7 +17,7 @@ use crate::utility::GenericTypePathCell; /// /// struct MyType; /// -/// impl TypePath for MyType{ +/// impl TypePath for MyType { /// fn type_path() -> &'static str { /// concat!(module_path!(), "::", "MyType") /// } @@ -64,11 +64,11 @@ use crate::utility::GenericTypePathCell; /// /// fn short_type_name() -> &'static str { /// const IDENT_POS: usize = module_path!().len() + 2; -/// &::type_path()[IDENT_POS..] +/// &::type_path()[IDENT_POS..] /// } /// /// fn module_path() -> &'static str { -/// &::type_path()[..module_path!().len()] +/// &::type_path()[..module_path!().len()] /// } /// /// fn crate_name() -> &'static str { @@ -100,7 +100,7 @@ pub trait TypePath: 'static { /// The crate name. /// - /// e.g. `"my_crate` + /// e.g. `my_crate` fn crate_name() -> &'static str; } From c28c3b4055c1d9695f459e31d64c235de2d860b9 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Thu, 15 Sep 2022 09:17:11 +0200 Subject: [PATCH 83/87] remove empty space --- crates/bevy_reflect/src/impls/std.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index 1822c0f2c5399..7787bc18bd061 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -43,7 +43,7 @@ impl_reflect_value!( E: Clone + Reflect + TypePath > () ); impl_reflect_value!(HashSet()); -impl_reflect_value!(@"std" Range()); +impl_reflect_value!(@"std" Range()); impl_reflect_value!(@"std" RangeInclusive()); impl_reflect_value!(@"std" RangeFrom()); impl_reflect_value!(@"std" RangeTo()); From 5303da305ba97c5b23fb7a40f3f6cc12d32732f7 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Tue, 20 Sep 2022 09:43:36 +0200 Subject: [PATCH 84/87] fix merge --- .../bevy_reflect/bevy_reflect_derive/src/derive_data.rs | 3 ++- crates/bevy_reflect/src/serde/ser.rs | 4 ++-- crates/bevy_reflect/src/type_registry.rs | 8 ++++---- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs index 9239ab416a967..5d8a70bdc32bb 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs @@ -11,7 +11,7 @@ use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{ Data, DeriveInput, Field, Fields, Generics, Ident, Lit, Meta, MetaList, NestedMeta, Path, - Token, Type, Variant, + Token, Variant, }; pub(crate) enum ReflectDerive<'a> { @@ -146,6 +146,7 @@ impl<'a> ReflectDerive<'a> { &input.ident, &input.generics, traits, + type_path_options.unwrap_or_default(), ))); } diff --git a/crates/bevy_reflect/src/serde/ser.rs b/crates/bevy_reflect/src/serde/ser.rs index 5a6ef87deb1ad..b2bd6229623e0 100644 --- a/crates/bevy_reflect/src/serde/ser.rs +++ b/crates/bevy_reflect/src/serde/ser.rs @@ -158,7 +158,7 @@ impl<'a> Serialize for StructValueSerializer<'a> { let mut state = serializer.serialize_map(Some(self.struct_value.field_len()))?; let serialization_data = self .registry - .get_with_name(self.struct_value.type_name()) + .get_with_name(self.struct_value.type_path()) .and_then(|registration| registration.data::()); for (index, value) in self.struct_value.iter_fields().enumerate() { @@ -212,7 +212,7 @@ impl<'a> Serialize for TupleStructValueSerializer<'a> { let mut state = serializer.serialize_seq(Some(self.tuple_struct.field_len()))?; let serialization_data = self .registry - .get_with_name(self.tuple_struct.type_name()) + .get_with_name(self.tuple_struct.type_path()) .and_then(|registration| registration.data::()); for (index, value) in self.tuple_struct.iter_fields().enumerate() { diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index 8e84bdadfcc8a..ead290cf3464e 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -162,9 +162,9 @@ impl TypeRegistry { /// given name. /// /// If no type with the given name has been registered, returns `None`. - pub fn get_with_name(&self, type_name: &str) -> Option<&TypeRegistration> { + pub fn get_with_name(&self, type_path: &str) -> Option<&TypeRegistration> { self.full_name_to_id - .get(type_name) + .get(type_path) .and_then(|id| self.get(*id)) } @@ -172,9 +172,9 @@ impl TypeRegistry { /// the given name. /// /// If no type with the given name has been registered, returns `None`. - pub fn get_with_name_mut(&mut self, type_name: &str) -> Option<&mut TypeRegistration> { + pub fn get_with_name_mut(&mut self, type_path: &str) -> Option<&mut TypeRegistration> { self.full_name_to_id - .get(type_name) + .get(type_path) .cloned() .and_then(move |id| self.get_mut(id)) } From de07bd50e74a004a5d097db936d7d89fa6202ae9 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Wed, 21 Sep 2022 10:12:28 +0200 Subject: [PATCH 85/87] fix merge error --- crates/bevy_reflect/src/enums/dynamic_enum.rs | 3 +- crates/bevy_reflect/src/serde/de.rs | 66 +++++++++---------- crates/bevy_reflect/src/serde/ser.rs | 24 +++---- 3 files changed, 46 insertions(+), 47 deletions(-) diff --git a/crates/bevy_reflect/src/enums/dynamic_enum.rs b/crates/bevy_reflect/src/enums/dynamic_enum.rs index 7c96d9b00c7bc..69700c47a829a 100644 --- a/crates/bevy_reflect/src/enums/dynamic_enum.rs +++ b/crates/bevy_reflect/src/enums/dynamic_enum.rs @@ -93,9 +93,8 @@ impl DynamicEnum { /// * `variant_name`: The name of the variant to set /// * `variant`: The variant data /// - pub fn new_with_index, V: Into>( + pub fn new, V: Into>( name: I, - variant_index: usize, variant_name: I, variant: V, ) -> Self { diff --git a/crates/bevy_reflect/src/serde/de.rs b/crates/bevy_reflect/src/serde/de.rs index d0f03d0f8631b..83119ba2eaf40 100644 --- a/crates/bevy_reflect/src/serde/de.rs +++ b/crates/bevy_reflect/src/serde/de.rs @@ -37,7 +37,7 @@ trait TupleLikeInfo { impl StructLikeInfo for StructInfo { fn get_name(&self) -> &str { - self.type_name() + self.type_path() } fn get_field(&self, name: &str) -> Option<&NamedField> { @@ -65,7 +65,7 @@ impl StructLikeInfo for StructVariantInfo { impl TupleLikeInfo for TupleInfo { fn get_name(&self) -> &str { - self.type_name() + self.type_path() } fn get_field(&self, index: usize) -> Option<&UnnamedField> { @@ -267,7 +267,7 @@ impl<'a, 'de> DeserializeSeed<'de> for TypedReflectDeserializer<'a> { where D: serde::Deserializer<'de>, { - let type_name = self.registration.type_name(); + let type_path = self.registration.type_path(); // Handle both Value case and types that have a custom `ReflectDeserialize` if let Some(deserialize_reflect) = self.registration.data::() { @@ -286,7 +286,7 @@ impl<'a, 'de> DeserializeSeed<'de> for TypedReflectDeserializer<'a> { registry: self.registry, }, )?; - dynamic_struct.set_name(struct_info.type_name().to_string()); + dynamic_struct.set_name(struct_info.type_path().to_string()); Ok(Box::new(dynamic_struct)) } TypeInfo::TupleStruct(tuple_struct_info) => { @@ -299,7 +299,7 @@ impl<'a, 'de> DeserializeSeed<'de> for TypedReflectDeserializer<'a> { registration: self.registration, }, )?; - dynamic_tuple_struct.set_name(tuple_struct_info.type_name().to_string()); + dynamic_tuple_struct.set_name(tuple_struct_info.type_path().to_string()); Ok(Box::new(dynamic_tuple_struct)) } TypeInfo::List(list_info) => { @@ -307,7 +307,7 @@ impl<'a, 'de> DeserializeSeed<'de> for TypedReflectDeserializer<'a> { list_info, registry: self.registry, })?; - dynamic_list.set_name(list_info.type_name().to_string()); + dynamic_list.set_name(list_info.type_path().to_string()); Ok(Box::new(dynamic_list)) } TypeInfo::Array(array_info) => { @@ -318,7 +318,7 @@ impl<'a, 'de> DeserializeSeed<'de> for TypedReflectDeserializer<'a> { registry: self.registry, }, )?; - dynamic_array.set_name(array_info.type_name().to_string()); + dynamic_array.set_name(array_info.type_path().to_string()); Ok(Box::new(dynamic_array)) } TypeInfo::Map(map_info) => { @@ -326,7 +326,7 @@ impl<'a, 'de> DeserializeSeed<'de> for TypedReflectDeserializer<'a> { map_info, registry: self.registry, })?; - dynamic_map.set_name(map_info.type_name().to_string()); + dynamic_map.set_name(map_info.type_path().to_string()); Ok(Box::new(dynamic_map)) } TypeInfo::Tuple(tuple_info) => { @@ -337,12 +337,12 @@ impl<'a, 'de> DeserializeSeed<'de> for TypedReflectDeserializer<'a> { registry: self.registry, }, )?; - dynamic_tuple.set_name(tuple_info.type_name().to_string()); + dynamic_tuple.set_name(tuple_info.type_path().to_string()); Ok(Box::new(dynamic_tuple)) } TypeInfo::Enum(enum_info) => { - let type_name = enum_info.type_name(); - let mut dynamic_enum = if type_name.starts_with("core::option::Option") { + let type_path = enum_info.type_path(); + let mut dynamic_enum = if type_path.starts_with("core::option::Option") { deserializer.deserialize_option(OptionVisitor { enum_info, registry: self.registry, @@ -358,14 +358,14 @@ impl<'a, 'de> DeserializeSeed<'de> for TypedReflectDeserializer<'a> { }, )? }; - dynamic_enum.set_name(type_name.to_string()); + dynamic_enum.set_name(type_path.to_string()); Ok(Box::new(dynamic_enum)) } TypeInfo::Value(_) => { // This case should already be handled Err(de::Error::custom(format_args!( "the TypeRegistration for {} doesn't have ReflectDeserialize", - type_name + type_path ))) } TypeInfo::Dynamic(_) => { @@ -373,7 +373,7 @@ impl<'a, 'de> DeserializeSeed<'de> for TypedReflectDeserializer<'a> { // fields are and would rely on the deserializer to determine them (e.g. `i32` vs `i64`) Err(de::Error::custom(format_args!( "cannot deserialize arbitrary dynamic type {}", - type_name + type_path ))) } } @@ -425,10 +425,10 @@ impl<'a, 'de> Visitor<'de> for TupleStructVisitor<'a> { de::Error::custom(format_args!( "no field at index {} on tuple {}", index, - self.tuple_struct_info.type_name(), + self.tuple_struct_info.type_path(), )) })?; - get_registration(field.type_id(), field.type_name(), self.registry) + get_registration(field.type_id(), field.type_path(), self.registry) }; while let Some(value) = seq.next_element_seed(TypedReflectDeserializer { @@ -497,7 +497,7 @@ impl<'a, 'de> Visitor<'de> for ArrayVisitor<'a> { let mut vec = Vec::with_capacity(seq.size_hint().unwrap_or_default()); let registration = get_registration( self.array_info.item_type_id(), - self.array_info.item_type_name(), + self.array_info.item_type_path(), self.registry, )?; while let Some(value) = seq.next_element_seed(TypedReflectDeserializer { @@ -537,7 +537,7 @@ impl<'a, 'de> Visitor<'de> for ListVisitor<'a> { let mut list = DynamicList::default(); let registration = get_registration( self.list_info.item_type_id(), - self.list_info.item_type_name(), + self.list_info.item_type_path(), self.registry, )?; while let Some(value) = seq.next_element_seed(TypedReflectDeserializer { @@ -569,12 +569,12 @@ impl<'a, 'de> Visitor<'de> for MapVisitor<'a> { let mut dynamic_map = DynamicMap::default(); let key_registration = get_registration( self.map_info.key_type_id(), - self.map_info.key_type_name(), + self.map_info.key_type_path(), self.registry, )?; let value_registration = get_registration( self.map_info.value_type_id(), - self.map_info.value_type_name(), + self.map_info.value_type_path(), self.registry, )?; while let Some(key) = map.next_key_seed(TypedReflectDeserializer { @@ -633,7 +633,7 @@ impl<'a, 'de> Visitor<'de> for EnumVisitor<'a> { VariantInfo::Tuple(tuple_info) if tuple_info.field_len() == 1 => { let field = tuple_info.field_at(0).unwrap(); let registration = - get_registration(field.type_id(), field.type_name(), self.registry)?; + get_registration(field.type_id(), field.type_path(), self.registry)?; let value = variant.newtype_variant_seed(TypedReflectDeserializer { registration, registry: self.registry, @@ -708,7 +708,7 @@ impl<'a, 'de> Visitor<'de> for OptionVisitor<'a> { fn expecting(&self, formatter: &mut Formatter) -> fmt::Result { formatter.write_str("reflected option value of type ")?; - formatter.write_str(self.enum_info.type_name()) + formatter.write_str(self.enum_info.type_path()) } fn visit_some(self, deserializer: D) -> Result @@ -720,7 +720,7 @@ impl<'a, 'de> Visitor<'de> for OptionVisitor<'a> { VariantInfo::Tuple(tuple_info) if tuple_info.field_len() == 1 => { let field = tuple_info.field_at(0).unwrap(); let registration = - get_registration(field.type_id(), field.type_name(), self.registry)?; + get_registration(field.type_id(), field.type_path(), self.registry)?; let de = TypedReflectDeserializer { registration, registry: self.registry, @@ -767,7 +767,7 @@ where ExpectedValues(fields.collect()) )) })?; - let registration = get_registration(field.type_id(), field.type_name(), registry)?; + let registration = get_registration(field.type_id(), field.type_path(), registry)?; let value = map.next_value_seed(TypedReflectDeserializer { registration, registry, @@ -794,7 +794,7 @@ where let field = info.get_field(index).ok_or_else(|| { Error::invalid_length(index, &info.get_field_len().to_string().as_str()) })?; - get_registration(field.type_id(), field.type_name(), registry) + get_registration(field.type_id(), field.type_path(), registry) }; while let Some(value) = seq.next_element_seed(TypedReflectDeserializer { @@ -822,13 +822,13 @@ where fn get_registration<'a, E: Error>( type_id: TypeId, - type_name: &str, + type_path: &str, registry: &'a TypeRegistry, ) -> Result<&'a TypeRegistration, E> { let registration = registry.get(type_id).ok_or_else(|| { Error::custom(format_args!( "no registration found for type `{}`", - type_name + type_path )) })?; Ok(registration) @@ -1064,7 +1064,7 @@ mod tests { // === Normal === // let input = r#"{ - "bevy_reflect::serde::de::tests::should_deserialize_option::OptionTest": ( + "bevy_reflect::serde::de::tests::OptionTest": ( none: None, simple: Some("Hello world!"), complex: Some(( @@ -1086,7 +1086,7 @@ mod tests { let input = r#" #![enable(implicit_some)] { - "bevy_reflect::serde::de::tests::should_deserialize_option::OptionTest": ( + "bevy_reflect::serde::de::tests::OptionTest": ( none: None, simple: "Hello world!", complex: ( @@ -1123,7 +1123,7 @@ mod tests { // === Unit Variant === // let input = r#"{ - "bevy_reflect::serde::de::tests::enum_should_deserialize::MyEnum": Unit, + "bevy_reflect::serde::de::tests::MyEnum": Unit, }"#; let reflect_deserializer = UntypedReflectDeserializer::new(®istry); let mut deserializer = ron::de::Deserializer::from_str(input).unwrap(); @@ -1134,7 +1134,7 @@ mod tests { // === NewType Variant === // let input = r#"{ - "bevy_reflect::serde::de::tests::enum_should_deserialize::MyEnum": NewType(123), + "bevy_reflect::serde::de::tests::MyEnum": NewType(123), }"#; let reflect_deserializer = UntypedReflectDeserializer::new(®istry); let mut deserializer = ron::de::Deserializer::from_str(input).unwrap(); @@ -1145,7 +1145,7 @@ mod tests { // === Tuple Variant === // let input = r#"{ - "bevy_reflect::serde::de::tests::enum_should_deserialize::MyEnum": Tuple(1.23, 3.21), + "bevy_reflect::serde::de::tests::MyEnum": Tuple(1.23, 3.21), }"#; let reflect_deserializer = UntypedReflectDeserializer::new(®istry); let mut deserializer = ron::de::Deserializer::from_str(input).unwrap(); @@ -1156,7 +1156,7 @@ mod tests { // === Struct Variant === // let input = r#"{ - "bevy_reflect::serde::de::tests::enum_should_deserialize::MyEnum": Struct( + "bevy_reflect::serde::de::tests::MyEnum": Struct( value: "I <3 Enums", ), }"#; diff --git a/crates/bevy_reflect/src/serde/ser.rs b/crates/bevy_reflect/src/serde/ser.rs index 73904912fe0e5..a0f7537e4b35c 100644 --- a/crates/bevy_reflect/src/serde/ser.rs +++ b/crates/bevy_reflect/src/serde/ser.rs @@ -89,7 +89,7 @@ impl<'a> Serialize for ReflectSerializer<'a> { { let mut state = serializer.serialize_map(Some(1))?; state.serialize_entry( - self.value.type_name(), + self.value.type_path(), &TypedReflectSerializer::new(self.value, self.registry), )?; state.end() @@ -189,7 +189,7 @@ impl<'a> Serialize for StructSerializer<'a> { { let type_info = get_type_info( self.struct_value.get_type_info(), - self.struct_value.type_name(), + self.struct_value.type_path(), self.registry, )?; @@ -239,7 +239,7 @@ impl<'a> Serialize for TupleStructSerializer<'a> { { let type_info = get_type_info( self.tuple_struct.get_type_info(), - self.tuple_struct.type_name(), + self.tuple_struct.type_path(), self.registry, )?; @@ -288,7 +288,7 @@ impl<'a> Serialize for EnumSerializer<'a> { { let type_info = get_type_info( self.enum_value.get_type_info(), - self.enum_value.type_name(), + self.enum_value.type_path(), self.registry, )?; @@ -320,7 +320,7 @@ impl<'a> Serialize for EnumSerializer<'a> { VariantType::Unit => { if self .enum_value - .type_name() + .type_path() .starts_with("core::option::Option") { serializer.serialize_none() @@ -358,7 +358,7 @@ impl<'a> Serialize for EnumSerializer<'a> { let field = self.enum_value.field_at(0).unwrap(); if self .enum_value - .type_name() + .type_path() .starts_with("core::option::Option") { serializer.serialize_some(&TypedReflectSerializer::new(field, self.registry)) @@ -641,7 +641,7 @@ mod tests { let output = ron::ser::to_string_pretty(&serializer, config).unwrap(); let expected = r#"{ - "bevy_reflect::serde::ser::tests::should_serialize_option::OptionTest": ( + "bevy_reflect::serde::ser::tests::OptionTest": ( none: None, simple: Some("Hello world!"), complex: Some(( @@ -661,7 +661,7 @@ mod tests { let output = ron::ser::to_string_pretty(&serializer, config).unwrap(); let expected = r#"#![enable(implicit_some)] { - "bevy_reflect::serde::ser::tests::should_serialize_option::OptionTest": ( + "bevy_reflect::serde::ser::tests::OptionTest": ( none: None, simple: "Hello world!", complex: ( @@ -693,7 +693,7 @@ mod tests { let serializer = ReflectSerializer::new(&value, ®istry); let output = ron::ser::to_string_pretty(&serializer, config.clone()).unwrap(); let expected = r#"{ - "bevy_reflect::serde::ser::tests::enum_should_serialize::MyEnum": Unit, + "bevy_reflect::serde::ser::tests::MyEnum": Unit, }"#; assert_eq!(expected, output); @@ -702,7 +702,7 @@ mod tests { let serializer = ReflectSerializer::new(&value, ®istry); let output = ron::ser::to_string_pretty(&serializer, config.clone()).unwrap(); let expected = r#"{ - "bevy_reflect::serde::ser::tests::enum_should_serialize::MyEnum": NewType(123), + "bevy_reflect::serde::ser::tests::MyEnum": NewType(123), }"#; assert_eq!(expected, output); @@ -711,7 +711,7 @@ mod tests { let serializer = ReflectSerializer::new(&value, ®istry); let output = ron::ser::to_string_pretty(&serializer, config.clone()).unwrap(); let expected = r#"{ - "bevy_reflect::serde::ser::tests::enum_should_serialize::MyEnum": Tuple(1.23, 3.21), + "bevy_reflect::serde::ser::tests::MyEnum": Tuple(1.23, 3.21), }"#; assert_eq!(expected, output); @@ -722,7 +722,7 @@ mod tests { let serializer = ReflectSerializer::new(&value, ®istry); let output = ron::ser::to_string_pretty(&serializer, config).unwrap(); let expected = r#"{ - "bevy_reflect::serde::ser::tests::enum_should_serialize::MyEnum": Struct( + "bevy_reflect::serde::ser::tests::MyEnum": Struct( value: "I <3 Enums", ), }"#; From 858a6c2d8b3a2a4da0d1aa6408119688633b8ade Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Wed, 21 Sep 2022 10:25:36 +0200 Subject: [PATCH 86/87] fix ser/de for option --- crates/bevy_reflect/src/serde/de.rs | 2 +- crates/bevy_reflect/src/serde/ser.rs | 12 ++---------- 2 files changed, 3 insertions(+), 11 deletions(-) diff --git a/crates/bevy_reflect/src/serde/de.rs b/crates/bevy_reflect/src/serde/de.rs index 83119ba2eaf40..e08360afc46c4 100644 --- a/crates/bevy_reflect/src/serde/de.rs +++ b/crates/bevy_reflect/src/serde/de.rs @@ -342,7 +342,7 @@ impl<'a, 'de> DeserializeSeed<'de> for TypedReflectDeserializer<'a> { } TypeInfo::Enum(enum_info) => { let type_path = enum_info.type_path(); - let mut dynamic_enum = if type_path.starts_with("core::option::Option") { + let mut dynamic_enum = if type_path.starts_with("Option<") { deserializer.deserialize_option(OptionVisitor { enum_info, registry: self.registry, diff --git a/crates/bevy_reflect/src/serde/ser.rs b/crates/bevy_reflect/src/serde/ser.rs index a0f7537e4b35c..a8637ab2bcae5 100644 --- a/crates/bevy_reflect/src/serde/ser.rs +++ b/crates/bevy_reflect/src/serde/ser.rs @@ -318,11 +318,7 @@ impl<'a> Serialize for EnumSerializer<'a> { match variant_type { VariantType::Unit => { - if self - .enum_value - .type_path() - .starts_with("core::option::Option") - { + if self.enum_value.type_path().starts_with("Option<") { serializer.serialize_none() } else { serializer.serialize_unit_variant(enum_name, variant_index, variant_name) @@ -356,11 +352,7 @@ impl<'a> Serialize for EnumSerializer<'a> { } VariantType::Tuple if field_len == 1 => { let field = self.enum_value.field_at(0).unwrap(); - if self - .enum_value - .type_path() - .starts_with("core::option::Option") - { + if self.enum_value.type_path().starts_with("Option<") { serializer.serialize_some(&TypedReflectSerializer::new(field, self.registry)) } else { serializer.serialize_newtype_variant( From 226dad2941fb95401e69ca0138b56aa9c19d5a00 Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Sun, 16 Oct 2022 09:51:01 +0200 Subject: [PATCH 87/87] fix CI --- examples/shader/animate_shader.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/shader/animate_shader.rs b/examples/shader/animate_shader.rs index cb5d09038a4a3..e10f8b9cf8170 100644 --- a/examples/shader/animate_shader.rs +++ b/examples/shader/animate_shader.rs @@ -31,7 +31,7 @@ fn setup( }); } -#[derive(AsBindGroup, TypeUuid, Debug, Clone)] +#[derive(AsBindGroup, TypeUuid, TypePath, Debug, Clone)] #[uuid = "a3d71c04-d054-4946-80f8-ba6cfbc90cad"] struct CustomMaterial {}