Encapsulate FunctionsLib to hold script-defined functions.

This commit is contained in:
Stephen Chung
2020-03-26 20:26:05 +08:00
parent 8679982b4b
commit 56df5c49c8
6 changed files with 89 additions and 65 deletions

View File

@@ -180,16 +180,15 @@ fn optimize_stmt<'a>(stmt: Stmt, state: &mut State<'a>, preserve_result: bool) -
// Optimize each statement in the block
let mut result: Vec<_> = block
.into_iter()
.map(|stmt| {
if let Stmt::Const(name, value, pos) = stmt {
// Add constant into the state
.map(|stmt| match stmt {
// Add constant into the state
Stmt::Const(name, value, pos) => {
state.push_constant(&name, *value);
state.set_dirty();
Stmt::Noop(pos) // No need to keep constants
} else {
// Optimize the statement
optimize_stmt(stmt, state, preserve_result)
}
// Optimize the statement
_ => optimize_stmt(stmt, state, preserve_result),
})
.collect();
@@ -445,7 +444,7 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr {
&& args.iter().all(|expr| expr.is_constant()) // all arguments are constants
=> {
// First search in script-defined functions (can override built-in)
if state.engine.script_functions.binary_search_by(|f| f.compare(&id, args.len())).is_ok() {
if state.engine.fn_lib.has_function(&id, args.len()) {
// A script-defined function overrides the built-in function - do not make the call
return Expr::FunctionCall(id, args.into_iter().map(|a| optimize_expr(a, state)).collect(), def_value, pos);
}