Refine docs and add custom syntax.
This commit is contained in:
@@ -7,9 +7,16 @@ use rhai::{
|
||||
fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
|
||||
let mut engine = Engine::new();
|
||||
|
||||
// Disable 'while' and make sure it still works with custom syntax
|
||||
engine.disable_symbol("while");
|
||||
engine.consume("while false {}").expect_err("should error");
|
||||
engine.consume("let while = 0")?;
|
||||
|
||||
engine
|
||||
.add_custom_syntax(
|
||||
&["do", "$ident$", "$block$", "while", "$expr$"],
|
||||
.register_custom_syntax(
|
||||
&[
|
||||
"do", "|", "$ident$", "|", "->", "$block$", "while", "$expr$",
|
||||
],
|
||||
1,
|
||||
|engine: &Engine,
|
||||
scope: &mut Scope,
|
||||
@@ -17,22 +24,19 @@ fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
|
||||
state: &mut EvalState,
|
||||
lib: &Module,
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
exprs: &[Expr],
|
||||
inputs: &[Expr],
|
||||
level: usize| {
|
||||
let var_name = match exprs.get(0).unwrap() {
|
||||
Expr::Variable(s) => (s.0).0.clone(),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let stmt = exprs.get(1).unwrap();
|
||||
let expr = exprs.get(2).unwrap();
|
||||
let var_name = inputs[0].get_variable_name().unwrap().to_string();
|
||||
let stmt = inputs.get(1).unwrap();
|
||||
let expr = inputs.get(2).unwrap();
|
||||
|
||||
scope.push(var_name, 0 as INT);
|
||||
|
||||
loop {
|
||||
engine.eval_expr_from_ast(scope, mods, state, lib, this_ptr, stmt, level)?;
|
||||
engine.eval_expression_tree(scope, mods, state, lib, this_ptr, stmt, level)?;
|
||||
|
||||
if !engine
|
||||
.eval_expr_from_ast(scope, mods, state, lib, this_ptr, expr, level)?
|
||||
.eval_expression_tree(scope, mods, state, lib, this_ptr, expr, level)?
|
||||
.as_bool()
|
||||
.map_err(|_| {
|
||||
EvalAltResult::ErrorBooleanArgMismatch(
|
||||
@@ -50,20 +54,24 @@ fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
*engine.add_custom_syntax(&["!"], 0, |_, _, _, _, _, _, _, _| Ok(().into())).expect_err("should error"),
|
||||
LexError::ImproperSymbol(s) if s == "!"
|
||||
));
|
||||
// 'while' is now a custom keyword so this it can no longer be a variable
|
||||
engine.consume("let while = 0").expect_err("should error");
|
||||
|
||||
assert_eq!(
|
||||
engine.eval::<INT>(
|
||||
r"
|
||||
do x { x += 1 } while x < 42;
|
||||
do |x| -> { x += 1 } while x < 42;
|
||||
x
|
||||
"
|
||||
)?,
|
||||
42
|
||||
);
|
||||
|
||||
// The first symbol must be an identifier
|
||||
assert!(matches!(
|
||||
*engine.register_custom_syntax(&["!"], 0, |_, _, _, _, _, _, _, _| Ok(().into())).expect_err("should error"),
|
||||
LexError::ImproperSymbol(s) if s == "!"
|
||||
));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
Reference in New Issue
Block a user