rhai/src/engine.rs

1938 lines
72 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
2020-04-12 17:00:06 +02:00
use crate::any::{Dynamic, Union};
2020-04-21 17:01:10 +02:00
use crate::calc_fn_hash;
use crate::error::ParseErrorType;
2020-05-21 11:11:01 +02:00
use crate::fn_native::{FnCallArgs, Shared};
2020-05-13 13:21:42 +02:00
use crate::module::Module;
2020-04-10 06:16:39 +02:00
use crate::optimize::OptimizationLevel;
2020-05-13 13:21:42 +02:00
use crate::packages::{CorePackage, Package, PackageLibrary, PackagesCollection, StandardPackage};
2020-05-19 16:25:57 +02:00
use crate::parser::{Expr, FnAccess, FnDef, ReturnType, Stmt, AST};
2020-05-22 07:08:57 +02:00
use crate::r#unsafe::{unsafe_cast_var_name_to_lifetime, unsafe_mut_cast_to_lifetime};
2020-03-04 15:00:01 +01:00
use crate::result::EvalAltResult;
2020-04-27 16:49:09 +02:00
use crate::scope::{EntryType as ScopeEntryType, Scope};
use crate::token::Position;
use crate::utils::StaticVec;
#[cfg(not(feature = "no_module"))]
2020-05-13 13:21:42 +02:00
use crate::module::{resolvers, ModuleRef, ModuleResolver};
2020-05-08 08:50:48 +02:00
#[cfg(feature = "no_module")]
use crate::parser::ModuleRef;
2020-03-17 19:26:11 +01:00
use crate::stdlib::{
2020-04-12 17:00:06 +02:00
any::TypeId,
2020-03-17 19:26:11 +01:00
boxed::Box,
2020-04-24 06:39:24 +02:00
collections::HashMap,
2020-03-17 19:26:11 +01:00
format,
iter::{empty, once},
2020-04-26 12:04:07 +02:00
mem,
2020-05-19 04:08:27 +02:00
num::NonZeroUsize,
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,
2020-03-10 03:07:44 +01:00
};
2020-05-15 15:40:54 +02:00
/// Variable-sized 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-05-15 15:40:54 +02:00
/// Hash map of `Dynamic` values with `String` keys.
2020-04-03 13:42:01 +02:00
///
/// Not available under the `no_object` feature.
#[cfg(not(feature = "no_object"))]
2020-03-29 17:53:35 +02:00
pub type Map = HashMap<String, Dynamic>;
#[cfg(not(feature = "unchecked"))]
2020-04-07 17:13:47 +02:00
#[cfg(debug_assertions)]
2020-05-19 04:08:27 +02:00
pub const MAX_CALL_STACK_DEPTH: usize = 16;
#[cfg(not(feature = "unchecked"))]
#[cfg(debug_assertions)]
pub const MAX_EXPR_DEPTH: usize = 32;
#[cfg(not(feature = "unchecked"))]
#[cfg(debug_assertions)]
pub const MAX_FUNCTION_EXPR_DEPTH: usize = 16;
2020-04-07 17:13:47 +02:00
#[cfg(not(feature = "unchecked"))]
2020-04-07 17:13:47 +02:00
#[cfg(not(debug_assertions))]
pub const MAX_CALL_STACK_DEPTH: usize = 128;
#[cfg(not(feature = "unchecked"))]
#[cfg(not(debug_assertions))]
pub const MAX_EXPR_DEPTH: usize = 128;
#[cfg(not(feature = "unchecked"))]
#[cfg(not(debug_assertions))]
pub const MAX_FUNCTION_EXPR_DEPTH: usize = 32;
2020-04-07 17:13:47 +02:00
#[cfg(feature = "unchecked")]
pub const MAX_CALL_STACK_DEPTH: usize = usize::MAX;
#[cfg(feature = "unchecked")]
pub const MAX_EXPR_DEPTH: usize = usize::MAX;
#[cfg(feature = "unchecked")]
pub const MAX_FUNCTION_EXPR_DEPTH: usize = usize::MAX;
2020-04-01 03:51:33 +02:00
pub const KEYWORD_PRINT: &str = "print";
pub const KEYWORD_DEBUG: &str = "debug";
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-05-05 14:38:48 +02:00
pub const FUNC_INDEXER: &str = "$index$";
2020-03-03 10:28:38 +01:00
2020-04-26 12:04:07 +02:00
/// A type that encapsulates a mutation target for an expression with side effects.
enum Target<'a> {
/// The target is a mutable reference to a `Dynamic` value somewhere.
Ref(&'a mut Dynamic),
/// The target is a temporary `Dynamic` value (i.e. the mutation can cause no side effects).
2020-05-16 05:42:56 +02:00
Value(Dynamic),
2020-04-26 12:04:07 +02:00
/// The target is a character inside a String.
/// This is necessary because directly pointing to a char inside a String is impossible.
2020-05-16 05:42:56 +02:00
StringChar(&'a mut Dynamic, usize, Dynamic),
2020-03-30 16:19:37 +02:00
}
2020-04-26 12:04:07 +02:00
impl Target<'_> {
2020-05-16 05:42:56 +02:00
/// Is the `Target` a reference pointing to other data?
pub fn is_ref(&self) -> bool {
match self {
Target::Ref(_) => true,
Target::Value(_) | Target::StringChar(_, _, _) => false,
}
}
/// Get the value of the `Target` as a `Dynamic`, cloning a referenced value if necessary.
2020-04-30 16:52:36 +02:00
pub fn clone_into_dynamic(self) -> Dynamic {
2020-03-30 16:19:37 +02:00
match self {
2020-05-16 05:42:56 +02:00
Target::Ref(r) => r.clone(), // Referenced value is cloned
Target::Value(v) => v, // Owned value is simply taken
Target::StringChar(_, _, ch) => ch, // Character is taken
}
}
/// Get a mutable reference from the `Target`.
pub fn as_mut(&mut self) -> &mut Dynamic {
match self {
Target::Ref(r) => *r,
Target::Value(ref mut r) => r,
Target::StringChar(_, _, ref mut r) => r,
2020-03-30 16:19:37 +02:00
}
}
2020-04-26 12:04:07 +02:00
/// Update the value of the `Target`.
pub fn set_value(&mut self, new_val: Dynamic, pos: Position) -> Result<(), Box<EvalAltResult>> {
2020-03-30 16:19:37 +02:00
match self {
2020-04-26 12:04:07 +02:00
Target::Ref(r) => **r = new_val,
Target::Value(_) => {
return Err(Box::new(EvalAltResult::ErrorAssignmentToUnknownLHS(pos)))
}
2020-05-16 05:42:56 +02:00
Target::StringChar(Dynamic(Union::Str(s)), index, _) => {
// Replace the character at the specified index position
let new_ch = new_val
.as_char()
.map_err(|_| EvalAltResult::ErrorCharMismatch(pos))?;
let mut chars: StaticVec<char> = s.chars().collect();
2020-05-17 16:19:49 +02:00
let ch = chars[*index];
2020-05-16 05:42:56 +02:00
// See if changed - if so, update the String
if ch != new_ch {
2020-05-17 16:19:49 +02:00
chars[*index] = new_ch;
2020-05-16 05:42:56 +02:00
s.clear();
chars.iter().for_each(|&ch| s.push(ch));
2020-04-26 12:04:07 +02:00
}
2020-05-16 05:42:56 +02:00
}
_ => unreachable!(),
2020-03-30 16:19:37 +02:00
}
2020-04-26 12:04:07 +02:00
Ok(())
2020-03-30 16:19:37 +02:00
}
2020-03-05 13:28:03 +01:00
}
impl<'a> From<&'a mut Dynamic> for Target<'a> {
fn from(value: &'a mut Dynamic) -> Self {
2020-04-26 12:04:07 +02:00
Self::Ref(value)
}
}
impl<T: Into<Dynamic>> From<T> for Target<'_> {
fn from(value: T) -> Self {
2020-05-16 05:42:56 +02:00
Self::Value(value.into())
}
}
2020-04-28 17:05:03 +02:00
/// A type that holds all the current states of the Engine.
///
/// # Safety
///
/// This type uses some unsafe code, mainly for avoiding cloning of local variable names via
/// direct lifetime casting.
#[derive(Debug, Clone, Copy)]
pub struct State<'a> {
/// Global script-defined functions.
pub fn_lib: &'a FunctionsLib,
2020-04-28 17:05:03 +02:00
/// Normally, access to variables are parsed with a relative offset into the scope to avoid a lookup.
/// In some situation, e.g. after running an `eval` statement, subsequent offsets may become mis-aligned.
/// When that happens, this flag is turned on to force a scope lookup by name.
pub always_search: bool,
/// Level of the current scope. The global (root) level is zero, a new block (or function call)
/// is one level higher, and so on.
pub scope_level: usize,
/// Number of operations performed.
pub operations: u64,
2020-05-15 15:40:54 +02:00
/// Number of modules loaded.
pub modules: u64,
2020-04-28 17:05:03 +02:00
}
impl<'a> State<'a> {
2020-04-29 10:11:54 +02:00
/// Create a new `State`.
pub fn new(fn_lib: &'a FunctionsLib) -> Self {
2020-04-28 17:05:03 +02:00
Self {
fn_lib,
2020-05-15 15:40:54 +02:00
always_search: false,
scope_level: 0,
operations: 0,
2020-05-15 15:40:54 +02:00
modules: 0,
2020-04-28 17:05:03 +02:00
}
}
/// Does a certain script-defined function exist in the `State`?
2020-05-09 10:15:50 +02:00
pub fn has_function(&self, hash: u64) -> bool {
2020-05-09 04:00:59 +02:00
self.fn_lib.contains_key(&hash)
}
/// Get a script-defined function definition from the `State`.
2020-05-09 10:15:50 +02:00
pub fn get_function(&self, hash: u64) -> Option<&FnDef> {
2020-05-17 16:19:49 +02:00
self.fn_lib.get(&hash).map(|fn_def| fn_def.as_ref())
}
2020-04-28 17:05:03 +02:00
}
2020-04-21 17:01:10 +02:00
/// A type that holds a library (`HashMap`) of script-defined functions.
///
/// Since script-defined functions have `Dynamic` parameters, functions with the same name
/// and number of parameters are considered equivalent.
///
/// The key of the `HashMap` is a `u64` hash calculated by the function `calc_fn_hash`.
2020-05-05 09:00:10 +02:00
#[derive(Debug, Clone, Default)]
2020-05-21 11:11:01 +02:00
pub struct FunctionsLib(HashMap<u64, Shared<FnDef>>);
impl FunctionsLib {
/// Create a new `FunctionsLib` from a collection of `FnDef`.
pub fn from_iter(vec: impl IntoIterator<Item = FnDef>) -> Self {
2020-04-16 17:58:57 +02:00
FunctionsLib(
vec.into_iter()
2020-05-09 04:00:59 +02:00
.map(|fn_def| {
// Qualifiers (none) + function name + number of arguments.
let hash = calc_fn_hash(empty(), &fn_def.name, fn_def.params.len(), empty());
(hash, fn_def.into())
2020-04-16 17:58:57 +02:00
})
.collect(),
)
}
/// Does a certain function exist in the `FunctionsLib`?
///
/// The `u64` hash is calculated by the function `crate::calc_fn_hash`.
2020-05-11 17:48:50 +02:00
pub fn has_function(&self, hash_fn_def: u64) -> bool {
self.contains_key(&hash_fn_def)
}
/// Get a function definition from the `FunctionsLib`.
///
/// The `u64` hash is calculated by the function `crate::calc_fn_hash`.
2020-05-11 17:48:50 +02:00
pub fn get_function(&self, hash_fn_def: u64) -> Option<&FnDef> {
self.get(&hash_fn_def).map(|fn_def| fn_def.as_ref())
}
/// Get a function definition from the `FunctionsLib`.
pub fn get_function_by_signature(
&self,
name: &str,
params: usize,
public_only: bool,
) -> Option<&FnDef> {
// Qualifiers (none) + function name + number of arguments.
let hash_fn_def = calc_fn_hash(empty(), name, params, empty());
2020-05-11 17:48:50 +02:00
let fn_def = self.get_function(hash_fn_def);
match fn_def.as_ref().map(|f| f.access) {
None => None,
Some(FnAccess::Private) if public_only => None,
Some(FnAccess::Private) | Some(FnAccess::Public) => fn_def,
}
}
/// 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();
functions.extend(other.iter().map(|(hash, fn_def)| (*hash, fn_def.clone())));
functions
}
}
}
2020-05-21 11:11:01 +02:00
impl From<Vec<(u64, Shared<FnDef>)>> for FunctionsLib {
fn from(values: Vec<(u64, Shared<FnDef>)>) -> Self {
FunctionsLib(values.into_iter().collect())
}
}
impl Deref for FunctionsLib {
2020-05-21 11:11:01 +02:00
type Target = HashMap<u64, Shared<FnDef>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for FunctionsLib {
2020-05-21 11:11:01 +02:00
fn deref_mut(&mut self) -> &mut HashMap<u64, Shared<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
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
2017-10-30 16:08:44 +01:00
/// use rhai::Engine;
///
/// let 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-04-16 17:31:48 +02:00
pub struct Engine {
2020-05-13 13:21:42 +02:00
/// A module containing all functions directly loaded into the Engine.
pub(crate) global_module: Module,
/// A collection of all library packages loaded into the Engine.
pub(crate) packages: PackagesCollection,
2020-05-13 13:21:42 +02:00
2020-05-05 17:57:25 +02:00
/// A module resolution service.
#[cfg(not(feature = "no_module"))]
pub(crate) module_resolver: Option<Box<dyn ModuleResolver>>,
2020-05-13 13:21:42 +02:00
2020-03-27 07:34:01 +01:00
/// A hashmap mapping type names to pretty-print names.
2020-04-27 15:28:31 +02:00
pub(crate) type_names: HashMap<String, String>,
2020-03-30 16:19:37 +02:00
/// Closure for implementing the `print` command.
2020-05-21 11:11:01 +02:00
#[cfg(not(feature = "sync"))]
pub(crate) print: Box<dyn Fn(&str) + 'static>,
/// Closure for implementing the `print` command.
#[cfg(feature = "sync")]
pub(crate) print: Box<dyn Fn(&str) + Send + Sync + 'static>,
/// Closure for implementing the `debug` command.
#[cfg(not(feature = "sync"))]
pub(crate) debug: Box<dyn Fn(&str) + 'static>,
2020-03-30 16:19:37 +02:00
/// Closure for implementing the `debug` command.
2020-05-21 11:11:01 +02:00
#[cfg(feature = "sync")]
pub(crate) debug: Box<dyn Fn(&str) + Send + Sync + 'static>,
/// Closure for progress reporting.
#[cfg(not(feature = "sync"))]
pub(crate) progress: Option<Box<dyn Fn(u64) -> bool + 'static>>,
/// Closure for progress reporting.
2020-05-21 11:11:01 +02:00
#[cfg(feature = "sync")]
pub(crate) progress: Option<Box<dyn Fn(u64) -> bool + Send + Sync + 'static>>,
2020-03-27 07:34:01 +01:00
/// Optimize the AST after compilation.
pub(crate) optimization_level: OptimizationLevel,
/// Maximum levels of call-stack to prevent infinite recursion.
2020-04-07 17:13:47 +02:00
///
2020-05-19 04:08:27 +02:00
/// Defaults to 16 for debug builds and 128 for non-debug builds.
2020-03-27 07:34:01 +01:00
pub(crate) max_call_stack_depth: usize,
/// Maximum depth of statements/expressions at global level.
pub(crate) max_expr_depth: usize,
/// Maximum depth of statements/expressions in functions.
pub(crate) max_function_expr_depth: usize,
2020-05-15 15:40:54 +02:00
/// Maximum number of operations allowed to run.
2020-05-19 04:08:27 +02:00
pub(crate) max_operations: u64,
2020-05-15 15:40:54 +02:00
/// Maximum number of modules allowed to load.
2020-05-19 04:08:27 +02:00
pub(crate) max_modules: u64,
2017-12-20 12:16:14 +01:00
}
2020-04-16 17:31:48 +02:00
impl Default for Engine {
2020-03-25 04:27:18 +01:00
fn default() -> Self {
2020-03-09 14:57:07 +01:00
// Create the new scripting Engine
let mut engine = Self {
2020-05-05 09:00:10 +02:00
packages: Default::default(),
2020-05-13 13:21:42 +02:00
global_module: Default::default(),
2020-05-05 17:57:25 +02:00
#[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_std"))]
module_resolver: Some(Box::new(resolvers::FileModuleResolver::new())),
#[cfg(not(feature = "no_module"))]
#[cfg(feature = "no_std")]
module_resolver: None,
2020-05-05 17:57:25 +02:00
2020-05-05 09:00:10 +02:00
type_names: Default::default(),
// default print/debug implementations
2020-04-27 15:28:31 +02:00
print: Box::new(default_print),
debug: Box::new(default_print),
2020-03-16 05:40:42 +01:00
// progress callback
progress: None,
// optimization level
2020-04-10 06:16:39 +02:00
#[cfg(feature = "no_optimize")]
optimization_level: OptimizationLevel::None,
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,
max_expr_depth: MAX_EXPR_DEPTH,
max_function_expr_depth: MAX_FUNCTION_EXPR_DEPTH,
2020-05-19 04:08:27 +02:00
max_operations: u64::MAX,
max_modules: u64::MAX,
2020-03-09 14:57:07 +01:00
};
#[cfg(feature = "no_stdlib")]
engine.load_package(CorePackage::new().get());
2020-03-09 14:57:07 +01:00
#[cfg(not(feature = "no_stdlib"))]
engine.load_package(StandardPackage::new().get());
2020-03-09 14:57:07 +01:00
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> {
2020-04-10 06:16:39 +02:00
#[cfg(not(feature = "no_object"))]
{
if fn_name.starts_with(FUNC_GETTER) {
Some(&fn_name[FUNC_GETTER.len()..])
} else {
None
}
}
#[cfg(feature = "no_object")]
{
2020-03-30 10:10:50 +02:00
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> {
2020-04-10 06:16:39 +02:00
#[cfg(not(feature = "no_object"))]
{
if fn_name.starts_with(FUNC_SETTER) {
Some(&fn_name[FUNC_SETTER.len()..])
} else {
None
}
}
#[cfg(feature = "no_object")]
{
2020-03-30 10:10:50 +02:00
None
}
}
2020-04-19 12:33:02 +02:00
/// Print/debug to stdout
fn default_print(s: &str) {
#[cfg(not(feature = "no_std"))]
println!("{}", s);
}
2020-05-04 17:07:42 +02:00
/// Search for a variable within the scope
2020-05-05 04:39:12 +02:00
fn search_scope<'a>(
2020-04-27 03:36:31 +02:00
scope: &'a mut Scope,
2020-04-27 14:43:55 +02:00
name: &str,
2020-05-09 10:15:50 +02:00
#[cfg(not(feature = "no_module"))] modules: Option<(&Box<ModuleRef>, u64)>,
#[cfg(feature = "no_module")] _: Option<(&ModuleRef, u64)>,
2020-05-04 17:07:42 +02:00
index: Option<NonZeroUsize>,
2020-05-04 11:43:54 +02:00
pos: Position,
2020-04-27 03:36:31 +02:00
) -> Result<(&'a mut Dynamic, ScopeEntryType), Box<EvalAltResult>> {
#[cfg(not(feature = "no_module"))]
{
2020-05-11 17:48:50 +02:00
if let Some((modules, hash_var)) = modules {
let module = if let Some(index) = modules.index() {
scope
.get_mut(scope.len() - index.get())
.0
.downcast_mut::<Module>()
.unwrap()
} else {
2020-05-17 16:19:49 +02:00
let (id, root_pos) = modules.get(0);
2020-05-11 17:48:50 +02:00
scope.find_module(id).ok_or_else(|| {
2020-05-11 17:48:50 +02:00
Box::new(EvalAltResult::ErrorModuleNotFound(id.into(), *root_pos))
})?
};
return Ok((
2020-05-11 17:48:50 +02:00
module.get_qualified_var_mut(name, hash_var, pos)?,
// Module variables are constant
ScopeEntryType::Constant,
));
}
}
2020-05-04 17:07:42 +02:00
let index = if let Some(index) = index {
scope.len() - index.get()
2020-05-04 17:07:42 +02:00
} else {
scope
.get_index(name)
.ok_or_else(|| Box::new(EvalAltResult::ErrorVariableNotFound(name.into(), pos)))?
.0
};
2020-05-05 04:39:12 +02:00
Ok(scope.get_mut(index))
2020-04-19 12:33:02 +02:00
}
2020-04-16 17:31:48 +02:00
impl Engine {
2020-03-25 04:27:18 +01:00
/// Create a new `Engine`
pub fn new() -> Self {
Default::default()
}
2020-03-09 14:57:07 +01:00
/// Create a new `Engine` with _no_ built-in functions.
/// Use the `load_package` method to load packages of functions.
pub fn new_raw() -> Self {
Self {
2020-05-05 09:00:10 +02:00
packages: Default::default(),
2020-05-13 13:21:42 +02:00
global_module: Default::default(),
#[cfg(not(feature = "no_module"))]
module_resolver: None,
2020-05-05 09:00:10 +02:00
type_names: Default::default(),
2020-04-27 15:28:31 +02:00
print: Box::new(|_| {}),
debug: Box::new(|_| {}),
progress: None,
2020-04-10 06:16:39 +02:00
#[cfg(feature = "no_optimize")]
optimization_level: OptimizationLevel::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,
max_expr_depth: MAX_EXPR_DEPTH,
max_function_expr_depth: MAX_FUNCTION_EXPR_DEPTH,
2020-05-19 04:08:27 +02:00
max_operations: u64::MAX,
max_modules: u64::MAX,
}
}
2020-04-21 17:01:10 +02:00
/// Load a new package into the `Engine`.
///
/// When searching for functions, packages loaded later are preferred.
/// In other words, loaded packages are searched in reverse order.
pub fn load_package(&mut self, package: PackageLibrary) {
2020-04-21 17:01:10 +02:00
// Push the package to the top - packages are searched in reverse order
self.packages.push(package);
}
/// Load a new package into the `Engine`.
///
/// When searching for functions, packages loaded later are preferred.
/// In other words, loaded packages are searched in reverse order.
pub fn load_packages(&mut self, package: PackageLibrary) {
// Push the package to the top - packages are searched in reverse order
self.packages.push(package);
}
2020-05-05 17:57:25 +02:00
/// 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.
#[cfg(not(feature = "unchecked"))]
2020-03-27 07:34:01 +01:00
pub fn set_max_call_levels(&mut self, levels: usize) {
self.max_call_stack_depth = levels
}
/// Set the maximum number of operations allowed for a script to run to avoid
/// consuming too much resources (0 for unlimited).
#[cfg(not(feature = "unchecked"))]
pub fn set_max_operations(&mut self, operations: u64) {
2020-05-19 04:08:27 +02:00
self.max_operations = if operations == 0 {
u64::MAX
} else {
operations
};
}
2020-05-15 15:40:54 +02:00
/// Set the maximum number of imported modules allowed for a script (0 for unlimited).
#[cfg(not(feature = "unchecked"))]
pub fn set_max_modules(&mut self, modules: u64) {
2020-05-19 04:08:27 +02:00
self.max_modules = if modules == 0 { u64::MAX } else { modules };
2020-05-15 15:40:54 +02:00
}
/// Set the depth limits for expressions/statements.
#[cfg(not(feature = "unchecked"))]
pub fn set_max_expr_depths(&mut self, max_expr_depth: usize, max_function_expr_depth: usize) {
self.max_expr_depth = max_expr_depth;
self.max_function_expr_depth = max_function_expr_depth;
}
2020-05-05 17:57:25 +02:00
/// Set the module resolution service used by the `Engine`.
///
/// Not available under the `no_module` feature.
#[cfg(not(feature = "no_module"))]
pub fn set_module_resolver(&mut self, resolver: Option<impl ModuleResolver + 'static>) {
self.module_resolver = resolver.map(|f| Box::new(f) as Box<dyn ModuleResolver>);
2020-05-05 17:57:25 +02:00
}
/// Universal method for calling functions either registered with the `Engine` or written in Rhai.
2020-05-06 17:52:47 +02:00
///
/// ## WARNING
///
/// Function call arguments may be _consumed_ when the function requires them to be passed by value.
/// All function arguments not in the first position are always passed by value and thus consumed.
/// **DO NOT** reuse the argument values unless for the first `&mut` argument - all others are silently replaced by `()`!
2020-03-04 15:00:01 +01:00
pub(crate) fn call_fn_raw(
&self,
scope: Option<&mut Scope>,
state: &mut State,
2020-03-04 15:00:01 +01:00
fn_name: &str,
2020-05-11 17:48:50 +02:00
hashes: (u64, u64),
2020-03-26 03:56:28 +01:00
args: &mut FnCallArgs,
2020-05-11 17:48:50 +02:00
is_ref: bool,
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, bool), Box<EvalAltResult>> {
self.inc_operations(state, pos)?;
2020-04-07 17:13:47 +02:00
// Check for stack overflow
if level > self.max_call_stack_depth {
return Err(Box::new(EvalAltResult::ErrorStackOverflow(pos)));
2020-04-07 17:13:47 +02:00
}
2020-03-11 16:43:04 +01:00
// First search in script-defined functions (can override built-in)
2020-05-11 17:48:50 +02:00
if hashes.1 > 0 {
if let Some(fn_def) = state.get_function(hashes.1) {
2020-05-15 15:40:54 +02:00
let (result, state2) =
self.call_script_fn(scope, *state, fn_name, fn_def, args, pos, level)?;
*state = state2;
return Ok((result, false));
2020-05-09 10:15:50 +02:00
}
2020-03-19 12:53:42 +01:00
}
// Search built-in's and external functions
if let Some(func) = self
2020-05-13 13:21:42 +02:00
.global_module
.get_fn(hashes.0)
2020-05-13 14:22:05 +02:00
.or_else(|| self.packages.get_fn(hashes.0))
{
// Calling pure function in method-call?
2020-05-22 07:08:57 +02:00
let mut this_copy: Option<Dynamic>;
let mut this_pointer: Option<&mut Dynamic> = None;
if func.is_pure() && is_ref && args.len() > 0 {
// Clone the original value. It'll be consumed because the function
// is pure and doesn't know that the first value is a reference (i.e. `is_ref`)
2020-05-22 07:08:57 +02:00
this_copy = Some(args[0].clone());
// Replace the first reference with a reference to the clone, force-casting the lifetime.
// Keep the original reference. Must remember to restore it before existing this function.
this_pointer = Some(mem::replace(
args.get_mut(0).unwrap(),
unsafe_mut_cast_to_lifetime(this_copy.as_mut().unwrap()),
));
}
2020-04-11 12:09:03 +02:00
// Run external function
2020-05-22 07:08:57 +02:00
let result = func.get_native_fn()(args);
// Restore the original reference
if let Some(this_pointer) = this_pointer {
mem::replace(args.get_mut(0).unwrap(), this_pointer);
}
let result = result.map_err(|err| err.new_position(pos))?;
2020-04-11 12:09:03 +02:00
// See if the function match print/debug (which requires special processing)
2020-04-22 08:55:40 +02:00
return Ok(match fn_name {
KEYWORD_PRINT => (
(self.print)(result.as_str().map_err(|type_name| {
Box::new(EvalAltResult::ErrorMismatchOutputType(
type_name.into(),
pos,
))
})?)
.into(),
false,
),
KEYWORD_DEBUG => (
(self.debug)(result.as_str().map_err(|type_name| {
Box::new(EvalAltResult::ErrorMismatchOutputType(
type_name.into(),
pos,
))
})?)
.into(),
false,
),
_ => (result, func.is_method()),
2020-04-22 08:55:40 +02:00
});
2020-03-11 16:43:04 +01:00
}
2020-05-05 14:38:48 +02:00
// Return default value (if any)
if let Some(val) = def_val {
return Ok((val.clone(), false));
2020-05-05 14:38:48 +02:00
}
2020-04-30 16:52:36 +02:00
// Getter function not found?
2020-03-30 10:10:50 +02:00
if let Some(prop) = extract_prop_from_getter(fn_name) {
return Err(Box::new(EvalAltResult::ErrorDotExpr(
format!("- property '{}' unknown or write-only", prop),
pos,
)));
2020-03-11 16:43:04 +01:00
}
2020-04-30 16:52:36 +02:00
// Setter function not found?
2020-03-30 10:10:50 +02:00
if let Some(prop) = extract_prop_from_setter(fn_name) {
return Err(Box::new(EvalAltResult::ErrorDotExpr(
format!("- property '{}' unknown or read-only", prop),
pos,
)));
2020-03-11 16:43:04 +01:00
}
2020-03-26 03:56:28 +01:00
let types_list: Vec<_> = args
2020-03-11 16:43:04 +01:00
.iter()
.map(|name| self.map_type_name(name.type_name()))
2020-03-26 03:56:28 +01:00
.collect();
2020-03-11 16:43:04 +01:00
2020-05-05 14:38:48 +02:00
// Getter function not found?
if fn_name == FUNC_INDEXER {
return Err(Box::new(EvalAltResult::ErrorFunctionNotFound(
format!("[]({})", types_list.join(", ")),
pos,
)));
}
// Raise error
Err(Box::new(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
}
2020-04-24 06:39:24 +02:00
/// Call a script-defined function.
2020-05-06 17:52:47 +02:00
///
/// ## WARNING
///
/// Function call arguments may be _consumed_ when the function requires them to be passed by value.
/// All function arguments not in the first position are always passed by value and thus consumed.
/// **DO NOT** reuse the argument values unless for the first `&mut` argument - all others are silently replaced by `()`!
pub(crate) fn call_script_fn<'s>(
2020-04-24 06:39:24 +02:00
&self,
2020-05-15 15:40:54 +02:00
scope: Option<&mut Scope>,
mut state: State<'s>,
fn_name: &str,
2020-04-24 06:39:24 +02:00
fn_def: &FnDef,
args: &mut FnCallArgs,
pos: Position,
level: usize,
2020-05-15 15:40:54 +02:00
) -> Result<(Dynamic, State<'s>), Box<EvalAltResult>> {
let orig_scope_level = state.scope_level;
state.scope_level += 1;
2020-04-24 06:39:24 +02:00
match scope {
// Extern scope passed in which is not empty
Some(scope) if scope.len() > 0 => {
let scope_len = scope.len();
// Put arguments into scope as variables
// Actually consume the arguments instead of cloning them
2020-04-24 06:39:24 +02:00
scope.extend(
fn_def
.params
.iter()
.zip(args.iter_mut().map(|v| mem::take(*v)))
.map(|(name, value)| {
let var_name =
unsafe_cast_var_name_to_lifetime(name.as_str(), &mut state);
(var_name, ScopeEntryType::Normal, value)
}),
2020-04-24 06:39:24 +02:00
);
// Evaluate the function at one higher level of call depth
let result = self
2020-05-15 15:40:54 +02:00
.eval_stmt(scope, &mut state, &fn_def.body, level + 1)
2020-04-24 06:39:24 +02:00
.or_else(|err| match *err {
// Convert return statement to return value
EvalAltResult::Return(x, _) => Ok(x),
EvalAltResult::ErrorInFunctionCall(name, err, _) => {
Err(Box::new(EvalAltResult::ErrorInFunctionCall(
format!("{} > {}", fn_name, name),
err,
pos,
)))
}
_ => Err(Box::new(EvalAltResult::ErrorInFunctionCall(
fn_name.to_string(),
err,
pos,
))),
2020-04-24 06:39:24 +02:00
});
// Remove all local variables
2020-04-24 06:39:24 +02:00
scope.rewind(scope_len);
2020-05-15 15:40:54 +02:00
state.scope_level = orig_scope_level;
2020-04-24 06:39:24 +02:00
2020-05-15 15:40:54 +02:00
return result.map(|v| (v, state));
2020-04-24 06:39:24 +02:00
}
// No new scope - create internal scope
_ => {
let mut scope = Scope::new();
2020-04-30 16:52:36 +02:00
// Put arguments into scope as variables
// Actually consume the arguments instead of cloning them
2020-04-24 06:39:24 +02:00
scope.extend(
fn_def
.params
.iter()
.zip(args.iter_mut().map(|v| mem::take(*v)))
2020-04-24 06:39:24 +02:00
.map(|(name, value)| (name, ScopeEntryType::Normal, value)),
);
// Evaluate the function at one higher level of call depth
2020-05-15 15:40:54 +02:00
let result = self
.eval_stmt(&mut scope, &mut state, &fn_def.body, level + 1)
2020-04-24 06:39:24 +02:00
.or_else(|err| match *err {
// Convert return statement to return value
EvalAltResult::Return(x, _) => Ok(x),
EvalAltResult::ErrorInFunctionCall(name, err, _) => {
Err(Box::new(EvalAltResult::ErrorInFunctionCall(
format!("{} > {}", fn_name, name),
err,
pos,
)))
}
_ => Err(Box::new(EvalAltResult::ErrorInFunctionCall(
fn_name.to_string(),
err,
pos,
))),
2020-05-15 15:40:54 +02:00
});
state.scope_level = orig_scope_level;
return result.map(|v| (v, state));
2020-04-24 06:39:24 +02:00
}
}
}
// Has a system function an override?
2020-05-11 17:48:50 +02:00
fn has_override(&self, state: &State, hashes: (u64, u64)) -> bool {
// First check registered functions
2020-05-13 13:21:42 +02:00
self.global_module.contains_fn(hashes.0)
// Then check packages
2020-05-13 14:22:05 +02:00
|| self.packages.contains_fn(hashes.0)
// Then check script-defined functions
2020-05-11 17:48:50 +02:00
|| state.has_function(hashes.1)
}
2020-04-26 12:04:07 +02:00
// Perform an actual function call, taking care of special functions
2020-05-06 17:52:47 +02:00
///
/// ## WARNING
///
/// Function call arguments may be _consumed_ when the function requires them to be passed by value.
/// All function arguments not in the first position are always passed by value and thus consumed.
/// **DO NOT** reuse the argument values unless for the first `&mut` argument - all others are silently replaced by `()`!
fn exec_fn_call(
&self,
state: &mut State,
fn_name: &str,
2020-05-09 10:15:50 +02:00
hash_fn_def: u64,
args: &mut FnCallArgs,
2020-05-11 17:48:50 +02:00
is_ref: bool,
def_val: Option<&Dynamic>,
pos: Position,
level: usize,
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
// Qualifiers (none) + function name + number of arguments + argument `TypeId`'s.
let hash_fn = calc_fn_hash(
empty(),
fn_name,
args.len(),
args.iter().map(|a| a.type_id()),
);
2020-05-11 17:48:50 +02:00
let hashes = (hash_fn, hash_fn_def);
2020-05-09 10:15:50 +02:00
match fn_name {
// type_of
2020-05-11 17:48:50 +02:00
KEYWORD_TYPE_OF if args.len() == 1 && !self.has_override(state, hashes) => Ok((
self.map_type_name(args[0].type_name()).to_string().into(),
false,
)),
2020-04-30 16:52:36 +02:00
// eval - reaching this point it must be a method-style call
2020-05-11 17:48:50 +02:00
KEYWORD_EVAL if args.len() == 1 && !self.has_override(state, hashes) => {
Err(Box::new(EvalAltResult::ErrorRuntime(
"'eval' should not be called in method style. Try eval(...);".into(),
pos,
)))
}
2020-05-09 10:15:50 +02:00
// Normal function call
2020-05-09 10:15:50 +02:00
_ => self.call_fn_raw(
2020-05-11 17:48:50 +02:00
None, state, fn_name, hashes, args, is_ref, def_val, pos, level,
2020-05-09 10:15:50 +02:00
),
}
}
2020-04-24 06:39:24 +02:00
/// Evaluate a text string as a script - used primarily for 'eval'.
fn eval_script_expr(
&self,
scope: &mut Scope,
state: &mut State,
2020-04-24 06:39:24 +02:00
script: &Dynamic,
pos: Position,
) -> Result<Dynamic, Box<EvalAltResult>> {
let script = script
.as_str()
.map_err(|type_name| EvalAltResult::ErrorMismatchOutputType(type_name.into(), pos))?;
// Compile the script text
// No optimizations because we only run it once
let mut ast = self.compile_with_scope_and_optimization_level(
&Scope::new(),
2020-05-13 05:57:07 +02:00
&[script],
2020-04-24 06:39:24 +02:00
OptimizationLevel::None,
)?;
// If new functions are defined within the eval string, it is an error
2020-05-05 09:00:10 +02:00
if ast.fn_lib().len() > 0 {
2020-04-24 06:39:24 +02:00
return Err(Box::new(EvalAltResult::ErrorParsing(
ParseErrorType::WrongFnDefinition.into_err(pos),
)));
}
2020-05-05 09:00:10 +02:00
let statements = mem::take(ast.statements_mut());
let ast = AST::new(statements, state.fn_lib.clone());
2020-04-24 06:39:24 +02:00
// Evaluate the AST
let (result, operations) = self
.eval_ast_with_scope_raw(scope, &ast)
.map_err(|err| err.new_position(pos))?;
state.operations += operations;
self.inc_operations(state, pos)?;
return Ok(result);
2020-04-24 06:39:24 +02:00
}
2020-04-26 12:04:07 +02:00
/// Chain-evaluate a dot/index chain.
fn eval_dot_index_chain_helper(
&self,
state: &mut State,
2020-05-16 05:42:56 +02:00
target: &mut Target,
2020-04-26 12:04:07 +02:00
rhs: &Expr,
2020-04-30 16:52:36 +02:00
idx_values: &mut StaticVec<Dynamic>,
2020-04-26 12:04:07 +02:00
is_index: bool,
op_pos: Position,
2020-03-27 07:34:01 +01:00
level: usize,
2020-04-26 12:04:07 +02:00
mut new_val: Option<Dynamic>,
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
2020-05-16 05:42:56 +02:00
let is_ref = target.is_ref();
2020-04-26 12:04:07 +02:00
// Get a reference to the mutation target Dynamic
2020-05-16 05:42:56 +02:00
let obj = target.as_mut();
2020-03-01 17:11:00 +01:00
2020-04-26 12:04:07 +02:00
// Pop the last index value
let mut idx_val = idx_values.pop();
2020-03-01 17:11:00 +01:00
2020-04-26 12:04:07 +02:00
if is_index {
match rhs {
// xxx[idx].dot_rhs... | xxx[idx][dot_rhs]...
Expr::Dot(x) | Expr::Index(x) => {
2020-05-11 17:48:50 +02:00
let is_idx = matches!(rhs, Expr::Index(_));
let pos = x.0.position();
2020-05-16 05:42:56 +02:00
let this_ptr = &mut self
.get_indexed_mut(state, obj, is_ref, idx_val, pos, op_pos, false)?;
2020-04-26 12:04:07 +02:00
self.eval_dot_index_chain_helper(
2020-05-16 05:42:56 +02:00
state, this_ptr, &x.1, idx_values, is_idx, x.2, level, new_val,
2020-04-26 12:04:07 +02:00
)
}
// xxx[rhs] = new_val
_ if new_val.is_some() => {
2020-05-11 17:48:50 +02:00
let pos = rhs.position();
2020-05-16 05:42:56 +02:00
let this_ptr = &mut self
.get_indexed_mut(state, obj, is_ref, idx_val, pos, op_pos, true)?;
2020-05-11 17:48:50 +02:00
2020-05-16 05:42:56 +02:00
this_ptr.set_value(new_val.unwrap(), rhs.position())?;
2020-04-30 16:52:36 +02:00
Ok((Default::default(), true))
2020-04-26 12:04:07 +02:00
}
// xxx[rhs]
_ => self
2020-05-11 17:48:50 +02:00
.get_indexed_mut(state, obj, is_ref, idx_val, rhs.position(), op_pos, false)
.map(|v| (v.clone_into_dynamic(), false)),
2020-04-26 12:04:07 +02:00
}
} else {
match rhs {
// xxx.fn_name(arg_expr_list)
Expr::FnCall(x) if x.1.is_none() => {
2020-05-11 17:48:50 +02:00
let ((name, pos), _, hash_fn_def, _, def_val) = x.as_ref();
let def_val = def_val.as_ref();
2020-05-09 18:19:13 +02:00
let mut arg_values: StaticVec<_> = once(obj)
.chain(
idx_val
.downcast_mut::<StaticVec<Dynamic>>()
.unwrap()
.iter_mut(),
)
.collect();
let args = arg_values.as_mut();
2020-05-11 17:48:50 +02:00
self.exec_fn_call(state, name, *hash_fn_def, args, is_ref, def_val, *pos, 0)
2020-04-26 12:04:07 +02:00
}
2020-05-04 13:36:58 +02:00
// xxx.module::fn_name(...) - syntax error
Expr::FnCall(_) => unreachable!(),
2020-04-26 15:48:49 +02:00
// {xxx:map}.id = ???
#[cfg(not(feature = "no_object"))]
Expr::Property(x) if obj.is::<Map>() && new_val.is_some() => {
let ((prop, _, _), pos) = x.as_ref();
let index = prop.clone().into();
2020-05-11 17:48:50 +02:00
let mut val =
self.get_indexed_mut(state, obj, is_ref, index, *pos, op_pos, true)?;
2020-05-11 17:48:50 +02:00
val.set_value(new_val.unwrap(), rhs.position())?;
2020-04-30 16:52:36 +02:00
Ok((Default::default(), true))
2020-04-26 15:48:49 +02:00
}
2020-04-26 12:04:07 +02:00
// {xxx:map}.id
#[cfg(not(feature = "no_object"))]
Expr::Property(x) if obj.is::<Map>() => {
let ((prop, _, _), pos) = x.as_ref();
let index = prop.clone().into();
2020-05-11 17:48:50 +02:00
let val =
self.get_indexed_mut(state, obj, is_ref, index, *pos, op_pos, false)?;
2020-05-11 17:48:50 +02:00
Ok((val.clone_into_dynamic(), false))
2020-04-26 12:04:07 +02:00
}
2020-05-11 17:48:50 +02:00
// xxx.id = ???
Expr::Property(x) if new_val.is_some() => {
let ((_, _, setter), pos) = x.as_ref();
2020-04-26 12:04:07 +02:00
let mut args = [obj, new_val.as_mut().unwrap()];
self.exec_fn_call(state, setter, 0, &mut args, is_ref, None, *pos, 0)
.map(|(v, _)| (v, true))
2020-04-26 12:04:07 +02:00
}
// xxx.id
Expr::Property(x) => {
let ((_, getter, _), pos) = x.as_ref();
2020-04-26 12:04:07 +02:00
let mut args = [obj];
self.exec_fn_call(state, getter, 0, &mut args, is_ref, None, *pos, 0)
.map(|(v, _)| (v, false))
2020-03-01 06:30:22 +01:00
}
#[cfg(not(feature = "no_object"))]
// {xxx:map}.idx_lhs[idx_expr] | {xxx:map}.dot_lhs.rhs
Expr::Index(x) | Expr::Dot(x) if obj.is::<Map>() => {
2020-05-11 17:48:50 +02:00
let is_idx = matches!(rhs, Expr::Index(_));
2020-05-16 05:42:56 +02:00
let mut val = if let Expr::Property(p) = &x.0 {
let ((prop, _, _), _) = p.as_ref();
let index = prop.clone().into();
2020-05-11 17:48:50 +02:00
self.get_indexed_mut(state, obj, is_ref, index, x.2, op_pos, false)?
2020-04-26 12:04:07 +02:00
} else {
// Syntax error
2020-04-26 12:04:07 +02:00
return Err(Box::new(EvalAltResult::ErrorDotExpr(
2020-05-11 17:48:50 +02:00
"".into(),
2020-04-26 12:04:07 +02:00
rhs.position(),
)));
2020-03-05 13:28:03 +01:00
};
2020-05-11 17:48:50 +02:00
2020-04-26 12:04:07 +02:00
self.eval_dot_index_chain_helper(
2020-05-16 05:42:56 +02:00
state, &mut val, &x.1, idx_values, is_idx, x.2, level, new_val,
2020-04-26 12:04:07 +02:00
)
}
// xxx.idx_lhs[idx_expr] | xxx.dot_lhs.rhs
Expr::Index(x) | Expr::Dot(x) => {
2020-05-11 17:48:50 +02:00
let is_idx = matches!(rhs, Expr::Index(_));
let args = &mut [obj, &mut Default::default()];
2020-04-26 12:04:07 +02:00
2020-05-11 17:48:50 +02:00
let (mut val, updated) = if let Expr::Property(p) = &x.0 {
let ((_, getter, _), _) = p.as_ref();
self.exec_fn_call(state, getter, 0, &mut args[..1], is_ref, None, x.2, 0)?
2020-04-26 12:04:07 +02:00
} else {
// Syntax error
return Err(Box::new(EvalAltResult::ErrorDotExpr(
2020-05-11 17:48:50 +02:00
"".into(),
2020-04-26 12:04:07 +02:00
rhs.position(),
)));
};
2020-05-11 17:48:50 +02:00
let val = &mut val;
2020-05-16 05:42:56 +02:00
let target = &mut val.into();
2020-04-30 16:52:36 +02:00
let (result, may_be_changed) = self.eval_dot_index_chain_helper(
2020-05-16 05:42:56 +02:00
state, target, &x.1, idx_values, is_idx, x.2, level, new_val,
2020-04-26 12:04:07 +02:00
)?;
2020-03-05 13:28:03 +01:00
2020-04-26 12:04:07 +02:00
// Feed the value back via a setter just in case it has been updated
if updated || may_be_changed {
if let Expr::Property(p) = &x.0 {
let ((_, _, setter), _) = p.as_ref();
2020-05-04 13:36:58 +02:00
// Re-use args because the first &mut parameter will not be consumed
2020-05-11 17:48:50 +02:00
args[1] = val;
self.exec_fn_call(state, setter, 0, args, is_ref, None, x.2, 0)
.or_else(|err| match *err {
// If there is no setter, no need to feed it back because the property is read-only
EvalAltResult::ErrorDotExpr(_, _) => Ok(Default::default()),
err => Err(Box::new(err)),
})?;
2020-04-26 12:04:07 +02:00
}
}
2020-04-30 16:52:36 +02:00
Ok((result, may_be_changed))
}
// Syntax error
_ => Err(Box::new(EvalAltResult::ErrorDotExpr(
2020-05-11 17:48:50 +02:00
"".into(),
2020-04-26 12:04:07 +02:00
rhs.position(),
))),
2020-04-26 12:04:07 +02:00
}
}
}
2020-04-26 15:48:49 +02:00
/// Evaluate a dot/index chain.
2020-04-26 12:04:07 +02:00
fn eval_dot_index_chain(
&self,
scope: &mut Scope,
2020-04-28 17:05:03 +02:00
state: &mut State,
dot_lhs: &Expr,
dot_rhs: &Expr,
2020-04-26 12:04:07 +02:00
is_index: bool,
op_pos: Position,
2020-03-27 07:34:01 +01:00
level: usize,
2020-04-26 12:04:07 +02:00
new_val: Option<Dynamic>,
) -> Result<Dynamic, Box<EvalAltResult>> {
let idx_values = &mut StaticVec::new();
2020-03-25 04:27:18 +01:00
self.eval_indexed_chain(scope, state, dot_rhs, idx_values, 0, level)?;
2020-04-11 10:06:57 +02:00
2020-04-26 12:04:07 +02:00
match dot_lhs {
// id.??? or id[???]
Expr::Variable(x) => {
2020-05-11 17:48:50 +02:00
let ((name, pos), modules, hash_var, index) = x.as_ref();
2020-05-09 18:19:13 +02:00
let index = if state.always_search { None } else { *index };
2020-05-11 17:48:50 +02:00
let mod_and_hash = modules.as_ref().map(|m| (m, *hash_var));
2020-05-09 18:19:13 +02:00
let (target, typ) = search_scope(scope, &name, mod_and_hash, index, *pos)?;
2020-05-17 16:19:49 +02:00
self.inc_operations(state, *pos)?;
2020-04-26 12:04:07 +02:00
// Constants cannot be modified
match typ {
2020-05-05 04:39:12 +02:00
ScopeEntryType::Module => unreachable!(),
2020-04-26 12:04:07 +02:00
ScopeEntryType::Constant if new_val.is_some() => {
return Err(Box::new(EvalAltResult::ErrorAssignmentToConstant(
2020-05-09 18:19:13 +02:00
name.clone(),
*pos,
2020-04-26 12:04:07 +02:00
)));
}
2020-05-04 17:07:42 +02:00
ScopeEntryType::Constant | ScopeEntryType::Normal => (),
}
2020-05-16 05:42:56 +02:00
let this_ptr = &mut target.into();
2020-04-26 12:04:07 +02:00
self.eval_dot_index_chain_helper(
state, this_ptr, dot_rhs, idx_values, is_index, op_pos, level, new_val,
2020-04-26 12:04:07 +02:00
)
.map(|(v, _)| v)
}
2020-04-26 12:04:07 +02:00
// {expr}.??? = ??? or {expr}[???] = ???
expr if new_val.is_some() => {
return Err(Box::new(EvalAltResult::ErrorAssignmentToUnknownLHS(
expr.position(),
)));
}
// {expr}.??? or {expr}[???]
expr => {
let val = self.eval_expr(scope, state, expr, level)?;
2020-05-16 05:42:56 +02:00
let this_ptr = &mut val.into();
2020-04-26 12:04:07 +02:00
self.eval_dot_index_chain_helper(
state, this_ptr, dot_rhs, idx_values, is_index, op_pos, level, new_val,
2020-04-26 12:04:07 +02:00
)
.map(|(v, _)| v)
}
}
}
2020-04-26 15:48:49 +02:00
/// Evaluate a chain of indexes and store the results in a list.
/// The first few results are stored in the array `list` which is of fixed length.
/// Any spill-overs are stored in `more`, which is dynamic.
/// The fixed length array is used to avoid an allocation in the overwhelming cases of just a few levels of indexing.
/// The total number of values is returned.
2020-04-26 12:04:07 +02:00
fn eval_indexed_chain(
&self,
scope: &mut Scope,
2020-04-28 17:05:03 +02:00
state: &mut State,
2020-04-26 12:04:07 +02:00
expr: &Expr,
2020-04-30 16:52:36 +02:00
idx_values: &mut StaticVec<Dynamic>,
2020-04-26 12:04:07 +02:00
size: usize,
2020-03-27 07:34:01 +01:00
level: usize,
) -> Result<(), Box<EvalAltResult>> {
2020-05-17 16:19:49 +02:00
self.inc_operations(state, expr.position())?;
2020-04-26 15:48:49 +02:00
match expr {
Expr::FnCall(x) if x.1.is_none() => {
let arg_values =
x.3.iter()
.map(|arg_expr| self.eval_expr(scope, state, arg_expr, level))
.collect::<Result<StaticVec<Dynamic>, _>>()?;
2020-04-26 12:04:07 +02:00
idx_values.push(Dynamic::from(arg_values));
2020-04-26 12:04:07 +02:00
}
Expr::FnCall(_) => unreachable!(),
Expr::Property(_) => idx_values.push(()), // Store a placeholder - no need to copy the property name
Expr::Index(x) | Expr::Dot(x) => {
2020-04-26 12:04:07 +02:00
// Evaluate in left-to-right order
let lhs_val = match x.0 {
Expr::Property(_) => Default::default(), // Store a placeholder in case of a property
_ => self.eval_expr(scope, state, &x.0, level)?,
2020-04-26 12:04:07 +02:00
};
// Push in reverse order
self.eval_indexed_chain(scope, state, &x.1, idx_values, size, level)?;
2020-04-26 12:04:07 +02:00
idx_values.push(lhs_val);
2020-04-26 12:04:07 +02:00
}
_ => idx_values.push(self.eval_expr(scope, state, expr, level)?),
2020-04-26 15:48:49 +02:00
}
Ok(())
2020-04-26 12:04:07 +02:00
}
/// Get the value at the indexed position of a base type
fn get_indexed_mut<'a>(
&self,
state: &mut State,
2020-04-26 12:04:07 +02:00
val: &'a mut Dynamic,
2020-05-11 17:48:50 +02:00
is_ref: bool,
2020-05-05 14:38:48 +02:00
mut idx: Dynamic,
2020-04-26 12:04:07 +02:00
idx_pos: Position,
op_pos: Position,
create: bool,
) -> Result<Target<'a>, Box<EvalAltResult>> {
self.inc_operations(state, op_pos)?;
2020-04-26 12:04:07 +02:00
match val {
#[cfg(not(feature = "no_index"))]
2020-04-26 12:04:07 +02:00
Dynamic(Union::Array(arr)) => {
// val_array[idx]
2020-04-26 12:04:07 +02:00
let index = idx
.as_int()
2020-04-26 12:04:07 +02:00
.map_err(|_| EvalAltResult::ErrorNumericIndexExpr(idx_pos))?;
2020-04-19 12:33:02 +02:00
let arr_len = arr.len();
if index >= 0 {
2020-04-26 12:04:07 +02:00
arr.get_mut(index as usize)
.map(Target::from)
.ok_or_else(|| {
2020-04-19 12:33:02 +02:00
Box::new(EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos))
})
} else {
Err(Box::new(EvalAltResult::ErrorArrayBounds(
2020-04-19 12:33:02 +02:00
arr_len, index, idx_pos,
)))
}
}
2020-03-29 17:53:35 +02:00
#[cfg(not(feature = "no_object"))]
2020-04-26 12:04:07 +02:00
Dynamic(Union::Map(map)) => {
// val_map[idx]
2020-04-26 12:04:07 +02:00
let index = idx
.take_string()
2020-04-26 12:04:07 +02:00
.map_err(|_| EvalAltResult::ErrorStringIndexExpr(idx_pos))?;
Ok(if create {
2020-04-30 16:52:36 +02:00
map.entry(index).or_insert(Default::default()).into()
2020-04-26 12:04:07 +02:00
} else {
map.get_mut(&index)
.map(Target::from)
.unwrap_or_else(|| Target::from(()))
2020-04-26 12:04:07 +02:00
})
}
2020-04-10 06:16:39 +02:00
#[cfg(not(feature = "no_index"))]
2020-04-26 12:04:07 +02:00
Dynamic(Union::Str(s)) => {
// val_string[idx]
2020-05-11 17:48:50 +02:00
let chars_len = s.chars().count();
2020-04-26 12:04:07 +02:00
let index = idx
.as_int()
2020-04-26 12:04:07 +02:00
.map_err(|_| EvalAltResult::ErrorNumericIndexExpr(idx_pos))?;
if index >= 0 {
2020-05-11 17:48:50 +02:00
let offset = index as usize;
let ch = s.chars().nth(offset).ok_or_else(|| {
Box::new(EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos))
})?;
2020-05-16 05:42:56 +02:00
Ok(Target::StringChar(val, offset, ch.into()))
} else {
Err(Box::new(EvalAltResult::ErrorStringBounds(
2020-05-11 17:48:50 +02:00
chars_len, index, idx_pos,
)))
}
}
2020-03-29 17:53:35 +02:00
2020-05-05 14:38:48 +02:00
_ => {
2020-05-11 17:48:50 +02:00
let type_name = self.map_type_name(val.type_name());
2020-05-05 14:38:48 +02:00
let args = &mut [val, &mut idx];
2020-05-11 17:48:50 +02:00
self.exec_fn_call(state, FUNC_INDEXER, 0, args, is_ref, None, op_pos, 0)
.map(|(v, _)| v.into())
2020-05-05 14:38:48 +02:00
.map_err(|_| {
2020-05-11 17:48:50 +02:00
Box::new(EvalAltResult::ErrorIndexingType(type_name.into(), op_pos))
2020-05-05 14:38:48 +02:00
})
}
2020-03-04 15:00:01 +01:00
}
}
2020-04-06 11:47:34 +02:00
// Evaluate an 'in' expression
fn eval_in_expr(
&self,
2020-04-06 11:47:34 +02:00
scope: &mut Scope,
2020-04-28 17:05:03 +02:00
state: &mut State,
2020-04-06 11:47:34 +02:00
lhs: &Expr,
rhs: &Expr,
level: usize,
) -> Result<Dynamic, Box<EvalAltResult>> {
self.inc_operations(state, rhs.position())?;
2020-05-11 17:48:50 +02:00
let mut lhs_value = self.eval_expr(scope, state, lhs, level)?;
let rhs_value = self.eval_expr(scope, state, rhs, level)?;
2020-04-06 11:47:34 +02:00
2020-04-12 17:00:06 +02:00
match rhs_value {
#[cfg(not(feature = "no_index"))]
2020-05-11 17:48:50 +02:00
Dynamic(Union::Array(mut rhs_value)) => {
2020-05-09 10:21:11 +02:00
let op = "==";
let def_value = false.into();
let hash_fn_def = calc_fn_hash(empty(), op, 2, empty());
2020-04-12 17:00:06 +02:00
2020-05-06 17:52:47 +02:00
// Call the `==` operator to compare each value
2020-05-11 17:48:50 +02:00
for value in rhs_value.iter_mut() {
let args = &mut [&mut lhs_value, value];
2020-04-12 17:00:06 +02:00
let def_value = Some(&def_value);
2020-05-05 04:39:12 +02:00
let pos = rhs.position();
2020-05-09 10:15:50 +02:00
// Qualifiers (none) + function name + argument `TypeId`'s.
let hash_fn =
calc_fn_hash(empty(), op, args.len(), args.iter().map(|a| a.type_id()));
2020-05-11 17:48:50 +02:00
let hashes = (hash_fn, hash_fn_def);
2020-04-30 16:52:36 +02:00
2020-05-11 17:48:50 +02:00
let (r, _) = self
.call_fn_raw(None, state, op, hashes, args, true, def_value, pos, level)?;
if r.as_bool().unwrap_or(false) {
2020-04-30 16:52:36 +02:00
return Ok(true.into());
2020-04-12 17:00:06 +02:00
}
2020-04-06 11:47:34 +02:00
}
2020-04-30 16:52:36 +02:00
Ok(false.into())
2020-04-10 06:16:39 +02:00
}
#[cfg(not(feature = "no_object"))]
2020-04-30 16:52:36 +02:00
Dynamic(Union::Map(rhs_value)) => match lhs_value {
2020-04-12 17:00:06 +02:00
// Only allows String or char
2020-05-17 16:19:49 +02:00
Dynamic(Union::Str(s)) => Ok(rhs_value.contains_key(s.as_str()).into()),
2020-04-30 16:52:36 +02:00
Dynamic(Union::Char(c)) => Ok(rhs_value.contains_key(&c.to_string()).into()),
_ => Err(Box::new(EvalAltResult::ErrorInExpr(lhs.position()))),
},
Dynamic(Union::Str(rhs_value)) => match lhs_value {
2020-04-12 17:00:06 +02:00
// Only allows String or char
2020-05-17 16:19:49 +02:00
Dynamic(Union::Str(s)) => Ok(rhs_value.contains(s.as_str()).into()),
2020-04-30 16:52:36 +02:00
Dynamic(Union::Char(c)) => Ok(rhs_value.contains(c).into()),
_ => Err(Box::new(EvalAltResult::ErrorInExpr(lhs.position()))),
},
_ => Err(Box::new(EvalAltResult::ErrorInExpr(rhs.position()))),
2020-04-06 11:47:34 +02:00
}
}
/// Evaluate an expression
2020-03-27 07:34:01 +01:00
fn eval_expr(
&self,
2020-03-27 07:34:01 +01:00
scope: &mut Scope,
2020-04-28 17:05:03 +02:00
state: &mut State,
2020-03-27 07:34:01 +01:00
expr: &Expr,
level: usize,
) -> Result<Dynamic, Box<EvalAltResult>> {
self.inc_operations(state, expr.position())?;
match expr {
Expr::IntegerConstant(x) => Ok(x.0.into()),
2020-04-12 17:00:06 +02:00
#[cfg(not(feature = "no_float"))]
Expr::FloatConstant(x) => Ok(x.0.into()),
Expr::StringConstant(x) => Ok(x.0.to_string().into()),
Expr::CharConstant(x) => Ok(x.0.into()),
Expr::Variable(x) => {
2020-05-11 17:48:50 +02:00
let ((name, pos), modules, hash_var, index) = x.as_ref();
2020-05-09 18:19:13 +02:00
let index = if state.always_search { None } else { *index };
2020-05-11 17:48:50 +02:00
let mod_and_hash = modules.as_ref().map(|m| (m, *hash_var));
2020-05-09 18:19:13 +02:00
let (val, _) = search_scope(scope, name, mod_and_hash, index, *pos)?;
Ok(val.clone())
2020-05-04 11:43:54 +02:00
}
Expr::Property(_) => unreachable!(),
2020-03-07 03:39:00 +01:00
// Statement block
Expr::Stmt(stmt) => self.eval_stmt(scope, state, &stmt.0, level),
2020-03-07 03:39:00 +01:00
// lhs = rhs
Expr::Assignment(x) => {
let op_pos = x.2;
let rhs_val = self.eval_expr(scope, state, &x.1, level)?;
2016-03-26 18:46:28 +01:00
match &x.0 {
// name = rhs
Expr::Variable(x) => {
2020-05-11 17:48:50 +02:00
let ((name, pos), modules, hash_var, index) = x.as_ref();
2020-05-09 18:19:13 +02:00
let index = if state.always_search { None } else { *index };
2020-05-11 17:48:50 +02:00
let mod_and_hash = modules.as_ref().map(|m| (m, *hash_var));
let (lhs_ptr, typ) = search_scope(scope, name, mod_and_hash, index, *pos)?;
2020-05-17 16:19:49 +02:00
self.inc_operations(state, *pos)?;
match typ {
ScopeEntryType::Constant => Err(Box::new(
2020-05-09 18:19:13 +02:00
EvalAltResult::ErrorAssignmentToConstant(name.clone(), *pos),
2020-05-04 11:43:54 +02:00
)),
ScopeEntryType::Normal => {
2020-05-11 17:48:50 +02:00
*lhs_ptr = rhs_val;
2020-05-04 11:43:54 +02:00
Ok(Default::default())
}
2020-05-05 04:39:12 +02:00
// End variable cannot be a module
ScopeEntryType::Module => unreachable!(),
2020-04-11 10:06:57 +02:00
}
2020-05-04 11:43:54 +02:00
}
// idx_lhs[idx_expr] = rhs
#[cfg(not(feature = "no_index"))]
Expr::Index(x) => {
2020-04-26 12:04:07 +02:00
let new_val = Some(rhs_val);
self.eval_dot_index_chain(
scope, state, &x.0, &x.1, true, x.2, level, new_val,
2020-04-26 12:04:07 +02:00
)
2016-03-26 18:46:28 +01:00
}
// dot_lhs.dot_rhs = rhs
#[cfg(not(feature = "no_object"))]
Expr::Dot(x) => {
2020-04-26 12:04:07 +02:00
let new_val = Some(rhs_val);
self.eval_dot_index_chain(
scope, state, &x.0, &x.1, false, op_pos, level, new_val,
)
}
2020-03-13 11:12:41 +01:00
// Error assignment to constant
expr if expr.is_constant() => {
Err(Box::new(EvalAltResult::ErrorAssignmentToConstant(
expr.get_constant_str(),
expr.position(),
)))
}
// Syntax error
expr => Err(Box::new(EvalAltResult::ErrorAssignmentToUnknownLHS(
expr.position(),
))),
2016-02-29 22:43:45 +01:00
}
}
2020-03-01 17:11:00 +01:00
2020-04-10 06:16:39 +02:00
// lhs[idx_expr]
#[cfg(not(feature = "no_index"))]
Expr::Index(x) => {
self.eval_dot_index_chain(scope, state, &x.0, &x.1, true, x.2, level, None)
}
2020-04-10 06:16:39 +02:00
2020-04-26 12:04:07 +02:00
// lhs.dot_rhs
#[cfg(not(feature = "no_object"))]
Expr::Dot(x) => {
self.eval_dot_index_chain(scope, state, &x.0, &x.1, false, x.2, level, None)
}
2020-03-01 17:11:00 +01:00
#[cfg(not(feature = "no_index"))]
Expr::Array(x) => Ok(Dynamic(Union::Array(Box::new(
x.0.iter()
.map(|item| self.eval_expr(scope, state, item, level))
2020-04-30 16:52:36 +02:00
.collect::<Result<Vec<_>, _>>()?,
)))),
2020-03-01 17:11:00 +01:00
2020-03-29 17:53:35 +02:00
#[cfg(not(feature = "no_object"))]
Expr::Map(x) => Ok(Dynamic(Union::Map(Box::new(
x.0.iter()
2020-05-09 18:19:13 +02:00
.map(|((key, _), expr)| {
self.eval_expr(scope, state, expr, level)
2020-04-30 16:52:36 +02:00
.map(|val| (key.clone(), val))
})
.collect::<Result<HashMap<_, _>, _>>()?,
)))),
2020-03-29 17:53:35 +02:00
// Normal function call
Expr::FnCall(x) if x.1.is_none() => {
2020-05-09 18:19:13 +02:00
let ((name, pos), _, hash_fn_def, args_expr, def_val) = x.as_ref();
2020-05-11 17:48:50 +02:00
let def_val = def_val.as_ref();
2020-05-09 18:19:13 +02:00
let mut arg_values = args_expr
.iter()
.map(|expr| self.eval_expr(scope, state, expr, level))
2020-05-10 10:56:17 +02:00
.collect::<Result<StaticVec<_>, _>>()?;
2020-03-11 04:39:15 +01:00
let mut args: StaticVec<_> = arg_values.iter_mut().collect();
2020-05-17 16:19:49 +02:00
if name == KEYWORD_EVAL && args.len() == 1 && args.get(0).is::<String>() {
let hash_fn = calc_fn_hash(empty(), name, 1, once(TypeId::of::<String>()));
2020-05-11 17:48:50 +02:00
if !self.has_override(state, (hash_fn, *hash_fn_def)) {
// eval - only in function call style
let prev_len = scope.len();
2020-05-17 16:19:49 +02:00
let pos = args_expr.get(0).position();
2020-05-11 17:48:50 +02:00
// Evaluate the text string as a script
let result = self.eval_script_expr(scope, state, args.pop(), pos);
2020-05-11 17:48:50 +02:00
if scope.len() != prev_len {
// IMPORTANT! If the eval defines new variables in the current scope,
// all variable offsets from this point on will be mis-aligned.
state.always_search = true;
}
2020-04-28 17:05:03 +02:00
2020-05-11 17:48:50 +02:00
return result;
2020-04-29 10:11:54 +02:00
}
2020-05-11 17:48:50 +02:00
}
2020-04-28 17:05:03 +02:00
2020-05-11 17:48:50 +02:00
// Normal function call - except for eval (handled above)
let args = args.as_mut();
self.exec_fn_call(state, name, *hash_fn_def, args, false, def_val, *pos, level)
.map(|(v, _)| v)
2020-03-04 15:00:01 +01:00
}
2020-03-01 17:11:00 +01:00
// Module-qualified function call
#[cfg(not(feature = "no_module"))]
Expr::FnCall(x) if x.1.is_some() => {
2020-05-09 18:19:13 +02:00
let ((name, pos), modules, hash_fn_def, args_expr, def_val) = x.as_ref();
let modules = modules.as_ref().unwrap();
2020-05-09 18:19:13 +02:00
let mut arg_values = args_expr
.iter()
.map(|expr| self.eval_expr(scope, state, expr, level))
2020-05-10 10:56:17 +02:00
.collect::<Result<StaticVec<_>, _>>()?;
let mut args: StaticVec<_> = arg_values.iter_mut().collect();
2020-05-17 16:19:49 +02:00
let (id, root_pos) = modules.get(0); // First module
let module = if let Some(index) = modules.index() {
scope
.get_mut(scope.len() - index.get())
.0
.downcast_mut::<Module>()
.unwrap()
} else {
scope.find_module(id).ok_or_else(|| {
Box::new(EvalAltResult::ErrorModuleNotFound(id.into(), *root_pos))
})?
};
// First search in script-defined functions (can override built-in)
let func = match module.get_qualified_fn(name, *hash_fn_def) {
Err(err) if matches!(*err, EvalAltResult::ErrorFunctionNotFound(_, _)) => {
// Then search in Rust functions
self.inc_operations(state, *pos)?;
// Rust functions are indexed in two steps:
// 1) Calculate a hash in a similar manner to script-defined functions,
// i.e. qualifiers + function name + number of arguments.
// 2) Calculate a second hash with no qualifiers, empty function name,
// zero number of arguments, and the actual list of argument `TypeId`'.s
let hash_fn_args =
calc_fn_hash(empty(), "", 0, args.iter().map(|a| a.type_id()));
// 3) The final hash is the XOR of the two hashes.
let hash_fn_native = *hash_fn_def ^ hash_fn_args;
module.get_qualified_fn(name, hash_fn_native)
}
r => r,
};
match func {
Ok(x) if x.is_script() => {
let args = args.as_mut();
let fn_def = x.get_fn_def();
let (result, state2) =
self.call_script_fn(None, *state, name, fn_def, args, *pos, level)?;
*state = state2;
Ok(result)
}
Ok(x) => x.get_native_fn()(args.as_mut()).map_err(|err| err.new_position(*pos)),
Err(err)
if def_val.is_some()
&& matches!(*err, EvalAltResult::ErrorFunctionNotFound(_, _)) =>
{
Ok(def_val.clone().unwrap())
}
Err(err) => Err(err),
}
}
Expr::In(x) => self.eval_in_expr(scope, state, &x.0, &x.1, level),
2020-04-06 11:47:34 +02:00
2020-05-09 18:19:13 +02:00
Expr::And(x) => {
let (lhs, rhs, _) = x.as_ref();
Ok((self
.eval_expr(scope, state, lhs, level)?
2020-04-12 17:00:06 +02:00
.as_bool()
.map_err(|_| {
2020-05-09 18:19:13 +02:00
EvalAltResult::ErrorBooleanArgMismatch("AND".into(), lhs.position())
})?
&& // Short-circuit using &&
self
2020-05-09 18:19:13 +02:00
.eval_expr(scope, state, rhs, level)?
2020-04-12 17:00:06 +02:00
.as_bool()
.map_err(|_| {
2020-05-09 18:19:13 +02:00
EvalAltResult::ErrorBooleanArgMismatch("AND".into(), rhs.position())
})?)
2020-05-09 18:19:13 +02:00
.into())
}
2020-03-02 05:08:03 +01:00
2020-05-09 18:19:13 +02:00
Expr::Or(x) => {
let (lhs, rhs, _) = x.as_ref();
Ok((self
.eval_expr(scope, state, lhs, level)?
2020-04-12 17:00:06 +02:00
.as_bool()
.map_err(|_| {
2020-05-09 18:19:13 +02:00
EvalAltResult::ErrorBooleanArgMismatch("OR".into(), lhs.position())
})?
|| // Short-circuit using ||
self
2020-05-09 18:19:13 +02:00
.eval_expr(scope, state, rhs, level)?
2020-04-12 17:00:06 +02:00
.as_bool()
.map_err(|_| {
2020-05-09 18:19:13 +02:00
EvalAltResult::ErrorBooleanArgMismatch("OR".into(), rhs.position())
})?)
2020-05-09 18:19:13 +02:00
.into())
}
2020-03-02 05:08:03 +01:00
Expr::True(_) => Ok(true.into()),
Expr::False(_) => Ok(false.into()),
Expr::Unit(_) => Ok(().into()),
2020-04-10 06:16:39 +02:00
2020-05-04 11:43:54 +02:00
_ => unreachable!(),
2016-02-29 22:43:45 +01:00
}
}
/// Evaluate a statement
pub(crate) fn eval_stmt<'s>(
&self,
scope: &mut Scope<'s>,
2020-04-28 17:05:03 +02:00
state: &mut State,
stmt: &Stmt,
2020-03-27 07:34:01 +01:00
level: usize,
) -> Result<Dynamic, Box<EvalAltResult>> {
self.inc_operations(state, stmt.position())?;
match stmt {
2020-03-09 14:57:07 +01:00
// No-op
2020-04-30 16:52:36 +02:00
Stmt::Noop(_) => Ok(Default::default()),
2020-03-09 14:57:07 +01:00
2020-03-06 16:49:52 +01:00
// Expression as statement
2020-03-14 04:51:45 +01:00
Stmt::Expr(expr) => {
let result = self.eval_expr(scope, state, expr, level)?;
2020-03-14 04:51:45 +01:00
Ok(match expr.as_ref() {
2020-03-14 04:51:45 +01:00
// If it is an assignment, erase the result at the root
Expr::Assignment(_) => Default::default(),
_ => result,
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
Stmt::Block(x) => {
let prev_len = scope.len();
state.scope_level += 1;
2016-02-29 22:43:45 +01:00
let result = x.0.iter().try_fold(Default::default(), |_, stmt| {
self.eval_stmt(scope, state, stmt, level)
2020-03-27 07:34:01 +01:00
});
2016-02-29 22:43:45 +01:00
2020-03-06 16:49:52 +01:00
scope.rewind(prev_len);
state.scope_level -= 1;
2016-02-29 22:43:45 +01:00
2020-04-28 17:05:03 +02:00
// The impact of an eval statement goes away at the end of a block
// because any new variables introduced will go out of scope
state.always_search = false;
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
Stmt::IfThenElse(x) => {
let (expr, if_block, else_block) = x.as_ref();
self.eval_expr(scope, state, expr, level)?
.as_bool()
.map_err(|_| Box::new(EvalAltResult::ErrorLogicGuard(expr.position())))
.and_then(|guard_val| {
if guard_val {
self.eval_stmt(scope, state, if_block, level)
} else if let Some(stmt) = else_block {
self.eval_stmt(scope, state, stmt, level)
} else {
Ok(Default::default())
}
})
}
2020-03-01 17:11:00 +01:00
2020-03-06 16:49:52 +01:00
// While loop
Stmt::While(x) => loop {
let (expr, body) = x.as_ref();
match self.eval_expr(scope, state, expr, level)?.as_bool() {
Ok(true) => match self.eval_stmt(scope, state, body, level) {
2020-05-17 16:19:49 +02:00
Ok(_) => (),
Err(err) => match *err {
EvalAltResult::ErrorLoopBreak(false, _) => (),
2020-04-30 16:52:36 +02:00
EvalAltResult::ErrorLoopBreak(true, _) => return Ok(Default::default()),
_ => return Err(err),
},
},
2020-04-30 16:52:36 +02:00
Ok(false) => return Ok(Default::default()),
Err(_) => {
return Err(Box::new(EvalAltResult::ErrorLogicGuard(expr.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 {
match self.eval_stmt(scope, state, body, level) {
2020-05-17 16:19:49 +02:00
Ok(_) => (),
Err(err) => match *err {
EvalAltResult::ErrorLoopBreak(false, _) => (),
2020-04-30 16:52:36 +02:00
EvalAltResult::ErrorLoopBreak(true, _) => return Ok(Default::default()),
_ => return Err(err),
},
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(x) => {
let (name, expr, stmt) = x.as_ref();
let iter_type = self.eval_expr(scope, state, expr, level)?;
let tid = iter_type.type_id();
2020-03-01 17:11:00 +01:00
if let Some(func) = self
2020-05-13 13:21:42 +02:00
.global_module
2020-05-13 14:22:05 +02:00
.get_iter(tid)
.or_else(|| self.packages.get_iter(tid))
{
2020-04-24 16:54:56 +02:00
// Add the loop variable
let var_name = unsafe_cast_var_name_to_lifetime(name, &state);
scope.push(var_name, ());
2020-04-27 16:49:09 +02:00
let index = scope.len() - 1;
state.scope_level += 1;
2020-03-01 17:11:00 +01:00
2020-05-19 16:25:57 +02:00
for loop_var in func(iter_type) {
2020-05-11 17:48:50 +02:00
*scope.get_mut(index).0 = loop_var;
self.inc_operations(state, stmt.position())?;
2020-03-01 17:11:00 +01:00
match self.eval_stmt(scope, state, stmt, level) {
Ok(_) => (),
Err(err) => match *err {
EvalAltResult::ErrorLoopBreak(false, _) => (),
EvalAltResult::ErrorLoopBreak(true, _) => break,
_ => return Err(err),
},
}
}
2020-04-11 12:09:03 +02:00
scope.rewind(scope.len() - 1);
state.scope_level -= 1;
2020-04-30 16:52:36 +02:00
Ok(Default::default())
} else {
Err(Box::new(EvalAltResult::ErrorFor(x.1.position())))
}
}
2020-03-01 17:11:00 +01:00
2020-04-01 10:22:18 +02:00
// Continue statement
Stmt::Continue(pos) => Err(Box::new(EvalAltResult::ErrorLoopBreak(false, *pos))),
2020-04-01 10:22:18 +02:00
2020-03-06 16:49:52 +01:00
// Break statement
Stmt::Break(pos) => Err(Box::new(EvalAltResult::ErrorLoopBreak(true, *pos))),
2020-03-01 17:11:00 +01:00
2020-03-03 11:15:20 +01:00
// Return value
2020-05-09 18:19:13 +02:00
Stmt::ReturnWithVal(x) if x.1.is_some() && (x.0).0 == ReturnType::Return => {
Err(Box::new(EvalAltResult::Return(
2020-05-09 18:19:13 +02:00
self.eval_expr(scope, state, x.1.as_ref().unwrap(), level)?,
(x.0).1,
)))
}
2020-03-03 11:15:20 +01:00
// Empty return
2020-05-09 18:19:13 +02:00
Stmt::ReturnWithVal(x) if (x.0).0 == ReturnType::Return => {
Err(Box::new(EvalAltResult::Return(Default::default(), (x.0).1)))
2020-03-03 11:15:20 +01:00
}
2020-03-01 17:11:00 +01:00
2020-03-03 11:15:20 +01:00
// Throw value
2020-05-09 18:19:13 +02:00
Stmt::ReturnWithVal(x) if x.1.is_some() && (x.0).0 == ReturnType::Exception => {
let val = self.eval_expr(scope, state, x.1.as_ref().unwrap(), level)?;
Err(Box::new(EvalAltResult::ErrorRuntime(
2020-05-11 17:48:50 +02:00
val.take_string().unwrap_or_else(|_| "".into()),
2020-05-09 18:19:13 +02:00
(x.0).1,
)))
}
2020-03-01 17:11:00 +01:00
// Empty throw
2020-05-09 18:19:13 +02:00
Stmt::ReturnWithVal(x) if (x.0).0 == ReturnType::Exception => {
Err(Box::new(EvalAltResult::ErrorRuntime("".into(), (x.0).1)))
}
Stmt::ReturnWithVal(_) => unreachable!(),
2020-03-06 16:49:52 +01:00
// Let statement
Stmt::Let(x) if x.1.is_some() => {
2020-05-18 03:36:34 +02:00
let ((var_name, _), expr) = x.as_ref();
2020-05-09 18:19:13 +02:00
let val = self.eval_expr(scope, state, expr.as_ref().unwrap(), level)?;
let var_name = unsafe_cast_var_name_to_lifetime(var_name, &state);
scope.push_dynamic_value(var_name, ScopeEntryType::Normal, val, false);
2020-04-30 16:52:36 +02:00
Ok(Default::default())
2020-03-11 16:43:04 +01:00
}
Stmt::Let(x) => {
2020-05-18 03:36:34 +02:00
let ((var_name, _), _) = x.as_ref();
let var_name = unsafe_cast_var_name_to_lifetime(var_name, &state);
scope.push(var_name, ());
2020-04-30 16:52:36 +02:00
Ok(Default::default())
2016-02-29 22:43:45 +01:00
}
2020-03-13 11:12:41 +01:00
// Const statement
Stmt::Const(x) if x.1.is_constant() => {
2020-05-18 03:36:34 +02:00
let ((var_name, _), expr) = x.as_ref();
2020-05-09 18:19:13 +02:00
let val = self.eval_expr(scope, state, &expr, level)?;
let var_name = unsafe_cast_var_name_to_lifetime(var_name, &state);
scope.push_dynamic_value(var_name, ScopeEntryType::Constant, val, true);
2020-04-30 16:52:36 +02:00
Ok(Default::default())
2020-03-13 11:12:41 +01:00
}
2020-05-04 11:43:54 +02:00
// Const expression not constant
Stmt::Const(_) => unreachable!(),
2020-05-04 13:36:58 +02:00
// Import statement
Stmt::Import(x) => {
2020-05-05 17:57:25 +02:00
#[cfg(feature = "no_module")]
unreachable!();
#[cfg(not(feature = "no_module"))]
2020-05-04 13:36:58 +02:00
{
2020-05-15 15:40:54 +02:00
let (expr, (name, pos)) = x.as_ref();
// Guard against too many modules
2020-05-19 04:08:27 +02:00
if state.modules >= self.max_modules {
return Err(Box::new(EvalAltResult::ErrorTooManyModules(*pos)));
2020-05-15 15:40:54 +02:00
}
if let Some(path) = self
.eval_expr(scope, state, &expr, level)?
.try_cast::<String>()
{
2020-05-17 16:19:49 +02:00
if let Some(resolver) = &self.module_resolver {
2020-05-08 10:49:24 +02:00
// Use an empty scope to create a module
let module =
resolver.resolve(self, Scope::new(), &path, expr.position())?;
let mod_name = unsafe_cast_var_name_to_lifetime(name, &state);
scope.push_module(mod_name, module);
2020-05-15 15:40:54 +02:00
state.modules += 1;
Ok(Default::default())
} else {
Err(Box::new(EvalAltResult::ErrorModuleNotFound(
path,
expr.position(),
)))
}
} else {
Err(Box::new(EvalAltResult::ErrorImportExpr(expr.position())))
}
2020-05-04 13:36:58 +02:00
}
}
2020-05-08 10:49:24 +02:00
// Export statement
Stmt::Export(list) => {
for ((id, id_pos), rename) in list.iter() {
2020-05-08 10:49:24 +02:00
// Mark scope variables as public
if let Some(index) = scope
.get_index(id)
.map(|(i, _)| i)
.or_else(|| scope.get_module_index(id))
{
let alias = rename
.as_ref()
.map(|(n, _)| n.clone())
.unwrap_or_else(|| id.clone());
scope.set_entry_alias(index, alias);
2020-05-11 17:48:50 +02:00
} else {
2020-05-08 10:49:24 +02:00
return Err(Box::new(EvalAltResult::ErrorVariableNotFound(
id.into(),
*id_pos,
)));
}
}
Ok(Default::default())
}
2016-02-29 22:43:45 +01:00
}
}
/// Check if the number of operations stay within limit.
fn inc_operations(&self, state: &mut State, pos: Position) -> Result<(), Box<EvalAltResult>> {
state.operations += 1;
#[cfg(not(feature = "unchecked"))]
{
// Guard against too many operations
2020-05-19 04:08:27 +02:00
if state.operations > self.max_operations {
return Err(Box::new(EvalAltResult::ErrorTooManyOperations(pos)));
}
}
// Report progress - only in steps
2020-05-17 16:19:49 +02:00
if let Some(progress) = &self.progress {
if !progress(state.operations) {
// Terminate script if progress returns false
return Err(Box::new(EvalAltResult::ErrorTerminated(pos)));
}
}
Ok(())
}
/// 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-04-11 12:09:03 +02:00
self.type_names
2020-04-27 15:28:31 +02:00
.get(name)
.map(String::as_str)
2020-04-11 12:09:03 +02:00
.unwrap_or(name)
2020-03-02 16:16:19 +01:00
}
2016-03-01 15:40:48 +01:00
}