From 2f0ab18b7010804c4d97565dd3e3ed36c5322bc8 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Fri, 22 May 2020 13:09:17 +0800 Subject: [PATCH] Merge register_result_fn and register_dynamic_fn. --- README.md | 50 ++++++++++++++--------------- src/fn_register.rs | 79 ++++++++++------------------------------------ src/lib.rs | 2 +- 3 files changed, 40 insertions(+), 91 deletions(-) diff --git a/README.md b/README.md index 8673aba5..fc04a54e 100644 --- a/README.md +++ b/README.md @@ -611,13 +611,12 @@ Traits A number of traits, under the `rhai::` module namespace, provide additional functionalities. -| Trait | Description | Methods | -| ------------------- | -------------------------------------------------------------------------------------- | --------------------------------------- | -| `RegisterFn` | Trait for registering functions | `register_fn` | -| `RegisterDynamicFn` | Trait for registering functions returning [`Dynamic`] | `register_dynamic_fn` | -| `RegisterResultFn` | Trait for registering fallible functions returning `Result<`_T_`, Box>` | `register_result_fn` | -| `Func` | Trait for creating anonymous functions from script | `create_from_ast`, `create_from_script` | -| `ModuleResolver` | Trait implemented by module resolution services | `resolve` | +| Trait | Description | Methods | +| ------------------ | -------------------------------------------------------------------------------------- | --------------------------------------- | +| `RegisterFn` | Trait for registering functions | `register_fn` | +| `RegisterResultFn` | Trait for registering fallible functions returning `Result<`_T_`, Box>` | `register_result_fn` | +| `Func` | Trait for creating anonymous functions from script | `create_from_ast`, `create_from_script` | +| `ModuleResolver` | Trait implemented by module resolution services | `resolve` | Working with functions ---------------------- @@ -628,16 +627,16 @@ To call these functions, they need to be registered with the [`Engine`]. ```rust use rhai::{Dynamic, Engine, EvalAltResult}; use rhai::RegisterFn; // use 'RegisterFn' trait for 'register_fn' -use rhai::{Dynamic, RegisterDynamicFn}; // use 'RegisterDynamicFn' trait for 'register_dynamic_fn' +use rhai::RegisterResultFn; // use 'RegisterResultFn' trait for 'register_result_fn' -// Normal function +// Normal function that returns any value type fn add(x: i64, y: i64) -> i64 { x + y } -// Function that returns a Dynamic value -fn get_an_any() -> Dynamic { - Dynamic::from(42_i64) +// Function that returns a 'Dynamic' value - must return a 'Result' +fn get_any_value() -> Result> { + Ok((42_i64).into()) // standard supported types can use 'into()' } fn main() -> Result<(), Box> @@ -650,10 +649,10 @@ fn main() -> Result<(), Box> println!("Answer: {}", result); // prints 42 - // Functions that return Dynamic values must use register_dynamic_fn() - engine.register_dynamic_fn("get_an_any", get_an_any); + // Functions that return Dynamic values must use register_result_fn() + engine.register_result_fn("get_any_value", get_any_value); - let result = engine.eval::("get_an_any()")?; + let result = engine.eval::("get_any_value()")?; println!("Answer: {}", result); // prints 42 @@ -661,18 +660,15 @@ fn main() -> Result<(), Box> } ``` -To return a [`Dynamic`] value from a Rust function, use the `Dynamic::from` method. +To create a [`Dynamic`] value, use the `Dynamic::from` method. +Standard supported types in Rhai can also use `into()`. ```rust use rhai::Dynamic; -fn decide(yes_no: bool) -> Dynamic { - if yes_no { - Dynamic::from(42_i64) - } else { - Dynamic::from(String::from("hello!")) // remember &str is not supported by Rhai - } -} +let x = (42_i64).into(); // 'into()' works for standard supported types + +let y = Dynamic::from(String::from("hello!")); // remember &str is not supported by Rhai ``` Generic functions @@ -709,7 +705,7 @@ Fallible functions If a function is _fallible_ (i.e. it returns a `Result<_, Error>`), it can be registered with `register_result_fn` (using the `RegisterResultFn` trait). -The function must return `Result<_, Box>`. `Box` implements `From<&str>` and `From` etc. +The function must return `Result>`. `Box` implements `From<&str>` and `From` etc. and the error text gets converted into `Box`. The error values are `Box`-ed in order to reduce memory footprint of the error path, which should be hit rarely. @@ -718,13 +714,13 @@ The error values are `Box`-ed in order to reduce memory footprint of the error p use rhai::{Engine, EvalAltResult, Position}; use rhai::RegisterResultFn; // use 'RegisterResultFn' trait for 'register_result_fn' -// Function that may fail -fn safe_divide(x: i64, y: i64) -> Result> { +// Function that may fail - the result type must be 'Dynamic' +fn safe_divide(x: i64, y: i64) -> Result> { if y == 0 { // Return an error if y is zero Err("Division by zero!".into()) // short-cut to create Box } else { - Ok(x / y) + Ok((x / y).into()) // convert result into 'Dynamic' } } diff --git a/src/fn_register.rs b/src/fn_register.rs index 46dbd166..ec2be474 100644 --- a/src/fn_register.rs +++ b/src/fn_register.rs @@ -42,49 +42,22 @@ pub trait RegisterFn { fn register_fn(&mut self, name: &str, f: FN); } -/// Trait to register custom functions that return `Dynamic` values with the `Engine`. -pub trait RegisterDynamicFn { - /// Register a custom function returning `Dynamic` values with the `Engine`. - /// - /// # Example - /// - /// ``` - /// # fn main() -> Result<(), Box> { - /// use rhai::{Engine, Dynamic, RegisterDynamicFn}; - /// - /// // Function that returns a Dynamic value - /// fn return_the_same_as_dynamic(x: i64) -> Dynamic { - /// Dynamic::from(x) - /// } - /// - /// let mut engine = Engine::new(); - /// - /// // You must use the trait rhai::RegisterDynamicFn to get this method. - /// engine.register_dynamic_fn("get_any_number", return_the_same_as_dynamic); - /// - /// assert_eq!(engine.eval::("get_any_number(42)")?, 42); - /// # Ok(()) - /// # } - /// ``` - fn register_dynamic_fn(&mut self, name: &str, f: FN); -} - -/// Trait to register fallible custom functions returning `Result<_, Box>` with the `Engine`. -pub trait RegisterResultFn { +/// Trait to register fallible custom functions returning `Result>` with the `Engine`. +pub trait RegisterResultFn { /// Register a custom fallible function with the `Engine`. /// /// # Example /// /// ``` - /// use rhai::{Engine, RegisterResultFn, EvalAltResult}; + /// use rhai::{Engine, Dynamic, RegisterResultFn, EvalAltResult}; /// /// // Normal function - /// fn div(x: i64, y: i64) -> Result> { + /// fn div(x: i64, y: i64) -> Result> { /// if y == 0 { /// // '.into()' automatically converts to 'Box' /// Err("division by zero!".into()) /// } else { - /// Ok(x / y) + /// Ok((x / y).into()) /// } /// } /// @@ -171,12 +144,12 @@ pub fn map_identity(data: Dynamic) -> Result> { Ok(data) } -/// To `Result>` mapping function. +/// To Dynamic mapping function. #[inline(always)] -pub fn map_result( - data: Result>, +pub fn map_result( + data: Result>, ) -> Result> { - data.map(|v| v.into_dynamic()) + data } macro_rules! def_register { @@ -185,10 +158,10 @@ macro_rules! def_register { }; (imp $abi:ident : $($par:ident => $mark:ty => $param:ty => $clone:expr),*) => { // ^ function ABI type - // ^ function parameter generic type name (A, B, C etc.) - // ^ function parameter marker type (T, Ref or Mut) - // ^ function parameter actual type (T, &T or &mut T) - // ^ dereferencing function + // ^ function parameter generic type name (A, B, C etc.) + // ^ function parameter marker type (T, Ref or Mut) + // ^ function parameter actual type (T, &T or &mut T) + // ^ dereferencing function impl< $($par: Variant + Clone,)* @@ -213,30 +186,10 @@ macro_rules! def_register { $($par: Variant + Clone,)* #[cfg(feature = "sync")] - FN: Fn($($param),*) -> Dynamic + Send + Sync + 'static, - + FN: Fn($($param),*) -> Result> + Send + Sync + 'static, #[cfg(not(feature = "sync"))] - FN: Fn($($param),*) -> Dynamic + 'static, - > RegisterDynamicFn for Engine - { - fn register_dynamic_fn(&mut self, name: &str, f: FN) { - self.global_module.set_fn(name.to_string(), FnAccess::Public, - &[$(TypeId::of::<$par>()),*], - CallableFunction::$abi(make_func!(f : map_identity ; $($par => $clone),*)) - ); - } - } - - impl< - $($par: Variant + Clone,)* - - #[cfg(feature = "sync")] - FN: Fn($($param),*) -> Result> + Send + Sync + 'static, - #[cfg(not(feature = "sync"))] - FN: Fn($($param),*) -> Result> + 'static, - - RET: Variant + Clone - > RegisterResultFn for Engine + FN: Fn($($param),*) -> Result> + 'static, + > RegisterResultFn for Engine { fn register_result_fn(&mut self, name: &str, f: FN) { self.global_module.set_fn(name.to_string(), FnAccess::Public, diff --git a/src/lib.rs b/src/lib.rs index b4e71a83..df039436 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -91,7 +91,7 @@ mod utils; pub use any::Dynamic; pub use engine::Engine; pub use error::{ParseError, ParseErrorType}; -pub use fn_register::{RegisterDynamicFn, RegisterFn, RegisterResultFn}; +pub use fn_register::{RegisterFn, RegisterResultFn}; pub use module::Module; pub use parser::{AST, INT}; pub use result::EvalAltResult;