rhai/src/api.rs

1077 lines
36 KiB
Rust
Raw Normal View History

2020-03-08 12:54:02 +01:00
//! Module that defines the extern API of `Engine`.
2020-04-12 17:00:06 +02:00
use crate::any::{Dynamic, Variant};
2020-04-16 17:31:48 +02:00
use crate::engine::{calc_fn_spec, make_getter, make_setter, Engine, FnAny, Map};
2020-03-04 15:00:01 +01:00
use crate::error::ParseError;
use crate::fn_call::FuncArgs;
2020-03-04 15:00:01 +01:00
use crate::fn_register::RegisterFn;
2020-04-10 06:16:39 +02:00
use crate::optimize::{optimize_into_ast, OptimizationLevel};
use crate::parser::{parse, parse_global_expr, AST};
2020-03-04 15:00:01 +01:00
use crate::result::EvalAltResult;
2020-03-03 08:20:20 +01:00
use crate::scope::Scope;
use crate::token::{lex, Position};
2020-03-17 19:26:11 +01:00
use crate::stdlib::{
2020-03-10 03:07:44 +01:00
any::{type_name, TypeId},
2020-03-17 19:26:11 +01:00
boxed::Box,
collections::HashMap,
2020-03-17 19:26:11 +01:00
string::{String, ToString},
vec::Vec,
2020-03-10 03:07:44 +01:00
};
#[cfg(not(feature = "no_std"))]
2020-03-17 19:26:11 +01:00
use crate::stdlib::{fs::File, io::prelude::*, path::PathBuf};
2020-04-03 11:17:00 +02:00
// Define callback function types
#[cfg(feature = "sync")]
pub trait ObjectGetCallback<T, U>: Fn(&mut T) -> U + Send + Sync + 'static {}
#[cfg(feature = "sync")]
impl<F: Fn(&mut T) -> U + Send + Sync + 'static, T, U> ObjectGetCallback<T, U> for F {}
#[cfg(not(feature = "sync"))]
pub trait ObjectGetCallback<T, U>: Fn(&mut T) -> U + 'static {}
#[cfg(not(feature = "sync"))]
impl<F: Fn(&mut T) -> U + 'static, T, U> ObjectGetCallback<T, U> for F {}
#[cfg(feature = "sync")]
pub trait ObjectSetCallback<T, U>: Fn(&mut T, U) + Send + Sync + 'static {}
#[cfg(feature = "sync")]
impl<F: Fn(&mut T, U) + Send + Sync + 'static, T, U> ObjectSetCallback<T, U> for F {}
#[cfg(not(feature = "sync"))]
pub trait ObjectSetCallback<T, U>: Fn(&mut T, U) + 'static {}
#[cfg(not(feature = "sync"))]
impl<F: Fn(&mut T, U) + 'static, T, U> ObjectSetCallback<T, U> for F {}
#[cfg(feature = "sync")]
pub trait IteratorCallback:
Fn(&Dynamic) -> Box<dyn Iterator<Item = Dynamic>> + Send + Sync + 'static
{
}
#[cfg(feature = "sync")]
impl<F: Fn(&Dynamic) -> Box<dyn Iterator<Item = Dynamic>> + Send + Sync + 'static> IteratorCallback
for F
{
}
#[cfg(not(feature = "sync"))]
pub trait IteratorCallback: Fn(&Dynamic) -> Box<dyn Iterator<Item = Dynamic>> + 'static {}
#[cfg(not(feature = "sync"))]
impl<F: Fn(&Dynamic) -> Box<dyn Iterator<Item = Dynamic>> + 'static> IteratorCallback for F {}
/// Engine public API
2020-04-16 17:31:48 +02:00
impl Engine {
2020-03-19 06:52:10 +01:00
/// Register a custom function.
2020-03-30 16:19:37 +02:00
pub(crate) fn register_fn_raw(&mut self, fn_name: &str, args: Vec<TypeId>, f: Box<FnAny>) {
if self.functions.is_none() {
self.functions = Some(HashMap::new());
}
2020-04-16 17:31:48 +02:00
self.functions
.as_mut()
.unwrap()
.insert(calc_fn_spec(fn_name, args.into_iter()), f);
2020-03-04 15:00:01 +01:00
}
/// Register a custom type for use with the `Engine`.
2020-03-19 06:52:10 +01:00
/// The type must implement `Clone`.
///
/// # Example
///
/// ```
2020-03-30 10:10:50 +02:00
/// #[derive(Debug, Clone, Eq, PartialEq)]
2020-03-19 06:52:10 +01:00
/// struct TestStruct {
/// field: i64
/// }
///
/// impl TestStruct {
2020-03-22 03:18:16 +01:00
/// fn new() -> Self { TestStruct { field: 1 } }
/// fn update(&mut self, offset: i64) { self.field += offset; }
2020-03-19 06:52:10 +01:00
/// }
///
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// use rhai::{Engine, RegisterFn};
///
/// let mut engine = Engine::new();
///
/// // Register the custom type.
/// engine.register_type::<TestStruct>();
///
/// engine.register_fn("new_ts", TestStruct::new);
///
2020-03-22 03:18:16 +01:00
/// // Use `register_fn` to register methods on the type.
2020-03-19 06:52:10 +01:00
/// engine.register_fn("update", TestStruct::update);
///
/// assert_eq!(
2020-03-30 10:10:50 +02:00
/// engine.eval::<TestStruct>("let x = new_ts(); x.update(41); x")?,
/// TestStruct { field: 42 }
2020-03-19 06:52:10 +01:00
/// );
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_object"))]
2020-04-12 17:00:06 +02:00
pub fn register_type<T: Variant + Clone>(&mut self) {
2020-03-08 12:54:02 +01:00
self.register_type_with_name::<T>(type_name::<T>());
2020-03-04 15:00:01 +01:00
}
2020-03-19 06:52:10 +01:00
/// Register a custom type for use with the `Engine`, with a pretty-print name
/// for the `type_of` function. The type must implement `Clone`.
///
/// # Example
///
/// ```
/// #[derive(Clone)]
2020-03-30 10:10:50 +02:00
/// struct TestStruct {
2020-03-19 06:52:10 +01:00
/// field: i64
/// }
///
/// impl TestStruct {
/// fn new() -> Self { TestStruct { field: 1 } }
/// }
///
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// use rhai::{Engine, RegisterFn};
///
/// let mut engine = Engine::new();
///
/// // Register the custom type.
/// engine.register_type::<TestStruct>();
///
/// engine.register_fn("new_ts", TestStruct::new);
///
/// assert_eq!(
/// engine.eval::<String>("let x = new_ts(); type_of(x)")?,
/// "rust_out::TestStruct"
/// );
///
/// // Register the custom type with a name.
/// engine.register_type_with_name::<TestStruct>("Hello");
///
/// // Register methods on the type.
/// engine.register_fn("new_ts", TestStruct::new);
///
/// assert_eq!(
/// engine.eval::<String>("let x = new_ts(); type_of(x)")?,
/// "Hello"
/// );
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_object"))]
2020-04-12 17:00:06 +02:00
pub fn register_type_with_name<T: Variant + Clone>(&mut self, name: &str) {
if self.type_names.is_none() {
self.type_names = Some(HashMap::new());
}
2020-03-04 15:00:01 +01:00
// Add the pretty-print type name into the map
2020-03-08 12:54:02 +01:00
self.type_names
.as_mut()
.unwrap()
2020-03-08 12:54:02 +01:00
.insert(type_name::<T>().to_string(), name.to_string());
2020-03-04 15:00:01 +01:00
}
/// Register an iterator adapter for a type with the `Engine`.
2020-03-19 06:52:10 +01:00
/// This is an advanced feature.
2020-04-12 17:00:06 +02:00
pub fn register_iterator<T: Variant + Clone, F: IteratorCallback>(&mut self, f: F) {
if self.type_iterators.is_none() {
self.type_iterators = Some(HashMap::new());
}
self.type_iterators
.as_mut()
.unwrap()
.insert(TypeId::of::<T>(), Box::new(f));
2020-03-04 15:00:01 +01:00
}
/// Register a getter function for a member of a registered type with the `Engine`.
2020-03-19 06:52:10 +01:00
///
2020-03-22 03:18:16 +01:00
/// The function signature must start with `&mut self` and not `&self`.
///
2020-03-19 06:52:10 +01:00
/// # Example
///
/// ```
/// #[derive(Clone)]
2020-03-30 10:10:50 +02:00
/// struct TestStruct {
2020-03-19 06:52:10 +01:00
/// field: i64
/// }
///
/// impl TestStruct {
/// fn new() -> Self { TestStruct { field: 1 } }
2020-03-22 03:18:16 +01:00
///
/// // Even a getter must start with `&mut self` and not `&self`.
2020-03-19 06:52:10 +01:00
/// fn get_field(&mut self) -> i64 { self.field }
/// }
///
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// use rhai::{Engine, RegisterFn};
///
/// let mut engine = Engine::new();
///
/// // Register the custom type.
/// engine.register_type::<TestStruct>();
///
/// engine.register_fn("new_ts", TestStruct::new);
///
/// // Register a getter on a property (notice it doesn't have to be the same name).
/// engine.register_get("xyz", TestStruct::get_field);
///
/// assert_eq!(engine.eval::<i64>("let a = new_ts(); a.xyz")?, 1);
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_object"))]
2020-04-03 11:17:00 +02:00
pub fn register_get<T, U, F>(&mut self, name: &str, callback: F)
where
2020-04-12 17:00:06 +02:00
T: Variant + Clone,
U: Variant + Clone,
2020-04-03 11:17:00 +02:00
F: ObjectGetCallback<T, U>,
{
2020-03-30 16:19:37 +02:00
self.register_fn(&make_getter(name), callback);
2020-03-04 15:00:01 +01:00
}
/// Register a setter function for a member of a registered type with the `Engine`.
2020-03-19 06:52:10 +01:00
///
/// # Example
///
/// ```
2020-03-30 10:10:50 +02:00
/// #[derive(Debug, Clone, Eq, PartialEq)]
2020-03-19 06:52:10 +01:00
/// struct TestStruct {
/// field: i64
/// }
///
/// impl TestStruct {
/// fn new() -> Self { TestStruct { field: 1 } }
/// fn set_field(&mut self, new_val: i64) { self.field = new_val; }
/// }
///
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// use rhai::{Engine, RegisterFn};
///
/// let mut engine = Engine::new();
///
/// // Register the custom type.
/// engine.register_type::<TestStruct>();
///
/// engine.register_fn("new_ts", TestStruct::new);
///
/// // Register a setter on a property (notice it doesn't have to be the same name)
/// engine.register_set("xyz", TestStruct::set_field);
///
/// // Notice that, with a getter, there is no way to get the property value
2020-03-30 10:10:50 +02:00
/// assert_eq!(
/// engine.eval::<TestStruct>("let a = new_ts(); a.xyz = 42; a")?,
/// TestStruct { field: 42 }
/// );
2020-03-19 06:52:10 +01:00
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_object"))]
2020-04-03 11:17:00 +02:00
pub fn register_set<T, U, F>(&mut self, name: &str, callback: F)
where
2020-04-12 17:00:06 +02:00
T: Variant + Clone,
U: Variant + Clone,
2020-04-03 11:17:00 +02:00
F: ObjectSetCallback<T, U>,
{
2020-03-30 16:19:37 +02:00
self.register_fn(&make_setter(name), callback);
2020-03-04 15:00:01 +01:00
}
/// Shorthand for registering both getter and setter functions
/// of a registered type with the `Engine`.
2020-03-19 06:52:10 +01:00
///
2020-03-22 03:18:16 +01:00
/// All function signatures must start with `&mut self` and not `&self`.
///
2020-03-19 06:52:10 +01:00
/// # Example
///
/// ```
/// #[derive(Clone)]
/// struct TestStruct {
/// field: i64
/// }
///
/// impl TestStruct {
2020-03-22 03:18:16 +01:00
/// fn new() -> Self { TestStruct { field: 1 } }
2020-03-19 06:52:10 +01:00
/// fn get_field(&mut self) -> i64 { self.field }
2020-03-22 03:18:16 +01:00
/// // Even a getter must start with `&mut self` and not `&self`.
2020-03-19 06:52:10 +01:00
/// fn set_field(&mut self, new_val: i64) { self.field = new_val; }
/// }
///
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// use rhai::{Engine, RegisterFn};
///
/// let mut engine = Engine::new();
///
/// // Register the custom type.
/// engine.register_type::<TestStruct>();
///
/// engine.register_fn("new_ts", TestStruct::new);
///
/// // Register a getter and a setter on a property
/// // (notice it doesn't have to be the same name)
/// engine.register_get_set("xyz", TestStruct::get_field, TestStruct::set_field);
///
/// assert_eq!(engine.eval::<i64>("let a = new_ts(); a.xyz = 42; a.xyz")?, 42);
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_object"))]
2020-04-03 11:17:00 +02:00
pub fn register_get_set<T, U, G, S>(&mut self, name: &str, get_fn: G, set_fn: S)
where
2020-04-12 17:00:06 +02:00
T: Variant + Clone,
U: Variant + Clone,
2020-04-03 11:17:00 +02:00
G: ObjectGetCallback<T, U>,
S: ObjectSetCallback<T, U>,
{
2020-03-04 15:00:01 +01:00
self.register_get(name, get_fn);
self.register_set(name, set_fn);
}
2020-03-19 12:53:42 +01:00
/// Compile a string into an `AST`, which can be used later for evaluation.
2020-03-19 06:52:10 +01:00
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// use rhai::Engine;
///
/// let engine = Engine::new();
2020-03-19 06:52:10 +01:00
///
2020-03-19 12:53:42 +01:00
/// // Compile a script to an AST and store it for later evaluation
2020-03-19 06:52:10 +01:00
/// let ast = engine.compile("40 + 2")?;
///
/// for _ in 0..42 {
/// assert_eq!(engine.eval_ast::<i64>(&ast)?, 42);
/// }
/// # Ok(())
/// # }
/// ```
2020-04-08 10:57:15 +02:00
pub fn compile(&self, script: &str) -> Result<AST, ParseError> {
self.compile_with_scope(&Scope::new(), script)
}
2020-03-19 12:53:42 +01:00
/// 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`.
2020-03-19 06:52:10 +01:00
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> {
2020-03-19 12:53:42 +01:00
/// # #[cfg(not(feature = "no_optimize"))]
/// # {
/// use rhai::{Engine, Scope, OptimizationLevel};
2020-03-19 06:52:10 +01:00
///
/// let mut engine = Engine::new();
///
2020-03-19 12:53:42 +01:00
/// // Set optimization level to 'Full' so the Engine can fold constants
/// // into function calls and operators.
/// engine.set_optimization_level(OptimizationLevel::Full);
///
2020-03-19 06:52:10 +01:00
/// // Create initialized scope
/// let mut scope = Scope::new();
/// scope.push_constant("x", 42_i64); // 'x' is a constant
///
2020-03-19 12:53:42 +01:00
/// // 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.
2020-03-19 06:52:10 +01:00
/// let ast = engine.compile_with_scope(&mut scope,
2020-03-19 12:53:42 +01:00
/// "if x > 40 { x } else { 0 }" // all 'x' are replaced with 42
2020-03-19 06:52:10 +01:00
/// )?;
///
2020-03-19 12:53:42 +01:00
/// // 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.
2020-03-19 06:52:10 +01:00
/// assert_eq!(engine.eval_ast::<i64>(&ast)?, 42);
2020-03-19 12:53:42 +01:00
/// # }
2020-03-19 06:52:10 +01:00
/// # Ok(())
/// # }
/// ```
2020-04-08 10:57:15 +02:00
pub fn compile_with_scope(&self, scope: &Scope, script: &str) -> Result<AST, ParseError> {
2020-04-10 06:16:39 +02:00
self.compile_with_scope_and_optimization_level(scope, script, self.optimization_level)
}
/// Compile a string into an `AST` using own scope at a specific optimization level.
pub(crate) fn compile_with_scope_and_optimization_level(
&self,
scope: &Scope,
2020-04-08 10:57:15 +02:00
script: &str,
2020-04-10 06:16:39 +02:00
optimization_level: OptimizationLevel,
) -> Result<AST, ParseError> {
2020-04-10 11:14:07 +02:00
let scripts = [script];
let stream = lex(&scripts);
parse(&mut stream.peekable(), self, scope, optimization_level)
}
2020-03-19 06:52:10 +01:00
/// Read the contents of a file into a string.
#[cfg(not(feature = "no_std"))]
2020-03-13 11:27:53 +01:00
fn read_file(path: PathBuf) -> Result<String, EvalAltResult> {
2020-03-13 11:07:51 +01:00
let mut f = File::open(path.clone())
.map_err(|err| EvalAltResult::ErrorReadingScriptFile(path.clone(), err))?;
let mut contents = String::new();
f.read_to_string(&mut contents)
2020-03-30 16:19:37 +02:00
.map_err(|err| EvalAltResult::ErrorReadingScriptFile(path.clone(), err))?;
Ok(contents)
}
2020-03-19 12:53:42 +01:00
/// Compile a script file into an `AST`, which can be used later for evaluation.
2020-03-19 06:52:10 +01:00
///
/// # Example
///
/// ```no_run
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// use rhai::Engine;
///
/// let engine = Engine::new();
2020-03-19 06:52:10 +01:00
///
2020-03-19 12:53:42 +01:00
/// // Compile a script file to an AST and store it for later evaluation.
2020-03-19 06:52:10 +01:00
/// // 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)?;
/// }
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_std"))]
2020-03-13 11:27:53 +01:00
pub fn compile_file(&self, path: PathBuf) -> Result<AST, EvalAltResult> {
2020-03-14 07:33:56 +01:00
self.compile_file_with_scope(&Scope::new(), path)
}
2020-03-19 12:53:42 +01:00
/// Compile a script file 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`.
2020-03-19 06:52:10 +01:00
///
/// # Example
///
/// ```no_run
/// # fn main() -> Result<(), rhai::EvalAltResult> {
2020-03-19 12:53:42 +01:00
/// # #[cfg(not(feature = "no_optimize"))]
/// # {
/// use rhai::{Engine, Scope, OptimizationLevel};
2020-03-19 06:52:10 +01:00
///
/// let mut engine = Engine::new();
///
2020-03-19 12:53:42 +01:00
/// // Set optimization level to 'Full' so the Engine can fold constants.
/// engine.set_optimization_level(OptimizationLevel::Full);
///
2020-03-19 06:52:10 +01:00
/// // Create initialized scope
/// let mut scope = Scope::new();
/// scope.push_constant("x", 42_i64); // 'x' is a constant
///
2020-03-19 12:53:42 +01:00
/// // Compile a script to an AST and store it for later evaluation.
2020-03-19 06:52:10 +01:00
/// // 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)?;
2020-03-19 12:53:42 +01:00
/// # }
2020-03-19 06:52:10 +01:00
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_std"))]
pub fn compile_file_with_scope(
&self,
scope: &Scope,
2020-03-14 07:33:56 +01:00
path: PathBuf,
) -> Result<AST, EvalAltResult> {
2020-04-08 10:57:15 +02:00
Self::read_file(path).and_then(|contents| Ok(self.compile_with_scope(scope, &contents)?))
}
2020-04-10 11:14:07 +02:00
/// Parse a JSON string into a map.
///
/// Set `has_null` to `true` in order to map `null` values to `()`.
/// Setting it to `false` will cause a _variable not found_ error during parsing.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> {
2020-04-12 17:00:06 +02:00
/// use rhai::Engine;
2020-04-10 11:14:07 +02:00
///
/// let engine = Engine::new();
///
/// let map = engine.parse_json(r#"{"a":123, "b":42, "c":false, "d":null}"#, true)?;
///
/// assert_eq!(map.len(), 4);
/// assert_eq!(map.get("a").cloned().unwrap().cast::<i64>(), 123);
/// assert_eq!(map.get("b").cloned().unwrap().cast::<i64>(), 42);
/// assert_eq!(map.get("c").cloned().unwrap().cast::<bool>(), false);
/// assert_eq!(map.get("d").cloned().unwrap().cast::<()>(), ());
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_object"))]
pub fn parse_json(&self, json: &str, has_null: bool) -> Result<Map, EvalAltResult> {
let mut scope = Scope::new();
// Trims the JSON string and add a '#' in front
let scripts = ["#", json.trim()];
let stream = lex(&scripts);
let ast = parse_global_expr(
&mut stream.peekable(),
self,
&scope,
OptimizationLevel::None,
)?;
// Handle null - map to ()
if has_null {
scope.push_constant("null", ());
}
self.eval_ast_with_scope(&mut scope, &ast)
}
2020-03-22 14:03:58 +01:00
/// Compile a string containing an expression into an `AST`,
/// which can be used later for evaluation.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// use rhai::Engine;
///
/// let engine = Engine::new();
2020-03-22 14:03:58 +01:00
///
/// // 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);
/// }
/// # Ok(())
/// # }
/// ```
2020-04-08 10:57:15 +02:00
pub fn compile_expression(&self, script: &str) -> Result<AST, ParseError> {
self.compile_expression_with_scope(&Scope::new(), script)
2020-03-22 14:03:58 +01:00
}
/// 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
///
/// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// # #[cfg(not(feature = "no_optimize"))]
/// # {
/// 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);
/// # }
/// # Ok(())
/// # }
/// ```
pub fn compile_expression_with_scope(
&self,
scope: &Scope,
2020-04-08 10:57:15 +02:00
script: &str,
2020-03-22 14:03:58 +01:00
) -> Result<AST, ParseError> {
2020-04-10 11:14:07 +02:00
let scripts = [script];
let stream = lex(&scripts);
parse_global_expr(&mut stream.peekable(), self, scope, self.optimization_level)
2020-03-22 14:03:58 +01:00
}
2020-03-19 06:52:10 +01:00
/// Evaluate a script file.
///
/// # Example
///
/// ```no_run
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// use rhai::Engine;
///
/// let engine = Engine::new();
2020-03-19 06:52:10 +01:00
///
/// // Notice that a PathBuf is required which can easily be constructed from a string.
/// let result = engine.eval_file::<i64>("script.rhai".into())?;
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_std"))]
2020-04-12 17:00:06 +02:00
pub fn eval_file<T: Variant + Clone>(&self, path: PathBuf) -> Result<T, EvalAltResult> {
2020-03-13 11:27:53 +01:00
Self::read_file(path).and_then(|contents| self.eval::<T>(&contents))
}
2020-03-19 06:52:10 +01:00
/// Evaluate a script file with own scope.
///
/// # Example
///
/// ```no_run
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// use rhai::{Engine, Scope};
///
/// let engine = Engine::new();
2020-03-19 06:52:10 +01:00
///
/// // 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())?;
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_std"))]
2020-04-12 17:00:06 +02:00
pub fn eval_file_with_scope<T: Variant + Clone>(
&self,
scope: &mut Scope,
path: PathBuf,
) -> Result<T, EvalAltResult> {
Self::read_file(path).and_then(|contents| self.eval_with_scope::<T>(scope, &contents))
}
/// Evaluate a string.
2020-03-19 06:52:10 +01:00
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// use rhai::Engine;
///
/// let engine = Engine::new();
2020-03-19 06:52:10 +01:00
///
/// assert_eq!(engine.eval::<i64>("40 + 2")?, 42);
/// # Ok(())
/// # }
/// ```
2020-04-12 17:00:06 +02:00
pub fn eval<T: Variant + Clone>(&self, script: &str) -> Result<T, EvalAltResult> {
2020-04-08 10:57:15 +02:00
self.eval_with_scope(&mut Scope::new(), script)
}
/// Evaluate a string with own scope.
2020-03-19 06:52:10 +01:00
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// use rhai::{Engine, Scope};
///
/// let engine = Engine::new();
2020-03-19 06:52:10 +01:00
///
/// // Create initialized scope
/// let mut scope = Scope::new();
/// scope.push("x", 40_i64);
///
/// assert_eq!(engine.eval_with_scope::<i64>(&mut scope, "x = x + 2; x")?, 42);
/// assert_eq!(engine.eval_with_scope::<i64>(&mut scope, "x = x + 2; x")?, 44);
///
/// // The variable in the scope is modified
/// assert_eq!(scope.get_value::<i64>("x").expect("variable x should exist"), 44);
/// # Ok(())
/// # }
/// ```
2020-04-12 17:00:06 +02:00
pub fn eval_with_scope<T: Variant + Clone>(
&self,
scope: &mut Scope,
2020-04-08 10:57:15 +02:00
script: &str,
) -> Result<T, EvalAltResult> {
2020-04-10 15:02:38 +02:00
// Since the AST will be thrown away afterwards, don't bother to optimize it
let ast =
self.compile_with_scope_and_optimization_level(scope, script, OptimizationLevel::None)?;
self.eval_ast_with_scope(scope, &ast)
}
2020-03-22 14:03:58 +01:00
/// Evaluate a string containing an expression.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// use rhai::Engine;
///
/// let engine = Engine::new();
2020-03-22 14:03:58 +01:00
///
/// assert_eq!(engine.eval_expression::<i64>("40 + 2")?, 42);
/// # Ok(())
/// # }
/// ```
2020-04-12 17:00:06 +02:00
pub fn eval_expression<T: Variant + Clone>(&self, script: &str) -> Result<T, EvalAltResult> {
2020-04-08 10:57:15 +02:00
self.eval_expression_with_scope(&mut Scope::new(), script)
2020-03-22 14:03:58 +01:00
}
/// Evaluate a string containing an expression with own scope.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// use rhai::{Engine, Scope};
///
/// let engine = Engine::new();
2020-03-22 14:03:58 +01:00
///
/// // 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);
/// # Ok(())
/// # }
/// ```
2020-04-12 17:00:06 +02:00
pub fn eval_expression_with_scope<T: Variant + Clone>(
&self,
2020-03-22 14:03:58 +01:00
scope: &mut Scope,
2020-04-08 10:57:15 +02:00
script: &str,
2020-03-22 14:03:58 +01:00
) -> Result<T, EvalAltResult> {
2020-04-10 15:02:38 +02:00
let scripts = [script];
let stream = lex(&scripts);
// Since the AST will be thrown away afterwards, don't bother to optimize it
let ast = parse_global_expr(&mut stream.peekable(), self, scope, OptimizationLevel::None)?;
2020-03-22 14:03:58 +01:00
self.eval_ast_with_scope(scope, &ast)
}
2020-03-19 06:52:10 +01:00
/// Evaluate an `AST`.
///
/// # Example
///
2020-03-19 12:53:42 +01:00
/// ```
2020-03-19 06:52:10 +01:00
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// use rhai::Engine;
///
/// let engine = Engine::new();
2020-03-19 06:52:10 +01:00
///
2020-03-19 12:53:42 +01:00
/// // Compile a script to an AST and store it for later evaluation
2020-03-19 06:52:10 +01:00
/// let ast = engine.compile("40 + 2")?;
///
/// // Evaluate it
/// assert_eq!(engine.eval_ast::<i64>(&ast)?, 42);
/// # Ok(())
/// # }
/// ```
2020-04-12 17:00:06 +02:00
pub fn eval_ast<T: Variant + Clone>(&self, ast: &AST) -> Result<T, EvalAltResult> {
2020-03-30 16:19:37 +02:00
self.eval_ast_with_scope(&mut Scope::new(), ast)
}
2020-03-19 06:52:10 +01:00
/// Evaluate an `AST` with own scope.
///
/// # Example
///
2020-03-19 12:53:42 +01:00
/// ```
2020-03-19 06:52:10 +01:00
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// use rhai::{Engine, Scope};
///
/// let engine = Engine::new();
2020-03-19 06:52:10 +01:00
///
2020-03-19 12:53:42 +01:00
/// // Compile a script to an AST and store it for later evaluation
2020-03-19 06:52:10 +01:00
/// let ast = engine.compile("x + 2")?;
///
/// // Create initialized scope
/// let mut scope = Scope::new();
/// scope.push("x", 40_i64);
///
2020-03-19 12:53:42 +01:00
/// // Compile a script to an AST and store it for later evaluation
/// let ast = engine.compile("x = x + 2; x")?;
///
2020-03-19 06:52:10 +01:00
/// // Evaluate it
2020-03-19 12:53:42 +01:00
/// assert_eq!(engine.eval_ast_with_scope::<i64>(&mut scope, &ast)?, 42);
/// assert_eq!(engine.eval_ast_with_scope::<i64>(&mut scope, &ast)?, 44);
2020-03-19 06:52:10 +01:00
///
/// // The variable in the scope is modified
/// assert_eq!(scope.get_value::<i64>("x").expect("variable x should exist"), 44);
/// # Ok(())
/// # }
/// ```
2020-04-12 17:00:06 +02:00
pub fn eval_ast_with_scope<T: Variant + Clone>(
&self,
scope: &mut Scope,
ast: &AST,
) -> Result<T, EvalAltResult> {
2020-04-13 04:27:08 +02:00
let result = self.eval_ast_with_scope_raw(scope, ast)?;
let return_type = self.map_type_name(result.type_name());
return result.try_cast::<T>().ok_or_else(|| {
EvalAltResult::ErrorMismatchOutputType(return_type.to_string(), Position::none())
});
2020-03-19 12:53:42 +01:00
}
pub(crate) fn eval_ast_with_scope_raw(
&self,
2020-03-19 12:53:42 +01:00
scope: &mut Scope,
ast: &AST,
) -> Result<Dynamic, EvalAltResult> {
ast.0
2020-03-30 16:19:37 +02:00
.iter()
2020-04-12 17:00:06 +02:00
.try_fold(Dynamic::from_unit(), |_, stmt| {
self.eval_stmt(scope, Some(ast.1.as_ref()), stmt, 0)
})
.or_else(|err| match err {
EvalAltResult::Return(out, _) => Ok(out),
_ => Err(err),
})
}
2020-03-04 15:00:01 +01:00
/// 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.
#[cfg(not(feature = "no_std"))]
pub fn consume_file(&self, path: PathBuf) -> Result<(), EvalAltResult> {
Self::read_file(path).and_then(|contents| self.consume(&contents))
}
/// 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.
#[cfg(not(feature = "no_std"))]
pub fn consume_file_with_scope(
&self,
scope: &mut Scope,
path: PathBuf,
) -> Result<(), EvalAltResult> {
Self::read_file(path).and_then(|contents| self.consume_with_scope(scope, &contents))
}
2020-03-04 15:00:01 +01:00
/// 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.
2020-04-08 10:57:15 +02:00
pub fn consume(&self, script: &str) -> Result<(), EvalAltResult> {
self.consume_with_scope(&mut Scope::new(), script)
}
/// 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.
2020-04-08 10:57:15 +02:00
pub fn consume_with_scope(&self, scope: &mut Scope, script: &str) -> Result<(), EvalAltResult> {
2020-04-10 11:14:07 +02:00
let scripts = [script];
let stream = lex(&scripts);
2020-04-10 15:02:38 +02:00
// Since the AST will be thrown away afterwards, don't bother to optimize it
let ast = parse(&mut stream.peekable(), self, scope, OptimizationLevel::None)?;
self.consume_ast_with_scope(scope, &ast)
}
/// 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(&self, ast: &AST) -> Result<(), EvalAltResult> {
self.consume_ast_with_scope(&mut Scope::new(), ast)
}
2020-03-19 06:52:10 +01:00
/// 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 consume_ast_with_scope(
&self,
scope: &mut Scope,
ast: &AST,
) -> Result<(), EvalAltResult> {
ast.0
.iter()
2020-04-12 17:00:06 +02:00
.try_fold(Dynamic::from_unit(), |_, stmt| {
self.eval_stmt(scope, Some(ast.1.as_ref()), stmt, 0)
})
.map(|_| ())
.or_else(|err| match err {
EvalAltResult::Return(_, _) => Ok(()),
_ => Err(err),
})
}
/// Call a script function defined in an `AST` with multiple arguments.
2020-03-04 15:00:01 +01:00
///
/// # Example
///
2020-03-19 06:52:10 +01:00
/// ```
2020-03-09 14:57:07 +01:00
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// # #[cfg(not(feature = "no_function"))]
/// # {
/// use rhai::{Engine, Scope};
2020-03-09 14:57:07 +01:00
///
/// let engine = Engine::new();
2020-03-04 15:00:01 +01:00
///
/// 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);
2020-03-04 15:00:01 +01:00
///
2020-03-19 06:52:10 +01:00
/// // 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);
/// # }
2020-03-04 15:00:01 +01:00
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_function"))]
2020-04-12 17:00:06 +02:00
pub fn call_fn<A: FuncArgs, T: Variant + Clone>(
&self,
scope: &mut Scope,
ast: &AST,
2020-03-04 15:00:01 +01:00
name: &str,
args: A,
) -> Result<T, EvalAltResult> {
let mut arg_values = args.into_vec();
2020-04-12 17:00:06 +02:00
let mut args: Vec<_> = arg_values.iter_mut().collect();
let fn_lib = Some(ast.1.as_ref());
let pos = Position::none();
2020-04-13 04:27:08 +02:00
let result = self.call_fn_raw(Some(scope), fn_lib, name, &mut args, None, pos, 0)?;
let return_type = self.map_type_name(result.type_name());
return result
.try_cast()
2020-04-13 04:27:08 +02:00
.ok_or_else(|| EvalAltResult::ErrorMismatchOutputType(return_type.into(), pos));
2020-03-04 15:00:01 +01:00
}
2020-03-19 06:52:10 +01:00
/// Optimize the `AST` with constants defined in an external Scope.
2020-04-05 11:44:48 +02:00
/// 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
2020-03-19 06:52:10 +01:00
/// external scope, it will be more efficient to optimize the `AST` once again to take advantage
/// of the new constants.
///
2020-03-19 06:52:10 +01:00
/// 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
2020-03-19 06:52:10 +01:00
/// (i.e. with `scope.push_constant(...)`). Then, the `AST is cloned and the copy re-optimized before running.
#[cfg(not(feature = "no_optimize"))]
pub fn optimize_ast(
&self,
scope: &Scope,
ast: AST,
optimization_level: OptimizationLevel,
) -> AST {
let fn_lib = ast.1.iter().map(|fn_def| fn_def.as_ref().clone()).collect();
optimize_into_ast(self, scope, ast.0, fn_lib, optimization_level)
}
2020-03-04 15:00:01 +01:00
/// Override default action of `print` (print to stdout using `println!`)
///
/// # Example
///
2020-03-19 06:52:10 +01:00
/// ```
2020-03-09 14:57:07 +01:00
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// # use std::sync::RwLock;
2020-04-16 17:31:48 +02:00
/// # use std::sync::Arc;
2020-03-09 14:57:07 +01:00
/// use rhai::Engine;
///
2020-04-16 17:31:48 +02:00
/// let result = Arc::new(RwLock::new(String::from("")));
///
2020-04-16 17:31:48 +02:00
/// let mut engine = Engine::new();
///
/// // Override action of 'print' function
/// let logger = result.clone();
/// engine.on_print(move |s| logger.write().unwrap().push_str(s));
///
/// engine.consume("print(40 + 2);")?;
2020-03-04 15:00:01 +01:00
///
/// assert_eq!(*result.read().unwrap(), "42");
2020-03-09 14:57:07 +01:00
/// # Ok(())
/// # }
2020-03-04 15:00:01 +01:00
/// ```
2020-04-03 11:17:00 +02:00
#[cfg(feature = "sync")]
2020-04-16 17:31:48 +02:00
pub fn on_print(&mut self, callback: impl Fn(&str) + Send + Sync + 'static) {
self.on_print = Some(Box::new(callback));
2020-04-03 11:17:00 +02:00
}
/// Override default action of `print` (print to stdout using `println!`)
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// # use std::sync::RwLock;
2020-04-16 17:31:48 +02:00
/// # use std::sync::Arc;
/// use rhai::Engine;
///
2020-04-16 17:31:48 +02:00
/// let result = Arc::new(RwLock::new(String::from("")));
///
2020-04-16 17:31:48 +02:00
/// let mut engine = Engine::new();
///
/// // Override action of 'print' function
/// let logger = result.clone();
/// engine.on_print(move |s| logger.write().unwrap().push_str(s));
///
/// engine.consume("print(40 + 2);")?;
///
/// assert_eq!(*result.read().unwrap(), "42");
/// # Ok(())
/// # }
/// ```
2020-04-03 11:17:00 +02:00
#[cfg(not(feature = "sync"))]
2020-04-16 17:31:48 +02:00
pub fn on_print(&mut self, callback: impl Fn(&str) + 'static) {
self.on_print = Some(Box::new(callback));
}
2020-03-04 15:00:01 +01:00
/// Override default action of `debug` (print to stdout using `println!`)
///
/// # Example
///
2020-03-19 06:52:10 +01:00
/// ```
2020-03-09 14:57:07 +01:00
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// # use std::sync::RwLock;
2020-04-16 17:31:48 +02:00
/// # use std::sync::Arc;
2020-03-09 14:57:07 +01:00
/// use rhai::Engine;
///
2020-04-16 17:31:48 +02:00
/// let result = Arc::new(RwLock::new(String::from("")));
2020-03-04 15:00:01 +01:00
///
2020-04-16 17:31:48 +02:00
/// let mut engine = Engine::new();
///
/// // Override action of 'print' function
/// let logger = result.clone();
/// engine.on_debug(move |s| logger.write().unwrap().push_str(s));
///
/// engine.consume(r#"debug("hello");"#)?;
///
/// assert_eq!(*result.read().unwrap(), r#""hello""#);
2020-03-09 14:57:07 +01:00
/// # Ok(())
/// # }
2020-03-04 15:00:01 +01:00
/// ```
2020-04-03 11:17:00 +02:00
#[cfg(feature = "sync")]
2020-04-16 17:31:48 +02:00
pub fn on_debug(&mut self, callback: impl Fn(&str) + Send + Sync + 'static) {
self.on_debug = Some(Box::new(callback));
2020-04-03 11:17:00 +02:00
}
/// Override default action of `debug` (print to stdout using `println!`)
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// # use std::sync::RwLock;
2020-04-16 17:31:48 +02:00
/// # use std::sync::Arc;
/// use rhai::Engine;
///
2020-04-16 17:31:48 +02:00
/// let result = Arc::new(RwLock::new(String::from("")));
///
2020-04-16 17:31:48 +02:00
/// let mut engine = Engine::new();
///
/// // Override action of 'print' function
/// let logger = result.clone();
/// engine.on_debug(move |s| logger.write().unwrap().push_str(s));
///
/// engine.consume(r#"debug("hello");"#)?;
///
/// assert_eq!(*result.read().unwrap(), r#""hello""#);
/// # Ok(())
/// # }
/// ```
2020-04-03 11:17:00 +02:00
#[cfg(not(feature = "sync"))]
2020-04-16 17:31:48 +02:00
pub fn on_debug(&mut self, callback: impl Fn(&str) + 'static) {
self.on_debug = Some(Box::new(callback));
}
}