Refine docs and API.

This commit is contained in:
Stephen Chung 2020-07-06 13:01:57 +08:00
parent d9fe6a1980
commit 3e45d5d9a5
12 changed files with 51 additions and 37 deletions

View File

@ -104,9 +104,10 @@ The Rhai Scripting Language
4. [Side-Effect Considerations](engine/optimize/side-effects.md)
5. [Volatility Considerations](engine/optimize/volatility.md)
6. [Subtle Semantic Changes](engine/optimize/semantics.md)
4. [Disable Keywords and/or Operators](engine/disable.md)
5. [Custom Operators](engine/custom-op.md)
6. [Eval Statement](language/eval.md)
4. [Low-Level API](rust/register-raw.md)
5. [Disable Keywords and/or Operators](engine/disable.md)
6. [Custom Operators](engine/custom-op.md)
7. [Eval Statement](language/eval.md)
9. [Appendix](appendix/index.md)
1. [Keywords](appendix/keywords.md)
2. [Operators](appendix/operators.md)

View File

@ -15,7 +15,7 @@ Operators
| `<<` | Left bit-shift | Yes | Left |
| `&` | Bit-wise _And_, Boolean _And_ | Yes | Left |
| <code>\|</code> | Bit-wise _Or_, Boolean _Or_ | Yes | Left |
| `^` | Bit-wise _Xor_ | Yes | Left |
| `^` | Bit-wise _Xor_, Boolean _Xor_ | Yes | Left |
| `==` | Equals to | Yes | Left |
| `~=` | Not equals to | Yes | Left |
| `>` | Greater than | Yes | Left |

View File

@ -18,8 +18,8 @@ use rhai::{Engine, RegisterFn};
let mut engine = Engine::new();
// Register a custom operator called 'foo' and give it
// a precedence of 140 (i.e. between +|- and *|/)
engine.register_custom_operator("foo", 140).unwrap();
// a precedence of 160 (i.e. between +|- and *|/)
engine.register_custom_operator("foo", 160).unwrap();
// Register the implementation of the customer operator as a function
engine.register_fn("foo", |x: i64, y: i64| (x * y) - (x + y));
@ -49,7 +49,7 @@ Therefore, the following are equivalent (assuming `foo` has been registered as a
A script using custom operators can always be pre-processed, via a pre-processor application,
into a syntax that uses the corresponding function calls.
Using `Engine::register_custom_operator` merely enables a convenient short-cut.
Using `Engine::register_custom_operator` merely enables a convenient shortcut.
Must Follow Variable Naming
@ -71,7 +71,7 @@ All custom operators must be _binary_ (i.e. they take two operands).
_Unary_ custom operators are not supported.
```rust
engine.register_custom_operator("foo", 140).unwrap();
engine.register_custom_operator("foo", 160).unwrap();
engine.register_fn("foo", |x: i64| x * x);
@ -91,12 +91,12 @@ The following _precedence table_ show the built-in precedence of standard Rhai o
| Assignments | `=`, `+=`, `-=`, `*=`, `/=`, `~=`, `%=`,<br/>`<<=`, `>>=`, `&=`, <code>\|=</code>, `^=` | 0 |
| Logic and bit masks | <code>\|\|</code>, <code>\|</code>, `^` | 30 |
| Logic and bit masks | `&`, `&&` | 60 |
| Comparisons | `==`, `!=`, `>`, `>=`, `<`, `<=` | 90 |
| | `in` | 110 |
| Arithmetic | `+`, `-` | 130 |
| Arithmetic | `*`, `/`, `~` | 160 |
| Bit-shifts | `<<`, `>>` | 190 |
| Arithmetic | `%` | 210 |
| Comparisons | `==`, `!=` | 90 |
| Comparisons | `>`, `>=`, `<`, `<=` | 110 |
| | `in` | 130 |
| Arithmetic | `+`, `-` | 150 |
| Arithmetic | `*`, `/`, `~`, `%` | 180 |
| Bit-shifts | `<<`, `>>` | 210 |
| Object | `.` _(binds to right)_ | 240 |
| _Others_ | | 0 |

View File

@ -20,6 +20,7 @@
[`Engine`]: {{rootUrl}}/engine/hello-world.md
[traits]: {{rootUrl}}/rust/traits.md
[`private`]: {{rootUrl}}/engine/call-fn.md
[`call_fn`]: {{rootUrl}}/engine/call-fn.md
[`Func`]: {{rootUrl}}/engine/func.md
[`AST`]: {{rootUrl}}/engine/compile.md
[`eval_expression`]: {{rootUrl}}/engine/expressions.md

View File

@ -16,7 +16,7 @@ use rhai::RegisterResultFn; // use 'RegisterResultFn' trait
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>
Err("Division by zero!".into()) // shortcut to create Box<EvalAltResult::ErrorRuntime>
} else {
Ok((x / y).into()) // convert result into 'Dynamic'
}

View File

@ -1325,8 +1325,7 @@ impl Engine {
args: A,
) -> Result<T, Box<EvalAltResult>> {
let mut arg_values = args.into_vec();
let result =
self.call_fn_dynamic_raw(scope, ast.lib(), name, &mut None, arg_values.as_mut())?;
let result = self.call_fn_dynamic_raw(scope, ast, name, &mut None, arg_values.as_mut())?;
let typ = self.map_type_name(result.type_name());
@ -1370,18 +1369,18 @@ impl Engine {
/// scope.push("foo", 42_i64);
///
/// // Call the script-defined function
/// let result = engine.call_fn_dynamic(&mut scope, ast.into(), "add", None, [ String::from("abc").into(), 123_i64.into() ])?;
/// let result = engine.call_fn_dynamic(&mut scope, &ast, "add", None, [ String::from("abc").into(), 123_i64.into() ])?;
/// // ^^^^ no 'this' pointer
/// assert_eq!(result.cast::<i64>(), 168);
///
/// let result = engine.call_fn_dynamic(&mut scope, ast.into(), "add1", None, [ String::from("abc").into() ])?;
/// let result = engine.call_fn_dynamic(&mut scope, &ast, "add1", None, [ String::from("abc").into() ])?;
/// assert_eq!(result.cast::<i64>(), 46);
///
/// let result = engine.call_fn_dynamic(&mut scope, ast.into(), "bar", None, [])?;
/// let result = engine.call_fn_dynamic(&mut scope, &ast, "bar", None, [])?;
/// assert_eq!(result.cast::<i64>(), 21);
///
/// let mut value: Dynamic = 1_i64.into();
/// let result = engine.call_fn_dynamic(&mut scope, ast.into(), "action", Some(&mut value), [ 41_i64.into() ])?;
/// let result = engine.call_fn_dynamic(&mut scope, &ast, "action", Some(&mut value), [ 41_i64.into() ])?;
/// // ^^^^^^^^^^^^^^^^ binding the 'this' pointer
/// assert_eq!(value.as_int().unwrap(), 42);
/// # }
@ -1392,7 +1391,7 @@ impl Engine {
pub fn call_fn_dynamic(
&self,
scope: &mut Scope,
lib: &Module,
lib: impl AsRef<Module>,
name: &str,
mut this_ptr: Option<&mut Dynamic>,
mut arg_values: impl AsMut<[Dynamic]>,
@ -1412,11 +1411,12 @@ impl Engine {
pub(crate) fn call_fn_dynamic_raw(
&self,
scope: &mut Scope,
lib: &Module,
lib: impl AsRef<Module>,
name: &str,
this_ptr: &mut Option<&mut Dynamic>,
arg_values: &mut [Dynamic],
) -> Result<Dynamic, Box<EvalAltResult>> {
let lib = lib.as_ref();
let mut args: StaticVec<_> = arg_values.iter_mut().collect();
let fn_def =
get_script_function_by_signature(lib, name, args.len(), true).ok_or_else(|| {

View File

@ -15,8 +15,8 @@ use crate::stdlib::{boxed::Box, string::ToString};
pub trait Func<ARGS, RET> {
type Output;
/// Create a Rust anonymous function from an [`AST`].
/// The `Engine` and [`AST`] are consumed and basically embedded into the closure.
/// Create a Rust anonymous function from an `AST`.
/// The `Engine` and `AST` are consumed and basically embedded into the closure.
///
/// # Examples
///

View File

@ -62,7 +62,7 @@
//! | `only_i32` | Set the system integer type to `i32` and disable all other integer types. `INT` is set to `i32`. |
//! | `only_i64` | Set the system integer type to `i64` and disable all other integer types. `INT` is set to `i64`. |
//! | `no_std` | Build for `no-std`. Notice that additional dependencies will be pulled in to replace `std` features. |
//! | `sync` | Restrict all values types to those that are `Send + Sync`. Under this feature, `Engine`, `Scope` and [`AST`] are all `Send + Sync`. |
//! | `sync` | Restrict all values types to those that are `Send + Sync`. Under this feature, `Engine`, `Scope` and `AST` are all `Send + Sync`. |
//! | `serde` | Enable serialization/deserialization via `serde`. Notice that the [`serde`](https://crates.io/crates/serde) crate will be pulled in together with its dependencies. |
//! | `internals` | Expose internal data structures (beware they may be volatile from version to version). |
//!

View File

@ -102,6 +102,12 @@ impl Clone for Module {
}
}
impl AsRef<Module> for Module {
fn as_ref(&self) -> &Module {
self
}
}
impl Module {
/// Create a new module.
///

View File

@ -66,14 +66,14 @@ impl AST {
/// Get the statements.
#[cfg(not(feature = "internals"))]
pub(crate) fn statements(&self) -> &Vec<Stmt> {
pub(crate) fn statements(&self) -> &[Stmt] {
&self.0
}
/// Get the statements.
#[cfg(feature = "internals")]
#[deprecated(note = "this method is volatile and may change")]
pub fn statements(&self) -> &Vec<Stmt> {
pub fn statements(&self) -> &[Stmt] {
&self.0
}
@ -298,9 +298,15 @@ impl Add<Self> for &AST {
}
}
impl<'a> From<&'a AST> for &'a Module {
fn from(ast: &'a AST) -> Self {
ast.lib()
impl AsRef<[Stmt]> for AST {
fn as_ref(&self) -> &[Stmt] {
self.statements()
}
}
impl AsRef<Module> for AST {
fn as_ref(&self) -> &Module {
self.lib()
}
}

View File

@ -218,8 +218,8 @@ impl Engine {
/// let mut engine = Engine::new();
///
/// // Register a custom operator called 'foo' and give it
/// // a precedence of 140 (i.e. between +|- and *|/).
/// engine.register_custom_operator("foo", 140).unwrap();
/// // a precedence of 160 (i.e. between +|- and *|/).
/// engine.register_custom_operator("foo", 160).unwrap();
///
/// // Register a binary function named 'foo'
/// engine.register_fn("foo", |x: i64, y: i64| (x * y) - (x + y));

View File

@ -24,8 +24,8 @@ fn test_tokens_custom_operator() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
// Register a custom operator called `foo` and give it
// a precedence of 140 (i.e. between +|- and *|/).
engine.register_custom_operator("foo", 140).unwrap();
// a precedence of 160 (i.e. between +|- and *|/).
engine.register_custom_operator("foo", 160).unwrap();
// Register a binary function named `foo`
engine.register_fn("foo", |x: INT, y: INT| (x * y) - (x + y));