Implement variable resolver.

This commit is contained in:
Stephen Chung
2020-10-11 21:58:11 +08:00
parent 9d93dac8e7
commit fd5a932611
18 changed files with 511 additions and 237 deletions

View File

@@ -1,4 +1,4 @@
use rhai::{Engine, EvalAltResult, Scope, INT};
use rhai::{Engine, EvalAltResult, Position, Scope, INT};
#[test]
fn test_var_scope() -> Result<(), Box<EvalAltResult>> {
@@ -52,3 +52,41 @@ fn test_scope_eval() -> Result<(), Box<EvalAltResult>> {
Ok(())
}
#[test]
fn test_var_resolver() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
let mut scope = Scope::new();
scope.push("innocent", 1 as INT);
scope.push("chameleon", 123 as INT);
scope.push("DO_NOT_USE", 999 as INT);
engine.on_var(|name, _, scope, _| {
match name {
"MYSTIC_NUMBER" => Ok(Some((42 as INT).into())),
// Override a variable - make it not found even if it exists!
"DO_NOT_USE" => {
Err(EvalAltResult::ErrorVariableNotFound(name.to_string(), Position::none()).into())
}
// Silently maps 'chameleon' into 'innocent'.
"chameleon" => scope.get_value("innocent").map(Some).ok_or_else(|| {
EvalAltResult::ErrorVariableNotFound(name.to_string(), Position::none()).into()
}),
// Return Ok(None) to continue with the normal variable resolution process.
_ => Ok(None),
}
});
assert_eq!(
engine.eval_with_scope::<INT>(&mut scope, "MYSTIC_NUMBER")?,
42
);
assert_eq!(engine.eval_with_scope::<INT>(&mut scope, "chameleon")?, 1);
assert!(
matches!(*engine.eval_with_scope::<INT>(&mut scope, "DO_NOT_USE").expect_err("should error"),
EvalAltResult::ErrorVariableNotFound(n, _) if n == "DO_NOT_USE")
);
Ok(())
}