rhai Documentation

Rhai - An embedded scripting language for Rust.

RAW Doc

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

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

Example

The scripts subdirectory contains sample Rhai scripts.

Below is the standard Fibonacci example for scripting languages:

ts
// 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

rhai.rs

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

bash
cargo +nightly bench

Overview (`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:

sh
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:

sh
cargo install --path . --bin rhai-run

How to Run

Run scripts using the rhai-run tool:

sh
rhai-run ./scripts/test_script_to_run.rhai

or

sh
cargo run --bin rhai-run ./scripts/test_script_to_run.rhai

Overview (`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

bash
cargo test --features bin-features

Overview (`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:

bash
cargo +nightly build --release

A specific profile can also be used:

bash
cargo +nightly build --profile unix

Three 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 numbers
  • metadata – access functions metadata
  • serde – export functions metadata to JSON
  • debugging – required by rhai-dbg
  • rustyline – required by rhai-repl

How to Run

sh
cargo run --features bin-features --bin sample_app_to_run

How to Install

To install these all tools (with full features), use the following command:

sh
cargo install --path . --bins  --features bin-features

or specifically:

sh
cargo install --path . --bin sample_app_to_run  --features bin-features

--- METRICS ---