diff --git a/RELEASES.md b/RELEASES.md index 759f08b9..1e200e97 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -18,12 +18,14 @@ Breaking changes * Modules imported at global level can now be accessed in functions. * `ModuleResolver::resolve` now returns `Shared` for better resources sharing when loading modules. +* `ParseErrorType::DuplicatedExport` is removed as multiple `export`'s are now allowed. 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. -* `export` keyword can now be tagged onto `let` and `const` statements as a short-hand. +* Modules imported via `import` statements are encapsulated into the `AST` when loading a module from a script file. +* `export` keyword can now be tagged onto `let` and `const` statements as a short-hand, e.g.: `export let x = 42;` * Variables can now be `export`-ed multiple times under different names. * `index_of`, `==` and `!=` are defined for arrays. * `==` and `!=` are defined for object maps. diff --git a/doc/src/rust/modules/resolvers.md b/doc/src/rust/modules/resolvers.md index 9bafb91b..a56b9b14 100644 --- a/doc/src/rust/modules/resolvers.md +++ b/doc/src/rust/modules/resolvers.md @@ -29,6 +29,9 @@ 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, are _merged_ into a _unified_ namespace. +All modules imported at _global_ level via [`import`] statements become sub-modules, +which are also available to functions defined within the same script file. + Modules are also _cached_ so a script file is only evaluated _once_, even when repeatedly imported. ```rust diff --git a/src/ast.rs b/src/ast.rs index 5b89148c..e5409b24 100644 --- a/src/ast.rs +++ b/src/ast.rs @@ -18,6 +18,9 @@ use crate::engine::Array; #[cfg(not(feature = "no_object"))] use crate::engine::{make_getter, make_setter, Map}; +#[cfg(not(feature = "no_module"))] +use crate::engine::Imports; + use crate::stdlib::{ any::TypeId, borrow::Cow, @@ -87,15 +90,18 @@ pub struct ScriptFnDef { pub body: Stmt, /// Encapsulated running environment, if any. pub lib: Option>, + /// Encapsulated imported modules. + #[cfg(not(feature = "no_module"))] + pub mods: Imports, /// Function name. pub name: ImmutableString, /// Function access mode. pub access: FnAccess, /// Names of function parameters. pub params: StaticVec, - /// Access to external variables. Boxed because it occurs rarely. + /// Access to external variables. #[cfg(not(feature = "no_closure"))] - pub externals: Option>>, + pub externals: HashSet, } impl fmt::Display for ScriptFnDef { diff --git a/src/engine.rs b/src/engine.rs index a2c90cb8..8a0035aa 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -75,7 +75,7 @@ pub type Map = HashMap; // We cannot use &str or Cow 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. #[derive(Debug, Clone, Default)] -pub struct Imports(StaticVec<(Shared, ImmutableString)>); +pub struct Imports(StaticVec<(ImmutableString, Shared)>); impl Imports { /// Get the length of this stack of imported modules. @@ -88,7 +88,7 @@ impl Imports { } /// Get the imported module at a particular index. pub fn get(&self, index: usize) -> Option> { - self.0.get(index).map(|(m, _)| m).cloned() + self.0.get(index).map(|(_, m)| m).cloned() } /// Get the index of an imported module by name. pub fn find(&self, name: &str) -> Option { @@ -96,12 +96,12 @@ impl Imports { .iter() .enumerate() .rev() - .find(|(_, (_, key))| key.as_str() == name) + .find(|(_, (key, _))| key.as_str() == name) .map(|(index, _)| index) } /// Push an imported module onto the stack. pub fn push(&mut self, name: impl Into, module: impl Into>) { - self.0.push((module.into(), name.into())); + self.0.push((name.into(), module.into())); } /// Truncate the stack of imported modules to a particular length. pub fn truncate(&mut self, size: usize) { @@ -112,11 +112,22 @@ impl Imports { pub fn iter(&self) -> impl Iterator)> { self.0 .iter() - .map(|(module, name)| (name.as_str(), module.clone())) + .map(|(name, module)| (name.as_str(), module.clone())) + } + /// Get an iterator to this stack of imported modules. + #[allow(dead_code)] + pub(crate) fn iter_raw<'a>( + &'a self, + ) -> impl Iterator)> + 'a { + self.0.iter().cloned() } /// Get a consuming iterator to this stack of imported modules. pub fn into_iter(self) -> impl Iterator)> { - self.0.into_iter().map(|(module, name)| (name, module)) + self.0.into_iter() + } + /// Add a stream of imported modules. + pub fn extend(&mut self, stream: impl Iterator)>) { + self.0.extend(stream) } } diff --git a/src/fn_call.rs b/src/fn_call.rs index 9911f2f2..3c258f93 100644 --- a/src/fn_call.rs +++ b/src/fn_call.rs @@ -391,6 +391,11 @@ impl Engine { lib }; + #[cfg(not(feature = "no_module"))] + if !fn_def.mods.is_empty() { + mods.extend(fn_def.mods.iter_raw()); + } + // Evaluate the function at one higher level of call depth let stmt = &fn_def.body; @@ -541,10 +546,10 @@ impl Engine { // Move captured variables into scope #[cfg(not(feature = "no_closure"))] if let Some(captured) = _capture_scope { - if let Some(ref externals) = func.externals { + if !func.externals.is_empty() { captured .into_iter() - .filter(|(name, _, _, _)| externals.contains(name.as_ref())) + .filter(|(name, _, _, _)| func.externals.contains(name.as_ref())) .for_each(|(name, typ, value, _)| { // Consume the scope values. match typ { diff --git a/src/module/mod.rs b/src/module/mod.rs index 3b442415..9983faed 100644 --- a/src/module/mod.rs +++ b/src/module/mod.rs @@ -1392,7 +1392,7 @@ impl Module { }); // Modules left in the scope become sub-modules - mods.into_iter().for_each(|(alias, m)| { + mods.iter().for_each(|(alias, m)| { module.modules.insert(alias.to_string(), m.as_ref().clone()); }); @@ -1407,6 +1407,7 @@ impl Module { // Encapsulate AST environment let mut func = func.as_ref().clone(); func.lib = Some(ast_lib.clone()); + func.mods = mods.clone(); module.set_script_fn(func.into()); }); } diff --git a/src/optimize.rs b/src/optimize.rs index d627faf8..e2685662 100644 --- a/src/optimize.rs +++ b/src/optimize.rs @@ -869,6 +869,8 @@ pub fn optimize_into_ast( #[cfg(not(feature = "no_closure"))] externals: fn_def.externals.clone(), lib: None, + #[cfg(not(feature = "no_module"))] + mods: Default::default(), } .into() }) diff --git a/src/parser.rs b/src/parser.rs index 0a69acbb..daa73352 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -2485,13 +2485,11 @@ fn parse_fn( access, params, #[cfg(not(feature = "no_closure"))] - externals: if externals.is_empty() { - None - } else { - Some(Box::new(externals)) - }, + externals, body, lib: None, + #[cfg(not(feature = "no_module"))] + mods: Default::default(), }) } @@ -2661,6 +2659,8 @@ fn parse_anon_fn( externals: Default::default(), body, lib: None, + #[cfg(not(feature = "no_module"))] + mods: Default::default(), }; let expr = Expr::FnPointer(Box::new(IdentX::new(fn_name, settings.pos)));