Fix bug in try block.

This commit is contained in:
Stephen Chung 2022-01-24 08:34:21 +08:00
parent 922931f51d
commit 8d34ffb9f5
4 changed files with 83 additions and 4 deletions

View File

@ -1,9 +1,14 @@
Rhai Release Notes
==================
Version 1.5.0
Version 1.4.2
=============
Bug fixes
---------
* Variables introduced inside `try` blocks are now properly cleaned up upon an exception.
Version 1.4.1
=============

View File

@ -35,7 +35,7 @@ impl Engine {
state.scope_level += 1;
}
let mut result = Dynamic::UNIT;
let mut result = Ok(Dynamic::UNIT);
for stmt in statements {
let _mods_len = global.num_imports();
@ -49,7 +49,11 @@ impl Engine {
stmt,
restore_orig_state,
level,
)?;
);
if result.is_err() {
break;
}
#[cfg(not(feature = "no_module"))]
if matches!(stmt, Stmt::Import(_, _, _)) {
@ -89,7 +93,7 @@ impl Engine {
state.always_search_scope = orig_always_search_scope;
}
Ok(result)
result
}
/// Evaluate an op-assignment statement.

View File

@ -302,3 +302,68 @@ fn test_get_set_collection() -> Result<(), Box<EvalAltResult>> {
Ok(())
}
#[cfg(not(feature = "no_index"))]
#[test]
fn test_get_set_indexer() -> Result<(), Box<EvalAltResult>> {
type MyMap = std::collections::BTreeMap<String, INT>;
let mut engine = Engine::new();
engine
.register_type_with_name::<MyMap>("MyMap")
.register_fn("new_map", || MyMap::new())
.register_indexer_get_result(|map: &mut MyMap, index: &str| {
map.get(index)
.cloned()
.ok_or_else(|| format!("Index `{}` not found!", index).into())
})
.register_indexer_set(|map: &mut MyMap, index: &str, value: INT| {
map.insert(index.to_string(), value);
})
.register_fn("to_string", |map: &mut MyMap| format!("{:?}", map));
assert_eq!(
engine.eval::<INT>(
r#"
let my_map = new_map();
my_map["eggs"] = 42;
my_map["eggs"]
"#,
)?,
42
);
assert!(engine
.eval::<INT>(
r#"
let my_map = new_map();
my_map["eggs"] = 42;
my_map["not_found"]
"#,
)
.is_err());
assert_eq!(
engine.eval::<INT>(
r#"
let my_map = new_map();
my_map["eggs"] = 42;
try {
let eggs = my_map["eggs"];
let eggs = my_map["not found"];
}
catch(x)
{
print("Not found!");
}
my_map["eggs"]
"#,
)?,
42
);
Ok(())
}

View File

@ -29,6 +29,11 @@ fn test_try_catch() -> Result<(), Box<EvalAltResult>> {
123
);
assert_eq!(
engine.eval::<INT>("let x = 42; try { let y = 123; print(x/0); } catch { x = 0 } x")?,
0
);
#[cfg(not(feature = "no_function"))]
assert_eq!(
engine.eval::<INT>(