Merge register_result_fn and register_dynamic_fn.

This commit is contained in:
Stephen Chung 2020-05-22 13:09:17 +08:00
parent 3408086240
commit 2f0ab18b70
3 changed files with 40 additions and 91 deletions

View File

@ -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<EvalAltResult>>` | `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<EvalAltResult>>` | `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<Dynamic, Box<EvalAltResult>> {
Ok((42_i64).into()) // standard supported types can use 'into()'
}
fn main() -> Result<(), Box<EvalAltResult>>
@ -650,10 +649,10 @@ fn main() -> Result<(), Box<EvalAltResult>>
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::<i64>("get_an_any()")?;
let result = engine.eval::<i64>("get_any_value()")?;
println!("Answer: {}", result); // prints 42
@ -661,18 +660,15 @@ fn main() -> Result<(), Box<EvalAltResult>>
}
```
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<EvalAltResult>>`. `Box<EvalAltResult>` implements `From<&str>` and `From<String>` etc.
The function must return `Result<Dynamic, Box<EvalAltResult>>`. `Box<EvalAltResult>` implements `From<&str>` and `From<String>` etc.
and the error text gets converted into `Box<EvalAltResult::ErrorRuntime>`.
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<i64, Box<EvalAltResult>> {
// Function that may fail - the result type must be 'Dynamic'
fn safe_divide(x: i64, y: i64) -> Result<Dynamic, Box<EvalAltResult>> {
if y == 0 {
// Return an error if y is zero
Err("Division by zero!".into()) // short-cut to create Box<EvalAltResult::ErrorRuntime>
} else {
Ok(x / y)
Ok((x / y).into()) // convert result into 'Dynamic'
}
}

View File

@ -42,49 +42,22 @@ pub trait RegisterFn<FN, ARGS, RET> {
fn register_fn(&mut self, name: &str, f: FN);
}
/// Trait to register custom functions that return `Dynamic` values with the `Engine`.
pub trait RegisterDynamicFn<FN, ARGS> {
/// Register a custom function returning `Dynamic` values with the `Engine`.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// 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::<i64>("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<EvalAltResult>>` with the `Engine`.
pub trait RegisterResultFn<FN, ARGS, RET> {
/// Trait to register fallible custom functions returning `Result<Dynamic, Box<EvalAltResult>>` with the `Engine`.
pub trait RegisterResultFn<FN, ARGS> {
/// 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<i64, Box<EvalAltResult>> {
/// fn div(x: i64, y: i64) -> Result<Dynamic, Box<EvalAltResult>> {
/// if y == 0 {
/// // '.into()' automatically converts to 'Box<EvalAltResult::ErrorRuntime>'
/// Err("division by zero!".into())
/// } else {
/// Ok(x / y)
/// Ok((x / y).into())
/// }
/// }
///
@ -171,12 +144,12 @@ pub fn map_identity(data: Dynamic) -> Result<Dynamic, Box<EvalAltResult>> {
Ok(data)
}
/// To `Result<Dynamic, Box<EvalAltResult>>` mapping function.
/// To Dynamic mapping function.
#[inline(always)]
pub fn map_result<T: Variant + Clone>(
data: Result<T, Box<EvalAltResult>>,
pub fn map_result(
data: Result<Dynamic, Box<EvalAltResult>>,
) -> Result<Dynamic, Box<EvalAltResult>> {
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<T> or Mut<T>)
// ^ 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<T> or Mut<T>)
// ^ 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<Dynamic, Box<EvalAltResult>> + Send + Sync + 'static,
#[cfg(not(feature = "sync"))]
FN: Fn($($param),*) -> Dynamic + 'static,
> RegisterDynamicFn<FN, ($($mark,)*)> 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<RET, Box<EvalAltResult>> + Send + Sync + 'static,
#[cfg(not(feature = "sync"))]
FN: Fn($($param),*) -> Result<RET, Box<EvalAltResult>> + 'static,
RET: Variant + Clone
> RegisterResultFn<FN, ($($mark,)*), RET> for Engine
FN: Fn($($param),*) -> Result<Dynamic, Box<EvalAltResult>> + 'static,
> RegisterResultFn<FN, ($($mark,)*)> for Engine
{
fn register_result_fn(&mut self, name: &str, f: FN) {
self.global_module.set_fn(name.to_string(), FnAccess::Public,

View File

@ -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;