rhai/tests/optimizer.rs

72 lines
2.1 KiB
Rust
Raw Normal View History

#![cfg(not(feature = "no_optimize"))]
2020-10-08 17:00:01 +02:00
use rhai::{Engine, EvalAltResult, OptimizationLevel, RegisterFn, INT};
#[test]
2020-06-13 15:57:46 +02:00
fn test_optimizer_run() -> Result<(), Box<EvalAltResult>> {
fn run_test(engine: &mut Engine) -> Result<(), Box<EvalAltResult>> {
assert_eq!(engine.eval::<INT>(r"if true { 42 } else { 123 }")?, 42);
assert_eq!(
engine.eval::<INT>(r"if 1 == 1 || 2 > 3 { 42 } else { 123 }")?,
42
);
assert_eq!(
engine.eval::<INT>(r#"const abc = "hello"; if abc < "foo" { 42 } else { 123 }"#)?,
123
);
Ok(())
}
let mut engine = Engine::new();
engine.set_optimization_level(OptimizationLevel::None);
run_test(&mut engine)?;
engine.set_optimization_level(OptimizationLevel::Simple);
run_test(&mut engine)?;
engine.set_optimization_level(OptimizationLevel::Full);
run_test(&mut engine)?;
// Override == operator
engine.register_fn("==", |_x: INT, _y: INT| false);
engine.set_optimization_level(OptimizationLevel::Simple);
assert_eq!(
engine.eval::<INT>(r"if 1 == 1 || 2 > 3 { 42 } else { 123 }")?,
123
);
engine.set_optimization_level(OptimizationLevel::Full);
assert_eq!(
engine.eval::<INT>(r"if 1 == 1 || 2 > 3 { 42 } else { 123 }")?,
123
);
Ok(())
}
2020-06-13 15:57:46 +02:00
#[test]
fn test_optimizer_parse() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
engine.set_optimization_level(OptimizationLevel::Simple);
let ast = engine.compile("{ const DECISION = false; if DECISION { 42 } else { 123 } }")?;
2020-12-12 08:57:55 +01:00
assert!(format!("{:?}", ast).starts_with(r#"AST { statements: [Block([Const(IdentX { name: "DECISION", pos: 1:9 }, Some(Unit(0:0)), false, 1:3), Expr(IntegerConstant(123, 1:53))], 1:1)]"#));
let ast = engine.compile("if 1 == 2 { 42 }")?;
2020-06-13 15:57:46 +02:00
2020-12-12 08:57:55 +01:00
assert!(format!("{:?}", ast).starts_with("AST { statements: [], functions: Module("));
2020-06-13 15:57:46 +02:00
engine.set_optimization_level(OptimizationLevel::Full);
let ast = engine.compile("abs(-42)")?;
2020-06-13 15:57:46 +02:00
2020-12-12 08:57:55 +01:00
assert!(format!("{:?}", ast).starts_with(r"AST { statements: [Expr(IntegerConstant(42, 1:1))]"));
2020-06-13 15:57:46 +02:00
Ok(())
}