2020-08-05 11:02:11 +02:00
|
|
|
use rhai::{Engine, EvalAltResult, EvalContext, Expression, ParseErrorType, Scope, INT};
|
2020-07-09 13:54:28 +02:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
|
|
|
|
let mut engine = Engine::new();
|
|
|
|
|
2020-07-17 08:50:23 +02:00
|
|
|
engine.consume("while false {}")?;
|
|
|
|
|
2020-07-10 16:01:47 +02:00
|
|
|
// Disable 'while' and make sure it still works with custom syntax
|
|
|
|
engine.disable_symbol("while");
|
2020-07-17 08:50:23 +02:00
|
|
|
assert!(matches!(
|
|
|
|
*engine.compile("while false {}").expect_err("should error").0,
|
|
|
|
ParseErrorType::Reserved(err) if err == "while"
|
|
|
|
));
|
|
|
|
assert!(matches!(
|
|
|
|
*engine.compile("let while = 0").expect_err("should error").0,
|
|
|
|
ParseErrorType::Reserved(err) if err == "while"
|
|
|
|
));
|
2020-07-10 16:01:47 +02:00
|
|
|
|
2020-08-05 11:02:11 +02:00
|
|
|
engine.register_custom_syntax(
|
|
|
|
&[
|
|
|
|
"do", "|", "$ident$", "|", "->", "$block$", "while", "$expr$",
|
|
|
|
],
|
|
|
|
1,
|
|
|
|
|engine: &Engine, context: &mut EvalContext, scope: &mut Scope, 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();
|
2020-07-09 13:54:28 +02:00
|
|
|
|
2020-08-05 11:02:11 +02:00
|
|
|
scope.push(var_name, 0 as INT);
|
2020-07-09 13:54:28 +02:00
|
|
|
|
2020-08-05 11:02:11 +02:00
|
|
|
loop {
|
|
|
|
engine.eval_expression_tree(context, scope, stmt)?;
|
2020-07-09 13:54:28 +02:00
|
|
|
|
2020-08-05 11:02:11 +02:00
|
|
|
if !engine
|
|
|
|
.eval_expression_tree(context, scope, expr)?
|
|
|
|
.as_bool()
|
|
|
|
.map_err(|_| {
|
|
|
|
EvalAltResult::ErrorBooleanArgMismatch("do-while".into(), expr.position())
|
|
|
|
})?
|
|
|
|
{
|
|
|
|
break;
|
2020-07-09 13:54:28 +02:00
|
|
|
}
|
2020-08-05 11:02:11 +02:00
|
|
|
}
|
2020-07-09 13:54:28 +02:00
|
|
|
|
2020-08-05 11:02:11 +02:00
|
|
|
Ok(().into())
|
|
|
|
},
|
|
|
|
)?;
|
2020-07-09 13:54:28 +02:00
|
|
|
|
2020-07-10 16:01:47 +02:00
|
|
|
// 'while' is now a custom keyword so this it can no longer be a variable
|
|
|
|
engine.consume("let while = 0").expect_err("should error");
|
2020-07-09 13:54:28 +02:00
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
engine.eval::<INT>(
|
|
|
|
r"
|
2020-07-10 16:01:47 +02:00
|
|
|
do |x| -> { x += 1 } while x < 42;
|
2020-07-09 13:54:28 +02:00
|
|
|
x
|
|
|
|
"
|
|
|
|
)?,
|
|
|
|
42
|
|
|
|
);
|
|
|
|
|
2020-07-10 16:01:47 +02:00
|
|
|
// The first symbol must be an identifier
|
2020-08-05 11:02:11 +02:00
|
|
|
assert_eq!(
|
|
|
|
*engine
|
|
|
|
.register_custom_syntax(&["!"], 0, |_, _, _, _| Ok(().into()))
|
|
|
|
.expect_err("should error")
|
|
|
|
.0,
|
|
|
|
ParseErrorType::BadInput("Improper symbol for custom syntax: '!'".to_string())
|
|
|
|
);
|
2020-07-10 16:01:47 +02:00
|
|
|
|
2020-07-09 13:54:28 +02:00
|
|
|
Ok(())
|
|
|
|
}
|