rhai/src/engine.rs

1075 lines
38 KiB
Rust
Raw Normal View History

2020-03-08 12:54:02 +01:00
//! Main module defining the script evaluation `Engine`.
2016-02-29 22:43:45 +01:00
use crate::any::{Any, AnyExt, Dynamic, Variant};
2020-03-04 15:00:01 +01:00
use crate::parser::{Expr, FnDef, Position, Stmt};
use crate::result::EvalAltResult;
2020-03-03 08:20:20 +01:00
use crate::scope::Scope;
#[cfg(not(feature = "no_index"))]
use crate::INT;
2020-03-10 03:07:44 +01:00
use std::{
any::{type_name, TypeId},
borrow::Cow,
cmp::{PartialEq, PartialOrd},
collections::HashMap,
iter::once,
sync::Arc,
};
2020-03-04 15:00:01 +01:00
/// An dynamic array of `Dynamic` values.
#[cfg(not(feature = "no_index"))]
pub type Array = Vec<Dynamic>;
2020-03-04 15:00:01 +01:00
pub type FnCallArgs<'a> = Vec<&'a mut Variant>;
2016-02-29 22:43:45 +01:00
2020-03-08 12:54:02 +01:00
pub type FnAny = dyn Fn(FnCallArgs, Position) -> Result<Dynamic, EvalAltResult>;
type IteratorFn = dyn Fn(&Dynamic) -> Box<dyn Iterator<Item = Dynamic>>;
2020-03-09 14:57:07 +01:00
pub(crate) const KEYWORD_PRINT: &'static str = "print";
pub(crate) const KEYWORD_DEBUG: &'static str = "debug";
pub(crate) const KEYWORD_TYPE_OF: &'static str = "type_of";
pub(crate) const FUNC_GETTER: &'static str = "get$";
pub(crate) const FUNC_SETTER: &'static str = "set$";
2020-03-03 10:28:38 +01:00
2020-03-05 13:28:03 +01:00
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[cfg(not(feature = "no_index"))]
2020-03-06 16:49:52 +01:00
enum IndexSourceType {
2020-03-05 13:28:03 +01:00
Array,
String,
Expression,
}
2017-12-20 12:16:14 +01:00
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
2020-03-04 15:00:01 +01:00
pub struct FnSpec<'a> {
pub name: Cow<'a, str>,
pub args: Option<Vec<TypeId>>,
}
2020-03-04 15:00:01 +01:00
/// Rhai main scripting engine.
2017-10-30 16:08:44 +01:00
///
/// ```rust
2020-03-09 14:57:07 +01:00
/// # fn main() -> Result<(), rhai::EvalAltResult> {
2017-10-30 16:08:44 +01:00
/// use rhai::Engine;
///
2020-03-09 14:57:07 +01:00
/// let mut engine = Engine::new();
2017-10-30 16:08:44 +01:00
///
2020-03-09 14:57:07 +01:00
/// let result = engine.eval::<i64>("40 + 2")?;
///
/// println!("Answer: {}", result); // prints 42
/// # Ok(())
/// # }
2017-10-30 16:08:44 +01:00
/// ```
2020-03-07 03:15:42 +01:00
pub struct Engine<'e> {
2020-03-09 14:57:07 +01:00
/// Optimize the AST after compilation
pub(crate) optimize: bool,
/// A hashmap containing all compiled functions known to the engine
2020-03-08 12:54:02 +01:00
pub(crate) ext_functions: HashMap<FnSpec<'e>, Arc<FnIntExt<'e>>>,
/// A hashmap containing all script-defined functions
2020-03-07 03:15:42 +01:00
pub(crate) script_functions: HashMap<FnSpec<'e>, Arc<FnIntExt<'e>>>,
/// A hashmap containing all iterators known to the engine
2020-03-04 15:00:01 +01:00
pub(crate) type_iterators: HashMap<TypeId, Arc<IteratorFn>>,
pub(crate) type_names: HashMap<String, String>,
2020-03-08 12:54:02 +01:00
// Closures for implementing the print/debug commands
2020-03-07 03:15:42 +01:00
pub(crate) on_print: Box<dyn FnMut(&str) + 'e>,
pub(crate) on_debug: Box<dyn FnMut(&str) + 'e>,
2017-12-20 12:16:14 +01:00
}
2020-03-07 03:15:42 +01:00
pub enum FnIntExt<'a> {
2017-12-20 12:16:14 +01:00
Ext(Box<FnAny>),
2020-03-07 03:15:42 +01:00
Int(FnDef<'a>),
2016-02-29 22:43:45 +01:00
}
2020-03-04 15:00:01 +01:00
impl Engine<'_> {
2020-03-09 14:57:07 +01:00
/// Create a new `Engine`
pub fn new() -> Self {
// User-friendly names for built-in types
let type_names = [
(type_name::<String>(), "string"),
(type_name::<Dynamic>(), "dynamic"),
#[cfg(not(feature = "no_index"))]
(type_name::<Array>(), "array"),
2020-03-09 14:57:07 +01:00
]
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
// Create the new scripting Engine
let mut engine = Engine {
optimize: true,
ext_functions: HashMap::new(),
script_functions: HashMap::new(),
type_iterators: HashMap::new(),
type_names,
on_print: Box::new(default_print), // default print/debug implementations
on_debug: Box::new(default_print),
};
engine.register_core_lib();
#[cfg(not(feature = "no_stdlib"))]
engine.register_stdlib(); // Register the standard library when no_stdlib is not set
engine
}
/// Control whether the `Engine` will optimize an AST after compilation
pub fn set_optimization(&mut self, optimize: bool) {
self.optimize = optimize
}
2017-10-30 16:08:44 +01:00
/// Universal method for calling functions, that are either
/// registered with the `Engine` or written in Rhai
2020-03-04 15:00:01 +01:00
pub(crate) fn call_fn_raw(
&mut self,
fn_name: &str,
args: FnCallArgs,
2020-03-08 12:54:02 +01:00
def_val: Option<&Dynamic>,
pos: Position,
) -> Result<Dynamic, EvalAltResult> {
debug_println!(
2020-03-04 15:00:01 +01:00
"Calling function: {} ({})",
fn_name,
args.iter()
2020-03-03 09:24:03 +01:00
.map(|x| (*x).type_name())
.map(|name| self.map_type_name(name))
.collect::<Vec<_>>()
2020-03-03 09:24:03 +01:00
.join(", ")
2017-12-20 21:09:53 +01:00
);
2020-03-04 15:00:01 +01:00
let mut spec = FnSpec {
name: fn_name.into(),
args: None,
};
// First search in script-defined functions (can override built-in),
2020-03-08 12:54:02 +01:00
// then built-in's and external functions
2020-03-04 15:00:01 +01:00
let fn_def = self
2020-03-04 16:06:05 +01:00
.script_functions
2020-03-04 15:00:01 +01:00
.get(&spec)
.or_else(|| {
spec.args = Some(args.iter().map(|a| Any::type_id(&**a)).collect());
2020-03-08 12:54:02 +01:00
self.ext_functions.get(&spec)
2020-03-04 15:00:01 +01:00
})
.map(|f| f.clone());
if let Some(f) = fn_def {
2020-03-04 15:00:01 +01:00
match *f {
2020-03-08 12:54:02 +01:00
// Run external function
2020-03-07 03:15:42 +01:00
FnIntExt::Ext(ref func) => {
let result = func(args, pos)?;
2020-02-25 03:40:48 +01:00
2020-03-08 12:54:02 +01:00
// See if the function match print/debug (which requires special processing)
2020-03-04 15:00:01 +01:00
let callback = match spec.name.as_ref() {
KEYWORD_PRINT => self.on_print.as_mut(),
KEYWORD_DEBUG => self.on_debug.as_mut(),
2020-03-07 03:15:42 +01:00
_ => return Ok(result),
2020-02-25 03:40:48 +01:00
};
2020-03-07 03:15:42 +01:00
let val = &result
.downcast::<String>()
.map(|s| *s)
.unwrap_or("error: not a string".into());
Ok(callback(val).into_dynamic())
2020-02-25 03:40:48 +01:00
}
2020-03-08 12:54:02 +01:00
// Run script-defined function
2020-03-07 03:15:42 +01:00
FnIntExt::Int(ref func) => {
2020-03-08 12:54:02 +01:00
// First check number of parameters
2020-03-07 03:15:42 +01:00
if func.params.len() != args.len() {
return Err(EvalAltResult::ErrorFunctionArgsMismatch(
2020-03-04 15:00:01 +01:00
spec.name.into(),
2020-03-07 03:15:42 +01:00
func.params.len(),
args.len(),
pos,
));
}
2017-12-20 21:09:53 +01:00
let mut scope = Scope::new();
2020-03-01 17:11:00 +01:00
2017-12-20 21:09:53 +01:00
scope.extend(
2020-03-08 12:54:02 +01:00
// Put arguments into scope as variables
2020-03-07 03:15:42 +01:00
func.params
2017-12-20 21:09:53 +01:00
.iter()
2020-03-08 12:54:02 +01:00
.cloned()
2020-03-03 09:24:03 +01:00
.zip(args.iter().map(|x| (*x).into_dynamic())),
2017-12-20 21:09:53 +01:00
);
2020-03-08 12:54:02 +01:00
// Evaluate
2020-03-09 14:57:07 +01:00
match self.eval_stmt(&mut scope, &func.body) {
2020-03-08 12:54:02 +01:00
// Convert return statement to return value
Err(EvalAltResult::Return(x, _)) => Ok(x),
2017-12-20 21:09:53 +01:00
other => other,
}
}
}
2020-03-04 15:00:01 +01:00
} else if spec.name == KEYWORD_TYPE_OF && args.len() == 1 {
2020-03-08 12:54:02 +01:00
// Handle `type_of` function
2020-03-03 10:28:38 +01:00
Ok(self
.map_type_name(args[0].type_name())
.to_string()
.into_dynamic())
2020-03-07 13:55:03 +01:00
} else if spec.name.starts_with(FUNC_GETTER) {
2020-03-08 12:54:02 +01:00
// Getter function not found
Err(EvalAltResult::ErrorDotExpr(
2020-03-07 13:55:03 +01:00
format!(
2020-03-08 12:54:02 +01:00
"- property '{}' unknown or write-only",
2020-03-07 13:55:03 +01:00
&spec.name[FUNC_GETTER.len()..]
),
pos,
))
} else if spec.name.starts_with(FUNC_SETTER) {
2020-03-08 12:54:02 +01:00
// Setter function not found
2020-03-07 13:55:03 +01:00
Err(EvalAltResult::ErrorDotExpr(
format!(
2020-03-08 12:54:02 +01:00
"- property '{}' unknown or read-only",
2020-03-07 13:55:03 +01:00
&spec.name[FUNC_SETTER.len()..]
),
pos,
))
2020-03-08 12:54:02 +01:00
} else if let Some(val) = def_val {
// Return default value
Ok(val.clone())
} else {
2020-03-08 12:54:02 +01:00
// Raise error
2020-03-02 16:16:19 +01:00
let types_list = args
.iter()
2020-03-03 09:24:03 +01:00
.map(|x| (*x).type_name())
2020-03-02 16:16:19 +01:00
.map(|name| self.map_type_name(name))
.collect::<Vec<_>>();
Err(EvalAltResult::ErrorFunctionNotFound(
2020-03-04 15:00:01 +01:00
format!("{} ({})", spec.name, types_list.join(", ")),
pos,
))
}
2017-12-20 12:16:14 +01:00
}
/// Chain-evaluate a dot setter
2017-12-20 12:16:14 +01:00
fn get_dot_val_helper(
2020-03-04 15:00:01 +01:00
&mut self,
2017-12-20 12:16:14 +01:00
scope: &mut Scope,
this_ptr: &mut Variant,
2017-12-20 12:16:14 +01:00
dot_rhs: &Expr,
) -> Result<Dynamic, EvalAltResult> {
match dot_rhs {
// xxx.fn_name(args)
2020-03-08 12:54:02 +01:00
Expr::FunctionCall(fn_name, args, def_val, pos) => {
let mut args = args
2019-09-18 12:21:07 +02:00
.iter()
2017-12-20 12:16:14 +01:00
.map(|arg| self.eval_expr(scope, arg))
.collect::<Result<Vec<_>, _>>()?;
2020-03-01 17:11:00 +01:00
2017-12-20 22:16:53 +01:00
let args = once(this_ptr)
.chain(args.iter_mut().map(|b| b.as_mut()))
.collect();
2017-12-20 12:16:14 +01:00
2020-03-08 12:54:02 +01:00
self.call_fn_raw(fn_name, args, def_val.as_ref(), *pos)
}
2020-03-01 17:11:00 +01:00
// xxx.id
Expr::Identifier(id, pos) => {
let get_fn_name = format!("{}{}", FUNC_GETTER, id);
2017-12-20 12:16:14 +01:00
2020-03-04 15:00:01 +01:00
self.call_fn_raw(&get_fn_name, vec![this_ptr], None, *pos)
}
2020-03-01 17:11:00 +01:00
// xxx.idx_lhs[idx_expr]
#[cfg(not(feature = "no_index"))]
Expr::Index(idx_lhs, idx_expr, idx_pos) => {
2020-03-08 12:54:02 +01:00
let (expr, _) = match idx_lhs.as_ref() {
// xxx.id[idx_expr]
2020-03-05 13:28:03 +01:00
Expr::Identifier(id, pos) => {
let get_fn_name = format!("{}{}", FUNC_GETTER, id);
2020-03-05 13:28:03 +01:00
(
self.call_fn_raw(&get_fn_name, vec![this_ptr], None, *pos)?,
*pos,
)
}
// xxx.???[???][idx_expr]
Expr::Index(_, _, _) => {
(self.get_dot_val_helper(scope, this_ptr, idx_lhs)?, *idx_pos)
}
// Syntax error
_ => {
return Err(EvalAltResult::ErrorDotExpr(
"".to_string(),
dot_rhs.position(),
))
}
2020-03-05 13:28:03 +01:00
};
let idx = self.eval_index_value(scope, idx_expr)?;
2020-03-08 12:54:02 +01:00
self.get_indexed_value(expr, idx, idx_expr.position(), *idx_pos)
.map(|(v, _)| v)
}
2020-03-01 17:11:00 +01:00
// xxx.dot_lhs.rhs
Expr::Dot(dot_lhs, rhs, _) => match dot_lhs.as_ref() {
// xxx.id.rhs
2020-03-04 15:00:01 +01:00
Expr::Identifier(id, pos) => {
let get_fn_name = format!("{}{}", FUNC_GETTER, id);
2020-03-04 15:00:01 +01:00
self.call_fn_raw(&get_fn_name, vec![this_ptr], None, *pos)
.and_then(|mut v| self.get_dot_val_helper(scope, v.as_mut(), rhs))
2020-03-01 06:30:22 +01:00
}
// xxx.idx_lhs[idx_expr].rhs
#[cfg(not(feature = "no_index"))]
Expr::Index(idx_lhs, idx_expr, idx_pos) => {
2020-03-08 12:54:02 +01:00
let (expr, _) = match idx_lhs.as_ref() {
// xxx.id[idx_expr].rhs
2020-03-05 13:28:03 +01:00
Expr::Identifier(id, pos) => {
let get_fn_name = format!("{}{}", FUNC_GETTER, id);
2020-03-05 13:28:03 +01:00
(
self.call_fn_raw(&get_fn_name, vec![this_ptr], None, *pos)?,
*pos,
)
}
// xxx.???[???][idx_expr].rhs
Expr::Index(_, _, _) => {
(self.get_dot_val_helper(scope, this_ptr, idx_lhs)?, *idx_pos)
}
// Syntax error
_ => {
return Err(EvalAltResult::ErrorDotExpr(
"".to_string(),
dot_rhs.position(),
))
}
2020-03-05 13:28:03 +01:00
};
let idx = self.eval_index_value(scope, idx_expr)?;
2020-03-08 12:54:02 +01:00
self.get_indexed_value(expr, idx, idx_expr.position(), *idx_pos)
.and_then(|(mut v, _)| self.get_dot_val_helper(scope, v.as_mut(), rhs))
}
// Syntax error
_ => Err(EvalAltResult::ErrorDotExpr(
"".to_string(),
dot_lhs.position(),
)),
2017-12-20 12:16:14 +01:00
},
// Syntax error
_ => Err(EvalAltResult::ErrorDotExpr(
"".to_string(),
dot_rhs.position(),
)),
}
}
/// Evaluate a dot chain getter
fn get_dot_val(
&mut self,
scope: &mut Scope,
dot_lhs: &Expr,
dot_rhs: &Expr,
) -> Result<Dynamic, EvalAltResult> {
match dot_lhs {
// id.???
Expr::Identifier(id, pos) => {
let (src_idx, mut target) = Self::search_scope(scope, id, Ok, *pos)?;
2020-03-08 12:54:02 +01:00
let val = self.get_dot_val_helper(scope, target.as_mut(), dot_rhs);
2020-03-08 12:54:02 +01:00
// In case the expression mutated `target`, we need to update it back into the scope because it is cloned.
*scope.get_mut(id, src_idx) = target;
2020-03-08 12:54:02 +01:00
val
}
// idx_lhs[idx_expr].???
#[cfg(not(feature = "no_index"))]
Expr::Index(idx_lhs, idx_expr, idx_pos) => {
let (src_type, src, idx, mut target) =
self.eval_index_expr(scope, idx_lhs, idx_expr, *idx_pos)?;
2020-03-08 12:54:02 +01:00
let val = self.get_dot_val_helper(scope, target.as_mut(), dot_rhs);
2020-03-08 12:54:02 +01:00
// In case the expression mutated `target`, we need to update it back into the scope because it is cloned.
if let Some((id, src_idx)) = src {
Self::update_indexed_var_in_scope(
src_type,
scope,
id,
src_idx,
idx,
target,
idx_lhs.position(),
)?;
}
2020-03-08 12:54:02 +01:00
val
}
// {expr}.???
expr => {
let mut target = self.eval_expr(scope, expr)?;
self.get_dot_val_helper(scope, target.as_mut(), dot_rhs)
}
}
}
/// Search for a variable within the scope, returning its value and index inside the Scope
2020-03-03 08:20:20 +01:00
fn search_scope<T>(
scope: &Scope,
2017-12-20 17:37:12 +01:00
id: &str,
2020-03-04 15:00:01 +01:00
map: impl FnOnce(Dynamic) -> Result<T, EvalAltResult>,
begin: Position,
2020-03-01 12:26:57 +01:00
) -> Result<(usize, T), EvalAltResult> {
2017-12-20 17:37:12 +01:00
scope
2020-03-03 08:20:20 +01:00
.get(id)
.ok_or_else(|| EvalAltResult::ErrorVariableNotFound(id.into(), begin))
2020-03-04 15:00:01 +01:00
.and_then(move |(idx, _, val)| map(val).map(|v| (idx, v)))
2017-12-20 17:37:12 +01:00
}
/// Evaluate the value of an index (must evaluate to INT)
#[cfg(not(feature = "no_index"))]
fn eval_index_value(
&mut self,
scope: &mut Scope,
idx_expr: &Expr,
) -> Result<INT, EvalAltResult> {
self.eval_expr(scope, idx_expr)?
.downcast::<INT>()
.map(|v| *v)
.map_err(|_| EvalAltResult::ErrorIndexExpr(idx_expr.position()))
}
/// Get the value at the indexed position of a base type
#[cfg(not(feature = "no_index"))]
2020-03-04 15:00:01 +01:00
fn get_indexed_value(
&self,
2020-03-04 15:00:01 +01:00
val: Dynamic,
idx: INT,
val_pos: Position,
idx_pos: Position,
2020-03-06 16:49:52 +01:00
) -> Result<(Dynamic, IndexSourceType), EvalAltResult> {
2020-03-04 15:00:01 +01:00
if val.is::<Array>() {
2020-03-06 16:49:52 +01:00
// val_array[idx]
2020-03-06 03:50:20 +01:00
let arr = val.downcast::<Array>().expect("array expected");
2020-03-04 15:00:01 +01:00
if idx >= 0 {
arr.get(idx as usize)
.cloned()
2020-03-06 16:49:52 +01:00
.map(|v| (v, IndexSourceType::Array))
.ok_or_else(|| EvalAltResult::ErrorArrayBounds(arr.len(), idx, val_pos))
2020-03-04 15:00:01 +01:00
} else {
Err(EvalAltResult::ErrorArrayBounds(arr.len(), idx, val_pos))
2020-03-04 15:00:01 +01:00
}
} else if val.is::<String>() {
2020-03-06 16:49:52 +01:00
// val_string[idx]
2020-03-06 03:50:20 +01:00
let s = val.downcast::<String>().expect("string expected");
2020-03-04 15:00:01 +01:00
if idx >= 0 {
s.chars()
.nth(idx as usize)
2020-03-06 16:49:52 +01:00
.map(|ch| (ch.into_dynamic(), IndexSourceType::String))
.ok_or_else(|| {
EvalAltResult::ErrorStringBounds(s.chars().count(), idx, val_pos)
})
2020-03-04 15:00:01 +01:00
} else {
Err(EvalAltResult::ErrorStringBounds(
s.chars().count(),
idx,
val_pos,
2020-03-04 15:00:01 +01:00
))
}
} else {
2020-03-06 16:49:52 +01:00
// Error - cannot be indexed
Err(EvalAltResult::ErrorIndexingType(
self.map_type_name(val.type_name()).to_string(),
idx_pos,
))
2020-03-04 15:00:01 +01:00
}
}
/// Evaluate an index expression
#[cfg(not(feature = "no_index"))]
2020-03-07 03:15:42 +01:00
fn eval_index_expr<'a>(
2020-03-04 15:00:01 +01:00
&mut self,
2017-12-20 21:09:53 +01:00
scope: &mut Scope,
2020-03-07 03:15:42 +01:00
lhs: &'a Expr,
2020-03-05 13:28:03 +01:00
idx_expr: &Expr,
idx_pos: Position,
2020-03-07 03:15:42 +01:00
) -> Result<(IndexSourceType, Option<(&'a str, usize)>, usize, Dynamic), EvalAltResult> {
let idx = self.eval_index_value(scope, idx_expr)?;
2020-03-05 13:28:03 +01:00
match lhs {
2020-03-06 03:50:20 +01:00
// id[idx_expr]
2020-03-05 13:28:03 +01:00
Expr::Identifier(id, _) => Self::search_scope(
scope,
&id,
|val| self.get_indexed_value(val, idx, idx_expr.position(), idx_pos),
2020-03-05 13:28:03 +01:00
lhs.position(),
)
2020-03-06 16:49:52 +01:00
.map(|(src_idx, (val, src_type))| {
2020-03-07 03:15:42 +01:00
(src_type, Some((id.as_str(), src_idx)), idx as usize, val)
2020-03-05 13:28:03 +01:00
}),
2020-03-06 03:50:20 +01:00
// (expr)[idx_expr]
expr => {
let val = self.eval_expr(scope, expr)?;
self.get_indexed_value(val, idx, idx_expr.position(), idx_pos)
2020-03-08 12:54:02 +01:00
.map(|(v, _)| (IndexSourceType::Expression, None, idx as usize, v))
}
2020-03-05 13:28:03 +01:00
}
2020-03-01 06:30:22 +01:00
}
/// Replace a character at an index position in a mutable string
#[cfg(not(feature = "no_index"))]
2020-03-01 06:30:22 +01:00
fn str_replace_char(s: &mut String, idx: usize, new_ch: char) {
2020-03-06 16:49:52 +01:00
let mut chars: Vec<char> = s.chars().collect();
let ch = *chars.get(idx).expect("string index out of bounds");
2020-03-01 06:30:22 +01:00
// See if changed - if so, update the String
2020-03-06 16:49:52 +01:00
if ch != new_ch {
chars[idx] = new_ch;
s.clear();
chars.iter().for_each(|&ch| s.push(ch));
2020-03-01 06:30:22 +01:00
}
2017-12-20 17:37:12 +01:00
}
/// Update the value at an index position in a variable inside the scope
#[cfg(not(feature = "no_index"))]
fn update_indexed_var_in_scope(
2020-03-06 16:49:52 +01:00
src_type: IndexSourceType,
scope: &mut Scope,
id: &str,
src_idx: usize,
idx: usize,
2020-03-08 12:54:02 +01:00
new_val: Dynamic,
val_pos: Position,
) -> Result<Dynamic, EvalAltResult> {
2020-03-06 16:49:52 +01:00
match src_type {
// array_id[idx] = val
IndexSourceType::Array => {
let arr = scope.get_mut_by_type::<Array>(id, src_idx);
2020-03-08 12:54:02 +01:00
Ok((arr[idx as usize] = new_val).into_dynamic())
}
2020-03-06 16:49:52 +01:00
// string_id[idx] = val
IndexSourceType::String => {
let s = scope.get_mut_by_type::<String>(id, src_idx);
// Value must be a character
2020-03-08 12:54:02 +01:00
let ch = *new_val
.downcast::<char>()
.map_err(|_| EvalAltResult::ErrorCharMismatch(val_pos))?;
Ok(Self::str_replace_char(s, idx as usize, ch).into_dynamic())
}
2020-03-06 16:49:52 +01:00
// All other variable types should be an error
_ => panic!("array or string source type expected for indexing"),
}
}
/// Update the value at an index position
#[cfg(not(feature = "no_index"))]
fn update_indexed_value(
2020-03-08 12:54:02 +01:00
mut target: Dynamic,
idx: usize,
new_val: Dynamic,
pos: Position,
) -> Result<Dynamic, EvalAltResult> {
2020-03-08 12:54:02 +01:00
if target.is::<Array>() {
let arr = target.downcast_mut::<Array>().expect("array expected");
arr[idx as usize] = new_val;
2020-03-08 12:54:02 +01:00
} else if target.is::<String>() {
let s = target.downcast_mut::<String>().expect("string expected");
// Value must be a character
let ch = *new_val
.downcast::<char>()
.map_err(|_| EvalAltResult::ErrorCharMismatch(pos))?;
Self::str_replace_char(s, idx as usize, ch);
} else {
// All other variable types should be an error
panic!("array or string source type expected for indexing")
}
2020-03-08 12:54:02 +01:00
Ok(target)
}
/// Chain-evaluate a dot setter
2017-12-20 12:16:14 +01:00
fn set_dot_val_helper(
2020-03-04 15:00:01 +01:00
&mut self,
scope: &mut Scope,
this_ptr: &mut Variant,
2017-12-20 12:16:14 +01:00
dot_rhs: &Expr,
mut new_val: Dynamic,
val_pos: Position,
) -> Result<Dynamic, EvalAltResult> {
match dot_rhs {
// xxx.id
Expr::Identifier(id, pos) => {
let set_fn_name = format!("{}{}", FUNC_SETTER, id);
2020-03-01 17:11:00 +01:00
self.call_fn_raw(&set_fn_name, vec![this_ptr, new_val.as_mut()], None, *pos)
}
2020-03-01 17:11:00 +01:00
// xxx.lhs[idx_expr]
// TODO - Allow chaining of indexing!
#[cfg(not(feature = "no_index"))]
Expr::Index(lhs, idx_expr, idx_pos) => match lhs.as_ref() {
// xxx.id[idx_expr]
Expr::Identifier(id, pos) => {
let get_fn_name = format!("{}{}", FUNC_GETTER, id);
self.call_fn_raw(&get_fn_name, vec![this_ptr], None, *pos)
.and_then(|v| {
let idx = self.eval_index_value(scope, idx_expr)?;
Self::update_indexed_value(v, idx as usize, new_val, val_pos)
})
.and_then(|mut v| {
let set_fn_name = format!("{}{}", FUNC_SETTER, id);
self.call_fn_raw(&set_fn_name, vec![this_ptr, v.as_mut()], None, *pos)
})
}
// All others - syntax error for setters chain
_ => Err(EvalAltResult::ErrorDotExpr(
"for assignment".to_string(),
*idx_pos,
)),
},
// xxx.lhs.{...}
Expr::Dot(lhs, rhs, _) => match lhs.as_ref() {
// xxx.id.rhs
2020-03-04 15:00:01 +01:00
Expr::Identifier(id, pos) => {
let get_fn_name = format!("{}{}", FUNC_GETTER, id);
2020-03-01 17:11:00 +01:00
2020-03-04 15:00:01 +01:00
self.call_fn_raw(&get_fn_name, vec![this_ptr], None, *pos)
2017-12-20 21:09:53 +01:00
.and_then(|mut v| {
self.set_dot_val_helper(scope, v.as_mut(), rhs, new_val, val_pos)
2017-12-20 21:09:53 +01:00
.map(|_| v) // Discard Ok return value
})
2017-12-20 12:16:14 +01:00
.and_then(|mut v| {
let set_fn_name = format!("{}{}", FUNC_SETTER, id);
2017-12-20 12:16:14 +01:00
2020-03-04 15:00:01 +01:00
self.call_fn_raw(&set_fn_name, vec![this_ptr, v.as_mut()], None, *pos)
2017-12-20 12:16:14 +01:00
})
}
// xxx.lhs[idx_expr].rhs
// TODO - Allow chaining of indexing!
#[cfg(not(feature = "no_index"))]
Expr::Index(lhs, idx_expr, idx_pos) => match lhs.as_ref() {
// xxx.id[idx_expr].rhs
Expr::Identifier(id, pos) => {
let get_fn_name = format!("{}{}", FUNC_GETTER, id);
self.call_fn_raw(&get_fn_name, vec![this_ptr], None, *pos)
.and_then(|v| {
let idx = self.eval_index_value(scope, idx_expr)?;
let (mut target, _) = self.get_indexed_value(
v.clone(), // TODO - Avoid cloning this
idx,
idx_expr.position(),
*idx_pos,
)?;
self.set_dot_val_helper(
scope,
target.as_mut(),
rhs,
new_val,
val_pos,
)?;
2020-03-08 12:54:02 +01:00
// In case the expression mutated `target`, we need to update it back into the scope because it is cloned.
Self::update_indexed_value(v, idx as usize, target, val_pos)
})
.and_then(|mut v| {
let set_fn_name = format!("{}{}", FUNC_SETTER, id);
self.call_fn_raw(
&set_fn_name,
vec![this_ptr, v.as_mut()],
None,
*pos,
)
})
}
// All others - syntax error for setters chain
_ => Err(EvalAltResult::ErrorDotExpr(
"for assignment".to_string(),
*idx_pos,
)),
},
// All others - syntax error for setters chain
_ => Err(EvalAltResult::ErrorDotExpr(
"for assignment".to_string(),
lhs.position(),
)),
2017-12-20 12:16:14 +01:00
},
// Syntax error
_ => Err(EvalAltResult::ErrorDotExpr(
"for assignment".to_string(),
dot_rhs.position(),
)),
}
}
// Evaluate a dot chain setter
2017-12-20 12:16:14 +01:00
fn set_dot_val(
2020-03-04 15:00:01 +01:00
&mut self,
2017-12-20 12:16:14 +01:00
scope: &mut Scope,
dot_lhs: &Expr,
dot_rhs: &Expr,
new_val: Dynamic,
val_pos: Position,
) -> Result<Dynamic, EvalAltResult> {
match dot_lhs {
// id.???
Expr::Identifier(id, pos) => {
2020-03-06 16:49:52 +01:00
let (src_idx, mut target) = Self::search_scope(scope, id, Ok, *pos)?;
2020-03-08 12:54:02 +01:00
let val =
self.set_dot_val_helper(scope, target.as_mut(), dot_rhs, new_val, val_pos);
2020-03-08 12:54:02 +01:00
// In case the expression mutated `target`, we need to update it back into the scope because it is cloned.
2020-03-06 16:49:52 +01:00
*scope.get_mut(id, src_idx) = target;
2020-03-08 12:54:02 +01:00
val
}
2020-03-01 17:11:00 +01:00
// lhs[idx_expr].???
// TODO - Allow chaining of indexing!
#[cfg(not(feature = "no_index"))]
Expr::Index(lhs, idx_expr, idx_pos) => {
2020-03-06 16:49:52 +01:00
let (src_type, src, idx, mut target) =
self.eval_index_expr(scope, lhs, idx_expr, *idx_pos)?;
2020-03-08 12:54:02 +01:00
let val =
self.set_dot_val_helper(scope, target.as_mut(), dot_rhs, new_val, val_pos);
2020-03-05 13:28:03 +01:00
2020-03-08 12:54:02 +01:00
// In case the expression mutated `target`, we need to update it back into the scope because it is cloned.
if let Some((id, src_idx)) = src {
Self::update_indexed_var_in_scope(
src_type,
scope,
id,
src_idx,
idx,
target,
lhs.position(),
)?;
2020-03-01 06:30:22 +01:00
}
2020-03-08 12:54:02 +01:00
val
}
// Syntax error
_ => Err(EvalAltResult::ErrorDotExpr(
"for assignment".to_string(),
dot_lhs.position(),
)),
}
}
/// Evaluate an expression
2020-03-04 15:00:01 +01:00
fn eval_expr(&mut self, scope: &mut Scope, expr: &Expr) -> Result<Dynamic, EvalAltResult> {
match expr {
#[cfg(not(feature = "no_float"))]
2020-03-07 03:15:42 +01:00
Expr::FloatConstant(f, _) => Ok(f.into_dynamic()),
Expr::IntegerConstant(i, _) => Ok(i.into_dynamic()),
2020-03-03 10:28:38 +01:00
Expr::StringConstant(s, _) => Ok(s.into_dynamic()),
2020-03-07 03:15:42 +01:00
Expr::CharConstant(c, _) => Ok(c.into_dynamic()),
2020-03-05 13:28:03 +01:00
Expr::Identifier(id, pos) => {
Self::search_scope(scope, id, Ok, *pos).map(|(_, val)| val)
}
2020-03-07 03:39:00 +01:00
// lhs[idx_expr]
#[cfg(not(feature = "no_index"))]
Expr::Index(lhs, idx_expr, idx_pos) => self
.eval_index_expr(scope, lhs, idx_expr, *idx_pos)
.map(|(_, _, _, x)| x),
2020-03-01 17:11:00 +01:00
2020-03-07 03:39:00 +01:00
// Statement block
2020-03-09 14:57:07 +01:00
Expr::Stmt(stmt, _) => self.eval_stmt(scope, stmt),
2020-03-07 03:39:00 +01:00
// lhs = rhs
Expr::Assignment(lhs, rhs, _) => {
let rhs_val = self.eval_expr(scope, rhs)?;
2016-03-26 18:46:28 +01:00
2020-03-05 13:28:03 +01:00
match lhs.as_ref() {
// name = rhs
2020-03-04 15:00:01 +01:00
Expr::Identifier(name, pos) => {
2020-03-03 09:24:03 +01:00
if let Some((idx, _, _)) = scope.get(name) {
*scope.get_mut(name, idx) = rhs_val;
2020-03-03 10:28:38 +01:00
Ok(().into_dynamic())
2020-03-03 09:24:03 +01:00
} else {
2020-03-04 15:00:01 +01:00
Err(EvalAltResult::ErrorVariableNotFound(name.clone(), *pos))
2020-03-03 09:24:03 +01:00
}
}
2020-03-05 13:28:03 +01:00
// idx_lhs[idx_expr] = rhs
#[cfg(not(feature = "no_index"))]
Expr::Index(idx_lhs, idx_expr, idx_pos) => {
2020-03-06 16:49:52 +01:00
let (src_type, src, idx, _) =
self.eval_index_expr(scope, idx_lhs, idx_expr, *idx_pos)?;
2020-03-05 13:28:03 +01:00
if let Some((id, src_idx)) = src {
Ok(Self::update_indexed_var_in_scope(
src_type,
scope,
&id,
src_idx,
idx,
rhs_val,
rhs.position(),
)?)
} else {
2020-03-06 16:49:52 +01:00
Err(EvalAltResult::ErrorAssignmentToUnknownLHS(
idx_lhs.position(),
))
2020-03-01 06:30:22 +01:00
}
2016-03-26 18:46:28 +01:00
}
2020-03-02 05:08:03 +01:00
// dot_lhs.dot_rhs = rhs
Expr::Dot(dot_lhs, dot_rhs, _) => {
self.set_dot_val(scope, dot_lhs, dot_rhs, rhs_val, rhs.position())
}
2020-03-02 05:08:03 +01:00
// Syntax error
2020-03-05 13:28:03 +01:00
_ => Err(EvalAltResult::ErrorAssignmentToUnknownLHS(lhs.position())),
2016-02-29 22:43:45 +01:00
}
}
2020-03-01 17:11:00 +01:00
Expr::Dot(lhs, rhs, _) => self.get_dot_val(scope, lhs, rhs),
2020-03-01 17:11:00 +01:00
#[cfg(not(feature = "no_index"))]
Expr::Array(contents, _) => {
2016-03-26 18:46:28 +01:00
let mut arr = Vec::new();
2020-03-04 15:00:01 +01:00
contents
.iter()
.try_for_each::<_, Result<_, EvalAltResult>>(|item| {
let arg = self.eval_expr(scope, item)?;
arr.push(arg);
Ok(())
})?;
2016-03-26 18:46:28 +01:00
Ok(Box::new(arr))
}
2020-03-01 17:11:00 +01:00
2020-03-08 12:54:02 +01:00
Expr::FunctionCall(fn_name, args, def_val, pos) => {
2020-03-04 15:00:01 +01:00
let mut args = args
.iter()
2020-03-02 05:08:03 +01:00
.map(|expr| self.eval_expr(scope, expr))
.collect::<Result<Vec<Dynamic>, _>>()?;
2020-03-04 15:00:01 +01:00
self.call_fn_raw(
fn_name,
args.iter_mut().map(|b| b.as_mut()).collect(),
2020-03-08 12:54:02 +01:00
def_val.as_ref(),
2020-03-04 15:00:01 +01:00
*pos,
)
}
2020-03-01 17:11:00 +01:00
2020-03-02 05:08:03 +01:00
Expr::And(lhs, rhs) => Ok(Box::new(
*self
.eval_expr(scope, &*lhs)?
.downcast::<bool>()
.map_err(|_| {
EvalAltResult::ErrorBooleanArgMismatch("AND".into(), lhs.position())
})?
&& // Short-circuit using &&
*self
.eval_expr(scope, &*rhs)?
.downcast::<bool>()
.map_err(|_| {
EvalAltResult::ErrorBooleanArgMismatch("AND".into(), rhs.position())
})?,
2020-03-02 05:08:03 +01:00
)),
Expr::Or(lhs, rhs) => Ok(Box::new(
*self
.eval_expr(scope, &*lhs)?
.downcast::<bool>()
.map_err(|_| {
EvalAltResult::ErrorBooleanArgMismatch("OR".into(), lhs.position())
})?
|| // Short-circuit using ||
*self
.eval_expr(scope, &*rhs)?
.downcast::<bool>()
.map_err(|_| {
EvalAltResult::ErrorBooleanArgMismatch("OR".into(), rhs.position())
})?,
2020-03-02 05:08:03 +01:00
)),
2020-03-03 10:28:38 +01:00
Expr::True(_) => Ok(true.into_dynamic()),
Expr::False(_) => Ok(false.into_dynamic()),
Expr::Unit(_) => Ok(().into_dynamic()),
2016-02-29 22:43:45 +01:00
}
}
/// Evaluate a statement
pub(crate) fn eval_stmt(
2020-03-04 15:00:01 +01:00
&mut self,
scope: &mut Scope,
stmt: &Stmt,
) -> Result<Dynamic, EvalAltResult> {
match stmt {
2020-03-09 14:57:07 +01:00
// No-op
Stmt::Noop(_) => Ok(().into_dynamic()),
2020-03-06 16:49:52 +01:00
// Expression as statement
2020-03-01 06:30:22 +01:00
Stmt::Expr(expr) => self.eval_expr(scope, expr),
2020-03-01 17:11:00 +01:00
2020-03-06 16:49:52 +01:00
// Block scope
2020-03-09 14:57:07 +01:00
Stmt::Block(block, _) => {
let prev_len = scope.len();
2020-03-03 10:28:38 +01:00
let mut last_result: Result<Dynamic, EvalAltResult> = Ok(().into_dynamic());
2016-02-29 22:43:45 +01:00
2020-03-01 06:30:22 +01:00
for block_stmt in block.iter() {
last_result = self.eval_stmt(scope, block_stmt);
2020-03-01 17:11:00 +01:00
2017-10-02 23:44:45 +02:00
if let Err(x) = last_result {
last_result = Err(x);
break;
}
2016-02-29 22:43:45 +01:00
}
2020-03-06 16:49:52 +01:00
scope.rewind(prev_len);
2016-02-29 22:43:45 +01:00
2017-10-02 23:44:45 +02:00
last_result
2016-02-29 22:43:45 +01:00
}
2020-03-01 17:11:00 +01:00
2020-03-06 16:49:52 +01:00
// If-else statement
2020-03-01 06:30:22 +01:00
Stmt::IfElse(guard, body, else_body) => self
.eval_expr(scope, guard)?
.downcast::<bool>()
.map_err(|_| EvalAltResult::ErrorIfGuard(guard.position()))
2020-03-01 06:30:22 +01:00
.and_then(|guard_val| {
if *guard_val {
self.eval_stmt(scope, body)
} else if let Some(stmt) = else_body {
self.eval_stmt(scope, stmt.as_ref())
2020-03-01 06:30:22 +01:00
} else {
2020-03-03 10:28:38 +01:00
Ok(().into_dynamic())
2016-03-03 14:20:55 +01:00
}
2020-03-01 06:30:22 +01:00
}),
2020-03-01 17:11:00 +01:00
2020-03-06 16:49:52 +01:00
// While loop
Stmt::While(guard, body) => loop {
2020-03-01 06:30:22 +01:00
match self.eval_expr(scope, guard)?.downcast::<bool>() {
Ok(guard_val) => {
if *guard_val {
2017-12-20 12:16:14 +01:00
match self.eval_stmt(scope, body) {
2020-03-03 10:28:38 +01:00
Err(EvalAltResult::LoopBreak) => return Ok(().into_dynamic()),
2017-12-21 12:28:59 +01:00
Err(x) => return Err(x),
2017-12-20 12:16:14 +01:00
_ => (),
2016-02-29 22:43:45 +01:00
}
2017-12-20 12:16:14 +01:00
} else {
2020-03-03 10:28:38 +01:00
return Ok(().into_dynamic());
2016-02-29 22:43:45 +01:00
}
}
Err(_) => return Err(EvalAltResult::ErrorIfGuard(guard.position())),
2016-02-29 22:43:45 +01:00
}
2017-12-20 12:16:14 +01:00
},
2020-03-01 17:11:00 +01:00
2020-03-06 16:49:52 +01:00
// Loop statement
Stmt::Loop(body) => loop {
2017-12-20 12:16:14 +01:00
match self.eval_stmt(scope, body) {
2020-03-03 10:28:38 +01:00
Err(EvalAltResult::LoopBreak) => return Ok(().into_dynamic()),
2017-12-21 12:28:59 +01:00
Err(x) => return Err(x),
2017-12-20 12:16:14 +01:00
_ => (),
2017-10-30 16:08:44 +01:00
}
2017-12-20 12:16:14 +01:00
},
2020-03-01 17:11:00 +01:00
2020-03-06 16:49:52 +01:00
// For loop
Stmt::For(name, expr, body) => {
let arr = self.eval_expr(scope, expr)?;
let tid = Any::type_id(&*arr);
2020-03-01 17:11:00 +01:00
if let Some(iter_fn) = self.type_iterators.get(&tid) {
2020-03-03 08:20:20 +01:00
scope.push(name.clone(), ());
let idx = scope.len() - 1;
2020-03-01 17:11:00 +01:00
for a in iter_fn(&arr) {
2020-03-03 08:20:20 +01:00
*scope.get_mut(name, idx) = a;
2020-03-01 17:11:00 +01:00
match self.eval_stmt(scope, body) {
Err(EvalAltResult::LoopBreak) => break,
Err(x) => return Err(x),
_ => (),
}
}
2020-03-03 08:20:20 +01:00
scope.pop();
2020-03-03 10:28:38 +01:00
Ok(().into_dynamic())
} else {
return Err(EvalAltResult::ErrorFor(expr.position()));
}
}
2020-03-01 17:11:00 +01:00
2020-03-06 16:49:52 +01:00
// Break statement
Stmt::Break(_) => Err(EvalAltResult::LoopBreak),
2020-03-01 17:11:00 +01:00
2020-03-03 11:15:20 +01:00
// Empty return
Stmt::ReturnWithVal(None, true, pos) => {
Err(EvalAltResult::Return(().into_dynamic(), *pos))
}
// Return value
Stmt::ReturnWithVal(Some(a), true, pos) => {
Err(EvalAltResult::Return(self.eval_expr(scope, a)?, *pos))
}
// Empty throw
Stmt::ReturnWithVal(None, false, pos) => {
Err(EvalAltResult::ErrorRuntime("".into(), *pos))
}
2020-03-01 17:11:00 +01:00
2020-03-03 11:15:20 +01:00
// Throw value
Stmt::ReturnWithVal(Some(a), false, pos) => {
let val = self.eval_expr(scope, a)?;
Err(EvalAltResult::ErrorRuntime(
2020-03-04 15:00:01 +01:00
val.downcast::<String>()
.map(|s| *s)
.unwrap_or("".to_string()),
2020-03-03 11:15:20 +01:00
*pos,
))
}
2020-03-01 17:11:00 +01:00
2020-03-06 16:49:52 +01:00
// Let statement
Stmt::Let(name, init, _) => {
2020-03-01 06:30:22 +01:00
if let Some(v) = init {
2020-03-03 08:20:20 +01:00
let val = self.eval_expr(scope, v)?;
scope.push_dynamic(name.clone(), val);
2020-03-01 06:30:22 +01:00
} else {
2020-03-03 08:20:20 +01:00
scope.push(name.clone(), ());
2020-03-01 06:30:22 +01:00
}
2020-03-03 10:28:38 +01:00
Ok(().into_dynamic())
2016-02-29 22:43:45 +01:00
}
}
}
/// Map a type_name into a pretty-print name
2020-03-03 09:24:03 +01:00
pub(crate) fn map_type_name<'a>(&'a self, name: &'a str) -> &'a str {
2020-03-02 16:16:19 +01:00
self.type_names
2020-03-03 09:24:03 +01:00
.get(name)
.map(|s| s.as_str())
.unwrap_or(name)
2020-03-02 16:16:19 +01:00
}
/// Clean up all script-defined functions within the `Engine`.
pub fn clear_functions(&mut self) {
self.script_functions.clear();
}
2016-03-01 15:40:48 +01:00
}
2020-03-04 16:44:32 +01:00
/// Print/debug to stdout
#[cfg(not(feature = "no_stdlib"))]
2020-03-04 16:44:32 +01:00
fn default_print(s: &str) {
println!("{}", s);
}
/// No-op
#[cfg(feature = "no_stdlib")]
2020-03-04 16:44:32 +01:00
fn default_print(_: &str) {}