rhai/src/engine.rs

961 lines
35 KiB
Rust
Raw Normal View History

2017-12-20 12:16:14 +01:00
use std::any::TypeId;
use std::cmp::{PartialEq, PartialOrd};
2016-02-29 22:43:45 +01:00
use std::collections::HashMap;
use std::error::Error;
2020-03-01 06:30:22 +01:00
use std::sync::Arc;
2016-02-29 22:43:45 +01:00
use crate::any::{Any, AnyExt, Dynamic, Variant};
2019-09-18 12:21:07 +02:00
use crate::call::FunArgs;
use crate::fn_register::RegisterFn;
use crate::parser::{Expr, FnDef, ParseError, Position, Stmt};
2020-03-03 08:20:20 +01:00
use crate::scope::Scope;
pub type Array = Vec<Dynamic>;
pub type FnCallArgs<'a> = Vec<&'a mut Variant>;
2016-02-29 22:43:45 +01:00
2020-03-03 10:28:38 +01:00
const KEYWORD_PRINT: &'static str = "print";
const KEYWORD_DEBUG: &'static str = "debug";
const KEYWORD_TYPE_OF: &'static str = "type_of";
2020-03-02 09:29:50 +01:00
#[derive(Debug)]
pub enum EvalAltResult {
2020-03-02 05:08:03 +01:00
ErrorParsing(ParseError),
ErrorFunctionNotFound(String, Position),
ErrorFunctionArgsMismatch(String, usize, Position),
ErrorBooleanArgMismatch(String, Position),
ErrorArrayBounds(usize, i64, Position),
ErrorStringBounds(usize, i64, Position),
ErrorIndexing(Position),
ErrorIndexExpr(Position),
ErrorIfGuard(Position),
ErrorFor(Position),
ErrorVariableNotFound(String, Position),
ErrorAssignmentToUnknownLHS(Position),
ErrorMismatchOutputType(String, Position),
2020-03-02 09:29:50 +01:00
ErrorCantOpenScriptFile(String, std::io::Error),
ErrorDotExpr(Position),
ErrorArithmetic(String, Position),
2020-03-03 11:15:20 +01:00
ErrorRuntime(String, Position),
LoopBreak,
Return(Dynamic, Position),
2017-12-20 21:09:53 +01:00
}
impl Error for EvalAltResult {
2016-02-29 22:43:45 +01:00
fn description(&self) -> &str {
match self {
2020-03-02 05:08:03 +01:00
Self::ErrorParsing(p) => p.description(),
Self::ErrorFunctionNotFound(_, _) => "Function not found",
Self::ErrorFunctionArgsMismatch(_, _, _) => {
"Function call with wrong number of arguments"
}
Self::ErrorBooleanArgMismatch(_, _) => "Boolean operator expects boolean operands",
Self::ErrorIndexExpr(_) => "Indexing into an array or string expects an integer index",
Self::ErrorIndexing(_) => "Indexing can only be performed on an array or a string",
Self::ErrorArrayBounds(_, index, _) if *index < 0 => {
"Array access expects non-negative index"
}
Self::ErrorArrayBounds(max, _, _) if *max == 0 => "Access of empty array",
Self::ErrorArrayBounds(_, _, _) => "Array index out of bounds",
Self::ErrorStringBounds(_, index, _) if *index < 0 => {
2020-03-01 06:30:22 +01:00
"Indexing a string expects a non-negative index"
}
Self::ErrorStringBounds(max, _, _) if *max == 0 => "Indexing of empty string",
Self::ErrorStringBounds(_, _, _) => "String index out of bounds",
Self::ErrorIfGuard(_) => "If guard expects boolean expression",
Self::ErrorFor(_) => "For loop expects array or range",
Self::ErrorVariableNotFound(_, _) => "Variable not found",
Self::ErrorAssignmentToUnknownLHS(_) => {
"Assignment to an unsupported left-hand side expression"
}
Self::ErrorMismatchOutputType(_, _) => "Output type is incorrect",
2020-03-02 09:29:50 +01:00
Self::ErrorCantOpenScriptFile(_, _) => "Cannot open script file",
Self::ErrorDotExpr(_) => "Malformed dot expression",
Self::ErrorArithmetic(_, _) => "Arithmetic error",
2020-03-03 11:15:20 +01:00
Self::ErrorRuntime(_, _) => "Runtime error",
2020-03-01 06:30:22 +01:00
Self::LoopBreak => "[Not Error] Breaks out of loop",
Self::Return(_, _) => "[Not Error] Function returns value",
2016-02-29 22:43:45 +01:00
}
}
2019-09-18 12:21:07 +02:00
fn cause(&self) -> Option<&dyn Error> {
2016-02-29 22:43:45 +01:00
None
}
}
2020-03-01 17:11:00 +01:00
impl std::fmt::Display for EvalAltResult {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let desc = self.description();
match self {
Self::ErrorFunctionNotFound(s, pos) => write!(f, "{}: '{}' ({})", desc, s, pos),
Self::ErrorVariableNotFound(s, pos) => write!(f, "{}: '{}' ({})", desc, s, pos),
Self::ErrorIndexing(pos) => write!(f, "{} ({})", desc, pos),
Self::ErrorIndexExpr(pos) => write!(f, "{} ({})", desc, pos),
Self::ErrorIfGuard(pos) => write!(f, "{} ({})", desc, pos),
Self::ErrorFor(pos) => write!(f, "{} ({})", desc, pos),
Self::ErrorAssignmentToUnknownLHS(pos) => write!(f, "{} ({})", desc, pos),
Self::ErrorMismatchOutputType(s, pos) => write!(f, "{}: {} ({})", desc, s, pos),
Self::ErrorDotExpr(pos) => write!(f, "{} ({})", desc, pos),
Self::ErrorArithmetic(s, pos) => write!(f, "{}: {} ({})", desc, s, pos),
2020-03-03 11:15:20 +01:00
Self::ErrorRuntime(s, pos) if s.is_empty() => write!(f, "{} ({})", desc, pos),
Self::ErrorRuntime(s, pos) => write!(f, "{}: {} ({})", desc, s, pos),
Self::LoopBreak => write!(f, "{}", desc),
Self::Return(_, pos) => write!(f, "{} ({})", desc, pos),
Self::ErrorCantOpenScriptFile(filename, err) => {
write!(f, "{} '{}': {}", desc, filename, err)
}
Self::ErrorParsing(p) => write!(f, "Syntax error: {}", p),
Self::ErrorFunctionArgsMismatch(fun, n, pos) => {
write!(f, "Function '{}' expects {} argument(s) ({})", fun, n, pos)
}
Self::ErrorBooleanArgMismatch(op, pos) => {
write!(f, "{} operator expects boolean operands ({})", op, pos)
}
Self::ErrorArrayBounds(_, index, pos) if *index < 0 => {
write!(f, "{}: {} < 0 ({})", desc, index, pos)
}
Self::ErrorArrayBounds(max, _, pos) if *max == 0 => write!(f, "{} ({})", desc, pos),
Self::ErrorArrayBounds(max, index, pos) => {
write!(f, "{} (max {}): {} ({})", desc, max - 1, index, pos)
}
Self::ErrorStringBounds(_, index, pos) if *index < 0 => {
write!(f, "{}: {} < 0 ({})", desc, index, pos)
}
Self::ErrorStringBounds(max, _, pos) if *max == 0 => write!(f, "{} ({})", desc, pos),
Self::ErrorStringBounds(max, index, pos) => {
write!(f, "{} (max {}): {} ({})", desc, max - 1, index, pos)
}
}
2016-02-29 22:43:45 +01:00
}
}
2017-12-20 12:16:14 +01:00
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct FnSpec {
pub ident: String,
pub args: Option<Vec<TypeId>>,
}
type IteratorFn = dyn Fn(&Dynamic) -> Box<dyn Iterator<Item = Dynamic>>;
2017-10-30 16:08:44 +01:00
/// Rhai's engine type. This is what you use to run Rhai scripts
///
/// ```rust
/// extern crate rhai;
/// use rhai::Engine;
///
/// fn main() {
/// let mut engine = Engine::new();
///
/// if let Ok(result) = engine.eval::<i64>("40 + 2") {
/// println!("Answer: {}", result); // prints 42
/// }
/// }
/// ```
2016-02-29 22:43:45 +01:00
pub struct Engine {
/// A hashmap containing all compiled functions known to the engine
fns: HashMap<FnSpec, Arc<FnIntExt>>,
/// A hashmap containing all script-defined functions
pub(crate) script_fns: HashMap<FnSpec, Arc<FnIntExt>>,
/// A hashmap containing all iterators known to the engine
type_iterators: HashMap<TypeId, Arc<IteratorFn>>,
2020-03-02 16:16:19 +01:00
type_names: HashMap<String, String>,
pub(crate) on_print: Box<dyn Fn(&str)>,
pub(crate) on_debug: Box<dyn Fn(&str)>,
2017-12-20 12:16:14 +01:00
}
pub enum FnIntExt {
Ext(Box<FnAny>),
Int(FnDef),
2016-02-29 22:43:45 +01:00
}
pub type FnAny = dyn Fn(FnCallArgs, Position) -> Result<Dynamic, EvalAltResult>;
2017-12-20 12:16:14 +01:00
2016-02-29 22:43:45 +01:00
impl Engine {
2017-12-20 22:16:53 +01:00
pub fn call_fn<'a, I, A, T>(&self, ident: I, args: A) -> Result<T, EvalAltResult>
where
I: Into<String>,
A: FunArgs<'a>,
T: Any + Clone,
{
2020-03-03 08:20:20 +01:00
let pos = Position::new();
self.call_fn_raw(ident.into(), args.into_vec(), None, pos)
2017-12-20 22:16:53 +01:00
.and_then(|b| {
2020-03-02 16:16:19 +01:00
b.downcast().map(|b| *b).map_err(|a| {
2020-03-03 09:24:03 +01:00
EvalAltResult::ErrorMismatchOutputType(
self.map_type_name((*a).type_name()).into(),
pos,
)
2020-03-02 16:16:19 +01:00
})
2017-12-20 22:16:53 +01:00
})
}
2017-10-30 16:08:44 +01:00
/// Universal method for calling functions, that are either
/// registered with the `Engine` or written in Rhai
fn call_fn_raw(
&self,
ident: String,
args: FnCallArgs,
def_value: Option<&Dynamic>,
pos: Position,
) -> Result<Dynamic, EvalAltResult> {
debug_println!(
2020-03-03 09:24:03 +01:00
"Calling {}({})",
2017-12-20 21:09:53 +01:00
ident,
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-03 09:24:03 +01:00
let mut spec = FnSpec { ident, args: None };
// First search in script-defined functions (can override built-in),
// then in built-in's
let fn_def = self.script_fns.get(&spec).or_else(|| {
spec.args = Some(args.iter().map(|a| Any::type_id(&**a)).collect());
self.fns.get(&spec)
});
if let Some(f) = fn_def {
match **f {
2020-02-25 03:40:48 +01:00
FnIntExt::Ext(ref f) => {
let r = f(args, pos);
2020-03-01 17:11:00 +01:00
2020-02-25 03:40:48 +01:00
if r.is_err() {
return r;
}
2020-03-03 09:24:03 +01:00
let callback = match spec.ident.as_str() {
2020-03-03 10:28:38 +01:00
KEYWORD_PRINT => &self.on_print,
KEYWORD_DEBUG => &self.on_debug,
2020-02-25 03:40:48 +01:00
_ => return r,
};
2020-03-03 10:28:38 +01:00
Ok(callback(
2020-02-25 03:40:48 +01:00
r.unwrap()
.downcast::<String>()
.map(|x| *x)
.unwrap_or("error: not a string".into())
.as_str(),
2020-03-03 10:28:38 +01:00
)
.into_dynamic())
2020-02-25 03:40:48 +01:00
}
2017-12-20 21:09:53 +01:00
FnIntExt::Int(ref f) => {
let mut scope = Scope::new();
2020-03-01 17:11:00 +01:00
2017-12-20 21:09:53 +01:00
scope.extend(
f.params
.iter()
.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
);
match self.eval_stmt(&mut scope, &*f.body) {
Err(EvalAltResult::Return(x, _)) => Ok(x),
2017-12-20 21:09:53 +01:00
other => other,
}
}
}
2020-03-03 10:28:38 +01:00
} else if spec.ident == KEYWORD_TYPE_OF && args.len() == 1 {
Ok(self
.map_type_name(args[0].type_name())
.to_string()
.into_dynamic())
} else if let Some(val) = def_value {
// Return default value
Ok(val.clone())
} else {
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-03 09:24:03 +01:00
format!("{} ({})", spec.ident, types_list.join(", ")),
pos,
))
}
2017-12-20 12:16:14 +01:00
}
pub(crate) fn register_fn_raw(
&mut self,
ident: String,
args: Option<Vec<TypeId>>,
f: Box<FnAny>,
) {
debug_println!("Register; {:?} with args {:?}", ident, args);
2017-12-20 21:09:53 +01:00
2017-12-20 14:35:44 +01:00
let spec = FnSpec { ident, args };
2017-12-31 19:58:50 +01:00
self.fns.insert(spec, Arc::new(FnIntExt::Ext(f)));
}
2017-10-30 16:08:44 +01:00
/// Register a type for use with Engine. Keep in mind that
/// your type must implement Clone.
2017-12-20 12:16:14 +01:00
pub fn register_type<T: Any>(&mut self) {
// currently a no-op, exists for future extensibility
2016-02-29 22:43:45 +01:00
}
/// Register an iterator adapter for a type.
pub fn register_iterator<T: Any, F>(&mut self, f: F)
where
2020-03-01 12:26:57 +01:00
F: Fn(&Dynamic) -> Box<dyn Iterator<Item = Dynamic>> + 'static,
{
self.type_iterators.insert(TypeId::of::<T>(), Arc::new(f));
}
2017-10-30 16:08:44 +01:00
/// Register a get function for a member of a registered type
2020-03-01 12:26:57 +01:00
pub fn register_get<T: Any + Clone, U: Any + Clone>(
&mut self,
name: &str,
get_fn: impl Fn(&mut T) -> U + 'static,
) {
let get_name = "get$".to_string() + name;
2016-03-17 13:45:48 +01:00
self.register_fn(&get_name, get_fn);
}
2017-10-30 16:08:44 +01:00
/// Register a set function for a member of a registered type
2020-03-01 12:26:57 +01:00
pub fn register_set<T: Any + Clone, U: Any + Clone>(
&mut self,
name: &str,
set_fn: impl Fn(&mut T, U) -> () + 'static,
) {
let set_name = "set$".to_string() + name;
2016-03-17 13:45:48 +01:00
self.register_fn(&set_name, set_fn);
}
2017-10-30 16:08:44 +01:00
/// Shorthand for registering both getters and setters
2020-03-01 12:26:57 +01:00
pub fn register_get_set<T: Any + Clone, U: Any + Clone>(
2017-12-20 12:16:14 +01:00
&mut self,
name: &str,
2020-03-01 12:26:57 +01:00
get_fn: impl Fn(&mut T) -> U + 'static,
set_fn: impl Fn(&mut T, U) -> () + 'static,
) {
2016-03-17 13:45:48 +01:00
self.register_get(name, get_fn);
self.register_set(name, set_fn);
}
2017-12-20 12:16:14 +01:00
fn get_dot_val_helper(
&self,
scope: &mut Scope,
this_ptr: &mut Variant,
2017-12-20 12:16:14 +01:00
dot_rhs: &Expr,
) -> Result<Dynamic, EvalAltResult> {
2017-12-20 12:16:14 +01:00
use std::iter::once;
match dot_rhs {
Expr::FunctionCall(fn_name, args, def_value, pos) => {
let mut args: Array = 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
self.call_fn_raw(fn_name.into(), args, def_value.as_ref(), *pos)
}
2020-03-01 17:11:00 +01:00
Expr::Identifier(id, pos) => {
let get_fn_name = "get$".to_string() + id;
2017-12-20 12:16:14 +01:00
self.call_fn_raw(get_fn_name, vec![this_ptr], None, *pos)
}
2020-03-01 17:11:00 +01:00
Expr::Index(id, idx_raw, pos) => {
2020-03-01 06:30:22 +01:00
let idx = self
.eval_expr(scope, idx_raw)?
.downcast_ref::<i64>()
.map(|i| *i)
.ok_or(EvalAltResult::ErrorIndexExpr(idx_raw.position()))?;
2020-03-01 06:30:22 +01:00
let get_fn_name = "get$".to_string() + id;
let mut val = self.call_fn_raw(get_fn_name, vec![this_ptr], None, *pos)?;
2017-12-20 12:16:14 +01:00
2020-03-03 09:24:03 +01:00
if let Some(arr) = val.downcast_mut() as Option<&mut Array> {
2020-03-01 17:11:00 +01:00
if idx >= 0 {
2020-03-01 06:30:22 +01:00
arr.get(idx as usize)
.cloned()
.ok_or_else(|| EvalAltResult::ErrorArrayBounds(arr.len(), idx, *pos))
2020-03-01 17:11:00 +01:00
} else {
Err(EvalAltResult::ErrorArrayBounds(arr.len(), idx, *pos))
2020-03-01 06:30:22 +01:00
}
2020-03-03 09:24:03 +01:00
} else if let Some(s) = val.downcast_mut() as Option<&mut String> {
2020-03-01 17:11:00 +01:00
if idx >= 0 {
2020-03-01 06:30:22 +01:00
s.chars()
.nth(idx as usize)
2020-03-03 10:28:38 +01:00
.map(|ch| ch.into_dynamic())
.ok_or_else(|| {
EvalAltResult::ErrorStringBounds(s.chars().count(), idx, *pos)
})
2020-03-01 17:11:00 +01:00
} else {
Err(EvalAltResult::ErrorStringBounds(
s.chars().count(),
idx,
*pos,
))
2020-03-01 06:30:22 +01:00
}
} else {
Err(EvalAltResult::ErrorIndexing(*pos))
2020-03-01 06:30:22 +01:00
}
}
2020-03-01 17:11:00 +01:00
Expr::Dot(inner_lhs, inner_rhs) => match **inner_lhs {
Expr::Identifier(ref id, pos) => {
2017-12-20 12:16:14 +01:00
let get_fn_name = "get$".to_string() + id;
2020-03-01 06:30:22 +01:00
let value = self
.call_fn_raw(get_fn_name, vec![this_ptr], None, pos)
2020-03-01 06:30:22 +01:00
.and_then(|mut v| self.get_dot_val_helper(scope, v.as_mut(), inner_rhs))?;
// TODO - Should propagate changes back in this scenario:
//
// fn update(p) { p = something_else; }
// obj.prop.update();
//
// Right now, a copy of the object's property value is mutated, but not propagated
// back to the property via $set.
Ok(value)
}
Expr::Index(_, _, pos) => {
2020-03-01 06:30:22 +01:00
// TODO - Handle Expr::Index for these scenarios:
//
// let x = obj.prop[2].x;
// obj.prop[3] = 42;
//
Err(EvalAltResult::ErrorDotExpr(pos))
}
_ => Err(EvalAltResult::ErrorDotExpr(inner_lhs.position())),
2017-12-20 12:16:14 +01:00
},
_ => Err(EvalAltResult::ErrorDotExpr(dot_rhs.position())),
}
}
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-03 08:20:20 +01:00
map: impl FnOnce(&Variant) -> 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-03 08:20:20 +01:00
.and_then(move |(idx, _, val)| map(val.as_ref()).map(|v| (idx, v)))
2017-12-20 17:37:12 +01:00
}
2020-03-01 06:30:22 +01:00
fn indexed_value(
2017-12-20 21:09:53 +01:00
&self,
scope: &mut Scope,
id: &str,
idx: &Expr,
begin: Position,
2020-03-01 06:30:22 +01:00
) -> Result<(bool, usize, usize, Dynamic), EvalAltResult> {
let idx = *self
2019-09-18 12:21:07 +02:00
.eval_expr(scope, idx)?
2017-12-20 17:37:12 +01:00
.downcast::<i64>()
.map_err(|_| EvalAltResult::ErrorIndexExpr(idx.position()))?;
2020-03-01 06:30:22 +01:00
let mut is_array = false;
Self::search_scope(
scope,
id,
|val| {
2020-03-03 09:24:03 +01:00
if let Some(arr) = val.downcast_ref() as Option<&Array> {
is_array = true;
2020-03-01 06:30:22 +01:00
if idx >= 0 {
arr.get(idx as usize)
.cloned()
.ok_or_else(|| EvalAltResult::ErrorArrayBounds(arr.len(), idx, begin))
} else {
Err(EvalAltResult::ErrorArrayBounds(arr.len(), idx, begin))
}
2020-03-03 09:24:03 +01:00
} else if let Some(s) = val.downcast_ref() as Option<&String> {
is_array = false;
if idx >= 0 {
s.chars()
.nth(idx as usize)
2020-03-03 10:28:38 +01:00
.map(|ch| ch.into_dynamic())
.ok_or_else(|| {
EvalAltResult::ErrorStringBounds(s.chars().count(), idx, begin)
})
} else {
Err(EvalAltResult::ErrorStringBounds(
s.chars().count(),
idx,
begin,
))
}
2020-03-01 17:11:00 +01:00
} else {
Err(EvalAltResult::ErrorIndexing(begin))
2020-03-01 17:11:00 +01:00
}
},
begin,
)
2020-03-01 06:30:22 +01:00
.map(|(idx_sc, val)| (is_array, idx_sc, idx as usize, val))
}
fn str_replace_char(s: &mut String, idx: usize, new_ch: char) {
// The new character
let ch = s.chars().nth(idx).unwrap();
// See if changed - if so, update the String
if ch == new_ch {
return;
}
2017-12-20 17:37:12 +01:00
2020-03-01 06:30:22 +01:00
// Collect all the characters after the index
let mut chars: Vec<char> = s.chars().collect();
chars[idx] = new_ch;
s.clear();
2020-03-01 06:30:22 +01:00
chars.iter().for_each(|&ch| s.push(ch));
2017-12-20 17:37:12 +01:00
}
2017-12-20 12:16:14 +01:00
fn get_dot_val(
&self,
scope: &mut Scope,
dot_lhs: &Expr,
dot_rhs: &Expr,
) -> Result<Dynamic, EvalAltResult> {
match dot_lhs {
Expr::Identifier(id, pos) => {
let (sc_idx, mut target) =
Self::search_scope(scope, id, |x| Ok(x.into_dynamic()), *pos)?;
2017-12-20 21:52:26 +01:00
let value = self.get_dot_val_helper(scope, target.as_mut(), dot_rhs);
2017-12-20 17:37:12 +01:00
// In case the expression mutated `target`, we need to reassign it because
// of the above `clone`.
2020-03-03 08:20:20 +01:00
*scope.get_mut(id, sc_idx) = target;
2017-12-20 17:37:12 +01:00
value
}
2020-03-01 17:11:00 +01:00
Expr::Index(id, idx_raw, pos) => {
let (is_array, sc_idx, idx, mut target) =
self.indexed_value(scope, id, idx_raw, *pos)?;
2017-12-20 21:52:26 +01:00
let value = self.get_dot_val_helper(scope, target.as_mut(), dot_rhs);
2017-12-20 17:37:12 +01:00
// In case the expression mutated `target`, we need to reassign it because
// of the above `clone`.
2020-03-01 06:30:22 +01:00
if is_array {
2020-03-03 08:20:20 +01:00
scope.get_mut(id, sc_idx).downcast_mut::<Array>().unwrap()[idx] = target;
2020-03-01 06:30:22 +01:00
} else {
2020-03-01 17:11:00 +01:00
Self::str_replace_char(
2020-03-03 08:20:20 +01:00
scope.get_mut(id, sc_idx).downcast_mut::<String>().unwrap(), // Root is a string
2020-03-01 17:11:00 +01:00
idx,
*target.downcast::<char>().unwrap(), // Target should be a char
);
2020-03-01 06:30:22 +01:00
}
2017-12-20 17:37:12 +01:00
value
}
_ => Err(EvalAltResult::ErrorDotExpr(dot_lhs.position())),
}
}
2017-12-20 12:16:14 +01:00
fn set_dot_val_helper(
&self,
this_ptr: &mut Variant,
2017-12-20 12:16:14 +01:00
dot_rhs: &Expr,
mut source_val: Dynamic,
) -> Result<Dynamic, EvalAltResult> {
match dot_rhs {
Expr::Identifier(id, pos) => {
let set_fn_name = "set$".to_string() + id;
2020-03-01 17:11:00 +01:00
self.call_fn_raw(set_fn_name, vec![this_ptr, source_val.as_mut()], None, *pos)
}
2020-03-01 17:11:00 +01:00
Expr::Dot(inner_lhs, inner_rhs) => match **inner_lhs {
Expr::Identifier(ref id, pos) => {
2017-12-20 12:16:14 +01:00
let get_fn_name = "get$".to_string() + id;
2020-03-01 17:11:00 +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| {
2017-12-20 21:52:26 +01:00
self.set_dot_val_helper(v.as_mut(), inner_rhs, source_val)
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 = "set$".to_string() + id;
self.call_fn_raw(set_fn_name, vec![this_ptr, v.as_mut()], None, pos)
2017-12-20 12:16:14 +01:00
})
}
_ => Err(EvalAltResult::ErrorDotExpr(inner_lhs.position())),
2017-12-20 12:16:14 +01:00
},
_ => Err(EvalAltResult::ErrorDotExpr(dot_rhs.position())),
}
}
2017-12-20 12:16:14 +01:00
fn set_dot_val(
&self,
scope: &mut Scope,
dot_lhs: &Expr,
dot_rhs: &Expr,
source_val: Dynamic,
) -> Result<Dynamic, EvalAltResult> {
match dot_lhs {
Expr::Identifier(id, pos) => {
let (sc_idx, mut target) =
Self::search_scope(scope, id, |x| Ok(x.into_dynamic()), *pos)?;
2017-12-20 21:52:26 +01:00
let value = self.set_dot_val_helper(target.as_mut(), dot_rhs, source_val);
2017-12-20 17:37:12 +01:00
// In case the expression mutated `target`, we need to reassign it because
// of the above `clone`.
2020-03-03 08:20:20 +01:00
*scope.get_mut(id, sc_idx) = target;
2017-12-20 17:37:12 +01:00
value
}
2020-03-01 17:11:00 +01:00
Expr::Index(id, idx_raw, pos) => {
let (is_array, sc_idx, idx, mut target) =
self.indexed_value(scope, id, idx_raw, *pos)?;
2017-12-20 21:52:26 +01:00
let value = self.set_dot_val_helper(target.as_mut(), dot_rhs, source_val);
2017-12-20 17:37:12 +01:00
// In case the expression mutated `target`, we need to reassign it because
// of the above `clone`.
2020-03-01 06:30:22 +01:00
if is_array {
2020-03-03 08:20:20 +01:00
scope.get_mut(id, sc_idx).downcast_mut::<Array>().unwrap()[idx] = target;
2020-03-01 06:30:22 +01:00
} else {
2020-03-01 17:11:00 +01:00
Self::str_replace_char(
2020-03-03 08:20:20 +01:00
scope.get_mut(id, sc_idx).downcast_mut::<String>().unwrap(), // Root is a string
2020-03-01 17:11:00 +01:00
idx,
*target.downcast::<char>().unwrap(), // Target should be a char
);
2020-03-01 06:30:22 +01:00
}
2017-12-20 17:37:12 +01:00
value
}
_ => Err(EvalAltResult::ErrorDotExpr(dot_lhs.position())),
}
}
fn eval_expr(&self, scope: &mut Scope, expr: &Expr) -> Result<Dynamic, EvalAltResult> {
match expr {
2020-03-03 10:28:38 +01:00
Expr::IntegerConstant(i, _) => Ok((*i).into_dynamic()),
Expr::FloatConstant(i, _) => Ok((*i).into_dynamic()),
Expr::StringConstant(s, _) => Ok(s.into_dynamic()),
Expr::CharConstant(c, _) => Ok((*c).into_dynamic()),
2020-03-01 17:11:00 +01:00
Expr::Identifier(id, pos) => scope
2020-03-03 09:24:03 +01:00
.get(id)
.map(|(_, _, val)| val)
.ok_or_else(|| EvalAltResult::ErrorVariableNotFound(id.clone(), *pos)),
2020-03-01 17:11:00 +01:00
Expr::Index(id, idx_raw, pos) => self
.indexed_value(scope, id, idx_raw, *pos)
.map(|(_, _, _, x)| x),
2020-03-01 17:11:00 +01:00
Expr::Assignment(ref id, rhs) => {
let rhs_val = self.eval_expr(scope, rhs)?;
2016-03-26 18:46:28 +01:00
2016-02-29 22:43:45 +01:00
match **id {
2020-03-03 09:24:03 +01:00
Expr::Identifier(ref name, pos) => {
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 {
Err(EvalAltResult::ErrorVariableNotFound(name.clone(), pos))
}
}
Expr::Index(ref id, ref idx_raw, pos) => {
let idx_pos = idx_raw.position();
2020-03-01 17:11:00 +01:00
2020-03-01 06:30:22 +01:00
let idx = *match self.eval_expr(scope, &idx_raw)?.downcast_ref::<i64>() {
Some(x) => x,
_ => return Err(EvalAltResult::ErrorIndexExpr(idx_pos)),
2020-03-01 06:30:22 +01:00
};
let variable = &mut scope
.iter_mut()
.rev()
.filter(|(name, _)| id == name)
.map(|(_, val)| val)
.next();
let val = match variable {
Some(v) => v,
_ => return Err(EvalAltResult::ErrorVariableNotFound(id.clone(), pos)),
2020-03-01 06:30:22 +01:00
};
if let Some(arr) = val.downcast_mut() as Option<&mut Array> {
2020-03-01 17:11:00 +01:00
if idx < 0 {
Err(EvalAltResult::ErrorArrayBounds(arr.len(), idx, idx_pos))
2020-03-01 06:30:22 +01:00
} else if idx as usize >= arr.len() {
Err(EvalAltResult::ErrorArrayBounds(arr.len(), idx, idx_pos))
2020-03-01 06:30:22 +01:00
} else {
arr[idx as usize] = rhs_val;
2020-03-03 10:28:38 +01:00
Ok(().into_dynamic())
2020-03-01 17:11:00 +01:00
}
} else if let Some(s) = val.downcast_mut() as Option<&mut String> {
2020-03-01 06:30:22 +01:00
let s_len = s.chars().count();
2020-03-01 17:11:00 +01:00
if idx < 0 {
Err(EvalAltResult::ErrorStringBounds(s_len, idx, idx_pos))
2020-03-01 06:30:22 +01:00
} else if idx as usize >= s_len {
Err(EvalAltResult::ErrorStringBounds(s_len, idx, idx_pos))
2020-03-01 06:30:22 +01:00
} else {
2020-03-01 17:11:00 +01:00
Self::str_replace_char(
s,
idx as usize,
*rhs_val.downcast::<char>().unwrap(),
);
2020-03-03 10:28:38 +01:00
Ok(().into_dynamic())
2020-03-01 17:11:00 +01:00
}
} else {
Err(EvalAltResult::ErrorIndexExpr(idx_pos))
2020-03-01 06:30:22 +01:00
}
2016-03-26 18:46:28 +01:00
}
2020-03-02 05:08:03 +01:00
2016-03-26 18:46:28 +01:00
Expr::Dot(ref dot_lhs, ref dot_rhs) => {
self.set_dot_val(scope, dot_lhs, dot_rhs, rhs_val)
}
2020-03-02 05:08:03 +01:00
_ => Err(EvalAltResult::ErrorAssignmentToUnknownLHS(id.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
Expr::Array(contents, _) => {
2016-03-26 18:46:28 +01:00
let mut arr = Vec::new();
2020-03-01 06:30:22 +01:00
contents.iter().try_for_each(|item| {
let arg = self.eval_expr(scope, item)?;
2016-03-26 18:46:28 +01:00
arr.push(arg);
2020-03-01 06:30:22 +01:00
Ok(())
})?;
2016-03-26 18:46:28 +01:00
Ok(Box::new(arr))
}
2020-03-01 17:11:00 +01:00
Expr::FunctionCall(fn_name, args, def_value, pos) => self.call_fn_raw(
fn_name.into(),
2017-12-20 12:16:14 +01:00
args.iter()
2020-03-02 05:08:03 +01:00
.map(|expr| self.eval_expr(scope, expr))
.collect::<Result<Array, _>>()?
2017-12-20 12:16:14 +01:00
.iter_mut()
2017-12-20 21:52:26 +01:00
.map(|b| b.as_mut())
2017-12-20 12:16:14 +01:00
.collect(),
def_value.as_ref(),
*pos,
2017-12-20 12:16:14 +01:00
),
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())
})?
2020-03-02 05:08:03 +01:00
&& *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())
})?
2020-03-02 05:08:03 +01:00
|| *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
}
}
pub(crate) fn eval_stmt(
&self,
scope: &mut Scope,
stmt: &Stmt,
) -> Result<Dynamic, EvalAltResult> {
match stmt {
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-01 06:30:22 +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
}
while scope.len() > prev_len {
scope.pop();
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-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)
2020-03-02 10:04:56 +01:00
} else if else_body.is_some() {
self.eval_stmt(scope, else_body.as_ref().unwrap())
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
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
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
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
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(
(val.downcast_ref() as Option<&String>)
.map(|s| s.as_ref())
.unwrap_or("")
.to_string(),
*pos,
))
}
2020-03-01 17:11:00 +01:00
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
}
}
}
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
}
2017-10-30 16:08:44 +01:00
/// Make a new engine
2016-02-29 22:43:45 +01:00
pub fn new() -> Engine {
2020-03-02 16:16:19 +01:00
// User-friendly names for built-in types
let type_names = [
("alloc::string::String", "string"),
(
"alloc::vec::Vec<alloc::boxed::Box<dyn rhai::any::Any>>",
"array",
),
("alloc::boxed::Box<dyn rhai::any::Any>", "dynamic"),
]
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
2017-12-20 12:16:14 +01:00
let mut engine = Engine {
2019-09-30 19:58:01 +02:00
fns: HashMap::new(),
script_fns: HashMap::new(),
type_iterators: HashMap::new(),
2020-03-02 16:16:19 +01:00
type_names,
2020-02-25 03:40:48 +01:00
on_print: Box::new(|x: &str| println!("{}", x)),
on_debug: Box::new(|x: &str| println!("{}", x)),
2017-12-20 12:16:14 +01:00
};
2016-03-01 15:40:48 +01:00
engine.register_builtins();
2016-03-01 15:40:48 +01:00
engine
}
}