Struct bpxe::language::rhai::Rhai[][src]

pub struct Rhai { /* fields omitted */ }

Rhai language engine

Implementations

impl Rhai[src]

pub fn new() -> Self[src]

Creates a new Rhai engine

impl Rhai[src]

pub fn engine_mut(&mut self) -> Option<&mut Engine>[src]

Tries to get a mutable reference to the engine

Primarily useful for custom setup, tests, etc.

Methods from Deref<Target = Engine>

pub fn compile(&self, script: &str) -> Result<AST, ParseError>[src]

Compile a string into an AST, which can be used later for evaluation.

Example

use rhai::Engine;

let engine = Engine::new();

// Compile a script to an AST and store it for later evaluation
let ast = engine.compile("40 + 2")?;

for _ in 0..42 {
    assert_eq!(engine.eval_ast::<i64>(&ast)?, 42);
}

pub fn compile_with_scope(
    &self,
    scope: &Scope<'_>,
    script: &str
) -> Result<AST, ParseError>
[src]

Compile a string into an AST using own scope, which can be used later for evaluation.

The scope is useful for passing constants into the script for optimization when using OptimizationLevel::Full.

Example

use rhai::{Engine, Scope, OptimizationLevel};

let mut engine = Engine::new();

// Set optimization level to 'Full' so the Engine can fold constants
// into function calls and operators.
engine.set_optimization_level(OptimizationLevel::Full);

// Create initialized scope
let mut scope = Scope::new();
scope.push_constant("x", 42_i64);   // 'x' is a constant

// Compile a script to an AST and store it for later evaluation.
// Notice that `Full` optimization is on, so constants are folded
// into function calls and operators.
let ast = engine.compile_with_scope(&mut scope,
            "if x > 40 { x } else { 0 }"    // all 'x' are replaced with 42
)?;

// Normally this would have failed because no scope is passed into the 'eval_ast'
// call and so the variable 'x' does not exist.  Here, it passes because the script
// has been optimized and all references to 'x' are already gone.
assert_eq!(engine.eval_ast::<i64>(&ast)?, 42);

pub fn compile_into_self_contained(
    &self,
    scope: &Scope<'_>,
    script: &str
) -> Result<AST, Box<EvalAltResult, Global>>
[src]

Compile a string into an AST using own scope, which can be used later for evaluation, embedding all imported modules.

Modules referred by import statements containing literal string paths are eagerly resolved via the current module resolver and embedded into the resultant AST. When it is evaluated later, import statement directly recall pre-resolved modules and the resolution process is not performed again.

pub fn compile_scripts_with_scope(
    &self,
    scope: &Scope<'_>,
    scripts: &[&str]
) -> Result<AST, ParseError>
[src]

When passed a list of strings, first join the strings into one large script, and then compile them into an AST using own scope, which can be used later for evaluation.

The scope is useful for passing constants into the script for optimization when using OptimizationLevel::Full.

Note

All strings are simply parsed one after another with nothing inserted in between, not even a newline or space.

Example

use rhai::{Engine, Scope, OptimizationLevel};

let mut engine = Engine::new();

// Set optimization level to 'Full' so the Engine can fold constants
// into function calls and operators.
engine.set_optimization_level(OptimizationLevel::Full);

// Create initialized scope
let mut scope = Scope::new();
scope.push_constant("x", 42_i64);   // 'x' is a constant

// Compile a script made up of script segments to an AST and store it for later evaluation.
// Notice that `Full` optimization is on, so constants are folded
// into function calls and operators.
let ast = engine.compile_scripts_with_scope(&mut scope, &[
            "if x > 40",            // all 'x' are replaced with 42
            "{ x } el",
            "se { 0 }"              // segments do not need to be valid scripts!
])?;

// Normally this would have failed because no scope is passed into the 'eval_ast'
// call and so the variable 'x' does not exist.  Here, it passes because the script
// has been optimized and all references to 'x' are already gone.
assert_eq!(engine.eval_ast::<i64>(&ast)?, 42);

pub fn compile_file(
    &self,
    path: PathBuf
) -> Result<AST, Box<EvalAltResult, Global>>
[src]

Compile a script file into an AST, which can be used later for evaluation.

Not available under no_std or WASM.

Example

use rhai::Engine;

let engine = Engine::new();

// Compile a script file to an AST and store it for later evaluation.
// Notice that a PathBuf is required which can easily be constructed from a string.
let ast = engine.compile_file("script.rhai".into())?;

for _ in 0..42 {
    engine.eval_ast::<i64>(&ast)?;
}

pub fn compile_file_with_scope(
    &self,
    scope: &Scope<'_>,
    path: PathBuf
) -> Result<AST, Box<EvalAltResult, Global>>
[src]

Compile a script file into an AST using own scope, which can be used later for evaluation.

Not available under no_std or WASM.

The scope is useful for passing constants into the script for optimization when using OptimizationLevel::Full.

Example

use rhai::{Engine, Scope, OptimizationLevel};

let mut engine = Engine::new();

// Set optimization level to 'Full' so the Engine can fold constants.
engine.set_optimization_level(OptimizationLevel::Full);

// Create initialized scope
let mut scope = Scope::new();
scope.push_constant("x", 42_i64);   // 'x' is a constant

// Compile a script to an AST and store it for later evaluation.
// Notice that a PathBuf is required which can easily be constructed from a string.
let ast = engine.compile_file_with_scope(&mut scope, "script.rhai".into())?;

let result = engine.eval_ast::<i64>(&ast)?;

pub fn parse_json(
    &self,
    json: &str,
    has_null: bool
) -> Result<HashMap<ImmutableString, Dynamic, RandomState>, Box<EvalAltResult, Global>>
[src]

Parse a JSON string into an object map. This is a light-weight alternative to using, say, [serde_json][https://crates.io/crates/serde_json] to deserialize the JSON.

The JSON string must be an object hash. It cannot be a simple scalar value.

Set has_null to true in order to map null values to (). Setting it to false will cause an ErrorVariableNotFound error during parsing.

JSON With Sub-Objects

This method assumes no sub-objects in the JSON string. That is because the syntax of a JSON sub-object (or object hash), { .. }, is different from Rhai's syntax, #{ .. }. Parsing a JSON string with sub-objects will cause a syntax error.

If it is certain that the character { never appears in any text string within the JSON object, which is a valid assumption for many use cases, then globally replace { with #{ before calling this method.

Example

use rhai::{Engine, Map};

let engine = Engine::new();

let map = engine.parse_json(
    r#"{"a":123, "b":42, "c":{"x":false, "y":true}, "d":null}"#
        .replace("{", "#{").as_str(), true)?;

assert_eq!(map.len(), 4);
assert_eq!(map["a"].as_int().unwrap(), 123);
assert_eq!(map["b"].as_int().unwrap(), 42);
assert!(map["d"].is::<()>());

let c = map["c"].read_lock::<Map>().unwrap();
assert_eq!(c["x"].as_bool().unwrap(), false);

pub fn compile_expression(&self, script: &str) -> Result<AST, ParseError>[src]

Compile a string containing an expression into an AST, which can be used later for evaluation.

Example

use rhai::Engine;

let engine = Engine::new();

// Compile a script to an AST and store it for later evaluation
let ast = engine.compile_expression("40 + 2")?;

for _ in 0..42 {
    assert_eq!(engine.eval_ast::<i64>(&ast)?, 42);
}

pub fn compile_expression_with_scope(
    &self,
    scope: &Scope<'_>,
    script: &str
) -> Result<AST, ParseError>
[src]

Compile a string containing an expression into an AST using own scope, which can be used later for evaluation.

The scope is useful for passing constants into the script for optimization when using OptimizationLevel::Full.

Example

use rhai::{Engine, Scope, OptimizationLevel};

let mut engine = Engine::new();

// Set optimization level to 'Full' so the Engine can fold constants
// into function calls and operators.
engine.set_optimization_level(OptimizationLevel::Full);

// Create initialized scope
let mut scope = Scope::new();
scope.push_constant("x", 10_i64);   // 'x' is a constant

// Compile a script to an AST and store it for later evaluation.
// Notice that `Full` optimization is on, so constants are folded
// into function calls and operators.
let ast = engine.compile_expression_with_scope(&mut scope,
            "2 + (x + x) * 2"    // all 'x' are replaced with 10
)?;

// Normally this would have failed because no scope is passed into the 'eval_ast'
// call and so the variable 'x' does not exist.  Here, it passes because the script
// has been optimized and all references to 'x' are already gone.
assert_eq!(engine.eval_ast::<i64>(&ast)?, 42);

pub fn eval_file<T>(
    &self,
    path: PathBuf
) -> Result<T, Box<EvalAltResult, Global>> where
    T: Variant + Clone
[src]

Evaluate a script file.

Not available under no_std or WASM.

Example

use rhai::Engine;

let engine = Engine::new();

// Notice that a PathBuf is required which can easily be constructed from a string.
let result = engine.eval_file::<i64>("script.rhai".into())?;

pub fn eval_file_with_scope<T>(
    &self,
    scope: &mut Scope<'_>,
    path: PathBuf
) -> Result<T, Box<EvalAltResult, Global>> where
    T: Variant + Clone
[src]

Evaluate a script file with own scope.

Not available under no_std or WASM.

Example

use rhai::{Engine, Scope};

let engine = Engine::new();

// Create initialized scope
let mut scope = Scope::new();
scope.push("x", 42_i64);

// Notice that a PathBuf is required which can easily be constructed from a string.
let result = engine.eval_file_with_scope::<i64>(&mut scope, "script.rhai".into())?;

pub fn eval<T>(&self, script: &str) -> Result<T, Box<EvalAltResult, Global>> where
    T: Variant + Clone
[src]

Evaluate a string.

Example

use rhai::Engine;

let engine = Engine::new();

assert_eq!(engine.eval::<i64>("40 + 2")?, 42);

pub fn eval_with_scope<T>(
    &self,
    scope: &mut Scope<'_>,
    script: &str
) -> Result<T, Box<EvalAltResult, Global>> where
    T: Variant + Clone
[src]

Evaluate a string with own scope.

Example

use rhai::{Engine, Scope};

let engine = Engine::new();

// Create initialized scope
let mut scope = Scope::new();
scope.push("x", 40_i64);

assert_eq!(engine.eval_with_scope::<i64>(&mut scope, "x += 2; x")?, 42);
assert_eq!(engine.eval_with_scope::<i64>(&mut scope, "x += 2; x")?, 44);

// The variable in the scope is modified
assert_eq!(scope.get_value::<i64>("x").expect("variable x should exist"), 44);

pub fn eval_expression<T>(
    &self,
    script: &str
) -> Result<T, Box<EvalAltResult, Global>> where
    T: Variant + Clone
[src]

Evaluate a string containing an expression.

Example

use rhai::Engine;

let engine = Engine::new();

assert_eq!(engine.eval_expression::<i64>("40 + 2")?, 42);

pub fn eval_expression_with_scope<T>(
    &self,
    scope: &mut Scope<'_>,
    script: &str
) -> Result<T, Box<EvalAltResult, Global>> where
    T: Variant + Clone
[src]

Evaluate a string containing an expression with own scope.

Example

use rhai::{Engine, Scope};

let engine = Engine::new();

// Create initialized scope
let mut scope = Scope::new();
scope.push("x", 40_i64);

assert_eq!(engine.eval_expression_with_scope::<i64>(&mut scope, "x + 2")?, 42);

pub fn eval_ast<T>(&self, ast: &AST) -> Result<T, Box<EvalAltResult, Global>> where
    T: Variant + Clone
[src]

Evaluate an AST.

Example

use rhai::Engine;

let engine = Engine::new();

// Compile a script to an AST and store it for later evaluation
let ast = engine.compile("40 + 2")?;

// Evaluate it
assert_eq!(engine.eval_ast::<i64>(&ast)?, 42);

pub fn eval_ast_with_scope<T>(
    &self,
    scope: &mut Scope<'_>,
    ast: &AST
) -> Result<T, Box<EvalAltResult, Global>> where
    T: Variant + Clone
[src]

Evaluate an AST with own scope.

Example

use rhai::{Engine, Scope};

let engine = Engine::new();

// Compile a script to an AST and store it for later evaluation
let ast = engine.compile("x + 2")?;

// Create initialized scope
let mut scope = Scope::new();
scope.push("x", 40_i64);

// Compile a script to an AST and store it for later evaluation
let ast = engine.compile("x += 2; x")?;

// Evaluate it
assert_eq!(engine.eval_ast_with_scope::<i64>(&mut scope, &ast)?, 42);
assert_eq!(engine.eval_ast_with_scope::<i64>(&mut scope, &ast)?, 44);

// The variable in the scope is modified
assert_eq!(scope.get_value::<i64>("x").expect("variable x should exist"), 44);

pub fn consume_file(
    &self,
    path: PathBuf
) -> Result<(), Box<EvalAltResult, Global>>
[src]

Evaluate a file, but throw away the result and only return error (if any). Useful for when you don't need the result, but still need to keep track of possible errors.

Not available under no_std or WASM.

pub fn consume_file_with_scope(
    &self,
    scope: &mut Scope<'_>,
    path: PathBuf
) -> Result<(), Box<EvalAltResult, Global>>
[src]

Evaluate a file with own scope, but throw away the result and only return error (if any). Useful for when you don't need the result, but still need to keep track of possible errors.

Not available under no_std or WASM.

pub fn consume(&self, script: &str) -> Result<(), Box<EvalAltResult, Global>>[src]

Evaluate a string, but throw away the result and only return error (if any). Useful for when you don't need the result, but still need to keep track of possible errors.

pub fn consume_with_scope(
    &self,
    scope: &mut Scope<'_>,
    script: &str
) -> Result<(), Box<EvalAltResult, Global>>
[src]

Evaluate a string with own scope, but throw away the result and only return error (if any). Useful for when you don't need the result, but still need to keep track of possible errors.

pub fn consume_ast(&self, ast: &AST) -> Result<(), Box<EvalAltResult, Global>>[src]

Evaluate an AST, but throw away the result and only return error (if any). Useful for when you don't need the result, but still need to keep track of possible errors.

pub fn consume_ast_with_scope(
    &self,
    scope: &mut Scope<'_>,
    ast: &AST
) -> Result<(), Box<EvalAltResult, Global>>
[src]

Evaluate an AST with own scope, but throw away the result and only return error (if any). Useful for when you don't need the result, but still need to keep track of possible errors.

pub fn call_fn<T>(
    &self,
    scope: &mut Scope<'_>,
    ast: &AST,
    name: &str,
    args: impl FuncArgs
) -> Result<T, Box<EvalAltResult, Global>> where
    T: Variant + Clone
[src]

Call a script function defined in an AST with multiple arguments. Arguments are passed as a tuple.

Example

use rhai::{Engine, Scope};

let engine = Engine::new();

let ast = engine.compile(r"
    fn add(x, y) { len(x) + y + foo }
    fn add1(x)   { len(x) + 1 + foo }
    fn bar()     { foo/2 }
")?;

let mut scope = Scope::new();
scope.push("foo", 42_i64);

// Call the script-defined function
let result: i64 = engine.call_fn(&mut scope, &ast, "add", ( String::from("abc"), 123_i64 ) )?;
assert_eq!(result, 168);

let result: i64 = engine.call_fn(&mut scope, &ast, "add1", ( String::from("abc"), ) )?;
//                                                         ^^^^^^^^^^^^^^^^^^^^^^^^ tuple of one
assert_eq!(result, 46);

let result: i64 = engine.call_fn(&mut scope, &ast, "bar", () )?;
assert_eq!(result, 21);

pub fn call_fn_dynamic(
    &self,
    scope: &mut Scope<'_>,
    lib: impl AsRef<Module>,
    name: &str,
    this_ptr: Option<&mut Dynamic>,
    arg_values: impl AsMut<[Dynamic]>
) -> Result<Dynamic, Box<EvalAltResult, Global>>
[src]

Call a script function defined in an AST with multiple Dynamic arguments and optionally a value for binding to the this pointer.

WARNING

All the arguments are consumed, meaning that they're replaced by (). This is to avoid unnecessarily cloning the arguments. Do not use the arguments after this call. If they are needed afterwards, clone them before calling this function.

Example

use rhai::{Engine, Scope, Dynamic};

let engine = Engine::new();

let ast = engine.compile(r"
    fn add(x, y) { len(x) + y + foo }
    fn add1(x)   { len(x) + 1 + foo }
    fn bar()     { foo/2 }
    fn action(x) { this += x; }         // function using 'this' pointer
")?;

let mut scope = Scope::new();
scope.push("foo", 42_i64);

// Call the script-defined function
let result = engine.call_fn_dynamic(&mut scope, &ast, "add", None, [ String::from("abc").into(), 123_i64.into() ])?;
//                                                           ^^^^ no 'this' pointer
assert_eq!(result.cast::<i64>(), 168);

let result = engine.call_fn_dynamic(&mut scope, &ast, "add1", None, [ String::from("abc").into() ])?;
assert_eq!(result.cast::<i64>(), 46);

let result = engine.call_fn_dynamic(&mut scope, &ast, "bar", None, [])?;
assert_eq!(result.cast::<i64>(), 21);

let mut value: Dynamic = 1_i64.into();
let result = engine.call_fn_dynamic(&mut scope, &ast, "action", Some(&mut value), [ 41_i64.into() ])?;
//                                                              ^^^^^^^^^^^^^^^^ binding the 'this' pointer
assert_eq!(value.as_int().unwrap(), 42);

pub fn optimize_ast(
    &self,
    scope: &Scope<'_>,
    ast: AST,
    optimization_level: OptimizationLevel
) -> AST
[src]

Optimize the AST with constants defined in an external Scope. An optimized copy of the AST is returned while the original AST is consumed.

Although optimization is performed by default during compilation, sometimes it is necessary to re-optimize an AST. For example, when working with constants that are passed in via an external scope, it will be more efficient to optimize the AST once again to take advantage of the new constants.

With this method, it is no longer necessary to recompile a large script. The script AST can be compiled just once. Before evaluation, constants are passed into the Engine via an external scope (i.e. with Scope::push_constant). Then, the AST is cloned and the copy re-optimized before running.

pub fn gen_fn_signatures(&self, include_packages: bool) -> Vec<String, Global>

Notable traits for Vec<u8, Global>

impl Write for Vec<u8, Global>
[src]

Generate a list of all registered functions.

Functions from the following sources are included, in order:

  1. Functions registered into the global namespace
  2. Functions in registered sub-modules
  3. Functions in packages (optional)

pub fn optimization_level(&self) -> OptimizationLevel[src]

The current optimization level. It controls whether and how the Engine will optimize an AST after compilation.

Not available under no_optimize.

pub fn max_call_levels(&self) -> usize[src]

The maximum levels of function calls allowed for a script.

Not available under unchecked or no_function.

pub fn max_operations(&self) -> u64[src]

The maximum number of operations allowed for a script to run (0 for unlimited).

Not available under unchecked.

pub fn max_modules(&self) -> usize[src]

The maximum number of imported modules allowed for a script.

Not available under unchecked or no_module.

pub fn max_expr_depth(&self) -> usize[src]

The depth limit for expressions (0 for unlimited).

Not available under unchecked.

pub fn max_function_expr_depth(&self) -> usize[src]

The depth limit for expressions in functions (0 for unlimited).

Not available under unchecked or no_function.

pub fn max_string_size(&self) -> usize[src]

The maximum length of strings (0 for unlimited).

Not available under unchecked.

pub fn max_array_size(&self) -> usize[src]

The maximum length of arrays (0 for unlimited).

Not available under unchecked or no_index.

pub fn max_map_size(&self) -> usize[src]

The maximum size of object maps (0 for unlimited).

Not available under unchecked or no_object.

pub fn lex<'a>(
    &'e self,
    input: impl IntoIterator<Item = &'a &'a str>
) -> TokenIterator<'a, 'e>
[src]

Tokenize an input text stream.

pub fn lex_with_map<'a>(
    &'e self,
    input: impl IntoIterator<Item = &'a &'a str>,
    map: fn(Token) -> Token
) -> TokenIterator<'a, 'e>
[src]

Tokenize an input text stream with a mapping function.

Trait Implementations

impl Clone for Rhai[src]

impl Default for Rhai[src]

impl Deref for Rhai[src]

type Target = Engine

The resulting type after dereferencing.

impl Engine<FormalExpression> for Rhai[src]

impl Engine<ScriptTask> for Rhai[src]

impl EngineContextProvider for Rhai[src]

type Context = Context

Context type

impl EngineInfo for Rhai[src]

Auto Trait Implementations

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> Downcast for T where
    T: Any
[src]

impl<T> DowncastSync for T where
    T: Send + Sync + Any
[src]

impl<T> DynClone for T where
    T: Clone
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.