
# Objective
We're able to reflect types sooooooo... why not functions?
The goal of this PR is to make functions callable within a dynamic
context, where type information is not readily available at compile
time.
For example, if we have a function:
```rust
fn add(left: i32, right: i32) -> i32 {
left + right
}
```
And two `Reflect` values we've already validated are `i32` types:
```rust
let left: Box<dyn Reflect> = Box::new(2_i32);
let right: Box<dyn Reflect> = Box::new(2_i32);
```
We should be able to call `add` with these values:
```rust
// ?????
let result: Box<dyn Reflect> = add.call_dynamic(left, right);
```
And ideally this wouldn't just work for functions, but methods and
closures too!
Right now, users have two options:
1. Manually parse the reflected data and call the function themselves
2. Rely on registered type data to handle the conversions for them
For a small function like `add`, this isn't too bad. But what about for
more complex functions? What about for many functions?
At worst, this process is error-prone. At best, it's simply tedious.
And this is assuming we know the function at compile time. What if we
want to accept a function dynamically and call it with our own
arguments?
It would be much nicer if `bevy_reflect` could alleviate some of the
problems here.
## Solution
Added function reflection!
This adds a `DynamicFunction` type to wrap a function dynamically. This
can be called with an `ArgList`, which is a dynamic list of
`Reflect`-containing `Arg` arguments. It returns a `FunctionResult`
which indicates whether or not the function call succeeded, returning a
`Reflect`-containing `Return` type if it did succeed.
Many functions can be converted into this `DynamicFunction` type thanks
to the `IntoFunction` trait.
Taking our previous `add` example, this might look something like
(explicit types added for readability):
```rust
fn add(left: i32, right: i32) -> i32 {
left + right
}
let mut function: DynamicFunction = add.into_function();
let args: ArgList = ArgList::new().push_owned(2_i32).push_owned(2_i32);
let result: Return = function.call(args).unwrap();
let value: Box<dyn Reflect> = result.unwrap_owned();
assert_eq!(value.take::<i32>().unwrap(), 4);
```
And it also works on closures:
```rust
let add = |left: i32, right: i32| left + right;
let mut function: DynamicFunction = add.into_function();
let args: ArgList = ArgList::new().push_owned(2_i32).push_owned(2_i32);
let result: Return = function.call(args).unwrap();
let value: Box<dyn Reflect> = result.unwrap_owned();
assert_eq!(value.take::<i32>().unwrap(), 4);
```
As well as methods:
```rust
#[derive(Reflect)]
struct Foo(i32);
impl Foo {
fn add(&mut self, value: i32) {
self.0 += value;
}
}
let mut foo = Foo(2);
let mut function: DynamicFunction = Foo::add.into_function();
let args: ArgList = ArgList::new().push_mut(&mut foo).push_owned(2_i32);
function.call(args).unwrap();
assert_eq!(foo.0, 4);
```
### Limitations
While this does cover many functions, it is far from a perfect system
and has quite a few limitations. Here are a few of the limitations when
using `IntoFunction`:
1. The lifetime of the return value is only tied to the lifetime of the
first argument (useful for methods). This means you can't have a
function like `(a: i32, b: &i32) -> &i32` without creating the
`DynamicFunction` manually.
2. Only 15 arguments are currently supported. If the first argument is a
(mutable) reference, this number increases to 16.
3. Manual implementations of `Reflect` will need to implement the new
`FromArg`, `GetOwnership`, and `IntoReturn` traits in order to be used
as arguments/return types.
And some limitations of `DynamicFunction` itself:
1. All arguments share the same lifetime, or rather, they will shrink to
the shortest lifetime.
2. Closures that capture their environment may need to have their
`DynamicFunction` dropped before accessing those variables again (there
is a `DynamicFunction::call_once` to make this a bit easier)
3. All arguments and return types must implement `Reflect`. While not a
big surprise coming from `bevy_reflect`, this implementation could
actually still work by swapping `Reflect` out with `Any`. Of course,
that makes working with the arguments and return values a bit harder.
4. Generic functions are not supported (unless they have been manually
monomorphized)
And general, reflection gotchas:
1. `&str` does not implement `Reflect`. Rather, `&'static str`
implements `Reflect` (the same is true for `&Path` and similar types).
This means that `&'static str` is considered an "owned" value for the
sake of generating arguments. Additionally, arguments and return types
containing `&str` will assume it's `&'static str`, which is almost never
the desired behavior. In these cases, the only solution (I believe) is
to use `&String` instead.
### Followup Work
This PR is the first of two PRs I intend to work on. The second PR will
aim to integrate this new function reflection system into the existing
reflection traits and `TypeInfo`. The goal would be to register and call
a reflected type's methods dynamically.
I chose not to do that in this PR since the diff is already quite large.
I also want the discussion for both PRs to be focused on their own
implementation.
Another followup I'd like to do is investigate allowing common container
types as a return type, such as `Option<&[mut] T>` and `Result<&[mut] T,
E>`. This would allow even more functions to opt into this system. I
chose to not include it in this one, though, for the same reasoning as
previously mentioned.
### Alternatives
One alternative I had considered was adding a macro to convert any
function into a reflection-based counterpart. The idea would be that a
struct that wraps the function would be created and users could specify
which arguments and return values should be `Reflect`. It could then be
called via a new `Function` trait.
I think that could still work, but it will be a fair bit more involved,
requiring some slightly more complex parsing. And it of course is a bit
more work for the user, since they need to create the type via macro
invocation.
It also makes registering these functions onto a type a bit more
complicated (depending on how it's implemented).
For now, I think this is a fairly simple, yet powerful solution that
provides the least amount of friction for users.
---
## Showcase
Bevy now adds support for storing and calling functions dynamically
using reflection!
```rust
// 1. Take a standard Rust function
fn add(left: i32, right: i32) -> i32 {
left + right
}
// 2. Convert it into a type-erased `DynamicFunction` using the `IntoFunction` trait
let mut function: DynamicFunction = add.into_function();
// 3. Define your arguments from reflected values
let args: ArgList = ArgList::new().push_owned(2_i32).push_owned(2_i32);
// 4. Call the function with your arguments
let result: Return = function.call(args).unwrap();
// 5. Extract the return value
let value: Box<dyn Reflect> = result.unwrap_owned();
assert_eq!(value.take::<i32>().unwrap(), 4);
```
## Changelog
#### TL;DR
- Added support for function reflection
- Added a new `Function Reflection` example:
ba727898f2/examples/reflection/function_reflection.rs (L1-L157)
#### Details
Added the following items:
- `ArgError` enum
- `ArgId` enum
- `ArgInfo` struct
- `ArgList` struct
- `Arg` enum
- `DynamicFunction` struct
- `FromArg` trait (derived with `derive(Reflect)`)
- `FunctionError` enum
- `FunctionInfo` struct
- `FunctionResult` alias
- `GetOwnership` trait (derived with `derive(Reflect)`)
- `IntoFunction` trait (with blanket implementation)
- `IntoReturn` trait (derived with `derive(Reflect)`)
- `Ownership` enum
- `ReturnInfo` struct
- `Return` enum
---------
Co-authored-by: Periwink <charlesbour@gmail.com>
758 lines
22 KiB
Rust
758 lines
22 KiB
Rust
use bevy_reflect_derive::impl_type_path;
|
|
use bevy_utils::all_tuples;
|
|
|
|
use crate::{
|
|
self as bevy_reflect, utility::GenericTypePathCell, ApplyError, FromReflect,
|
|
GetTypeRegistration, Reflect, ReflectMut, ReflectOwned, ReflectRef, TypeInfo, TypePath,
|
|
TypeRegistration, TypeRegistry, Typed, UnnamedField,
|
|
};
|
|
use crate::{ReflectKind, TypePathTable};
|
|
use std::any::{Any, TypeId};
|
|
use std::fmt::{Debug, Formatter};
|
|
use std::slice::Iter;
|
|
|
|
/// A trait used to power [tuple-like] operations via [reflection].
|
|
///
|
|
/// This trait uses the [`Reflect`] trait to allow implementors to have their fields
|
|
/// be dynamically addressed by index.
|
|
///
|
|
/// This trait is automatically implemented for arbitrary tuples of up to 12
|
|
/// elements, provided that each element implements [`Reflect`].
|
|
///
|
|
/// # Example
|
|
///
|
|
/// ```
|
|
/// use bevy_reflect::{Reflect, Tuple};
|
|
///
|
|
/// let foo = (123_u32, true);
|
|
/// assert_eq!(foo.field_len(), 2);
|
|
///
|
|
/// let field: &dyn Reflect = foo.field(0).unwrap();
|
|
/// assert_eq!(field.downcast_ref::<u32>(), Some(&123));
|
|
/// ```
|
|
///
|
|
/// [tuple-like]: https://doc.rust-lang.org/book/ch03-02-data-types.html#the-tuple-type
|
|
/// [reflection]: crate
|
|
pub trait Tuple: Reflect {
|
|
/// Returns a reference to the value of the field with index `index` as a
|
|
/// `&dyn Reflect`.
|
|
fn field(&self, index: usize) -> Option<&dyn Reflect>;
|
|
|
|
/// Returns a mutable reference to the value of the field with index `index`
|
|
/// as a `&mut dyn Reflect`.
|
|
fn field_mut(&mut self, index: usize) -> Option<&mut dyn Reflect>;
|
|
|
|
/// Returns the number of fields in the tuple.
|
|
fn field_len(&self) -> usize;
|
|
|
|
/// Returns an iterator over the values of the tuple's fields.
|
|
fn iter_fields(&self) -> TupleFieldIter;
|
|
|
|
/// Drain the fields of this tuple to get a vector of owned values.
|
|
fn drain(self: Box<Self>) -> Vec<Box<dyn Reflect>>;
|
|
|
|
/// Clones the struct into a [`DynamicTuple`].
|
|
fn clone_dynamic(&self) -> DynamicTuple;
|
|
}
|
|
|
|
/// An iterator over the field values of a tuple.
|
|
pub struct TupleFieldIter<'a> {
|
|
pub(crate) tuple: &'a dyn Tuple,
|
|
pub(crate) index: usize,
|
|
}
|
|
|
|
impl<'a> TupleFieldIter<'a> {
|
|
pub fn new(value: &'a dyn Tuple) -> Self {
|
|
TupleFieldIter {
|
|
tuple: value,
|
|
index: 0,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<'a> Iterator for TupleFieldIter<'a> {
|
|
type Item = &'a dyn Reflect;
|
|
|
|
fn next(&mut self) -> Option<Self::Item> {
|
|
let value = self.tuple.field(self.index);
|
|
self.index += value.is_some() as usize;
|
|
value
|
|
}
|
|
|
|
fn size_hint(&self) -> (usize, Option<usize>) {
|
|
let size = self.tuple.field_len();
|
|
(size, Some(size))
|
|
}
|
|
}
|
|
|
|
impl<'a> ExactSizeIterator for TupleFieldIter<'a> {}
|
|
|
|
/// A convenience trait which combines fetching and downcasting of tuple
|
|
/// fields.
|
|
///
|
|
/// # Example
|
|
///
|
|
/// ```
|
|
/// use bevy_reflect::GetTupleField;
|
|
///
|
|
/// # fn main() {
|
|
/// let foo = ("blue".to_string(), 42_i32);
|
|
///
|
|
/// assert_eq!(foo.get_field::<String>(0), Some(&"blue".to_string()));
|
|
/// assert_eq!(foo.get_field::<i32>(1), Some(&42));
|
|
/// # }
|
|
/// ```
|
|
pub trait GetTupleField {
|
|
/// Returns a reference to the value of the field with index `index`,
|
|
/// downcast to `T`.
|
|
fn get_field<T: Reflect>(&self, index: usize) -> Option<&T>;
|
|
|
|
/// Returns a mutable reference to the value of the field with index
|
|
/// `index`, downcast to `T`.
|
|
fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T>;
|
|
}
|
|
|
|
impl<S: Tuple> GetTupleField for S {
|
|
fn get_field<T: Reflect>(&self, index: usize) -> Option<&T> {
|
|
self.field(index)
|
|
.and_then(|value| value.downcast_ref::<T>())
|
|
}
|
|
|
|
fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T> {
|
|
self.field_mut(index)
|
|
.and_then(|value| value.downcast_mut::<T>())
|
|
}
|
|
}
|
|
|
|
impl GetTupleField for dyn Tuple {
|
|
fn get_field<T: Reflect>(&self, index: usize) -> Option<&T> {
|
|
self.field(index)
|
|
.and_then(|value| value.downcast_ref::<T>())
|
|
}
|
|
|
|
fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T> {
|
|
self.field_mut(index)
|
|
.and_then(|value| value.downcast_mut::<T>())
|
|
}
|
|
}
|
|
|
|
/// A container for compile-time tuple info.
|
|
#[derive(Clone, Debug)]
|
|
pub struct TupleInfo {
|
|
type_path: TypePathTable,
|
|
type_id: TypeId,
|
|
fields: Box<[UnnamedField]>,
|
|
#[cfg(feature = "documentation")]
|
|
docs: Option<&'static str>,
|
|
}
|
|
|
|
impl TupleInfo {
|
|
/// Create a new [`TupleInfo`].
|
|
///
|
|
/// # Arguments
|
|
///
|
|
/// * `fields`: The fields of this tuple in the order they are defined
|
|
///
|
|
pub fn new<T: Reflect + TypePath>(fields: &[UnnamedField]) -> Self {
|
|
Self {
|
|
type_path: TypePathTable::of::<T>(),
|
|
type_id: TypeId::of::<T>(),
|
|
fields: fields.to_vec().into_boxed_slice(),
|
|
#[cfg(feature = "documentation")]
|
|
docs: None,
|
|
}
|
|
}
|
|
|
|
/// Sets the docstring for this tuple.
|
|
#[cfg(feature = "documentation")]
|
|
pub fn with_docs(self, docs: Option<&'static str>) -> Self {
|
|
Self { docs, ..self }
|
|
}
|
|
|
|
/// Get the field at the given index.
|
|
pub fn field_at(&self, index: usize) -> Option<&UnnamedField> {
|
|
self.fields.get(index)
|
|
}
|
|
|
|
/// Iterate over the fields of this tuple.
|
|
pub fn iter(&self) -> Iter<'_, UnnamedField> {
|
|
self.fields.iter()
|
|
}
|
|
|
|
/// The total number of fields in this tuple.
|
|
pub fn field_len(&self) -> usize {
|
|
self.fields.len()
|
|
}
|
|
|
|
/// A representation of the type path of the tuple.
|
|
///
|
|
/// Provides dynamic access to all methods on [`TypePath`].
|
|
pub fn type_path_table(&self) -> &TypePathTable {
|
|
&self.type_path
|
|
}
|
|
|
|
/// The [stable, full type path] of the tuple.
|
|
///
|
|
/// Use [`type_path_table`] if you need access to the other methods on [`TypePath`].
|
|
///
|
|
/// [stable, full type path]: TypePath
|
|
/// [`type_path_table`]: Self::type_path_table
|
|
pub fn type_path(&self) -> &'static str {
|
|
self.type_path_table().path()
|
|
}
|
|
|
|
/// The [`TypeId`] of the tuple.
|
|
pub fn type_id(&self) -> TypeId {
|
|
self.type_id
|
|
}
|
|
|
|
/// Check if the given type matches the tuple type.
|
|
pub fn is<T: Any>(&self) -> bool {
|
|
TypeId::of::<T>() == self.type_id
|
|
}
|
|
|
|
/// The docstring of this tuple, if any.
|
|
#[cfg(feature = "documentation")]
|
|
pub fn docs(&self) -> Option<&'static str> {
|
|
self.docs
|
|
}
|
|
}
|
|
|
|
/// A tuple which allows fields to be added at runtime.
|
|
#[derive(Default, Debug)]
|
|
pub struct DynamicTuple {
|
|
represented_type: Option<&'static TypeInfo>,
|
|
fields: Vec<Box<dyn Reflect>>,
|
|
}
|
|
|
|
impl DynamicTuple {
|
|
/// Sets the [type] to be represented by this `DynamicTuple`.
|
|
///
|
|
/// # Panics
|
|
///
|
|
/// Panics if the given [type] is not a [`TypeInfo::Tuple`].
|
|
///
|
|
/// [type]: TypeInfo
|
|
pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) {
|
|
if let Some(represented_type) = represented_type {
|
|
assert!(
|
|
matches!(represented_type, TypeInfo::Tuple(_)),
|
|
"expected TypeInfo::Tuple but received: {:?}",
|
|
represented_type
|
|
);
|
|
}
|
|
self.represented_type = represented_type;
|
|
}
|
|
|
|
/// Appends an element with value `value` to the tuple.
|
|
pub fn insert_boxed(&mut self, value: Box<dyn Reflect>) {
|
|
self.represented_type = None;
|
|
self.fields.push(value);
|
|
}
|
|
|
|
/// Appends a typed element with value `value` to the tuple.
|
|
pub fn insert<T: Reflect>(&mut self, value: T) {
|
|
self.represented_type = None;
|
|
self.insert_boxed(Box::new(value));
|
|
}
|
|
}
|
|
|
|
impl Tuple for DynamicTuple {
|
|
#[inline]
|
|
fn field(&self, index: usize) -> Option<&dyn Reflect> {
|
|
self.fields.get(index).map(|field| &**field)
|
|
}
|
|
|
|
#[inline]
|
|
fn field_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> {
|
|
self.fields.get_mut(index).map(|field| &mut **field)
|
|
}
|
|
|
|
#[inline]
|
|
fn field_len(&self) -> usize {
|
|
self.fields.len()
|
|
}
|
|
|
|
#[inline]
|
|
fn iter_fields(&self) -> TupleFieldIter {
|
|
TupleFieldIter {
|
|
tuple: self,
|
|
index: 0,
|
|
}
|
|
}
|
|
|
|
#[inline]
|
|
fn drain(self: Box<Self>) -> Vec<Box<dyn Reflect>> {
|
|
self.fields
|
|
}
|
|
|
|
#[inline]
|
|
fn clone_dynamic(&self) -> DynamicTuple {
|
|
DynamicTuple {
|
|
represented_type: self.represented_type,
|
|
fields: self
|
|
.fields
|
|
.iter()
|
|
.map(|value| value.clone_value())
|
|
.collect(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Reflect for DynamicTuple {
|
|
#[inline]
|
|
fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
|
|
self.represented_type
|
|
}
|
|
|
|
#[inline]
|
|
fn into_any(self: Box<Self>) -> Box<dyn Any> {
|
|
self
|
|
}
|
|
|
|
#[inline]
|
|
fn as_any(&self) -> &dyn Any {
|
|
self
|
|
}
|
|
|
|
#[inline]
|
|
fn as_any_mut(&mut self) -> &mut dyn Any {
|
|
self
|
|
}
|
|
|
|
#[inline]
|
|
fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
|
|
self
|
|
}
|
|
|
|
#[inline]
|
|
fn as_reflect(&self) -> &dyn Reflect {
|
|
self
|
|
}
|
|
|
|
#[inline]
|
|
fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
|
|
self
|
|
}
|
|
|
|
fn apply(&mut self, value: &dyn Reflect) {
|
|
tuple_apply(self, value);
|
|
}
|
|
|
|
fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
|
|
*self = value.take()?;
|
|
Ok(())
|
|
}
|
|
|
|
#[inline]
|
|
fn reflect_kind(&self) -> ReflectKind {
|
|
ReflectKind::Tuple
|
|
}
|
|
|
|
#[inline]
|
|
fn reflect_ref(&self) -> ReflectRef {
|
|
ReflectRef::Tuple(self)
|
|
}
|
|
|
|
#[inline]
|
|
fn reflect_mut(&mut self) -> ReflectMut {
|
|
ReflectMut::Tuple(self)
|
|
}
|
|
|
|
#[inline]
|
|
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
|
|
ReflectOwned::Tuple(self)
|
|
}
|
|
|
|
#[inline]
|
|
fn clone_value(&self) -> Box<dyn Reflect> {
|
|
Box::new(self.clone_dynamic())
|
|
}
|
|
|
|
fn try_apply(&mut self, value: &dyn Reflect) -> Result<(), ApplyError> {
|
|
tuple_try_apply(self, value)
|
|
}
|
|
|
|
fn reflect_partial_eq(&self, value: &dyn Reflect) -> Option<bool> {
|
|
tuple_partial_eq(self, value)
|
|
}
|
|
|
|
fn debug(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
|
write!(f, "DynamicTuple(")?;
|
|
tuple_debug(self, f)?;
|
|
write!(f, ")")
|
|
}
|
|
|
|
#[inline]
|
|
fn is_dynamic(&self) -> bool {
|
|
true
|
|
}
|
|
}
|
|
|
|
impl_type_path!((in bevy_reflect) DynamicTuple);
|
|
|
|
/// Applies the elements of `b` to the corresponding elements of `a`.
|
|
///
|
|
/// # Panics
|
|
///
|
|
/// This function panics if `b` is not a tuple.
|
|
#[inline]
|
|
pub fn tuple_apply<T: Tuple>(a: &mut T, b: &dyn Reflect) {
|
|
if let Err(err) = tuple_try_apply(a, b) {
|
|
panic!("{err}");
|
|
}
|
|
}
|
|
|
|
/// Tries to apply the elements of `b` to the corresponding elements of `a` and
|
|
/// returns a Result.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// This function returns an [`ApplyError::MismatchedKinds`] if `b` is not a tuple or if
|
|
/// applying elements to each other fails.
|
|
#[inline]
|
|
pub fn tuple_try_apply<T: Tuple>(a: &mut T, b: &dyn Reflect) -> Result<(), ApplyError> {
|
|
if let ReflectRef::Tuple(tuple) = b.reflect_ref() {
|
|
for (i, value) in tuple.iter_fields().enumerate() {
|
|
if let Some(v) = a.field_mut(i) {
|
|
v.try_apply(value)?;
|
|
}
|
|
}
|
|
} else {
|
|
return Err(ApplyError::MismatchedKinds {
|
|
from_kind: b.reflect_kind(),
|
|
to_kind: ReflectKind::Tuple,
|
|
});
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Compares a [`Tuple`] with a [`Reflect`] value.
|
|
///
|
|
/// Returns true if and only if all of the following are true:
|
|
/// - `b` is a tuple;
|
|
/// - `b` has the same number of elements as `a`;
|
|
/// - [`Reflect::reflect_partial_eq`] returns `Some(true)` for pairwise elements of `a` and `b`.
|
|
///
|
|
/// Returns [`None`] if the comparison couldn't even be performed.
|
|
#[inline]
|
|
pub fn tuple_partial_eq<T: Tuple>(a: &T, b: &dyn Reflect) -> Option<bool> {
|
|
let ReflectRef::Tuple(b) = b.reflect_ref() else {
|
|
return Some(false);
|
|
};
|
|
|
|
if a.field_len() != b.field_len() {
|
|
return Some(false);
|
|
}
|
|
|
|
for (a_field, b_field) in a.iter_fields().zip(b.iter_fields()) {
|
|
let eq_result = a_field.reflect_partial_eq(b_field);
|
|
if let failed @ (Some(false) | None) = eq_result {
|
|
return failed;
|
|
}
|
|
}
|
|
|
|
Some(true)
|
|
}
|
|
|
|
/// The default debug formatter for [`Tuple`] types.
|
|
///
|
|
/// # Example
|
|
/// ```
|
|
/// use bevy_reflect::Reflect;
|
|
///
|
|
/// let my_tuple: &dyn Reflect = &(1, 2, 3);
|
|
/// println!("{:#?}", my_tuple);
|
|
///
|
|
/// // Output:
|
|
///
|
|
/// // (
|
|
/// // 1,
|
|
/// // 2,
|
|
/// // 3,
|
|
/// // )
|
|
/// ```
|
|
#[inline]
|
|
pub fn tuple_debug(dyn_tuple: &dyn Tuple, f: &mut Formatter<'_>) -> std::fmt::Result {
|
|
let mut debug = f.debug_tuple("");
|
|
for field in dyn_tuple.iter_fields() {
|
|
debug.field(&field as &dyn Debug);
|
|
}
|
|
debug.finish()
|
|
}
|
|
|
|
macro_rules! impl_reflect_tuple {
|
|
{$($index:tt : $name:tt),*} => {
|
|
impl<$($name: Reflect + TypePath + GetTypeRegistration),*> Tuple for ($($name,)*) {
|
|
#[inline]
|
|
fn field(&self, index: usize) -> Option<&dyn Reflect> {
|
|
match index {
|
|
$($index => Some(&self.$index as &dyn Reflect),)*
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
#[inline]
|
|
fn field_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> {
|
|
match index {
|
|
$($index => Some(&mut self.$index as &mut dyn Reflect),)*
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
#[inline]
|
|
fn field_len(&self) -> usize {
|
|
let indices: &[usize] = &[$($index as usize),*];
|
|
indices.len()
|
|
}
|
|
|
|
#[inline]
|
|
fn iter_fields(&self) -> TupleFieldIter {
|
|
TupleFieldIter {
|
|
tuple: self,
|
|
index: 0,
|
|
}
|
|
}
|
|
|
|
#[inline]
|
|
fn drain(self: Box<Self>) -> Vec<Box<dyn Reflect>> {
|
|
vec![
|
|
$(Box::new(self.$index),)*
|
|
]
|
|
}
|
|
|
|
#[inline]
|
|
fn clone_dynamic(&self) -> DynamicTuple {
|
|
let info = self.get_represented_type_info();
|
|
DynamicTuple {
|
|
represented_type: info,
|
|
fields: self
|
|
.iter_fields()
|
|
.map(|value| value.clone_value())
|
|
.collect(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<$($name: Reflect + TypePath + GetTypeRegistration),*> Reflect for ($($name,)*) {
|
|
fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
|
|
Some(<Self as Typed>::type_info())
|
|
}
|
|
|
|
fn into_any(self: Box<Self>) -> Box<dyn Any> {
|
|
self
|
|
}
|
|
|
|
fn as_any(&self) -> &dyn Any {
|
|
self
|
|
}
|
|
|
|
fn as_any_mut(&mut self) -> &mut dyn Any {
|
|
self
|
|
}
|
|
|
|
fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
|
|
self
|
|
}
|
|
|
|
fn as_reflect(&self) -> &dyn Reflect {
|
|
self
|
|
}
|
|
|
|
fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
|
|
self
|
|
}
|
|
|
|
fn apply(&mut self, value: &dyn Reflect) {
|
|
crate::tuple_apply(self, value);
|
|
}
|
|
|
|
fn try_apply(&mut self, value: &dyn Reflect) -> Result<(), ApplyError> {
|
|
crate::tuple_try_apply(self, value)
|
|
}
|
|
|
|
fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
|
|
*self = value.take()?;
|
|
Ok(())
|
|
}
|
|
|
|
fn reflect_kind(&self) -> ReflectKind {
|
|
ReflectKind::Tuple
|
|
}
|
|
|
|
fn reflect_ref(&self) -> ReflectRef {
|
|
ReflectRef::Tuple(self)
|
|
}
|
|
|
|
fn reflect_mut(&mut self) -> ReflectMut {
|
|
ReflectMut::Tuple(self)
|
|
}
|
|
|
|
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
|
|
ReflectOwned::Tuple(self)
|
|
}
|
|
|
|
fn clone_value(&self) -> Box<dyn Reflect> {
|
|
Box::new(self.clone_dynamic())
|
|
}
|
|
|
|
fn reflect_partial_eq(&self, value: &dyn Reflect) -> Option<bool> {
|
|
crate::tuple_partial_eq(self, value)
|
|
}
|
|
}
|
|
|
|
impl <$($name: Reflect + TypePath + GetTypeRegistration),*> Typed for ($($name,)*) {
|
|
fn type_info() -> &'static TypeInfo {
|
|
static CELL: $crate::utility::GenericTypeInfoCell = $crate::utility::GenericTypeInfoCell::new();
|
|
CELL.get_or_insert::<Self, _>(|| {
|
|
let fields = [
|
|
$(UnnamedField::new::<$name>($index),)*
|
|
];
|
|
let info = TupleInfo::new::<Self>(&fields);
|
|
TypeInfo::Tuple(info)
|
|
})
|
|
}
|
|
}
|
|
|
|
impl<$($name: Reflect + TypePath + GetTypeRegistration),*> GetTypeRegistration for ($($name,)*) {
|
|
fn get_type_registration() -> TypeRegistration {
|
|
TypeRegistration::of::<($($name,)*)>()
|
|
}
|
|
|
|
fn register_type_dependencies(_registry: &mut TypeRegistry) {
|
|
$(_registry.register::<$name>();)*
|
|
}
|
|
}
|
|
|
|
impl<$($name: FromReflect + TypePath + GetTypeRegistration),*> FromReflect for ($($name,)*)
|
|
{
|
|
fn from_reflect(reflect: &dyn Reflect) -> Option<Self> {
|
|
if let ReflectRef::Tuple(_ref_tuple) = reflect.reflect_ref() {
|
|
Some(
|
|
(
|
|
$(
|
|
<$name as FromReflect>::from_reflect(_ref_tuple.field($index)?)?,
|
|
)*
|
|
)
|
|
)
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl_reflect_tuple! {}
|
|
impl_reflect_tuple! {0: A}
|
|
impl_reflect_tuple! {0: A, 1: B}
|
|
impl_reflect_tuple! {0: A, 1: B, 2: C}
|
|
impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D}
|
|
impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E}
|
|
impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F}
|
|
impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G}
|
|
impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H}
|
|
impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I}
|
|
impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J}
|
|
impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K}
|
|
impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L}
|
|
|
|
macro_rules! impl_type_path_tuple {
|
|
() => {
|
|
impl TypePath for () {
|
|
fn type_path() -> &'static str {
|
|
"()"
|
|
}
|
|
|
|
fn short_type_path() -> &'static str {
|
|
"()"
|
|
}
|
|
}
|
|
};
|
|
|
|
($param:ident) => {
|
|
impl <$param: TypePath> TypePath for ($param,) {
|
|
fn type_path() -> &'static str {
|
|
static CELL: GenericTypePathCell = GenericTypePathCell::new();
|
|
CELL.get_or_insert::<Self, _>(|| {
|
|
"(".to_owned() + $param::type_path() + ",)"
|
|
})
|
|
}
|
|
|
|
fn short_type_path() -> &'static str {
|
|
static CELL: GenericTypePathCell = GenericTypePathCell::new();
|
|
CELL.get_or_insert::<Self, _>(|| {
|
|
"(".to_owned() + $param::short_type_path() + ",)"
|
|
})
|
|
}
|
|
}
|
|
};
|
|
|
|
($last:ident $(,$param:ident)*) => {
|
|
|
|
impl <$($param: TypePath,)* $last: TypePath> TypePath for ($($param,)* $last) {
|
|
fn type_path() -> &'static str {
|
|
static CELL: GenericTypePathCell = GenericTypePathCell::new();
|
|
CELL.get_or_insert::<Self, _>(|| {
|
|
"(".to_owned() $(+ $param::type_path() + ", ")* + $last::type_path() + ")"
|
|
})
|
|
}
|
|
|
|
fn short_type_path() -> &'static str {
|
|
static CELL: GenericTypePathCell = GenericTypePathCell::new();
|
|
CELL.get_or_insert::<Self, _>(|| {
|
|
"(".to_owned() $(+ $param::short_type_path() + ", ")* + $last::short_type_path() + ")"
|
|
})
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
all_tuples!(impl_type_path_tuple, 0, 12, P);
|
|
|
|
macro_rules! impl_get_ownership_tuple {
|
|
($($name: ident),*) => {
|
|
$crate::func::args::impl_get_ownership!(($($name,)*); <$($name),*>);
|
|
};
|
|
}
|
|
|
|
all_tuples!(impl_get_ownership_tuple, 0, 12, P);
|
|
|
|
macro_rules! impl_from_arg_tuple {
|
|
($($name: ident),*) => {
|
|
$crate::func::args::impl_from_arg!(($($name,)*); <$($name: FromReflect + TypePath + GetTypeRegistration),*>);
|
|
};
|
|
}
|
|
|
|
all_tuples!(impl_from_arg_tuple, 0, 12, P);
|
|
|
|
macro_rules! impl_into_return_tuple {
|
|
($($name: ident),+) => {
|
|
$crate::func::impl_into_return!(($($name,)*); <$($name: FromReflect + TypePath + GetTypeRegistration),*>);
|
|
};
|
|
}
|
|
|
|
// The unit type (i.e. `()`) is special-cased, so we skip implementing it here.
|
|
all_tuples!(impl_into_return_tuple, 1, 12, P);
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::Tuple;
|
|
|
|
#[test]
|
|
fn next_index_increment() {
|
|
let mut iter = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11).iter_fields();
|
|
let size = iter.len();
|
|
iter.index = size - 1;
|
|
let prev_index = iter.index;
|
|
assert!(iter.next().is_some());
|
|
assert_eq!(prev_index, iter.index - 1);
|
|
|
|
// When None we should no longer increase index
|
|
assert!(iter.next().is_none());
|
|
assert_eq!(size, iter.index);
|
|
assert!(iter.next().is_none());
|
|
assert_eq!(size, iter.index);
|
|
}
|
|
}
|