rhai/src/engine.rs

2575 lines
98 KiB
Rust
Raw Normal View History

2020-11-20 09:52:28 +01:00
//! Main module defining the script evaluation [`Engine`].
2016-02-29 22:43:45 +01:00
2020-12-22 09:45:56 +01:00
use crate::ast::{Expr, FnCallExpr, Ident, ReturnType, Stmt};
use crate::dynamic::{map_std_type_name, AccessMode, Union, Variant};
use crate::fn_call::run_builtin_op_assignment;
2020-12-12 03:10:27 +01:00
use crate::fn_native::{
2020-12-12 04:47:18 +01:00
CallableFunction, IteratorFn, OnDebugCallback, OnPrintCallback, OnProgressCallback,
OnVarCallback,
2020-12-12 03:10:27 +01:00
};
2021-01-08 17:40:44 +01:00
use crate::module::NamespaceRef;
2020-11-16 16:32:44 +01:00
use crate::optimize::OptimizationLevel;
2020-12-22 15:36:36 +01:00
use crate::packages::{Package, StandardPackage};
2020-06-29 17:55:28 +02:00
use crate::r#unsafe::unsafe_cast_var_name_to_lifetime;
2020-03-17 19:26:11 +01:00
use crate::stdlib::{
2020-11-16 09:28:04 +01:00
any::{type_name, TypeId},
2020-10-28 12:11:17 +01:00
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,
2020-11-13 11:32:18 +01:00
hash::{Hash, Hasher},
2020-12-26 06:05:57 +01:00
iter::{empty, once, FromIterator},
2020-12-26 16:21:16 +01:00
num::{NonZeroU64, NonZeroU8, NonZeroUsize},
2020-08-02 07:33:51 +02:00
ops::DerefMut,
2020-03-17 19:26:11 +01:00
string::{String, ToString},
2020-03-10 03:07:44 +01:00
};
2020-11-16 16:10:14 +01:00
use crate::syntax::CustomSyntax;
2020-12-18 16:47:17 +01:00
use crate::utils::{get_hasher, StraightHasherBuilder};
2020-11-16 16:10:14 +01:00
use crate::{
2021-01-08 17:40:44 +01:00
calc_native_fn_hash, Dynamic, EvalAltResult, FnPtr, ImmutableString, Module, Position, Scope,
Shared, StaticVec,
2020-11-16 16:10:14 +01:00
};
#[cfg(not(feature = "no_index"))]
use crate::Array;
2020-03-04 15:00:01 +01:00
2020-11-15 05:07:35 +01:00
#[cfg(not(feature = "no_index"))]
pub const TYPICAL_ARRAY_SIZE: usize = 8; // Small arrays are typical
#[cfg(not(feature = "no_object"))]
use crate::Map;
2020-03-29 17:53:35 +02:00
2020-11-15 05:07:35 +01:00
#[cfg(not(feature = "no_object"))]
pub const TYPICAL_MAP_SIZE: usize = 8; // Small maps are typical
2020-11-25 02:36:06 +01:00
/// _(INTERNALS)_ A stack of imported [modules][Module].
/// Exported under the `internals` feature only.
///
2021-01-02 16:30:10 +01:00
/// # WARNING
///
/// This type is volatile and may change.
2020-10-02 12:52:18 +02:00
//
2020-11-01 16:42:00 +01:00
// # Implementation Notes
//
2021-01-02 16:30:10 +01:00
// We cannot use Cow<str> here because `eval` may load a [module][Module] and
2020-11-25 02:36:06 +01:00
// the module name will live beyond the AST of the eval script text.
// The best we can do is a shared reference.
2020-11-01 16:42:00 +01:00
#[derive(Debug, Clone, Default)]
2020-12-22 15:36:36 +01:00
pub struct Imports(StaticVec<(ImmutableString, Shared<Module>)>);
2020-11-01 16:42:00 +01:00
impl Imports {
2020-11-25 02:36:06 +01:00
/// Get the length of this stack of imported [modules][Module].
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-11-01 16:42:00 +01:00
pub fn len(&self) -> usize {
2020-12-22 15:36:36 +01:00
self.0.len()
2020-11-01 16:42:00 +01:00
}
2020-11-25 02:36:06 +01:00
/// Is this stack of imported [modules][Module] empty?
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-11-07 16:33:21 +01:00
pub fn is_empty(&self) -> bool {
2020-12-22 15:36:36 +01:00
self.0.is_empty()
2020-11-07 16:33:21 +01:00
}
2020-11-25 02:36:06 +01:00
/// Get the imported [modules][Module] at a particular index.
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-11-07 16:33:21 +01:00
pub fn get(&self, index: usize) -> Option<Shared<Module>> {
2020-12-22 15:36:36 +01:00
self.0.get(index).map(|(_, m)| m).cloned()
2020-11-01 16:42:00 +01:00
}
2020-11-25 02:36:06 +01:00
/// Get the index of an imported [modules][Module] by name.
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-11-01 16:42:00 +01:00
pub fn find(&self, name: &str) -> Option<usize> {
2020-12-22 15:36:36 +01:00
self.0
.iter()
.enumerate()
.rev()
.find(|(_, (key, _))| key.as_str() == name)
.map(|(index, _)| index)
2020-11-01 16:42:00 +01:00
}
2020-11-25 02:36:06 +01:00
/// Push an imported [modules][Module] onto the stack.
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-11-07 16:33:21 +01:00
pub fn push(&mut self, name: impl Into<ImmutableString>, module: impl Into<Shared<Module>>) {
2020-12-22 15:36:36 +01:00
self.0.push((name.into(), module.into()));
2020-11-01 16:42:00 +01:00
}
2020-11-25 02:36:06 +01:00
/// Truncate the stack of imported [modules][Module] to a particular length.
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-11-01 16:42:00 +01:00
pub fn truncate(&mut self, size: usize) {
2020-12-22 15:36:36 +01:00
self.0.truncate(size);
2020-11-01 16:42:00 +01:00
}
2020-11-25 02:36:06 +01:00
/// Get an iterator to this stack of imported [modules][Module] in reverse order.
2020-11-01 16:42:00 +01:00
#[allow(dead_code)]
2020-12-29 03:41:20 +01:00
#[inline(always)]
2021-01-01 10:05:06 +01:00
pub fn iter(&self) -> impl Iterator<Item = (&str, &Module)> {
2020-12-22 15:36:36 +01:00
self.0
.iter()
.rev()
.map(|(name, module)| (name.as_str(), module.as_ref()))
2020-11-09 14:52:23 +01:00
}
2020-11-25 02:36:06 +01:00
/// Get an iterator to this stack of imported [modules][Module] in reverse order.
2020-11-09 14:52:23 +01:00
#[allow(dead_code)]
2020-12-29 03:41:20 +01:00
#[inline(always)]
2021-01-01 10:05:06 +01:00
pub(crate) fn iter_raw(&self) -> impl Iterator<Item = (&ImmutableString, &Shared<Module>)> {
2020-12-22 15:36:36 +01:00
self.0.iter().rev().map(|(n, m)| (n, m))
2020-11-01 16:42:00 +01:00
}
2020-11-25 02:36:06 +01:00
/// Get a consuming iterator to this stack of imported [modules][Module] in reverse order.
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-11-17 05:23:53 +01:00
pub fn into_iter(self) -> impl Iterator<Item = (ImmutableString, Shared<Module>)> {
2020-12-22 15:36:36 +01:00
self.0.into_iter().rev()
2020-11-09 14:52:23 +01:00
}
2020-11-25 02:36:06 +01:00
/// Add a stream of imported [modules][Module].
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-11-17 05:23:53 +01:00
pub fn extend(&mut self, stream: impl Iterator<Item = (ImmutableString, Shared<Module>)>) {
2020-12-22 15:36:36 +01:00
self.0.extend(stream)
2020-11-01 16:42:00 +01:00
}
2020-11-25 02:36:06 +01:00
/// Does the specified function hash key exist in this stack of imported [modules][Module]?
#[allow(dead_code)]
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-12-24 09:32:43 +01:00
pub fn contains_fn(&self, hash: NonZeroU64) -> bool {
self.0.iter().any(|(_, m)| m.contains_qualified_fn(hash))
}
/// Get specified function via its hash key.
2020-12-29 03:41:20 +01:00
#[inline(always)]
2021-01-02 17:20:13 +01:00
pub fn get_fn(
&self,
hash: NonZeroU64,
) -> Option<(&CallableFunction, Option<&ImmutableString>)> {
2020-12-24 09:32:43 +01:00
self.0
.iter()
.rev()
2021-01-02 17:20:13 +01:00
.find_map(|(_, m)| m.get_qualified_fn(hash).map(|f| (f, m.id_raw())))
}
2021-01-06 06:46:53 +01:00
/// Does the specified [`TypeId`][std::any::TypeId] iterator exist in this stack of
/// imported [modules][Module]?
#[allow(dead_code)]
2020-12-29 03:41:20 +01:00
#[inline(always)]
pub fn contains_iter(&self, id: TypeId) -> bool {
2020-12-22 15:36:36 +01:00
self.0.iter().any(|(_, m)| m.contains_qualified_iter(id))
}
2020-11-25 02:36:06 +01:00
/// Get the specified [`TypeId`][std::any::TypeId] iterator.
2020-12-29 03:41:20 +01:00
#[inline(always)]
pub fn get_iter(&self, id: TypeId) -> Option<IteratorFn> {
self.0
2020-12-22 15:36:36 +01:00
.iter()
.rev()
.find_map(|(_, m)| m.get_qualified_iter(id))
}
2020-11-01 16:42:00 +01:00
}
2020-12-26 06:05:57 +01:00
impl<'a, T: IntoIterator<Item = (&'a ImmutableString, &'a Shared<Module>)>> From<T> for Imports {
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-12-26 06:05:57 +01:00
fn from(value: T) -> Self {
Self(
value
.into_iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
)
}
}
impl FromIterator<(ImmutableString, Shared<Module>)> for Imports {
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-12-26 06:05:57 +01:00
fn from_iter<T: IntoIterator<Item = (ImmutableString, Shared<Module>)>>(iter: T) -> Self {
Self(iter.into_iter().collect())
}
}
#[cfg(not(feature = "unchecked"))]
2020-04-07 17:13:47 +02:00
#[cfg(debug_assertions)]
2020-12-29 05:29:45 +01:00
#[cfg(not(feature = "no_function"))]
2020-10-21 04:10:46 +02:00
pub const MAX_CALL_STACK_DEPTH: usize = 8;
#[cfg(not(feature = "unchecked"))]
#[cfg(debug_assertions)]
pub const MAX_EXPR_DEPTH: usize = 32;
#[cfg(not(feature = "unchecked"))]
#[cfg(not(feature = "no_function"))]
#[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))]
2020-12-29 05:29:45 +01:00
#[cfg(not(feature = "no_function"))]
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(feature = "no_function"))]
#[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-10-03 10:25:58 +02:00
#[cfg(not(feature = "no_closure"))]
2020-07-31 12:43:34 +02:00
pub const KEYWORD_IS_SHARED: &str = "is_shared";
2020-10-03 10:25:58 +02:00
pub const KEYWORD_IS_DEF_VAR: &str = "is_def_var";
2020-06-26 04:39:18 +02:00
pub const KEYWORD_THIS: &str = "this";
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-11-16 09:28:04 +01:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
2020-11-08 16:00:37 +01:00
pub const OP_EQUALS: &str = "==";
2020-03-03 10:28:38 +01:00
2021-01-02 16:30:10 +01:00
/// 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 {
2021-01-02 16:30:10 +01:00
/// Not a chaining type.
NonChaining,
/// Indexing.
Index,
2021-01-02 16:30:10 +01:00
/// Dotting.
Dot,
}
2021-01-02 16:30:10 +01:00
/// Value of a chaining argument.
2020-10-15 17:30:30 +02:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
2021-01-02 16:30:10 +01:00
#[derive(Debug, Clone, Hash)]
pub enum ChainArgument {
/// Dot-property access.
Property,
/// Arguments to a dot-function call.
2020-10-15 17:30:30 +02:00
FnCallArgs(StaticVec<Dynamic>),
2021-01-02 16:30:10 +01:00
/// Index value.
IndexValue(Dynamic),
2020-10-15 17:30:30 +02:00
}
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
2021-01-02 16:30:10 +01:00
impl ChainArgument {
2020-10-15 17:30:30 +02:00
/// Return the `Dynamic` value.
///
/// # Panics
///
2021-01-02 16:30:10 +01:00
/// Panics if not `ChainArgument::IndexValue`.
2020-12-29 03:41:20 +01:00
#[inline(always)]
#[cfg(not(feature = "no_index"))]
2021-01-02 16:30:10 +01:00
pub fn as_index_value(self) -> Dynamic {
2020-10-15 17:30:30 +02:00
match self {
2021-01-02 16:30:10 +01:00
Self::Property | Self::FnCallArgs(_) => panic!("expecting ChainArgument::IndexValue"),
Self::IndexValue(value) => value,
2020-10-15 17:30:30 +02:00
}
}
/// Return the `StaticVec<Dynamic>` value.
///
/// # Panics
///
2021-01-02 16:30:10 +01:00
/// Panics if not `ChainArgument::FnCallArgs`.
2020-12-29 03:41:20 +01:00
#[inline(always)]
#[cfg(not(feature = "no_object"))]
2020-10-15 17:30:30 +02:00
pub fn as_fn_call_args(self) -> StaticVec<Dynamic> {
match self {
2021-01-02 16:30:10 +01:00
Self::Property | Self::IndexValue(_) => panic!("expecting ChainArgument::FnCallArgs"),
2020-10-15 17:30:30 +02:00
Self::FnCallArgs(value) => value,
}
}
}
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
2021-01-02 16:30:10 +01:00
impl From<StaticVec<Dynamic>> for ChainArgument {
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-10-15 17:30:30 +02:00
fn from(value: StaticVec<Dynamic>) -> Self {
Self::FnCallArgs(value)
}
}
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
2021-01-02 16:30:10 +01:00
impl From<Dynamic> for ChainArgument {
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-10-15 17:30:30 +02:00
fn from(value: Dynamic) -> Self {
2021-01-02 16:30:10 +01:00
Self::IndexValue(value)
2020-10-15 17:30:30 +02:00
}
}
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)]
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"))]
2020-11-16 09:28:04 +01:00
LockGuard((crate::dynamic::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-10-11 15:58:11 +02:00
impl<'a> Target<'a> {
2020-05-16 05:42:56 +02:00
/// Is the `Target` a reference pointing to other data?
2020-10-04 04:40:44 +02:00
#[allow(dead_code)]
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-10-04 04:40:44 +02:00
#[allow(dead_code)]
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-10-04 04:40:44 +02:00
#[allow(dead_code)]
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-10-11 15:58:11 +02:00
pub fn take_or_clone(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
}
}
2020-10-11 15:58:11 +02:00
/// Take a `&mut Dynamic` reference from the `Target`.
#[inline(always)]
pub fn take_ref(self) -> Option<&'a mut Dynamic> {
match self {
Self::Ref(r) => Some(r),
_ => None,
}
}
/// Convert a shared or reference `Target` into a target with an owned value.
2020-08-08 10:24:10 +02:00
#[inline(always)]
pub fn into_owned(self) -> Target<'static> {
self.take_or_clone().into()
2020-03-30 16:19:37 +02:00
}
2020-10-04 04:40:44 +02:00
/// Propagate a changed value back to the original source.
/// This has no effect except for string indexing.
2020-10-05 06:05:46 +02:00
#[cfg(not(feature = "no_object"))]
#[inline(always)]
2020-10-04 04:40:44 +02:00
pub fn propagate_changed_value(&mut self) {
match self {
2020-10-05 06:05:46 +02:00
Self::Ref(_) | Self::Value(_) => (),
#[cfg(not(feature = "no_closure"))]
Self::LockGuard(_) => (),
2020-10-04 04:40:44 +02:00
#[cfg(not(feature = "no_index"))]
Self::StringChar(_, _, ch) => {
2020-10-12 11:00:58 +02:00
let char_value = ch.clone();
2020-12-20 16:25:11 +01:00
self.set_value(char_value, Position::NONE).unwrap();
2020-10-04 04:40:44 +02:00
}
}
}
2020-04-26 12:04:07 +02:00
/// Update the value of the `Target`.
#[cfg(any(not(feature = "no_object"), not(feature = "no_index")))]
2020-12-20 16:25:11 +01:00
pub fn set_value(&mut self, new_val: Dynamic, pos: Position) -> Result<(), Box<EvalAltResult>> {
2020-03-30 16:19:37 +02:00
match self {
2020-12-20 16:25:11 +01: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"))]
2020-12-20 16:25:11 +01:00
Self::LockGuard((r, _)) => **r = new_val,
Self::Value(_) => panic!("cannot update a value"),
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
2020-12-20 16:25:11 +01:00
let new_ch = new_val.as_char().map_err(|err| {
2020-10-03 17:27:30 +02:00
Box::new(EvalAltResult::ErrorMismatchDataType(
err.to_string(),
"char".to_string(),
2020-12-20 16:25:11 +01:00
pos,
2020-10-03 17:27:30 +02:00
))
})?;
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-16 05:42:56 +02:00
// See if changed - if so, update the String
2020-10-12 11:00:58 +02:00
if chars[*index] != 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
}
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
}
}
impl AsRef<Dynamic> for Target<'_> {
#[inline(always)]
fn as_ref(&self) -> &Dynamic {
match self {
Self::Ref(r) => *r,
#[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "no_object"))]
Self::LockGuard((r, _)) => &**r,
Self::Value(ref r) => r,
#[cfg(not(feature = "no_index"))]
Self::StringChar(_, _, ref r) => r,
}
}
}
impl AsMut<Dynamic> for Target<'_> {
#[inline(always)]
fn as_mut(&mut self) -> &mut Dynamic {
match self {
Self::Ref(r) => *r,
#[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "no_object"))]
Self::LockGuard((r, _)) => r.deref_mut(),
Self::Value(ref mut r) => r,
#[cfg(not(feature = "no_index"))]
Self::StringChar(_, _, ref mut r) => r,
}
}
}
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())
}
}
2020-11-25 02:36:06 +01:00
/// _(INTERNALS)_ A type that holds all the current states of the [`Engine`].
/// Exported under the `internals` feature only.
///
2021-01-02 16:30:10 +01:00
/// # WARNING
///
/// This type is volatile and may change.
2020-12-18 16:47:17 +01:00
#[derive(Debug, Clone, Default)]
pub struct State {
2020-12-21 15:04:46 +01:00
/// Source of the current context.
pub source: Option<ImmutableString>,
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,
2021-01-06 06:46:53 +01:00
/// 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,
2021-01-08 17:24:55 +01:00
/// Embedded module resolver.
2021-01-08 17:40:44 +01:00
#[cfg(not(feature = "no_module"))]
pub resolver: Option<Shared<crate::module::resolvers::StaticModuleResolver>>,
2020-12-18 16:47:17 +01:00
/// Cached lookup values for function hashes.
2020-12-30 14:12:51 +01:00
pub functions_cache: HashMap<
NonZeroU64,
Option<(CallableFunction, Option<ImmutableString>)>,
StraightHasherBuilder,
>,
2020-04-28 17:05:03 +02:00
}
impl State {
2020-10-28 12:11:17 +01:00
/// Is the state currently at global (root) level?
#[inline(always)]
pub fn is_global(&self) -> bool {
self.scope_level == 0
}
2020-04-28 17:05:03 +02:00
}
2020-11-20 09:52:28 +01:00
/// _(INTERNALS)_ A type containing all the limits imposed by the [`Engine`].
2020-07-26 09:53:22 +02:00
/// Exported under the `internals` feature only.
///
2021-01-02 16:30:10 +01:00
/// # WARNING
2020-07-26 09:53:22 +02:00
///
/// 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.
2020-12-29 05:29:45 +01:00
/// Not available under `no_function`.
2021-01-06 06:46:53 +01:00
///
/// Set to zero to effectively disable function calls.
2020-12-29 05:29:45 +01:00
#[cfg(not(feature = "no_function"))]
2020-07-26 09:53:22 +02:00
pub max_call_stack_depth: usize,
2021-01-06 06:46:53 +01:00
/// Maximum depth of statements/expressions at global level.
pub max_expr_depth: Option<NonZeroUsize>,
/// Maximum depth of statements/expressions in functions.
/// Not available under `no_function`.
#[cfg(not(feature = "no_function"))]
2021-01-06 06:46:53 +01:00
pub max_function_expr_depth: Option<NonZeroUsize>,
/// Maximum number of operations allowed to run.
pub max_operations: Option<NonZeroU64>,
2020-11-25 02:36:06 +01:00
/// Maximum number of [modules][Module] allowed to load.
/// Not available under `no_module`.
2021-01-06 06:46:53 +01:00
///
/// Set to zero to effectively disable loading any [module][Module].
2020-10-18 16:10:08 +02:00
#[cfg(not(feature = "no_module"))]
2020-07-26 09:53:22 +02:00
pub max_modules: usize,
2021-01-06 06:46:53 +01:00
/// Maximum length of a [string][ImmutableString].
pub max_string_size: Option<NonZeroUsize>,
/// Maximum length of an [array][Array].
/// Not available under `no_index`.
#[cfg(not(feature = "no_index"))]
2021-01-06 06:46:53 +01:00
pub max_array_size: Option<NonZeroUsize>,
/// Maximum number of properties in an [object map][Map].
/// Not available under `no_object`.
#[cfg(not(feature = "no_object"))]
2021-01-06 06:46:53 +01:00
pub max_map_size: Option<NonZeroUsize>,
2020-07-26 09:53:22 +02:00
}
2020-10-11 15:58:11 +02:00
/// Context of a script evaluation process.
#[derive(Debug)]
2020-10-20 04:54:32 +02:00
pub struct EvalContext<'e, 'x, 'px: 'x, 'a, 's, 'm, 'pm: 'm, 't, 'pt: 't> {
pub(crate) engine: &'e Engine,
2020-12-14 16:05:13 +01:00
pub(crate) scope: &'x mut Scope<'px>,
2020-10-11 15:58:11 +02:00
pub(crate) mods: &'a mut Imports,
pub(crate) state: &'s mut State,
pub(crate) lib: &'m [&'pm Module],
pub(crate) this_ptr: &'t mut Option<&'pt mut Dynamic>,
pub(crate) level: usize,
2020-10-11 15:58:11 +02:00
}
2020-10-20 04:54:32 +02:00
impl<'e, 'x, 'px, 'a, 's, 'm, 'pm, 't, 'pt> EvalContext<'e, 'x, 'px, 'a, 's, 'm, 'pm, 't, 'pt> {
2020-11-20 09:52:28 +01:00
/// The current [`Engine`].
#[inline(always)]
2021-01-01 10:05:06 +01:00
pub fn engine(&self) -> &Engine {
2020-10-11 15:58:11 +02:00
self.engine
}
2020-12-21 16:12:45 +01:00
/// The current source.
#[inline(always)]
2021-01-01 10:05:06 +01:00
pub fn source(&self) -> Option<&str> {
2020-12-21 16:12:45 +01:00
self.state.source.as_ref().map(|s| s.as_str())
}
2020-12-14 16:05:13 +01:00
/// The current [`Scope`].
#[inline(always)]
2021-01-01 10:05:06 +01:00
pub fn scope(&self) -> &Scope {
2020-12-14 16:05:13 +01:00
self.scope
}
/// Mutable reference to the current [`Scope`].
#[inline(always)]
pub fn scope_mut(&mut self) -> &mut &'x mut Scope<'px> {
&mut self.scope
}
2021-01-01 10:05:06 +01:00
/// Get an iterator over the current set of modules imported via `import` statements.
#[cfg(not(feature = "no_module"))]
#[inline(always)]
pub fn iter_imports(&self) -> impl Iterator<Item = (&str, &Module)> {
self.mods.iter()
}
2020-11-20 09:52:28 +01:00
/// _(INTERNALS)_ The current set of modules imported via `import` statements.
2020-10-11 15:58:11 +02:00
/// Available under the `internals` feature only.
#[cfg(feature = "internals")]
2020-10-18 16:10:08 +02:00
#[cfg(not(feature = "no_module"))]
#[inline(always)]
2021-01-01 10:05:06 +01:00
pub fn imports(&self) -> &Imports {
2020-10-29 04:37:51 +01:00
self.mods
2020-10-11 15:58:11 +02:00
}
/// Get an iterator over the namespaces containing definition of all script-defined functions.
#[inline(always)]
2021-01-01 10:05:06 +01:00
pub fn iter_namespaces(&self) -> impl Iterator<Item = &Module> {
self.lib.iter().cloned()
2020-10-11 15:58:11 +02:00
}
2021-01-01 10:05:06 +01:00
/// _(INTERNALS)_ The current set of namespaces containing definitions of all script-defined functions.
/// Available under the `internals` feature only.
#[cfg(feature = "internals")]
#[inline(always)]
pub fn namespaces(&self) -> &[&Module] {
self.lib
}
/// The current bound `this` pointer, if any.
#[inline(always)]
pub fn this_ptr(&self) -> Option<&Dynamic> {
self.this_ptr.as_ref().map(|v| &**v)
}
2020-10-11 15:58:11 +02:00
/// The current nesting level of function calls.
#[inline(always)]
2020-10-11 15:58:11 +02:00
pub fn call_level(&self) -> usize {
self.level
}
}
2020-03-04 15:00:01 +01:00
/// Rhai main scripting engine.
2017-10-30 16:08:44 +01:00
///
2020-10-27 04:30:38 +01:00
/// # Thread Safety
///
2020-11-20 09:52:28 +01:00
/// [`Engine`] is re-entrant.
2020-10-27 04:30:38 +01:00
///
2020-11-20 09:52:28 +01:00
/// Currently, [`Engine`] is neither [`Send`] nor [`Sync`].
2020-11-25 02:36:06 +01:00
/// Use the `sync` feature to make it [`Send`] `+` [`Sync`].
2020-10-27 04:30:38 +01:00
///
/// # Example
///
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-16 17:31:48 +02:00
pub struct Engine {
2020-11-20 09:52:28 +01:00
/// A unique ID identifying this scripting [`Engine`].
2020-10-27 04:30:38 +01:00
pub id: String,
2020-06-15 17:20:50 +02:00
2020-05-13 13:21:42 +02:00
/// A module containing all functions directly loaded into the Engine.
2020-11-19 06:56:03 +01:00
pub(crate) global_namespace: Module,
2020-12-22 16:45:14 +01:00
/// A collection of all modules loaded into the global namespace of the Engine.
pub(crate) global_modules: StaticVec<Shared<Module>>,
2020-11-15 16:14:16 +01:00
/// A collection of all sub-modules directly loaded into the Engine.
2020-12-26 06:05:57 +01:00
pub(crate) global_sub_modules: HashMap<ImmutableString, Shared<Module>>,
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"))]
2020-12-26 06:05:57 +01:00
pub(crate) module_resolver: Box<dyn crate::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-10-25 14:57:18 +01:00
pub(crate) type_names: HashMap<String, String>,
2020-07-05 09:23:51 +02:00
2020-07-05 11:41:45 +02:00
/// A hashset containing symbols to disable.
2020-10-25 14:57:18 +01:00
pub(crate) disabled_symbols: HashSet<String>,
2020-11-15 05:07:35 +01:00
/// A hashmap containing custom keywords and precedence to recognize.
2020-12-26 16:21:16 +01:00
pub(crate) custom_keywords: HashMap<String, Option<NonZeroU8>>,
2020-07-09 13:54:28 +02:00
/// Custom syntax.
2020-10-25 14:57:18 +01:00
pub(crate) custom_syntax: HashMap<ImmutableString, CustomSyntax>,
2020-10-11 15:58:11 +02:00
/// Callback closure for resolving variable access.
pub(crate) resolve_var: Option<OnVarCallback>,
2020-06-02 07:33:16 +02:00
/// Callback closure for implementing the `print` command.
2020-12-12 03:10:27 +01:00
pub(crate) print: OnPrintCallback,
2020-06-02 07:33:16 +02:00
/// Callback closure for implementing the `debug` command.
2020-12-12 04:47:18 +01:00
pub(crate) debug: OnDebugCallback,
2020-06-02 07:33:16 +02:00
/// Callback closure for progress reporting.
2020-12-12 03:10:27 +01:00
pub(crate) progress: Option<OnProgressCallback>,
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"))]
2020-11-10 16:26:50 +01:00
pub(crate) limits: Limits,
/// Disable doc-comments?
pub(crate) disable_doc_comments: bool,
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 {
2020-10-27 04:30:38 +01:00
if !self.id.is_empty() {
write!(f, "Engine({})", self.id)
} else {
f.write_str("Engine")
2020-07-13 13:38:50 +02:00
}
}
}
2020-04-16 17:31:48 +02:00
impl Default for Engine {
2020-10-08 16:25:50 +02:00
#[inline(always)]
2020-03-25 04:27:18 +01:00
fn default() -> Self {
2020-10-03 17:27:30 +02:00
Self::new()
2020-03-09 14:57:07 +01:00
}
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-10-12 16:49:51 +02:00
/// Is this function an anonymous function?
#[cfg(not(feature = "no_function"))]
#[inline(always)]
pub fn is_anonymous_fn(fn_name: &str) -> bool {
fn_name.starts_with(FN_ANONYMOUS)
}
2020-12-12 04:47:18 +01:00
/// Print to stdout
2020-11-10 16:26:50 +01:00
#[inline(always)]
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-12-12 04:47:18 +01:00
/// Debug to stdout
#[inline(always)]
2020-12-21 15:04:46 +01:00
fn default_debug(_s: &str, _source: Option<&str>, _pos: Position) {
2020-12-12 04:47:18 +01:00
#[cfg(not(feature = "no_std"))]
#[cfg(not(target_arch = "wasm32"))]
2020-12-21 15:04:46 +01:00
if let Some(source) = _source {
println!("{} @ {:?} | {}", source, _pos, _s);
} else {
println!("{:?} | {}", _pos, _s);
}
2020-12-12 04:47:18 +01:00
}
2020-06-28 09:49:24 +02:00
/// Search for a module within an imports stack.
2020-11-20 09:52:28 +01:00
/// [`Position`] in [`EvalAltResult`] is [`None`][Position::None] and must be set afterwards.
2020-11-07 16:33:21 +01:00
pub fn search_imports(
mods: &Imports,
state: &mut State,
2020-11-10 16:26:50 +01:00
namespace: &NamespaceRef,
2020-11-07 16:33:21 +01:00
) -> Result<Shared<Module>, Box<EvalAltResult>> {
2020-12-22 09:45:56 +01:00
let Ident { name: root, pos } = &namespace[0];
// Qualified - check if the root module is directly indexed
let index = if state.always_search {
2021-01-06 06:46:53 +01:00
None
} else {
2021-01-06 06:46:53 +01:00
namespace.index()
};
2021-01-06 06:46:53 +01:00
Ok(if let Some(index) = index {
let offset = mods.len() - index.get();
2020-11-01 16:42:00 +01:00
mods.get(offset).expect("invalid index in Imports")
} else {
2020-11-01 16:42:00 +01:00
mods.find(root)
.map(|n| mods.get(n).expect("invalid index in Imports"))
2020-10-31 17:04:02 +01:00
.ok_or_else(|| EvalAltResult::ErrorModuleNotFound(root.to_string(), *pos))?
})
}
2020-04-16 17:31:48 +02:00
impl Engine {
2020-11-20 09:52:28 +01:00
/// Create a new [`Engine`]
2020-11-10 16:26:50 +01:00
#[inline]
2020-03-25 04:27:18 +01:00
pub fn new() -> Self {
2020-10-03 17:27:30 +02:00
// Create the new scripting Engine
let mut engine = Self {
2020-10-27 04:30:38 +01:00
id: Default::default(),
2020-10-03 17:27:30 +02:00
2020-11-19 06:56:03 +01:00
global_namespace: Default::default(),
2020-12-22 16:45:14 +01:00
global_modules: Default::default(),
2020-11-15 16:14:16 +01:00
global_sub_modules: Default::default(),
2020-10-03 17:27:30 +02:00
#[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_std"))]
#[cfg(not(target_arch = "wasm32"))]
2020-12-26 06:05:57 +01:00
module_resolver: Box::new(crate::module::resolvers::FileModuleResolver::new()),
2020-10-03 17:27:30 +02:00
#[cfg(not(feature = "no_module"))]
#[cfg(any(feature = "no_std", target_arch = "wasm32",))]
2020-12-30 15:37:22 +01:00
module_resolver: Box::new(crate::module::resolvers::DummyModuleResolver::new()),
2020-10-03 17:27:30 +02:00
2020-11-15 06:49:54 +01:00
type_names: Default::default(),
disabled_symbols: Default::default(),
custom_keywords: Default::default(),
custom_syntax: Default::default(),
2020-10-03 17:27:30 +02:00
2020-10-11 15:58:11 +02:00
// variable resolver
resolve_var: None,
2020-10-03 17:27:30 +02:00
// default print/debug implementations
print: Box::new(default_print),
2020-12-12 04:47:18 +01:00
debug: Box::new(default_debug),
2020-10-03 17:27:30 +02:00
// progress callback
progress: None,
// optimization level
optimization_level: if cfg!(feature = "no_optimize") {
OptimizationLevel::None
} else {
OptimizationLevel::Simple
},
#[cfg(not(feature = "unchecked"))]
2020-11-10 16:26:50 +01:00
limits: Limits {
2020-12-29 05:29:45 +01:00
#[cfg(not(feature = "no_function"))]
2020-10-03 17:27:30 +02:00
max_call_stack_depth: MAX_CALL_STACK_DEPTH,
2021-01-06 06:46:53 +01:00
max_expr_depth: NonZeroUsize::new(MAX_EXPR_DEPTH),
#[cfg(not(feature = "no_function"))]
2021-01-06 06:46:53 +01:00
max_function_expr_depth: NonZeroUsize::new(MAX_FUNCTION_EXPR_DEPTH),
max_operations: None,
#[cfg(not(feature = "no_module"))]
2020-10-03 17:27:30 +02:00
max_modules: usize::MAX,
2021-01-06 06:46:53 +01:00
max_string_size: None,
#[cfg(not(feature = "no_index"))]
2021-01-06 06:46:53 +01:00
max_array_size: None,
#[cfg(not(feature = "no_object"))]
2021-01-06 06:46:53 +01:00
max_map_size: None,
2020-10-03 17:27:30 +02:00
},
disable_doc_comments: false,
2020-10-03 17:27:30 +02:00
};
2020-12-22 16:45:14 +01:00
engine.register_global_module(StandardPackage::new().as_shared_module());
2020-10-03 17:27:30 +02:00
engine
2020-03-25 04:27:18 +01:00
}
2020-03-09 14:57:07 +01:00
2020-11-20 09:52:28 +01:00
/// Create a new [`Engine`] with minimal built-in functions.
2021-01-02 16:30:10 +01:00
///
/// Use [`register_global_module`][Engine::register_global_module] to add packages of functions.
2020-11-10 16:26:50 +01:00
#[inline]
pub fn new_raw() -> Self {
Self {
2020-10-27 04:30:38 +01:00
id: Default::default(),
2020-06-15 17:20:50 +02:00
2020-11-19 06:56:03 +01:00
global_namespace: Default::default(),
2020-12-22 16:45:14 +01:00
global_modules: Default::default(),
2020-11-15 16:14:16 +01:00
global_sub_modules: Default::default(),
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_module"))]
2020-12-26 06:05:57 +01:00
module_resolver: Box::new(crate::module::resolvers::DummyModuleResolver::new()),
2020-11-15 06:49:54 +01:00
type_names: Default::default(),
disabled_symbols: Default::default(),
custom_keywords: Default::default(),
custom_syntax: Default::default(),
2020-07-05 09:23:51 +02:00
2020-10-11 15:58:11 +02:00
resolve_var: None,
2020-04-27 15:28:31 +02:00
print: Box::new(|_| {}),
2020-12-21 15:04:46 +01:00
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"))]
2020-11-10 16:26:50 +01:00
limits: Limits {
2020-12-29 05:29:45 +01:00
#[cfg(not(feature = "no_function"))]
2020-07-26 09:53:22 +02:00
max_call_stack_depth: MAX_CALL_STACK_DEPTH,
2021-01-06 06:46:53 +01:00
max_expr_depth: NonZeroUsize::new(MAX_EXPR_DEPTH),
#[cfg(not(feature = "no_function"))]
2021-01-06 06:46:53 +01:00
max_function_expr_depth: NonZeroUsize::new(MAX_FUNCTION_EXPR_DEPTH),
max_operations: None,
#[cfg(not(feature = "no_module"))]
2020-07-26 09:53:22 +02:00
max_modules: usize::MAX,
2021-01-06 06:46:53 +01:00
max_string_size: None,
#[cfg(not(feature = "no_index"))]
2021-01-06 06:46:53 +01:00
max_array_size: None,
#[cfg(not(feature = "no_object"))]
2021-01-06 06:46:53 +01:00
max_map_size: None,
2020-07-26 09:53:22 +02:00
},
disable_doc_comments: false,
}
}
2020-10-11 15:58:11 +02:00
/// Search for a variable within the scope or within imports,
2020-11-10 16:26:50 +01:00
/// depending on whether the variable name is namespace-qualified.
2020-12-26 06:05:57 +01:00
pub(crate) fn search_namespace<'s>(
2020-10-11 15:58:11 +02:00
&self,
scope: &'s mut Scope,
mods: &mut Imports,
2020-10-11 15:58:11 +02:00
state: &mut State,
2020-10-20 04:54:32 +02:00
lib: &[&Module],
2020-10-11 15:58:11 +02:00
this_ptr: &'s mut Option<&mut Dynamic>,
2020-12-26 06:05:57 +01:00
expr: &Expr,
) -> Result<(Target<'s>, Position), Box<EvalAltResult>> {
2020-10-11 15:58:11 +02:00
match expr {
Expr::Variable(v) => match v.as_ref() {
// Qualified variable
2020-12-24 16:22:50 +01:00
(_, Some((hash_var, modules)), Ident { name, pos }) => {
let module = search_imports(mods, state, modules)?;
2020-12-24 16:22:50 +01:00
let target = module.get_qualified_var(*hash_var).map_err(|mut err| {
match *err {
EvalAltResult::ErrorVariableNotFound(ref mut err_name, _) => {
*err_name = format!("{}{}", modules, name);
}
_ => (),
}
err.fill_position(*pos)
})?;
2020-10-11 15:58:11 +02:00
// Module variables are constant
2020-12-08 15:47:38 +01:00
let mut target = target.clone();
target.set_access_mode(AccessMode::ReadOnly);
2020-12-26 06:05:57 +01:00
Ok((target.into(), *pos))
2020-10-11 15:58:11 +02:00
}
// Normal variable access
_ => self.search_scope_only(scope, mods, state, lib, this_ptr, expr),
},
_ => unreachable!("Expr::Variable expected, but gets {:?}", expr),
2020-10-11 15:58:11 +02:00
}
}
/// Search for a variable within the scope
2020-12-26 06:05:57 +01:00
pub(crate) fn search_scope_only<'s>(
2020-10-11 15:58:11 +02:00
&self,
scope: &'s mut Scope,
mods: &mut Imports,
state: &mut State,
2020-10-20 04:54:32 +02:00
lib: &[&Module],
2020-10-11 15:58:11 +02:00
this_ptr: &'s mut Option<&mut Dynamic>,
2020-12-26 06:05:57 +01:00
expr: &Expr,
) -> Result<(Target<'s>, Position), Box<EvalAltResult>> {
2020-12-24 16:22:50 +01:00
let (index, _, Ident { name, pos }) = match expr {
2020-10-11 15:58:11 +02:00
Expr::Variable(v) => v.as_ref(),
_ => unreachable!("Expr::Variable expected, but gets {:?}", expr),
2020-10-11 15:58:11 +02:00
};
// Check if the variable is `this`
if name.as_str() == KEYWORD_THIS {
2020-10-11 15:58:11 +02:00
if let Some(val) = this_ptr {
2020-12-26 06:05:57 +01:00
return Ok(((*val).into(), *pos));
2020-10-11 15:58:11 +02:00
} else {
return EvalAltResult::ErrorUnboundThis(*pos).into();
}
}
// Check if it is directly indexed
2021-01-06 06:46:53 +01:00
let index = if state.always_search { &None } else { index };
2020-10-11 15:58:11 +02:00
// Check the variable resolver, if any
if let Some(ref resolve_var) = self.resolve_var {
2021-01-06 06:46:53 +01:00
let index = index.map(NonZeroUsize::get).unwrap_or(0);
2020-10-11 15:58:11 +02:00
let context = EvalContext {
engine: self,
scope,
2020-10-11 15:58:11 +02:00
mods,
state,
lib,
this_ptr,
level: 0,
};
2020-12-08 15:47:38 +01:00
if let Some(mut result) =
resolve_var(name, index, &context).map_err(|err| err.fill_position(*pos))?
2020-10-11 15:58:11 +02:00
{
result.set_access_mode(AccessMode::ReadOnly);
2020-12-26 06:05:57 +01:00
return Ok((result.into(), *pos));
2020-10-11 15:58:11 +02:00
}
}
2021-01-06 06:46:53 +01:00
let index = if let Some(index) = index {
scope.len() - index.get()
2020-10-11 15:58:11 +02:00
} else {
// Find the variable in the scope
scope
.get_index(name)
.ok_or_else(|| EvalAltResult::ErrorVariableNotFound(name.to_string(), *pos))?
2020-10-11 15:58:11 +02:00
.0
};
2020-12-26 06:05:57 +01:00
let val = scope.get_mut_by_index(index);
2020-10-11 15:58:11 +02:00
2021-01-06 06:46:53 +01: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-10-11 15:58:11 +02:00
// if cfg!(not(feature = "no_closure")) && val.is_locked() {
// return EvalAltResult::ErrorDataRace(name.into(), *pos).into();
// }
2020-12-26 06:05:57 +01:00
Ok((val.into(), *pos))
2020-10-11 15:58:11 +02:00
}
2020-04-26 12:04:07 +02:00
/// Chain-evaluate a dot/index chain.
2020-11-20 09:52:28 +01:00
/// [`Position`] in [`EvalAltResult`] is [`None`][Position::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,
mods: &mut Imports,
state: &mut State,
2020-10-20 04:54:32 +02:00
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,
2021-01-02 16:30:10 +01:00
idx_values: &mut StaticVec<ChainArgument>,
chain_type: ChainType,
2020-03-27 07:34:01 +01:00
level: usize,
2020-10-05 07:45:57 +02:00
new_val: Option<(Dynamic, Position)>,
2020-04-26 12:04:07 +02:00
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
2021-01-02 16:30:10 +01:00
if chain_type == ChainType::NonChaining {
unreachable!("should not be ChainType::NonChaining");
2020-06-25 05:07:46 +02:00
}
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 {
2020-10-31 16:26:21 +01:00
Expr::Index(_, _) => ChainType::Index,
Expr::Dot(_, _) => ChainType::Dot,
2021-01-02 16:30:10 +01:00
_ => ChainType::NonChaining,
2020-06-25 05:07:46 +02:00
};
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
let target_val = target.as_mut();
match chain_type {
#[cfg(not(feature = "no_index"))]
ChainType::Index => {
let pos = rhs.position();
match rhs {
// xxx[idx].expr... | xxx[idx][expr]...
2020-10-31 16:26:21 +01:00
Expr::Dot(x, x_pos) | Expr::Index(x, x_pos) => {
2020-10-27 16:00:05 +01:00
let idx_pos = x.lhs.position();
2021-01-02 16:30:10 +01:00
let idx_val = idx_val.as_index_value();
2020-08-01 06:21:15 +02:00
let obj_ptr = &mut self.get_indexed_mut(
mods, state, lib, target_val, idx_val, idx_pos, false, is_ref, true,
level,
2020-08-01 06:21:15 +02:00
)?;
self.eval_dot_index_chain_helper(
mods, state, lib, this_ptr, obj_ptr, &x.rhs, idx_values, next_chain,
level, new_val,
)
2020-10-31 16:26:21 +01:00
.map_err(|err| err.fill_position(*x_pos))
}
// xxx[rhs] = new_val
2020-08-08 10:24:10 +02:00
_ if new_val.is_some() => {
2021-01-02 16:30:10 +01:00
let idx_val = idx_val.as_index_value();
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
let _call_setter = match self.get_indexed_mut(
mods, state, lib, target_val, idx_val, pos, true, is_ref, false, level,
) {
// Indexed value is a reference - update directly
2020-06-26 04:39:18 +02:00
Ok(ref mut obj_ptr) => {
2020-12-20 16:25:11 +01:00
let (new_val, new_val_pos) = new_val.unwrap();
obj_ptr.set_value(new_val, new_val_pos)?;
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_type_name = target_val.type_name();
let args = &mut [target_val, &mut idx_val2, &mut new_val.0];
2020-08-01 06:21:15 +02:00
self.exec_fn_call(
2020-12-24 09:32:43 +01:00
mods, state, lib, FN_IDX_SET, None, args, is_ref, true, false,
2020-12-12 04:15:09 +01:00
new_val.1, None, None, level,
2020-08-01 06:21:15 +02:00
)
.map_err(|err| match *err {
2020-10-19 08:26:15 +02:00
EvalAltResult::ErrorFunctionNotFound(fn_sig, _)
if fn_sig.ends_with("]=") =>
{
2020-08-01 06:21:15 +02:00
EvalAltResult::ErrorIndexingType(
self.map_type_name(val_type_name).into(),
2020-11-20 09:52:28 +01:00
Position::NONE,
2020-08-01 06:21:15 +02:00
)
}
err => err,
})?;
}
2020-11-20 15:23:37 +01:00
Ok((Dynamic::UNIT, true))
2020-06-06 07:06:00 +02:00
}
// xxx[rhs]
2020-10-15 17:30:30 +02:00
_ => {
2021-01-02 16:30:10 +01:00
let idx_val = idx_val.as_index_value();
self.get_indexed_mut(
mods, state, lib, target_val, idx_val, pos, false, is_ref, true, level,
)
.map(|v| (v.take_or_clone(), false))
2020-10-15 17:30:30 +02:00
}
2020-04-26 12:04:07 +02:00
}
}
#[cfg(not(feature = "no_object"))]
ChainType::Dot => {
match rhs {
// xxx.fn_name(arg_expr_list)
2020-12-29 03:41:20 +01:00
Expr::FnCall(x, pos) if x.namespace.is_none() && new_val.is_none() => {
2020-11-10 16:26:50 +01:00
let FnCallExpr {
2020-10-31 07:13:45 +01:00
name,
2020-12-24 09:32:43 +01:00
hash_script: hash,
2020-10-31 07:13:45 +01:00
def_value,
..
} = x.as_ref();
2020-11-20 09:52:28 +01:00
let def_value = def_value.as_ref();
2020-10-15 17:30:30 +02:00
let args = idx_val.as_fn_call_args();
self.make_method_call(
2020-12-24 09:32:43 +01:00
mods, state, lib, name, *hash, target, args, def_value, false, *pos,
level,
)
}
2020-12-29 03:41:20 +01:00
// xxx.fn_name(...) = ???
Expr::FnCall(_, _) if new_val.is_some() => {
unreachable!("method call cannot be assigned to")
}
// xxx.module::fn_name(...) - syntax error
Expr::FnCall(_, _) => {
unreachable!("function call in dot chain should not be namespace-qualified")
}
// {xxx:map}.id = ???
Expr::Property(x) if target_val.is::<Map>() && new_val.is_some() => {
2020-12-25 04:02:29 +01:00
let Ident { name, pos } = &x.2;
2020-10-31 07:13:45 +01:00
let index = name.clone().into();
let mut val = self.get_indexed_mut(
mods, state, lib, target_val, index, *pos, true, is_ref, false, level,
)?;
2020-12-20 16:25:11 +01:00
let (new_val, new_val_pos) = new_val.unwrap();
val.set_value(new_val, new_val_pos)?;
Ok((Default::default(), true))
}
// {xxx:map}.id
Expr::Property(x) if target_val.is::<Map>() => {
2020-12-25 04:02:29 +01:00
let Ident { name, pos } = &x.2;
2020-10-31 07:13:45 +01:00
let index = name.clone().into();
2020-08-01 06:21:15 +02:00
let val = self.get_indexed_mut(
mods, state, lib, target_val, index, *pos, false, is_ref, false, level,
2020-08-01 06:21:15 +02:00
)?;
2020-05-11 17:48:50 +02:00
2020-10-11 15:58:11 +02:00
Ok((val.take_or_clone(), false))
}
// xxx.id = ???
2020-08-08 10:24:10 +02:00
Expr::Property(x) if new_val.is_some() => {
2020-12-25 04:02:29 +01:00
let (_, setter, Ident { pos, .. }) = x.as_ref();
2020-08-08 10:24:10 +02:00
let mut new_val = new_val;
let mut args = [target_val, &mut new_val.as_mut().unwrap().0];
2020-06-26 04:39:18 +02:00
self.exec_fn_call(
2020-12-24 09:32:43 +01:00
mods, state, lib, setter, None, &mut args, is_ref, true, false, *pos,
2020-12-12 04:15:09 +01:00
None, None, level,
2020-06-26 04:39:18 +02:00
)
.map(|(v, _)| (v, true))
}
// xxx.id
Expr::Property(x) => {
2020-12-25 04:02:29 +01:00
let (getter, _, Ident { pos, .. }) = x.as_ref();
let mut args = [target_val];
2020-06-26 04:39:18 +02:00
self.exec_fn_call(
2020-12-24 09:32:43 +01:00
mods, state, lib, getter, None, &mut args, is_ref, true, false, *pos,
2020-12-12 04:15:09 +01:00
None, None, level,
2020-06-26 04:39:18 +02:00
)
.map(|(v, _)| (v, false))
}
2020-07-09 16:21:07 +02:00
// {xxx:map}.sub_lhs[expr] | {xxx:map}.sub_lhs.expr
Expr::Index(x, x_pos) | Expr::Dot(x, x_pos) if target_val.is::<Map>() => {
2020-10-27 16:00:05 +01:00
let mut val = match &x.lhs {
2020-07-09 16:21:07 +02:00
Expr::Property(p) => {
2020-12-25 04:02:29 +01:00
let Ident { name, pos } = &p.2;
2020-10-31 07:13:45 +01:00
let index = name.clone().into();
2020-08-01 06:21:15 +02:00
self.get_indexed_mut(
mods, state, lib, target_val, index, *pos, false, is_ref, true,
level,
2020-08-01 06:21:15 +02:00
)?
2020-07-09 16:21:07 +02:00
}
// {xxx:map}.fn_name(arg_expr_list)[expr] | {xxx:map}.fn_name(arg_expr_list).expr
2020-10-31 16:26:21 +01:00
Expr::FnCall(x, pos) if x.namespace.is_none() => {
2020-11-10 16:26:50 +01:00
let FnCallExpr {
2020-10-31 07:13:45 +01:00
name,
2020-12-24 09:32:43 +01:00
hash_script: hash,
2020-10-31 07:13:45 +01:00
def_value,
..
} = x.as_ref();
2020-11-20 09:52:28 +01:00
let def_value = def_value.as_ref();
2020-10-15 17:30:30 +02:00
let args = idx_val.as_fn_call_args();
2020-12-12 04:15:09 +01:00
let (val, _) = self.make_method_call(
2020-12-24 09:32:43 +01:00
mods, state, lib, name, *hash, target, args, def_value, false,
*pos, level,
2020-12-12 04:15:09 +01:00
)?;
2020-07-09 16:21:07 +02:00
val.into()
}
// {xxx:map}.module::fn_name(...) - syntax error
Expr::FnCall(_, _) => unreachable!(
"function call in dot chain should not be namespace-qualified"
),
2020-07-09 16:21:07 +02:00
// Others - syntax error
expr => unreachable!("invalid dot expression: {:?}", expr),
};
self.eval_dot_index_chain_helper(
mods, state, lib, this_ptr, &mut val, &x.rhs, idx_values, next_chain,
level, new_val,
2020-06-01 09:25:22 +02:00
)
2020-10-31 16:26:21 +01:00
.map_err(|err| err.fill_position(*x_pos))
}
2020-07-09 16:21:07 +02:00
// xxx.sub_lhs[expr] | xxx.sub_lhs.expr
2020-10-31 16:26:21 +01:00
Expr::Index(x, x_pos) | Expr::Dot(x, x_pos) => {
2020-10-27 16:00:05 +01:00
match &x.lhs {
2020-07-09 16:21:07 +02:00
// xxx.prop[expr] | xxx.prop.expr
Expr::Property(p) => {
2020-12-25 04:02:29 +01:00
let (getter, setter, Ident { pos, .. }) = p.as_ref();
let arg_values = &mut [target_val, &mut Default::default()];
2020-07-09 16:21:07 +02:00
let args = &mut arg_values[..1];
2021-01-02 06:29:16 +01:00
let (mut val, updated) = self.exec_fn_call(
mods, state, lib, getter, None, args, is_ref, true, false,
*pos, None, None, level,
)?;
2020-07-09 16:21:07 +02:00
let val = &mut val;
let (result, may_be_changed) = self
.eval_dot_index_chain_helper(
mods,
state,
lib,
this_ptr,
&mut val.into(),
2020-10-27 16:00:05 +01:00
&x.rhs,
idx_values,
next_chain,
level,
2020-08-08 10:24:10 +02:00
new_val,
2020-07-09 16:21:07 +02:00
)
2020-10-31 16:26:21 +01:00
.map_err(|err| err.fill_position(*x_pos))?;
2020-07-09 16:21:07 +02:00
// 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-12-24 09:32:43 +01:00
mods, state, lib, setter, None, arg_values, is_ref, true,
2020-12-12 04:15:09 +01:00
false, *pos, None, None, level,
2020-07-09 16:21:07 +02:00
)
.or_else(
|err| match *err {
2021-01-06 06:46:53 +01:00
// If there is no setter, no need to feed it back because
// the property is read-only
2020-07-09 16:21:07 +02:00
EvalAltResult::ErrorDotExpr(_, _) => {
2020-11-20 15:23:37 +01:00
Ok((Dynamic::UNIT, false))
2020-07-09 16:21:07 +02:00
}
2021-01-02 06:29:16 +01:00
_ => Err(err),
2020-07-09 16:21:07 +02:00
},
)?;
}
Ok((result, may_be_changed))
}
// xxx.fn_name(arg_expr_list)[expr] | xxx.fn_name(arg_expr_list).expr
2020-10-31 16:26:21 +01:00
Expr::FnCall(f, pos) if f.namespace.is_none() => {
2020-11-10 16:26:50 +01:00
let FnCallExpr {
2020-10-31 07:13:45 +01:00
name,
2020-12-24 09:32:43 +01:00
hash_script: hash,
2020-10-31 07:13:45 +01:00
def_value,
..
} = f.as_ref();
2020-11-20 09:52:28 +01:00
let def_value = def_value.as_ref();
2020-10-15 17:30:30 +02:00
let args = idx_val.as_fn_call_args();
2020-12-12 04:15:09 +01:00
let (mut val, _) = self.make_method_call(
2020-12-24 09:32:43 +01:00
mods, state, lib, name, *hash, target, args, def_value, false,
*pos, level,
2020-12-12 04:15:09 +01:00
)?;
2020-07-09 16:21:07 +02:00
let val = &mut val;
let target = &mut val.into();
self.eval_dot_index_chain_helper(
mods, state, lib, this_ptr, target, &x.rhs, idx_values,
next_chain, level, new_val,
)
2020-10-11 15:58:11 +02:00
.map_err(|err| err.fill_position(*pos))
}
2020-07-09 16:21:07 +02:00
// xxx.module::fn_name(...) - syntax error
Expr::FnCall(_, _) => unreachable!(
"function call in dot chain should not be namespace-qualified"
),
2020-07-09 16:21:07 +02:00
// Others - syntax error
expr => unreachable!("invalid dot expression: {:?}", expr),
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
}
chain_type => unreachable!("invalid ChainType: {:?}", chain_type),
}
}
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,
2020-10-20 04:54:32 +02:00
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-10-05 07:45:57 +02:00
new_val: Option<(Dynamic, Position)>,
) -> Result<Dynamic, Box<EvalAltResult>> {
2020-11-16 09:28:04 +01:00
let (crate::ast::BinaryExpr { lhs, rhs }, chain_type, op_pos) = match expr {
2020-10-31 16:26:21 +01:00
Expr::Index(x, pos) => (x.as_ref(), ChainType::Index, *pos),
Expr::Dot(x, pos) => (x.as_ref(), ChainType::Dot, *pos),
_ => unreachable!("index or dot chain expected, but gets {:?}", expr),
2020-05-31 09:51:26 +02:00
};
2020-11-19 06:51:59 +01:00
let idx_values = &mut Default::default();
2020-03-25 04:27:18 +01:00
self.eval_indexed_chain(
2020-11-19 06:51:59 +01:00
scope, mods, state, lib, this_ptr, rhs, chain_type, idx_values, 0, level,
)?;
2020-04-11 10:06:57 +02:00
2020-11-10 16:26:50 +01:00
match lhs {
2020-04-26 12:04:07 +02:00
// id.??? or id[???]
2020-06-26 04:39:18 +02:00
Expr::Variable(x) => {
2020-12-22 09:45:56 +01:00
let Ident {
2020-10-28 12:11:17 +01:00
name: var_name,
pos: var_pos,
2020-12-24 16:22:50 +01:00
} = &x.2;
2020-06-26 04:39:18 +02:00
2020-12-20 16:25:11 +01:00
self.inc_operations(state, *var_pos)?;
2020-06-26 04:39:18 +02:00
2020-12-26 06:05:57 +01:00
let (target, pos) =
2020-11-10 16:26:50 +01:00
self.search_namespace(scope, mods, state, lib, this_ptr, lhs)?;
2020-04-26 12:04:07 +02:00
// Constants cannot be modified
2020-12-08 16:09:12 +01:00
if target.as_ref().is_read_only() && new_val.is_some() {
2020-12-08 15:47:38 +01:00
return EvalAltResult::ErrorAssignmentToConstant(var_name.to_string(), pos)
.into();
}
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-11-10 16:26:50 +01:00
mods, state, lib, &mut None, obj_ptr, rhs, idx_values, chain_type, level,
new_val,
2020-04-26 12:04:07 +02:00
)
.map(|(v, _)| v)
2020-10-31 16:26:21 +01:00
.map_err(|err| err.fill_position(op_pos))
}
2020-04-26 12:04:07 +02:00
// {expr}.??? = ??? or {expr}[???] = ???
_ if new_val.is_some() => unreachable!("cannot assign to an expression"),
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-11-10 16:26:50 +01:00
mods, state, lib, this_ptr, obj_ptr, rhs, idx_values, chain_type, level,
new_val,
2020-04-26 12:04:07 +02:00
)
.map(|(v, _)| v)
2020-10-31 16:26:21 +01:00
.map_err(|err| err.fill_position(op_pos))
}
}
}
2020-11-20 09:52:28 +01:00
/// Evaluate a chain of indexes and store the results in a [`StaticVec`].
2021-01-06 06:46:53 +01:00
/// [`StaticVec`] is used to avoid an allocation in the overwhelming cases of
/// just a few levels of indexing.
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,
2020-10-20 04:54:32 +02:00
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,
parent_chain_type: ChainType,
2021-01-02 16:30:10 +01:00
idx_values: &mut StaticVec<ChainArgument>,
2020-04-26 12:04:07 +02:00
size: usize,
2020-03-27 07:34:01 +01:00
level: usize,
) -> Result<(), Box<EvalAltResult>> {
2020-12-20 16:25:11 +01:00
self.inc_operations(state, expr.position())?;
2020-05-17 16:19:49 +02:00
2020-04-26 15:48:49 +02:00
match expr {
Expr::FnCall(x, _) if parent_chain_type == ChainType::Dot && x.namespace.is_none() => {
2020-10-31 07:13:45 +01:00
let arg_values = x
.args
.iter()
.map(|arg_expr| {
self.eval_expr(scope, mods, state, lib, this_ptr, arg_expr, level)
})
.collect::<Result<StaticVec<_>, _>>()?;
2020-04-26 12:04:07 +02:00
2020-10-15 17:30:30 +02:00
idx_values.push(arg_values.into());
2020-04-26 12:04:07 +02:00
}
Expr::FnCall(_, _) if parent_chain_type == ChainType::Dot => {
unreachable!("function call in dot chain should not be namespace-qualified")
}
Expr::Property(_) if parent_chain_type == ChainType::Dot => {
2021-01-02 16:30:10 +01:00
idx_values.push(ChainArgument::Property)
}
Expr::Property(_) => unreachable!("unexpected Expr::Property for indexing"),
2020-10-31 16:26:21 +01:00
Expr::Index(x, _) | Expr::Dot(x, _) => {
2020-11-16 09:28:04 +01:00
let crate::ast::BinaryExpr { lhs, rhs, .. } = x.as_ref();
2020-05-30 04:27:48 +02:00
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(_) if parent_chain_type == ChainType::Dot => {
2021-01-02 16:30:10 +01:00
ChainArgument::Property
}
Expr::Property(_) => unreachable!("unexpected Expr::Property for indexing"),
Expr::FnCall(x, _)
if parent_chain_type == ChainType::Dot && x.namespace.is_none() =>
{
2020-10-31 16:26:21 +01:00
x.args
.iter()
.map(|arg_expr| {
self.eval_expr(scope, mods, state, lib, this_ptr, arg_expr, level)
})
.collect::<Result<StaticVec<Dynamic>, _>>()?
.into()
}
Expr::FnCall(_, _) if parent_chain_type == ChainType::Dot => {
unreachable!("function call in dot chain should not be namespace-qualified")
}
2020-10-15 17:30:30 +02:00
_ => self
.eval_expr(scope, mods, state, lib, this_ptr, lhs, level)?
.into(),
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 {
2020-10-31 16:26:21 +01:00
Expr::Index(_, _) => ChainType::Index,
Expr::Dot(_, _) => ChainType::Dot,
_ => unreachable!("index or dot chain expected, but gets {:?}", expr),
2020-07-09 16:21:07 +02:00
};
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
}
2020-10-15 17:30:30 +02:00
_ => idx_values.push(
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.into(),
),
2020-04-26 15:48:49 +02:00
}
Ok(())
2020-04-26 12:04:07 +02:00
}
2020-11-20 09:52:28 +01:00
/// Get the value at the indexed position of a base type.
/// [`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")))]
fn get_indexed_mut<'t>(
2020-04-26 12:04:07 +02:00
&self,
_mods: &mut Imports,
state: &mut State,
2020-10-20 04:54:32 +02:00
_lib: &[&Module],
target: &'t mut Dynamic,
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,
_is_ref: bool,
2020-08-01 06:21:15 +02:00
_indexers: bool,
2020-07-26 09:53:22 +02:00
_level: usize,
) -> Result<Target<'t>, Box<EvalAltResult>> {
2020-12-20 16:25:11 +01:00
self.inc_operations(state, Position::NONE)?;
match target {
#[cfg(not(feature = "no_index"))]
2020-12-08 15:47:38 +01:00
Dynamic(Union::Array(arr, _)) => {
// val_array[idx]
2020-08-08 10:24:10 +02:00
let index = idx
.as_int()
2020-11-16 09:28:04 +01:00
.map_err(|err| self.make_type_mismatch_err::<crate::INT>(err, 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-12-08 15:47:38 +01:00
Dynamic(Union::Map(map, _)) => {
// val_map[idx]
2020-07-26 09:53:22 +02:00
Ok(if _create {
2020-10-05 07:45:57 +02:00
let index = idx.take_immutable_string().map_err(|err| {
self.make_type_mismatch_err::<ImmutableString>(err, idx_pos)
})?;
2020-05-25 07:44:28 +02:00
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-10-05 07:45:57 +02:00
let index = idx.read_lock::<ImmutableString>().ok_or_else(|| {
self.make_type_mismatch_err::<ImmutableString>("", idx_pos)
})?;
2020-05-25 07:44:28 +02:00
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-12-08 15:47:38 +01: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-11-16 09:28:04 +01:00
.map_err(|err| self.make_type_mismatch_err::<crate::INT>(err, 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)
})?;
Ok(Target::StringChar(target, 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 = target.type_name();
2020-08-08 10:24:10 +02:00
let mut idx = idx;
let args = &mut [target, &mut idx];
2020-06-26 04:39:18 +02:00
self.exec_fn_call(
2020-12-24 09:32:43 +01:00
_mods, state, _lib, FN_IDX_GET, None, args, _is_ref, true, false, idx_pos,
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 {
2020-10-19 11:26:47 +02:00
EvalAltResult::ErrorFunctionNotFound(fn_sig, _) if fn_sig.ends_with(']') => {
2020-11-20 09:52:28 +01:00
Box::new(EvalAltResult::ErrorIndexingType(
type_name.into(),
Position::NONE,
))
2020-10-19 08:26:15 +02:00
}
2020-07-25 03:55:33 +02:00
_ => err,
2020-06-26 04:39:18 +02:00
})
2020-05-05 14:38:48 +02:00
}
_ => EvalAltResult::ErrorIndexingType(
self.map_type_name(target.type_name()).into(),
2020-11-20 09:52:28 +01:00
Position::NONE,
)
.into(),
2020-03-04 15:00:01 +01:00
}
}
2020-11-20 09:52:28 +01:00
// Evaluate an 'in' expression.
2020-04-06 11:47:34 +02:00
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,
2020-10-20 04:54:32 +02:00
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-12-20 16:25:11 +01:00
self.inc_operations(state, 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-12-08 15:47:38 +01:00
Dynamic(Union::Array(mut rhs_value, _)) => {
2020-05-06 17:52:47 +02:00
// Call the `==` operator to compare each value
let def_value = Some(false.into());
2020-11-20 09:52:28 +01:00
let def_value = def_value.as_ref();
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.
2020-12-29 03:41:20 +01:00
let hash_fn =
2020-12-24 09:32:43 +01:00
calc_native_fn_hash(empty(), OP_EQUALS, args.iter().map(|a| a.type_id()))
.unwrap();
2020-04-30 16:52:36 +02:00
2020-12-12 04:15:09 +01:00
let pos = rhs.position();
2020-07-31 06:11:16 +02:00
if self
2020-11-07 16:33:21 +01:00
.call_native_fn(
2020-12-29 03:41:20 +01:00
mods, state, lib, OP_EQUALS, hash_fn, args, false, false, pos,
def_value,
2020-12-12 04:15:09 +01:00
)?
2020-07-31 06:11:16 +02:00
.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
}
2020-11-02 16:54:19 +01:00
Ok(false.into())
2020-04-10 06:16:39 +02:00
}
#[cfg(not(feature = "no_object"))]
2020-12-08 15:47:38 +01:00
Dynamic(Union::Map(rhs_value, _)) => match lhs_value {
2020-10-31 16:26:21 +01:00
// Only allows string or char
2020-12-08 15:47:38 +01:00
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
},
2020-12-08 15:47:38 +01:00
Dynamic(Union::Str(rhs_value, _)) => match lhs_value {
2020-10-31 16:26:21 +01:00
// Only allows string or char
2020-12-08 15:47:38 +01:00
Dynamic(Union::Str(s, _)) => Ok(rhs_value.contains(s.as_str()).into()),
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
}
}
2020-11-20 09:52:28 +01: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,
2020-10-20 04:54:32 +02:00
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-12-20 16:25:11 +01:00
self.inc_operations(state, expr.position())?;
2020-06-13 18:09:16 +02:00
let result = match expr {
2020-11-14 12:04:49 +01:00
Expr::DynamicConstant(x, _) => Ok(x.as_ref().clone()),
2020-10-31 07:13:45 +01:00
Expr::IntegerConstant(x, _) => Ok((*x).into()),
2020-04-12 17:00:06 +02:00
#[cfg(not(feature = "no_float"))]
2020-11-13 11:32:18 +01:00
Expr::FloatConstant(x, _) => Ok((*x).into()),
2020-11-13 03:43:54 +01:00
Expr::StringConstant(x, _) => Ok(x.clone().into()),
2020-10-31 07:13:45 +01:00
Expr::CharConstant(x, _) => Ok((*x).into()),
2020-11-13 03:43:54 +01:00
Expr::FnPointer(x, _) => Ok(FnPtr::new_unchecked(x.clone(), Default::default()).into()),
2020-12-29 03:41:20 +01:00
Expr::Variable(x) if (x.2).name == KEYWORD_THIS => this_ptr
.as_deref()
.cloned()
.ok_or_else(|| EvalAltResult::ErrorUnboundThis((x.2).pos).into()),
Expr::Variable(_) => self
.search_namespace(scope, mods, state, lib, this_ptr, expr)
.map(|(val, _)| val.take_or_clone()),
2020-03-07 03:39:00 +01:00
// Statement block
2020-11-04 04:49:02 +01:00
Expr::Stmt(x, _) => {
self.eval_stmt_block(scope, mods, state, lib, this_ptr, x.as_ref(), level)
2020-11-04 04:49:02 +01:00
}
2020-03-07 03:39:00 +01:00
2020-10-27 16:21:20 +01:00
// lhs[idx_expr]
#[cfg(not(feature = "no_index"))]
2020-10-31 16:26:21 +01:00
Expr::Index(_, _) => {
2020-10-27 16:21:20 +01:00
self.eval_dot_index_chain(scope, mods, state, lib, this_ptr, expr, level, None)
}
// lhs.dot_rhs
#[cfg(not(feature = "no_object"))]
2020-10-31 16:26:21 +01:00
Expr::Dot(_, _) => {
2020-10-27 16:21:20 +01:00
self.eval_dot_index_chain(scope, mods, state, lib, this_ptr, expr, level, None)
}
#[cfg(not(feature = "no_index"))]
2020-11-15 05:07:35 +01:00
Expr::Array(x, _) => {
2020-11-16 09:28:04 +01:00
let mut arr =
Array::with_capacity(crate::stdlib::cmp::max(TYPICAL_ARRAY_SIZE, x.len()));
2020-11-15 05:07:35 +01:00
for item in x.as_ref() {
arr.push(self.eval_expr(scope, mods, state, lib, this_ptr, item, level)?);
}
Ok(Dynamic(Union::Array(Box::new(arr), AccessMode::ReadWrite)))
2020-11-15 05:07:35 +01:00
}
2020-10-27 16:21:20 +01:00
#[cfg(not(feature = "no_object"))]
2020-11-15 05:07:35 +01:00
Expr::Map(x, _) => {
2020-11-16 09:28:04 +01:00
let mut map =
Map::with_capacity(crate::stdlib::cmp::max(TYPICAL_MAP_SIZE, x.len()));
2020-12-22 09:45:56 +01:00
for (Ident { name: key, .. }, expr) in x.as_ref() {
2020-11-15 05:07:35 +01:00
map.insert(
key.clone(),
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?,
);
}
Ok(Dynamic(Union::Map(Box::new(map), AccessMode::ReadWrite)))
2020-11-15 05:07:35 +01:00
}
2020-10-27 16:21:20 +01:00
// Normal function call
2020-10-31 16:26:21 +01:00
Expr::FnCall(x, pos) if x.namespace.is_none() => {
2020-11-10 16:26:50 +01:00
let FnCallExpr {
2020-10-31 07:13:45 +01:00
name,
capture: cap_scope,
2020-12-24 09:32:43 +01:00
hash_script: hash,
2020-10-31 07:13:45 +01:00
args,
def_value,
..
} = x.as_ref();
2020-11-20 09:52:28 +01:00
let def_value = def_value.as_ref();
2020-10-27 16:21:20 +01:00
self.make_function_call(
2020-12-24 09:32:43 +01:00
scope, mods, state, lib, this_ptr, name, args, def_value, *hash, false, *pos,
*cap_scope, level,
2020-10-27 16:21:20 +01:00
)
}
2020-11-10 16:26:50 +01:00
// Namespace-qualified function call
2020-10-31 16:26:21 +01:00
Expr::FnCall(x, pos) if x.namespace.is_some() => {
2020-11-10 16:26:50 +01:00
let FnCallExpr {
2020-10-31 07:13:45 +01:00
name,
namespace,
2020-12-29 03:41:20 +01:00
hash_script,
2020-10-31 07:13:45 +01:00
args,
def_value,
..
} = x.as_ref();
2020-12-24 16:22:50 +01:00
let namespace = namespace.as_ref();
2020-12-29 03:41:20 +01:00
let hash = hash_script.unwrap();
2020-11-20 09:52:28 +01:00
let def_value = def_value.as_ref();
2020-10-27 16:21:20 +01:00
self.make_qualified_function_call(
2020-12-24 09:32:43 +01:00
scope, mods, state, lib, this_ptr, namespace, name, args, def_value, hash,
2020-12-12 04:15:09 +01:00
*pos, level,
2020-10-27 16:21:20 +01:00
)
}
2020-10-31 16:26:21 +01:00
Expr::In(x, _) => {
2020-10-27 16:21:20 +01:00
self.eval_in_expr(scope, mods, state, lib, this_ptr, &x.lhs, &x.rhs, level)
}
2020-10-31 16:26:21 +01:00
Expr::And(x, _) => {
2020-10-27 16:21:20 +01:00
Ok((self
.eval_expr(scope, mods, state, lib, this_ptr, &x.lhs, level)?
.as_bool()
.map_err(|err| self.make_type_mismatch_err::<bool>(err, x.lhs.position()))?
&& // Short-circuit using &&
self
.eval_expr(scope, mods, state, lib, this_ptr, &x.rhs, level)?
.as_bool()
.map_err(|err| self.make_type_mismatch_err::<bool>(err, x.rhs.position()))?)
.into())
}
2020-10-31 16:26:21 +01:00
Expr::Or(x, _) => {
2020-10-27 16:21:20 +01:00
Ok((self
.eval_expr(scope, mods, state, lib, this_ptr, &x.lhs, level)?
.as_bool()
.map_err(|err| self.make_type_mismatch_err::<bool>(err, x.lhs.position()))?
|| // Short-circuit using ||
self
.eval_expr(scope, mods, state, lib, this_ptr, &x.rhs, level)?
.as_bool()
.map_err(|err| self.make_type_mismatch_err::<bool>(err, x.rhs.position()))?)
.into())
}
Expr::BoolConstant(x, _) => Ok((*x).into()),
2020-11-15 16:14:16 +01:00
Expr::Unit(_) => Ok(Dynamic::UNIT),
2020-10-27 16:21:20 +01:00
2020-10-31 16:26:21 +01:00
Expr::Custom(custom, _) => {
2020-10-27 16:21:20 +01:00
let expressions = custom
2020-12-14 16:05:13 +01:00
.keywords
2020-10-27 16:21:20 +01:00
.iter()
.map(Into::into)
.collect::<StaticVec<_>>();
let custom_def = self
.custom_syntax
.get(custom.tokens.first().unwrap())
.unwrap();
2020-10-27 16:21:20 +01:00
let mut context = EvalContext {
engine: self,
scope,
mods,
state,
lib,
this_ptr,
level,
};
(custom_def.func)(&mut context, &expressions)
2020-10-27 16:21:20 +01:00
}
_ => unreachable!("expression cannot be evaluated: {:?}", expr),
2020-10-27 16:21:20 +01:00
};
2020-12-20 16:25:11 +01:00
self.check_data_size(result, expr.position())
2020-10-27 16:21:20 +01:00
}
/// Evaluate a statements block.
pub(crate) fn eval_stmt_block<'a>(
2020-11-04 04:49:02 +01:00
&self,
scope: &mut Scope,
mods: &mut Imports,
state: &mut State,
lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>,
statements: impl IntoIterator<Item = &'a Stmt>,
level: usize,
) -> Result<Dynamic, Box<EvalAltResult>> {
let prev_always_search = state.always_search;
2020-11-04 04:49:02 +01:00
let prev_scope_len = scope.len();
let prev_mods_len = mods.len();
state.scope_level += 1;
let result = statements
.into_iter()
.try_fold(Default::default(), |_, stmt| {
self.eval_stmt(scope, mods, state, lib, this_ptr, stmt, level)
});
scope.rewind(prev_scope_len);
2020-12-18 16:47:17 +01:00
if mods.len() != prev_mods_len {
// If imports list is modified, clear the functions lookup cache
state.functions_cache.clear();
}
2020-11-04 04:49:02 +01:00
mods.truncate(prev_mods_len);
state.scope_level -= 1;
// The impact of new local variables goes away at the end of a block
2020-11-04 04:49:02 +01:00
// because any new variables introduced will go out of scope
state.always_search = prev_always_search;
2020-11-04 04:49:02 +01:00
result
}
2020-11-20 09:52:28 +01:00
/// Evaluate a statement.
2020-10-27 16:21:20 +01:00
///
/// # Safety
///
/// This method uses some unsafe code, mainly for avoiding cloning of local variable names via
/// direct lifetime casting.
pub(crate) fn eval_stmt(
&self,
scope: &mut Scope,
mods: &mut Imports,
state: &mut State,
lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>,
stmt: &Stmt,
level: usize,
) -> Result<Dynamic, Box<EvalAltResult>> {
2020-12-20 16:25:11 +01:00
self.inc_operations(state, stmt.position())?;
2020-10-27 16:21:20 +01:00
let result = match stmt {
// No-op
2020-11-20 15:23:37 +01:00
Stmt::Noop(_) => Ok(Dynamic::UNIT),
2020-10-27 16:21:20 +01:00
// Expression as statement
Stmt::Expr(expr) => self.eval_expr(scope, mods, state, lib, this_ptr, expr, level),
// var op= rhs
2020-10-27 16:21:20 +01:00
Stmt::Assignment(x, op_pos) if x.0.get_variable_access(false).is_some() => {
let (lhs_expr, op, rhs_expr) = x.as_ref();
2020-10-11 15:58:11 +02:00
let mut rhs_val = self
.eval_expr(scope, mods, state, lib, this_ptr, rhs_expr, level)?
.flatten();
2020-12-26 06:05:57 +01:00
let (mut lhs_ptr, pos) =
2020-10-11 15:58:11 +02:00
self.search_namespace(scope, mods, state, lib, this_ptr, lhs_expr)?;
if !lhs_ptr.is_ref() {
2020-12-26 06:05:57 +01:00
return EvalAltResult::ErrorAssignmentToConstant(
lhs_expr.get_variable_access(false).unwrap().to_string(),
pos,
)
.into();
2020-10-11 15:58:11 +02:00
}
2020-12-20 16:25:11 +01:00
self.inc_operations(state, pos)?;
2020-12-08 16:09:12 +01:00
if lhs_ptr.as_ref().is_read_only() {
// Assignment to constant variable
2020-12-08 15:47:38 +01:00
Err(Box::new(EvalAltResult::ErrorAssignmentToConstant(
2020-12-26 06:05:57 +01:00
lhs_expr.get_variable_access(false).unwrap().to_string(),
2020-12-08 15:47:38 +01:00
pos,
)))
} else if op.is_empty() {
// Normal assignment
2020-12-08 15:47:38 +01:00
if cfg!(not(feature = "no_closure")) && lhs_ptr.is_shared() {
*lhs_ptr.as_mut().write_lock::<Dynamic>().unwrap() = rhs_val;
} else {
*lhs_ptr.as_mut() = rhs_val;
}
2020-12-08 15:47:38 +01:00
Ok(Dynamic::UNIT)
} else {
// Op-assignment - in order of precedence:
2020-12-08 15:47:38 +01:00
// 1) Native registered overriding function
// 2) Built-in implementation
// 3) Map to `var = var op rhs`
2020-09-21 10:15:52 +02:00
2020-12-08 15:47:38 +01:00
// Qualifiers (none) + function name + number of arguments + argument `TypeId`'s.
let arg_types = once(lhs_ptr.as_mut().type_id()).chain(once(rhs_val.type_id()));
2020-12-24 09:32:43 +01:00
let hash_fn = calc_native_fn_hash(empty(), op, arg_types).unwrap();
2020-12-08 15:47:38 +01:00
match self
.global_namespace
.get_fn(hash_fn, false)
2021-01-02 17:20:13 +01:00
.map(|f| (f, None))
2020-12-22 16:45:14 +01:00
.or_else(|| {
self.global_modules
.iter()
.find_map(|m| m.get_fn(hash_fn, false).map(|f| (f, m.id_raw())))
2020-12-22 16:45:14 +01:00
})
.or_else(|| mods.get_fn(hash_fn))
2020-12-08 15:47:38 +01:00
{
// op= function registered as method
2021-01-02 17:20:13 +01:00
Some((func, source)) if func.is_method() => {
2020-12-08 15:47:38 +01:00
let mut lock_guard;
let lhs_ptr_inner;
if cfg!(not(feature = "no_closure")) && lhs_ptr.is_shared() {
lock_guard = lhs_ptr.as_mut().write_lock::<Dynamic>().unwrap();
lhs_ptr_inner = lock_guard.deref_mut();
} else {
lhs_ptr_inner = lhs_ptr.as_mut();
}
2020-07-31 10:39:38 +02:00
2020-12-08 15:47:38 +01:00
let args = &mut [lhs_ptr_inner, &mut rhs_val];
// Overriding exact implementation
let source = source.or_else(|| state.source.as_ref());
2020-12-08 15:47:38 +01:00
if func.is_plugin_fn() {
func.get_plugin_fn()
2021-01-02 17:20:13 +01:00
.call((self, source, &*mods, lib).into(), args)?;
2020-12-08 15:47:38 +01:00
} else {
2021-01-02 17:20:13 +01:00
func.get_native_fn()((self, source, &*mods, lib).into(), args)?;
}
2020-12-08 15:47:38 +01:00
}
// Built-in op-assignment function
_ if run_builtin_op_assignment(op, lhs_ptr.as_mut(), &rhs_val)?
.is_some() => {}
// Not built-in: expand to `var = var op rhs`
_ => {
let op = &op[..op.len() - 1]; // extract operator without =
// Clone the LHS value
let args = &mut [&mut lhs_ptr.as_mut().clone(), &mut rhs_val];
// Run function
2020-12-12 04:15:09 +01:00
let (value, _) = self.exec_fn_call(
2020-12-24 09:32:43 +01:00
mods, state, lib, op, None, args, false, false, false, *op_pos,
None, None, level,
2020-12-12 04:15:09 +01:00
)?;
2020-12-08 15:47:38 +01:00
let value = value.flatten();
2020-09-21 10:15:52 +02:00
2020-12-08 15:47:38 +01:00
if cfg!(not(feature = "no_closure")) && lhs_ptr.is_shared() {
*lhs_ptr.as_mut().write_lock::<Dynamic>().unwrap() = value;
} else {
*lhs_ptr.as_mut() = value;
2020-07-31 10:39:38 +02:00
}
2020-05-25 14:14:31 +02:00
}
2020-05-04 11:43:54 +02:00
}
2020-12-08 15:47:38 +01:00
Ok(Dynamic::UNIT)
}
}
// lhs op= rhs
2020-10-27 16:21:20 +01:00
Stmt::Assignment(x, op_pos) => {
let (lhs_expr, op, rhs_expr) = x.as_ref();
let mut rhs_val =
self.eval_expr(scope, mods, state, lib, this_ptr, rhs_expr, level)?;
2020-10-05 07:45:57 +02:00
let _new_val = if op.is_empty() {
// Normal assignment
2020-10-05 07:45:57 +02:00
Some((rhs_val, rhs_expr.position()))
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,
];
2020-10-03 17:27:30 +02:00
Some(
self.exec_fn_call(
2020-12-24 09:32:43 +01:00
mods, state, lib, op, None, args, false, false, false, *op_pos, None,
2020-12-12 04:15:09 +01:00
None, level,
2020-10-03 17:27:30 +02:00
)
.map(|(v, _)| (v, rhs_expr.position()))?,
)
2020-10-03 17:27:30 +02:00
};
2020-05-25 14:14:31 +02:00
// Must be either `var[index] op= val` or `var.prop op= val`
match lhs_expr {
// name op= rhs (handled above)
Expr::Variable(_) => {
unreachable!("Expr::Variable case should already been handled")
}
// idx_lhs[idx_expr] op= rhs
#[cfg(not(feature = "no_index"))]
2020-10-31 16:26:21 +01:00
Expr::Index(_, _) => {
self.eval_dot_index_chain(
2020-10-05 07:45:57 +02:00
scope, mods, state, lib, this_ptr, lhs_expr, level, _new_val,
)?;
2020-11-20 15:23:37 +01:00
Ok(Dynamic::UNIT)
}
// dot_lhs.dot_rhs op= rhs
#[cfg(not(feature = "no_object"))]
2020-10-31 16:26:21 +01:00
Expr::Dot(_, _) => {
self.eval_dot_index_chain(
2020-10-05 07:45:57 +02:00
scope, mods, state, lib, this_ptr, lhs_expr, level, _new_val,
)?;
2020-11-20 15:23:37 +01:00
Ok(Dynamic::UNIT)
}
_ => unreachable!("cannot assign to expression: {:?}", lhs_expr),
2016-02-29 22:43:45 +01:00
}
}
2020-03-01 17:11:00 +01:00
2020-03-06 16:49:52 +01:00
// Block scope
2020-10-27 11:18:19 +01:00
Stmt::Block(statements, _) => {
self.eval_stmt_block(scope, mods, state, lib, this_ptr, statements, level)
2016-02-29 22:43:45 +01:00
}
2020-03-01 17:11:00 +01:00
2020-11-14 16:43:36 +01:00
// If statement
2020-11-14 15:55:23 +01:00
Stmt::If(expr, x, _) => {
2020-10-27 12:23:43 +01:00
let (if_block, else_block) = x.as_ref();
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.as_bool()
.map_err(|err| self.make_type_mismatch_err::<bool>(err, 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 {
2020-11-20 15:23:37 +01:00
Ok(Dynamic::UNIT)
2020-10-27 12:23:43 +01:00
}
})
}
2020-03-01 17:11:00 +01:00
2020-11-14 16:43:36 +01:00
// Switch statement
Stmt::Switch(match_expr, x, _) => {
let (table, def_stmt) = x.as_ref();
let hasher = &mut get_hasher();
2021-01-05 11:01:42 +01:00
self.eval_expr(scope, mods, state, lib, this_ptr, match_expr, level)?
.hash(hasher);
2020-11-14 16:43:36 +01:00
let hash = hasher.finish();
if let Some(stmt) = table.get(&hash) {
self.eval_stmt(scope, mods, state, lib, this_ptr, stmt, level)
} else if let Some(def_stmt) = def_stmt {
self.eval_stmt(scope, mods, state, lib, this_ptr, def_stmt, level)
} else {
2020-11-15 16:14:16 +01:00
Ok(Dynamic::UNIT)
2020-11-14 16:43:36 +01:00
}
}
2020-03-06 16:49:52 +01:00
// While loop
2020-10-27 11:18:19 +01:00
Stmt::While(expr, body, _) => loop {
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 {
2020-10-17 10:34:07 +02:00
EvalAltResult::LoopBreak(false, _) => (),
2020-11-20 15:23:37 +01:00
EvalAltResult::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
_ => return Err(err),
},
}
}
2020-11-20 15:23:37 +01:00
Ok(false) => return Ok(Dynamic::UNIT),
2020-10-05 07:45:57 +02:00
Err(err) => {
return Err(self.make_type_mismatch_err::<bool>(err, 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-11-20 15:23:37 +01:00
// Do loop
Stmt::Do(body, expr, is_while, _) => 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 {
2020-11-20 15:23:37 +01:00
EvalAltResult::LoopBreak(false, _) => continue,
EvalAltResult::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
_ => return Err(err),
},
2017-10-30 16:08:44 +01:00
}
2020-11-20 15:23:37 +01:00
match self
.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.as_bool()
{
Ok(true) if !*is_while => return Ok(Dynamic::UNIT),
Ok(false) if *is_while => return Ok(Dynamic::UNIT),
Ok(_) => (),
Err(err) => {
return Err(self.make_type_mismatch_err::<bool>(err, expr.position()))
}
}
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
2020-10-27 12:23:43 +01:00
Stmt::For(expr, x, _) => {
let (name, stmt) = x.as_ref();
2020-10-14 17:22:10 +02:00
let iter_obj = self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?;
let iter_type = iter_obj.type_id();
2020-03-01 17:11:00 +01:00
2020-10-14 17:22:10 +02:00
let func = self
2020-11-19 06:56:03 +01:00
.global_namespace
2020-10-14 17:22:10 +02:00
.get_iter(iter_type)
2020-12-22 16:45:14 +01:00
.or_else(|| {
self.global_modules
.iter()
.find_map(|m| m.get_iter(iter_type))
})
.or_else(|| mods.get_iter(iter_type));
2020-10-14 17:22:10 +02:00
if let Some(func) = func {
2020-04-24 16:54:56 +02:00
// Add the loop variable
2020-10-28 12:11:17 +01:00
let var_name: Cow<'_, str> = if state.is_global() {
name.clone().into()
} else {
unsafe_cast_var_name_to_lifetime(name).into()
};
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-10-14 17:22:10 +02:00
for iter_value in func(iter_obj) {
2020-12-26 06:05:57 +01:00
let loop_var = scope.get_mut_by_index(index);
2020-08-08 10:24:10 +02:00
let value = iter_value.flatten();
2020-12-29 03:41:20 +01:00
2020-08-08 10:24:10 +02:00
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-12-20 16:25:11 +01:00
self.inc_operations(state, 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 {
2020-10-17 10:34:07 +02:00
EvalAltResult::LoopBreak(false, _) => (),
EvalAltResult::LoopBreak(true, _) => break,
_ => return Err(err),
},
}
}
2020-04-11 12:09:03 +02:00
state.scope_level -= 1;
2020-10-21 08:45:10 +02:00
scope.rewind(scope.len() - 1);
2020-11-20 15:23:37 +01:00
Ok(Dynamic::UNIT)
} else {
2020-10-27 11:18:19 +01:00
EvalAltResult::ErrorFor(expr.position()).into()
}
}
2020-03-01 17:11:00 +01:00
2020-04-01 10:22:18 +02:00
// Continue statement
2020-10-17 10:34:07 +02:00
Stmt::Continue(pos) => EvalAltResult::LoopBreak(false, *pos).into(),
2020-04-01 10:22:18 +02:00
2020-03-06 16:49:52 +01:00
// Break statement
2020-10-17 10:34:07 +02:00
Stmt::Break(pos) => EvalAltResult::LoopBreak(true, *pos).into(),
2020-03-01 17:11:00 +01:00
2020-10-20 17:16:03 +02:00
// Try/Catch statement
2020-11-06 09:27:40 +01:00
Stmt::TryCatch(x, _, _) => {
2020-12-29 03:41:20 +01:00
let (try_body, err_var, catch_body) = x.as_ref();
2020-10-20 17:16:03 +02:00
let result = self
2020-10-27 11:18:19 +01:00
.eval_stmt(scope, mods, state, lib, this_ptr, try_body, level)
2021-01-02 16:30:10 +01:00
.map(|_| Dynamic::UNIT);
2020-10-20 17:16:03 +02:00
2020-10-21 08:45:10 +02:00
match result {
Ok(_) => result,
2020-12-29 03:41:20 +01:00
Err(err) if !err.is_catchable() => Err(err),
Err(mut err) => {
let value = match *err {
EvalAltResult::ErrorRuntime(ref x, _) => x.clone(),
_ => {
2020-11-20 09:52:28 +01:00
err.set_position(Position::NONE);
2020-10-21 08:45:10 +02:00
err.to_string().into()
}
2020-12-29 03:41:20 +01:00
};
2020-10-20 17:16:03 +02:00
2020-12-29 03:41:20 +01:00
let orig_scope_len = scope.len();
state.scope_level += 1;
2020-10-20 17:16:03 +02:00
2020-12-29 03:41:20 +01:00
if let Some(Ident { name, .. }) = err_var {
scope.push(unsafe_cast_var_name_to_lifetime(&name), value);
}
2020-10-20 17:16:03 +02:00
2020-12-29 03:41:20 +01:00
let result =
self.eval_stmt(scope, mods, state, lib, this_ptr, catch_body, level);
2020-10-20 17:16:03 +02:00
2020-12-29 03:41:20 +01:00
state.scope_level -= 1;
scope.rewind(orig_scope_len);
match result {
Ok(_) => Ok(Dynamic::UNIT),
Err(result_err) => match *result_err {
// Re-throw exception
EvalAltResult::ErrorRuntime(Dynamic(Union::Unit(_, _)), pos) => {
err.set_position(pos);
Err(err)
}
_ => Err(result_err),
},
2020-10-20 17:16:03 +02:00
}
2020-12-29 03:41:20 +01:00
}
2020-10-20 17:16:03 +02:00
}
}
2020-03-03 11:15:20 +01:00
// Return value
2020-11-14 15:55:23 +01:00
Stmt::Return((ReturnType::Return, pos), Some(expr), _) => EvalAltResult::Return(
2020-10-27 11:18:19 +01:00
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?,
*pos,
)
.into(),
2020-03-03 11:15:20 +01:00
// Empty return
2020-11-14 15:55:23 +01:00
Stmt::Return((ReturnType::Return, pos), None, _) => {
2020-10-27 11:18:19 +01:00
EvalAltResult::Return(Default::default(), *pos).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-11-14 15:55:23 +01:00
Stmt::Return((ReturnType::Exception, pos), Some(expr), _) => {
let val = self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?;
2020-10-27 11:18:19 +01:00
EvalAltResult::ErrorRuntime(val, *pos).into()
}
2020-03-01 17:11:00 +01:00
// Empty throw
2020-11-14 15:55:23 +01:00
Stmt::Return((ReturnType::Exception, pos), None, _) => {
2021-01-02 16:30:10 +01:00
EvalAltResult::ErrorRuntime(Dynamic::UNIT, *pos).into()
}
2020-10-09 07:25:53 +02:00
// Let/const statement
Stmt::Let(var_def, expr, export, _) | Stmt::Const(var_def, expr, export, _) => {
2020-10-09 07:25:53 +02:00
let entry_type = match stmt {
Stmt::Let(_, _, _, _) => AccessMode::ReadWrite,
Stmt::Const(_, _, _, _) => AccessMode::ReadOnly,
_ => unreachable!("should be Stmt::Let or Stmt::Const, but gets {:?}", stmt),
2020-10-09 07:25:53 +02:00
};
2020-03-13 11:12:41 +01:00
2020-10-09 07:25:53 +02:00
let val = if let Some(expr) = expr {
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.flatten()
2020-10-09 05:15:25 +02:00
} else {
2021-01-02 16:30:10 +01:00
Dynamic::UNIT
2020-10-09 05:15:25 +02:00
};
2020-11-09 05:50:18 +01:00
let (var_name, _alias): (Cow<'_, str>, _) = if state.is_global() {
(
2020-12-11 05:57:07 +01:00
var_def.name.to_string().into(),
if *export {
2020-12-11 05:57:07 +01:00
Some(var_def.name.clone())
} else {
None
},
)
} else if *export {
unreachable!("exported variable not on global level");
2020-10-28 12:11:17 +01:00
} else {
(unsafe_cast_var_name_to_lifetime(&var_def.name).into(), None)
2020-10-28 12:11:17 +01:00
};
2020-11-01 15:46:46 +01:00
scope.push_dynamic_value(var_name, entry_type, val);
2020-11-09 05:50:18 +01:00
#[cfg(not(feature = "no_module"))]
if let Some(alias) = _alias {
2020-11-09 07:38:33 +01:00
scope.add_entry_alias(scope.len() - 1, alias);
}
2020-11-20 15:23:37 +01:00
Ok(Dynamic::UNIT)
2020-03-13 11:12:41 +01:00
}
2020-05-04 13:36:58 +02:00
// Import statement
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_module"))]
2020-10-27 11:18:19 +01:00
Stmt::Import(expr, alias, _pos) => {
// Guard against too many modules
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "unchecked"))]
if state.modules >= self.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>()
{
2021-01-08 17:40:44 +01:00
use crate::ModuleResolver;
2021-01-08 17:24:55 +01:00
let expr_pos = expr.position();
let module = state
.resolver
.as_ref()
.and_then(|r| match r.resolve(self, &path, expr_pos) {
Ok(m) => return Some(Ok(m)),
Err(err) => match *err {
EvalAltResult::ErrorModuleNotFound(_, _) => None,
_ => return Some(Err(err)),
},
})
.unwrap_or_else(|| self.module_resolver.resolve(self, &path, expr_pos))?;
2020-12-26 06:05:57 +01:00
if let Some(name_def) = alias {
if !module.is_indexed() {
// Index the module (making a clone copy if necessary) if it is not indexed
let mut module = crate::fn_native::shared_take_or_clone(module);
module.build_index();
mods.push(name_def.name.clone(), module);
} else {
mods.push(name_def.name.clone(), module);
}
2020-12-26 06:05:57 +01:00
// When imports list is modified, clear the functions lookup cache
state.functions_cache.clear();
}
2020-05-15 15:40:54 +02:00
2020-12-26 06:05:57 +01:00
state.modules += 1;
2020-05-15 15:40:54 +02:00
2020-12-26 06:05:57 +01:00
Ok(Dynamic::UNIT)
} else {
2020-10-05 07:45:57 +02:00
Err(self.make_type_mismatch_err::<ImmutableString>("", expr.position()))
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"))]
2020-10-27 11:18:19 +01:00
Stmt::Export(list, _) => {
2020-12-22 09:45:56 +01:00
for (Ident { name, pos: id_pos }, rename) in list.iter() {
2020-05-08 10:49:24 +02:00
// Mark scope variables as public
2020-10-28 12:11:17 +01:00
if let Some(index) = scope.get_index(name).map(|(i, _)| i) {
let alias = rename.as_ref().map(|x| &x.name).unwrap_or_else(|| name);
2020-12-11 05:57:07 +01:00
scope.add_entry_alias(index, alias.clone());
2020-05-11 17:48:50 +02:00
} else {
2020-11-13 03:43:54 +01:00
return EvalAltResult::ErrorVariableNotFound(name.to_string(), *id_pos)
.into();
2020-05-08 10:49:24 +02:00
}
}
2020-11-20 15:23:37 +01:00
Ok(Dynamic::UNIT)
2020-05-08 10:49:24 +02:00
}
2020-08-03 06:10:20 +02:00
// Share statement
#[cfg(not(feature = "no_closure"))]
2020-10-31 07:13:45 +01:00
Stmt::Share(x) => {
2020-12-09 14:06:36 +01:00
if let Some((index, _)) = scope.get_index(&x.name) {
2020-12-26 06:05:57 +01:00
let val = scope.get_mut_by_index(index);
2020-08-03 06:10:20 +02:00
2020-12-09 14:06:36 +01:00
if !val.is_shared() {
// Replace the variable with a shared value.
*val = crate::stdlib::mem::take(val).into_shared();
2020-08-03 06:10:20 +02:00
}
}
2020-11-20 15:23:37 +01:00
Ok(Dynamic::UNIT)
2020-08-03 06:10:20 +02:00
}
2020-06-13 18:09:16 +02:00
};
2020-12-20 16:25:11 +01:00
self.check_data_size(result, 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.
2020-11-20 09:52:28 +01:00
/// [`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>>,
2020-12-20 16:25:11 +01:00
_pos: Position,
2020-07-26 09:53:22 +02:00
) -> 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-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>>,
2020-12-20 16:25:11 +01:00
pos: Position,
2020-06-14 16:44:59 +02:00
) -> Result<Dynamic, Box<EvalAltResult>> {
2021-01-06 06:46:53 +01:00
// Simply return all errors
if result.is_err() {
return result;
}
2021-01-06 06:46:53 +01:00
// If no data size limits, just return
let mut has_limit = self.limits.max_string_size.is_some();
#[cfg(not(feature = "no_index"))]
2020-07-26 09:53:22 +02:00
{
2021-01-06 06:46:53 +01:00
has_limit = has_limit || self.limits.max_array_size.is_some();
}
#[cfg(not(feature = "no_object"))]
{
2021-01-06 06:46:53 +01:00
has_limit = has_limit || self.limits.max_map_size.is_some();
}
2021-01-06 06:46:53 +01:00
if !has_limit {
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"))]
2020-12-08 15:47:38 +01:00
Dynamic(Union::Array(arr, _)) => {
2020-06-14 08:25:47 +02:00
let mut arrays = 0;
let mut maps = 0;
arr.iter().for_each(|value| match value {
2020-12-08 15:47:38 +01:00
Dynamic(Union::Array(_, _)) => {
2020-07-01 16:21:43 +02:00
let (a, m, _) = calc_size(value);
arrays += a;
maps += m;
}
#[cfg(not(feature = "no_object"))]
2020-12-08 15:47:38 +01:00
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"))]
2020-12-08 15:47:38 +01:00
Dynamic(Union::Map(map, _)) => {
2020-06-14 08:25:47 +02:00
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"))]
2020-12-08 15:47:38 +01:00
Dynamic(Union::Array(_, _)) => {
2020-07-01 16:21:43 +02:00
let (a, m, _) = calc_size(value);
arrays += a;
maps += m;
}
2020-12-08 15:47:38 +01:00
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)
}
2020-12-08 15:47:38 +01:00
Dynamic(Union::Str(s, _)) => (0, 0, s.len()),
2020-06-14 08:25:47 +02:00
_ => (0, 0, 0),
2020-06-13 18:09:16 +02:00
}
2020-06-14 08:25:47 +02:00
}
let (_arr, _map, s) = calc_size(result.as_ref().unwrap());
2020-06-14 08:25:47 +02:00
2021-01-06 06:46:53 +01:00
if s > self
.limits
.max_string_size
.map_or(usize::MAX, NonZeroUsize::get)
{
2020-12-20 16:25:11 +01:00
return EvalAltResult::ErrorDataTooLarge("Length of string".to_string(), pos).into();
}
#[cfg(not(feature = "no_index"))]
2021-01-06 06:46:53 +01:00
if _arr
> self
.limits
.max_array_size
.map_or(usize::MAX, NonZeroUsize::get)
{
2020-12-20 16:25:11 +01:00
return EvalAltResult::ErrorDataTooLarge("Size of array".to_string(), pos).into();
}
#[cfg(not(feature = "no_object"))]
2021-01-06 06:46:53 +01:00
if _map
> self
.limits
.max_map_size
.map_or(usize::MAX, NonZeroUsize::get)
{
2020-12-20 16:25:11 +01:00
return EvalAltResult::ErrorDataTooLarge("Size of object map".to_string(), pos).into();
2016-02-29 22:43:45 +01:00
}
result
2016-02-29 22:43:45 +01:00
}
/// Check if the number of operations stay within limit.
2021-01-02 16:30:10 +01:00
#[inline]
2020-12-20 16:25:11 +01:00
pub(crate) fn inc_operations(
&self,
state: &mut State,
pos: Position,
) -> 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() {
2020-12-20 16:25:11 +01:00
return EvalAltResult::ErrorTooManyOperations(pos).into();
}
// Report progress - only in steps
2020-05-17 16:19:49 +02:00
if let Some(progress) = &self.progress {
2020-12-12 03:10:27 +01:00
if let Some(token) = progress(state.operations) {
2020-11-02 04:04:45 +01:00
// Terminate script if progress returns a termination token
2020-12-20 16:25:11 +01:00
return EvalAltResult::ErrorTerminated(token, pos).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-10-25 14:57:18 +01:00
.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
}
2020-10-05 07:45:57 +02:00
2020-11-20 09:52:28 +01:00
/// Make a `Box<`[`EvalAltResult<ErrorMismatchDataType>`][EvalAltResult::ErrorMismatchDataType]`>`.
2020-10-08 16:25:50 +02:00
#[inline(always)]
2020-10-27 04:30:38 +01:00
pub(crate) fn make_type_mismatch_err<T>(&self, typ: &str, pos: Position) -> Box<EvalAltResult> {
2020-10-05 07:45:57 +02:00
EvalAltResult::ErrorMismatchDataType(
typ.into(),
self.map_type_name(type_name::<T>()).into(),
pos,
)
.into()
}
2016-03-01 15:40:48 +01:00
}