Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Merged by Bors] - implement TypeUuid for primitives and fix multiple-parameter generics having the same TypeUuid #6633

Closed
wants to merge 20 commits into from
Closed
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions crates/bevy_reflect/bevy_reflect_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@ mod type_uuid;
mod utility;

use crate::derive_data::{ReflectDerive, ReflectMeta, ReflectStruct};
use crate::type_uuid::gen_impl_type_uuid;
use proc_macro::TokenStream;
use quote::quote;
use reflect_value::ReflectValueDef;
use syn::spanned::Spanned;
use syn::{parse_macro_input, DeriveInput};
use type_uuid::TypeUuidDef;

pub(crate) static REFLECT_ATTRIBUTE_NAME: &str = "reflect";
pub(crate) static REFLECT_VALUE_ATTRIBUTE_NAME: &str = "reflect_value";
Expand Down Expand Up @@ -184,3 +186,10 @@ pub fn impl_from_reflect_value(input: TokenStream) -> TokenStream {
def.traits.unwrap_or_default(),
))
}

/// Derives `TypeUuid` for the given type. This is used internally to implement `TypeUuid` on foreign types, such as those in the std. This macro should be used in the format of `<[Generic Params]> [Type (Path)], [Uuid (String Literal)]`.
#[proc_macro]
pub fn impl_type_uuid(input: TokenStream) -> TokenStream {
let def = parse_macro_input!(input as TypeUuidDef);
gen_impl_type_uuid(def)
}
83 changes: 68 additions & 15 deletions crates/bevy_reflect/bevy_reflect_derive/src/type_uuid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,20 @@ extern crate proc_macro;

use bevy_macro_utils::BevyManifest;
use quote::quote;
use syn::parse::{Parse, ParseStream};
use syn::*;
use uuid::Uuid;

/// Parses input from a derive of `TypeUuid`.
pub(crate) fn type_uuid_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
// Construct a representation of Rust code as a syntax tree
// that we can manipulate
let mut ast: DeriveInput = syn::parse(input).unwrap();
let bevy_reflect_path: Path = BevyManifest::default().get_path("bevy_reflect");

let ast: DeriveInput = syn::parse(input).unwrap();
// Build the trait implementation
let name = &ast.ident;

ast.generics.type_params_mut().for_each(|param| {
param
.bounds
.push(syn::parse_quote!(#bevy_reflect_path::TypeUuid));
});

let (impl_generics, type_generics, where_clause) = &ast.generics.split_for_impl();
let name = ast.ident;
let path = Path::from(name);
let type_path = TypePath { qself: None, path };
let r#type = Type::Path(type_path);

let mut uuid = None;
for attribute in ast.attrs.iter().filter_map(|attr| attr.parse_meta().ok()) {
Expand Down Expand Up @@ -50,24 +45,82 @@ pub(crate) fn type_uuid_derive(input: proc_macro::TokenStream) -> proc_macro::To

let uuid =
uuid.expect("No `#[uuid = \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"` attribute found.");
gen_impl_type_uuid(TypeUuidDef {
r#type,
generics: ast.generics,
uuid,
include_type_generics: true,
})
}

/// Generates an implementation of `TypeUuid`. If there any generics, the `TYPE_UUID` will be a composite of the generic types' `TYPE_UUID`.
pub(crate) fn gen_impl_type_uuid(def: TypeUuidDef) -> proc_macro::TokenStream {
let uuid = def.uuid;
let mut generics = def.generics;
let r#type = def.r#type;

let bevy_reflect_path: Path = BevyManifest::default().get_path("bevy_reflect");

generics.type_params_mut().for_each(|param| {
param
.bounds
.push(syn::parse_quote!(#bevy_reflect_path::TypeUuid));
});

let bytes = uuid
.as_bytes()
.iter()
.map(|byte| format!("{byte:#X}"))
.map(|byte_str| syn::parse_str::<LitInt>(&byte_str).unwrap());

let (impl_generics, type_generics, where_clause) = generics.split_for_impl();

let type_generics = if def.include_type_generics {
Some(type_generics)
} else {
None
};
let base = quote! { #bevy_reflect_path::Uuid::from_bytes([#( #bytes ),*]) };
let type_uuid = ast.generics.type_params().fold(base, |acc, param| {
let type_uuid = generics.type_params().enumerate().fold(base, |acc, (index, param)| {
let ident = &param.ident;
let param_uuid = quote!(
#bevy_reflect_path::Uuid::from_u128(<#ident as #bevy_reflect_path::TypeUuid>::TYPE_UUID.as_u128().wrapping_add(#index as u128))
);
quote! {
#bevy_reflect_path::__macro_exports::generate_composite_uuid(#acc, <#ident as #bevy_reflect_path::TypeUuid>::TYPE_UUID)
#bevy_reflect_path::__macro_exports::generate_composite_uuid(#acc, #param_uuid)
}
});

let gen = quote! {
impl #impl_generics #bevy_reflect_path::TypeUuid for #name #type_generics #where_clause {
impl #impl_generics #bevy_reflect_path::TypeUuid for #r#type #type_generics #where_clause {
const TYPE_UUID: #bevy_reflect_path::Uuid = #type_uuid;
}
};
gen.into()
}

/// A struct containing the data required to generate an implementation of `TypeUuid`. This can be generated by either [`impl_type_uuid!`][crate::impl_type_uuid!] or [`type_uuid_derive`].
pub(crate) struct TypeUuidDef {
pub r#type: Type,
pub generics: Generics,
pub uuid: Uuid,
pub include_type_generics: bool,
}

impl Parse for TypeUuidDef {
fn parse(input: ParseStream) -> Result<Self> {
let generics = input.parse::<Generics>()?;
let r#type = input.parse::<Type>()?;
input.parse::<Token![,]>()?;
let uuid = input.parse::<LitStr>()?.value();
let uuid = Uuid::parse_str(&uuid).map_err(|err| input.error(format!("{}", err)))?;
let include_type_generics = matches!(r#type, Type::Path(_));

Ok(Self {
r#type,
generics,
uuid,
include_type_generics,
})
}
}
1 change: 1 addition & 0 deletions crates/bevy_reflect/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ mod tuple_struct;
mod type_info;
mod type_registry;
mod type_uuid;
mod type_uuid_impl;
mod impls {
#[cfg(feature = "glam")]
mod glam;
Expand Down
32 changes: 32 additions & 0 deletions crates/bevy_reflect/src/type_uuid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,36 @@ mod test {

assert_eq!(uuid_a, uuid_b);
}

#[test]
fn test_multiple_generic_uuid() {
#[derive(TypeUuid)]
#[uuid = "35c8a7d3-d4b3-4bd7-b847-1118dc78092f"]
struct TestGeneric<A, B> {
_value_a: A,
_value_b: B,
}
assert_ne!(
TestGeneric::<f32, bool>::TYPE_UUID,
TestGeneric::<bool, f32>::TYPE_UUID
);
}

#[test]
fn test_primitive_generic_uuid() {
test_impl_type_uuid(&true);
test_impl_type_uuid(&Some(true));
test_impl_type_uuid(&TestDeriveStruct::<bool> { _value: true });

assert_ne!(Option::<bool>::TYPE_UUID, Option::<f32>::TYPE_UUID);

assert_ne!(<[bool; 0]>::TYPE_UUID, <[bool; 1]>::TYPE_UUID);
assert_ne!(<[bool; 0]>::TYPE_UUID, <[f32; 0]>::TYPE_UUID);

assert_ne!(
<(bool, bool)>::TYPE_UUID,
<(bool, bool, bool, bool)>::TYPE_UUID
);
assert_ne!(<(bool, f32)>::TYPE_UUID, <(f32, bool)>::TYPE_UUID);
}
}
88 changes: 88 additions & 0 deletions crates/bevy_reflect/src/type_uuid_impl.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
use crate::TypeUuid;
use crate::{self as bevy_reflect, __macro_exports::generate_composite_uuid};
use bevy_reflect_derive::impl_type_uuid;
use bevy_utils::{Duration, HashMap, HashSet, Instant, Uuid};

#[cfg(any(unix, windows))]
use std::ffi::OsString;
use std::{
num::{
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128,
NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize,
},
ops::{RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive},
path::PathBuf,
};
impl<T: TypeUuid, const N: usize> TypeUuid for [T; N] {
const TYPE_UUID: Uuid = generate_composite_uuid(
Uuid::from_u128(0x18d33c78e63c47b9bbf8f095008ab693),
generate_composite_uuid(Uuid::from_u128(N as u128), T::TYPE_UUID),
);
}
impl_type_uuid!(bool, "eb1ad0ee2dff473285bc54ebbdef682c");
impl_type_uuid!(char, "45a4710278ba48f8b31f0d72ff7f9d46");
impl_type_uuid!(u8, "fdf1a88a3e0543ca9f51ad5978ca519f");
impl_type_uuid!(u16, "ddeb93f791074860aaac1540de254edc");
impl_type_uuid!(u32, "fc565ea2367f405591e1c55f91cb60bd");
impl_type_uuid!(u64, "6c74b6a983eb44b096a9169baa6af0a1");
impl_type_uuid!(u128, "f837371a4f534b7381ed776d5056d0c1");
impl_type_uuid!(usize, "0129e1d8cff041f9b23aa99c6e1006b8");
impl_type_uuid!(i8, "af7a5411661e43b0b1631ea43a825fd2");
impl_type_uuid!(i16, "68592d5de5be4a608603c6988edfdf9c");
impl_type_uuid!(i32, "439ff07f96c94aa5a86352ded71e4730");
impl_type_uuid!(i64, "7f9534793ad24ab2b9f05d8254f4204a");
impl_type_uuid!(i128, "6e5009be5845460daf814e052cc9fcf0");
impl_type_uuid!(isize, "d3d52630da45497faf86859051c79e7d");
impl_type_uuid!(f32, "006607124a8148e1910c86f0c18c9015");
impl_type_uuid!(f64, "a5bc32f5632b478c92a0939b821fff80");
impl_type_uuid!(<T,E> Result, "d5960af2e8a743dfb7427dd59b70df95");
impl_type_uuid!(String, "c9f90d31b52d4bcd8b5c1d8b6fc1bcba");
impl_type_uuid!(PathBuf, "aa79933abd1743698583a3acad3b8989");
impl_type_uuid!(<T> Vec, "ab98f5408b974475b643662247fb3886");
impl_type_uuid!(<K, V> HashMap,"f37bfad9ca8c4f6ea7448f1c39e05f98");
impl_type_uuid!(<T> Option, "8d5ba9a9031347078955fba01ff439f0");
#[cfg(feature = "smallvec")]
impl_type_uuid!(
<T: smallvec::Array> smallvec::SmallVec,
"26fd5c1bed7144fbb8d1546c02ba255a"
);
impl_type_uuid!(<K> HashSet, "5ebd2379ece44ef2b1478262962617a3");
impl_type_uuid!(<T> RangeInclusive, "79613b729ca9490881c7f47b24b22b60");
impl_type_uuid!(<T> RangeFrom, "1bd8c975f122486c9ed443e277964642");
impl_type_uuid!(<T> RangeTo, "7d938903749a4d198f496cb354929b9b");
impl_type_uuid!(<T> RangeToInclusive, "2fec56936206462fa5f35c99a62c5ed1");
impl_type_uuid!(RangeFull, "227af17f65db448782a2f6980ceae25d");
impl_type_uuid!(Duration, "cee5978c60f74a53b6848cb9c46a6e1c");
impl_type_uuid!(Instant, "9b0194a1d31c44c1afd2f6fd80ab8dfb");
impl_type_uuid!(NonZeroI128, "915a1e7fcaeb433982cebf58c2ac20e7");
impl_type_uuid!(NonZeroU128, "286de521146042cda31dfbef8f3f6cdc");
impl_type_uuid!(NonZeroIsize, "9318740a9fd14603b709b8fbc6fd2812");
impl_type_uuid!(NonZeroUsize, "a26533ed16324189878263d5e7a294ce");
impl_type_uuid!(NonZeroI64, "1aa38623127a42419cca4992e6fc3152");
impl_type_uuid!(NonZeroU64, "46be65e669a2477d942e2ec39d0d2af7");
impl_type_uuid!(NonZeroU32, "cf53a46d9efe4022967160cb61762c91");
impl_type_uuid!(NonZeroI32, "a69fbd659bef4322b88b15ff3263f530");
impl_type_uuid!(NonZeroI16, "8744c2ec8a10491fae40f8bafa58b30d");
impl_type_uuid!(NonZeroU16, "c7b8b60780a6495bab4fda2bdfedabcc");
impl_type_uuid!(NonZeroU8, "635ee104ef7947fb9d7f79dad47255a3");
impl_type_uuid!(NonZeroI8, "2d3f1570b7f64779826d44da5c7ba069");
#[cfg(any(unix, windows))]
impl_type_uuid!(OsString, "809e7b3c1ea240979ecd832f91eb842a");

macro_rules! impl_tuple {
( $($name: ident)+ ) => {
impl_type_uuid!(< $($name),+ > ( $($name),+ ), "35c8a7d3d4b34bd7b8471118dc78092f");
};
}

impl_tuple!(A B);
impl_tuple!(A B C);
impl_tuple!(A B C D);
impl_tuple!(A B C D E);
impl_tuple!(A B C D E F);
impl_tuple!(A B C D E F G);
impl_tuple!(A B C D E F G H);
impl_tuple!(A B C D E F G H I);
impl_tuple!(A B C D E F G H I J);
impl_tuple!(A B C D E F G H I J K);
impl_tuple!(A B C D E F G H I J K L);