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

bevy_reflect: Reflection-based cloning #13432

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
48 changes: 45 additions & 3 deletions crates/bevy_reflect/derive/src/container_attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::custom_attributes::CustomAttributes;
use crate::derive_data::ReflectTraitToImpl;
use crate::utility;
use crate::utility::terminated_parser;
use bevy_macro_utils::fq_std::{FQAny, FQOption};
use bevy_macro_utils::fq_std::{FQAny, FQBox, FQClone, FQOption, FQResult};
use proc_macro2::{Ident, Span};
use quote::quote_spanned;
use syn::ext::IdentExt;
Expand All @@ -23,6 +23,7 @@ mod kw {
syn::custom_keyword!(Debug);
syn::custom_keyword!(PartialEq);
syn::custom_keyword!(Hash);
syn::custom_keyword!(Clone);
syn::custom_keyword!(no_field_bounds);
}

Expand Down Expand Up @@ -181,6 +182,7 @@ impl TypePathAttrs {
///
#[derive(Default, Clone)]
pub(crate) struct ContainerAttributes {
clone: TraitImpl,
debug: TraitImpl,
hash: TraitImpl,
partial_eq: TraitImpl,
Expand Down Expand Up @@ -239,12 +241,14 @@ impl ContainerAttributes {
self.parse_type_path(input, trait_)
} else if lookahead.peek(kw::no_field_bounds) {
self.parse_no_field_bounds(input)
} else if lookahead.peek(kw::Clone) {
self.parse_clone(input)
} else if lookahead.peek(kw::Debug) {
self.parse_debug(input)
} else if lookahead.peek(kw::PartialEq) {
self.parse_partial_eq(input)
} else if lookahead.peek(kw::Hash) {
self.parse_hash(input)
} else if lookahead.peek(kw::PartialEq) {
self.parse_partial_eq(input)
} else if lookahead.peek(Ident::peek_any) {
self.parse_ident(input)
} else {
Expand Down Expand Up @@ -277,6 +281,26 @@ impl ContainerAttributes {
Ok(())
}

/// Parse `clone` attribute.
///
/// Examples:
/// - `#[reflect(Clone)]`
/// - `#[reflect(Clone(custom_clone_fn))]`
fn parse_clone(&mut self, input: ParseStream) -> syn::Result<()> {
let ident = input.parse::<kw::Clone>()?;

if input.peek(token::Paren) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we should use darling as a helper crate to parse attributes?
It seems easier than what you're doing, especially if the attributes become more complex later on

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could utilize something like darling in the future (not this PR though). I'm not sure our parsing logic is so complex we really need it, but it's certainly worth considering.

let content;
parenthesized!(content in input);
let path = content.parse::<Path>()?;
self.clone.merge(TraitImpl::Custom(path, ident.span))?;
} else {
self.clone = TraitImpl::Implemented(ident.span);
}

Ok(())
}

/// Parse special `Debug` registration.
///
/// Examples:
Expand Down Expand Up @@ -513,6 +537,24 @@ impl ContainerAttributes {
}
}

pub fn get_clone_impl(&self, bevy_reflect_path: &Path) -> Option<proc_macro2::TokenStream> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where is this used? I couldn't understand this part.
I get the clone_impl on struct,tuple,enum,value,etc. but not this.

Or is this the top-level impl?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's used by derive_data.rs. I could probably move this logic into that file directly, since it's the only place where it's used.

match &self.clone {
&TraitImpl::Implemented(span) => Some(quote_spanned! {span=>
#[inline]
fn reflect_clone(&self) -> #FQResult<#FQBox<dyn #bevy_reflect_path::Reflect>, #bevy_reflect_path::ReflectCloneError> {
#FQResult::Ok(#FQBox::new(#FQClone::clone(self)))
}
}),
&TraitImpl::Custom(ref impl_fn, span) => Some(quote_spanned! {span=>
#[inline]
fn reflect_clone(&self) -> #FQResult<#FQBox<dyn #bevy_reflect_path::Reflect>, #bevy_reflect_path::ReflectCloneError> {
#FQResult::Ok(#FQBox::new(#impl_fn(self)))
}
}),
TraitImpl::NotImplemented => None,
}
}

pub fn custom_attributes(&self) -> &CustomAttributes {
&self.custom_attributes
}
Expand Down
117 changes: 115 additions & 2 deletions crates/bevy_reflect/derive/src/derive_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,19 @@ use core::fmt;
use proc_macro2::Span;

use crate::container_attributes::{ContainerAttributes, FromReflectAttrs, TypePathAttrs};
use crate::field_attributes::FieldAttributes;
use crate::field_attributes::{CloneBehavior, FieldAttributes};
use crate::type_path::parse_path_no_leading_colon;
use crate::utility::{StringExpr, WhereClauseOptions};
use crate::utility::{ident_or_index, StringExpr, WhereClauseOptions};
use quote::{quote, ToTokens};
use syn::token::Comma;

use crate::enum_utility::{EnumVariantOutputData, ReflectCloneVariantBuilder, VariantBuilder};
use crate::serialization::SerializationDataDef;
use crate::{
utility, REFLECT_ATTRIBUTE_NAME, REFLECT_VALUE_ATTRIBUTE_NAME, TYPE_NAME_ATTRIBUTE_NAME,
TYPE_PATH_ATTRIBUTE_NAME,
};
use bevy_macro_utils::fq_std::{FQBox, FQClone, FQOption, FQResult};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{
Expand Down Expand Up @@ -518,6 +520,20 @@ impl<'a> StructField<'a> {

info
}

/// Returns a token stream for generating a `FieldId` for this field.
pub fn field_id(&self, bevy_reflect_path: &Path) -> proc_macro2::TokenStream {
match &self.data.ident {
Some(ident) => {
let name = ident.to_string();
quote!(#bevy_reflect_path::FieldId::Named(#name))
}
None => {
let index = self.declaration_index;
quote!(#bevy_reflect_path::FieldId::Unnamed(#index))
}
}
}
}

impl<'a> ReflectStruct<'a> {
Expand Down Expand Up @@ -622,6 +638,77 @@ impl<'a> ReflectStruct<'a> {
#bevy_reflect_path::TypeInfo::#info_variant(#info)
}
}
/// Returns the `Reflect::reflect_clone` impl, if any, as a `TokenStream`.
pub fn get_clone_impl(&self) -> Option<proc_macro2::TokenStream> {
let bevy_reflect_path = self.meta().bevy_reflect_path();

if let container_clone @ Some(_) = self.meta().attrs().get_clone_impl(bevy_reflect_path) {
return container_clone;
}

let mut tokens = proc_macro2::TokenStream::new();

for field in self.fields() {
let field_ty = &field.data.ty;
let member = ident_or_index(field.data.ident.as_ref(), field.declaration_index);

match &field.attrs.clone {
CloneBehavior::Default => {
let value = if field.attrs.ignore.is_ignored() {
let field_id = field.field_id(bevy_reflect_path);

quote! {
return #FQResult::Err(#bevy_reflect_path::ReflectCloneError::FieldNotClonable {
field: #field_id,
variant: #FQOption::None,
container_type_path: ::std::borrow::Cow::Borrowed(
<Self as #bevy_reflect_path::TypePath>::type_path()
)
})
}
} else {
quote! {
#bevy_reflect_path::Reflect::reflect_clone(&self.#member)?
.take()
.map_err(|value| #bevy_reflect_path::ReflectCloneError::FailedDowncast {
expected: ::std::borrow::Cow::Borrowed(
<#field_ty as #bevy_reflect_path::TypePath>::type_path()
),
received: ::std::borrow::Cow::Owned(
#bevy_reflect_path::DynamicTypePath::reflect_type_path(&*value)
.to_string()
),
})?
}
};

tokens.extend(quote! {
#member: #value,
});
}
CloneBehavior::Trait => {
tokens.extend(quote! {
#member: #FQClone::clone(&self.#member),
});
}
CloneBehavior::Func(clone_fn) => {
tokens.extend(quote! {
#member: #clone_fn(&self.#member),
});
}
}
}

Some(quote! {
#[inline]
fn reflect_clone(&self) -> #FQResult<#FQBox<dyn #bevy_reflect_path::Reflect>, #bevy_reflect_path::ReflectCloneError> {
#[allow(unreachable_code)]
#FQResult::Ok(#FQBox::new(Self {
#tokens
}))
}
})
}
}

impl<'a> ReflectEnum<'a> {
Expand Down Expand Up @@ -711,6 +798,32 @@ impl<'a> ReflectEnum<'a> {
#bevy_reflect_path::TypeInfo::Enum(#info)
}
}

/// Returns the `Reflect::reflect_clone` impl, if any, as a `TokenStream`.
pub fn get_clone_impl(&self) -> Option<proc_macro2::TokenStream> {
let bevy_reflect_path = self.meta().bevy_reflect_path();

if let container_clone @ Some(_) = self.meta().attrs().get_clone_impl(bevy_reflect_path) {
return container_clone;
}

let this = Ident::new("self", Span::call_site());
let EnumVariantOutputData {
variant_patterns,
variant_constructors,
..
} = ReflectCloneVariantBuilder::new(self).build(&this);

Some(quote! {
#[inline]
fn reflect_clone(&self) -> #FQResult<#FQBox<dyn #bevy_reflect_path::Reflect>, #bevy_reflect_path::ReflectCloneError> {
#[allow(unreachable_code)]
#FQResult::Ok(#FQBox::new(match #this {
#(#variant_patterns => #variant_constructors),*
}))
}
})
}
}

impl<'a> EnumVariant<'a> {
Expand Down
Loading