Technical Documentation: rhaiscript/rhai
โน๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference
Overview (`README.md`)
Rhai - Embedded Scripting for Rust
Rhai is an embedded scripting language and evaluation engine for Rust that gives a safe and easy way
to add scripting to any application.
Targets and builds
- All CPU and O/S targets supported by Rust, including:
- WebAssembly (WASM)
no-std
- Minimum Rust version 1.66.0
Standard features
- Simple language similar to JavaScript+Rust with dynamic typing.
- Fairly efficient evaluation - 1 million iterations in 0.14 sec on a single-core 2.6 GHz Linux VM running this script by the standard AST walker.
- Rhai Grain bytecodes compiler and VM for even faster evaluation (around 1.8-2x). Enable with the
grainfeature. - Tight integration with native Rust functions and types, including getters/setters, methods and indexers.
- Freely pass Rust values into a script as variables/constants via an external
Scope- all clonable Rust types are supported; no need to implement any special trait. Or tap directly into the variable resolution process. - Built-in support for most common data types including booleans, integers, floating-point numbers (including
Decimal), strings, Unicode characters, arrays (including packed byte arrays) and object maps. - Easily call a script-defined function from Rust.
- Relatively little
unsafecode (yes there are some for performance reasons). - Few dependencies - currently only
smallvec,thin-vec,num-traits,once_cell,ahash,bitflagsandsmartstring. - Re-entrant scripting engine can be made
Send + Sync(via thesyncfeature). - Compile once to AST form for repeated evaluations.
- Scripts are optimized (useful for template-based machine-generated scripts).
- Easy custom API development via plugins system powered by procedural macros.
- Function overloading and operator overloading.
- Dynamic dispatch via function pointers with additional support for currying.
- Closures (anonymous functions) that can capture shared values.
- Some syntactic support for object-oriented programming (OOP).
- Organize code base with dynamically-loadable modules, optionally overriding the resolution process.
- Serialization/deserialization support via serde (requires the
serdefeature). - Support for minimal builds by excluding unneeded language features.
- A debugging interface.
Protected against attacks
- Don't Panic guarantee - Any panic is a bug. Rhai subscribes to the motto that a library should never panic the host system, and is coded with this in mind.
- Sand-boxed - the scripting engine, if declared immutable, cannot mutate the containing environment unless explicitly permitted.
- Rugged - protected against malicious attacks (such as stack-overflow, over-sized data, and runaway scripts etc.) that may come from untrusted third-party user-land scripts.
- Track script evaluation progress and manually terminate a script run.
- Passes Miri.
For those who actually want their own language
- Use as a DSL.
- Disable certain language features such as looping.
- Further restrict the language by surgically disabling keywords and operators.
- Define custom operators.
- Extend the language with custom syntax.
Example
The scripts subdirectory contains sample Rhai scripts.
Below is the standard Fibonacci example for scripting languages:
// This Rhai script calculates the n-th Fibonacci number using a
// really dumb algorithm to test the speed of the scripting engine.
const TARGET = 28;
const REPEAT = 5;
const ANSWER = 317_811;
fn fib(n) {
if n < 2 {
n
} else {
fib(n-1) + fib(n-2)
}
}
print(`Running Fibonacci(${TARGET}) x ${REPEAT} times...`);
print("Ready... Go!");
let result;
let now = timestamp();
for n in 0..REPEAT {
result = fib(TARGET);
}
print(`Finished. Run time = ${now.elapsed} seconds.`);
print(`Fibonacci number #${TARGET} = ${result}`);
if result != ANSWER {
print(`The answer is WRONG! Should be ${ANSWER}!`);
}Project Site
Documentation
See The Rhai Book for details on the Rhai scripting engine and language.
Playground
An Online Playground is available with syntax-highlighting editor,
powered by WebAssembly.
Scripts can be evaluated directly from the editor.
License
Licensed under either of the following, at your choice:
Unless explicitly stated otherwise, any contribution intentionally submitted
for inclusion in this crate, as defined in the Apache-2.0 license, shall
be dual-licensed as above, without any additional terms or conditions.
Overview (`benches/README.md`)
Micro Benchmarks
Micro benchmarks to measure the speed of Rhai.
As with all micro benchmarks, take these with a grain of salt.
How to Run
cargo +nightly benchOverview (`codegen/README.md`)
Procedural Macros for Plugins
This crate holds procedural macros for code generation, supporting the plugins system
for Rhai.
This crate is automatically referenced by the Rhai crate.
Normally it should not be used directly.
Overview (`examples/README.md`)
Sample Applications
Standard Examples
| Example | Description |
|---|---|
arrays_and_structs |
shows how to register a Rust type and using it with arrays |
callback |
shows how to store a Rhai closure and call it later within Rust |
custom_types_and_methods |
shows how to register a Rust type and methods/getters/setters for it |
custom_types |
shows how to register a Rust type and methods/getters/setters using the CustomType trait. |
definitions |
shows how to generate definition files for use with the Rhai Language Server (requires the metadata feature) |
grain_bench |
comparison benchmarks for Rhai Grain bytecodes VM |
hello |
simple example that evaluates an expression and prints the result |
lazy_bench |
comparison benchmarks for lazy-loading |
pause_and_resume |
shows how to pause/resume/stop an Engine running in a separate thread via an MPSC channel |
reuse_scope |
evaluates two pieces of code in separate runs, but using a common Scope |
serde |
example to serialize and deserialize Rust types with serde (requires the serde feature) |
simple_fn |
shows how to register a simple Rust function |
strings |
shows different ways to register Rust functions taking string arguments |
threading |
shows how to communicate in duplex with an Engine running in a separate thread via a pair of MPSC channels |
Scriptable Event Handler With State Examples
Because of its popularity, included are sample implementations for the pattern
Scriptable Event Handler With State in different styles.
| Example | Handler Script | Description |
|---|---|---|
event_handler_main |
event_handler_main/script.rhai |
Main Style |
event_handler_js |
event_handler_js/script.rhai |
JS Style |
event_handler_map |
event_handler_map/script.rhai |
Map Style |
Running Examples
Examples can be run with the following command:
cargo run --example {example_name}Overview (`scripts/README.md`)
Testing Scripts
Testing scripts written in Rhai.
Install `rhai-run` Tool
Use the following command to install the rhai-run tool:
cargo install --path . --bin rhai-runHow to Run
Run scripts using the rhai-run tool:
rhai-run ./scripts/test_script_to_run.rhaior
cargo run --bin rhai-run ./scripts/test_script_to_run.rhaiOverview (`src/README.md`)
Source Structure
Root Sources
| Source file | Description |
|---|---|
lib.rs |
Crate root |
engine.rs |
The scripting engine, defines the Engine type |
tokenizer.rs |
Script tokenizer/lexer |
parser.rs |
Script parser |
optimizer.rs |
Script optimizer |
defer.rs |
Utilities for deferred clean-up of resources |
reify.rs |
Utilities for making generic types concrete |
tests.rs |
Unit tests (not integration tests, which are in the main tests sub-directory) |
Sub-Directories
| Sub-directory | Description |
|---|---|
config |
Configuration |
types |
Common data types (e.g. Dynamic, errors) |
api |
Public API for the scripting engine |
ast |
AST definition |
module |
Support for modules |
packages |
Pre-defined packages |
func |
Registering and calling functions (native Rust and script-defined) |
eval |
AST evaluation |
serde |
Support for serde and metadata |
grain |
The Rhai Grain bytecodes compiler and VM |
bin |
Pre-built CLI binaries |
Overview (`tests/README.md`)
Tests
Rhai engine tests.
How to Run
cargo test --features bin-featuresOverview (`tools/README.md`)
Build Tools
This directory contains input files for various build tools required for building Rhai.
| File | Build tool | Description |
|---|---|---|
keywords.txt |
GNU gperf |
Input file for the tokenizer – keywords recognition. |
reserved.txt |
GNU gperf |
Input file for the tokenizer – reserved symbols recognition. |
Overview (`no_std/no_std_test/README.md`)
`no-std` Test Sample
This sample application is a bare-bones no-std build for testing.
wee_alloc is used as the allocator.
To Build
The nightly compiler is required:
cargo +nightly build --releaseA specific profile can also be used:
cargo +nightly build --profile unixThree profiles are defined: unix, windows and macos.
The release build is optimized for size. It can be changed to optimize on speed instead.
Overview (`src/bin/README.md`)
Rhai Tools
Tools for working with Rhai scripts.
| Tool | Required feature(s) | Description |
|---|---|---|
rhai-run |
runs each filename passed to it as a Rhai script, or as Rhai Grain bytecodes (requires the grain feature) |
|
rhai-repl |
rustyline |
a simple REPL that interactively evaluates statements |
rhai-dbg |
debugging |
the Rhai Debugger |
grain-compile |
grain |
compile a Rhai script to Rhai Grain bytecodes |
grain-dump |
grain |
print the disassembly of a Rhai Grain bytecodes program |
For convenience, a feature named bin-features is available which is a combination of the following:
decimal– support for decimal numbersmetadata– access functions metadataserde– export functions metadata to JSONdebugging– required byrhai-dbgrustyline– required byrhai-repl
How to Run
cargo run --features bin-features --bin sample_app_to_runHow to Install
To install these all tools (with full features), use the following command:
cargo install --path . --bins --features bin-featuresor specifically:
cargo install --path . --bin sample_app_to_run --features bin-features--- METRICS ---
- Files Extracted: 10
- Estimated Token Budget: ~4980 tokens
- Canonical Reference: https://codewiki.google/github.com/rhaiscript/rhai