Rename packages to global modules.

This commit is contained in:
Stephen Chung
2020-12-22 23:45:14 +08:00
parent eb46ec8296
commit 15fb03218c
34 changed files with 192 additions and 218 deletions

View File

@@ -43,8 +43,7 @@ The Rhai Scripting Language
4. [Printing Custom Types](rust/print-custom.md)
9. [Packages](rust/packages/index.md)
1. [Built-in Packages](rust/packages/builtin.md)
2. [Load a Plugin Module as a Package](rust/packages/plugin.md)
3. [Manually Create a Custom Package](rust/packages/create.md)
2. [Custom Packages](rust/packages/create.md)
10. [Modules](rust/modules/index.md)
1. [Create from Rust](rust/modules/create.md)
2. [Create from AST](rust/modules/ast.md)

View File

@@ -20,9 +20,9 @@ Functions from the following sources are included:
1) Script-defined functions in an [`AST`] (for `Engine::gen_fn_metadata_with_ast_to_json`)
2) Native Rust functions registered into the global namespace via the `Engine::register_XXX` API
3) _Public_ (i.e. non-[`private`]) functions (native Rust or Rhai scripted) in global sub-modules registered via
[`Engine::register_module`]({{rootUrl}}/rust/modules/create.md)
4) Native Rust functions in registered [packages] (optional)
3) _Public_ (i.e. non-[`private`]) functions (native Rust or Rhai scripted) in static modules
registered via `Engine::register_static_module`
4) Native Rust functions in global modules registered via `Engine::register_global_module` (optional)
Notice that if a function has been [overloaded][function overloading], only the overriding function's
metadata is included.

View File

@@ -17,9 +17,9 @@ As part of a _reflections_ API, `Engine::gen_fn_signatures` returns a list of fu
Functions from the following sources are included, in order:
1) Native Rust functions registered into the global namespace via the `Engine::register_XXX` API
2) _Public_ (i.e. non-[`private`]) functions (native Rust or Rhai scripted) in global sub-modules registered via
[`Engine::register_module`]({{rootUrl}}/rust/modules/create.md)
3) Native Rust functions in registered [packages] (optional)
2) _Public_ (i.e. non-[`private`]) functions (native Rust or Rhai scripted) in global sub-modules
registered via `Engine::register_static_module`.
3) Native Rust functions in global modules registered via `Engine::register_global_module` (optional)
Functions Metadata

View File

@@ -15,10 +15,10 @@ allow combining all functions in one [`AST`] into another, forming a new, unifie
In general, there are two types of _namespaces_ where functions are looked up:
| Namespace | How Many | Source | Lookup method | Sub-modules? | Variables? |
| --------- | :------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | :----------: | :--------: |
| Global | One | 1) [`AST`] being evaluated<br/>2) `Engine::register_XXX` API<br/>3) [packages] loaded<br/>4) functions in [modules] loaded via `Engine::register_module` and marked _global_ | simple function name | ignored | ignored |
| Module | Many | [`Module`] | namespace-qualified function name | yes | yes |
| Namespace | How Many | Source | Lookup method | Sub-modules? | Variables? |
| --------- | :------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | :----------: | :--------: |
| Global | One | 1) [`AST`] being evaluated<br/>2) `Engine::register_XXX` API<br/>3) global [modules] loaded via `Engine::register_global_module`<br/>4) functions in static [modules] loaded via `Engine::register_static_module` and marked _global_ | simple function name | ignored | ignored |
| Module | Many | [`Module`] | namespace-qualified function name | yes | yes |
Module Namespace
@@ -52,9 +52,10 @@ There is one _global_ namespace for every [`Engine`], which includes (in the fol
* All native Rust functions and iterators registered via the `Engine::register_XXX` API.
* All functions and iterators defined in [packages] that are loaded into the [`Engine`].
* All functions and iterators defined in global [modules] that are registered into the [`Engine`] via
`Engine::register_global_module`.
* Functions defined in [modules] loaded via `Engine::register_module` that are specifically marked
* Functions defined in [modules] loaded via `Engine::register_static_module` that are specifically marked
for exposure to the global namespace (e.g. via the `#[rhai(global)]` attribute in a [plugin module]).
Anywhere in a Rhai script, when a function call is made, the function is searched within the

View File

@@ -172,7 +172,7 @@ Functions from the following sources are returned, in order:
1) Encapsulated script environment (e.g. when loading a [module] from a script file),
2) Current script,
3) [Modules] imported via the [`import`] statement (latest imports first),
4) [Modules] added via [`Engine::register_module`]({{rootUrl}}/rust/modules/create.md) (latest registrations first)
4) [Modules] added via [`Engine::register_static_module`]({{rootUrl}}/rust/modules/create.md) (latest registrations first)
The return value is an [array] of [object maps] (so `get_fn_metadata_list` is not available under
[`no_index`] or [`no_object`]), containing the following fields:

View File

@@ -4,7 +4,7 @@ Export Variables, Functions and Sub-Modules in Module
{{#include ../../links.md}}
The easiest way to expose a package of functions as a self-contained [module] is to do it via a Rhai script itself.
The easiest way to expose a collection of functions as a self-contained [module] is to do it via a Rhai script itself.
See the section on [_Creating a Module from AST_]({{rootUrl}}/rust/modules/ast.md) for more details.

View File

@@ -116,7 +116,7 @@ let mut engine = Engine::new();
// Load the module as the module namespace "MyEnum"
engine
.register_type_with_name::<MyEnum>("MyEnum")
.register_module("MyEnum", exported_module!(MyEnumModule));
.register_static_module("MyEnum", exported_module!(MyEnumModule));
```
With this API in place, working with enums feels almost the same as in Rust:

View File

@@ -100,7 +100,7 @@ impl Handler {
// Register custom types and API's
engine
.register_type_with_name::<SomeType>("SomeType")
.load_package(exported_module!(SomeTypeAPI));
.register_global_module(exported_module!(SomeTypeAPI));
// Create a custom 'Scope' to hold state
let mut scope = Scope::new();

View File

@@ -20,7 +20,8 @@ Usage Scenario
Key Concepts
------------
* Create a single instance of each standard [package] required. To duplicate `Engine::new`, create a [`StandardPackage`]({{rootUrl}}/rust/packages/builtin.md).
* Create a single instance of each standard [package] required.
To duplicate `Engine::new`, create a [`StandardPackage`]({{rootUrl}}/rust/packages/builtin.md).
* Gather up all common custom functions into a [custom package].
@@ -29,10 +30,14 @@ Key Concepts
* Always use `Engine::new_raw` to create a [raw `Engine`], instead of `Engine::new` which is _much_ more expensive.
A [raw `Engine`] is _extremely_ cheap to create.
Loading the [`StandardPackage`]({{rootUrl}}/rust/packages/builtin.md) into a [raw `Engine`] via `Engine::load_package` is essentially the same as `Engine::new`.
But because packages are shared, loading an existing package is _much cheaper_ than registering all the functions one by one.
Registering the [`StandardPackage`]({{rootUrl}}/rust/packages/builtin.md) into a [raw `Engine`] via
`Engine::register_global_module` is essentially the same as `Engine::new`.
However, because packages are shared, using existing package is _much cheaper_ than
registering all the functions one by one.
* Load the required packages into the [raw `Engine`] via `Engine::load_package`, using `Package::get` to obtain a shared copy.
* Register the required packages with the [raw `Engine`] via `Engine::register_global_module`,
using `Package::as_shared_module` to obtain a shared [module].
Examples
@@ -46,17 +51,17 @@ let std_pkg = StandardPackage::new();
let custom_pkg = MyCustomPackage::new();
let make_call = |x: i64| -> Result<(), Box<EvalAltResult>> {
// Create a raw Engine - extremely cheap.
// Create a raw Engine - extremely cheap
let mut engine = Engine::new_raw();
// Load packages - cheap.
engine.load_package(std_pkg.get());
engine.load_package(custom_pkg.get());
// Register packages as global modules - cheap
engine.register_global_module(std_pkg.as_shared_module());
engine.register_global_module(custom_pkg.as_shared_module());
// Create custom scope - cheap.
// Create custom scope - cheap
let mut scope = Scope::new();
// Push variable into scope - relatively cheap.
// Push variable into scope - relatively cheap
scope.push("x", x);
// Evaluate script.

View File

@@ -146,7 +146,7 @@ pub mod bunny_api {
}
}
engine.load_package(exported_module!(bunny_api));
engine.register_global_module(exported_module!(bunny_api));
```
### Push Constant Command Object into Custom Scope

View File

@@ -28,11 +28,11 @@ and is custom fit to each exported item.
All `pub` functions become registered functions, all `pub` constants become [module] constant variables,
and all sub-modules become Rhai sub-modules.
This Rust module can then either be loaded into an [`Engine`] as a normal [module] or
registered as a [package]. This is done by using the `exported_module!` macro.
This Rust module can then be registered into an [`Engine`] as a normal [module].
This is done via the `exported_module!` macro.
The macro `combine_with_exported_module!` can also be used to _combine_ all the functions
and variables into an existing module, _flattening_ the namespace - i.e. all sub-modules
The macro `combine_with_exported_module!` can be used to _combine_ all the functions
and variables into an existing [module], _flattening_ the namespace - i.e. all sub-modules
are eliminated and their contents promoted to the top level. This is typical for
developing [custom packages].
@@ -42,7 +42,7 @@ use rhai::plugin::*; // a "prelude" import for macros
#[export_module]
mod my_module {
// This constant will be registered as the constant variable 'MY_NUMBER'.
// Ignored when loaded as a package.
// Ignored when registered as a global module.
pub const MY_NUMBER: i64 = 42;
// This function will be registered as 'greet'.
@@ -64,9 +64,9 @@ mod my_module {
42
}
// Sub-modules are ignored when the Module is loaded as a package.
// Sub-modules are ignored when the module is registered globally.
pub mod my_sub_module {
// This function is ignored when loaded as a package.
// This function is ignored when registered globally.
// Otherwise it is a valid registered function under a sub-module.
pub fn get_info() -> String {
"hello".to_string()
@@ -78,7 +78,7 @@ mod my_module {
// This is currently a limitation of the plugin procedural macros.
#[cfg(feature = "advanced_functions")]
pub mod advanced {
// This function is ignored when loaded as a package.
// This function is ignored when registered globally.
// Otherwise it is a valid registered function under a sub-module
// which only exists when the 'advanced_functions' feature is used.
pub fn advanced_calc(input: i64) -> i64 {
@@ -88,10 +88,10 @@ mod my_module {
}
```
### Use `Engine::load_package`
### Use `Engine::register_global_module`
The simplest way to load this into an [`Engine`] is to first use the `exported_module!` macro
to turn it into a normal Rhai [module], then use the `Engine::load_package` method on it:
The simplest way to register this into an [`Engine`] is to first use the `exported_module!` macro
to turn it into a normal Rhai [module], then use the `Engine::register_global_module` method on it:
```rust
fn main() {
@@ -100,13 +100,13 @@ fn main() {
// The macro call creates a Rhai module from the plugin module.
let module = exported_module!(my_module);
// A module can simply be loaded, registering all public functions.
engine.load_package(module);
// A module can simply be registered into the global namespace.
engine.register_global_module(module);
}
```
The functions contained within the module definition (i.e. `greet`, `get_num` and `increment`)
are automatically registered into the [`Engine`] when `Engine::load_package` is called.
are automatically registered into the [`Engine`] when `Engine::register_global_module` is called.
```rust
let x = greet("world");
@@ -123,12 +123,14 @@ x == 43;
```
Notice that, when using a [module] as a [package], only functions registered at the _top level_
can be accessed. Variables as well as sub-modules are ignored.
can be accessed.
### Use `Engine::register_module`
Variables as well as sub-modules are **ignored**.
Another simple way to load this into an [`Engine`] is, again, to use the `exported_module!` macro
to turn it into a normal Rhai [module], then use the `Engine::register_module` method on it:
### Use `Engine::register_static_module`
Another simple way to register this into an [`Engine`] is, again, to use the `exported_module!` macro
to turn it into a normal Rhai [module], then use the `Engine::register_static_module` method on it:
```rust
fn main() {
@@ -137,13 +139,13 @@ fn main() {
// The macro call creates a Rhai module from the plugin module.
let module = exported_module!(my_module);
// A module can simply be loaded as a globally-available module.
engine.register_module("service", module);
// A module can simply be registered as a static module namespace.
engine.register_static_module("service", module);
}
```
The functions contained within the module definition (i.e. `greet`, `get_num` and `increment`),
plus the constant `MY_NUMBER`, are automatically loaded under the module namespace `service`:
plus the constant `MY_NUMBER`, are automatically registered under the module namespace `service`:
```rust
let x = service::greet("world");
@@ -178,14 +180,14 @@ x.increment();
x == 43;
```
### Use as loadable `Module`
### Use Dynamically
Using this directly as a dynamically-loadable Rhai [module] is almost the same, except that a
[module resolver] must be used to serve the module, and the module is loaded via `import` statements.
See the [module] section for more information.
### Use as custom package
### Combine into Custom Package
Finally the plugin module can also be used to develop a [custom package],
using `combine_with_exported_module!`:

View File

@@ -19,14 +19,16 @@ Manually creating a [module] is possible via the `Module` API.
For the complete `Module` API, refer to the [documentation](https://docs.rs/rhai/{{version}}/rhai/struct.Module.html) online.
Make the `Module` Available to the `Engine`
------------------------------------------
Make the `Module` Globally Available
-----------------------------------
`Engine::load_package` supports loading a [module] as a [package].
`Engine::register_global_module` registers a shared [module] into the _global_ namespace.
Since it acts as a [package], all functions will be registered into the _global_ namespace
and can be accessed without _namespace qualifiers_. This is by far the easiest way to expose
a module's functionalities to Rhai.
All [functions] and [type iterators] can be accessed without _namespace qualifiers_.
Variables and sub-modules are **ignored**.
This is by far the easiest way to expose a module's functionalities to Rhai.
```rust
use rhai::{Engine, Module};
@@ -40,18 +42,18 @@ let hash = module.set_fn_1("inc", |x: i64| Ok(x+1));
// 'set_fn_XXX' by default does not set function metadata.
module.update_fn_metadata(hash, ["x: i64", "i64"]);
// Load the module into the Engine as a new package.
// Register the module into the global namespace of the Engine.
let mut engine = Engine::new();
engine.load_package(module);
engine.register_global_module(module);
engine.eval::<i64>("inc(41)")? == 42; // no need to import module
```
Make the `Module` a Global Module
------------------------------------
Make the `Module` a Static Module
--------------------------------
`Engine::register_module` loads a [module] and makes it available globally under a specific namespace.
`Engine::register_static_module` registers a [module] and under a specific module namespace.
```rust
use rhai::{Engine, Module};
@@ -65,9 +67,9 @@ let hash = module.set_fn_1("inc", |x: i64| Ok(x+1));
// 'set_fn_XXX' by default does not set function metadata.
module.update_fn_metadata(hash, ["x: i64", "i64"]);
// Load the module into the Engine as a sub-module named 'calc'
// Register the module into the Engine as a static module namespace 'calc'
let mut engine = Engine::new();
engine.register_module("calc", module);
engine.register_static_module("calc", module);
engine.eval::<i64>("calc::inc(41)")? == 42; // refer to the 'Calc' module
```
@@ -89,9 +91,9 @@ let hash = module.set_fn_1_mut("inc", FnNamespace::Global, |x: &mut i64| Ok(x+1)
// 'set_fn_XXX' by default does not set function metadata.
module.update_fn_metadata(hash, ["x: &mut i64", "i64"]);
// Load the module into the Engine as a sub-module named 'calc'
// Register the module into the Engine as a static module namespace 'calc'
let mut engine = Engine::new();
engine.register_module("calc", module);
engine.register_static_module("calc", module);
// The method 'inc' works as expected because it is exposed to the global namespace
engine.eval::<i64>("let x = 41; x.inc()")? == 42;

View File

@@ -35,5 +35,6 @@ use rhai::packages::{Package, CorePackage};
let mut engine = Engine::new_raw();
let package = CorePackage::new();
engine.load_package(package.get());
// Register the package into the Engine by converting it into a shared module.
engine.register_global_module(package.as_shared_module());
```

View File

@@ -1,17 +1,17 @@
Manually Create a Custom Package
===============================
Create a Custom Package
=======================
{{#include ../../links.md}}
Sometimes specific functionalities are needed, so custom packages can be created.
A custom package is a convenient means to gather up a number of functions for later use.
An [`Engine`] only needs to `Engine::load_package` the custom package once to gain access
An [`Engine`] only needs to `Engine::register_global_module` the custom package once to gain access
to the entire set of functions within.
Loading a package into an [`Engine`] is functionally equivalent to calling `Engine::register_fn` etc.
on _each_ of the functions inside the package. But because packages are _shared_, loading an existing
package is _much_ cheaper than registering all the functions one by one.
Registering a package into an [`Engine`] is functionally equivalent to calling `Engine::register_fn` etc.
on _each_ of the functions inside the package. But because packages are _shared_, using a package is
_much_ cheaper than registering all the functions one by one.
The macro `rhai::def_package!` can be used to create a new custom package.

View File

@@ -3,16 +3,17 @@ Packages
{{#include ../../links.md}}
Standard built-in Rhai features are provided in various _packages_ that can be loaded via a call to `Engine::load_package`.
Standard built-in Rhai features are provided in various _packages_ that can be registered into the
_global namespace_ of an [`Engine`] via `Engine::register_global_module`.
Packages reside under `rhai::packages::*` and the trait `rhai::packages::Package` must be loaded in order for
packages to be used.
Packages typically contain Rust functions that are callable within a Rhai script.
All functions registered in a package is loaded under the _global namespace_
All _top-level_ functions in a package are available under the _global namespace_
(i.e. they're available without namespace qualifiers).
Once a package is created (e.g. via `Package::new`), it can be _shared_ (via `Package::get`)
Once a package is created (e.g. via `Package::new`), it can be _shared_ (via `Package::as_shared_module`)
among multiple instances of [`Engine`], even across threads (under [`sync`]).
Therefore, a package only has to be created _once_.
@@ -21,43 +22,21 @@ use rhai::Engine;
use rhai::packages::Package // load the 'Package' trait to use packages
use rhai::packages::CorePackage; // the 'core' package contains basic functionalities (e.g. arithmetic)
let mut engine = Engine::new_raw(); // create a 'raw' Engine
let package = CorePackage::new(); // create a package - can be shared among multiple `Engine` instances
// Create a 'raw' Engine
let mut engine = Engine::new_raw();
engine.load_package(package.get()); // load the package manually. 'get' returns a reference to the shared package
// Create a package - can be shared among multiple `Engine` instances
let package = CorePackage::new();
// Register the package into the global namespace.
// 'Package::as_shared_module' converts the package into a shared module.
engine.register_global_module(package.as_shared_module());
```
Difference Between a Package and a Module
----------------------------------------
Share a Package Among `Engine`s
------------------------------
Packages are internally implemented as [modules], so they share a lot of behavior and characteristics.
`Engine::register_global_module` consumes the input shared module.
The main difference is that a package loads under the _global_ namespace, while a module loads under its own
namespace alias specified in an [`import`] statement (see also [modules]).
A package is _static_ (i.e. pre-loaded into an [`Engine`]), while a module is _dynamic_ (i.e. loaded with
the `import` statement).
Sub-modules in a package are _flattened_, meaning that functions from them must be pulled up to the root level.
In other words, there can be no sub-modules in a package, and everything should reside in one, flat namespace.
Only functions matter for a package. Constant variables registered in a package are ignored.
Load a Module as a Package
--------------------------
Stand-alone [modules] can be loaded directly into an [`Engine`] as a package via the same `Engine::load_package` API.
```rust
let mut module = Module::new();
:
// add functions into module
:
engine.load_package(module);
```
[Modules], however, are not _shared_, so use a [custom package] if it must be shared among multiple
instances of [`Engine`].
However, `Package::as_shared_module` can be called multiple times for multiple instances of [`Engine`].

View File

@@ -1,42 +0,0 @@
Load a Plugin Module as a Package
================================
{{#include ../../links.md}}
[Plugin modules] can be loaded as a package just like a normal [module]
via the `exported_module!` macro.
```rust
use rhai::Engine;
use rhai::plugin::*;
// Define plugin module.
#[export_module]
mod my_module {
pub fn greet(name: &str) -> String {
format!("hello, {}!", name)
}
pub fn get_num() -> i64 {
42
}
}
fn main() {
let mut engine = Engine::new();
// Create plugin module.
let module = exported_module!(my_module);
// Make the 'greet' and 'get_num' functions available to scripts.
engine.load_package(module);
}
```
Share a Package Among `Engine`s
------------------------------
Loading a [module] via `Engine::load_package` consumes the module and it cannot be used again.
If the functions are needed for multiple instances of [`Engine`], create a [custom package] from the
[plugin module], which can then be shared with `Package::get`.

View File

@@ -49,6 +49,6 @@ Use a Raw [`Engine`]
A _raw_ engine supports, out of the box, only a very [restricted set]({{rootUrl}}/engine/raw.md#built-in-operators)
of basic arithmetic and logical operators.
Selectively include other necessary functionalities by loading specific [packages] to minimize the footprint.
Selectively include other necessary functionalities by picking specific [packages] to minimize the footprint.
Packages are sharable (even across threads via the [`sync`] feature), so they only have to be created once.
Packages are shared (even across threads via the [`sync`] feature), so they only have to be created once.