rhai/src/engine.rs

2820 lines
107 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-07-03 04:45:01 +02:00
use crate::any::{map_std_type_name, Dynamic, Union, Variant};
2020-04-21 17:01:10 +02:00
use crate::calc_fn_hash;
use crate::error::ParseErrorType;
2020-06-25 12:07:57 +02:00
use crate::fn_native::{CallableFunction, Callback, FnCallArgs, FnPtr};
2020-06-28 09:49:24 +02:00
use crate::module::{resolvers, Module, ModuleRef, ModuleResolver};
2020-04-10 06:16:39 +02:00
use crate::optimize::OptimizationLevel;
2020-07-05 09:23:51 +02:00
use crate::packages::{Package, PackagesCollection, StandardPackage};
use crate::parser::{Expr, FnAccess, ImmutableString, ReturnType, ScriptFnDef, Stmt, AST, INT};
2020-06-29 17:55:28 +02:00
use crate::r#unsafe::unsafe_cast_var_name_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;
2020-05-23 12:59:28 +02:00
#[cfg(not(feature = "no_float"))]
use crate::parser::FLOAT;
2020-07-10 16:01:47 +02:00
#[cfg(feature = "internals")]
use crate::syntax::CustomSyntax;
2020-03-17 19:26:11 +01:00
use crate::stdlib::{
2020-07-03 04:45:01 +02:00
any::{type_name, TypeId},
borrow::Cow,
2020-03-17 19:26:11 +01:00
boxed::Box,
2020-07-05 09:23:51 +02:00
collections::{HashMap, HashSet},
convert::TryFrom,
2020-03-17 19:26:11 +01:00
format,
iter::{empty, once},
2020-04-26 12:04:07 +02:00
mem,
2020-03-17 19:26:11 +01:00
string::{String, ToString},
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-07-03 11:19:55 +02:00
/// Hash map of `Dynamic` values with `ImmutableString` keys.
2020-04-03 13:42:01 +02:00
///
/// Not available under the `no_object` feature.
#[cfg(not(feature = "no_object"))]
pub type Map = HashMap<ImmutableString, Dynamic>;
2020-03-29 17:53:35 +02:00
/// A stack of imported modules.
pub type Imports<'a> = Vec<(Cow<'a, str>, Module)>;
#[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")]
2020-06-14 16:44:59 +02:00
pub const MAX_EXPR_DEPTH: usize = 0;
#[cfg(feature = "unchecked")]
2020-06-14 16:44:59 +02:00
pub const MAX_FUNCTION_EXPR_DEPTH: usize = 0;
2020-06-13 18:09:16 +02:00
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";
2020-06-29 17:55:28 +02:00
pub const KEYWORD_FN_PTR: &str = "Fn";
2020-06-25 12:07:57 +02:00
pub const KEYWORD_FN_PTR_CALL: &str = "call";
2020-06-26 04:39:18 +02:00
pub const KEYWORD_THIS: &str = "this";
2020-06-25 05:07:46 +02:00
pub const FN_TO_STRING: &str = "to_string";
pub const FN_GET: &str = "get$";
pub const FN_SET: &str = "set$";
2020-07-09 13:54:28 +02:00
pub const FN_IDX_GET: &str = "index$get$";
pub const FN_IDX_SET: &str = "index$set$";
2020-07-10 16:01:47 +02:00
#[cfg(feature = "internals")]
2020-07-09 13:54:28 +02:00
pub const MARKER_EXPR: &str = "$expr$";
2020-07-10 16:01:47 +02:00
#[cfg(feature = "internals")]
2020-07-09 13:54:28 +02:00
pub const MARKER_BLOCK: &str = "$block$";
2020-07-10 16:01:47 +02:00
#[cfg(feature = "internals")]
2020-07-09 13:54:28 +02:00
pub const MARKER_IDENT: &str = "$ident$";
2020-03-03 10:28:38 +01:00
2020-07-11 09:09:17 +02:00
#[cfg(feature = "internals")]
pub struct Expression<'a>(&'a Expr);
#[cfg(feature = "internals")]
impl<'a> From<&'a Expr> for Expression<'a> {
fn from(expr: &'a Expr) -> Self {
Self(expr)
}
}
#[cfg(feature = "internals")]
impl Expression<'_> {
/// If this expression is a variable name, return it. Otherwise `None`.
#[cfg(feature = "internals")]
pub fn get_variable_name(&self) -> Option<&str> {
match self.0 {
Expr::Variable(x) => Some((x.0).0.as_str()),
_ => None,
}
}
/// Get the expression.
pub(crate) fn expr(&self) -> &Expr {
&self.0
}
/// Get the position of this expression.
pub fn position(&self) -> Position {
self.0.position()
}
}
/// A type specifying the method of chaining.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
enum ChainType {
2020-06-25 05:07:46 +02:00
None,
Index,
Dot,
}
2020-04-26 12:04:07 +02:00
/// A type that encapsulates a mutation target for an expression with side effects.
2020-06-06 07:06:00 +02:00
#[derive(Debug)]
2020-04-26 12:04:07 +02:00
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 {
2020-06-06 07:06:00 +02:00
Self::Ref(_) => true,
Self::Value(_) | Self::StringChar(_, _, _) => false,
}
}
/// Is the `Target` an owned value?
pub fn is_value(&self) -> bool {
match self {
Self::Ref(_) => false,
Self::Value(_) => true,
Self::StringChar(_, _, _) => false,
2020-05-16 05:42:56 +02:00
}
}
/// Is the `Target` a specific type?
pub fn is<T: Variant + Clone>(&self) -> bool {
match self {
Target::Ref(r) => r.is::<T>(),
Target::Value(r) => r.is::<T>(),
Target::StringChar(_, _, _) => TypeId::of::<T>() == TypeId::of::<char>(),
}
}
2020-05-16 05:42:56 +02:00
/// 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-06-06 07:06:00 +02:00
Self::Ref(r) => r.clone(), // Referenced value is cloned
Self::Value(v) => v, // Owned value is simply taken
Self::StringChar(_, _, ch) => ch, // Character is taken
2020-05-16 05:42:56 +02:00
}
}
/// Get a mutable reference from the `Target`.
pub fn as_mut(&mut self) -> &mut Dynamic {
match self {
2020-06-06 07:06:00 +02:00
Self::Ref(r) => *r,
Self::Value(ref mut r) => r,
Self::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`.
2020-06-01 09:25:22 +02:00
/// Position in `EvalAltResult` is None and must be set afterwards.
pub fn set_value(&mut self, new_val: Dynamic) -> Result<(), Box<EvalAltResult>> {
2020-03-30 16:19:37 +02:00
match self {
2020-06-06 07:06:00 +02:00
Self::Ref(r) => **r = new_val,
Self::Value(_) => {
2020-06-01 09:25:22 +02:00
return Err(Box::new(EvalAltResult::ErrorAssignmentToUnknownLHS(
Position::none(),
)))
2020-04-26 12:04:07 +02:00
}
2020-06-06 07:06:00 +02:00
Self::StringChar(Dynamic(Union::Str(ref mut s)), index, _) => {
2020-05-16 05:42:56 +02:00
// Replace the character at the specified index position
let new_ch = new_val
.as_char()
2020-06-01 09:25:22 +02:00
.map_err(|_| EvalAltResult::ErrorCharMismatch(Position::none()))?;
2020-05-16 05:42:56 +02:00
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-25 07:44:28 +02:00
*s = chars.iter().collect::<String>().into();
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.
2020-06-26 04:39:18 +02:00
#[derive(Debug, Clone, Eq, PartialEq, Hash, Default)]
pub struct State {
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.
2020-05-24 17:42:16 +02:00
/// In some situation, e.g. after running an `eval` statement, subsequent offsets become mis-aligned.
2020-04-28 17:05:03 +02:00
/// 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.
2020-06-14 08:25:47 +02:00
pub modules: usize,
2020-04-28 17:05:03 +02:00
}
impl State {
2020-04-29 10:11:54 +02:00
/// Create a new `State`.
pub fn new() -> Self {
Default::default()
2020-04-28 17:05:03 +02:00
}
}
/// Get a script-defined function definition from a module.
2020-07-04 10:21:15 +02:00
#[cfg(not(feature = "no_function"))]
pub fn get_script_function_by_signature<'a>(
module: &'a Module,
name: &str,
params: usize,
public_only: bool,
) -> Option<&'a ScriptFnDef> {
// Qualifiers (none) + function name + number of arguments.
2020-06-11 12:13:33 +02:00
let hash_script = calc_fn_hash(empty(), name, params, empty());
let func = module.get_fn(hash_script)?;
if !func.is_script() {
return None;
}
let fn_def = func.get_fn_def();
match fn_def.access {
FnAccess::Private if public_only => None,
FnAccess::Private | FnAccess::Public => Some(&fn_def),
}
}
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
///
2020-06-09 06:21:21 +02:00
/// Currently, `Engine` is neither `Send` nor `Sync`. Use the `sync` feature to make it `Send + Sync`.
2020-04-16 17:31:48 +02:00
pub struct Engine {
2020-06-15 17:20:50 +02:00
/// A unique ID identifying this scripting `Engine`.
pub id: Option<String>,
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.
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-07-05 09:23:51 +02:00
pub(crate) type_names: Option<HashMap<String, String>>,
2020-07-05 11:41:45 +02:00
/// A hashset containing symbols to disable.
pub(crate) disabled_symbols: Option<HashSet<String>>,
/// A hashset containing custom keywords and precedence to recognize.
pub(crate) custom_keywords: Option<HashMap<String, u8>>,
2020-07-09 13:54:28 +02:00
/// Custom syntax.
2020-07-10 16:01:47 +02:00
#[cfg(feature = "internals")]
2020-07-09 13:54:28 +02:00
pub(crate) custom_syntax: Option<HashMap<String, CustomSyntax>>,
2020-06-02 07:33:16 +02:00
/// Callback closure for implementing the `print` command.
pub(crate) print: Callback<str, ()>,
/// Callback closure for implementing the `debug` command.
pub(crate) debug: Callback<str, ()>,
/// Callback closure for progress reporting.
pub(crate) progress: Option<Callback<u64, bool>>,
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-06-14 08:25:47 +02:00
pub(crate) max_modules: usize,
2020-06-13 18:09:16 +02:00
/// Maximum length of a string.
pub(crate) max_string_size: usize,
/// Maximum length of an array.
pub(crate) max_array_size: usize,
/// Maximum number of properties in a map.
pub(crate) max_map_size: usize,
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-06-15 17:20:50 +02:00
id: None,
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"))]
2020-06-17 03:54:17 +02:00
#[cfg(not(target_arch = "wasm32"))]
module_resolver: Some(Box::new(resolvers::FileModuleResolver::new())),
2020-06-17 10:49:51 +02:00
#[cfg(any(feature = "no_module", feature = "no_std", target_arch = "wasm32",))]
module_resolver: None,
2020-05-05 17:57:25 +02:00
2020-07-05 09:23:51 +02:00
type_names: None,
2020-07-05 11:41:45 +02:00
disabled_symbols: None,
custom_keywords: None,
2020-07-10 16:01:47 +02:00
#[cfg(feature = "internals")]
2020-07-09 13:54:28 +02:00
custom_syntax: None,
// 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"))]
optimization_level: OptimizationLevel::Simple,
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-06-14 08:25:47 +02:00
max_operations: 0,
max_modules: usize::MAX,
max_string_size: 0,
max_array_size: 0,
max_map_size: 0,
2020-03-09 14:57:07 +01:00
};
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 {
2020-06-25 05:07:46 +02:00
format!("{}{}", FN_GET, id)
2020-03-30 10:10:50 +02:00
}
/// 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"))]
2020-07-04 16:53:00 +02:00
if fn_name.starts_with(FN_GET) {
Some(&fn_name[FN_GET.len()..])
} else {
2020-03-30 10:10:50 +02:00
None
}
2020-07-04 16:53:00 +02:00
#[cfg(feature = "no_object")]
None
2020-03-30 10:10:50 +02:00
}
/// Make setter function
pub fn make_setter(id: &str) -> String {
2020-06-25 05:07:46 +02:00
format!("{}{}", FN_SET, id)
2020-03-30 10:10:50 +02:00
}
/// 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"))]
2020-07-04 16:53:00 +02:00
if fn_name.starts_with(FN_SET) {
Some(&fn_name[FN_SET.len()..])
} else {
2020-03-30 10:10:50 +02:00
None
}
2020-07-04 16:53:00 +02:00
#[cfg(feature = "no_object")]
None
2020-03-30 10:10:50 +02:00
}
2020-04-19 12:33:02 +02:00
/// Print/debug to stdout
fn default_print(s: &str) {
#[cfg(not(feature = "no_std"))]
2020-06-17 03:54:17 +02:00
#[cfg(not(target_arch = "wasm32"))]
2020-04-19 12:33:02 +02:00
println!("{}", s);
}
2020-06-28 09:49:24 +02:00
/// Search for a module within an imports stack.
/// Position in `EvalAltResult` is None and must be set afterwards.
fn search_imports<'s>(
mods: &'s Imports,
state: &mut State,
modules: &Box<ModuleRef>,
) -> Result<&'s Module, Box<EvalAltResult>> {
let (root, root_pos) = modules.get(0);
// Qualified - check if the root module is directly indexed
let index = if state.always_search {
None
} else {
modules.index()
};
Ok(if let Some(index) = index {
let offset = mods.len() - index.get();
&mods.get(offset).unwrap().1
} else {
mods.iter()
.rev()
.find(|(n, _)| n == root)
.map(|(_, m)| m)
.ok_or_else(|| {
Box::new(EvalAltResult::ErrorModuleNotFound(
root.to_string(),
*root_pos,
))
})?
})
}
/// Search for a module within an imports stack.
/// Position in `EvalAltResult` is None and must be set afterwards.
fn search_imports_mut<'s>(
2020-06-28 09:49:24 +02:00
mods: &'s mut Imports,
state: &mut State,
modules: &Box<ModuleRef>,
) -> Result<&'s mut Module, Box<EvalAltResult>> {
let (root, root_pos) = modules.get(0);
// Qualified - check if the root module is directly indexed
let index = if state.always_search {
None
} else {
modules.index()
};
Ok(if let Some(index) = index {
let offset = mods.len() - index.get();
&mut mods.get_mut(offset).unwrap().1
} else {
mods.iter_mut()
.rev()
.find(|(n, _)| n == root)
.map(|(_, m)| m)
.ok_or_else(|| {
Box::new(EvalAltResult::ErrorModuleNotFound(
root.to_string(),
*root_pos,
))
})?
})
}
/// Search for a variable within the scope and imports
fn search_namespace<'s, 'a>(
2020-05-30 04:27:48 +02:00
scope: &'s mut Scope,
mods: &'s mut Imports,
state: &mut State,
2020-06-26 04:39:18 +02:00
this_ptr: &'s mut Option<&mut Dynamic>,
expr: &'a Expr,
2020-05-30 04:27:48 +02:00
) -> Result<(&'s mut Dynamic, &'a str, ScopeEntryType, Position), Box<EvalAltResult>> {
match expr {
Expr::Variable(v) => match v.as_ref() {
// Qualified variable
((name, pos), Some(modules), hash_var, _) => {
let module = search_imports_mut(mods, state, modules)?;
let target = module
.get_qualified_var_mut(*hash_var)
.map_err(|err| match *err {
EvalAltResult::ErrorVariableNotFound(_, _) => {
Box::new(EvalAltResult::ErrorVariableNotFound(
format!("{}{}", modules, name),
*pos,
))
}
_ => err.new_position(*pos),
})?;
// Module variables are constant
Ok((target, name, ScopeEntryType::Constant, *pos))
}
// Normal variable access
_ => search_scope_only(scope, state, this_ptr, expr),
},
_ => unreachable!(),
}
}
/// Search for a variable within the scope
fn search_scope_only<'s, 'a>(
scope: &'s mut Scope,
state: &mut State,
this_ptr: &'s mut Option<&mut Dynamic>,
expr: &'a Expr,
) -> Result<(&'s mut Dynamic, &'a str, ScopeEntryType, Position), Box<EvalAltResult>> {
let ((name, pos), _, _, index) = match expr {
2020-06-26 04:39:18 +02:00
Expr::Variable(v) => v.as_ref(),
_ => unreachable!(),
};
2020-06-26 04:39:18 +02:00
// Check if the variable is `this`
if name == KEYWORD_THIS {
if let Some(val) = this_ptr {
return Ok(((*val).into(), KEYWORD_THIS, ScopeEntryType::Normal, *pos));
} else {
return Err(Box::new(EvalAltResult::ErrorUnboundedThis(*pos)));
}
}
// Check if it is directly indexed
let index = if state.always_search { None } else { *index };
2020-05-31 09:51:26 +02:00
let index = if let Some(index) = index {
scope.len() - index.get()
2020-05-04 17:07:42 +02:00
} else {
// Find the variable in the scope
scope
.get_index(name)
.ok_or_else(|| Box::new(EvalAltResult::ErrorVariableNotFound(name.into(), *pos)))?
.0
};
2020-06-06 07:06:00 +02:00
let (val, typ) = scope.get_mut(index);
Ok((val, name, typ, *pos))
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
2020-05-24 17:42:16 +02:00
/// Create a new `Engine` with minimal built-in functions.
/// Use the `load_package` method to load additional packages of functions.
pub fn new_raw() -> Self {
Self {
2020-06-15 17:20:50 +02:00
id: None,
2020-05-05 09:00:10 +02:00
packages: Default::default(),
2020-05-13 13:21:42 +02:00
global_module: Default::default(),
module_resolver: None,
2020-07-05 09:23:51 +02:00
type_names: None,
2020-07-05 11:41:45 +02:00
disabled_symbols: None,
custom_keywords: None,
2020-07-10 16:01:47 +02:00
#[cfg(feature = "internals")]
2020-07-09 13:54:28 +02:00
custom_syntax: None,
2020-07-05 09:23:51 +02:00
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"))]
optimization_level: OptimizationLevel::Simple,
max_call_stack_depth: MAX_CALL_STACK_DEPTH,
max_expr_depth: MAX_EXPR_DEPTH,
max_function_expr_depth: MAX_FUNCTION_EXPR_DEPTH,
2020-06-14 08:25:47 +02:00
max_operations: 0,
max_modules: usize::MAX,
max_string_size: 0,
max_array_size: 0,
max_map_size: 0,
}
}
2020-05-05 17:57:25 +02:00
/// Universal method for calling functions either registered with the `Engine` or written in Rhai.
2020-06-01 09:25:22 +02:00
/// Position in `EvalAltResult` is None and must be set afterwards.
2020-05-06 17:52:47 +02:00
///
/// ## WARNING
///
2020-05-24 17:42:16 +02:00
/// Function call arguments be _consumed_ when the function requires them to be passed by value.
2020-05-06 17:52:47 +02:00
/// 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,
2020-05-30 04:27:48 +02:00
scope: &mut Scope,
mods: &mut Imports,
state: &mut State,
lib: &Module,
2020-03-04 15:00:01 +01:00
fn_name: &str,
2020-06-11 12:13:33 +02:00
(hash_fn, hash_script): (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-06-26 04:39:18 +02:00
is_method: bool,
2020-03-08 12:54:02 +01:00
def_val: Option<&Dynamic>,
2020-03-27 07:34:01 +01:00
level: usize,
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
2020-06-01 09:25:22 +02:00
self.inc_operations(state)?;
2020-06-11 12:13:33 +02:00
let native_only = hash_script == 0;
2020-05-23 18:29:06 +02:00
2020-04-07 17:13:47 +02:00
// Check for stack overflow
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "unchecked"))]
2020-07-04 16:53:00 +02:00
if level > self.max_call_stack_depth {
return Err(Box::new(
EvalAltResult::ErrorStackOverflow(Position::none()),
));
2020-04-07 17:13:47 +02:00
}
let mut this_copy: Dynamic = Default::default();
let mut old_this_ptr: Option<&mut Dynamic> = None;
/// This function replaces the first argument of a method call with a clone copy.
/// This is to prevent a pure function unintentionally consuming the first argument.
fn normalize_first_arg<'a>(
normalize: bool,
this_copy: &mut Dynamic,
old_this_ptr: &mut Option<&'a mut Dynamic>,
args: &mut FnCallArgs<'a>,
) {
// Only do it for method calls with arguments.
if !normalize || args.is_empty() {
return;
}
// Clone the original value.
*this_copy = 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 later with `restore_first_arg_of_method_call`.
2020-06-29 17:55:28 +02:00
//
// # Safety
//
// Blindly casting a a reference to another lifetime saves on allocations and string cloning,
// but must be used with the utmost care.
//
// We can do this here because, at the end of this scope, we'd restore the original reference
// with `restore_first_arg_of_method_call`. Therefore this shorter lifetime does not get "out".
let this_pointer = mem::replace(args.get_mut(0).unwrap(), unsafe {
mem::transmute(this_copy)
});
*old_this_ptr = Some(this_pointer);
}
/// This function restores the first argument that was replaced by `normalize_first_arg_of_method_call`.
fn restore_first_arg<'a>(old_this_ptr: Option<&'a mut Dynamic>, args: &mut FnCallArgs<'a>) {
if let Some(this_pointer) = old_this_ptr {
mem::replace(args.get_mut(0).unwrap(), this_pointer);
}
}
// Search for the function
2020-03-11 16:43:04 +01:00
// First search in script-defined functions (can override built-in)
// Then search registered native functions (can override packages)
// Then search packages
// NOTE: We skip script functions for global_module and packages, and native functions for lib
let func = if !native_only {
2020-06-11 12:13:33 +02:00
lib.get_fn(hash_script) //.or_else(|| lib.get_fn(hash_fn))
} else {
None
}
2020-06-11 12:13:33 +02:00
//.or_else(|| self.global_module.get_fn(hash_script))
.or_else(|| self.global_module.get_fn(hash_fn))
//.or_else(|| self.packages.get_fn(hash_script))
.or_else(|| self.packages.get_fn(hash_fn));
if let Some(func) = func {
2020-07-04 10:21:15 +02:00
#[cfg(not(feature = "no_function"))]
let need_normalize = is_ref && (func.is_pure() || (func.is_script() && !is_method));
#[cfg(feature = "no_function")]
let need_normalize = is_ref && func.is_pure();
2020-06-26 04:39:18 +02:00
// Calling pure function but the first argument is a reference?
2020-07-04 10:21:15 +02:00
normalize_first_arg(need_normalize, &mut this_copy, &mut old_this_ptr, args);
2020-06-06 07:06:00 +02:00
2020-07-04 10:21:15 +02:00
#[cfg(not(feature = "no_function"))]
if func.is_script() {
// Run scripted function
let fn_def = func.get_fn_def();
2020-06-26 04:39:18 +02:00
// Method call of script function - map first argument to `this`
2020-07-04 10:21:15 +02:00
return if is_method {
2020-06-26 04:39:18 +02:00
let (first, rest) = args.split_at_mut(1);
2020-07-04 10:21:15 +02:00
Ok((
2020-06-26 04:39:18 +02:00
self.call_script_fn(
scope,
mods,
2020-06-26 04:39:18 +02:00
state,
lib,
&mut Some(first[0]),
fn_name,
fn_def,
rest,
level,
)?,
false,
2020-07-04 10:21:15 +02:00
))
2020-06-26 04:39:18 +02:00
} else {
let result = self.call_script_fn(
scope, mods, state, lib, &mut None, fn_name, fn_def, args, level,
2020-06-26 04:39:18 +02:00
)?;
// Restore the original reference
restore_first_arg(old_this_ptr, args);
2020-07-04 10:21:15 +02:00
Ok((result, false))
2020-06-26 04:39:18 +02:00
};
}
2020-07-04 10:21:15 +02:00
// Run external function
let result = func.get_native_fn()(self, lib, args)?;
2020-07-04 10:21:15 +02:00
// Restore the original reference
restore_first_arg(old_this_ptr, args);
// See if the function match print/debug (which requires special processing)
return Ok(match fn_name {
KEYWORD_PRINT => (
(self.print)(result.as_str().map_err(|typ| {
Box::new(EvalAltResult::ErrorMismatchOutputType(
self.map_type_name(type_name::<ImmutableString>()).into(),
typ.into(),
Position::none(),
))
})?)
.into(),
false,
),
KEYWORD_DEBUG => (
(self.debug)(result.as_str().map_err(|typ| {
Box::new(EvalAltResult::ErrorMismatchOutputType(
self.map_type_name(type_name::<ImmutableString>()).into(),
typ.into(),
Position::none(),
))
})?)
.into(),
false,
),
_ => (result, func.is_method()),
});
2020-03-11 16:43:04 +01:00
}
// See if it is built in.
if args.len() == 2 {
2020-05-23 18:29:06 +02:00
match run_builtin_binary_op(fn_name, args[0], args[1])? {
2020-05-24 17:42:16 +02:00
Some(v) => return Ok((v, false)),
2020-05-23 12:59:28 +02:00
None => (),
}
}
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),
2020-06-01 09:25:22 +02:00
Position::none(),
)));
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),
2020-06-01 09:25:22 +02:00
Position::none(),
)));
2020-03-11 16:43:04 +01:00
}
2020-06-06 07:06:00 +02:00
// index getter function not found?
2020-06-25 05:07:46 +02:00
if fn_name == FN_IDX_GET && args.len() == 2 {
2020-06-06 07:06:00 +02:00
return Err(Box::new(EvalAltResult::ErrorFunctionNotFound(
format!(
"{} [{}]",
self.map_type_name(args[0].type_name()),
self.map_type_name(args[1].type_name()),
),
Position::none(),
)));
}
2020-03-11 16:43:04 +01:00
2020-06-06 07:06:00 +02:00
// index setter function not found?
2020-06-25 05:07:46 +02:00
if fn_name == FN_IDX_SET {
2020-05-05 14:38:48 +02:00
return Err(Box::new(EvalAltResult::ErrorFunctionNotFound(
2020-06-06 07:06:00 +02:00
format!(
"{} [{}]=",
self.map_type_name(args[0].type_name()),
self.map_type_name(args[1].type_name()),
),
2020-06-01 09:25:22 +02:00
Position::none(),
2020-05-05 14:38:48 +02:00
)));
}
// Raise error
Err(Box::new(EvalAltResult::ErrorFunctionNotFound(
2020-06-06 07:06:00 +02:00
format!(
"{} ({})",
fn_name,
args.iter()
2020-06-08 04:26:32 +02:00
.map(|name| if name.is::<ImmutableString>() {
"&str | ImmutableString"
} else {
self.map_type_name((*name).type_name())
2020-06-08 04:26:32 +02:00
})
2020-06-06 07:06:00 +02:00
.collect::<Vec<_>>()
.join(", ")
),
2020-06-01 09:25:22 +02:00
Position::none(),
)))
2017-12-20 12:16:14 +01:00
}
2020-04-24 06:39:24 +02:00
/// Call a script-defined function.
2020-06-01 09:25:22 +02:00
/// Position in `EvalAltResult` is None and must be set afterwards.
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(
2020-04-24 06:39:24 +02:00
&self,
2020-05-30 04:27:48 +02:00
scope: &mut Scope,
mods: &mut Imports,
state: &mut State,
lib: &Module,
2020-06-26 04:39:18 +02:00
this_ptr: &mut Option<&mut Dynamic>,
fn_name: &str,
fn_def: &ScriptFnDef,
2020-04-24 06:39:24 +02:00
args: &mut FnCallArgs,
level: usize,
) -> Result<Dynamic, Box<EvalAltResult>> {
2020-05-15 15:40:54 +02:00
let orig_scope_level = state.scope_level;
state.scope_level += 1;
let prev_scope_len = scope.len();
let prev_mods_len = mods.len();
2020-05-30 04:27:48 +02:00
// Put arguments into scope as variables
// Actually consume the arguments instead of cloning them
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(), state);
(var_name, ScopeEntryType::Normal, value)
}),
);
2020-04-24 06:39:24 +02:00
2020-05-30 04:27:48 +02:00
// Evaluate the function at one higher level of call depth
let result = self
.eval_stmt(scope, mods, state, lib, this_ptr, &fn_def.body, level + 1)
2020-05-30 04:27:48 +02:00
.or_else(|err| match *err {
// Convert return statement to return value
EvalAltResult::Return(x, _) => Ok(x),
2020-06-01 09:25:22 +02:00
EvalAltResult::ErrorInFunctionCall(name, err, _) => {
Err(Box::new(EvalAltResult::ErrorInFunctionCall(
format!("{} > {}", fn_name, name),
err,
Position::none(),
)))
}
2020-05-30 04:27:48 +02:00
_ => Err(Box::new(EvalAltResult::ErrorInFunctionCall(
fn_name.to_string(),
err,
2020-06-01 09:25:22 +02:00
Position::none(),
2020-05-30 04:27:48 +02:00
))),
});
2020-04-24 06:39:24 +02:00
2020-05-30 04:27:48 +02:00
// Remove all local variables
scope.rewind(prev_scope_len);
mods.truncate(prev_mods_len);
2020-05-30 04:27:48 +02:00
state.scope_level = orig_scope_level;
2020-04-24 06:39:24 +02:00
2020-05-30 04:27:48 +02:00
result
2020-04-24 06:39:24 +02:00
}
// Has a system function an override?
2020-06-11 12:13:33 +02:00
fn has_override(&self, lib: &Module, (hash_fn, hash_script): (u64, u64)) -> bool {
// NOTE: We skip script functions for global_module and packages, and native functions for lib
// First check script-defined functions
2020-06-11 12:13:33 +02:00
lib.contains_fn(hash_script)
//|| lib.contains_fn(hash_fn)
// Then check registered functions
2020-06-11 12:13:33 +02:00
//|| self.global_module.contains_fn(hash_script)
|| self.global_module.contains_fn(hash_fn)
// Then check packages
2020-06-11 12:13:33 +02:00
//|| self.packages.contains_fn(hash_script)
|| self.packages.contains_fn(hash_fn)
}
2020-06-01 09:25:22 +02:00
/// Perform an actual function call, taking care of special functions
/// Position in `EvalAltResult` is None and must be set afterwards.
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,
lib: &Module,
fn_name: &str,
2020-05-23 12:59:28 +02:00
native_only: bool,
2020-06-11 12:13:33 +02:00
hash_script: u64,
args: &mut FnCallArgs,
2020-05-11 17:48:50 +02:00
is_ref: bool,
2020-06-26 04:39:18 +02:00
is_method: bool,
def_val: Option<&Dynamic>,
level: usize,
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
// Qualifiers (none) + function name + number of arguments + argument `TypeId`'s.
2020-06-06 07:06:00 +02:00
let arg_types = args.iter().map(|a| a.type_id());
let hash_fn = calc_fn_hash(empty(), fn_name, args.len(), arg_types);
2020-06-11 12:13:33 +02:00
let hashes = (hash_fn, if native_only { 0 } else { hash_script });
2020-05-09 10:15:50 +02:00
match fn_name {
// type_of
KEYWORD_TYPE_OF if args.len() == 1 && !self.has_override(lib, hashes) => Ok((
2020-05-11 17:48:50 +02:00
self.map_type_name(args[0].type_name()).to_string().into(),
false,
)),
2020-06-25 12:07:57 +02:00
// Fn
2020-06-29 17:55:28 +02:00
KEYWORD_FN_PTR if args.len() == 1 && !self.has_override(lib, hashes) => {
2020-06-25 12:07:57 +02:00
Err(Box::new(EvalAltResult::ErrorRuntime(
"'Fn' should not be called in method style. Try Fn(...);".into(),
Position::none(),
)))
}
2020-04-30 16:52:36 +02:00
// eval - reaching this point it must be a method-style call
KEYWORD_EVAL if args.len() == 1 && !self.has_override(lib, hashes) => {
Err(Box::new(EvalAltResult::ErrorRuntime(
"'eval' should not be called in method style. Try eval(...);".into(),
2020-06-01 09:25:22 +02:00
Position::none(),
)))
}
2020-05-09 10:15:50 +02:00
// Normal function call
2020-05-30 04:27:48 +02:00
_ => {
let mut scope = Scope::new();
let mut mods = Imports::new();
2020-05-30 04:27:48 +02:00
self.call_fn_raw(
&mut scope, &mut mods, state, lib, fn_name, hashes, args, is_ref, is_method,
def_val, level,
2020-05-30 04:27:48 +02:00
)
}
}
}
2020-04-24 06:39:24 +02:00
/// Evaluate a text string as a script - used primarily for 'eval'.
2020-06-01 09:25:22 +02:00
/// Position in `EvalAltResult` is None and must be set afterwards.
2020-04-24 06:39:24 +02:00
fn eval_script_expr(
&self,
scope: &mut Scope,
mods: &mut Imports,
state: &mut State,
lib: &Module,
2020-04-24 06:39:24 +02:00
script: &Dynamic,
) -> Result<Dynamic, Box<EvalAltResult>> {
2020-07-03 04:45:01 +02:00
let script = script.as_str().map_err(|typ| {
EvalAltResult::ErrorMismatchOutputType(
self.map_type_name(type_name::<ImmutableString>()).into(),
typ.into(),
Position::none(),
)
2020-06-01 09:25:22 +02:00
})?;
2020-04-24 06:39:24 +02:00
// 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
if ast.lib().num_fn() != 0 {
return Err(ParseErrorType::WrongFnDefinition.into());
2020-04-24 06:39:24 +02:00
}
2020-05-05 09:00:10 +02:00
let statements = mem::take(ast.statements_mut());
let ast = AST::new(statements, lib.clone());
2020-04-24 06:39:24 +02:00
// Evaluate the AST
let (result, operations) = self.eval_ast_with_scope_raw(scope, mods, &ast)?;
state.operations += operations;
2020-06-01 09:25:22 +02:00
self.inc_operations(state)?;
return Ok(result);
2020-04-24 06:39:24 +02:00
}
2020-07-09 16:21:07 +02:00
/// Call a dot method.
fn call_method(
&self,
state: &mut State,
lib: &Module,
target: &mut Target,
expr: &Expr,
mut idx_val: Dynamic,
level: usize,
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
let ((name, native, pos), _, hash, _, def_val) = match expr {
Expr::FnCall(x) => x.as_ref(),
_ => unreachable!(),
};
let is_ref = target.is_ref();
let is_value = target.is_value();
let def_val = def_val.as_ref();
// Get a reference to the mutation target Dynamic
let obj = target.as_mut();
let idx = idx_val.downcast_mut::<StaticVec<Dynamic>>().unwrap();
let mut fn_name = name.as_ref();
// Check if it is a FnPtr call
let (result, updated) = if fn_name == KEYWORD_FN_PTR_CALL && obj.is::<FnPtr>() {
// Redirect function name
fn_name = obj.as_str().unwrap();
// Recalculate hash
let hash = calc_fn_hash(empty(), fn_name, idx.len(), empty());
// Arguments are passed as-is
let mut arg_values = idx.iter_mut().collect::<StaticVec<_>>();
let args = arg_values.as_mut();
// Map it to name(args) in function-call style
self.exec_fn_call(
state, lib, fn_name, *native, hash, args, false, false, def_val, level,
)
} else {
let redirected: Option<ImmutableString>;
let mut hash = *hash;
// Check if it is a map method call in OOP style
if let Some(map) = obj.downcast_ref::<Map>() {
if let Some(val) = map.get(fn_name) {
if let Some(f) = val.downcast_ref::<FnPtr>() {
// Remap the function name
redirected = Some(f.get_fn_name().clone());
fn_name = redirected.as_ref().unwrap();
// Recalculate the hash based on the new function name
hash = calc_fn_hash(empty(), fn_name, idx.len(), empty());
}
}
};
// Attached object pointer in front of the arguments
let mut arg_values = once(obj).chain(idx.iter_mut()).collect::<StaticVec<_>>();
let args = arg_values.as_mut();
self.exec_fn_call(
state, lib, fn_name, *native, hash, args, is_ref, true, def_val, level,
)
}
.map_err(|err| err.new_position(*pos))?;
// Feed the changed temp value back
if updated && !is_ref && !is_value {
let new_val = target.as_mut().clone();
target.set_value(new_val)?;
}
Ok((result, updated))
}
2020-04-26 12:04:07 +02:00
/// Chain-evaluate a dot/index chain.
2020-06-01 09:25:22 +02:00
/// Position in `EvalAltResult` is None and must be set afterwards.
2020-04-26 12:04:07 +02:00
fn eval_dot_index_chain_helper(
&self,
state: &mut State,
lib: &Module,
2020-06-26 04:39:18 +02:00
this_ptr: &mut Option<&mut Dynamic>,
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>,
chain_type: ChainType,
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-06-25 05:07:46 +02:00
if chain_type == ChainType::None {
panic!();
}
2020-05-16 05:42:56 +02:00
let is_ref = target.is_ref();
2020-03-01 17:11:00 +01:00
2020-06-25 05:07:46 +02:00
let next_chain = match rhs {
Expr::Index(_) => ChainType::Index,
Expr::Dot(_) => ChainType::Dot,
_ => ChainType::None,
};
2020-04-26 12:04:07 +02:00
// Pop the last index value
2020-07-09 16:21:07 +02:00
let idx_val = idx_values.pop();
2020-03-01 17:11:00 +01:00
match chain_type {
#[cfg(not(feature = "no_index"))]
ChainType::Index => {
let pos = rhs.position();
match rhs {
// xxx[idx].expr... | xxx[idx][expr]...
Expr::Dot(x) | Expr::Index(x) => {
let (idx, expr, pos) = x.as_ref();
let idx_pos = idx.position();
2020-06-26 04:39:18 +02:00
let obj_ptr = &mut self
.get_indexed_mut(state, lib, target, idx_val, idx_pos, false, level)?;
self.eval_dot_index_chain_helper(
2020-06-26 04:39:18 +02:00
state, lib, this_ptr, obj_ptr, expr, idx_values, next_chain, level,
new_val,
)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(*pos))
}
// xxx[rhs] = new_val
_ if new_val.is_some() => {
let mut idx_val2 = idx_val.clone();
2020-06-26 04:39:18 +02:00
match self.get_indexed_mut(state, lib, target, idx_val, pos, true, level) {
// Indexed value is an owned value - the only possibility is an indexer
// Try to call an index setter
2020-06-26 04:39:18 +02:00
Ok(obj_ptr) if obj_ptr.is_value() => {
let args =
&mut [target.as_mut(), &mut idx_val2, &mut new_val.unwrap()];
self.exec_fn_call(
2020-06-26 04:39:18 +02:00
state, lib, FN_IDX_SET, true, 0, args, is_ref, true, None,
level,
)
2020-06-06 07:06:00 +02:00
.or_else(|err| match *err {
// If there is no index setter, no need to set it back because the indexer is read-only
EvalAltResult::ErrorFunctionNotFound(s, _)
2020-06-25 05:07:46 +02:00
if s == FN_IDX_SET =>
2020-06-06 07:06:00 +02:00
{
Ok(Default::default())
}
_ => Err(err),
})?;
}
// Indexed value is a reference - update directly
2020-06-26 04:39:18 +02:00
Ok(ref mut obj_ptr) => {
2020-06-29 17:55:28 +02:00
obj_ptr
.set_value(new_val.unwrap())
.map_err(|err| err.new_position(rhs.position()))?;
}
Err(err) => match *err {
// No index getter - try to call an index setter
EvalAltResult::ErrorIndexingType(_, _) => {
let args = &mut [
target.as_mut(),
&mut idx_val2,
&mut new_val.unwrap(),
];
self.exec_fn_call(
2020-06-26 04:39:18 +02:00
state, lib, FN_IDX_SET, true, 0, args, is_ref, true, None,
level,
)?;
}
// Error
err => return Err(Box::new(err)),
},
}
Ok(Default::default())
2020-06-06 07:06:00 +02:00
}
// xxx[rhs]
_ => self
2020-06-26 04:39:18 +02:00
.get_indexed_mut(state, lib, target, idx_val, pos, false, level)
.map(|v| (v.clone_into_dynamic(), false)),
2020-04-26 12:04:07 +02:00
}
}
#[cfg(not(feature = "no_object"))]
ChainType::Dot => {
match rhs {
// xxx.fn_name(arg_expr_list)
Expr::FnCall(x) if x.1.is_none() => {
2020-07-09 16:21:07 +02:00
self.call_method(state, lib, target, rhs, idx_val, level)
}
// xxx.module::fn_name(...) - syntax error
Expr::FnCall(_) => unreachable!(),
// {xxx:map}.id = ???
Expr::Property(x) if target.is::<Map>() && new_val.is_some() => {
let ((prop, _, _), pos) = x.as_ref();
let index = prop.clone().into();
let mut val =
2020-06-26 04:39:18 +02:00
self.get_indexed_mut(state, lib, target, index, *pos, true, level)?;
val.set_value(new_val.unwrap())
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(rhs.position()))?;
Ok((Default::default(), true))
}
// {xxx:map}.id
Expr::Property(x) if target.is::<Map>() => {
let ((prop, _, _), pos) = x.as_ref();
let index = prop.clone().into();
2020-06-26 04:39:18 +02:00
let val =
self.get_indexed_mut(state, lib, target, index, *pos, false, level)?;
2020-05-11 17:48:50 +02:00
Ok((val.clone_into_dynamic(), false))
}
// xxx.id = ???
Expr::Property(x) if new_val.is_some() => {
let ((_, _, setter), pos) = x.as_ref();
let mut args = [target.as_mut(), new_val.as_mut().unwrap()];
2020-06-26 04:39:18 +02:00
self.exec_fn_call(
state, lib, setter, true, 0, &mut args, is_ref, true, None, level,
)
.map(|(v, _)| (v, true))
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(*pos))
}
// xxx.id
Expr::Property(x) => {
let ((_, getter, _), pos) = x.as_ref();
let mut args = [target.as_mut()];
2020-06-26 04:39:18 +02:00
self.exec_fn_call(
state, lib, getter, true, 0, &mut args, is_ref, true, None, level,
)
.map(|(v, _)| (v, false))
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(*pos))
}
2020-07-09 16:21:07 +02:00
// {xxx:map}.sub_lhs[expr] | {xxx:map}.sub_lhs.expr
Expr::Index(x) | Expr::Dot(x) if target.is::<Map>() => {
2020-07-09 16:21:07 +02:00
let (sub_lhs, expr, pos) = x.as_ref();
let mut val = match sub_lhs {
Expr::Property(p) => {
let ((prop, _, _), _) = p.as_ref();
let index = prop.clone().into();
self.get_indexed_mut(state, lib, target, index, *pos, false, level)?
}
// {xxx:map}.fn_name(arg_expr_list)[expr] | {xxx:map}.fn_name(arg_expr_list).expr
Expr::FnCall(x) if x.1.is_none() => {
let (val, _) =
self.call_method(state, lib, target, sub_lhs, idx_val, level)?;
val.into()
}
// {xxx:map}.module::fn_name(...) - syntax error
Expr::FnCall(_) => unreachable!(),
// Others - syntax error
_ => unreachable!(),
};
self.eval_dot_index_chain_helper(
2020-06-26 04:39:18 +02:00
state, lib, this_ptr, &mut val, expr, idx_values, next_chain, level,
new_val,
2020-06-01 09:25:22 +02:00
)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(*pos))
}
2020-07-09 16:21:07 +02:00
// xxx.sub_lhs[expr] | xxx.sub_lhs.expr
Expr::Index(x) | Expr::Dot(x) => {
2020-07-09 16:21:07 +02:00
let (sub_lhs, expr, pos) = x.as_ref();
match sub_lhs {
// xxx.prop[expr] | xxx.prop.expr
Expr::Property(p) => {
let ((_, getter, setter), _) = p.as_ref();
let arg_values = &mut [target.as_mut(), &mut Default::default()];
let args = &mut arg_values[..1];
let (mut val, updated) = self
.exec_fn_call(
state, lib, getter, true, 0, args, is_ref, true, None,
level,
)
.map_err(|err| err.new_position(*pos))?;
let val = &mut val;
let target = &mut val.into();
let (result, may_be_changed) = self
.eval_dot_index_chain_helper(
state, lib, this_ptr, target, expr, idx_values, next_chain,
level, new_val,
)
.map_err(|err| err.new_position(*pos))?;
// Feed the value back via a setter just in case it has been updated
if updated || may_be_changed {
// Re-use args because the first &mut parameter will not be consumed
arg_values[1] = val;
self.exec_fn_call(
state, lib, setter, true, 0, arg_values, is_ref, true,
None, level,
)
.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.new_position(*pos)),
},
)?;
}
Ok((result, may_be_changed))
}
// xxx.fn_name(arg_expr_list)[expr] | xxx.fn_name(arg_expr_list).expr
Expr::FnCall(x) if x.1.is_none() => {
let (mut val, _) =
self.call_method(state, lib, target, sub_lhs, idx_val, level)?;
let val = &mut val;
let target = &mut val.into();
self.eval_dot_index_chain_helper(
state, lib, this_ptr, target, expr, idx_values, next_chain,
level, new_val,
)
2020-07-09 16:21:07 +02:00
.map_err(|err| err.new_position(*pos))
}
2020-07-09 16:21:07 +02:00
// xxx.module::fn_name(...) - syntax error
Expr::FnCall(_) => unreachable!(),
// Others - syntax error
_ => unreachable!(),
2020-04-26 12:04:07 +02:00
}
}
// Syntax error
_ => Err(Box::new(EvalAltResult::ErrorDotExpr(
"".into(),
rhs.position(),
))),
}
2020-04-26 12:04:07 +02:00
}
_ => unreachable!(),
}
}
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,
mods: &mut Imports,
2020-04-28 17:05:03 +02:00
state: &mut State,
lib: &Module,
2020-06-26 04:39:18 +02:00
this_ptr: &mut Option<&mut Dynamic>,
2020-05-31 09:51:26 +02:00
expr: &Expr,
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 ((dot_lhs, dot_rhs, op_pos), chain_type) = match expr {
Expr::Index(x) => (x.as_ref(), ChainType::Index),
Expr::Dot(x) => (x.as_ref(), ChainType::Dot),
2020-05-31 09:51:26 +02:00
_ => unreachable!(),
};
let idx_values = &mut StaticVec::new();
2020-03-25 04:27:18 +01:00
self.eval_indexed_chain(
2020-07-09 16:21:07 +02:00
scope, mods, state, lib, this_ptr, dot_rhs, chain_type, 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[???]
2020-06-26 04:39:18 +02:00
Expr::Variable(x) => {
let (var_name, var_pos) = &x.0;
2020-06-01 09:25:22 +02:00
self.inc_operations(state)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(*var_pos))?;
2020-06-26 04:39:18 +02:00
let (target, _, typ, pos) =
search_namespace(scope, mods, state, this_ptr, dot_lhs)?;
2020-04-26 12:04:07 +02:00
// Constants cannot be modified
match typ {
ScopeEntryType::Constant if new_val.is_some() => {
return Err(Box::new(EvalAltResult::ErrorAssignmentToConstant(
2020-06-26 04:39:18 +02:00
var_name.to_string(),
pos,
2020-04-26 12:04:07 +02:00
)));
}
2020-05-04 17:07:42 +02:00
ScopeEntryType::Constant | ScopeEntryType::Normal => (),
}
2020-06-26 04:39:18 +02:00
let obj_ptr = &mut target.into();
2020-04-26 12:04:07 +02:00
self.eval_dot_index_chain_helper(
2020-06-26 04:39:18 +02:00
state, lib, &mut None, obj_ptr, dot_rhs, idx_values, chain_type, level, new_val,
2020-04-26 12:04:07 +02:00
)
.map(|(v, _)| v)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(*op_pos))
}
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, mods, state, lib, this_ptr, expr, level)?;
2020-06-26 04:39:18 +02:00
let obj_ptr = &mut val.into();
2020-04-26 12:04:07 +02:00
self.eval_dot_index_chain_helper(
2020-06-26 04:39:18 +02:00
state, lib, this_ptr, obj_ptr, dot_rhs, idx_values, chain_type, level, new_val,
2020-04-26 12:04:07 +02:00
)
.map(|(v, _)| v)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(*op_pos))
}
}
}
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,
mods: &mut Imports,
2020-04-28 17:05:03 +02:00
state: &mut State,
lib: &Module,
2020-06-26 04:39:18 +02:00
this_ptr: &mut Option<&mut Dynamic>,
2020-04-26 12:04:07 +02:00
expr: &Expr,
2020-07-09 16:21:07 +02:00
chain_type: ChainType,
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-06-01 09:25:22 +02:00
self.inc_operations(state)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(expr.position()))?;
2020-05-17 16:19:49 +02:00
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, mods, state, lib, this_ptr, 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-05-30 04:27:48 +02:00
let (lhs, rhs, _) = x.as_ref();
2020-04-26 12:04:07 +02:00
// Evaluate in left-to-right order
2020-05-30 04:27:48 +02:00
let lhs_val = match lhs {
Expr::Property(_) => Default::default(), // Store a placeholder in case of a property
2020-07-09 16:21:07 +02:00
Expr::FnCall(x) if chain_type == ChainType::Dot && x.1.is_none() => {
let arg_values = x
.3
.iter()
.map(|arg_expr| {
self.eval_expr(scope, mods, state, lib, this_ptr, arg_expr, level)
})
.collect::<Result<StaticVec<Dynamic>, _>>()?;
Dynamic::from(arg_values)
}
Expr::FnCall(_) => unreachable!(),
_ => self.eval_expr(scope, mods, state, lib, this_ptr, lhs, level)?,
2020-04-26 12:04:07 +02:00
};
// Push in reverse order
2020-07-09 16:21:07 +02:00
let chain_type = match expr {
Expr::Index(_) => ChainType::Index,
Expr::Dot(_) => ChainType::Dot,
_ => unreachable!(),
};
self.eval_indexed_chain(
2020-07-09 16:21:07 +02:00
scope, mods, state, lib, this_ptr, rhs, chain_type, 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, mods, state, lib, this_ptr, 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
2020-06-01 09:25:22 +02:00
/// Position in `EvalAltResult` may be None and should be set afterwards.
2020-04-26 12:04:07 +02:00
fn get_indexed_mut<'a>(
&self,
state: &mut State,
lib: &Module,
2020-06-06 07:06:00 +02:00
target: &'a mut Target,
2020-05-05 14:38:48 +02:00
mut idx: Dynamic,
2020-04-26 12:04:07 +02:00
idx_pos: Position,
create: bool,
2020-06-26 04:39:18 +02:00
level: usize,
2020-04-26 12:04:07 +02:00
) -> Result<Target<'a>, Box<EvalAltResult>> {
2020-06-01 09:25:22 +02:00
self.inc_operations(state)?;
2020-06-06 07:06:00 +02:00
let is_ref = target.is_ref();
let val = target.as_mut();
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
Ok(if create {
2020-05-25 07:44:28 +02:00
let index = idx
.take_immutable_string()
2020-05-25 07:44:28 +02:00
.map_err(|_| EvalAltResult::ErrorStringIndexExpr(idx_pos))?;
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 {
2020-05-25 07:44:28 +02:00
let index = idx
.downcast_ref::<String>()
.ok_or_else(|| EvalAltResult::ErrorStringIndexExpr(idx_pos))?;
map.get_mut(index.as_str())
.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
#[cfg(not(feature = "no_index"))]
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-06-26 04:39:18 +02:00
self.exec_fn_call(
state, lib, FN_IDX_GET, true, 0, args, is_ref, true, None, level,
)
.map(|(v, _)| v.into())
.map_err(|_| {
Box::new(EvalAltResult::ErrorIndexingType(
type_name.into(),
Position::none(),
))
})
2020-05-05 14:38:48 +02:00
}
#[cfg(feature = "no_index")]
_ => Err(Box::new(EvalAltResult::ErrorIndexingType(
self.map_type_name(val.type_name()).into(),
Position::none(),
))),
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,
mods: &mut Imports,
2020-04-28 17:05:03 +02:00
state: &mut State,
lib: &Module,
2020-06-26 04:39:18 +02:00
this_ptr: &mut Option<&mut Dynamic>,
2020-04-06 11:47:34 +02:00
lhs: &Expr,
rhs: &Expr,
level: usize,
) -> Result<Dynamic, Box<EvalAltResult>> {
2020-06-01 09:25:22 +02:00
self.inc_operations(state)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(rhs.position()))?;
let lhs_value = self.eval_expr(scope, mods, state, lib, this_ptr, lhs, level)?;
let rhs_value = self.eval_expr(scope, mods, state, lib, this_ptr, 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();
2020-05-30 04:27:48 +02:00
let mut scope = Scope::new();
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() {
2020-05-24 05:57:46 +02:00
let args = &mut [&mut lhs_value.clone(), value];
2020-04-12 17:00:06 +02:00
let def_value = Some(&def_value);
2020-05-09 10:15:50 +02:00
2020-05-25 14:14:31 +02:00
let hashes = (
// Qualifiers (none) + function name + number of arguments + argument `TypeId`'s.
calc_fn_hash(empty(), op, args.len(), args.iter().map(|a| a.type_id())),
0,
);
2020-04-30 16:52:36 +02:00
2020-06-01 09:25:22 +02:00
let (r, _) = self
.call_fn_raw(
&mut scope, mods, state, lib, op, hashes, args, false, false,
def_value, level,
2020-06-01 09:25:22 +02:00
)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(rhs.position()))?;
2020-05-11 17:48:50 +02:00
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()),
Dynamic(Union::Char(c)) => {
Ok(rhs_value.contains_key(c.to_string().as_str()).into())
}
2020-04-30 16:52:36 +02:00
_ => 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
}
}
2020-07-10 16:01:47 +02:00
/// Evaluate an expression tree.
2020-07-09 13:54:28 +02:00
///
/// ## WARNING - Low Level API
///
/// This function is very low level. It evaluates an expression from an AST.
#[cfg(feature = "internals")]
#[deprecated(note = "this method is volatile and may change")]
2020-07-10 16:01:47 +02:00
pub fn eval_expression_tree(
2020-07-09 13:54:28 +02:00
&self,
scope: &mut Scope,
mods: &mut Imports,
state: &mut State,
lib: &Module,
this_ptr: &mut Option<&mut Dynamic>,
2020-07-11 09:09:17 +02:00
expr: &Expression,
2020-07-09 13:54:28 +02:00
level: usize,
) -> Result<Dynamic, Box<EvalAltResult>> {
2020-07-11 09:09:17 +02:00
self.eval_expr(scope, mods, state, lib, this_ptr, expr.expr(), level)
2020-07-09 13:54:28 +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,
mods: &mut Imports,
2020-04-28 17:05:03 +02:00
state: &mut State,
lib: &Module,
2020-06-26 04:39:18 +02:00
this_ptr: &mut Option<&mut Dynamic>,
2020-03-27 07:34:01 +01:00
expr: &Expr,
level: usize,
) -> Result<Dynamic, Box<EvalAltResult>> {
2020-06-01 09:25:22 +02:00
self.inc_operations(state)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(expr.position()))?;
2020-06-13 18:09:16 +02:00
let result = match expr {
Expr::Expr(x) => self.eval_expr(scope, mods, state, lib, this_ptr, x.as_ref(), level),
2020-05-30 04:27:48 +02:00
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()),
2020-06-26 04:39:18 +02:00
Expr::Variable(x) if (x.0).0 == KEYWORD_THIS => {
if let Some(ref val) = this_ptr {
Ok((*val).clone())
} else {
Err(Box::new(EvalAltResult::ErrorUnboundedThis((x.0).1)))
}
}
Expr::Variable(_) => {
let (val, _, _, _) = search_namespace(scope, mods, state, this_ptr, expr)?;
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(x) => self.eval_stmt(scope, mods, state, lib, this_ptr, &x.0, level),
2020-03-07 03:39:00 +01:00
// var op= rhs
Expr::Assignment(x) if matches!(x.0, Expr::Variable(_)) => {
let (lhs_expr, op, rhs_expr, op_pos) = x.as_ref();
let mut rhs_val =
self.eval_expr(scope, mods, state, lib, this_ptr, rhs_expr, level)?;
let (lhs_ptr, name, typ, pos) =
search_namespace(scope, mods, state, this_ptr, lhs_expr)?;
2020-06-01 09:25:22 +02:00
self.inc_operations(state)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(pos))?;
match typ {
// Assignment to constant variable
ScopeEntryType::Constant => Err(Box::new(
EvalAltResult::ErrorAssignmentToConstant(name.to_string(), pos),
)),
// Normal assignment
ScopeEntryType::Normal if op.is_empty() => {
*lhs_ptr = rhs_val;
Ok(Default::default())
}
// Op-assignment - in order of precedence:
ScopeEntryType::Normal => {
// 1) Native registered overriding function
// 2) Built-in implementation
// 3) Map to `var = var op rhs`
// Qualifiers (none) + function name + number of arguments + argument `TypeId`'s.
let arg_types = once(lhs_ptr.type_id()).chain(once(rhs_val.type_id()));
let hash_fn = calc_fn_hash(empty(), op, 2, arg_types);
if let Some(CallableFunction::Method(func)) = self
.global_module
.get_fn(hash_fn)
.or_else(|| self.packages.get_fn(hash_fn))
{
// Overriding exact implementation
func(self, lib, &mut [lhs_ptr, &mut rhs_val])?;
} else if run_builtin_op_assignment(op, lhs_ptr, &rhs_val)?.is_none() {
// Not built in, map to `var = var op rhs`
let op = &op[..op.len() - 1]; // extract operator without =
let hash = calc_fn_hash(empty(), op, 2, empty());
let args = &mut [&mut lhs_ptr.clone(), &mut rhs_val];
// Set variable value
*lhs_ptr = self
2020-06-26 04:39:18 +02:00
.exec_fn_call(
state, lib, op, true, hash, args, false, false, None, level,
)
2020-06-01 09:25:22 +02:00
.map(|(v, _)| v)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(*op_pos))?;
2020-05-25 14:14:31 +02:00
}
Ok(Default::default())
2020-05-04 11:43:54 +02:00
}
}
}
// lhs op= rhs
Expr::Assignment(x) => {
let (lhs_expr, op, rhs_expr, op_pos) = x.as_ref();
let mut rhs_val =
self.eval_expr(scope, mods, state, lib, this_ptr, rhs_expr, level)?;
let new_val = Some(if op.is_empty() {
// Normal assignment
rhs_val
2020-05-25 14:14:31 +02:00
} else {
// Op-assignment - always map to `lhs = lhs op rhs`
let op = &op[..op.len() - 1]; // extract operator without =
let hash = calc_fn_hash(empty(), op, 2, empty());
let args = &mut [
&mut self.eval_expr(scope, mods, state, lib, this_ptr, lhs_expr, level)?,
&mut rhs_val,
];
2020-06-26 04:39:18 +02:00
self.exec_fn_call(state, lib, op, true, hash, args, false, false, None, level)
2020-06-01 09:25:22 +02:00
.map(|(v, _)| v)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(*op_pos))?
});
2020-05-25 14:14:31 +02:00
match lhs_expr {
// name op= rhs
Expr::Variable(_) => unreachable!(),
// idx_lhs[idx_expr] op= rhs
#[cfg(not(feature = "no_index"))]
Expr::Index(_) => {
self.eval_dot_index_chain(
scope, mods, state, lib, this_ptr, lhs_expr, level, new_val,
)?;
Ok(Default::default())
}
// dot_lhs.dot_rhs op= rhs
#[cfg(not(feature = "no_object"))]
Expr::Dot(_) => {
self.eval_dot_index_chain(
scope, mods, state, lib, this_ptr, lhs_expr, level, new_val,
)?;
Ok(Default::default())
}
// 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"))]
2020-06-26 04:39:18 +02:00
Expr::Index(_) => {
self.eval_dot_index_chain(scope, mods, state, lib, this_ptr, expr, level, None)
2020-06-26 04:39:18 +02:00
}
2020-04-10 06:16:39 +02:00
2020-04-26 12:04:07 +02:00
// lhs.dot_rhs
#[cfg(not(feature = "no_object"))]
2020-06-26 04:39:18 +02:00
Expr::Dot(_) => {
self.eval_dot_index_chain(scope, mods, state, lib, this_ptr, expr, level, None)
2020-06-26 04:39:18 +02:00
}
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, mods, state, lib, this_ptr, 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, mods, state, lib, this_ptr, 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-23 12:59:28 +02:00
let ((name, native, pos), _, hash, 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
2020-06-29 17:55:28 +02:00
// Handle Fn()
if name == KEYWORD_FN_PTR && args_expr.len() == 1 {
2020-06-25 12:07:57 +02:00
let hash_fn =
calc_fn_hash(empty(), name, 1, once(TypeId::of::<ImmutableString>()));
if !self.has_override(lib, (hash_fn, *hash)) {
// Fn - only in function call style
let expr = args_expr.get(0);
let arg_value =
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?;
2020-06-25 12:07:57 +02:00
return arg_value
.take_immutable_string()
2020-07-03 04:45:01 +02:00
.map_err(|typ| {
2020-06-25 12:07:57 +02:00
Box::new(EvalAltResult::ErrorMismatchOutputType(
2020-07-03 04:45:01 +02:00
self.map_type_name(type_name::<ImmutableString>()).into(),
typ.into(),
2020-06-29 17:55:28 +02:00
expr.position(),
2020-06-25 12:07:57 +02:00
))
2020-06-29 17:55:28 +02:00
})
.and_then(|s| FnPtr::try_from(s))
.map(Into::<Dynamic>::into)
.map_err(|err| err.new_position(*pos));
2020-06-25 12:07:57 +02:00
}
}
2020-06-29 17:55:28 +02:00
// Handle eval()
if name == KEYWORD_EVAL && args_expr.len() == 1 {
2020-05-25 11:01:39 +02:00
let hash_fn =
calc_fn_hash(empty(), name, 1, once(TypeId::of::<ImmutableString>()));
2020-05-11 17:48:50 +02:00
if !self.has_override(lib, (hash_fn, *hash)) {
2020-05-11 17:48:50 +02:00
// eval - only in function call style
let prev_len = scope.len();
2020-06-01 09:25:22 +02:00
let expr = args_expr.get(0);
let script =
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?;
2020-06-01 09:25:22 +02:00
let result = self
.eval_script_expr(scope, mods, state, lib, &script)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(expr.position()));
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-06-26 04:39:18 +02:00
// Normal function call - except for Fn and eval (handled above)
let mut arg_values: StaticVec<Dynamic>;
let mut args: StaticVec<_>;
let mut is_ref = false;
if args_expr.is_empty() {
// No arguments
args = Default::default();
} else {
// See if the first argument is a variable, if so, convert to method-call style
// in order to leverage potential &mut first argument and avoid cloning the value
match args_expr.get(0) {
// func(x, ...) -> x.func(...)
lhs @ Expr::Variable(_) => {
arg_values = args_expr
.iter()
.skip(1)
2020-06-26 04:39:18 +02:00
.map(|expr| {
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)
2020-06-26 04:39:18 +02:00
})
.collect::<Result<_, _>>()?;
let (target, _, _, pos) =
search_namespace(scope, mods, state, this_ptr, lhs)?;
2020-06-26 04:39:18 +02:00
self.inc_operations(state)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(pos))?;
2020-06-26 04:39:18 +02:00
args = once(target).chain(arg_values.iter_mut()).collect();
is_ref = true;
}
// func(..., ...)
_ => {
arg_values = args_expr
.iter()
2020-06-26 04:39:18 +02:00
.map(|expr| {
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)
2020-06-26 04:39:18 +02:00
})
.collect::<Result<_, _>>()?;
args = arg_values.iter_mut().collect();
}
}
}
2020-05-11 17:48:50 +02:00
let args = args.as_mut();
2020-05-23 12:59:28 +02:00
self.exec_fn_call(
2020-06-26 04:39:18 +02:00
state, lib, name, *native, *hash, args, is_ref, false, def_val, level,
2020-05-23 12:59:28 +02:00
)
.map(|(v, _)| v)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(*pos))
2020-03-04 15:00:01 +01:00
}
2020-03-01 17:11:00 +01:00
// Module-qualified function call
Expr::FnCall(x) if x.1.is_some() => {
2020-06-11 12:13:33 +02:00
let ((name, _, pos), modules, hash_script, args_expr, def_val) = x.as_ref();
2020-05-09 18:19:13 +02:00
let modules = modules.as_ref().unwrap();
let mut arg_values: StaticVec<Dynamic>;
let mut args: StaticVec<_>;
if args_expr.is_empty() {
// No arguments
args = Default::default();
} else {
// See if the first argument is a variable (not module-qualified).
// If so, convert to method-call style in order to leverage potential
// &mut first argument and avoid cloning the value
match args_expr.get(0) {
// func(x, ...) -> x.func(...)
Expr::Variable(x) if x.1.is_none() => {
arg_values = args_expr
.iter()
.skip(1)
.map(|expr| {
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)
})
.collect::<Result<_, _>>()?;
let (target, _, _, pos) =
search_scope_only(scope, state, this_ptr, args_expr.get(0))?;
self.inc_operations(state)
.map_err(|err| err.new_position(pos))?;
args = once(target).chain(arg_values.iter_mut()).collect();
}
// func(..., ...) or func(mod::x, ...)
_ => {
arg_values = args_expr
.iter()
.map(|expr| {
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)
})
.collect::<Result<_, _>>()?;
args = arg_values.iter_mut().collect();
}
}
}
2020-06-28 09:49:24 +02:00
let module = search_imports(mods, state, modules)?;
// First search in script-defined functions (can override built-in)
2020-06-28 09:49:24 +02:00
let func = match module.get_qualified_fn(*hash_script) {
Err(err) if matches!(*err, EvalAltResult::ErrorFunctionNotFound(_, _)) => {
// Then search in Rust functions
2020-06-01 09:25:22 +02:00
self.inc_operations(state)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(*pos))?;
2020-06-11 12:13:33 +02:00
// Qualified 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.
2020-06-11 12:13:33 +02:00
let hash_qualified_fn = *hash_script ^ hash_fn_args;
2020-06-28 09:49:24 +02:00
module.get_qualified_fn(hash_qualified_fn)
}
r => r,
};
match func {
2020-07-04 10:21:15 +02:00
#[cfg(not(feature = "no_function"))]
Ok(f) if f.is_script() => {
let args = args.as_mut();
let fn_def = f.get_fn_def();
2020-05-30 04:27:48 +02:00
let mut scope = Scope::new();
let mut mods = Imports::new();
2020-06-26 04:39:18 +02:00
self.call_script_fn(
&mut scope, &mut mods, state, lib, &mut None, name, fn_def, args, level,
2020-06-26 04:39:18 +02:00
)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(*pos))
}
Ok(f) => f.get_native_fn()(self, lib, args.as_mut())
.map_err(|err| err.new_position(*pos)),
2020-06-28 09:49:24 +02:00
Err(err) => match *err {
EvalAltResult::ErrorFunctionNotFound(_, _) if def_val.is_some() => {
Ok(def_val.clone().unwrap())
}
EvalAltResult::ErrorFunctionNotFound(_, _) => {
Err(Box::new(EvalAltResult::ErrorFunctionNotFound(
format!("{}{}", modules, name),
*pos,
)))
}
_ => Err(err.new_position(*pos)),
},
}
}
Expr::In(x) => self.eval_in_expr(scope, mods, state, lib, this_ptr, &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, mods, state, lib, this_ptr, 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
.eval_expr(scope, mods, state, lib, this_ptr, 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, mods, state, lib, this_ptr, 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
.eval_expr(scope, mods, state, lib, this_ptr, 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-07-10 16:01:47 +02:00
#[cfg(feature = "internals")]
2020-07-09 13:54:28 +02:00
Expr::Custom(x) => {
let func = (x.0).1.as_ref();
2020-07-11 09:09:17 +02:00
let ep: StaticVec<_> = (x.0).0.iter().map(|e| e.into()).collect();
func(self, scope, mods, state, lib, this_ptr, ep.as_ref(), level)
2020-07-09 13:54:28 +02:00
}
2020-05-04 11:43:54 +02:00
_ => unreachable!(),
2020-06-13 18:09:16 +02:00
};
2020-06-14 16:44:59 +02:00
self.check_data_size(result)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(expr.position()))
2016-02-29 22:43:45 +01:00
}
/// Evaluate a statement
2020-05-30 04:27:48 +02:00
pub(crate) fn eval_stmt(
&self,
2020-05-30 04:27:48 +02:00
scope: &mut Scope,
mods: &mut Imports,
2020-04-28 17:05:03 +02:00
state: &mut State,
lib: &Module,
2020-06-26 04:39:18 +02:00
this_ptr: &mut Option<&mut Dynamic>,
stmt: &Stmt,
2020-03-27 07:34:01 +01:00
level: usize,
) -> Result<Dynamic, Box<EvalAltResult>> {
2020-06-01 09:25:22 +02:00
self.inc_operations(state)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(stmt.position()))?;
2020-06-13 18:09:16 +02:00
let result = 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
Stmt::Expr(expr) => self.eval_expr(scope, mods, state, lib, this_ptr, expr, level),
2020-03-01 17:11:00 +01:00
2020-03-06 16:49:52 +01:00
// Block scope
Stmt::Block(x) => {
let prev_scope_len = scope.len();
let prev_mods_len = mods.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, mods, state, lib, this_ptr, stmt, level)
2020-03-27 07:34:01 +01:00
});
2016-02-29 22:43:45 +01:00
scope.rewind(prev_scope_len);
mods.truncate(prev_mods_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, mods, state, lib, this_ptr, expr, level)?
.as_bool()
.map_err(|_| Box::new(EvalAltResult::ErrorLogicGuard(expr.position())))
.and_then(|guard_val| {
if guard_val {
self.eval_stmt(scope, mods, state, lib, this_ptr, if_block, level)
} else if let Some(stmt) = else_block {
self.eval_stmt(scope, mods, state, lib, this_ptr, 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();
2020-06-26 04:39:18 +02:00
match self
.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
2020-06-26 04:39:18 +02:00
.as_bool()
{
Ok(true) => {
match self.eval_stmt(scope, mods, state, lib, this_ptr, body, level) {
Ok(_) => (),
Err(err) => match *err {
EvalAltResult::ErrorLoopBreak(false, _) => (),
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, mods, state, lib, this_ptr, 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, mods, state, lib, this_ptr, 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;
2020-06-01 09:25:22 +02:00
self.inc_operations(state)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(stmt.position()))?;
2020-03-01 17:11:00 +01:00
match self.eval_stmt(scope, mods, state, lib, this_ptr, 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(
self.eval_expr(
scope,
mods,
state,
lib,
this_ptr,
x.1.as_ref().unwrap(),
level,
)?,
2020-05-09 18:19:13 +02:00
(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,
mods,
state,
lib,
this_ptr,
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();
let val = self.eval_expr(
scope,
mods,
state,
lib,
this_ptr,
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();
let val = self.eval_expr(scope, mods, state, lib, this_ptr, &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) => {
let (expr, (name, pos)) = x.as_ref();
2020-05-15 15:40:54 +02:00
// Guard against too many modules
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, mods, state, lib, this_ptr, &expr, level)?
.try_cast::<ImmutableString>()
{
#[cfg(not(feature = "no_module"))]
2020-07-04 16:53:00 +02:00
if let Some(resolver) = &self.module_resolver {
let mut module = resolver.resolve(self, &path, expr.position())?;
module.index_all_sub_modules();
mods.push((name.clone().into(), module));
2020-05-15 15:40:54 +02:00
2020-07-04 16:53:00 +02:00
state.modules += 1;
2020-05-15 15:40:54 +02:00
2020-07-04 16:53:00 +02:00
Ok(Default::default())
} else {
Err(Box::new(EvalAltResult::ErrorModuleNotFound(
path.to_string(),
expr.position(),
)))
}
#[cfg(feature = "no_module")]
Ok(Default::default())
} 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) {
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())
}
2020-06-13 18:09:16 +02:00
};
2020-06-14 16:44:59 +02:00
self.check_data_size(result)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(stmt.position()))
2020-06-13 18:09:16 +02:00
}
2020-06-14 16:44:59 +02:00
/// Check a result to ensure that the data size is within allowable limit.
2020-06-29 17:55:28 +02:00
/// Position in `EvalAltResult` may be None and should be set afterwards.
2020-06-14 16:44:59 +02:00
fn check_data_size(
&self,
result: Result<Dynamic, Box<EvalAltResult>>,
) -> Result<Dynamic, Box<EvalAltResult>> {
2020-06-13 18:09:16 +02:00
#[cfg(feature = "unchecked")]
2020-06-14 16:44:59 +02:00
return result;
2020-06-14 08:25:47 +02:00
2020-06-14 16:44:59 +02:00
// If no data size limits, just return
2020-06-14 08:25:47 +02:00
if self.max_string_size + self.max_array_size + self.max_map_size == 0 {
2020-06-14 16:44:59 +02:00
return result;
2020-06-14 08:25:47 +02:00
}
// Recursively calculate the size of a value (especially `Array` and `Map`)
fn calc_size(value: &Dynamic) -> (usize, usize, usize) {
match value {
#[cfg(not(feature = "no_index"))]
Dynamic(Union::Array(arr)) => {
let mut arrays = 0;
let mut maps = 0;
arr.iter().for_each(|value| match value {
2020-07-01 16:21:43 +02:00
Dynamic(Union::Array(_)) => {
let (a, m, _) = calc_size(value);
arrays += a;
maps += m;
}
#[cfg(not(feature = "no_object"))]
Dynamic(Union::Map(_)) => {
2020-06-14 08:25:47 +02:00
let (a, m, _) = calc_size(value);
arrays += a;
maps += m;
}
_ => arrays += 1,
});
(arrays, maps, 0)
}
#[cfg(not(feature = "no_object"))]
Dynamic(Union::Map(map)) => {
let mut arrays = 0;
let mut maps = 0;
map.values().for_each(|value| match value {
2020-07-01 16:21:43 +02:00
#[cfg(not(feature = "no_index"))]
Dynamic(Union::Array(_)) => {
let (a, m, _) = calc_size(value);
arrays += a;
maps += m;
}
Dynamic(Union::Map(_)) => {
2020-06-14 08:25:47 +02:00
let (a, m, _) = calc_size(value);
arrays += a;
maps += m;
}
_ => maps += 1,
});
(arrays, maps, 0)
}
Dynamic(Union::Str(s)) => (0, 0, s.len()),
_ => (0, 0, 0),
2020-06-13 18:09:16 +02:00
}
2020-06-14 08:25:47 +02:00
}
2020-06-14 16:44:59 +02:00
match result {
// Simply return all errors
Err(_) => return result,
// String with limit
Ok(Dynamic(Union::Str(_))) if self.max_string_size > 0 => (),
// Array with limit
2020-06-13 18:09:16 +02:00
#[cfg(not(feature = "no_index"))]
2020-06-14 16:44:59 +02:00
Ok(Dynamic(Union::Array(_))) if self.max_array_size > 0 => (),
// Map with limit
2020-06-13 18:09:16 +02:00
#[cfg(not(feature = "no_object"))]
2020-06-14 16:44:59 +02:00
Ok(Dynamic(Union::Map(_))) if self.max_map_size > 0 => (),
// Everything else is simply returned
Ok(_) => return result,
2020-06-14 08:25:47 +02:00
};
2020-06-14 16:44:59 +02:00
let (arr, map, s) = calc_size(result.as_ref().unwrap());
2020-06-14 08:25:47 +02:00
if s > self.max_string_size {
Err(Box::new(EvalAltResult::ErrorDataTooLarge(
"Length of string".to_string(),
self.max_string_size,
s,
Position::none(),
)))
} else if arr > self.max_array_size {
Err(Box::new(EvalAltResult::ErrorDataTooLarge(
"Size of array".to_string(),
2020-06-14 08:25:47 +02:00
self.max_array_size,
arr,
Position::none(),
)))
} else if map > self.max_map_size {
Err(Box::new(EvalAltResult::ErrorDataTooLarge(
"Number of properties in object map".to_string(),
self.max_map_size,
map,
Position::none(),
)))
} else {
2020-06-14 16:44:59 +02:00
result
2016-02-29 22:43:45 +01:00
}
}
/// Check if the number of operations stay within limit.
2020-06-01 09:25:22 +02:00
/// Position in `EvalAltResult` is None and must be set afterwards.
fn inc_operations(&self, state: &mut State) -> Result<(), Box<EvalAltResult>> {
state.operations += 1;
#[cfg(not(feature = "unchecked"))]
2020-07-04 16:53:00 +02:00
// Guard against too many operations
if self.max_operations > 0 && state.operations > self.max_operations {
return Err(Box::new(EvalAltResult::ErrorTooManyOperations(
Position::none(),
)));
}
// Report progress - only in steps
2020-05-17 16:19:49 +02:00
if let Some(progress) = &self.progress {
2020-06-02 07:33:16 +02:00
if !progress(&state.operations) {
// Terminate script if progress returns false
2020-06-01 09:25:22 +02:00
return Err(Box::new(EvalAltResult::ErrorTerminated(Position::none())));
}
}
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-07-05 09:23:51 +02:00
.as_ref()
.and_then(|t| t.get(name).map(String::as_str))
2020-07-03 04:45:01 +02:00
.unwrap_or(map_std_type_name(name))
2020-03-02 16:16:19 +01:00
}
2016-03-01 15:40:48 +01:00
}
2020-05-23 12:59:28 +02:00
2020-05-23 18:29:06 +02:00
/// Build in common binary operator implementations to avoid the cost of calling a registered function.
fn run_builtin_binary_op(
2020-05-23 12:59:28 +02:00
op: &str,
x: &Dynamic,
y: &Dynamic,
) -> Result<Option<Dynamic>, Box<EvalAltResult>> {
use crate::packages::arithmetic::*;
let args_type = x.type_id();
2020-05-24 17:42:16 +02:00
if y.type_id() != args_type {
return Ok(None);
}
if args_type == TypeId::of::<INT>() {
let x = *x.downcast_ref::<INT>().unwrap();
let y = *y.downcast_ref::<INT>().unwrap();
2020-05-23 12:59:28 +02:00
#[cfg(not(feature = "unchecked"))]
match op {
2020-06-16 03:34:30 +02:00
"+" => return add(x, y).map(Into::into).map(Some),
"-" => return sub(x, y).map(Into::into).map(Some),
"*" => return mul(x, y).map(Into::into).map(Some),
"/" => return div(x, y).map(Into::into).map(Some),
"%" => return modulo(x, y).map(Into::into).map(Some),
"~" => return pow_i_i(x, y).map(Into::into).map(Some),
">>" => return shr(x, y).map(Into::into).map(Some),
"<<" => return shl(x, y).map(Into::into).map(Some),
2020-05-23 12:59:28 +02:00
_ => (),
}
#[cfg(feature = "unchecked")]
match op {
"+" => return Ok(Some((x + y).into())),
"-" => return Ok(Some((x - y).into())),
"*" => return Ok(Some((x * y).into())),
"/" => return Ok(Some((x / y).into())),
"%" => return Ok(Some((x % y).into())),
2020-06-16 03:34:30 +02:00
"~" => return pow_i_i_u(x, y).map(Into::into).map(Some),
">>" => return shr_u(x, y).map(Into::into).map(Some),
"<<" => return shl_u(x, y).map(Into::into).map(Some),
2020-05-23 12:59:28 +02:00
_ => (),
}
match op {
"==" => return Ok(Some((x == y).into())),
"!=" => return Ok(Some((x != y).into())),
">" => return Ok(Some((x > y).into())),
">=" => return Ok(Some((x >= y).into())),
"<" => return Ok(Some((x < y).into())),
"<=" => return Ok(Some((x <= y).into())),
"&" => return Ok(Some((x & y).into())),
"|" => return Ok(Some((x | y).into())),
"^" => return Ok(Some((x ^ y).into())),
_ => (),
}
} else if args_type == TypeId::of::<bool>() {
let x = *x.downcast_ref::<bool>().unwrap();
let y = *y.downcast_ref::<bool>().unwrap();
2020-05-23 12:59:28 +02:00
match op {
"&" => return Ok(Some((x && y).into())),
"|" => return Ok(Some((x || y).into())),
"^" => return Ok(Some((x ^ y).into())),
2020-05-23 12:59:28 +02:00
"==" => return Ok(Some((x == y).into())),
"!=" => return Ok(Some((x != y).into())),
_ => (),
}
2020-05-25 07:44:28 +02:00
} else if args_type == TypeId::of::<ImmutableString>() {
let x = x.downcast_ref::<ImmutableString>().unwrap();
let y = y.downcast_ref::<ImmutableString>().unwrap();
2020-05-23 12:59:28 +02:00
match op {
2020-05-26 08:14:03 +02:00
"+" => return Ok(Some((x + y).into())),
2020-05-23 12:59:28 +02:00
"==" => return Ok(Some((x == y).into())),
"!=" => return Ok(Some((x != y).into())),
">" => return Ok(Some((x > y).into())),
">=" => return Ok(Some((x >= y).into())),
"<" => return Ok(Some((x < y).into())),
"<=" => return Ok(Some((x <= y).into())),
_ => (),
}
} else if args_type == TypeId::of::<char>() {
let x = *x.downcast_ref::<char>().unwrap();
let y = *y.downcast_ref::<char>().unwrap();
2020-05-23 12:59:28 +02:00
match op {
"==" => return Ok(Some((x == y).into())),
"!=" => return Ok(Some((x != y).into())),
">" => return Ok(Some((x > y).into())),
">=" => return Ok(Some((x >= y).into())),
"<" => return Ok(Some((x < y).into())),
"<=" => return Ok(Some((x <= y).into())),
_ => (),
}
} else if args_type == TypeId::of::<()>() {
2020-05-23 12:59:28 +02:00
match op {
"==" => return Ok(Some(true.into())),
"!=" | ">" | ">=" | "<" | "<=" => return Ok(Some(false.into())),
_ => (),
}
}
#[cfg(not(feature = "no_float"))]
2020-07-04 16:53:00 +02:00
if args_type == TypeId::of::<FLOAT>() {
let x = *x.downcast_ref::<FLOAT>().unwrap();
let y = *y.downcast_ref::<FLOAT>().unwrap();
match op {
"+" => return Ok(Some((x + y).into())),
"-" => return Ok(Some((x - y).into())),
"*" => return Ok(Some((x * y).into())),
"/" => return Ok(Some((x / y).into())),
"%" => return Ok(Some((x % y).into())),
"~" => return pow_f_f(x, y).map(Into::into).map(Some),
"==" => return Ok(Some((x == y).into())),
"!=" => return Ok(Some((x != y).into())),
">" => return Ok(Some((x > y).into())),
">=" => return Ok(Some((x >= y).into())),
"<" => return Ok(Some((x < y).into())),
"<=" => return Ok(Some((x <= y).into())),
_ => (),
2020-05-23 12:59:28 +02:00
}
}
Ok(None)
}
2020-05-25 14:14:31 +02:00
/// Build in common operator assignment implementations to avoid the cost of calling a registered function.
fn run_builtin_op_assignment(
op: &str,
x: &mut Dynamic,
y: &Dynamic,
) -> Result<Option<()>, Box<EvalAltResult>> {
use crate::packages::arithmetic::*;
let args_type = x.type_id();
if y.type_id() != args_type {
return Ok(None);
}
if args_type == TypeId::of::<INT>() {
let x = x.downcast_mut::<INT>().unwrap();
let y = *y.downcast_ref::<INT>().unwrap();
2020-05-25 14:14:31 +02:00
#[cfg(not(feature = "unchecked"))]
match op {
"+=" => return Ok(Some(*x = add(*x, y)?)),
"-=" => return Ok(Some(*x = sub(*x, y)?)),
"*=" => return Ok(Some(*x = mul(*x, y)?)),
"/=" => return Ok(Some(*x = div(*x, y)?)),
"%=" => return Ok(Some(*x = modulo(*x, y)?)),
"~=" => return Ok(Some(*x = pow_i_i(*x, y)?)),
">>=" => return Ok(Some(*x = shr(*x, y)?)),
"<<=" => return Ok(Some(*x = shl(*x, y)?)),
2020-05-25 14:14:31 +02:00
_ => (),
}
#[cfg(feature = "unchecked")]
match op {
"+=" => return Ok(Some(*x += y)),
"-=" => return Ok(Some(*x -= y)),
"*=" => return Ok(Some(*x *= y)),
"/=" => return Ok(Some(*x /= y)),
"%=" => return Ok(Some(*x %= y)),
"~=" => return Ok(Some(*x = pow_i_i_u(*x, y)?)),
">>=" => return Ok(Some(*x = shr_u(*x, y)?)),
"<<=" => return Ok(Some(*x = shl_u(*x, y)?)),
2020-05-25 14:14:31 +02:00
_ => (),
}
match op {
"&=" => return Ok(Some(*x &= y)),
"|=" => return Ok(Some(*x |= y)),
"^=" => return Ok(Some(*x ^= y)),
2020-05-25 14:14:31 +02:00
_ => (),
}
} else if args_type == TypeId::of::<bool>() {
let x = x.downcast_mut::<bool>().unwrap();
let y = *y.downcast_ref::<bool>().unwrap();
2020-05-25 14:14:31 +02:00
match op {
"&=" => return Ok(Some(*x = *x && y)),
"|=" => return Ok(Some(*x = *x || y)),
2020-05-25 14:14:31 +02:00
_ => (),
}
2020-05-28 04:33:28 +02:00
} else if args_type == TypeId::of::<ImmutableString>() {
let x = x.downcast_mut::<ImmutableString>().unwrap();
let y = y.downcast_ref::<ImmutableString>().unwrap();
match op {
"+=" => return Ok(Some(*x += y)),
_ => (),
}
2020-05-25 14:14:31 +02:00
}
#[cfg(not(feature = "no_float"))]
2020-07-04 16:53:00 +02:00
if args_type == TypeId::of::<FLOAT>() {
let x = x.downcast_mut::<FLOAT>().unwrap();
let y = *y.downcast_ref::<FLOAT>().unwrap();
match op {
"+=" => return Ok(Some(*x += y)),
"-=" => return Ok(Some(*x -= y)),
"*=" => return Ok(Some(*x *= y)),
"/=" => return Ok(Some(*x /= y)),
"%=" => return Ok(Some(*x %= y)),
"~=" => return Ok(Some(*x = pow_f_f(*x, y)?)),
_ => (),
2020-05-25 14:14:31 +02:00
}
}
Ok(None)
}