Add complete_namespace to Module::eval_ast_as_new.

This commit is contained in:
Stephen Chung
2020-09-25 18:07:39 +08:00
parent 93f53fa417
commit 599fe846cb
7 changed files with 191 additions and 102 deletions

View File

@@ -44,7 +44,13 @@ let ast = engine.compile(r#"
"#)?;
// Convert the 'AST' into a module, using the 'Engine' to evaluate it first
let module = Module::eval_ast_as_new(Scope::new(), &ast, &engine)?;
//
// The second parameter ('private_namespace'), when set to true, will encapsulate
// a copy of the entire 'AST' into each function, allowing functions in the module script
// to cross-call each other. Otherwise module script functions access the global namespace.
//
// This incurs additional overhead, avoidable by setting 'private_namespace' to false.
let module = Module::eval_ast_as_new(Scope::new(), &ast, true, &engine)?;
// 'module' now can be loaded into a custom 'Scope' for future use. It contains:
// - sub-module: 'foobar' (renamed from 'extra')

View File

@@ -3,10 +3,10 @@ Export Variables, Functions and Sub-Modules in Module
{{#include ../../links.md}}
A _module_ is a single script (or pre-compiled [`AST`]) containing global variables, functions and sub-modules.
A _module_ can be created from a single script (or pre-compiled [`AST`]) containing global variables,
functions and sub-modules via the `Module::eval_ast_as_new` method.
A module can be created from a script via the `Module::eval_ast_as_new` method. When given an [`AST`],
it is first evaluated, then the following items are exposed as members of the new module:
When given an [`AST`], it is first evaluated, then the following items are exposed as members of the new module:
* Global variables - essentially all variables that remain in the [`Scope`] at the end of a script run - that are exported. Variables not exported (via the `export` statement) remain hidden.
@@ -14,6 +14,14 @@ it is first evaluated, then the following items are exposed as members of the ne
* Global modules that remain in the [`Scope`] at the end of a script run.
The parameter `private_namespace` in `Module::eval_ast_as_new` determines the exact behavior of
functions exposed by the module and the namespace that they can access:
| `private_namespace` value | Behavior of module functions | Namespace | Call global functions | Call functions in same module |
| :-----------------------: | ---------------------------------------------------- | :-------: | :-------------------: | :---------------------------: |
| `true` | encapsulate the entire `AST` into each function call | module | no | yes |
| `false` | register each function independently | global | yes | no |
Global Variables
----------------