Encapsulate environment in ScriptFnDef.

This commit is contained in:
Stephen Chung 2020-10-13 09:38:14 +08:00
parent 0b4129fb98
commit 3c7805d514
5 changed files with 35 additions and 48 deletions

View File

@ -1611,10 +1611,10 @@ impl Engine {
// Module-qualified function call // Module-qualified function call
Expr::FnCall(x) if x.1.is_some() => { Expr::FnCall(x) if x.1.is_some() => {
let ((name, _, capture, pos), modules, hash, args_expr, def_val) = x.as_ref(); let ((name, _, _, pos), modules, hash, args_expr, def_val) = x.as_ref();
self.make_qualified_function_call( self.make_qualified_function_call(
scope, mods, state, lib, this_ptr, modules, name, args_expr, *def_val, *hash, scope, mods, state, lib, this_ptr, modules, name, args_expr, *def_val, *hash,
*capture, level, level,
) )
.map_err(|err| err.fill_position(*pos)) .map_err(|err| err.fill_position(*pos))
} }

View File

@ -384,9 +384,27 @@ impl Engine {
}), }),
); );
// Merge in encapsulated environment, if any
let mut lib_merged;
let unified_lib = if let Some(ref env_lib) = fn_def.lib {
if !lib.is_empty() {
// In the special case of the main script not defining any function
env_lib
} else {
lib_merged = lib.clone();
lib_merged.merge(env_lib);
&lib_merged
}
} else {
lib
};
// Evaluate the function at one higher level of call depth // Evaluate the function at one higher level of call depth
let stmt = &fn_def.body;
let result = self let result = self
.eval_stmt(scope, mods, state, lib, this_ptr, &fn_def.body, level + 1) .eval_stmt(scope, mods, state, unified_lib, this_ptr, stmt, level + 1)
.or_else(|err| match *err { .or_else(|err| match *err {
// Convert return statement to return value // Convert return statement to return value
EvalAltResult::Return(x, _) => Ok(x), EvalAltResult::Return(x, _) => Ok(x),
@ -1082,7 +1100,6 @@ impl Engine {
args_expr: &[Expr], args_expr: &[Expr],
def_val: Option<bool>, def_val: Option<bool>,
hash_script: u64, hash_script: u64,
_capture: bool,
level: usize, level: usize,
) -> Result<Dynamic, Box<EvalAltResult>> { ) -> Result<Dynamic, Box<EvalAltResult>> {
let modules = modules.as_ref().unwrap(); let modules = modules.as_ref().unwrap();

View File

@ -288,7 +288,7 @@ impl Module {
/// If there is an existing function of the same name and number of arguments, it is replaced. /// If there is an existing function of the same name and number of arguments, it is replaced.
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
#[inline] #[inline]
pub(crate) fn set_script_fn(&mut self, fn_def: ScriptFnDef) -> u64 { pub(crate) fn set_script_fn(&mut self, fn_def: Shared<ScriptFnDef>) -> u64 {
// None + function name + number of arguments. // None + function name + number of arguments.
let num_params = fn_def.params.len(); let num_params = fn_def.params.len();
let hash_script = calc_fn_hash(empty(), &fn_def.name, num_params, empty()); let hash_script = calc_fn_hash(empty(), &fn_def.name, num_params, empty());
@ -1392,53 +1392,18 @@ impl Module {
module.modules.insert(alias.to_string(), m); module.modules.insert(alias.to_string(), m);
}); });
// Non-private functions defined become module functions
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
{ {
let ast_lib: Shared<Module> = ast.lib().clone().into(); let ast_lib: Shared<Module> = ast.lib().clone().into();
ast.iter_functions() ast.iter_functions()
.filter(|(access, _, _, _)| access.is_public()) .filter(|(access, _, _, _)| !access.is_private())
.for_each(|(_, name, num_params, func)| { .for_each(|(_, _, _, func)| {
let ast_lib = ast_lib.clone(); // Encapsulate AST environment
let mut func = func.as_ref().clone();
module.set_raw_fn_as_scripted( func.lib = Some(ast_lib.clone());
name, module.set_script_fn(func.into());
num_params,
move |engine: &Engine, lib: &Module, args: &mut [&mut Dynamic]| {
let mut lib_merged;
let unified_lib = if lib.is_empty() {
// In the special case of the main script not defining any function
&ast_lib
} else {
lib_merged = lib.clone();
lib_merged.merge(&ast_lib);
&lib_merged
};
engine
.call_script_fn(
&mut Default::default(),
&mut Default::default(),
&mut Default::default(),
unified_lib,
&mut None,
&func.name,
func.as_ref(),
args,
0,
)
.map_err(|err| {
// Wrap the error in a module-error
EvalAltResult::ErrorInModule(
"".to_string(),
err,
Position::none(),
)
.into()
})
},
);
}); });
} }

View File

@ -823,6 +823,7 @@ pub fn optimize_into_ast(
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
externals: fn_def.externals.clone(), externals: fn_def.externals.clone(),
pos: fn_def.pos, pos: fn_def.pos,
lib: None,
} }
.into() .into()
}) })
@ -862,7 +863,7 @@ pub fn optimize_into_ast(
}); });
} else { } else {
_functions.into_iter().for_each(|fn_def| { _functions.into_iter().for_each(|fn_def| {
module.set_script_fn(fn_def); module.set_script_fn(fn_def.into());
}); });
} }

View File

@ -549,6 +549,8 @@ pub struct ScriptFnDef {
pub body: Stmt, pub body: Stmt,
/// Position of the function definition. /// Position of the function definition.
pub pos: Position, pub pos: Position,
/// Encapsulated running environment, if any.
pub lib: Option<Shared<Module>>,
} }
impl fmt::Display for ScriptFnDef { impl fmt::Display for ScriptFnDef {
@ -3373,6 +3375,7 @@ fn parse_fn(
externals, externals,
body, body,
pos: settings.pos, pos: settings.pos,
lib: None,
}) })
} }
@ -3550,6 +3553,7 @@ fn parse_anon_fn(
externals: Default::default(), externals: Default::default(),
body, body,
pos: settings.pos, pos: settings.pos,
lib: None,
}; };
let expr = Expr::FnPointer(Box::new((fn_name, settings.pos))); let expr = Expr::FnPointer(Box::new((fn_name, settings.pos)));