Add custom syntax test.

This commit is contained in:
Stephen Chung 2022-08-20 22:10:15 +08:00
parent 689ed48235
commit de3b7cbbee

View File

@ -21,8 +21,46 @@ fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
ParseErrorType::Reserved(err) if err == "while" ParseErrorType::Reserved(err) if err == "while"
)); ));
// Implement ternary operator
engine.register_custom_syntax( engine.register_custom_syntax(
&[ ["iff", "$expr$", "?", "$expr$", ":", "$expr$"],
false,
|context, inputs| match context.eval_expression_tree(&inputs[0])?.as_bool() {
Ok(true) => context.eval_expression_tree(&inputs[1]),
Ok(false) => context.eval_expression_tree(&inputs[2]),
Err(typ) => Err(Box::new(EvalAltResult::ErrorMismatchDataType(
"bool".to_string(),
typ.to_string(),
inputs[0].position(),
))),
},
)?;
assert_eq!(
engine.eval::<INT>(
"
let x = 42;
let y = iff x > 40 ? 0 : 123;
y
"
)?,
0
);
assert_eq!(
engine.eval::<INT>(
"
let x = 42;
let y = iff x == 0 ? 0 : 123;
y
"
)?,
123
);
// Custom syntax
engine.register_custom_syntax(
[
"exec", "[", "$ident$", "$symbol$", "$int$", "]", "->", "$block$", "while", "$expr$", "exec", "[", "$ident$", "$symbol$", "$int$", "]", "->", "$block$", "while", "$expr$",
], ],
true, true,