rhai/src/engine.rs

1675 lines
60 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};
use crate::parser::{Expr, FnDef, Position, ReturnType, Stmt, AST, INT};
2020-03-04 15:00:01 +01:00
use crate::result::EvalAltResult;
2020-03-25 04:27:18 +01:00
use crate::scope::{EntryRef as ScopeSource, EntryType as ScopeEntryType, Scope};
#[cfg(not(feature = "no_optimize"))]
use crate::optimize::OptimizationLevel;
2020-03-17 19:26:11 +01:00
use crate::stdlib::{
2020-03-10 03:07:44 +01:00
any::{type_name, TypeId},
borrow::Cow,
2020-03-17 19:26:11 +01:00
boxed::Box,
cmp::Ordering,
2020-03-10 03:07:44 +01:00
collections::HashMap,
2020-03-17 19:26:11 +01:00
format,
2020-03-10 03:07:44 +01:00
iter::once,
ops::{Deref, DerefMut},
rc::Rc,
2020-03-17 19:26:11 +01:00
string::{String, ToString},
2020-03-10 03:07:44 +01:00
sync::Arc,
2020-03-17 19:26:11 +01:00
vec,
vec::Vec,
2020-03-10 03:07:44 +01:00
};
2020-03-04 15:00:01 +01:00
/// An dynamic array of `Dynamic` values.
2020-04-03 13:42:01 +02:00
///
/// Not available under the `no_index` feature.
#[cfg(not(feature = "no_index"))]
pub type Array = Vec<Dynamic>;
2020-03-04 15:00:01 +01:00
2020-04-03 13:42:01 +02:00
/// An dynamic hash map of `Dynamic` values with `String` keys.
///
/// Not available under the `no_object` feature.
2020-03-29 17:53:35 +02:00
#[cfg(not(feature = "no_object"))]
pub type Map = HashMap<String, Dynamic>;
2020-03-26 03:56:28 +01:00
pub type FnCallArgs<'a> = [&'a mut Variant];
2016-02-29 22:43:45 +01:00
2020-04-03 11:17:00 +02:00
#[cfg(feature = "sync")]
pub type FnAny = dyn Fn(&mut FnCallArgs, Position) -> Result<Dynamic, EvalAltResult> + Send + Sync;
#[cfg(not(feature = "sync"))]
2020-03-26 03:56:28 +01:00
pub type FnAny = dyn Fn(&mut FnCallArgs, Position) -> Result<Dynamic, EvalAltResult>;
2020-03-08 12:54:02 +01:00
2020-04-03 11:17:00 +02:00
#[cfg(feature = "sync")]
type IteratorFn = dyn Fn(&Dynamic) -> Box<dyn Iterator<Item = Dynamic>> + Send + Sync;
#[cfg(not(feature = "sync"))]
2020-03-08 12:54:02 +01:00
type IteratorFn = dyn Fn(&Dynamic) -> Box<dyn Iterator<Item = Dynamic>>;
2020-04-01 03:51:33 +02:00
pub const MAX_CALL_STACK_DEPTH: usize = 64;
pub const KEYWORD_PRINT: &str = "print";
pub const KEYWORD_DEBUG: &str = "debug";
pub const KEYWORD_DUMP_AST: &str = "dump_ast";
pub const KEYWORD_TYPE_OF: &str = "type_of";
pub const KEYWORD_EVAL: &str = "eval";
pub const FUNC_TO_STRING: &str = "to_string";
pub const FUNC_GETTER: &str = "get$";
pub const FUNC_SETTER: &str = "set$";
2020-03-03 10:28:38 +01:00
2020-03-11 16:43:04 +01:00
#[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)]
#[cfg(not(feature = "no_index"))]
2020-03-06 16:49:52 +01:00
enum IndexSourceType {
2020-03-30 16:19:37 +02:00
Expression,
String,
2020-03-05 13:28:03 +01:00
Array,
2020-03-29 17:53:35 +02:00
#[cfg(not(feature = "no_object"))]
Map,
2020-03-30 16:19:37 +02:00
}
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
enum IndexValue {
Num(usize),
Str(String),
}
impl IndexValue {
fn from_num(idx: INT) -> Self {
Self::Num(idx as usize)
}
fn from_str(name: String) -> Self {
Self::Str(name)
}
fn as_num(self) -> usize {
match self {
Self::Num(n) => n,
_ => panic!("index value is numeric"),
}
}
fn as_str(self) -> String {
match self {
Self::Str(s) => s,
_ => panic!("index value is string"),
}
}
}
#[derive(Debug)]
enum Target<'a> {
Scope(ScopeSource<'a>),
Value(&'a mut Variant),
}
impl<'a> Target<'a> {
fn from(value: &'a mut Variant) -> Self {
Self::Value(value)
}
fn from_src(src: ScopeSource<'a>) -> Self {
Self::Scope(src)
}
fn get_mut(self, scope: &'a mut Scope) -> &'a mut Variant {
match self {
Self::Value(t) => t,
Self::Scope(src) => scope.get_mut(src).as_mut(),
}
}
2020-03-05 13:28:03 +01:00
}
2020-03-12 06:02:13 +01:00
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
2020-03-04 15:00:01 +01:00
pub struct FnSpec<'a> {
pub name: Cow<'a, str>,
2020-03-30 16:19:37 +02:00
pub args: Vec<TypeId>,
}
/// A type that holds a library of script-defined functions.
///
/// Since script-defined functions have `Dynamic` parameters, functions with the same name
/// and number of parameters are considered equivalent.
///
/// Since the key is a combination of the function name (a String) plus the number of parameters,
/// we cannot use a `HashMap` because we don't want to clone the function name string just
/// to search for it.
///
/// So instead this is implemented as a sorted list and binary searched.
#[derive(Debug, Clone)]
pub struct FunctionsLib(
#[cfg(feature = "sync")] Vec<Arc<FnDef>>,
#[cfg(not(feature = "sync"))] Vec<Rc<FnDef>>,
);
impl FnDef {
/// Function to order two FnDef records, for binary search.
pub fn compare(&self, name: &str, params_len: usize) -> Ordering {
// First order by name
match self.name.as_str().cmp(name) {
// Then by number of parameters
Ordering::Equal => self.params.len().cmp(&params_len),
order => order,
}
}
}
impl FunctionsLib {
/// Create a new `FunctionsLib`.
pub fn new() -> Self {
FunctionsLib(Vec::new())
}
/// Create a new `FunctionsLib` from a collection of `FnDef`.
pub fn from_vec(vec: Vec<FnDef>) -> Self {
#[cfg(feature = "sync")]
{
FunctionsLib(vec.into_iter().map(Arc::new).collect())
}
#[cfg(not(feature = "sync"))]
{
FunctionsLib(vec.into_iter().map(Rc::new).collect())
}
}
/// Does a certain function exist in the `FunctionsLib`?
pub fn has_function(&self, name: &str, params: usize) -> bool {
self.0.binary_search_by(|f| f.compare(name, params)).is_ok()
}
/// Get a function definition from the `FunctionsLib`.
pub fn get_function(&self, name: &str, params: usize) -> Option<&FnDef> {
if let Ok(n) = self.0.binary_search_by(|f| f.compare(name, params)) {
Some(&self.0[n])
} else {
None
}
}
/// Merge another `FunctionsLib` into this `FunctionsLib`.
pub fn merge(&self, other: &Self) -> Self {
if self.is_empty() {
other.clone()
} else if other.is_empty() {
self.clone()
} else {
let mut functions = self.clone();
other.iter().cloned().for_each(|fn_def| {
if let Some((n, _)) = functions
.iter()
.enumerate()
.find(|(_, f)| f.name == fn_def.name && f.params.len() == fn_def.params.len())
{
functions[n] = fn_def;
} else {
functions.push(fn_def);
}
});
functions
}
}
}
impl Deref for FunctionsLib {
#[cfg(feature = "sync")]
type Target = Vec<Arc<FnDef>>;
#[cfg(not(feature = "sync"))]
type Target = Vec<Rc<FnDef>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for FunctionsLib {
#[cfg(feature = "sync")]
fn deref_mut(&mut self) -> &mut Vec<Arc<FnDef>> {
&mut self.0
}
#[cfg(not(feature = "sync"))]
fn deref_mut(&mut self) -> &mut Vec<Rc<FnDef>> {
&mut self.0
}
}
2020-03-04 15:00:01 +01:00
/// Rhai main scripting engine.
2017-10-30 16:08:44 +01:00
///
2020-03-19 06:52:10 +01:00
/// ```
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-04-03 13:42:01 +02:00
///
/// Currently, `Engine` is neither `Send` nor `Sync`. Turn on the `sync` feature to make it `Send + Sync`.
2020-03-07 03:15:42 +01:00
pub struct Engine<'e> {
2020-03-27 07:34:01 +01:00
/// A hashmap containing all compiled functions known to the engine.
pub(crate) functions: Option<HashMap<FnSpec<'e>, Box<FnAny>>>,
/// A hashmap containing all script-defined functions.
#[cfg(feature = "sync")]
pub(crate) fn_lib: Option<Arc<FunctionsLib>>,
2020-03-27 07:34:01 +01:00
/// A hashmap containing all script-defined functions.
#[cfg(not(feature = "sync"))]
pub(crate) fn_lib: Option<Rc<FunctionsLib>>,
2020-03-27 07:34:01 +01:00
/// A hashmap containing all iterators known to the engine.
pub(crate) type_iterators: Option<HashMap<TypeId, Box<IteratorFn>>>,
2020-03-27 07:34:01 +01:00
/// A hashmap mapping type names to pretty-print names.
pub(crate) type_names: Option<HashMap<String, String>>,
2020-03-30 16:19:37 +02:00
/// Closure for implementing the `print` command.
2020-04-03 11:17:00 +02:00
#[cfg(feature = "sync")]
pub(crate) on_print: Option<Box<dyn FnMut(&str) + Send + Sync + 'e>>,
/// Closure for implementing the `print` command.
2020-04-03 11:17:00 +02:00
#[cfg(not(feature = "sync"))]
pub(crate) on_print: Option<Box<dyn FnMut(&str) + 'e>>,
2020-04-03 11:17:00 +02:00
2020-03-30 16:19:37 +02:00
/// Closure for implementing the `debug` command.
2020-04-03 11:17:00 +02:00
#[cfg(feature = "sync")]
pub(crate) on_debug: Option<Box<dyn FnMut(&str) + Send + Sync + 'e>>,
/// Closure for implementing the `debug` command.
2020-04-03 11:17:00 +02:00
#[cfg(not(feature = "sync"))]
pub(crate) on_debug: Option<Box<dyn FnMut(&str) + 'e>>,
2020-03-27 07:34:01 +01:00
/// Optimize the AST after compilation.
#[cfg(not(feature = "no_optimize"))]
pub(crate) optimization_level: OptimizationLevel,
/// Maximum levels of call-stack to prevent infinite recursion.
pub(crate) max_call_stack_depth: usize,
2017-12-20 12:16:14 +01:00
}
2020-03-25 04:27:18 +01:00
impl Default for Engine<'_> {
fn default() -> Self {
2020-03-09 14:57:07 +01:00
// User-friendly names for built-in types
let type_names = [
#[cfg(not(feature = "no_index"))]
(type_name::<Array>(), "array"),
2020-03-29 17:53:35 +02:00
#[cfg(not(feature = "no_object"))]
(type_name::<Map>(), "map"),
2020-03-12 06:02:13 +01:00
(type_name::<String>(), "string"),
(type_name::<Dynamic>(), "dynamic"),
2020-03-09 14:57:07 +01:00
]
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
2020-03-09 14:57:07 +01:00
.collect();
// Create the new scripting Engine
let mut engine = Engine {
functions: None,
fn_lib: None,
type_iterators: None,
type_names: Some(type_names),
on_print: Some(Box::new(default_print)), // default print/debug implementations
on_debug: Some(Box::new(default_print)),
2020-03-16 05:40:42 +01:00
#[cfg(not(feature = "no_optimize"))]
#[cfg(not(feature = "optimize_full"))]
optimization_level: OptimizationLevel::Simple,
#[cfg(not(feature = "no_optimize"))]
#[cfg(feature = "optimize_full")]
optimization_level: OptimizationLevel::Full,
2020-03-27 07:34:01 +01:00
max_call_stack_depth: MAX_CALL_STACK_DEPTH,
2020-03-09 14:57:07 +01:00
};
engine.register_core_lib();
#[cfg(not(feature = "no_stdlib"))]
engine.register_stdlib(); // Register the standard library when no_stdlib is not set
engine
}
2020-03-25 04:27:18 +01:00
}
2020-03-30 10:10:50 +02:00
/// Make getter function
pub fn make_getter(id: &str) -> String {
format!("{}{}", FUNC_GETTER, id)
}
/// Extract the property name from a getter function name.
fn extract_prop_from_getter(fn_name: &str) -> Option<&str> {
if fn_name.starts_with(FUNC_GETTER) {
Some(&fn_name[FUNC_GETTER.len()..])
} else {
None
}
}
/// Make setter function
pub fn make_setter(id: &str) -> String {
format!("{}{}", FUNC_SETTER, id)
}
/// Extract the property name from a setter function name.
fn extract_prop_from_setter(fn_name: &str) -> Option<&str> {
if fn_name.starts_with(FUNC_SETTER) {
Some(&fn_name[FUNC_SETTER.len()..])
} else {
None
}
}
2020-03-25 04:27:18 +01:00
impl Engine<'_> {
/// Create a new `Engine`
pub fn new() -> Self {
2020-04-03 11:17:00 +02:00
// fn abc<F: Fn() + Send + Sync>(f: F) {
// f();
// }
// abc(|| ());
2020-03-25 04:27:18 +01:00
Default::default()
}
2020-03-09 14:57:07 +01:00
/// Create a new `Engine` with minimal configurations - i.e. without pretty-print type names etc.
pub fn new_raw() -> Self {
let mut engine = Engine {
functions: None,
fn_lib: None,
type_iterators: None,
type_names: None,
on_print: None,
on_debug: None,
#[cfg(not(feature = "no_optimize"))]
#[cfg(not(feature = "optimize_full"))]
optimization_level: OptimizationLevel::Simple,
#[cfg(not(feature = "no_optimize"))]
#[cfg(feature = "optimize_full")]
optimization_level: OptimizationLevel::Full,
max_call_stack_depth: MAX_CALL_STACK_DEPTH,
};
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 and how the `Engine` will optimize an AST after compilation
2020-04-03 13:42:01 +02:00
///
/// Not available under the `no_optimize` feature.
#[cfg(not(feature = "no_optimize"))]
pub fn set_optimization_level(&mut self, optimization_level: OptimizationLevel) {
self.optimization_level = optimization_level
}
2020-03-27 07:34:01 +01:00
/// Set the maximum levels of function calls allowed for a script in order to avoid
/// infinite recursion and stack overflows.
pub fn set_max_call_levels(&mut self, levels: usize) {
self.max_call_stack_depth = levels
}
/// Call a registered function
#[cfg(not(feature = "no_optimize"))]
pub(crate) fn call_ext_fn_raw(
&self,
fn_name: &str,
2020-03-26 03:56:28 +01:00
args: &mut FnCallArgs,
pos: Position,
) -> Result<Option<Dynamic>, EvalAltResult> {
let spec = FnSpec {
name: fn_name.into(),
2020-03-30 16:19:37 +02:00
args: args.iter().map(|a| Any::type_id(&**a)).collect(),
};
// Search built-in's and external functions
if let Some(ref functions) = self.functions {
if let Some(func) = functions.get(&spec) {
// Run external function
Ok(Some(func(args, pos)?))
} else {
Ok(None)
}
} else {
Ok(None)
}
2020-03-09 14:57:07 +01:00
}
2020-04-01 03:51:33 +02:00
/// Universal method for calling functions 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,
scope: Option<&mut Scope>,
2020-03-04 15:00:01 +01:00
fn_name: &str,
2020-03-26 03:56:28 +01:00
args: &mut FnCallArgs,
2020-03-08 12:54:02 +01:00
def_val: Option<&Dynamic>,
pos: Position,
2020-03-27 07:34:01 +01:00
level: usize,
) -> Result<Dynamic, EvalAltResult> {
2020-03-11 16:43:04 +01:00
// First search in script-defined functions (can override built-in)
if let Some(ref fn_lib_arc) = self.fn_lib {
if let Some(fn_def) = fn_lib_arc.clone().get_function(fn_name, args.len()) {
match scope {
// Extern scope passed in which is not empty
Some(scope) if scope.len() > 0 => {
let scope_len = scope.len();
scope.extend(
// Put arguments into scope as variables - variable name is copied
fn_def
.params
.iter()
.zip(args.iter().map(|x| (*x).into_dynamic()))
.map(|(name, value)| (name.clone(), ScopeEntryType::Normal, value)),
);
// Evaluate the function at one higher level of call depth
let result = self.eval_stmt(scope, &fn_def.body, level + 1).or_else(
|err| match err {
// Convert return statement to return value
EvalAltResult::Return(x, _) => Ok(x),
err => Err(err.set_position(pos)),
},
);
scope.rewind(scope_len);
return result;
}
// No new scope - create internal scope
_ => {
let mut scope = Scope::new();
scope.extend(
// Put arguments into scope as variables
fn_def
.params
.iter()
.zip(args.iter().map(|x| (*x).into_dynamic()))
.map(|(name, value)| (name, ScopeEntryType::Normal, value)),
);
// Evaluate the function at one higher level of call depth
return self.eval_stmt(&mut scope, &fn_def.body, level + 1).or_else(
|err| match err {
// Convert return statement to return value
EvalAltResult::Return(x, _) => Ok(x),
err => Err(err.set_position(pos)),
},
);
}
}
}
2020-03-11 16:43:04 +01:00
}
let spec = FnSpec {
2020-03-04 15:00:01 +01:00
name: fn_name.into(),
2020-03-30 16:19:37 +02:00
args: args.iter().map(|a| Any::type_id(&**a)).collect(),
2020-03-04 15:00:01 +01:00
};
2020-03-19 12:53:42 +01:00
// Argument must be a string
2020-03-24 09:57:35 +01:00
fn cast_to_string(r: &Variant, pos: Position) -> Result<&str, EvalAltResult> {
2020-03-19 12:53:42 +01:00
r.downcast_ref::<String>()
.map(String::as_str)
.ok_or_else(|| EvalAltResult::ErrorMismatchOutputType(r.type_name().into(), pos))
}
// Search built-in's and external functions
if let Some(ref functions) = self.functions {
if let Some(func) = functions.get(&spec) {
// Run external function
let result = func(args, pos)?;
// See if the function match print/debug (which requires special processing)
return Ok(match fn_name {
KEYWORD_PRINT if self.on_print.is_some() => {
self.on_print.as_deref_mut().unwrap()(cast_to_string(result.as_ref(), pos)?)
.into_dynamic()
}
KEYWORD_DEBUG if self.on_debug.is_some() => {
self.on_debug.as_deref_mut().unwrap()(cast_to_string(result.as_ref(), pos)?)
.into_dynamic()
}
KEYWORD_PRINT | KEYWORD_DEBUG => ().into_dynamic(),
_ => result,
});
}
2020-03-11 16:43:04 +01:00
}
2020-03-30 10:10:50 +02:00
if let Some(prop) = extract_prop_from_getter(fn_name) {
2020-03-29 17:53:35 +02:00
#[cfg(not(feature = "no_object"))]
{
// Map property access
if let Some(map) = args[0].downcast_ref::<Map>() {
2020-03-30 10:13:12 +02:00
return Ok(map.get(prop).cloned().unwrap_or_else(|| ().into_dynamic()));
2020-03-29 17:53:35 +02:00
}
}
2020-03-08 12:54:02 +01:00
// Getter function not found
2020-03-11 16:43:04 +01:00
return Err(EvalAltResult::ErrorDotExpr(
2020-03-30 10:10:50 +02:00
format!("- property '{}' unknown or write-only", prop),
2020-03-07 13:55:03 +01:00
pos,
2020-03-11 16:43:04 +01:00
));
}
2020-03-30 10:10:50 +02:00
if let Some(prop) = extract_prop_from_setter(fn_name) {
2020-03-29 17:53:35 +02:00
#[cfg(not(feature = "no_object"))]
{
2020-04-01 03:51:33 +02:00
let value = args[1].into_dynamic();
2020-03-29 17:53:35 +02:00
// Map property update
if let Some(map) = args[0].downcast_mut::<Map>() {
2020-04-01 03:51:33 +02:00
map.insert(prop.to_string(), value);
2020-03-29 17:53:35 +02:00
return Ok(().into_dynamic());
}
}
2020-03-08 12:54:02 +01:00
// Setter function not found
2020-03-11 16:43:04 +01:00
return Err(EvalAltResult::ErrorDotExpr(
2020-03-30 10:10:50 +02:00
format!("- property '{}' unknown or read-only", prop),
pos,
2020-03-11 16:43:04 +01:00
));
}
2020-03-11 16:43:04 +01:00
if let Some(val) = def_val {
// Return default value
return Ok(val.clone());
}
2020-03-11 16:43:04 +01:00
// Raise error
2020-03-26 03:56:28 +01:00
let types_list: Vec<_> = args
2020-03-11 16:43:04 +01:00
.iter()
.map(|x| (*x).type_name())
.map(|name| self.map_type_name(name))
2020-03-26 03:56:28 +01:00
.collect();
2020-03-11 16:43:04 +01:00
Err(EvalAltResult::ErrorFunctionNotFound(
format!("{} ({})", fn_name, types_list.join(", ")),
2020-03-11 16:43:04 +01:00
pos,
))
2017-12-20 12:16:14 +01:00
}
/// Chain-evaluate a dot setter.
#[cfg(not(feature = "no_object"))]
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,
2020-03-30 16:19:37 +02:00
target: Target,
2017-12-20 12:16:14 +01:00
dot_rhs: &Expr,
2020-03-27 07:34:01 +01:00
level: usize,
) -> Result<Dynamic, EvalAltResult> {
match dot_rhs {
// xxx.fn_name(arg_expr_list)
Expr::FunctionCall(fn_name, arg_expr_list, def_val, pos) => {
let mut values = arg_expr_list
2019-09-18 12:21:07 +02:00
.iter()
2020-03-27 07:34:01 +01:00
.map(|arg_expr| self.eval_expr(scope, arg_expr, level))
2017-12-20 12:16:14 +01:00
.collect::<Result<Vec<_>, _>>()?;
2020-03-01 17:11:00 +01:00
2020-03-30 16:19:37 +02:00
let this_ptr = target.get_mut(scope);
let mut args: Vec<_> = once(this_ptr)
.chain(values.iter_mut().map(Dynamic::as_mut))
2017-12-20 22:16:53 +01:00
.collect();
2017-12-20 12:16:14 +01:00
let def_val = def_val.as_ref();
self.call_fn_raw(None, fn_name, &mut args, def_val, *pos, 0)
}
2020-03-01 17:11:00 +01:00
// xxx.id
2020-03-13 11:12:41 +01:00
Expr::Property(id, pos) => {
let mut args = [target.get_mut(scope)];
self.call_fn_raw(None, &make_getter(id), &mut args, None, *pos, 0)
}
2020-03-01 17:11:00 +01:00
// xxx.idx_lhs[idx_expr]
#[cfg(not(feature = "no_index"))]
Expr::Index(idx_lhs, idx_expr, op_pos) => {
2020-04-01 03:51:33 +02:00
let value = match idx_lhs.as_ref() {
// xxx.id[idx_expr]
2020-03-13 11:12:41 +01:00
Expr::Property(id, pos) => {
let mut args = [target.get_mut(scope)];
self.call_fn_raw(None, &make_getter(id), &mut args, None, *pos, 0)?
2020-03-05 13:28:03 +01:00
}
// xxx.???[???][idx_expr]
2020-03-29 17:53:35 +02:00
Expr::Index(_, _, _) => {
2020-03-30 16:19:37 +02:00
self.get_dot_val_helper(scope, target, idx_lhs, level)?
2020-03-29 17:53:35 +02:00
}
// Syntax error
_ => {
return Err(EvalAltResult::ErrorDotExpr(
"".to_string(),
dot_rhs.position(),
))
}
2020-03-05 13:28:03 +01:00
};
2020-04-01 03:51:33 +02:00
self.get_indexed_value(scope, &value, idx_expr, *op_pos, level)
.map(|(val, _, _)| val)
}
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-13 11:12:41 +01:00
Expr::Property(id, pos) => {
let mut args = [target.get_mut(scope)];
self.call_fn_raw(None, &make_getter(id), &mut args, None, *pos, 0)
2020-04-01 03:51:33 +02:00
.and_then(|mut val| {
self.get_dot_val_helper(scope, Target::from(val.as_mut()), rhs, level)
})
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, op_pos) => {
2020-03-29 17:53:35 +02:00
let val = match idx_lhs.as_ref() {
// xxx.id[idx_expr].rhs
2020-03-13 11:12:41 +01:00
Expr::Property(id, pos) => {
let mut args = [target.get_mut(scope)];
self.call_fn_raw(None, &make_getter(id), &mut args, None, *pos, 0)?
2020-03-05 13:28:03 +01:00
}
// xxx.???[???][idx_expr].rhs
2020-03-29 17:53:35 +02:00
Expr::Index(_, _, _) => {
2020-03-30 16:19:37 +02:00
self.get_dot_val_helper(scope, target, idx_lhs, level)?
2020-03-29 17:53:35 +02:00
}
// Syntax error
_ => {
return Err(EvalAltResult::ErrorDotExpr(
"".to_string(),
dot_rhs.position(),
))
}
2020-03-05 13:28:03 +01:00
};
2020-03-29 17:53:35 +02:00
self.get_indexed_value(scope, &val, idx_expr, *op_pos, level)
2020-04-01 03:51:33 +02:00
.and_then(|(mut val, _, _)| {
self.get_dot_val_helper(scope, Target::from(val.as_mut()), rhs, level)
})
}
// 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
#[cfg(not(feature = "no_object"))]
fn get_dot_val(
&mut self,
scope: &mut Scope,
dot_lhs: &Expr,
dot_rhs: &Expr,
2020-03-27 07:34:01 +01:00
level: usize,
) -> Result<Dynamic, EvalAltResult> {
match dot_lhs {
// id.???
2020-03-13 11:12:41 +01:00
Expr::Variable(id, pos) => {
2020-03-29 17:53:35 +02:00
let (entry, _) = Self::search_scope(scope, id, *pos)?;
2020-03-25 04:27:18 +01:00
// Avoid referencing scope which is used below as mut
let entry = ScopeSource { name: id, ..entry };
// This is a variable property access (potential function call).
// Use a direct index into `scope` to directly mutate the variable value.
2020-03-30 16:19:37 +02:00
self.get_dot_val_helper(scope, Target::from_src(entry), dot_rhs, level)
}
// idx_lhs[idx_expr].???
#[cfg(not(feature = "no_index"))]
Expr::Index(idx_lhs, idx_expr, op_pos) => {
2020-04-01 03:51:33 +02:00
let (idx_src_type, src, idx, mut val) =
2020-03-27 07:34:01 +01:00
self.eval_index_expr(scope, idx_lhs, idx_expr, *op_pos, level)?;
2020-04-01 03:51:33 +02:00
let value =
self.get_dot_val_helper(scope, Target::from(val.as_mut()), dot_rhs, level);
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(src) = src {
2020-03-25 04:27:18 +01:00
match src.typ {
ScopeEntryType::Constant => {
return Err(EvalAltResult::ErrorAssignmentToConstant(
src.name.to_string(),
idx_lhs.position(),
));
}
2020-03-25 04:27:18 +01:00
ScopeEntryType::Normal => {
Self::update_indexed_var_in_scope(
2020-03-29 17:53:35 +02:00
idx_src_type,
scope,
src,
idx,
2020-04-01 03:51:33 +02:00
(val, dot_rhs.position()),
)?;
}
}
}
2020-04-01 03:51:33 +02:00
value
}
// {expr}.???
expr => {
2020-04-01 03:51:33 +02:00
let mut val = self.eval_expr(scope, expr, level)?;
self.get_dot_val_helper(scope, Target::from(val.as_mut()), dot_rhs, level)
}
}
}
/// Search for a variable within the scope, returning its value and index inside the Scope
2020-03-29 17:53:35 +02:00
fn search_scope<'a>(
scope: &'a Scope,
2017-12-20 17:37:12 +01:00
id: &str,
begin: Position,
2020-03-29 17:53:35 +02:00
) -> Result<(ScopeSource<'a>, Dynamic), 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))
2017-12-20 17:37:12 +01:00
}
2020-03-29 17:53:35 +02:00
/// Get the value at the indexed position of a base type
#[cfg(not(feature = "no_index"))]
2020-03-29 17:53:35 +02:00
fn get_indexed_value(
&mut self,
scope: &mut Scope,
2020-03-29 17:53:35 +02:00
val: &Dynamic,
idx_expr: &Expr,
2020-03-29 17:53:35 +02:00
op_pos: Position,
2020-03-27 07:34:01 +01:00
level: usize,
2020-03-30 16:19:37 +02:00
) -> Result<(Dynamic, IndexSourceType, IndexValue), EvalAltResult> {
2020-03-29 17:53:35 +02:00
let idx_pos = idx_expr.position();
2020-04-01 03:51:33 +02:00
// val_array[idx]
if let Some(arr) = val.downcast_ref::<Array>() {
let idx = self
2020-03-29 17:53:35 +02:00
.eval_expr(scope, idx_expr, level)?
.try_cast::<INT>()
2020-03-29 17:53:35 +02:00
.map_err(|_| EvalAltResult::ErrorNumericIndexExpr(idx_expr.position()))?;
return if idx >= 0 {
2020-03-04 15:00:01 +01:00
arr.get(idx as usize)
.cloned()
2020-03-30 16:19:37 +02:00
.map(|v| (v, IndexSourceType::Array, IndexValue::from_num(idx)))
.ok_or_else(|| EvalAltResult::ErrorArrayBounds(arr.len(), idx, idx_pos))
2020-03-04 15:00:01 +01:00
} else {
Err(EvalAltResult::ErrorArrayBounds(arr.len(), idx, idx_pos))
2020-03-29 17:53:35 +02:00
};
}
#[cfg(not(feature = "no_object"))]
{
2020-04-01 03:51:33 +02:00
// val_map[idx]
if let Some(map) = val.downcast_ref::<Map>() {
let idx = self
2020-03-29 17:53:35 +02:00
.eval_expr(scope, idx_expr, level)?
.try_cast::<String>()
2020-03-29 17:53:35 +02:00
.map_err(|_| EvalAltResult::ErrorStringIndexExpr(idx_expr.position()))?;
return Ok((
map.get(&idx).cloned().unwrap_or_else(|| ().into_dynamic()),
IndexSourceType::Map,
2020-03-30 16:19:37 +02:00
IndexValue::from_str(idx),
2020-03-29 17:53:35 +02:00
));
2020-03-04 15:00:01 +01:00
}
2020-03-29 17:53:35 +02:00
}
2020-04-01 03:51:33 +02:00
// val_string[idx]
if let Some(s) = val.downcast_ref::<String>() {
let idx = self
2020-03-29 17:53:35 +02:00
.eval_expr(scope, idx_expr, level)?
.try_cast::<INT>()
2020-03-29 17:53:35 +02:00
.map_err(|_| EvalAltResult::ErrorNumericIndexExpr(idx_expr.position()))?;
return if idx >= 0 {
2020-03-04 15:00:01 +01:00
s.chars()
.nth(idx as usize)
2020-03-29 17:53:35 +02:00
.map(|ch| {
(
ch.into_dynamic(),
IndexSourceType::String,
2020-03-30 16:19:37 +02:00
IndexValue::from_num(idx),
2020-03-29 17:53:35 +02:00
)
})
.ok_or_else(|| {
EvalAltResult::ErrorStringBounds(s.chars().count(), idx, idx_pos)
})
2020-03-04 15:00:01 +01:00
} else {
Err(EvalAltResult::ErrorStringBounds(
s.chars().count(),
idx,
idx_pos,
2020-03-04 15:00:01 +01:00
))
2020-03-29 17:53:35 +02:00
};
2020-03-04 15:00:01 +01:00
}
2020-03-29 17:53:35 +02:00
// Error - cannot be indexed
2020-04-01 03:51:33 +02:00
Err(EvalAltResult::ErrorIndexingType(
2020-03-29 17:53:35 +02:00
self.map_type_name(val.type_name()).to_string(),
op_pos,
2020-04-01 03:51:33 +02:00
))
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,
op_pos: Position,
2020-03-27 07:34:01 +01:00
level: usize,
2020-03-29 17:53:35 +02:00
) -> Result<
(
IndexSourceType,
Option<ScopeSource<'a>>,
2020-03-30 16:19:37 +02:00
IndexValue,
2020-03-29 17:53:35 +02:00
Dynamic,
),
EvalAltResult,
> {
2020-03-05 13:28:03 +01:00
match lhs {
2020-03-06 03:50:20 +01:00
// id[idx_expr]
2020-03-29 17:53:35 +02:00
Expr::Variable(id, _) => {
let (
ScopeSource {
typ: src_type,
index: src_idx,
..
},
val,
) = Self::search_scope(scope, &id, lhs.position())?;
let (val, idx_src_type, idx) =
self.get_indexed_value(scope, &val, idx_expr, op_pos, level)?;
Ok((
idx_src_type,
Some(ScopeSource {
name: &id,
2020-03-29 17:53:35 +02:00
typ: src_type,
index: src_idx,
}),
2020-03-29 17:53:35 +02:00
idx,
val,
2020-03-29 17:53:35 +02:00
))
}
2020-03-05 13:28:03 +01:00
2020-03-06 03:50:20 +01:00
// (expr)[idx_expr]
expr => {
2020-03-27 07:34:01 +01:00
let val = self.eval_expr(scope, expr, level)?;
2020-03-29 17:53:35 +02:00
self.get_indexed_value(scope, &val, idx_expr, op_pos, level)
2020-04-01 03:51:33 +02:00
.map(|(val, _, idx)| (IndexSourceType::Expression, None, idx, val))
}
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-29 17:53:35 +02:00
idx_src_type: IndexSourceType,
scope: &mut Scope,
src: ScopeSource,
2020-03-30 16:19:37 +02:00
idx: IndexValue,
new_val: (Dynamic, Position),
) -> Result<Dynamic, EvalAltResult> {
2020-03-29 17:53:35 +02:00
match idx_src_type {
2020-03-06 16:49:52 +01:00
// array_id[idx] = val
IndexSourceType::Array => {
2020-03-25 04:27:18 +01:00
let arr = scope.get_mut_by_type::<Array>(src);
2020-03-30 16:19:37 +02:00
arr[idx.as_num()] = new_val.0;
2020-03-29 17:53:35 +02:00
Ok(().into_dynamic())
}
// map_id[idx] = val
#[cfg(not(feature = "no_object"))]
IndexSourceType::Map => {
let arr = scope.get_mut_by_type::<Map>(src);
2020-03-30 16:19:37 +02:00
arr.insert(idx.as_str(), new_val.0);
2020-03-24 09:57:35 +01:00
Ok(().into_dynamic())
}
2020-03-06 16:49:52 +01:00
// string_id[idx] = val
IndexSourceType::String => {
2020-03-25 04:27:18 +01:00
let s = scope.get_mut_by_type::<String>(src);
let pos = new_val.1;
// Value must be a character
let ch = new_val
.0
.try_cast::<char>()
.map_err(|_| EvalAltResult::ErrorCharMismatch(pos))?;
2020-03-30 16:19:37 +02:00
Self::str_replace_char(s, idx.as_num(), ch);
2020-03-24 09:57:35 +01:00
Ok(().into_dynamic())
}
IndexSourceType::Expression => panic!("expression cannot be indexed for update"),
}
}
/// 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,
2020-03-30 16:19:37 +02:00
idx: IndexValue,
new_val: Dynamic,
pos: Position,
) -> Result<Dynamic, EvalAltResult> {
2020-04-01 03:51:33 +02:00
if let Some(arr) = target.downcast_mut::<Array>() {
2020-03-30 16:19:37 +02:00
arr[idx.as_num()] = new_val;
2020-03-29 17:53:35 +02:00
return Ok(target);
}
#[cfg(not(feature = "no_object"))]
{
2020-04-01 03:51:33 +02:00
if let Some(map) = target.downcast_mut::<Map>() {
2020-03-30 16:19:37 +02:00
map.insert(idx.as_str(), new_val);
2020-03-29 17:53:35 +02:00
return Ok(target);
}
}
2020-04-01 03:51:33 +02:00
if let Some(s) = target.downcast_mut::<String>() {
// Value must be a character
let ch = new_val
.try_cast::<char>()
.map_err(|_| EvalAltResult::ErrorCharMismatch(pos))?;
2020-03-30 16:19:37 +02:00
Self::str_replace_char(s, idx.as_num(), ch);
2020-03-29 17:53:35 +02:00
return Ok(target);
}
2020-03-29 17:53:35 +02:00
// All other variable types should be an error
panic!("array, map or string source type expected for indexing")
}
/// Chain-evaluate a dot setter
#[cfg(not(feature = "no_object"))]
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,
new_val: (&mut Dynamic, Position),
2020-03-27 07:34:01 +01:00
level: usize,
) -> Result<Dynamic, EvalAltResult> {
match dot_rhs {
// xxx.id
2020-03-13 11:12:41 +01:00
Expr::Property(id, pos) => {
2020-03-27 07:34:01 +01:00
let mut args = [this_ptr, new_val.0.as_mut()];
self.call_fn_raw(None, &make_setter(id), &mut args, None, *pos, 0)
}
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, op_pos) => match lhs.as_ref() {
// xxx.id[idx_expr]
2020-03-30 16:19:37 +02:00
Expr::Property(id, pos) => self
.call_fn_raw(None, &make_getter(id), &mut [this_ptr], None, *pos, 0)
2020-04-01 03:51:33 +02:00
.and_then(|val| {
2020-03-30 16:19:37 +02:00
let (_, _, idx) =
2020-04-01 03:51:33 +02:00
self.get_indexed_value(scope, &val, idx_expr, *op_pos, level)?;
2020-04-01 03:51:33 +02:00
Self::update_indexed_value(val, idx, new_val.0.clone(), new_val.1)
2020-03-30 16:19:37 +02:00
})
2020-04-01 03:51:33 +02:00
.and_then(|mut val| {
let mut args = [this_ptr, val.as_mut()];
self.call_fn_raw(None, &make_setter(id), &mut args, None, *pos, 0)
2020-03-30 16:19:37 +02:00
}),
// All others - syntax error for setters chain
_ => Err(EvalAltResult::ErrorDotExpr(
"for assignment".to_string(),
*op_pos,
)),
},
// xxx.lhs.{...}
Expr::Dot(lhs, rhs, _) => match lhs.as_ref() {
// xxx.id.rhs
2020-03-13 11:12:41 +01:00
Expr::Property(id, pos) => {
self.call_fn_raw(None, &make_getter(id), &mut [this_ptr], None, *pos, 0)
2020-04-01 03:51:33 +02:00
.and_then(|mut val| {
self.set_dot_val_helper(scope, val.as_mut(), rhs, new_val, level)
.map(|_| val) // Discard Ok return value
2017-12-20 21:09:53 +01:00
})
2020-04-01 03:51:33 +02:00
.and_then(|mut val| {
let mut args = [this_ptr, val.as_mut()];
self.call_fn_raw(None, &make_setter(id), &mut args, None, *pos, 0)
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, op_pos) => match lhs.as_ref() {
// xxx.id[idx_expr].rhs
2020-03-13 11:12:41 +01:00
Expr::Property(id, pos) => {
self.call_fn_raw(None, &make_getter(id), &mut [this_ptr], None, *pos, 0)
.and_then(|v| {
2020-03-30 16:19:37 +02:00
let (mut value, _, idx) =
2020-03-29 17:53:35 +02:00
self.get_indexed_value(scope, &v, idx_expr, *op_pos, level)?;
let val_pos = new_val.1;
2020-03-30 16:19:37 +02:00
let this_ptr = value.as_mut();
2020-03-27 07:34:01 +01:00
self.set_dot_val_helper(scope, this_ptr, rhs, new_val, level)?;
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-30 16:19:37 +02:00
Self::update_indexed_value(v, idx, value, val_pos)
})
.and_then(|mut v| {
let mut args = [this_ptr, v.as_mut()];
self.call_fn_raw(None, &make_setter(id), &mut args, None, *pos, 0)
})
}
// All others - syntax error for setters chain
_ => Err(EvalAltResult::ErrorDotExpr(
"for assignment".to_string(),
*op_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
#[cfg(not(feature = "no_object"))]
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: (&mut Dynamic, Position),
2020-03-13 11:12:41 +01:00
op_pos: Position,
2020-03-27 07:34:01 +01:00
level: usize,
) -> Result<Dynamic, EvalAltResult> {
match dot_lhs {
// id.???
2020-03-13 11:12:41 +01:00
Expr::Variable(id, pos) => {
2020-03-29 17:53:35 +02:00
let (entry, mut target) = Self::search_scope(scope, id, *pos)?;
2020-03-13 11:12:41 +01:00
2020-03-25 04:27:18 +01:00
match entry.typ {
ScopeEntryType::Constant => Err(EvalAltResult::ErrorAssignmentToConstant(
2020-03-24 09:57:35 +01:00
id.to_string(),
op_pos,
)),
_ => {
2020-03-25 04:27:18 +01:00
// Avoid referencing scope which is used below as mut
let entry = ScopeSource { name: id, ..entry };
2020-03-27 07:34:01 +01:00
let this_ptr = target.as_mut();
2020-04-01 03:51:33 +02:00
let value =
self.set_dot_val_helper(scope, this_ptr, dot_rhs, new_val, level);
2020-03-24 09:57:35 +01:00
// In case the expression mutated `target`, we need to update it back into the scope because it is cloned.
2020-03-25 04:27:18 +01:00
*scope.get_mut(entry) = target;
2020-04-01 03:51:33 +02:00
value
2020-03-24 09:57:35 +01:00
}
}
}
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, op_pos) => {
2020-03-29 17:53:35 +02:00
let (idx_src_type, src, idx, mut target) =
2020-03-27 07:34:01 +01:00
self.eval_index_expr(scope, lhs, idx_expr, *op_pos, level)?;
let val_pos = new_val.1;
2020-03-27 07:34:01 +01:00
let this_ptr = target.as_mut();
2020-04-01 03:51:33 +02:00
let value = self.set_dot_val_helper(scope, this_ptr, dot_rhs, new_val, level);
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(src) = src {
2020-03-25 04:27:18 +01:00
match src.typ {
ScopeEntryType::Constant => {
return Err(EvalAltResult::ErrorAssignmentToConstant(
src.name.to_string(),
lhs.position(),
));
}
2020-03-25 04:27:18 +01:00
ScopeEntryType::Normal => {
Self::update_indexed_var_in_scope(
2020-03-29 17:53:35 +02:00
idx_src_type,
scope,
src,
idx,
(target, val_pos),
)?;
}
}
2020-03-01 06:30:22 +01:00
}
2020-04-01 03:51:33 +02:00
value
}
// Syntax error
_ => Err(EvalAltResult::ErrorDotExpr(
"for assignment".to_string(),
dot_lhs.position(),
)),
}
}
/// Evaluate an expression
2020-03-27 07:34:01 +01:00
fn eval_expr(
&mut self,
scope: &mut Scope,
expr: &Expr,
level: usize,
) -> 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-29 17:53:35 +02:00
Expr::Variable(id, pos) => Self::search_scope(scope, id, *pos).map(|(_, val)| val),
2020-03-13 11:12:41 +01:00
Expr::Property(_, _) => panic!("unexpected property."),
2020-03-07 03:39:00 +01:00
// lhs[idx_expr]
#[cfg(not(feature = "no_index"))]
Expr::Index(lhs, idx_expr, op_pos) => self
2020-03-27 07:34:01 +01:00
.eval_index_expr(scope, lhs, idx_expr, *op_pos, level)
.map(|(_, _, _, x)| x),
2020-03-01 17:11:00 +01:00
2020-03-07 03:39:00 +01:00
// Statement block
2020-03-27 07:34:01 +01:00
Expr::Stmt(stmt, _) => self.eval_stmt(scope, stmt, level),
2020-03-07 03:39:00 +01:00
// lhs = rhs
2020-03-13 11:12:41 +01:00
Expr::Assignment(lhs, rhs, op_pos) => {
2020-03-27 07:34:01 +01:00
let mut rhs_val = self.eval_expr(scope, rhs, level)?;
2016-03-26 18:46:28 +01:00
2020-03-05 13:28:03 +01:00
match lhs.as_ref() {
// name = rhs
2020-03-25 04:27:18 +01:00
Expr::Variable(name, pos) => match scope
.get(name)
.ok_or_else(|| EvalAltResult::ErrorVariableNotFound(name.clone(), *pos))?
.0
{
entry
@
ScopeSource {
typ: ScopeEntryType::Normal,
..
} => {
// Avoid referencing scope which is used below as mut
let entry = ScopeSource { name, ..entry };
*scope.get_mut(entry) = rhs_val.clone();
2020-03-14 04:51:45 +01:00
Ok(rhs_val)
2020-03-03 09:24:03 +01:00
}
2020-03-25 04:27:18 +01:00
ScopeSource {
typ: ScopeEntryType::Constant,
..
} => Err(EvalAltResult::ErrorAssignmentToConstant(
name.to_string(),
*op_pos,
)),
2020-03-13 11:12:41 +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, op_pos) => {
2020-03-29 17:53:35 +02:00
let (idx_src_type, src, idx, _) =
2020-03-27 07:34:01 +01:00
self.eval_index_expr(scope, idx_lhs, idx_expr, *op_pos, level)?;
2020-03-05 13:28:03 +01:00
if let Some(src) = src {
2020-03-25 04:27:18 +01:00
match src.typ {
ScopeEntryType::Constant => {
2020-03-24 09:57:35 +01:00
Err(EvalAltResult::ErrorAssignmentToConstant(
src.name.to_string(),
idx_lhs.position(),
2020-03-24 09:57:35 +01:00
))
}
2020-03-25 04:27:18 +01:00
ScopeEntryType::Normal => Ok(Self::update_indexed_var_in_scope(
2020-03-29 17:53:35 +02:00
idx_src_type,
scope,
src,
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
#[cfg(not(feature = "no_object"))]
Expr::Dot(dot_lhs, dot_rhs, _) => self.set_dot_val(
scope,
dot_lhs,
dot_rhs,
(&mut rhs_val, rhs.position()),
*op_pos,
2020-03-27 07:34:01 +01:00
level,
),
2020-03-02 05:08:03 +01:00
2020-03-13 11:12:41 +01:00
// Error assignment to constant
expr if expr.is_constant() => Err(EvalAltResult::ErrorAssignmentToConstant(
expr.get_constant_str(),
2020-03-13 11:12:41 +01:00
lhs.position(),
)),
// 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
#[cfg(not(feature = "no_object"))]
2020-03-27 07:34:01 +01:00
Expr::Dot(lhs, rhs, _) => self.get_dot_val(scope, lhs, rhs, level),
2020-03-01 17:11:00 +01:00
#[cfg(not(feature = "no_index"))]
Expr::Array(contents, _) => {
2020-03-29 17:53:35 +02:00
let mut arr = Array::new();
2016-03-26 18:46:28 +01:00
2020-03-27 07:34:01 +01:00
contents.into_iter().try_for_each(|item| {
self.eval_expr(scope, item, level).map(|val| arr.push(val))
})?;
2016-03-26 18:46:28 +01:00
Ok(Box::new(arr))
}
2020-03-01 17:11:00 +01:00
2020-03-29 17:53:35 +02:00
#[cfg(not(feature = "no_object"))]
Expr::Map(contents, _) => {
let mut map = Map::new();
contents.into_iter().try_for_each(|item| {
self.eval_expr(scope, &item.1, level).map(|val| {
map.insert(item.0.clone(), val);
})
})?;
Ok(Box::new(map))
}
Expr::FunctionCall(fn_name, args_expr_list, def_val, pos) => {
// Has a system function an override?
fn has_override(engine: &Engine, name: &str) -> bool {
(engine.functions.is_some() && {
engine.functions.as_ref().unwrap().contains_key(&FnSpec {
name: name.into(),
args: vec![TypeId::of::<String>()],
})
}) || (engine.fn_lib.is_some()
&& engine.fn_lib.as_ref().unwrap().has_function(name, 1))
}
2020-03-11 04:39:15 +01:00
match fn_name.as_str() {
// Dump AST
KEYWORD_DUMP_AST => {
2020-03-24 09:57:35 +01:00
let pos = if args_expr_list.is_empty() {
*pos
} else {
args_expr_list[0].position()
};
// Change the argument to a debug dump of the expressions
2020-03-27 07:34:01 +01:00
let mut result = args_expr_list
2020-03-24 09:57:35 +01:00
.iter()
.map(|expr| format!("{:#?}", expr))
2020-03-27 07:34:01 +01:00
.collect::<Vec<_>>()
.join("\n")
.into_dynamic();
// Redirect call to `print`
let mut args = [result.as_mut()];
self.call_fn_raw(None, KEYWORD_PRINT, &mut args, None, pos, level)
}
// type_of
KEYWORD_TYPE_OF
if args_expr_list.len() == 1 && !has_override(self, KEYWORD_TYPE_OF) =>
{
2020-03-27 07:34:01 +01:00
let r = self.eval_expr(scope, &args_expr_list[0], level)?;
Ok(self
.map_type_name((*r).type_name())
.to_string()
.into_dynamic())
}
// eval
KEYWORD_EVAL
if args_expr_list.len() == 1 && !has_override(self, KEYWORD_EVAL) =>
{
let pos = args_expr_list[0].position();
2020-03-27 07:34:01 +01:00
let r = self.eval_expr(scope, &args_expr_list[0], level)?;
// Get the script text by evaluating the expression
let script =
r.downcast_ref::<String>()
.map(String::as_str)
.ok_or_else(|| {
EvalAltResult::ErrorMismatchOutputType(
r.type_name().into(),
pos,
)
})?;
// Compile the script text
#[cfg(not(feature = "no_optimize"))]
let ast = {
let orig_optimization_level = self.optimization_level;
self.set_optimization_level(OptimizationLevel::None);
let ast = self.compile(script);
self.set_optimization_level(orig_optimization_level);
ast.map_err(EvalAltResult::ErrorParsing)?
};
#[cfg(feature = "no_optimize")]
let ast = self.compile(script).map_err(EvalAltResult::ErrorParsing)?;
// If new functions are defined, merge it into the current functions library
let merged = AST(
ast.0,
if let Some(ref fn_lib) = self.fn_lib {
#[cfg(feature = "sync")]
{
Arc::new(fn_lib.as_ref().merge(&ast.1))
}
#[cfg(not(feature = "sync"))]
{
Rc::new(fn_lib.as_ref().merge(&ast.1))
}
} else {
ast.1
},
);
// Evaluate the AST
let result = self
.eval_ast_with_scope_raw(scope, &merged)
.map_err(|err| err.set_position(pos));
// Update the new functions library if there are new functions
self.fn_lib = if !merged.1.is_empty() {
Some(merged.1)
} else {
None
};
Ok(result?)
}
// Normal function call
_ => {
let mut values = args_expr_list
.iter()
2020-03-27 07:34:01 +01:00
.map(|expr| self.eval_expr(scope, expr, level))
2020-03-26 03:56:28 +01:00
.collect::<Result<Vec<_>, _>>()?;
2020-03-26 03:56:28 +01:00
let mut arg_values: Vec<_> =
values.iter_mut().map(Dynamic::as_mut).collect();
let def_val = def_val.as_ref();
self.call_fn_raw(None, fn_name, &mut arg_values, def_val, *pos, level)
}
}
2020-03-04 15:00:01 +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
2020-03-27 07:34:01 +01:00
.eval_expr(scope, &*lhs, level)?
.try_cast::<bool>()
.map_err(|_| {
EvalAltResult::ErrorBooleanArgMismatch("AND".into(), lhs.position())
})?
&& // Short-circuit using &&
self
2020-03-27 07:34:01 +01:00
.eval_expr(scope, &*rhs, level)?
.try_cast::<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
2020-03-27 07:34:01 +01:00
.eval_expr(scope, &*lhs, level)?
.try_cast::<bool>()
.map_err(|_| {
EvalAltResult::ErrorBooleanArgMismatch("OR".into(), lhs.position())
})?
|| // Short-circuit using ||
self
2020-03-27 07:34:01 +01:00
.eval_expr(scope, &*rhs, level)?
.try_cast::<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,
2020-03-27 07:34:01 +01:00
level: usize,
) -> 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-14 04:51:45 +01:00
Stmt::Expr(expr) => {
2020-03-27 07:34:01 +01:00
let result = self.eval_expr(scope, expr, level)?;
2020-03-14 04:51:45 +01:00
2020-03-14 16:41:15 +01:00
Ok(if !matches!(expr.as_ref(), Expr::Assignment(_, _, _)) {
result
} else {
2020-03-14 04:51:45 +01:00
// If it is an assignment, erase the result at the root
2020-03-14 16:41:15 +01:00
().into_dynamic()
2020-03-14 04:51:45 +01:00
})
}
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();
2016-02-29 22:43:45 +01:00
2020-03-27 07:34:01 +01:00
let result = block.iter().try_fold(().into_dynamic(), |_, stmt| {
self.eval_stmt(scope, stmt, level)
});
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
2020-03-16 16:51:32 +01:00
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-22 03:18:16 +01:00
Stmt::IfThenElse(guard, if_body, else_body) => self
2020-03-27 07:34:01 +01:00
.eval_expr(scope, guard, level)?
.try_cast::<bool>()
.map_err(|_| EvalAltResult::ErrorLogicGuard(guard.position()))
2020-03-01 06:30:22 +01:00
.and_then(|guard_val| {
if guard_val {
2020-03-27 07:34:01 +01:00
self.eval_stmt(scope, if_body, level)
} else if let Some(stmt) = else_body {
2020-03-27 07:34:01 +01:00
self.eval_stmt(scope, stmt.as_ref(), level)
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 {
match self.eval_expr(scope, guard, level)?.try_cast::<bool>() {
Ok(guard_val) if guard_val => match self.eval_stmt(scope, body, level) {
2020-04-01 10:22:18 +02:00
Ok(_) | Err(EvalAltResult::ErrorLoopBreak(false, _)) => (),
Err(EvalAltResult::ErrorLoopBreak(true, _)) => return Ok(().into_dynamic()),
Err(x) => return Err(x),
},
Ok(_) => return Ok(().into_dynamic()),
Err(_) => return Err(EvalAltResult::ErrorLogicGuard(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 {
2020-03-27 07:34:01 +01:00
match self.eval_stmt(scope, body, level) {
2020-04-01 10:22:18 +02:00
Ok(_) | Err(EvalAltResult::ErrorLoopBreak(false, _)) => (),
Err(EvalAltResult::ErrorLoopBreak(true, _)) => return Ok(().into_dynamic()),
2017-12-21 12:28:59 +01:00
Err(x) => return Err(x),
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) => {
2020-03-27 07:34:01 +01:00
let arr = self.eval_expr(scope, expr, level)?;
let tid = Any::type_id(&*arr);
2020-03-01 17:11:00 +01:00
if let Some(ref type_iterators) = self.type_iterators {
if let Some(iter_fn) = type_iterators.get(&tid) {
// Add the loop variable - variable name is copied
scope.push(name.clone(), ());
2020-03-25 04:27:18 +01:00
let entry = ScopeSource {
name,
index: scope.len() - 1,
typ: ScopeEntryType::Normal,
};
2020-03-01 17:11:00 +01:00
for a in iter_fn(&arr) {
*scope.get_mut(entry) = a;
2020-03-01 17:11:00 +01:00
match self.eval_stmt(scope, body, level) {
Ok(_) | Err(EvalAltResult::ErrorLoopBreak(false, _)) => (),
Err(EvalAltResult::ErrorLoopBreak(true, _)) => break,
Err(x) => return Err(x),
}
}
2020-03-25 04:27:18 +01:00
scope.rewind(scope.len() - 1);
Ok(().into_dynamic())
} else {
Err(EvalAltResult::ErrorFor(expr.position()))
}
} else {
2020-03-24 09:57:35 +01:00
Err(EvalAltResult::ErrorFor(expr.position()))
}
}
2020-03-01 17:11:00 +01:00
2020-04-01 10:22:18 +02:00
// Continue statement
Stmt::Continue(pos) => Err(EvalAltResult::ErrorLoopBreak(false, *pos)),
2020-03-06 16:49:52 +01:00
// Break statement
2020-04-01 10:22:18 +02:00
Stmt::Break(pos) => Err(EvalAltResult::ErrorLoopBreak(true, *pos)),
2020-03-01 17:11:00 +01:00
2020-03-03 11:15:20 +01:00
// Empty return
2020-03-11 16:43:04 +01:00
Stmt::ReturnWithVal(None, ReturnType::Return, pos) => {
2020-03-03 11:15:20 +01:00
Err(EvalAltResult::Return(().into_dynamic(), *pos))
}
// Return value
2020-03-27 07:34:01 +01:00
Stmt::ReturnWithVal(Some(a), ReturnType::Return, pos) => Err(EvalAltResult::Return(
self.eval_expr(scope, a, level)?,
*pos,
)),
2020-03-03 11:15:20 +01:00
// Empty throw
2020-03-11 16:43:04 +01:00
Stmt::ReturnWithVal(None, ReturnType::Exception, pos) => {
2020-03-03 11:15:20 +01:00
Err(EvalAltResult::ErrorRuntime("".into(), *pos))
}
2020-03-01 17:11:00 +01:00
2020-03-03 11:15:20 +01:00
// Throw value
2020-03-11 16:43:04 +01:00
Stmt::ReturnWithVal(Some(a), ReturnType::Exception, pos) => {
2020-03-27 07:34:01 +01:00
let val = self.eval_expr(scope, a, level)?;
2020-03-03 11:15:20 +01:00
Err(EvalAltResult::ErrorRuntime(
val.try_cast::<String>().unwrap_or_else(|_| "".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
2020-03-11 16:43:04 +01:00
Stmt::Let(name, Some(expr), _) => {
2020-03-27 07:34:01 +01:00
let val = self.eval_expr(scope, expr, level)?;
2020-03-25 04:27:18 +01:00
scope.push_dynamic_value(name.clone(), ScopeEntryType::Normal, val, false);
2020-03-11 16:43:04 +01:00
Ok(().into_dynamic())
}
Stmt::Let(name, None, _) => {
scope.push(name.clone(), ());
2020-03-03 10:28:38 +01:00
Ok(().into_dynamic())
2016-02-29 22:43:45 +01:00
}
2020-03-13 11:12:41 +01:00
// Const statement
Stmt::Const(name, expr, _) if expr.is_constant() => {
2020-03-27 07:34:01 +01:00
let val = self.eval_expr(scope, expr, level)?;
2020-03-25 04:27:18 +01:00
scope.push_dynamic_value(name.clone(), ScopeEntryType::Constant, val, true);
2020-03-13 11:12:41 +01:00
Ok(().into_dynamic())
}
Stmt::Const(_, _, _) => panic!("constant expression not constant!"),
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 {
if self.type_names.is_none() {
name
} else {
self.type_names
.as_ref()
.unwrap()
.get(name)
.map(String::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.fn_lib = None;
}
2016-03-01 15:40:48 +01:00
}
2020-03-04 16:44:32 +01:00
/// Print/debug to stdout
#[cfg(not(feature = "no_std"))]
#[cfg(not(feature = "no_stdlib"))]
2020-03-04 16:44:32 +01:00
fn default_print(s: &str) {
println!("{}", s);
}
/// No-op
#[cfg(any(feature = "no_std", feature = "no_stdlib"))]
2020-03-04 16:44:32 +01:00
fn default_print(_: &str) {}