Module resolver returns shared module.

This commit is contained in:
Stephen Chung 2020-11-07 23:33:21 +08:00
parent d5d70367fa
commit b3d318ef7f
20 changed files with 158 additions and 136 deletions

View File

@ -8,6 +8,12 @@ Breaking changes
---------------- ----------------
* Modules imported at global level can now be accessed in functions. * Modules imported at global level can now be accessed in functions.
* `ModuleResolver::resolve` now returns `Shared<Module>` for better resources sharing when loading modules.
Enhancements
------------
* Modules imported via `import` statements at global level can now be used in functions. There is no longer any need to re-`import` the modules at the beginning of each function block.
Version 0.19.4 Version 0.19.4

View File

@ -121,6 +121,7 @@ where:
| `context` | `&mut EvalContext` | mutable reference to the current evaluation _context_ | | `context` | `&mut EvalContext` | mutable reference to the current evaluation _context_ |
| - `context.scope` | `&mut Scope` | mutable reference to the current [`Scope`]; variables can be added to/removed from it | | - `context.scope` | `&mut Scope` | mutable reference to the current [`Scope`]; variables can be added to/removed from it |
| - `context.engine()` | `&Engine` | reference to the current [`Engine`] | | - `context.engine()` | `&Engine` | reference to the current [`Engine`] |
| - `context.imports()` | `&Imports` | reference to the current stack of [modules] imported via `import` statements |
| - `context.iter_namespaces()` | `impl Iterator<Item = &Module>` | iterator of the namespaces (as [modules]) containing all script-defined functions | | - `context.iter_namespaces()` | `impl Iterator<Item = &Module>` | iterator of the namespaces (as [modules]) containing all script-defined functions |
| - `context.this_ptr()` | `Option<&Dynamic>` | reference to the current bound [`this`] pointer, if any | | - `context.this_ptr()` | `Option<&Dynamic>` | reference to the current bound [`this`] pointer, if any |
| - `context.call_level()` | `usize` | the current nesting level of function calls | | - `context.call_level()` | `usize` | the current nesting level of function calls |

View File

@ -74,6 +74,7 @@ where:
| `context` | `&EvalContext` | reference to the current evaluation _context_ | | `context` | `&EvalContext` | reference to the current evaluation _context_ |
| - `context.scope` | `&Scope` | reference to the current [`Scope`] containing all variables up to the current evaluation position | | - `context.scope` | `&Scope` | reference to the current [`Scope`] containing all variables up to the current evaluation position |
| - `context.engine()` | `&Engine` | reference to the current [`Engine`] | | - `context.engine()` | `&Engine` | reference to the current [`Engine`] |
| - `context.imports()` | `&Imports` | reference to the current stack of [modules] imported via `import` statements |
| - `context.iter_namespaces()` | `impl Iterator<Item = &Module>` | iterator of the namespaces (as [modules]) containing all script-defined functions | | - `context.iter_namespaces()` | `impl Iterator<Item = &Module>` | iterator of the namespaces (as [modules]) containing all script-defined functions |
| - `context.this_ptr()` | `Option<&Dynamic>` | reference to the current bound [`this`] pointer, if any | | - `context.this_ptr()` | `Option<&Dynamic>` | reference to the current bound [`this`] pointer, if any |
| - `context.call_level()` | `usize` | the current nesting level of function calls | | - `context.call_level()` | `usize` | the current nesting level of function calls |

View File

@ -30,6 +30,8 @@ There is one _global_ namespace for every [`Engine`], which includes:
* All the Rust functions defined in [packages] that are loaded into the [`Engine`]. * All the Rust functions defined in [packages] that are loaded into the [`Engine`].
* All the [modules] imported via [`import`] statements.
In addition, during evaluation of an [`AST`], all script-defined functions bundled together within In addition, during evaluation of an [`AST`], all script-defined functions bundled together within
the [`AST`] are added to the global namespace and override any existing registered functions of the [`AST`] are added to the global namespace and override any existing registered functions of
the same names and number of parameters. the same names and number of parameters.

View File

@ -223,7 +223,14 @@ engine.register_raw_fn("super_call",
------------------ ------------------
`FnPtr::call_dynamic` takes a parameter of type `NativeCallContext` which holds the _native call context_ `FnPtr::call_dynamic` takes a parameter of type `NativeCallContext` which holds the _native call context_
of the particular call to a registered Rust function. of the particular call to a registered Rust function. It is a type that exposes the following:
| Field | Type | Description |
| ------------------- | :-----------------------------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `engine()` | `&Engine` | the current [`Engine`], with all configurations and settings.<br/>This is sometimes useful for calling a script-defined function within the same evaluation context using [`Engine::call_fn`][`call_fn`], or calling a [function pointer]. |
| `imports()` | `Option<&Imports>` | reference to the current stack of [modules] imported via `import` statements (if any) |
| `iter_namespaces()` | `impl Iterator<Item = &Module>` | iterator of the namespaces (as [modules]) containing all script-defined functions |
This type is normally provided by the [`Engine`] (e.g. when using [`Engine::register_fn_raw`](../rust/register-raw.md)). This type is normally provided by the [`Engine`] (e.g. when using [`Engine::register_fn_raw`](../rust/register-raw.md)).
However, it may also be manually constructed from a tuple: However, it may also be manually constructed from a tuple:

View File

@ -85,11 +85,11 @@ specially by the plugins system.
`NativeCallContext` is a type that encapsulates the current _native call context_ and exposes the following: `NativeCallContext` is a type that encapsulates the current _native call context_ and exposes the following:
* `NativeCallContext::engine(): &Engine` - the current [`Engine`], with all configurations and settings. | Field | Type | Description |
This is sometimes useful for calling a script-defined function within the same evaluation context | ------------------- | :-----------------------------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
using [`Engine::call_fn`][`call_fn`]. | `engine()` | `&Engine` | the current [`Engine`], with all configurations and settings.<br/>This is sometimes useful for calling a script-defined function within the same evaluation context using [`Engine::call_fn`][`call_fn`], or calling a [function pointer]. |
| `imports()` | `Option<&Imports>` | reference to the current stack of [modules] imported via `import` statements (if any) |
* `NativeCallContext::namespace(): &Module` - the global namespace of script-defined functions, as a [`Module`]. | `iter_namespaces()` | `impl Iterator<Item = &Module>` | iterator of the namespaces (as [modules]) containing all script-defined functions |
This first parameter, if exists, will be stripped before all other processing. It is _virtual_. This first parameter, if exists, will be stripped before all other processing. It is _virtual_.
Most importantly, it does _not_ count as a parameter to the function and there is no need to provide Most importantly, it does _not_ count as a parameter to the function and there is no need to provide

View File

@ -342,11 +342,11 @@ specially by the plugins system.
`NativeCallContext` is a type that encapsulates the current _native call context_ and exposes the following: `NativeCallContext` is a type that encapsulates the current _native call context_ and exposes the following:
* `NativeCallContext::engine(): &Engine` - the current [`Engine`], with all configurations and settings. | Field | Type | Description |
This is sometimes useful for calling a script-defined function within the same evaluation context | ------------------- | :-----------------------------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
using [`Engine::call_fn`][`call_fn`]. | `engine()` | `&Engine` | the current [`Engine`], with all configurations and settings.<br/>This is sometimes useful for calling a script-defined function within the same evaluation context using [`Engine::call_fn`][`call_fn`], or calling a [function pointer]. |
| `imports()` | `Option<&Imports>` | reference to the current stack of [modules] imported via `import` statements (if any) |
* `NativeCallContext::namespace(): &Module` - the global namespace of script-defined functions, as a [`Module`]. | `iter_namespaces()` | `impl Iterator<Item = &Module>` | iterator of the namespaces (as [modules]) containing all script-defined functions |
This first parameter, if exists, will be stripped before all other processing. It is _virtual_. This first parameter, if exists, will be stripped before all other processing. It is _virtual_.
Most importantly, it does _not_ count as a parameter to the function and there is no need to provide Most importantly, it does _not_ count as a parameter to the function and there is no need to provide

View File

@ -13,7 +13,7 @@ which contains only one function: `resolve`.
When Rhai prepares to load a module, `ModuleResolver::resolve` is called with the name When Rhai prepares to load a module, `ModuleResolver::resolve` is called with the name
of the _module path_ (i.e. the path specified in the [`import`] statement). of the _module path_ (i.e. the path specified in the [`import`] statement).
* Upon success, it should return a [`Module`]. * Upon success, it should return an [`Rc<Module>`][module] (or `Arc<Module>` under [`sync`]).
* If the path does not resolve to a valid module, return `EvalAltResult::ErrorModuleNotFound`. * If the path does not resolve to a valid module, return `EvalAltResult::ErrorModuleNotFound`.
@ -37,11 +37,12 @@ impl ModuleResolver for MyModuleResolver {
engine: &Engine, // reference to the current 'Engine' engine: &Engine, // reference to the current 'Engine'
path: &str, // the module path path: &str, // the module path
pos: Position, // position of the 'import' statement pos: Position, // position of the 'import' statement
) -> Result<Module, Box<EvalAltResult>> { ) -> Result<Rc<Module>, Box<EvalAltResult>> {
// Check module path. // Check module path.
if is_valid_module_path(path) { if is_valid_module_path(path) {
// Load the custom module. load_secret_module(path) // load the custom module
load_secret_module(path).map_err(|err| .map(Rc::new) // share it
.map_err(|err|
// Return EvalAltResult::ErrorInModule upon loading error // Return EvalAltResult::ErrorInModule upon loading error
EvalAltResult::ErrorInModule(err.to_string(), pos).into() EvalAltResult::ErrorInModule(err.to_string(), pos).into()
) )

View File

@ -29,6 +29,8 @@ Loads a script file (based off the current directory) with `.rhai` extension.
All functions in the _global_ namespace, plus all those defined in the same module, All functions in the _global_ namespace, plus all those defined in the same module,
are _merged_ into a _unified_ namespace. are _merged_ into a _unified_ namespace.
Modules are also _cached_ so a script file is only evaluated _once_, even when repeatedly imported.
```rust ```rust
------------------ ------------------
| my_module.rhai | | my_module.rhai |
@ -122,10 +124,6 @@ m::greet(); // prints "hello! from module!"
The base directory can be changed via the `FileModuleResolver::new_with_path` constructor function. The base directory can be changed via the `FileModuleResolver::new_with_path` constructor function.
### Returning a module instead
`FileModuleResolver::create_module` loads a script file and returns a module with the standard behavior.
`StaticModuleResolver` `StaticModuleResolver`
--------------------- ---------------------

View File

@ -70,6 +70,7 @@ where:
| `T` | `impl Clone` | return type of the function | | `T` | `impl Clone` | return type of the function |
| `context` | `NativeCallContext` | the current _native call context_ | | `context` | `NativeCallContext` | the current _native call context_ |
| - `context.engine()` | `&Engine` | the current [`Engine`], with all configurations and settings.<br/>This is sometimes useful for calling a script-defined function within the same evaluation context using [`Engine::call_fn`][`call_fn`], or calling a [function pointer]. | | - `context.engine()` | `&Engine` | the current [`Engine`], with all configurations and settings.<br/>This is sometimes useful for calling a script-defined function within the same evaluation context using [`Engine::call_fn`][`call_fn`], or calling a [function pointer]. |
| - `context.imports()` | `Option<&Imports>` | reference to the current stack of [modules] imported via `import` statements (if any) |
| - `context.iter_namespaces()` | `impl Iterator<Item = &Module>` | iterator of the namespaces (as [modules]) containing all script-defined functions | | - `context.iter_namespaces()` | `impl Iterator<Item = &Module>` | iterator of the namespaces (as [modules]) containing all script-defined functions |
| `args` | `&mut [&mut Dynamic]` | a slice containing `&mut` references to [`Dynamic`] values.<br/>The slice is guaranteed to contain enough arguments _of the correct types_. | | `args` | `&mut [&mut Dynamic]` | a slice containing `&mut` references to [`Dynamic`] values.<br/>The slice is guaranteed to contain enough arguments _of the correct types_. |

View File

@ -3,7 +3,7 @@
use crate::ast::{BinaryExpr, Expr, FnCallInfo, Ident, IdentX, ReturnType, Stmt}; use crate::ast::{BinaryExpr, Expr, FnCallInfo, Ident, IdentX, ReturnType, Stmt};
use crate::dynamic::{map_std_type_name, Dynamic, Union, Variant}; use crate::dynamic::{map_std_type_name, Dynamic, Union, Variant};
use crate::fn_call::run_builtin_op_assignment; use crate::fn_call::run_builtin_op_assignment;
use crate::fn_native::{Callback, FnPtr, OnVarCallback}; use crate::fn_native::{Callback, FnPtr, OnVarCallback, Shared};
use crate::module::{Module, ModuleRef}; use crate::module::{Module, ModuleRef};
use crate::optimize::OptimizationLevel; use crate::optimize::OptimizationLevel;
use crate::packages::{Package, PackagesCollection, StandardPackage}; use crate::packages::{Package, PackagesCollection, StandardPackage};
@ -73,48 +73,49 @@ pub type Map = HashMap<ImmutableString, Dynamic>;
// //
// We cannot use &str or Cow<str> here because `eval` may load a module and the module name will live beyond // We cannot use &str or Cow<str> here because `eval` may load a module and the module name will live beyond
// the AST of the eval script text. The best we can do is a shared reference. // the AST of the eval script text. The best we can do is a shared reference.
//
// `Imports` is implemented as two `Vec`'s of exactly the same length. That's because a `Module` is large,
// so packing the import names together improves cache locality.
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct Imports(StaticVec<Module>, StaticVec<ImmutableString>); pub struct Imports(StaticVec<(Shared<Module>, ImmutableString)>);
impl Imports { impl Imports {
/// Get the length of this stack of imported modules. /// Get the length of this stack of imported modules.
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
self.0.len() self.0.len()
} }
/// Is this stack of imported modules empty?
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Get the imported module at a particular index. /// Get the imported module at a particular index.
pub fn get(&self, index: usize) -> Option<&Module> { pub fn get(&self, index: usize) -> Option<Shared<Module>> {
self.0.get(index) self.0.get(index).map(|(m, _)| m).cloned()
} }
/// Get the index of an imported module by name. /// Get the index of an imported module by name.
pub fn find(&self, name: &str) -> Option<usize> { pub fn find(&self, name: &str) -> Option<usize> {
self.1 self.0
.iter() .iter()
.enumerate() .enumerate()
.rev() .rev()
.find(|(_, key)| key.as_str() == name) .find(|(_, (_, key))| key.as_str() == name)
.map(|(index, _)| index) .map(|(index, _)| index)
} }
/// Push an imported module onto the stack. /// Push an imported module onto the stack.
pub fn push(&mut self, name: impl Into<ImmutableString>, module: Module) { pub fn push(&mut self, name: impl Into<ImmutableString>, module: impl Into<Shared<Module>>) {
self.0.push(module); self.0.push((module.into(), name.into()));
self.1.push(name.into());
} }
/// Truncate the stack of imported modules to a particular length. /// Truncate the stack of imported modules to a particular length.
pub fn truncate(&mut self, size: usize) { pub fn truncate(&mut self, size: usize) {
self.0.truncate(size); self.0.truncate(size);
self.1.truncate(size);
} }
/// Get an iterator to this stack of imported modules. /// Get an iterator to this stack of imported modules.
#[allow(dead_code)] #[allow(dead_code)]
pub fn iter(&self) -> impl Iterator<Item = (&str, &Module)> { pub fn iter(&self) -> impl Iterator<Item = (&str, Shared<Module>)> {
self.1.iter().map(|name| name.as_str()).zip(self.0.iter()) self.0
.iter()
.map(|(module, name)| (name.as_str(), module.clone()))
} }
/// Get a consuming iterator to this stack of imported modules. /// Get a consuming iterator to this stack of imported modules.
pub fn into_iter(self) -> impl Iterator<Item = (ImmutableString, Module)> { pub fn into_iter(self) -> impl Iterator<Item = (ImmutableString, Shared<Module>)> {
self.1.into_iter().zip(self.0.into_iter()) self.0.into_iter().map(|(module, name)| (name, module))
} }
} }
@ -630,11 +631,11 @@ fn default_print(_s: &str) {
/// Search for a module within an imports stack. /// Search for a module within an imports stack.
/// Position in `EvalAltResult` is `None` and must be set afterwards. /// Position in `EvalAltResult` is `None` and must be set afterwards.
pub fn search_imports<'s>( pub fn search_imports(
mods: &'s Imports, mods: &Imports,
state: &mut State, state: &mut State,
modules: &ModuleRef, modules: &ModuleRef,
) -> Result<&'s Module, Box<EvalAltResult>> { ) -> Result<Shared<Module>, Box<EvalAltResult>> {
let Ident { name: root, pos } = &modules[0]; let Ident { name: root, pos } = &modules[0];
// Qualified - check if the root module is directly indexed // Qualified - check if the root module is directly indexed
@ -1487,7 +1488,9 @@ impl Engine {
calc_native_fn_hash(empty(), OP_FUNC, args.iter().map(|a| a.type_id())); calc_native_fn_hash(empty(), OP_FUNC, args.iter().map(|a| a.type_id()));
if self if self
.call_native_fn(state, lib, OP_FUNC, hash, args, false, false, def_value) .call_native_fn(
mods, state, lib, OP_FUNC, hash, args, false, false, def_value,
)
.map_err(|err| err.fill_position(rhs.position()))? .map_err(|err| err.fill_position(rhs.position()))?
.0 .0
.as_bool() .as_bool()
@ -1805,9 +1808,9 @@ impl Engine {
// Overriding exact implementation // Overriding exact implementation
if func.is_plugin_fn() { if func.is_plugin_fn() {
func.get_plugin_fn().call((self, lib).into(), args)?; func.get_plugin_fn().call((self, mods, lib).into(), args)?;
} else { } else {
func.get_native_fn()((self, lib).into(), args)?; func.get_native_fn()((self, mods, lib).into(), args)?;
} }
} }
// Built-in op-assignment function // Built-in op-assignment function
@ -2126,10 +2129,9 @@ impl Engine {
.try_cast::<ImmutableString>() .try_cast::<ImmutableString>()
{ {
if let Some(resolver) = &self.module_resolver { if let Some(resolver) = &self.module_resolver {
let mut module = resolver.resolve(self, &path, expr.position())?; let module = resolver.resolve(self, &path, expr.position())?;
if let Some(name_def) = alias { if let Some(name_def) = alias {
module.index_all_sub_modules();
mods.push(name_def.name.clone(), module); mods.push(name_def.name.clone(), module);
} }

View File

@ -1662,7 +1662,7 @@ impl Engine {
ast.lib() ast.lib()
.iter_fn() .iter_fn()
.filter(|f| f.func.is_script()) .filter(|f| f.func.is_script())
.map(|f| f.func.get_fn_def().clone()) .map(|f| (**f.func.get_fn_def()).clone())
.collect() .collect()
} else { } else {
Default::default() Default::default()

View File

@ -178,6 +178,7 @@ impl Engine {
/// **DO NOT** reuse the argument values unless for the first `&mut` argument - all others are silently replaced by `()`! /// **DO NOT** reuse the argument values unless for the first `&mut` argument - all others are silently replaced by `()`!
pub(crate) fn call_native_fn( pub(crate) fn call_native_fn(
&self, &self,
mods: &mut Imports,
state: &mut State, state: &mut State,
lib: &[&Module], lib: &[&Module],
fn_name: &str, fn_name: &str,
@ -205,9 +206,9 @@ impl Engine {
// Run external function // Run external function
let result = if func.is_plugin_fn() { let result = if func.is_plugin_fn() {
func.get_plugin_fn().call((self, lib).into(), args) func.get_plugin_fn().call((self, mods, lib).into(), args)
} else { } else {
func.get_native_fn()((self, lib).into(), args) func.get_native_fn()((self, mods, lib).into(), args)
}; };
// Restore the original reference // Restore the original reference
@ -588,6 +589,7 @@ impl Engine {
} else { } else {
// If it is a native function, redirect it // If it is a native function, redirect it
self.call_native_fn( self.call_native_fn(
mods,
state, state,
lib, lib,
fn_name, fn_name,
@ -602,7 +604,7 @@ impl Engine {
// Normal native function call // Normal native function call
_ => self.call_native_fn( _ => self.call_native_fn(
state, lib, fn_name, hash_fn, args, is_ref, pub_only, def_val, mods, state, lib, fn_name, hash_fn, args, is_ref, pub_only, def_val,
), ),
} }
} }
@ -1178,15 +1180,14 @@ impl Engine {
} }
let args = args.as_mut(); let args = args.as_mut();
let fn_def = f.get_shared_fn_def().clone();
let new_scope = &mut Default::default(); let new_scope = &mut Default::default();
let fn_def = f.get_fn_def().clone();
self.call_script_fn(new_scope, mods, state, lib, &mut None, &fn_def, args, level) self.call_script_fn(new_scope, mods, state, lib, &mut None, &fn_def, args, level)
} }
Some(f) if f.is_plugin_fn() => { Some(f) if f.is_plugin_fn() => f
f.get_plugin_fn().call((self, lib).into(), args.as_mut()) .get_plugin_fn()
} .clone()
.call((self, mods, lib).into(), args.as_mut()),
Some(f) if f.is_native() => { Some(f) if f.is_native() => {
if !f.is_method() { if !f.is_method() {
// Clone first argument // Clone first argument
@ -1197,7 +1198,7 @@ impl Engine {
} }
} }
f.get_native_fn()((self, lib).into(), args.as_mut()) f.get_native_fn().clone()((self, mods, lib).into(), args.as_mut())
} }
Some(_) => unreachable!(), Some(_) => unreachable!(),
None if def_val.is_some() => Ok(def_val.unwrap().into()), None if def_val.is_some() => Ok(def_val.unwrap().into()),

View File

@ -2,7 +2,7 @@
use crate::ast::{FnAccess, ScriptFnDef}; use crate::ast::{FnAccess, ScriptFnDef};
use crate::dynamic::Dynamic; use crate::dynamic::Dynamic;
use crate::engine::{Engine, EvalContext}; use crate::engine::{Engine, EvalContext, Imports};
use crate::module::Module; use crate::module::Module;
use crate::plugin::PluginFunction; use crate::plugin::PluginFunction;
use crate::result::EvalAltResult; use crate::result::EvalAltResult;
@ -50,28 +50,50 @@ pub type Locked<T> = RwLock<T>;
/// Context of native Rust function call. /// Context of native Rust function call.
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
pub struct NativeCallContext<'e, 'm, 'pm: 'm> { pub struct NativeCallContext<'e, 'a, 'm, 'pm: 'm> {
engine: &'e Engine, engine: &'e Engine,
mods: Option<&'a Imports>,
lib: &'m [&'pm Module], lib: &'m [&'pm Module],
} }
impl<'e, 'a, 'm, 'pm: 'm, M: AsRef<[&'pm Module]> + ?Sized>
From<(&'e Engine, &'a mut Imports, &'m M)> for NativeCallContext<'e, 'a, 'm, 'pm>
{
fn from(value: (&'e Engine, &'a mut Imports, &'m M)) -> Self {
Self {
engine: value.0,
mods: Some(value.1),
lib: value.2.as_ref(),
}
}
}
impl<'e, 'm, 'pm: 'm, M: AsRef<[&'pm Module]> + ?Sized> From<(&'e Engine, &'m M)> impl<'e, 'm, 'pm: 'm, M: AsRef<[&'pm Module]> + ?Sized> From<(&'e Engine, &'m M)>
for NativeCallContext<'e, 'm, 'pm> for NativeCallContext<'e, '_, 'm, 'pm>
{ {
fn from(value: (&'e Engine, &'m M)) -> Self { fn from(value: (&'e Engine, &'m M)) -> Self {
Self { Self {
engine: value.0, engine: value.0,
mods: None,
lib: value.1.as_ref(), lib: value.1.as_ref(),
} }
} }
} }
impl<'e, 'm, 'pm> NativeCallContext<'e, 'm, 'pm> { impl<'e, 'a, 'm, 'pm> NativeCallContext<'e, 'a, 'm, 'pm> {
/// The current `Engine`. /// The current `Engine`.
#[inline(always)] #[inline(always)]
pub fn engine(&self) -> &'e Engine { pub fn engine(&self) -> &'e Engine {
self.engine self.engine
} }
/// _[INTERNALS]_ The current set of modules imported via `import` statements.
/// Available under the `internals` feature only.
#[cfg(feature = "internals")]
#[cfg(not(feature = "no_module"))]
#[inline(always)]
pub fn imports(&self) -> Option<&Imports> {
self.mods
}
/// Get an iterator over the namespaces containing definition of all script-defined functions. /// Get an iterator over the namespaces containing definition of all script-defined functions.
#[inline(always)] #[inline(always)]
pub fn iter_namespaces(&self) -> impl Iterator<Item = &'pm Module> + 'm { pub fn iter_namespaces(&self) -> impl Iterator<Item = &'pm Module> + 'm {
@ -181,9 +203,11 @@ impl FnPtr {
args.insert(0, obj); args.insert(0, obj);
} }
let mut mods = ctx.mods.cloned().unwrap_or_default();
ctx.engine() ctx.engine()
.exec_fn_call( .exec_fn_call(
&mut Default::default(), &mut mods,
&mut Default::default(), &mut Default::default(),
ctx.lib, ctx.lib,
fn_name, fn_name,
@ -396,14 +420,14 @@ impl CallableFunction {
Self::Script(f) => f.access, Self::Script(f) => f.access,
} }
} }
/// Get a reference to a native Rust function. /// Get a shared reference to a native Rust function.
/// ///
/// # Panics /// # Panics
/// ///
/// Panics if the `CallableFunction` is not `Pure` or `Method`. /// Panics if the `CallableFunction` is not `Pure` or `Method`.
pub fn get_native_fn(&self) -> &FnAny { pub fn get_native_fn(&self) -> &Shared<FnAny> {
match self { match self {
Self::Pure(f) | Self::Method(f) => f.as_ref(), Self::Pure(f) | Self::Method(f) => f,
Self::Iterator(_) | Self::Plugin(_) => unreachable!(), Self::Iterator(_) | Self::Plugin(_) => unreachable!(),
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
@ -416,25 +440,12 @@ impl CallableFunction {
/// ///
/// Panics if the `CallableFunction` is not `Script`. /// Panics if the `CallableFunction` is not `Script`.
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
pub fn get_shared_fn_def(&self) -> &Shared<ScriptFnDef> { pub fn get_fn_def(&self) -> &Shared<ScriptFnDef> {
match self { match self {
Self::Pure(_) | Self::Method(_) | Self::Iterator(_) | Self::Plugin(_) => unreachable!(), Self::Pure(_) | Self::Method(_) | Self::Iterator(_) | Self::Plugin(_) => unreachable!(),
Self::Script(f) => f, Self::Script(f) => f,
} }
} }
/// Get a reference to a script-defined function definition.
///
/// # Panics
///
/// Panics if the `CallableFunction` is not `Script`.
pub fn get_fn_def(&self) -> &ScriptFnDef {
match self {
Self::Pure(_) | Self::Method(_) | Self::Iterator(_) | Self::Plugin(_) => unreachable!(),
#[cfg(not(feature = "no_function"))]
Self::Script(f) => f,
}
}
/// Get a reference to an iterator function. /// Get a reference to an iterator function.
/// ///
/// # Panics /// # Panics
@ -449,14 +460,14 @@ impl CallableFunction {
Self::Script(_) => unreachable!(), Self::Script(_) => unreachable!(),
} }
} }
/// Get a reference to a plugin function. /// Get a shared reference to a plugin function.
/// ///
/// # Panics /// # Panics
/// ///
/// Panics if the `CallableFunction` is not `Plugin`. /// Panics if the `CallableFunction` is not `Plugin`.
pub fn get_plugin_fn<'s>(&'s self) -> &FnPlugin { pub fn get_plugin_fn<'s>(&'s self) -> &Shared<FnPlugin> {
match self { match self {
Self::Plugin(f) => f.as_ref(), Self::Plugin(f) => f,
Self::Pure(_) | Self::Method(_) | Self::Iterator(_) => unreachable!(), Self::Pure(_) | Self::Method(_) | Self::Iterator(_) => unreachable!(),
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]

View File

@ -329,7 +329,7 @@ impl Module {
&& fn_name == name && fn_name == name
}, },
) )
.map(|FuncInfo { func, .. }| func.get_shared_fn_def()) .map(|FuncInfo { func, .. }| func.get_fn_def())
} }
/// Does a sub-module exist in the module? /// Does a sub-module exist in the module?
@ -1286,7 +1286,7 @@ impl Module {
.values() .values()
.map(|f| &f.func) .map(|f| &f.func)
.filter(|f| f.is_script()) .filter(|f| f.is_script())
.map(CallableFunction::get_shared_fn_def) .map(CallableFunction::get_fn_def)
.map(|f| { .map(|f| {
let func = f.clone(); let func = f.clone();
(f.access, f.name.as_str(), f.params.len(), func) (f.access, f.name.as_str(), f.params.len(), func)
@ -1374,7 +1374,7 @@ impl Module {
// Modules left in the scope become sub-modules // Modules left in the scope become sub-modules
mods.into_iter().for_each(|(alias, m)| { mods.into_iter().for_each(|(alias, m)| {
module.modules.insert(alias.to_string(), m); module.modules.insert(alias.to_string(), m.as_ref().clone());
}); });
// Non-private functions defined become module functions // Non-private functions defined become module functions

View File

@ -1,4 +1,5 @@
use crate::engine::Engine; use crate::engine::Engine;
use crate::fn_native::Shared;
use crate::module::{Module, ModuleResolver}; use crate::module::{Module, ModuleResolver};
use crate::result::EvalAltResult; use crate::result::EvalAltResult;
use crate::token::Position; use crate::token::Position;
@ -90,7 +91,7 @@ impl ModuleResolver for ModuleResolversCollection {
engine: &Engine, engine: &Engine,
path: &str, path: &str,
pos: Position, pos: Position,
) -> Result<Module, Box<EvalAltResult>> { ) -> Result<Shared<Module>, Box<EvalAltResult>> {
for resolver in self.0.iter() { for resolver in self.0.iter() {
match resolver.resolve(engine, path, pos) { match resolver.resolve(engine, path, pos) {
Ok(module) => return Ok(module), Ok(module) => return Ok(module),

View File

@ -1,6 +1,5 @@
use crate::ast::AST;
use crate::engine::Engine; use crate::engine::Engine;
use crate::fn_native::Locked; use crate::fn_native::{Locked, Shared};
use crate::module::{Module, ModuleResolver}; use crate::module::{Module, ModuleResolver};
use crate::result::EvalAltResult; use crate::result::EvalAltResult;
use crate::token::Position; use crate::token::Position;
@ -40,7 +39,7 @@ use crate::stdlib::{boxed::Box, collections::HashMap, path::PathBuf, string::Str
pub struct FileModuleResolver { pub struct FileModuleResolver {
path: PathBuf, path: PathBuf,
extension: String, extension: String,
cache: Locked<HashMap<PathBuf, AST>>, cache: Locked<HashMap<PathBuf, Shared<Module>>>,
} }
impl Default for FileModuleResolver { impl Default for FileModuleResolver {
@ -119,16 +118,6 @@ impl FileModuleResolver {
pub fn new() -> Self { pub fn new() -> Self {
Default::default() Default::default()
} }
/// Create a `Module` from a file path.
#[inline(always)]
pub fn create_module<P: Into<PathBuf>>(
&self,
engine: &Engine,
path: &str,
) -> Result<Module, Box<EvalAltResult>> {
self.resolve(engine, path, Default::default())
}
} }
impl ModuleResolver for FileModuleResolver { impl ModuleResolver for FileModuleResolver {
@ -137,48 +126,51 @@ impl ModuleResolver for FileModuleResolver {
engine: &Engine, engine: &Engine,
path: &str, path: &str,
pos: Position, pos: Position,
) -> Result<Module, Box<EvalAltResult>> { ) -> Result<Shared<Module>, Box<EvalAltResult>> {
// Construct the script file path // Construct the script file path
let mut file_path = self.path.clone(); let mut file_path = self.path.clone();
file_path.push(path); file_path.push(path);
file_path.set_extension(&self.extension); // Force extension file_path.set_extension(&self.extension); // Force extension
let scope = Default::default(); let scope = Default::default();
let module;
// See if it is cached // See if it is cached
let ast = { let mut module = None;
let module_ref = {
#[cfg(not(feature = "sync"))] #[cfg(not(feature = "sync"))]
let c = self.cache.borrow(); let c = self.cache.borrow();
#[cfg(feature = "sync")] #[cfg(feature = "sync")]
let c = self.cache.read().unwrap(); let c = self.cache.read().unwrap();
if let Some(ast) = c.get(&file_path) { if let Some(module) = c.get(&file_path) {
module = Module::eval_ast_as_new(scope, ast, engine).map_err(|err| { module.clone()
Box::new(EvalAltResult::ErrorInModule(path.to_string(), err, pos))
})?;
None
} else { } else {
// Load the file and compile it if not found // Load the file and compile it if not found
let ast = engine.compile_file(file_path.clone()).map_err(|err| { let ast = engine.compile_file(file_path.clone()).map_err(|err| {
Box::new(EvalAltResult::ErrorInModule(path.to_string(), err, pos)) Box::new(EvalAltResult::ErrorInModule(path.to_string(), err, pos))
})?; })?;
module = Module::eval_ast_as_new(scope, &ast, engine).map_err(|err| { let mut m = Module::eval_ast_as_new(scope, &ast, engine).map_err(|err| {
Box::new(EvalAltResult::ErrorInModule(path.to_string(), err, pos)) Box::new(EvalAltResult::ErrorInModule(path.to_string(), err, pos))
})?; })?;
Some(ast)
m.index_all_sub_modules();
let m: Shared<Module> = m.into();
module = Some(m.clone());
m
} }
}; };
if let Some(ast) = ast { if let Some(module) = module {
// Put it into the cache // Put it into the cache
#[cfg(not(feature = "sync"))] #[cfg(not(feature = "sync"))]
self.cache.borrow_mut().insert(file_path, ast); self.cache.borrow_mut().insert(file_path, module);
#[cfg(feature = "sync")] #[cfg(feature = "sync")]
self.cache.write().unwrap().insert(file_path, ast); self.cache.write().unwrap().insert(file_path, module);
} }
Ok(module) Ok(module_ref)
} }
} }

View File

@ -1,5 +1,5 @@
use crate::engine::Engine; use crate::engine::Engine;
use crate::fn_native::SendSync; use crate::fn_native::{SendSync, Shared};
use crate::module::Module; use crate::module::Module;
use crate::result::EvalAltResult; use crate::result::EvalAltResult;
use crate::token::Position; use crate::token::Position;
@ -28,5 +28,5 @@ pub trait ModuleResolver: SendSync {
engine: &Engine, engine: &Engine,
path: &str, path: &str,
pos: Position, pos: Position,
) -> Result<Module, Box<EvalAltResult>>; ) -> Result<Shared<Module>, Box<EvalAltResult>>;
} }

View File

@ -1,4 +1,5 @@
use crate::engine::Engine; use crate::engine::Engine;
use crate::fn_native::Shared;
use crate::module::{Module, ModuleResolver}; use crate::module::{Module, ModuleResolver};
use crate::result::EvalAltResult; use crate::result::EvalAltResult;
use crate::token::Position; use crate::token::Position;
@ -23,7 +24,7 @@ use crate::stdlib::{boxed::Box, collections::HashMap, ops::AddAssign, string::St
/// engine.set_module_resolver(Some(resolver)); /// engine.set_module_resolver(Some(resolver));
/// ``` /// ```
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct StaticModuleResolver(HashMap<String, Module>); pub struct StaticModuleResolver(HashMap<String, Shared<Module>>);
impl StaticModuleResolver { impl StaticModuleResolver {
/// Create a new `StaticModuleResolver`. /// Create a new `StaticModuleResolver`.
@ -48,12 +49,13 @@ impl StaticModuleResolver {
} }
/// Add a module keyed by its path. /// Add a module keyed by its path.
#[inline(always)] #[inline(always)]
pub fn insert(&mut self, path: impl Into<String>, module: Module) { pub fn insert(&mut self, path: impl Into<String>, mut module: Module) {
self.0.insert(path.into(), module); module.index_all_sub_modules();
self.0.insert(path.into(), module.into());
} }
/// Remove a module given its path. /// Remove a module given its path.
#[inline(always)] #[inline(always)]
pub fn remove(&mut self, path: &str) -> Option<Module> { pub fn remove(&mut self, path: &str) -> Option<Shared<Module>> {
self.0.remove(path) self.0.remove(path)
} }
/// Does the path exist? /// Does the path exist?
@ -63,17 +65,12 @@ impl StaticModuleResolver {
} }
/// Get an iterator of all the modules. /// Get an iterator of all the modules.
#[inline(always)] #[inline(always)]
pub fn iter(&self) -> impl Iterator<Item = (&str, &Module)> { pub fn iter(&self) -> impl Iterator<Item = (&str, Shared<Module>)> {
self.0.iter().map(|(k, v)| (k.as_str(), v)) self.0.iter().map(|(k, v)| (k.as_str(), v.clone()))
} }
/// Get a mutable iterator of all the modules. /// Get a mutable iterator of all the modules.
#[inline(always)] #[inline(always)]
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut Module)> { pub fn into_iter(self) -> impl Iterator<Item = (String, Shared<Module>)> {
self.0.iter_mut().map(|(k, v)| (k.as_str(), v))
}
/// Get a mutable iterator of all the modules.
#[inline(always)]
pub fn into_iter(self) -> impl Iterator<Item = (String, Module)> {
self.0.into_iter() self.0.into_iter()
} }
/// Get an iterator of all the module paths. /// Get an iterator of all the module paths.
@ -83,13 +80,8 @@ impl StaticModuleResolver {
} }
/// Get an iterator of all the modules. /// Get an iterator of all the modules.
#[inline(always)] #[inline(always)]
pub fn values(&self) -> impl Iterator<Item = &Module> { pub fn values<'a>(&'a self) -> impl Iterator<Item = Shared<Module>> + 'a {
self.0.values() self.0.values().map(|m| m.clone())
}
/// Get a mutable iterator of all the modules.
#[inline(always)]
pub fn values_mut(&mut self) -> impl Iterator<Item = &mut Module> {
self.0.values_mut()
} }
/// Remove all modules. /// Remove all modules.
#[inline(always)] #[inline(always)]
@ -118,7 +110,12 @@ impl StaticModuleResolver {
impl ModuleResolver for StaticModuleResolver { impl ModuleResolver for StaticModuleResolver {
#[inline(always)] #[inline(always)]
fn resolve(&self, _: &Engine, path: &str, pos: Position) -> Result<Module, Box<EvalAltResult>> { fn resolve(
&self,
_: &Engine,
path: &str,
pos: Position,
) -> Result<Shared<Module>, Box<EvalAltResult>> {
self.0 self.0
.get(path) .get(path)
.cloned() .cloned()

View File

@ -140,6 +140,7 @@ fn call_fn_with_constant_arguments(
state state
.engine .engine
.call_native_fn( .call_native_fn(
&mut Default::default(),
&mut Default::default(), &mut Default::default(),
state.lib, state.lib,
fn_name, fn_name,