Merge pull request #290 from schungx/master

Encapsulate imported modules into AST.
This commit is contained in:
Stephen Chung 2020-11-09 22:04:12 +08:00 committed by GitHub
commit a55083feba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 47 additions and 17 deletions

View File

@ -18,12 +18,14 @@ 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. * `ModuleResolver::resolve` now returns `Shared<Module>` for better resources sharing when loading modules.
* `ParseErrorType::DuplicatedExport` is removed as multiple `export`'s are now allowed.
Enhancements 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. * 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. * Variables can now be `export`-ed multiple times under different names.
* `index_of`, `==` and `!=` are defined for arrays. * `index_of`, `==` and `!=` are defined for arrays.
* `==` and `!=` are defined for object maps. * `==` and `!=` are defined for object maps.

View File

@ -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, 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.
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. Modules are also _cached_ so a script file is only evaluated _once_, even when repeatedly imported.
```rust ```rust

View File

@ -18,6 +18,9 @@ use crate::engine::Array;
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
use crate::engine::{make_getter, make_setter, Map}; use crate::engine::{make_getter, make_setter, Map};
#[cfg(not(feature = "no_module"))]
use crate::engine::Imports;
use crate::stdlib::{ use crate::stdlib::{
any::TypeId, any::TypeId,
borrow::Cow, borrow::Cow,
@ -87,15 +90,18 @@ pub struct ScriptFnDef {
pub body: Stmt, pub body: Stmt,
/// Encapsulated running environment, if any. /// Encapsulated running environment, if any.
pub lib: Option<Shared<Module>>, pub lib: Option<Shared<Module>>,
/// Encapsulated imported modules.
#[cfg(not(feature = "no_module"))]
pub mods: Imports,
/// Function name. /// Function name.
pub name: ImmutableString, pub name: ImmutableString,
/// Function access mode. /// Function access mode.
pub access: FnAccess, pub access: FnAccess,
/// Names of function parameters. /// Names of function parameters.
pub params: StaticVec<String>, pub params: StaticVec<String>,
/// Access to external variables. Boxed because it occurs rarely. /// Access to external variables.
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
pub externals: Option<Box<HashSet<String>>>, pub externals: HashSet<String>,
} }
impl fmt::Display for ScriptFnDef { impl fmt::Display for ScriptFnDef {

View File

@ -75,7 +75,7 @@ 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.
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct Imports(StaticVec<(Shared<Module>, ImmutableString)>); pub struct Imports(StaticVec<(ImmutableString, Shared<Module>)>);
impl Imports { impl Imports {
/// Get the length of this stack of imported modules. /// Get the length of this stack of imported modules.
@ -88,7 +88,7 @@ impl Imports {
} }
/// Get the imported module at a particular index. /// Get the imported module at a particular index.
pub fn get(&self, index: usize) -> Option<Shared<Module>> { pub fn get(&self, index: usize) -> Option<Shared<Module>> {
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. /// 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> {
@ -96,12 +96,12 @@ impl Imports {
.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: impl Into<Shared<Module>>) { pub fn push(&mut self, name: impl Into<ImmutableString>, module: impl Into<Shared<Module>>) {
self.0.push((module.into(), name.into())); self.0.push((name.into(), module.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) {
@ -112,11 +112,22 @@ impl Imports {
pub fn iter(&self) -> impl Iterator<Item = (&str, Shared<Module>)> { pub fn iter(&self) -> impl Iterator<Item = (&str, Shared<Module>)> {
self.0 self.0
.iter() .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<Item = (ImmutableString, Shared<Module>)> + 'a {
self.0.iter().cloned()
} }
/// 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, Shared<Module>)> { pub fn into_iter(self) -> impl Iterator<Item = (ImmutableString, Shared<Module>)> {
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<Item = (ImmutableString, Shared<Module>)>) {
self.0.extend(stream)
} }
} }

View File

@ -391,6 +391,11 @@ impl Engine {
lib 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 // Evaluate the function at one higher level of call depth
let stmt = &fn_def.body; let stmt = &fn_def.body;
@ -541,10 +546,10 @@ impl Engine {
// Move captured variables into scope // Move captured variables into scope
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
if let Some(captured) = _capture_scope { if let Some(captured) = _capture_scope {
if let Some(ref externals) = func.externals { if !func.externals.is_empty() {
captured captured
.into_iter() .into_iter()
.filter(|(name, _, _, _)| externals.contains(name.as_ref())) .filter(|(name, _, _, _)| func.externals.contains(name.as_ref()))
.for_each(|(name, typ, value, _)| { .for_each(|(name, typ, value, _)| {
// Consume the scope values. // Consume the scope values.
match typ { match typ {

View File

@ -1392,7 +1392,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.iter().for_each(|(alias, m)| {
module.modules.insert(alias.to_string(), m.as_ref().clone()); module.modules.insert(alias.to_string(), m.as_ref().clone());
}); });
@ -1407,6 +1407,7 @@ impl Module {
// Encapsulate AST environment // Encapsulate AST environment
let mut func = func.as_ref().clone(); let mut func = func.as_ref().clone();
func.lib = Some(ast_lib.clone()); func.lib = Some(ast_lib.clone());
func.mods = mods.clone();
module.set_script_fn(func.into()); module.set_script_fn(func.into());
}); });
} }

View File

@ -869,6 +869,8 @@ 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(),
lib: None, lib: None,
#[cfg(not(feature = "no_module"))]
mods: Default::default(),
} }
.into() .into()
}) })

View File

@ -2485,13 +2485,11 @@ fn parse_fn(
access, access,
params, params,
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
externals: if externals.is_empty() { externals,
None
} else {
Some(Box::new(externals))
},
body, body,
lib: None, lib: None,
#[cfg(not(feature = "no_module"))]
mods: Default::default(),
}) })
} }
@ -2661,6 +2659,8 @@ fn parse_anon_fn(
externals: Default::default(), externals: Default::default(),
body, body,
lib: None, lib: None,
#[cfg(not(feature = "no_module"))]
mods: Default::default(),
}; };
let expr = Expr::FnPointer(Box::new(IdentX::new(fn_name, settings.pos))); let expr = Expr::FnPointer(Box::new(IdentX::new(fn_name, settings.pos)));