rhai/src/engine.rs

2038 lines
78 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-31 12:06:01 +02:00
use crate::any::{map_std_type_name, Dynamic, Union};
2020-04-21 17:01:10 +02:00
use crate::calc_fn_hash;
use crate::fn_call::run_builtin_op_assignment;
2020-09-21 12:00:46 +02:00
use crate::fn_native::{Callback, FnPtr};
2020-07-26 09:53:22 +02:00
use crate::module::{Module, ModuleRef};
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};
2020-07-26 09:53:22 +02:00
use crate::parser::{Expr, ReturnType, Stmt};
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};
2020-07-24 17:16:54 +02:00
use crate::syntax::{CustomSyntax, EvalContext};
use crate::token::Position;
use crate::utils::StaticVec;
2020-07-26 09:53:22 +02:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
use crate::any::Variant;
#[cfg(not(feature = "no_function"))]
use crate::parser::ScriptFnDef;
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_module"))]
use crate::module::ModuleResolver;
#[cfg(not(feature = "no_std"))]
#[cfg(not(feature = "no_module"))]
use crate::module::resolvers;
#[cfg(any(not(feature = "no_object"), not(feature = "no_module")))]
use crate::utils::ImmutableString;
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-07-31 16:30:23 +02:00
#[cfg(not(feature = "no_object"))]
2020-07-31 12:06:01 +02:00
use crate::any::DynamicWriteLock;
2020-03-17 19:26:11 +01:00
use crate::stdlib::{
borrow::Cow,
2020-03-17 19:26:11 +01:00
boxed::Box,
2020-07-05 09:23:51 +02:00
collections::{HashMap, HashSet},
2020-07-13 13:38:50 +02:00
fmt, format,
iter::{empty, once},
2020-08-02 07:33:51 +02:00
ops::DerefMut,
2020-03-17 19:26:11 +01:00
string::{String, ToString},
vec::Vec,
2020-03-10 03:07:44 +01:00
};
2020-07-31 16:30:23 +02:00
#[cfg(not(feature = "no_index"))]
use crate::stdlib::any::TypeId;
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
use crate::stdlib::mem;
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
/// [INTERNALS] A stack of imported modules.
/// Exported under the `internals` feature only.
///
/// ## WARNING
///
/// This type is volatile and may change.
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
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-07-22 17:12:09 +02:00
pub const KEYWORD_FN_PTR_CURRY: &str = "curry";
2020-07-31 12:43:34 +02:00
pub const KEYWORD_IS_SHARED: &str = "is_shared";
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";
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_object"))]
2020-06-25 05:07:46 +02:00
pub const FN_GET: &str = "get$";
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_object"))]
2020-06-25 05:07:46 +02:00
pub const FN_SET: &str = "set$";
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_index"))]
2020-07-09 13:54:28 +02:00
pub const FN_IDX_GET: &str = "index$get$";
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_index"))]
2020-07-09 13:54:28 +02:00
pub const FN_IDX_SET: &str = "index$set$";
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_function"))]
2020-07-19 11:14:55 +02:00
pub const FN_ANONYMOUS: &str = "anon$";
2020-07-09 13:54:28 +02:00
pub const MARKER_EXPR: &str = "$expr$";
pub const MARKER_BLOCK: &str = "$block$";
pub const MARKER_IDENT: &str = "$ident$";
2020-03-03 10:28:38 +01:00
/// A type specifying the method of chaining.
2020-07-26 09:53:22 +02:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub 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-07-26 09:53:22 +02:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
2020-06-06 07:06:00 +02:00
#[derive(Debug)]
pub enum Target<'a> {
2020-04-26 12:04:07 +02:00
/// The target is a mutable reference to a `Dynamic` value somewhere.
Ref(&'a mut Dynamic),
/// The target is a mutable reference to a Shared `Dynamic` value.
2020-07-31 12:06:01 +02:00
/// It holds both the access guard and the original shared value.
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-07-31 16:30:23 +02:00
#[cfg(not(feature = "no_object"))]
LockGuard((DynamicWriteLock<'a, Dynamic>, Dynamic)),
2020-04-26 12:04:07 +02:00
/// 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-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_index"))]
2020-05-16 05:42:56 +02:00
StringChar(&'a mut Dynamic, usize, Dynamic),
2020-03-30 16:19:37 +02:00
}
2020-07-26 09:53:22 +02:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
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?
2020-08-08 10:24:10 +02:00
#[inline(always)]
2020-05-16 05:42:56 +02:00
pub fn is_ref(&self) -> bool {
match self {
2020-06-06 07:06:00 +02:00
Self::Ref(_) => true,
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-07-31 16:30:23 +02:00
#[cfg(not(feature = "no_object"))]
Self::LockGuard(_) => true,
2020-07-26 09:53:22 +02:00
Self::Value(_) => false,
#[cfg(not(feature = "no_index"))]
Self::StringChar(_, _, _) => false,
2020-06-06 07:06:00 +02:00
}
}
/// Is the `Target` an owned value?
2020-08-08 10:24:10 +02:00
#[inline(always)]
2020-06-06 07:06:00 +02:00
pub fn is_value(&self) -> bool {
match self {
Self::Ref(_) => false,
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-07-31 16:30:23 +02:00
#[cfg(not(feature = "no_object"))]
Self::LockGuard(_) => false,
2020-06-06 07:06:00 +02:00
Self::Value(_) => true,
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_index"))]
2020-06-06 07:06:00 +02:00
Self::StringChar(_, _, _) => false,
2020-05-16 05:42:56 +02:00
}
}
2020-07-31 16:30:23 +02:00
/// Is the `Target` a shared value?
2020-08-08 10:24:10 +02:00
#[inline(always)]
2020-07-31 16:30:23 +02:00
pub fn is_shared(&self) -> bool {
match self {
Self::Ref(r) => r.is_shared(),
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-07-31 16:30:23 +02:00
#[cfg(not(feature = "no_object"))]
Self::LockGuard(_) => true,
Self::Value(r) => r.is_shared(),
#[cfg(not(feature = "no_index"))]
Self::StringChar(_, _, _) => false,
}
}
/// Is the `Target` a specific type?
2020-07-26 09:53:22 +02:00
#[allow(dead_code)]
2020-08-08 10:24:10 +02:00
#[inline(always)]
pub fn is<T: Variant + Clone>(&self) -> bool {
match self {
Target::Ref(r) => r.is::<T>(),
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-07-31 16:30:23 +02:00
#[cfg(not(feature = "no_object"))]
Target::LockGuard((r, _)) => r.is::<T>(),
Target::Value(r) => r.is::<T>(),
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_index"))]
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-08-08 10:24:10 +02:00
#[inline(always)]
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-07-31 12:43:34 +02:00
Self::Ref(r) => r.clone(), // Referenced value is cloned
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-07-31 16:30:23 +02:00
#[cfg(not(feature = "no_object"))]
2020-07-31 12:06:01 +02:00
Self::LockGuard((_, orig)) => orig, // Original value is simply taken
2020-07-31 12:43:34 +02:00
Self::Value(v) => v, // Owned value is simply taken
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_index"))]
2020-06-06 07:06:00 +02:00
Self::StringChar(_, _, ch) => ch, // Character is taken
2020-05-16 05:42:56 +02:00
}
}
/// Get a mutable reference from the `Target`.
2020-08-08 10:24:10 +02:00
#[inline(always)]
2020-05-16 05:42:56 +02:00
pub fn as_mut(&mut self) -> &mut Dynamic {
match self {
2020-06-06 07:06:00 +02:00
Self::Ref(r) => *r,
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-07-31 16:30:23 +02:00
#[cfg(not(feature = "no_object"))]
Self::LockGuard((r, _)) => r.deref_mut(),
2020-06-06 07:06:00 +02:00
Self::Value(ref mut r) => r,
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_index"))]
2020-06-06 07:06:00 +02:00
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`.
/// Position in `EvalAltResult` is `None` and must be set afterwards.
2020-06-01 09:25:22 +02:00
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,
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-07-31 16:30:23 +02:00
#[cfg(not(feature = "no_object"))]
Self::LockGuard((r, _)) => **r = new_val,
2020-06-06 07:06:00 +02:00
Self::Value(_) => {
2020-08-06 04:17:32 +02:00
return EvalAltResult::ErrorAssignmentToUnknownLHS(Position::none()).into();
2020-04-26 12:04:07 +02:00
}
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_index"))]
Self::StringChar(string, index, _) if string.is::<ImmutableString>() => {
let mut s = string.write_lock::<ImmutableString>().unwrap();
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
2020-07-23 04:12:51 +02:00
let mut chars = s.chars().collect::<StaticVec<_>>();
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
}
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_index"))]
Self::StringChar(_, _, _) => 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
}
2020-07-26 09:53:22 +02:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
impl<'a> From<&'a mut Dynamic> for Target<'a> {
2020-08-08 10:24:10 +02:00
#[inline(always)]
fn from(value: &'a mut Dynamic) -> Self {
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-07-31 16:30:23 +02:00
#[cfg(not(feature = "no_object"))]
if value.is_shared() {
2020-07-31 12:06:01 +02:00
// Cloning is cheap for a shared value
let container = value.clone();
return Self::LockGuard((value.write_lock::<Dynamic>().unwrap(), container));
}
Self::Ref(value)
2020-04-26 12:04:07 +02:00
}
}
2020-07-26 09:53:22 +02:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
2020-04-26 12:04:07 +02:00
impl<T: Into<Dynamic>> From<T> for Target<'_> {
2020-08-08 10:24:10 +02:00
#[inline(always)]
2020-04-26 12:04:07 +02:00
fn from(value: T) -> Self {
2020-05-16 05:42:56 +02:00
Self::Value(value.into())
}
}
/// [INTERNALS] A type that holds all the current states of the Engine.
/// Exported under the `internals` feature only.
///
/// ## WARNING
///
/// This type is volatile and may change.
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`.
2020-08-08 10:24:10 +02:00
#[inline(always)]
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,
pub_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, pub_only)?;
if func.is_script() {
Some(func.get_fn_def())
} else {
None
}
}
2020-07-26 09:53:22 +02:00
/// [INTERNALS] A type containing all the limits imposed by the `Engine`.
/// Exported under the `internals` feature only.
///
/// ## WARNING
///
/// This type is volatile and may change.
#[cfg(not(feature = "unchecked"))]
2020-08-23 10:29:32 +02:00
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
2020-07-26 09:53:22 +02:00
pub struct Limits {
/// Maximum levels of call-stack to prevent infinite recursion.
///
/// Defaults to 16 for debug builds and 128 for non-debug builds.
pub max_call_stack_depth: usize,
/// Maximum depth of statements/expressions at global level.
pub max_expr_depth: usize,
/// Maximum depth of statements/expressions in functions.
pub max_function_expr_depth: usize,
/// Maximum number of operations allowed to run.
pub max_operations: u64,
/// Maximum number of modules allowed to load.
pub max_modules: usize,
/// Maximum length of a string.
pub max_string_size: usize,
/// Maximum length of an array.
pub max_array_size: usize,
/// Maximum number of properties in a map.
pub max_map_size: usize,
}
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.
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_module"))]
pub(crate) module_resolver: Option<Box<dyn ModuleResolver>>,
2020-05-13 13:21:42 +02:00
2020-03-27 07:34:01 +01:00
/// A hashmap mapping type names to pretty-print names.
2020-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.
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,
2020-07-26 09:53:22 +02:00
/// Max limits.
#[cfg(not(feature = "unchecked"))]
pub(crate) limits: Limits,
2017-12-20 12:16:14 +01:00
}
2020-07-13 13:38:50 +02:00
impl fmt::Debug for Engine {
2020-08-08 10:24:10 +02:00
#[inline(always)]
2020-07-13 13:38:50 +02:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.id.as_ref() {
Some(id) => write!(f, "Engine({})", id),
None => f.write_str("Engine"),
}
}
}
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-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_module"))]
#[cfg(any(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-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-07-31 16:30:23 +02:00
optimization_level: if cfg!(feature = "no_optimize") {
OptimizationLevel::None
} else {
OptimizationLevel::Simple
},
2020-03-16 05:40:42 +01:00
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "unchecked"))]
limits: Limits {
max_call_stack_depth: MAX_CALL_STACK_DEPTH,
max_expr_depth: MAX_EXPR_DEPTH,
max_function_expr_depth: MAX_FUNCTION_EXPR_DEPTH,
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
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_object"))]
#[inline(always)]
2020-03-30 10:10:50 +02:00
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
}
/// Make setter function
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_object"))]
#[inline(always)]
2020-03-30 10:10:50 +02:00
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
}
2020-04-19 12:33:02 +02:00
/// Print/debug to stdout
2020-07-26 09:53:22 +02:00
fn default_print(_s: &str) {
2020-04-19 12:33:02 +02:00
#[cfg(not(feature = "no_std"))]
2020-06-17 03:54:17 +02:00
#[cfg(not(target_arch = "wasm32"))]
2020-07-26 09:53:22 +02:00
println!("{}", _s);
2020-04-19 12:33:02 +02:00
}
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.
pub fn search_imports<'s>(
mods: &'s Imports,
state: &mut State,
modules: &Box<ModuleRef>,
) -> Result<&'s Module, Box<EvalAltResult>> {
2020-07-29 10:10:06 +02:00
let (root, root_pos) = &modules[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)
2020-08-06 04:17:32 +02:00
.ok_or_else(|| 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.
pub 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>> {
2020-07-29 10:10:06 +02:00
let (root, root_pos) = &modules[0];
2020-06-28 09:49:24 +02:00
// 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)
2020-08-06 04:17:32 +02:00
.ok_or_else(|| EvalAltResult::ErrorModuleNotFound(root.to_string(), *root_pos))?
2020-06-28 09:49:24 +02:00
})
}
2020-08-02 07:33:51 +02:00
/// Search for a variable within the scope or within imports,
/// depending on whether the variable name is qualified.
pub 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(_, _) => {
2020-08-06 04:17:32 +02:00
EvalAltResult::ErrorVariableNotFound(
format!("{}{}", modules, name),
*pos,
2020-08-06 04:17:32 +02:00
)
.into()
}
_ => 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
pub 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 {
2020-08-06 04:17:32 +02:00
return EvalAltResult::ErrorUnboundThis(*pos).into();
2020-06-26 04:39:18 +02:00
}
}
// 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)
2020-08-06 04:17:32 +02:00
.ok_or_else(|| EvalAltResult::ErrorVariableNotFound(name.into(), *pos))?
.0
};
2020-06-06 07:06:00 +02:00
let (val, typ) = scope.get_mut(index);
2020-08-02 07:33:51 +02:00
// Check for data race - probably not necessary because the only place it should conflict is in a method call
// when the object variable is also used as a parameter.
2020-08-03 06:10:20 +02:00
// if cfg!(not(feature = "no_closure")) && val.is_locked() {
2020-08-06 04:17:32 +02:00
// return EvalAltResult::ErrorDataRace(name.into(), *pos).into();
2020-08-02 07:33:51 +02:00
// }
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(),
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_module"))]
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-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-07-31 16:30:23 +02:00
optimization_level: if cfg!(feature = "no_optimize") {
OptimizationLevel::None
} else {
OptimizationLevel::Simple
},
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "unchecked"))]
limits: Limits {
max_call_stack_depth: MAX_CALL_STACK_DEPTH,
max_expr_depth: MAX_EXPR_DEPTH,
max_function_expr_depth: MAX_FUNCTION_EXPR_DEPTH,
max_operations: 0,
max_modules: usize::MAX,
max_string_size: 0,
max_array_size: 0,
max_map_size: 0,
},
}
}
2020-04-26 12:04:07 +02:00
/// Chain-evaluate a dot/index chain.
/// Position in `EvalAltResult` is `None` and must be set afterwards.
2020-07-26 09:53:22 +02:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
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-08-08 10:24:10 +02:00
new_val: Option<Dynamic>,
2020-04-26 12:04:07 +02:00
) -> 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-29 10:10:06 +02:00
let idx_val = idx_values.pop().unwrap();
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-08-01 06:21:15 +02:00
let obj_ptr = &mut self.get_indexed_mut(
state, lib, target, idx_val, idx_pos, false, true, 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,
2020-08-08 10:24:10 +02:00
new_val,
)
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(*pos))
}
// xxx[rhs] = new_val
2020-08-08 10:24:10 +02:00
_ if new_val.is_some() => {
let mut idx_val2 = idx_val.clone();
2020-07-31 17:37:30 +02:00
// `call_setter` is introduced to bypass double mutable borrowing of target
2020-08-01 06:21:15 +02:00
let _call_setter = match self
.get_indexed_mut(state, lib, target, idx_val, pos, true, false, level)
2020-07-31 17:37:30 +02:00
{
// 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
2020-08-08 10:24:10 +02:00
.set_value(new_val.unwrap())
2020-06-29 17:55:28 +02:00
.map_err(|err| err.new_position(rhs.position()))?;
2020-07-31 17:37:30 +02:00
None
}
Err(err) => match *err {
// No index getter - try to call an index setter
2020-08-01 06:21:15 +02:00
#[cfg(not(feature = "no_index"))]
EvalAltResult::ErrorIndexingType(_, _) => Some(new_val.unwrap()),
2020-07-31 17:37:30 +02:00
// Any other error - return
err => return Err(Box::new(err)),
},
};
2020-08-01 06:21:15 +02:00
#[cfg(not(feature = "no_index"))]
if let Some(mut new_val) = _call_setter {
let val = target.as_mut();
let val_type_name = val.type_name();
let args = &mut [val, &mut idx_val2, &mut new_val];
2020-08-01 06:21:15 +02:00
self.exec_fn_call(
state, lib, FN_IDX_SET, 0, args, is_ref, true, false, None, &None,
2020-07-31 17:37:30 +02:00
level,
2020-08-01 06:21:15 +02:00
)
.map_err(|err| match *err {
EvalAltResult::ErrorFunctionNotFound(_, _) => {
EvalAltResult::ErrorIndexingType(
self.map_type_name(val_type_name).into(),
Position::none(),
)
}
err => err,
})?;
}
Ok(Default::default())
2020-06-06 07:06:00 +02:00
}
// xxx[rhs]
_ => self
2020-08-01 06:21:15 +02:00
.get_indexed_mut(state, lib, target, idx_val, pos, false, true, 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-30 12:18:28 +02:00
let ((name, native, _, pos), _, hash, _, def_val) = x.as_ref();
let def_val = def_val.map(Into::<Dynamic>::into);
self.make_method_call(
state, lib, name, *hash, target, idx_val, &def_val, *native, false,
level,
)
.map_err(|err| err.new_position(*pos))
}
// xxx.module::fn_name(...) - syntax error
Expr::FnCall(_) => unreachable!(),
// {xxx:map}.id = ???
2020-08-08 10:24:10 +02:00
Expr::Property(x) if target.is::<Map>() && new_val.is_some() => {
let ((prop, _, _), pos) = x.as_ref();
let index = prop.clone().into();
2020-08-01 06:21:15 +02:00
let mut val = self
.get_indexed_mut(state, lib, target, index, *pos, true, false, level)?;
2020-08-08 10:24:10 +02:00
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-08-01 06:21:15 +02:00
let val = self.get_indexed_mut(
state, lib, target, index, *pos, false, false, level,
)?;
2020-05-11 17:48:50 +02:00
Ok((val.clone_into_dynamic(), false))
}
// xxx.id = ???
2020-08-08 10:24:10 +02:00
Expr::Property(x) if new_val.is_some() => {
let ((_, _, setter), pos) = x.as_ref();
2020-08-08 10:24:10 +02:00
let mut new_val = new_val;
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, 0, &mut args, is_ref, true, false, None, &None,
level,
2020-06-26 04:39:18 +02:00
)
.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, 0, &mut args, is_ref, true, false, None, &None,
level,
2020-06-26 04:39:18 +02:00
)
.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, _, _), pos) = p.as_ref();
2020-07-09 16:21:07 +02:00
let index = prop.clone().into();
2020-08-01 06:21:15 +02:00
self.get_indexed_mut(
state, lib, target, index, *pos, false, true, level,
)?
2020-07-09 16:21:07 +02:00
}
// {xxx:map}.fn_name(arg_expr_list)[expr] | {xxx:map}.fn_name(arg_expr_list).expr
Expr::FnCall(x) if x.1.is_none() => {
2020-07-30 12:18:28 +02:00
let ((name, native, _, pos), _, hash, _, def_val) = x.as_ref();
let def_val = def_val.map(Into::<Dynamic>::into);
let (val, _) = self
.make_method_call(
state, lib, name, *hash, target, idx_val, &def_val,
*native, false, level,
)
.map_err(|err| err.new_position(*pos))?;
2020-07-09 16:21:07 +02:00
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,
2020-08-08 10:24:10 +02:00
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) => {
let (sub_lhs, expr, _) = x.as_ref();
2020-07-09 16:21:07 +02:00
match sub_lhs {
// xxx.prop[expr] | xxx.prop.expr
Expr::Property(p) => {
let ((_, getter, setter), pos) = p.as_ref();
2020-07-09 16:21:07 +02:00
let arg_values = &mut [target.as_mut(), &mut Default::default()];
let args = &mut arg_values[..1];
let (mut val, updated) = self
.exec_fn_call(
2020-07-30 12:18:28 +02:00
state, lib, getter, 0, args, is_ref, true, false, None,
&None, level,
2020-07-09 16:21:07 +02:00
)
.map_err(|err| err.new_position(*pos))?;
let val = &mut val;
let (result, may_be_changed) = self
.eval_dot_index_chain_helper(
state,
lib,
this_ptr,
&mut val.into(),
expr,
idx_values,
next_chain,
level,
2020-08-08 10:24:10 +02:00
new_val,
2020-07-09 16:21:07 +02:00
)
.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(
2020-07-30 12:18:28 +02:00
state, lib, setter, 0, arg_values, is_ref, true, false,
None, &None, level,
2020-07-09 16:21:07 +02:00
)
.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() => {
2020-07-30 12:18:28 +02:00
let ((name, native, _, pos), _, hash, _, def_val) = x.as_ref();
let def_val = def_val.map(Into::<Dynamic>::into);
let (mut val, _) = self
.make_method_call(
state, lib, name, *hash, target, idx_val, &def_val,
*native, false, level,
)
.map_err(|err| err.new_position(*pos))?;
2020-07-09 16:21:07 +02:00
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,
2020-08-08 10:24:10 +02:00
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
2020-08-06 04:17:32 +02:00
_ => EvalAltResult::ErrorDotExpr("".into(), rhs.position()).into(),
}
2020-04-26 12:04:07 +02:00
}
_ => unreachable!(),
}
}
2020-04-26 15:48:49 +02:00
/// Evaluate a dot/index chain.
2020-07-26 09:53:22 +02:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
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() => {
2020-08-06 04:17:32 +02:00
return EvalAltResult::ErrorAssignmentToConstant(var_name.to_string(), pos)
.into();
}
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() => {
2020-08-06 04:17:32 +02:00
return EvalAltResult::ErrorAssignmentToUnknownLHS(expr.position()).into();
2020-04-26 12:04:07 +02:00
}
// {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-07-26 09:53:22 +02:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
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!(),
2020-07-29 10:10:06 +02:00
Expr::Property(_) => idx_values.push(().into()), // 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-07-26 09:53:22 +02:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
2020-04-26 12:04:07 +02:00
fn get_indexed_mut<'a>(
&self,
state: &mut State,
2020-07-26 09:53:22 +02:00
_lib: &Module,
2020-06-06 07:06:00 +02:00
target: &'a mut Target,
2020-08-08 10:24:10 +02:00
idx: Dynamic,
2020-04-26 12:04:07 +02:00
idx_pos: Position,
2020-07-26 09:53:22 +02:00
_create: bool,
2020-08-01 06:21:15 +02:00
_indexers: bool,
2020-07-26 09:53:22 +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-09-20 09:55:11 +02:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
2020-06-06 07:06:00 +02:00
let is_ref = target.is_ref();
2020-07-26 09:53:22 +02:00
2020-06-06 07:06:00 +02:00
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-08-08 10:24:10 +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-08-06 04:17:32 +02:00
EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos).into()
})
} else {
2020-08-06 04:17:32 +02:00
EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos).into()
}
}
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-07-26 09:53:22 +02:00
Ok(if _create {
2020-08-08 10:24:10 +02:00
let index = idx
.take_immutable_string()
2020-05-25 07:44:28 +02:00
.map_err(|_| EvalAltResult::ErrorStringIndexExpr(idx_pos))?;
2020-09-20 20:07:43 +02:00
map.entry(index).or_insert_with(Default::default).into()
2020-04-26 12:04:07 +02:00
} else {
2020-08-08 10:24:10 +02:00
let index = idx
.read_lock::<ImmutableString>()
2020-05-25 07:44:28 +02:00
.ok_or_else(|| EvalAltResult::ErrorStringIndexExpr(idx_pos))?;
map.get_mut(&*index)
.map(Target::from)
.unwrap_or_else(|| Target::from(()))
2020-04-26 12:04:07 +02:00
})
}
2020-04-10 06:16:39 +02:00
#[cfg(not(feature = "no_index"))]
2020-04-26 12:04:07 +02:00
Dynamic(Union::Str(s)) => {
// val_string[idx]
2020-05-11 17:48:50 +02:00
let chars_len = s.chars().count();
2020-08-08 10:24:10 +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(|| {
2020-08-06 04:17:32 +02:00
EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos)
})?;
2020-05-16 05:42:56 +02:00
Ok(Target::StringChar(val, offset, ch.into()))
} else {
2020-08-06 04:17:32 +02:00
EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos).into()
}
}
2020-03-29 17:53:35 +02:00
#[cfg(not(feature = "no_index"))]
2020-08-01 06:21:15 +02:00
_ if _indexers => {
let type_name = val.type_name();
2020-08-08 10:24:10 +02:00
let mut idx = idx;
let args = &mut [val, &mut idx];
2020-06-26 04:39:18 +02:00
self.exec_fn_call(
state, _lib, FN_IDX_GET, 0, args, is_ref, true, false, None, &None, _level,
2020-06-26 04:39:18 +02:00
)
.map(|(v, _)| v.into())
2020-07-25 03:55:33 +02:00
.map_err(|err| match *err {
EvalAltResult::ErrorFunctionNotFound(_, _) => Box::new(
EvalAltResult::ErrorIndexingType(type_name.into(), Position::none()),
),
_ => err,
2020-06-26 04:39:18 +02:00
})
2020-05-05 14:38:48 +02:00
}
2020-08-06 04:17:32 +02:00
_ => EvalAltResult::ErrorIndexingType(
self.map_type_name(val.type_name()).into(),
Position::none(),
2020-08-06 04:17:32 +02:00
)
.into(),
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 = "==";
2020-04-12 17:00:06 +02:00
2020-05-06 17:52:47 +02:00
// Call the `==` operator to compare each value
let def_value = Some(false.into());
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-05-09 10:15:50 +02:00
2020-07-30 12:18:28 +02:00
// Qualifiers (none) + function name + number of arguments + argument `TypeId`'s.
let hash =
calc_fn_hash(empty(), op, args.len(), args.iter().map(|a| a.type_id()));
2020-04-30 16:52:36 +02:00
2020-07-31 06:11:16 +02:00
if self
.call_native_fn(state, lib, op, hash, args, false, false, &def_value)
2020-07-31 06:11:16 +02:00
.map_err(|err| err.new_position(rhs.position()))?
.0
.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
}
Ok(def_value.unwrap())
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
Dynamic(Union::Str(s)) => Ok(rhs_value.contains_key(&s).into()),
Dynamic(Union::Char(c)) => Ok(rhs_value.contains_key(&c.to_string()).into()),
2020-08-06 04:17:32 +02:00
_ => EvalAltResult::ErrorInExpr(lhs.position()).into(),
2020-04-30 16:52:36 +02:00
},
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()),
2020-08-06 04:17:32 +02:00
_ => EvalAltResult::ErrorInExpr(lhs.position()).into(),
2020-04-30 16:52:36 +02:00
},
2020-08-06 04:17:32 +02:00
_ => EvalAltResult::ErrorInExpr(rhs.position()).into(),
2020-04-06 11:47:34 +02:00
}
}
/// Evaluate an expression
pub(crate) 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-07-22 17:12:09 +02:00
Expr::FnPointer(x) => Ok(FnPtr::new_unchecked(x.0.clone(), Default::default()).into()),
2020-06-26 04:39:18 +02:00
Expr::Variable(x) if (x.0).0 == KEYWORD_THIS => {
2020-07-21 16:32:24 +02:00
if let Some(val) = this_ptr {
Ok(val.clone())
2020-06-26 04:39:18 +02:00
} else {
2020-08-06 04:17:32 +02:00
EvalAltResult::ErrorUnboundThis((x.0).1).into()
2020-06-26 04:39:18 +02:00
}
}
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() => {
2020-08-08 10:24:10 +02:00
let value = rhs_val.flatten();
2020-08-03 06:10:20 +02:00
if cfg!(not(feature = "no_closure")) && lhs_ptr.is_shared() {
2020-08-08 10:24:10 +02:00
*lhs_ptr.write_lock::<Dynamic>().unwrap() = value;
} else {
2020-08-08 10:24:10 +02:00
*lhs_ptr = value;
2020-07-31 10:39:38 +02:00
}
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);
2020-09-21 10:15:52 +02:00
match self
.global_module
.get_fn(hash_fn, false)
.or_else(|| self.packages.get_fn(hash_fn, false))
{
2020-09-21 10:15:52 +02:00
// op= function registered as method
Some(func) if func.is_method() => {
let mut lock_guard;
let lhs_ptr_inner;
if cfg!(not(feature = "no_closure")) && lhs_ptr.is_shared() {
lock_guard = lhs_ptr.write_lock::<Dynamic>().unwrap();
lhs_ptr_inner = lock_guard.deref_mut();
} else {
lhs_ptr_inner = lhs_ptr;
}
let args = &mut [lhs_ptr_inner, &mut rhs_val];
2020-07-31 10:39:38 +02:00
// Overriding exact implementation
2020-09-21 10:15:52 +02:00
if func.is_plugin_fn() {
func.get_plugin_fn().call(args)?;
} else {
func.get_native_fn()(self, lib, args)?;
}
}
2020-09-21 10:15:52 +02:00
// Built-in op-assignment function
_ if run_builtin_op_assignment(op, lhs_ptr, &rhs_val)?.is_some() => {}
// Not built-in: expand to `var = var op rhs`
_ => {
let op = &op[..op.len() - 1]; // extract operator without =
2020-07-30 12:18:28 +02:00
2020-09-21 10:15:52 +02:00
// Clone the LHS value
let args = &mut [&mut lhs_ptr.clone(), &mut rhs_val];
2020-07-30 12:18:28 +02:00
2020-09-21 10:15:52 +02:00
// Run function
let (value, _) = self
.exec_fn_call(
state, lib, op, 0, args, false, false, false, None, &None,
2020-09-21 10:15:52 +02:00
level,
)
.map_err(|err| err.new_position(*op_pos))?;
2020-09-21 10:15:52 +02:00
let value = value.flatten();
if cfg!(not(feature = "no_closure")) && lhs_ptr.is_shared() {
*lhs_ptr.write_lock::<Dynamic>().unwrap() = value;
} else {
*lhs_ptr = value;
}
2020-07-31 10:39:38 +02:00
}
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)?;
2020-07-26 09:53:22 +02:00
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 args = &mut [
&mut self.eval_expr(scope, mods, state, lib, this_ptr, lhs_expr, level)?,
&mut rhs_val,
];
self.exec_fn_call(
state, lib, op, 0, args, false, false, false, None, &None, level,
)
.map(|(v, _)| v)
.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(
2020-07-26 09:53:22 +02:00
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(
2020-07-26 09:53:22 +02:00
scope, mods, state, lib, this_ptr, lhs_expr, level, _new_val,
)?;
Ok(Default::default())
}
// Error assignment to constant
2020-08-06 04:17:32 +02:00
expr if expr.is_constant() => EvalAltResult::ErrorAssignmentToConstant(
expr.get_constant_str(),
expr.position(),
2020-08-06 04:17:32 +02:00
)
.into(),
// Syntax error
expr => EvalAltResult::ErrorAssignmentToUnknownLHS(expr.position()).into(),
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-07-30 12:18:28 +02:00
let ((name, native, capture, pos), _, hash, args_expr, def_val) = x.as_ref();
let def_val = def_val.map(Into::<Dynamic>::into);
self.make_function_call(
scope, mods, state, lib, this_ptr, name, args_expr, &def_val, *hash, *native,
2020-07-30 12:18:28 +02:00
false, *capture, level,
2020-05-23 12:59:28 +02:00
)
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-07-30 12:18:28 +02:00
let ((name, _, capture, pos), modules, hash, args_expr, def_val) = x.as_ref();
self.make_qualified_function_call(
scope, mods, state, lib, this_ptr, modules, name, args_expr, *def_val, *hash,
2020-07-30 12:18:28 +02:00
*capture, level,
)
.map_err(|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-09 13:54:28 +02:00
Expr::Custom(x) => {
let func = (x.0).1.as_ref();
2020-07-23 04:12:51 +02:00
let ep = (x.0).0.iter().map(|e| e.into()).collect::<StaticVec<_>>();
2020-07-22 07:08:51 +02:00
let mut context = EvalContext {
mods,
state,
lib,
this_ptr,
level,
};
func(self, &mut context, scope, ep.as_ref())
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
///
///
/// # Safety
///
/// This method uses some unsafe code, mainly for avoiding cloning of local variable names via
/// direct lifetime casting.
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()
2020-08-06 04:17:32 +02:00
.map_err(|_| EvalAltResult::ErrorLogicGuard(expr.position()).into())
.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()),
2020-08-06 04:17:32 +02:00
Err(_) => return EvalAltResult::ErrorLogicGuard(expr.position()).into(),
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(x) => loop {
match self.eval_stmt(scope, mods, state, lib, this_ptr, &x.0, 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-08-08 10:24:10 +02:00
for iter_value in func(iter_type) {
let (loop_var, _) = scope.get_mut(index);
2020-08-03 17:11:38 +02:00
2020-08-08 10:24:10 +02:00
let value = iter_value.flatten();
if cfg!(not(feature = "no_closure")) && loop_var.is_shared() {
*loop_var.write_lock().unwrap() = value;
2020-08-03 17:11:38 +02:00
} else {
2020-08-08 10:24:10 +02:00
*loop_var = value;
2020-08-03 17:11:38 +02:00
}
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 {
2020-08-06 04:17:32 +02:00
EvalAltResult::ErrorFor(x.1.position()).into()
}
}
2020-03-01 17:11:00 +01:00
2020-04-01 10:22:18 +02:00
// Continue statement
2020-08-06 04:17:32 +02:00
Stmt::Continue(pos) => EvalAltResult::ErrorLoopBreak(false, *pos).into(),
2020-04-01 10:22:18 +02:00
2020-03-06 16:49:52 +01:00
// Break statement
2020-08-06 04:17:32 +02:00
Stmt::Break(pos) => EvalAltResult::ErrorLoopBreak(true, *pos).into(),
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 => {
let expr = x.1.as_ref().unwrap();
2020-08-06 04:17:32 +02:00
EvalAltResult::Return(
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?,
2020-05-09 18:19:13 +02:00
(x.0).1,
2020-08-06 04:17:32 +02:00
)
.into()
}
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 => {
2020-08-06 04:17:32 +02:00
EvalAltResult::Return(Default::default(), (x.0).1).into()
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 expr = x.1.as_ref().unwrap();
let val = self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?;
2020-08-06 04:17:32 +02:00
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-08-06 04:17:32 +02:00
)
.into()
}
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 => {
2020-08-06 04:17:32 +02:00
EvalAltResult::ErrorRuntime("".into(), (x.0).1).into()
}
Stmt::ReturnWithVal(_) => unreachable!(),
2020-03-06 16:49:52 +01:00
// Let statement
Stmt::Let(x) if x.1.is_some() => {
let ((var_name, _), expr, _) = x.as_ref();
let expr = expr.as_ref().unwrap();
let val = self
.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
2020-08-08 10:24:10 +02:00
.flatten();
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) => {
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() => {
let ((var_name, _), expr, _) = x.as_ref();
let val = self
.eval_expr(scope, mods, state, lib, this_ptr, &expr, level)?
2020-08-08 10:24:10 +02:00
.flatten();
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
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_module"))]
Stmt::Import(x) => {
let (expr, alias, _pos) = x.as_ref();
2020-05-15 15:40:54 +02:00
// Guard against too many modules
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "unchecked"))]
if state.modules >= self.limits.max_modules {
2020-08-06 04:17:32 +02:00
return EvalAltResult::ErrorTooManyModules(*_pos).into();
}
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>()
{
2020-07-04 16:53:00 +02:00
if let Some(resolver) = &self.module_resolver {
let mut module = resolver.resolve(self, &path, expr.position())?;
if let Some((name, _)) = alias {
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 {
2020-08-06 04:17:32 +02:00
Err(
EvalAltResult::ErrorModuleNotFound(path.to_string(), expr.position())
.into(),
)
}
} else {
2020-08-06 04:17:32 +02:00
EvalAltResult::ErrorImportExpr(expr.position()).into()
2020-05-04 13:36:58 +02:00
}
}
2020-05-08 10:49:24 +02:00
// Export statement
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_module"))]
Stmt::Export(x) => {
for ((id, id_pos), rename) in x.0.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) {
2020-07-21 16:32:24 +02:00
let alias = rename.as_ref().map(|(n, _)| n).unwrap_or_else(|| id);
scope.set_entry_alias(index, alias.clone());
2020-05-11 17:48:50 +02:00
} else {
2020-08-06 04:17:32 +02:00
return EvalAltResult::ErrorVariableNotFound(id.into(), *id_pos).into();
2020-05-08 10:49:24 +02:00
}
}
Ok(Default::default())
}
2020-08-03 06:10:20 +02:00
// Share statement
#[cfg(not(feature = "no_closure"))]
Stmt::Share(x) => {
let (var_name, _) = x.as_ref();
match scope.get_index(var_name) {
Some((index, ScopeEntryType::Normal)) => {
let (val, _) = scope.get_mut(index);
if !val.is_shared() {
// Replace the variable with a shared value.
*val = mem::take(val).into_shared();
}
}
_ => (),
}
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-07-31 16:30:23 +02:00
/// Check a result to ensure that the data size is within allowable limit.
/// Position in `EvalAltResult` may be None and should be set afterwards.
2020-07-26 09:53:22 +02:00
#[cfg(feature = "unchecked")]
#[inline(always)]
fn check_data_size(
&self,
result: Result<Dynamic, Box<EvalAltResult>>,
) -> Result<Dynamic, Box<EvalAltResult>> {
2020-07-31 16:30:23 +02:00
result
2020-07-26 09:53:22 +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-07-26 09:53:22 +02:00
#[cfg(not(feature = "unchecked"))]
2020-06-14 16:44:59 +02:00
fn check_data_size(
&self,
result: Result<Dynamic, Box<EvalAltResult>>,
) -> Result<Dynamic, Box<EvalAltResult>> {
// If no data size limits, just return
2020-07-26 09:53:22 +02:00
if self.limits.max_string_size + self.limits.max_array_size + self.limits.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
2020-07-26 09:53:22 +02:00
Ok(Dynamic(Union::Str(_))) if self.limits.max_string_size > 0 => (),
2020-06-14 16:44:59 +02:00
// Array with limit
2020-06-13 18:09:16 +02:00
#[cfg(not(feature = "no_index"))]
2020-07-26 09:53:22 +02:00
Ok(Dynamic(Union::Array(_))) if self.limits.max_array_size > 0 => (),
2020-06-14 16:44:59 +02:00
// Map with limit
2020-06-13 18:09:16 +02:00
#[cfg(not(feature = "no_object"))]
2020-07-26 09:53:22 +02:00
Ok(Dynamic(Union::Map(_))) if self.limits.max_map_size > 0 => (),
2020-06-14 16:44:59 +02:00
// 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
2020-07-26 09:53:22 +02:00
if s > self.limits.max_string_size {
2020-08-06 04:17:32 +02:00
EvalAltResult::ErrorDataTooLarge(
2020-06-14 08:25:47 +02:00
"Length of string".to_string(),
2020-07-26 09:53:22 +02:00
self.limits.max_string_size,
2020-06-14 08:25:47 +02:00
s,
Position::none(),
2020-08-06 04:17:32 +02:00
)
.into()
2020-07-26 09:53:22 +02:00
} else if arr > self.limits.max_array_size {
2020-08-06 04:17:32 +02:00
EvalAltResult::ErrorDataTooLarge(
"Size of array".to_string(),
2020-07-26 09:53:22 +02:00
self.limits.max_array_size,
2020-06-14 08:25:47 +02:00
arr,
Position::none(),
2020-08-06 04:17:32 +02:00
)
.into()
2020-07-26 09:53:22 +02:00
} else if map > self.limits.max_map_size {
2020-08-06 04:17:32 +02:00
EvalAltResult::ErrorDataTooLarge(
2020-06-14 08:25:47 +02:00
"Number of properties in object map".to_string(),
2020-07-26 09:53:22 +02:00
self.limits.max_map_size,
2020-06-14 08:25:47 +02:00
map,
Position::none(),
2020-08-06 04:17:32 +02:00
)
.into()
2020-06-14 08:25:47 +02:00
} 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.
/// Position in `EvalAltResult` is `None` and must be set afterwards.
pub(crate) 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
2020-07-26 09:53:22 +02:00
if self.limits.max_operations > 0 && state.operations > self.limits.max_operations {
2020-08-06 04:17:32 +02:00
return EvalAltResult::ErrorTooManyOperations(Position::none()).into();
}
// 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-08-06 04:17:32 +02:00
return EvalAltResult::ErrorTerminated(Position::none()).into();
}
}
Ok(())
}
/// Map a type_name into a pretty-print name
2020-08-08 10:24:10 +02:00
#[inline(always)]
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-09-20 20:07:43 +02:00
.unwrap_or_else(|| map_std_type_name(name))
2020-03-02 16:16:19 +01:00
}
2016-03-01 15:40:48 +01:00
}