Crate rhai

Source
Expand description

§Rhai - embedded scripting for Rust

Rhai logo

Rhai is a tiny, simple and fast embedded scripting language for Rust that gives you a safe and easy way to add scripting to your applications.

It provides a familiar syntax based on JavaScript+Rust and a simple Rust interface.

§A Quick Example

§Contents of my_script.rhai

/// Brute force factorial function
fn factorial(x) {
    if x == 1 { return 1; }
    x * factorial(x - 1)
}

// Calling an external function 'compute'
compute(factorial(10))

§The Rust part

use rhai::{Engine, EvalAltResult};

fn main() -> Result<(), Box<EvalAltResult>>
{
    // Define external function
    fn compute_something(x: i64) -> bool {
        (x % 40) == 0
    }

    // Create scripting engine
    let mut engine = Engine::new();

    // Register external function as 'compute'
    engine.register_fn("compute", compute_something);

    // Evaluate the script, expecting a 'bool' result
    let result: bool = engine.eval_file("my_script.rhai".into())?;

    assert_eq!(result, true);

    Ok(())
}

§Features

  • default — Default features: std, uses runtime random numbers for hashing.
  • std (enabled by default) — Standard features: uses compile-time random number for hashing.

§Enable Special Functionalities

  • sync — Require that all data types implement Send + Sync (for multi-threaded usage).
  • decimal — Add support for the Decimal data type (acts as the system floating-point type under no_float).
  • serde — Enable serialization/deserialization of Rhai data types via serde.
  • unicode-xid-ident — Allow Unicode Standard Annex #31 for identifiers.
  • metadata — Enable functions metadata (including doc-comments); implies serde.
  • internals — Expose internal data structures (e.g. AST nodes).
  • debugging — Enable the debugging interface (implies internals).
  • bin-features — Features and dependencies required by bin tools: decimal, metadata, serde, debugging and rustyline.
  • fuzz — Enable fuzzing via the arbitrary crate.

§System Configuration Features

  • f32_float — Use f32 instead of f64 as the system floating-point number type.
  • only_i32 — Use i32 instead of i64 for the system integer number type (useful for 32-bit architectures). All other integer types (e.g. u8) are disabled.
  • only_i64 — Disable all integer types (e.g. u8) other than i64.

§Disable Language Features

  • no_float — Remove support for floating-point numbers.
  • no_index — Remove support for arrays and indexing.
  • no_object — Remove support for custom types, properties, method-style calls and object maps.
  • no_time — Remove support for time-stamps.
  • no_function — Remove support for script-defined functions (implies no_closure).
  • no_closure — Remove support for capturing external variables in anonymous functions (i.e. closures).
  • no_module — Remove support for loading external modules.
  • no_custom_syntax — Remove support for custom syntax.
  • unchecked — Disable all safety checks.
  • no_position — Do not track position when parsing.
  • no_optimize — Disable the script optimizer.

§Compiling for no-std

  • no_std — Turn on no-std compilation (nightly only).

§JavaScript Interface for WASM

  • wasm-bindgen — Use wasm-bindgen as JavaScript interface.
  • stdweb — Use stdweb as JavaScript interface.

§Features used in testing environments only

  • unstable — Compiled with a non-stable compiler (i.e. beta or nightly)
  • testing-environ — Running under a testing environment.

§On-Line Documentation

See The Rhai Book for details on the Rhai scripting engine and language.

Modules§

config
Configuration for Rhai.
debugger
(debugging) Module containing types for debugging. Exported under the debugging feature only.
default_limits
Default limits.
module_resolvers
Module containing all built-in module resolvers available to Rhai. Module containing all built-in module resolvers.
packages
Module containing all built-in packages available to Rhai, plus facilities to define custom packages.
plugin
Module defining macros for developing plugins.
serde
(serde) Serialization and deserialization support for serde. Exported under the serde feature only.

Macros§

combine_with_exported_module
Macro to combine a plugin module into an existing module.
def_package
Macro that makes it easy to define a package (which is basically a shared module) and register functions into it.
exported_module
Macro to generate a Rhai Module from a plugin module defined via #[export_module].
register_exported_fn
Macro to register a plugin function (defined via #[export_fn]) into an Engine.
set_exported_fn
Macro to register a plugin function into a Rhai Module.
set_exported_global_fn
Macro to register a plugin function into a Rhai Module and expose it globally.

Structs§

AST
Compiled AST (abstract syntax tree) of a Rhai script.
ASTFlags
(internals) Bit-flags containing AST node configuration options. Exported under the internals feature only.
BinaryExpr
(internals) A binary expression. Exported under the internals feature only.
BloomFilterU64
(internals) A simple bloom filter implementation for u64 hash values only - i.e. all 64 bits are assumed to be relatively random. Exported under the internals feature only.
Caches
(internals) A type containing system-wide caches. Exported under the internals feature only.
CallFnOptions
Options for calling a script-defined function via Engine::call_fn_with_options.
CustomExpr
(internals) A custom syntax expression. Exported under the internals feature only.
CustomTypeInfo
(internals) Information for a registered custom type. Exported under the internals feature only.
Definitions
(metadata, internals) Definitions helper type to generate definition files based on the contents of an Engine. Exported under the internals and metadata feature only.
Dynamic
Dynamic type containing any value.
DynamicReadLock
(internals) Lock guard for reading a Dynamic. Exported under the internals feature only.
DynamicWriteLock
(internals) Lock guard for writing a Dynamic. Exported under the internals feature only.
EncapsulatedEnviron
(internals) Encapsulated AST environment. Exported under the internals feature only.
Engine
Rhai main scripting engine.
EvalContext
Context of a script evaluation process.
Expression
An expression sub-tree in an AST.
FloatWrapper
(internals) A type that wraps a floating-point number and implements Hash. Exported under the internals feature only.
FlowControl
(internals) A flow control block containing:
FnCallExpr
(internals) A function call. Exported under the internals feature only.
FnCallHashes
(internals) A set of function call hashes. Exported under the internals feature only.
FnPtr
A general function pointer, which may carry additional (i.e. curried) argument values to be passed onto a function during a call.
FnResolutionCache
(internals) A function resolution cache with a bloom filter. Exported under the internals feature only.
FnResolutionCacheEntry
(internals) An entry in a function resolution cache. Exported under the internals feature only.
FuncInfo
Information about a function, native or scripted.
FuncMetadata
(internals) A type containing the metadata of a single registered function. Exported under the internals features only.
FuncRegistration
Type for fine-tuned module function registration.
GlobalRuntimeState
(internals) Global runtime states. Exported under the internals feature only.
Ident
(internals) An identifier containing a name and a position. Exported under the internals feature only.
ImmutableString
The system immutable string type.
Instant
A measurement of a monotonically nondecreasing clock. Opaque and useful only with Duration.
Locked
Alias to RefCell or RwLock depending on the sync feature flag. Synchronized shared object. A mutable memory location with dynamically checked borrow rules
Module
A module which may contain variables, sub-modules, external Rust functions, and/or script-defined functions.
MultiInputsStream
(internals) A type that implements the InputStream trait. Exported under the internals feature only.
Namespace
(internals) A chain of module names to namespace-qualify a variable or function call. Exported under the internals feature only.
NativeCallContext
Context of a native Rust function call.
NativeCallContextStoreDeprecated
(internals) Context of a native Rust function call, intended for persistence. Exported under the internals feature only.
OpAssignment
(internals) An op-assignment operator. Exported under the internals feature only.
ParseError
Error when parsing a script.
ParseState
(internals) A type that encapsulates the current state of the parser. Exported under the internals feature only.
Position
A location (line number + character position) in the input script.
Scope
Type containing information about the current scope. Useful for keeping state between Engine evaluation runs.
ScriptFnMetadata
A type containing the metadata of a script-defined function.
ScriptFuncDef
(internals) A type containing information on a script-defined function. Exported under the internals feature only.
Shared
Alias to Rc or Arc depending on the sync feature flag. Immutable reference-counted container. A single-threaded reference-counting pointer. ‘Rc’ stands for ‘Reference Counted’.
Span
(internals) A span consisting of a starting and an ending positions. Exported under the internals feature only.
StmtBlock
(internals) A scoped block of statements. Exported under the internals feature only.
StringsInterner
(internals) A cache for interned strings. Exported under the internals feature only.
SwitchCasesCollection
(internals) A type containing all cases for a switch statement. Exported under the internals feature only.
TokenIterator
(internals) An iterator on a Token stream. Exported under the internals feature only.
TokenizeState
(internals) State of the tokenizer. Exported under the internals feature only.
TokenizerControlBlock
(internals) A type containing commands to control the tokenizer.
TypeBuilder
Builder to build the API of a custom type for use with an Engine.
VarDefInfo
Information on a variable declaration.

Enums§

ASTNode
(internals) An AST node, consisting of either an Expr or a Stmt. Exported under the internals feature only.
AccessMode
(internals) Modes of access. Exported under the internals feature only.
EvalAltResult
Evaluation result.
Expr
(internals) An expression sub-tree. Exported under the internals feature only.
FnAccess
A type representing the access mode of a function.
FnNamespace
A type representing the namespace of a function.
LexError
Error encountered when tokenizing the script text.
OptimizationLevel
Level of optimization performed.
ParseErrorType
Error encountered when parsing a script.
RangeCase
(internals) A type containing a range case for a switch statement. Exported under the internals feature only.
RhaiFunc
(internals) A type encapsulating a function callable by Rhai. Exported under the internals feature only.
Stmt
(internals) A statement. Exported under the internals feature only.
Target
(internals) A type that encapsulates a mutation target for an expression with side effects. Exported under the internals feature only.
Token
(internals) A Rhai language token. Exported under the internals feature only.

Constants§

FUNC_TO_DEBUG
Standard debug-print function.
FUNC_TO_STRING
Standard pretty-print function.
OP_CONTAINS
Standard containment testing function.
OP_EQUALS
Standard equality comparison operator.

Traits§

CustomType
Trait to build the API of a custom type for use with an Engine (i.e. register the type and its getters, setters, methods, etc.).
Func
Trait to create a Rust closure from a script.
FuncArgs
Trait that parses arguments to a function call.
InputStream
(internals) Trait that encapsulates a peekable character input stream. Exported under the internals feature only.
ModuleResolver
Trait that encapsulates a module resolution service.
RhaiNativeFunc
Trait to register custom Rust functions.
Variant
(internals) Trait to represent any type. Exported under the internals feature only.

Functions§

eval
Evaluate a string as a script, returning the result value or an error.
eval_file
Evaluate a script file, returning the result value or an error.
format_map_as_json
Return the JSON representation of an object map.
get_next_token
(internals) Get the next token from the input stream. Exported under the internals feature only.
is_valid_function_name
(internals) Is a text string a valid script-defined function name? Exported under the internals feature only.
is_valid_identifier
(internals) Is a text string a valid identifier? Exported under the internals feature only.
locked_read
(internals) Lock a Locked resource for immutable access. Exported under the internals feature only.
locked_write
(internals) Lock a Locked resource for mutable access. Exported under the internals feature only.
parse_raw_string_literal
(internals) Parse a raw string literal. Exported under the internals feature only.
parse_string_literal
(internals) Parse a string literal ended by a specified termination character. Exported under the internals feature only.
run
Evaluate a string as a script.
run_file
Evaluate a file.

Type Aliases§

Array
Variable-sized array of Dynamic values.
Blob
Variable-sized array of u8 values (byte array).
FLOAT
The system floating-point type. It is defined as f64.
FnArgsVec
(internals) Inline arguments storage for function calls. Exported under the internals feature only.
INT
The system integer type. It is defined as i64.
Identifier
(internals) An identifier in Rhai. Exported under the internals feature only.
Map
A dictionary of Dynamic values with string keys.
StaticVec
(internals) Alias to smallvec::SmallVec<[T; 3]>, which is a Vec backed by a small, inline, fixed-size array when there are ≤ 3 items stored. Exported under the internals feature only.
ThinVec
(internals) A smaller Vec alternative. Exported under the internals feature only. Exported under the internals feature only.
TokenizerControl
(internals) A shared object that allows control of the tokenizer from outside.

Attribute Macros§

export_fn
Attribute, when put on a Rust function, turns it into a plugin function.
export_module
Attribute, when put on a Rust module, turns it into a plugin module.
expose_under_internals
Macro to automatically expose a Rust function, type-def or use statement as pub when under the internals feature.

Derive Macros§

CustomType
Macro to implement the [CustomType][rhai::CustomType] trait.