Encapsulate imported modules into AST.
This commit is contained in:
parent
821e64adc4
commit
e69444293c
@ -18,12 +18,14 @@ Breaking changes
|
||||
|
||||
* Modules imported at global level can now be accessed in functions.
|
||||
* `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
|
||||
------------
|
||||
|
||||
* 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.
|
||||
|
@ -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
|
||||
|
10
src/ast.rs
10
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<Shared<Module>>,
|
||||
/// 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<String>,
|
||||
/// Access to external variables. Boxed because it occurs rarely.
|
||||
/// Access to external variables.
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
pub externals: Option<Box<HashSet<String>>>,
|
||||
pub externals: HashSet<String>,
|
||||
}
|
||||
|
||||
impl fmt::Display for ScriptFnDef {
|
||||
|
@ -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
|
||||
// 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<Module>, ImmutableString)>);
|
||||
pub struct Imports(StaticVec<(ImmutableString, Shared<Module>)>);
|
||||
|
||||
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<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.
|
||||
pub fn find(&self, name: &str) -> Option<usize> {
|
||||
@ -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<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.
|
||||
pub fn truncate(&mut self, size: usize) {
|
||||
@ -112,11 +112,22 @@ impl Imports {
|
||||
pub fn iter(&self) -> impl Iterator<Item = (&str, Shared<Module>)> {
|
||||
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<Item = (ImmutableString, Shared<Module>)> + 'a {
|
||||
self.0.iter().cloned()
|
||||
}
|
||||
/// Get a consuming iterator to this stack of imported modules.
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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 {
|
||||
|
@ -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());
|
||||
});
|
||||
}
|
||||
|
@ -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()
|
||||
})
|
||||
|
@ -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)));
|
||||
|
Loading…
Reference in New Issue
Block a user