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

View File

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

View File

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

View File

@ -22,26 +22,13 @@ use crate::stdlib::{
#[cfg(not(feature = "sync"))] #[cfg(not(feature = "sync"))]
pub type FnCustomSyntaxEval = dyn Fn( pub type FnCustomSyntaxEval = dyn Fn(
&Engine, &Engine,
&mut EvalContext,
&mut Scope, &mut Scope,
&mut Imports,
&mut State,
&Module,
&mut Option<&mut Dynamic>,
&[Expression], &[Expression],
usize,
) -> Result<Dynamic, Box<EvalAltResult>>; ) -> Result<Dynamic, Box<EvalAltResult>>;
/// A general function trail object. /// A general function trail object.
#[cfg(feature = "sync")] #[cfg(feature = "sync")]
pub type FnCustomSyntaxEval = dyn Fn( pub type FnCustomSyntaxEval = dyn Fn(&Engine, &mut EvalContext, &mut Scope, &[Expression]) -> Result<Dynamic, Box<EvalAltResult>>
&Engine,
&mut Scope,
&mut Imports,
&mut State,
&Module,
&mut Option<&mut Dynamic>,
&[Expression],
usize,
) -> Result<Dynamic, Box<EvalAltResult>>
+ Send + Send
+ Sync; + 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 { impl Engine {
pub fn register_custom_syntax<S: AsRef<str> + ToString>( pub fn register_custom_syntax<S: AsRef<str> + ToString>(
&mut self, &mut self,
@ -65,13 +60,9 @@ impl Engine {
scope_delta: isize, scope_delta: isize,
func: impl Fn( func: impl Fn(
&Engine, &Engine,
&mut EvalContext,
&mut Scope, &mut Scope,
&mut Imports,
&mut State,
&Module,
&mut Option<&mut Dynamic>,
&[Expression], &[Expression],
usize,
) -> Result<Dynamic, Box<EvalAltResult>> ) -> Result<Dynamic, Box<EvalAltResult>>
+ SendSync + SendSync
+ 'static, + 'static,

View File

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