|
| 1 | +use alloc::borrow::Cow; |
| 2 | +use core::fmt::{Debug, Formatter}; |
| 3 | + |
| 4 | +use crate::func::args::{ArgInfo, ArgList}; |
| 5 | +use crate::func::info::FunctionInfo; |
| 6 | +use crate::func::{FunctionResult, IntoClosure, ReturnInfo}; |
| 7 | + |
| 8 | +/// A dynamic representation of a Rust closure. |
| 9 | +/// |
| 10 | +/// This type can be used to represent any Rust closure that captures its environment immutably. |
| 11 | +/// For closures that need to capture their environment mutably, |
| 12 | +/// see [`DynamicClosureMut`]. |
| 13 | +/// |
| 14 | +/// This type can be seen as a superset of [`DynamicFunction`]. |
| 15 | +/// |
| 16 | +/// See the [module-level documentation] for more information. |
| 17 | +/// |
| 18 | +/// You will generally not need to construct this manually. |
| 19 | +/// Instead, many functions and closures can be automatically converted using the [`IntoClosure`] trait. |
| 20 | +/// |
| 21 | +/// # Example |
| 22 | +/// |
| 23 | +/// Most of the time, a [`DynamicClosure`] can be created using the [`IntoClosure`] trait: |
| 24 | +/// |
| 25 | +/// ``` |
| 26 | +/// # use bevy_reflect::func::{ArgList, DynamicClosure, FunctionInfo, IntoClosure}; |
| 27 | +/// # |
| 28 | +/// let punct = String::from("!!!"); |
| 29 | +/// |
| 30 | +/// let punctuate = |text: &String| -> String { |
| 31 | +/// format!("{}{}", text, punct) |
| 32 | +/// }; |
| 33 | +/// |
| 34 | +/// // Convert the closure into a dynamic closure using `IntoClosure::into_closure` |
| 35 | +/// let mut func: DynamicClosure = punctuate.into_closure(); |
| 36 | +/// |
| 37 | +/// // Dynamically call the closure: |
| 38 | +/// let text = String::from("Hello, world"); |
| 39 | +/// let args = ArgList::default().push_ref(&text); |
| 40 | +/// let value = func.call(args).unwrap().unwrap_owned(); |
| 41 | +/// |
| 42 | +/// // Check the result: |
| 43 | +/// assert_eq!(value.take::<String>().unwrap(), "Hello, world!!!"); |
| 44 | +/// ``` |
| 45 | +/// |
| 46 | +/// [`DynamicClosureMut`]: crate::func::closures::DynamicClosureMut |
| 47 | +/// [`DynamicFunction`]: crate::func::DynamicFunction |
| 48 | +pub struct DynamicClosure<'env> { |
| 49 | + info: FunctionInfo, |
| 50 | + func: Box<dyn for<'a> Fn(ArgList<'a>, &FunctionInfo) -> FunctionResult<'a> + 'env>, |
| 51 | +} |
| 52 | + |
| 53 | +impl<'env> DynamicClosure<'env> { |
| 54 | + /// Create a new [`DynamicClosure`]. |
| 55 | + /// |
| 56 | + /// The given function can be used to call out to a regular function, closure, or method. |
| 57 | + /// |
| 58 | + /// It's important that the closure signature matches the provided [`FunctionInfo`]. |
| 59 | + /// This info is used to validate the arguments and return value. |
| 60 | + pub fn new<F: for<'a> Fn(ArgList<'a>, &FunctionInfo) -> FunctionResult<'a> + 'env>( |
| 61 | + func: F, |
| 62 | + info: FunctionInfo, |
| 63 | + ) -> Self { |
| 64 | + Self { |
| 65 | + info, |
| 66 | + func: Box::new(func), |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + /// Set the name of the closure. |
| 71 | + /// |
| 72 | + /// For [`DynamicClosures`] created using [`IntoClosure`], |
| 73 | + /// the default name will always be the full path to the closure as returned by [`std::any::type_name`]. |
| 74 | + /// |
| 75 | + /// This default name generally does not contain the actual name of the closure, only its module path. |
| 76 | + /// It is therefore recommended to set the name manually using this method. |
| 77 | + /// |
| 78 | + /// [`DynamicClosures`]: DynamicClosure |
| 79 | + pub fn with_name(mut self, name: impl Into<Cow<'static, str>>) -> Self { |
| 80 | + self.info = self.info.with_name(name); |
| 81 | + self |
| 82 | + } |
| 83 | + |
| 84 | + /// Set the arguments of the closure. |
| 85 | + /// |
| 86 | + /// It is very important that the arguments match the intended closure signature, |
| 87 | + /// as this is used to validate arguments passed to the closure. |
| 88 | + pub fn with_args(mut self, args: Vec<ArgInfo>) -> Self { |
| 89 | + self.info = self.info.with_args(args); |
| 90 | + self |
| 91 | + } |
| 92 | + |
| 93 | + /// Set the return information of the closure. |
| 94 | + pub fn with_return_info(mut self, return_info: ReturnInfo) -> Self { |
| 95 | + self.info = self.info.with_return_info(return_info); |
| 96 | + self |
| 97 | + } |
| 98 | + |
| 99 | + /// Call the closure with the given arguments. |
| 100 | + /// |
| 101 | + /// # Example |
| 102 | + /// |
| 103 | + /// ``` |
| 104 | + /// # use bevy_reflect::func::{IntoClosure, ArgList}; |
| 105 | + /// let c = 23; |
| 106 | + /// let add = |a: i32, b: i32| -> i32 { |
| 107 | + /// a + b + c |
| 108 | + /// }; |
| 109 | + /// |
| 110 | + /// let mut func = add.into_closure().with_name("add"); |
| 111 | + /// let args = ArgList::new().push_owned(25_i32).push_owned(75_i32); |
| 112 | + /// let result = func.call(args).unwrap().unwrap_owned(); |
| 113 | + /// assert_eq!(result.take::<i32>().unwrap(), 123); |
| 114 | + /// ``` |
| 115 | + pub fn call<'a>(&self, args: ArgList<'a>) -> FunctionResult<'a> { |
| 116 | + (self.func)(args, &self.info) |
| 117 | + } |
| 118 | + |
| 119 | + /// Returns the closure info. |
| 120 | + pub fn info(&self) -> &FunctionInfo { |
| 121 | + &self.info |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +/// Outputs the closure's signature. |
| 126 | +/// |
| 127 | +/// This takes the format: `DynamicClosure(fn {name}({arg1}: {type1}, {arg2}: {type2}, ...) -> {return_type})`. |
| 128 | +/// |
| 129 | +/// Names for arguments and the closure itself are optional and will default to `_` if not provided. |
| 130 | +impl<'env> Debug for DynamicClosure<'env> { |
| 131 | + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { |
| 132 | + let name = self.info.name().unwrap_or("_"); |
| 133 | + write!(f, "DynamicClosure(fn {name}(")?; |
| 134 | + |
| 135 | + for (index, arg) in self.info.args().iter().enumerate() { |
| 136 | + let name = arg.name().unwrap_or("_"); |
| 137 | + let ty = arg.type_path(); |
| 138 | + write!(f, "{name}: {ty}")?; |
| 139 | + |
| 140 | + if index + 1 < self.info.args().len() { |
| 141 | + write!(f, ", ")?; |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + let ret = self.info.return_info().type_path(); |
| 146 | + write!(f, ") -> {ret})") |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +impl<'env> IntoClosure<'env, ()> for DynamicClosure<'env> { |
| 151 | + #[inline] |
| 152 | + fn into_closure(self) -> DynamicClosure<'env> { |
| 153 | + self |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +#[cfg(test)] |
| 158 | +mod tests { |
| 159 | + use super::*; |
| 160 | + |
| 161 | + #[test] |
| 162 | + fn should_overwrite_closure_name() { |
| 163 | + let c = 23; |
| 164 | + let func = (|a: i32, b: i32| a + b + c) |
| 165 | + .into_closure() |
| 166 | + .with_name("my_closure"); |
| 167 | + assert_eq!(func.info().name(), Some("my_closure")); |
| 168 | + } |
| 169 | + |
| 170 | + #[test] |
| 171 | + fn should_convert_dynamic_closure_with_into_closure() { |
| 172 | + fn make_closure<'env, F: IntoClosure<'env, M>, M>(f: F) -> DynamicClosure<'env> { |
| 173 | + f.into_closure() |
| 174 | + } |
| 175 | + |
| 176 | + let c = 23; |
| 177 | + let closure: DynamicClosure = make_closure(|a: i32, b: i32| a + b + c); |
| 178 | + let _: DynamicClosure = make_closure(closure); |
| 179 | + } |
| 180 | +} |
0 commit comments