Simplify custom syntax.

This commit is contained in:
Stephen Chung 2020-07-22 13:08:51 +08:00
parent 187824e684
commit 35374f5b3b
6 changed files with 62 additions and 76 deletions

View File

@ -16,6 +16,11 @@ New features
* `x.call(f, ...)` allows binding `x` to `this` for the function referenced by the function pointer `f`.
* Anonymous functions in the syntax of a closure, e.g. `|x, y, z| x + y - z`.
Breaking changes
----------------
* Function signature for defining custom syntax is simplified.
Version 0.17.0
==============

View File

@ -126,32 +126,21 @@ Any custom syntax must include an _implementation_ of it.
The function signature of an implementation is:
```rust
Fn(
engine: &Engine,
scope: &mut Scope,
mods: &mut Imports,
state: &mut State,
lib: &Module,
this_ptr: &mut Option<&mut Dynamic>,
inputs: &[Expression],
level: usize
) -> Result<Dynamic, Box<EvalAltResult>>
Fn(engine: &Engine, context: &mut EvalContext, scope: &mut Scope, inputs: &[Expression])
-> Result<Dynamic, Box<EvalAltResult>>
```
where:
* `engine : &Engine` - reference to the current [`Engine`].
* `scope : &mut Scope` - mutable reference to the current [`Scope`]; variables can be added to it.
* `mods : &mut Imports` - mutable reference to the current collection of imported [`Module`]'s; **do not touch**.
* `state : &mut State` - mutable reference to the current evaluation state; **do not touch**.
* `lib : &Module` - reference to the current collection of script-defined functions.
* `this_ptr : &mut Option<&mut Dynamic>` - mutable reference to the current binding of the `this` pointer; **do not touch**.
* `inputs : &[Expression]` - a list of input expression trees.
* `level : usize` - the current function call level.
* `engine: &Engine` - reference to the current [`Engine`].
* `context: &mut EvalContext` - mutable reference to the current evaluation _context_; **do not touch**.
* `scope: &mut Scope` - mutable reference to the current [`Scope`]; variables can be added to it.
* `inputs: &[Expression]` - a list of input expression trees.
There are a lot of parameters, most of which should not be touched or Bad Things Happen™.
They represent the running _content_ of a script evaluation and should simply be passed
straight-through the the [`Engine`].
#### WARNING - Lark's Vomit
The `context` parameter contains the evaluation _context_ and should not be touched or Bad Things Happen™.
It should simply be passed straight-through the the [`Engine`].
### Access Arguments
@ -172,7 +161,7 @@ Use the `engine::eval_expression_tree` method to evaluate an expression tree.
```rust
let expr = inputs.get(0).unwrap();
let result = engine.eval_expression_tree(scope, mods, state, lib, this_ptr, expr, level)?;
let result = engine.eval_expression_tree(context, scope, expr)?;
```
As can be seem above, most arguments are simply passed straight-through to `engine::eval_expression_tree`.
@ -210,13 +199,9 @@ The syntax is passed simply as a slice of `&str`.
// Custom syntax implementation
fn implementation_func(
engine: &Engine,
context: &mut EvalContext,
scope: &mut Scope,
mods: &mut Imports,
state: &mut State,
lib: &Module,
this_ptr: &mut Option<&mut Dynamic>,
inputs: &[Expression],
level: usize
inputs: &[Expression]
) -> Result<Dynamic, Box<EvalAltResult>> {
let var_name = inputs[0].get_variable_name().unwrap().to_string();
let stmt = inputs.get(1).unwrap();
@ -227,15 +212,12 @@ fn implementation_func(
loop {
// Evaluate the statement block
engine.eval_expression_tree(scope, mods, state, lib, this_ptr, stmt, level)?;
engine.eval_expression_tree(context, scope, stmt)?;
// Evaluate the condition expression
let stop = !engine
.eval_expression_tree(scope, mods, state, lib, this_ptr, condition, level)?
.as_bool()
.map_err(|_| EvalAltResult::ErrorBooleanArgMismatch(
"do-while".into(), expr.position()
))?;
let stop = !engine.eval_expression_tree(context, scope, condition)?
.as_bool().map_err(|_| EvalAltResult::ErrorBooleanArgMismatch(
"do-while".into(), expr.position()))?;
if stop {
break;

View File

@ -18,7 +18,7 @@ use crate::utils::StaticVec;
use crate::parser::FLOAT;
#[cfg(feature = "internals")]
use crate::syntax::CustomSyntax;
use crate::syntax::{CustomSyntax, EvalContext};
use crate::stdlib::{
any::{type_name, TypeId},
@ -1738,15 +1738,19 @@ impl Engine {
#[deprecated(note = "this method is volatile and may change")]
pub fn eval_expression_tree(
&self,
context: &mut EvalContext,
scope: &mut Scope,
mods: &mut Imports,
state: &mut State,
lib: &Module,
this_ptr: &mut Option<&mut Dynamic>,
expr: &Expression,
level: usize,
) -> Result<Dynamic, Box<EvalAltResult>> {
self.eval_expr(scope, mods, state, lib, this_ptr, expr.expr(), level)
self.eval_expr(
scope,
context.mods,
context.state,
context.lib,
context.this_ptr,
expr.expr(),
context.level,
)
}
/// Evaluate an expression
@ -2215,7 +2219,14 @@ impl Engine {
Expr::Custom(x) => {
let func = (x.0).1.as_ref();
let ep: StaticVec<_> = (x.0).0.iter().map(|e| e.into()).collect();
func(self, scope, mods, state, lib, this_ptr, ep.as_ref(), level)
let mut context = EvalContext {
mods,
state,
lib,
this_ptr,
level,
};
func(self, &mut context, scope, ep.as_ref())
}
_ => unreachable!(),

View File

@ -171,6 +171,10 @@ pub use parser::{CustomExpr, Expr, ReturnType, ScriptFnDef, Stmt};
#[deprecated(note = "this type is volatile and may change")]
pub use engine::{Expression, Imports, State as EvalState};
#[cfg(feature = "internals")]
#[deprecated(note = "this type is volatile and may change")]
pub use syntax::EvalContext;
#[cfg(feature = "internals")]
#[deprecated(note = "this type is volatile and may change")]
pub use module::ModuleRef;

View File

@ -22,26 +22,13 @@ use crate::stdlib::{
#[cfg(not(feature = "sync"))]
pub type FnCustomSyntaxEval = dyn Fn(
&Engine,
&mut EvalContext,
&mut Scope,
&mut Imports,
&mut State,
&Module,
&mut Option<&mut Dynamic>,
&[Expression],
usize,
) -> Result<Dynamic, Box<EvalAltResult>>;
/// A general function trail object.
#[cfg(feature = "sync")]
pub type FnCustomSyntaxEval = dyn Fn(
&Engine,
&mut Scope,
&mut Imports,
&mut State,
&Module,
&mut Option<&mut Dynamic>,
&[Expression],
usize,
) -> Result<Dynamic, Box<EvalAltResult>>
pub type FnCustomSyntaxEval = dyn Fn(&Engine, &mut EvalContext, &mut Scope, &[Expression]) -> Result<Dynamic, Box<EvalAltResult>>
+ Send
+ Sync;
@ -58,6 +45,14 @@ impl fmt::Debug for CustomSyntax {
}
}
pub struct EvalContext<'a, 'b: 'a, 's, 'm, 't, 'd: 't> {
pub(crate) mods: &'a mut Imports<'b>,
pub(crate) state: &'s mut State,
pub(crate) lib: &'m Module,
pub(crate) this_ptr: &'t mut Option<&'d mut Dynamic>,
pub(crate) level: usize,
}
impl Engine {
pub fn register_custom_syntax<S: AsRef<str> + ToString>(
&mut self,
@ -65,13 +60,9 @@ impl Engine {
scope_delta: isize,
func: impl Fn(
&Engine,
&mut EvalContext,
&mut Scope,
&mut Imports,
&mut State,
&Module,
&mut Option<&mut Dynamic>,
&[Expression],
usize,
) -> Result<Dynamic, Box<EvalAltResult>>
+ SendSync
+ 'static,

View File

@ -1,8 +1,5 @@
#![cfg(feature = "internals")]
use rhai::{
Dynamic, Engine, EvalAltResult, EvalState, Expression, Imports, LexError, Module, ParseError,
ParseErrorType, Scope, INT,
};
use rhai::{Engine, EvalAltResult, EvalContext, Expression, LexError, ParseErrorType, Scope, INT};
#[test]
fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
@ -28,13 +25,9 @@ fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
],
1,
|engine: &Engine,
context: &mut EvalContext,
scope: &mut Scope,
mods: &mut Imports,
state: &mut EvalState,
lib: &Module,
this_ptr: &mut Option<&mut Dynamic>,
inputs: &[Expression],
level: usize| {
inputs: &[Expression]| {
let var_name = inputs[0].get_variable_name().unwrap().to_string();
let stmt = inputs.get(1).unwrap();
let expr = inputs.get(2).unwrap();
@ -42,10 +35,10 @@ fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
scope.push(var_name, 0 as INT);
loop {
engine.eval_expression_tree(scope, mods, state, lib, this_ptr, stmt, level)?;
engine.eval_expression_tree(context, scope, stmt)?;
if !engine
.eval_expression_tree(scope, mods, state, lib, this_ptr, expr, level)?
.eval_expression_tree(context, scope, expr)?
.as_bool()
.map_err(|_| {
EvalAltResult::ErrorBooleanArgMismatch(
@ -78,7 +71,7 @@ fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
// The first symbol must be an identifier
assert!(matches!(
*engine.register_custom_syntax(&["!"], 0, |_, _, _, _, _, _, _, _| Ok(().into())).expect_err("should error"),
*engine.register_custom_syntax(&["!"], 0, |_, _, _, _| Ok(().into())).expect_err("should error"),
LexError::ImproperSymbol(s) if s == "!"
));