diff --git a/src/module/mod.rs b/src/module/mod.rs index bb107ad7..674d93fe 100644 --- a/src/module/mod.rs +++ b/src/module/mod.rs @@ -3,7 +3,7 @@ use crate::any::{Dynamic, Variant}; use crate::calc_fn_hash; use crate::engine::Engine; -use crate::fn_native::{CallableFunction, FnCallArgs, IteratorFn, SendSync}; +use crate::fn_native::{CallableFunction, FnCallArgs, FnPtr, IteratorFn, SendSync}; use crate::fn_register::by_value as cast_arg; use crate::parser::{FnAccess, FnAccess::Public}; use crate::result::EvalAltResult; @@ -1217,11 +1217,16 @@ impl Module { /// /// ### `private_namespace` parameter /// - /// If `true`, the entire `AST` is encapsulated into each function as a private namespace, - /// allowing functions to cross-call each other. + /// * If `true`, the entire `AST` is encapsulated into each function as a private namespace, + /// allowing functions to cross-call each other. Functions are searched in the module's + /// private namespace, and the global namespace cannot be accessed. /// - /// If `false`, each function is registered independently and cannot cross-call - /// each other. Functions are searched in the global namespace. + /// Under this scenario, if any argument is a function pointer, then the function referred + /// to by the function pointer is also _merged_ into the module's private namespace before + /// the function call, so passing simple closures to functions work as expected. + /// + /// * If `false`, each function is registered independently and cannot cross-call + /// each other. Functions are searched in the global namespace. /// /// # Examples /// @@ -1277,11 +1282,32 @@ impl Module { module.set_raw_fn_as_scripted( name, num_args, - move |engine: &Engine, _, args: &mut [&mut Dynamic]| { + move |engine: &Engine, lib: &Module, args: &mut [&mut Dynamic]| { + // Get anonymous functions + let anon_fns: StaticVec<_> = args + .iter() + .filter(|&arg| arg.is::()) + .map(|arg| arg.read_lock::().unwrap().get_fn_name().clone()) + .collect(); + + let mut lib_merged; + + let call_lib = if anon_fns.is_empty() { + // No anonymous functions - just pass the AST through + &ast_lib + } else { + // If there are anonymous functions, merge them in + lib_merged = ast_lib.clone(); + lib_merged.merge_filtered(&lib, &mut |_, name, _| { + anon_fns.iter().find(|s| s.as_str() == name).is_some() + }); + &lib_merged + }; + engine .call_fn_dynamic_raw( &mut Scope::new(), - &ast_lib, + call_lib, &fn_name, &mut None, args, diff --git a/src/module/resolvers/stat.rs b/src/module/resolvers/stat.rs index 5903ce57..563f5074 100644 --- a/src/module/resolvers/stat.rs +++ b/src/module/resolvers/stat.rs @@ -49,8 +49,7 @@ impl StaticModuleResolver { impl StaticModuleResolver { /// Add a module keyed by its path. - pub fn insert>(&mut self, path: S, mut module: Module) { - module.index_all_sub_modules(); + pub fn insert>(&mut self, path: S, module: Module) { self.0.insert(path.into(), module); } /// Remove a module given its path.