rhai/src/engine.rs

2997 lines
116 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
2021-04-16 07:15:11 +02:00
use crate::ast::{Expr, FnCallExpr, Ident, OpAssignment, ReturnType, Stmt};
use crate::dynamic::{map_std_type_name, AccessMode, Union, Variant};
2020-12-12 03:10:27 +01:00
use crate::fn_native::{
2021-04-25 09:27:58 +02:00
CallableFunction, IteratorFn, OnDebugCallback, OnPrintCallback, 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;
2021-04-17 09:15:54 +02:00
use crate::syntax::CustomSyntax;
2021-04-24 05:55:40 +02:00
use crate::token::Token;
2021-04-17 09:15:54 +02:00
use crate::utils::get_hasher;
use crate::{
2021-04-20 17:40:52 +02:00
Dynamic, EvalAltResult, Identifier, ImmutableString, Module, Position, RhaiResult, Scope,
Shared, StaticVec,
2021-04-17 09:15:54 +02:00
};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{
2020-11-16 09:28:04 +01:00
any::{type_name, TypeId},
2020-10-28 12:11:17 +01:00
borrow::Cow,
2021-03-23 05:13:53 +01:00
collections::{BTreeMap, BTreeSet},
2021-04-17 09:15:54 +02:00
fmt,
2020-11-13 11:32:18 +01:00
hash::{Hash, Hasher},
2021-03-14 03:47:29 +01:00
num::{NonZeroU8, NonZeroUsize},
2021-04-17 07:36:51 +02:00
ops::{Deref, DerefMut},
2020-11-16 16:10:14 +01:00
};
#[cfg(not(feature = "no_index"))]
2021-05-19 14:26:11 +02:00
use crate::Array;
2020-03-04 15:00:01 +01:00
#[cfg(not(feature = "no_object"))]
use crate::Map;
2020-03-29 17:53:35 +02:00
2021-03-31 04:16:38 +02:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
2021-04-20 16:26:08 +02:00
use crate::ast::FnCallHashes;
2021-03-31 04:16:38 +02:00
2021-03-14 03:47:29 +01:00
pub type Precedence = NonZeroU8;
2020-11-25 02:36:06 +01:00
/// _(INTERNALS)_ A stack of imported [modules][Module].
/// Exported under the `internals` feature only.
///
2021-01-16 07:46:03 +01:00
/// # Volatile Data Structure
///
/// 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.
2021-04-27 16:28:01 +02:00
//
// This implementation splits the module names from the shared modules to improve data locality.
// Most usage will be looking up a particular key from the list and then getting the module that
// corresponds to that key.
2021-04-06 17:18:41 +02:00
#[derive(Clone, Default)]
2021-04-27 16:28:01 +02:00
pub struct Imports {
keys: StaticVec<Identifier>,
modules: StaticVec<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 {
2021-04-27 16:28:01 +02:00
self.keys.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 {
2021-04-27 16:28:01 +02:00
self.keys.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>> {
2021-04-27 16:28:01 +02:00
self.modules.get(index).cloned()
2020-11-01 16:42:00 +01:00
}
2021-04-17 11:25:35 +02:00
/// Get the imported [modules][Module] at a particular index.
2021-04-17 12:40:16 +02:00
#[allow(dead_code)]
2021-04-17 11:25:35 +02:00
#[inline(always)]
pub(crate) fn get_mut(&mut self, index: usize) -> Option<&mut Shared<Module>> {
2021-04-27 16:28:01 +02:00
self.modules.get_mut(index)
2021-04-17 11:25:35 +02: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> {
2021-04-27 16:28:01 +02:00
self.keys
2020-12-22 15:36:36 +01:00
.iter()
.enumerate()
.rev()
2021-03-24 06:17:52 +01:00
.find_map(|(i, key)| if *key == name { Some(i) } else { None })
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)]
2021-03-29 05:36:02 +02:00
pub fn push(&mut self, name: impl Into<Identifier>, module: impl Into<Shared<Module>>) {
2021-04-27 16:28:01 +02:00
self.keys.push(name.into());
self.modules.push(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) {
2021-04-27 16:28:01 +02:00
self.keys.truncate(size);
self.modules.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)> {
2021-04-27 16:28:01 +02:00
self.keys
2020-12-22 15:36:36 +01:00
.iter()
2021-04-27 16:28:01 +02:00
.zip(self.modules.iter())
2020-12-22 15:36:36 +01:00
.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-03-29 05:36:02 +02:00
pub(crate) fn iter_raw(&self) -> impl Iterator<Item = (&Identifier, &Shared<Module>)> {
2021-04-27 16:28:01 +02:00
self.keys.iter().rev().zip(self.modules.iter().rev())
2020-11-01 16:42:00 +01:00
}
/// Get an iterator to this stack of imported [modules][Module] in forward order.
2021-03-07 15:10:54 +01:00
#[allow(dead_code)]
#[inline(always)]
2021-03-29 05:36:02 +02:00
pub(crate) fn scan_raw(&self) -> impl Iterator<Item = (&Identifier, &Shared<Module>)> {
2021-04-27 16:28:01 +02:00
self.keys.iter().zip(self.modules.iter())
}
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)]
2021-03-29 05:36:02 +02:00
pub fn into_iter(self) -> impl Iterator<Item = (Identifier, Shared<Module>)> {
2021-04-27 16:28:01 +02:00
self.keys
.into_iter()
.rev()
.zip(self.modules.into_iter().rev())
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)]
2021-03-08 08:30:32 +01:00
pub fn contains_fn(&self, hash: u64) -> bool {
2021-04-27 16:28:01 +02:00
self.modules.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-03-29 05:36:02 +02:00
pub fn get_fn(&self, hash: u64) -> Option<(&CallableFunction, Option<&Identifier>)> {
2021-04-27 16:28:01 +02:00
self.modules
2020-12-24 09:32:43 +01:00
.iter()
.rev()
2021-03-12 15:30:08 +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 {
2021-04-27 16:28:01 +02:00
self.modules.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> {
2021-04-27 16:28:01 +02:00
self.modules
.iter()
.rev()
.find_map(|m| m.get_qualified_iter(id))
}
2020-11-01 16:42:00 +01:00
}
2021-04-06 17:18:41 +02:00
impl fmt::Debug for Imports {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Imports")?;
if self.is_empty() {
f.debug_map().finish()
} else {
f.debug_map()
2021-04-27 16:28:01 +02:00
.entries(self.keys.iter().zip(self.modules.iter()))
2021-04-06 17:18:41 +02:00
.finish()
}
}
}
#[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 = 64;
#[cfg(not(feature = "unchecked"))]
#[cfg(not(debug_assertions))]
pub const MAX_EXPR_DEPTH: usize = 64;
#[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
2021-02-24 15:40:18 +01:00
pub const MAX_DYNAMIC_PARAMETERS: usize = 16;
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";
2021-03-01 15:44:56 +01:00
#[cfg(not(feature = "no_function"))]
pub const KEYWORD_IS_DEF_FN: &str = "is_def_fn";
2020-06-26 04:39:18 +02:00
pub const KEYWORD_THIS: &str = "this";
2021-04-17 11:25:35 +02:00
#[cfg(not(feature = "no_function"))]
pub const KEYWORD_GLOBAL: &str = "global";
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$";
2021-05-18 14:12:30 +02:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
2020-07-09 13:54:28 +02:00
pub const FN_IDX_GET: &str = "index$get$";
2021-05-18 14:12:30 +02:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
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$";
/// Standard equality comparison operator.
2020-11-08 16:00:37 +01:00
pub const OP_EQUALS: &str = "==";
2020-03-03 10:28:38 +01:00
/// Standard method function for containment testing.
///
/// The `in` operator is implemented as a call to this method.
pub const OP_CONTAINS: &str = "contains";
2021-04-24 05:55:40 +02:00
/// Standard concatenation operator token.
pub const TOKEN_OP_CONCAT: Token = Token::PlusAssign;
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)]
2021-04-27 16:28:01 +02:00
enum ChainType {
2021-01-02 16:30:10 +01:00
/// Indexing.
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_index"))]
Index,
2021-01-02 16:30:10 +01:00
/// Dotting.
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
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)]
2021-04-27 16:28:01 +02:00
enum ChainArgument {
2021-01-02 16:30:10 +01:00
/// Dot-property access.
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
Property(Position),
2021-04-27 16:28:01 +02:00
/// Arguments to a dot method call.
#[cfg(not(feature = "no_object"))]
MethodCallArgs(StaticVec<Dynamic>, StaticVec<Position>),
2021-01-02 16:30:10 +01:00
/// Index value.
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_index"))]
IndexValue(Dynamic, Position),
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-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
Self::Property(_) | Self::MethodCallArgs(_, _) => {
panic!("expecting ChainArgument::IndexValue")
}
Self::IndexValue(value, _) => value,
2020-10-15 17:30:30 +02:00
}
}
/// Return the `StaticVec<Dynamic>` value.
///
/// # Panics
///
2021-04-27 16:28:01 +02:00
/// Panics if not `ChainArgument::MethodCallArgs`.
2020-12-29 03:41:20 +01:00
#[inline(always)]
#[cfg(not(feature = "no_object"))]
2021-03-09 11:11:43 +01:00
pub fn as_fn_call_args(self) -> (StaticVec<Dynamic>, StaticVec<Position>) {
2020-10-15 17:30:30 +02:00
match self {
2021-04-27 16:28:01 +02:00
Self::Property(_) => {
panic!("expecting ChainArgument::MethodCallArgs")
}
#[cfg(not(feature = "no_index"))]
Self::IndexValue(_, _) => {
panic!("expecting ChainArgument::MethodCallArgs")
}
2021-04-27 16:28:01 +02:00
Self::MethodCallArgs(values, positions) => (values, positions),
2020-10-15 17:30:30 +02:00
}
}
}
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
2021-03-09 11:11:43 +01:00
impl From<(StaticVec<Dynamic>, StaticVec<Position>)> for ChainArgument {
2020-12-29 03:41:20 +01:00
#[inline(always)]
2021-03-09 11:11:43 +01:00
fn from((values, positions): (StaticVec<Dynamic>, StaticVec<Position>)) -> Self {
2021-04-27 16:28:01 +02:00
Self::MethodCallArgs(values, positions)
2020-10-15 17:30:30 +02:00
}
}
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_index"))]
impl From<(Dynamic, Position)> for ChainArgument {
2020-12-29 03:41:20 +01:00
#[inline(always)]
fn from((value, pos): (Dynamic, Position)) -> Self {
Self::IndexValue(value, pos)
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?
#[cfg(not(feature = "no_closure"))]
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 {
2021-03-23 13:04:54 +01:00
Self::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"))]
2021-03-23 13:04:54 +01:00
Self::LockGuard((r, _)) => r.is::<T>(),
Self::Value(r) => r.is::<T>(),
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_index"))]
2021-03-23 13:04:54 +01:00
Self::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)]
2021-05-22 13:14:24 +02:00
pub fn propagate_changed_value(&mut self) -> Result<(), Box<EvalAltResult>> {
2020-10-04 04:40:44 +02:00
match self {
2021-05-22 13:14:24 +02:00
Self::Ref(_) | Self::Value(_) => Ok(()),
2020-10-05 06:05:46 +02:00
#[cfg(not(feature = "no_closure"))]
2021-05-22 13:14:24 +02:00
Self::LockGuard(_) => Ok(()),
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();
2021-05-22 13:14:24 +02:00
self.set_value(char_value, Position::NONE)
2020-10-04 04:40:44 +02:00
}
}
}
2020-04-26 12:04:07 +02:00
/// Update the value of the `Target`.
pub fn set_value(
&mut self,
new_val: Dynamic,
_pos: Position,
) -> Result<(), Box<EvalAltResult>> {
2020-03-30 16:19:37 +02:00
match self {
2020-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"))]
2021-03-07 15:10:54 +01:00
Self::StringChar(s, index, _) => {
2021-05-22 13:14:24 +02:00
let s = &mut *s
.write_lock::<ImmutableString>()
.expect("never fails because `StringChar` always holds an `ImmutableString`");
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(
"char".to_string(),
2021-02-28 07:38:34 +01:00
err.to_string(),
_pos,
2020-10-03 17:27:30 +02:00
))
})?;
2020-05-16 05:42:56 +02:00
2021-03-07 15:10:54 +01:00
let index = *index;
2020-05-16 05:42:56 +02:00
2021-03-07 15:10:54 +01:00
*s = s
.chars()
.enumerate()
.map(|(i, ch)| if i == index { new_ch } else { ch })
.collect();
2020-05-16 05:42:56 +02:00
}
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();
2021-05-22 13:14:24 +02:00
return Self::LockGuard((
value
.write_lock::<Dynamic>()
.expect("never fails when casting to `Dynamic`"),
container,
));
}
Self::Ref(value)
2020-04-26 12:04:07 +02:00
}
}
2021-04-17 07:36:51 +02:00
impl Deref for Target<'_> {
type Target = Dynamic;
#[inline(always)]
2021-04-17 07:36:51 +02:00
fn deref(&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,
}
}
}
2021-04-17 07:36:51 +02:00
impl AsRef<Dynamic> for Target<'_> {
#[inline(always)]
2021-04-17 07:36:51 +02:00
fn as_ref(&self) -> &Dynamic {
self
}
}
impl DerefMut for Target<'_> {
#[inline(always)]
fn deref_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,
}
}
}
2021-04-17 07:36:51 +02:00
impl AsMut<Dynamic> for Target<'_> {
#[inline(always)]
fn as_mut(&mut self) -> &mut Dynamic {
self
}
}
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())
}
}
2021-03-13 11:46:08 +01:00
/// An entry in a function resolution cache.
#[derive(Debug, Clone)]
pub struct FnResolutionCacheEntry {
/// Function.
pub func: CallableFunction,
/// Optional source.
2021-03-29 05:36:02 +02:00
pub source: Option<Identifier>,
2021-03-13 11:46:08 +01:00
}
/// A function resolution cache.
2021-05-03 07:45:41 +02:00
pub type FnResolutionCache = BTreeMap<u64, Option<Box<FnResolutionCacheEntry>>>;
2021-03-13 11:46:08 +01:00
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-16 07:46:03 +01:00
/// # Volatile Data Structure
///
/// 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.
2021-03-29 05:36:02 +02:00
pub source: Option<Identifier>,
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>>,
2021-03-17 06:30:47 +01:00
/// Function resolution cache and free list.
fn_resolution_caches: (StaticVec<FnResolutionCache>, Vec<FnResolutionCache>),
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
}
2021-03-13 11:46:08 +01:00
/// Get a mutable reference to the current function resolution cache.
2021-04-21 11:39:45 +02:00
#[inline(always)]
2021-03-13 11:46:08 +01:00
pub fn fn_resolution_cache_mut(&mut self) -> &mut FnResolutionCache {
2021-03-17 06:30:47 +01:00
if self.fn_resolution_caches.0.is_empty() {
2021-05-22 13:14:24 +02:00
// Push a new function resolution cache if the stack is empty
2021-03-23 05:13:53 +01:00
self.fn_resolution_caches.0.push(BTreeMap::new());
}
2021-05-22 13:14:24 +02:00
self.fn_resolution_caches.0.last_mut().expect(
"never fails because there is at least one function resolution cache by this point",
)
}
2021-03-13 11:46:08 +01:00
/// Push an empty function resolution cache onto the stack and make it current.
2021-03-07 15:10:54 +01:00
#[allow(dead_code)]
2021-04-21 11:39:45 +02:00
#[inline(always)]
pub fn push_fn_resolution_cache(&mut self) {
2021-03-17 06:30:47 +01:00
self.fn_resolution_caches
.0
.push(self.fn_resolution_caches.1.pop().unwrap_or_default());
}
2021-03-13 11:46:08 +01:00
/// Remove the current function resolution cache from the stack and make the last one current.
///
/// # Panics
///
/// Panics if there are no more function resolution cache in the stack.
2021-04-21 11:39:45 +02:00
#[inline(always)]
pub fn pop_fn_resolution_cache(&mut self) {
2021-05-22 13:14:24 +02:00
let mut cache = self
.fn_resolution_caches
.0
.pop()
.expect("there should be at least one function resolution cache");
2021-03-13 11:46:08 +01:00
cache.clear();
2021-03-17 06:30:47 +01:00
self.fn_resolution_caches.1.push(cache);
}
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-16 07:46:03 +01:00
/// # Volatile Data Structure
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.
2021-01-06 06:46:53 +01:00
///
/// Set to zero to effectively disable function calls.
///
/// Not available under `no_function`.
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.
2021-04-17 09:15:54 +02:00
pub max_operations: Option<std::num::NonZeroU64>,
2020-11-25 02:36:06 +01:00
/// Maximum number of [modules][Module] allowed to load.
2021-01-06 06:46:53 +01:00
///
/// Set to zero to effectively disable loading any [module][Module].
///
/// Not available under `no_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-04-04 07:13:07 +02:00
/// Maximum length of a [string][ImmutableString].
2021-01-06 06:46:53 +01:00
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)]
2021-03-03 15:49:57 +01:00
pub struct EvalContext<'a, 'x, 'px, 'm, 's, 't, 'pt> {
pub(crate) engine: &'a Engine,
2020-12-14 16:05:13 +01:00
pub(crate) scope: &'x mut Scope<'px>,
2021-03-03 15:49:57 +01:00
pub(crate) mods: &'m mut Imports,
2020-10-11 15:58:11 +02:00
pub(crate) state: &'s mut State,
2021-03-03 15:49:57 +01:00
pub(crate) lib: &'a [&'a Module],
pub(crate) this_ptr: &'t mut Option<&'pt mut Dynamic>,
pub(crate) level: usize,
2020-10-11 15:58:11 +02:00
}
2021-03-03 15:49:57 +01:00
impl<'x, 'px> EvalContext<'_, 'x, 'px, '_, '_, '_, '_> {
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.
/// Exported under the `internals` feature only.
2020-10-11 15:58:11 +02:00
#[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.
/// Exported under the `internals` feature only.
2021-01-01 10:05:06 +01:00
#[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-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.
2021-03-29 05:36:02 +02:00
pub(crate) global_sub_modules: BTreeMap<Identifier, 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
2021-03-23 05:13:53 +01:00
/// A map mapping type names to pretty-print names.
2021-05-03 07:45:41 +02:00
pub(crate) type_names: BTreeMap<Identifier, Box<Identifier>>,
2020-07-05 09:23:51 +02:00
2021-04-04 07:13:07 +02:00
/// An empty [`ImmutableString`] for cloning purposes.
pub(crate) empty_string: ImmutableString,
2021-03-23 05:13:53 +01:00
/// A set of symbols to disable.
pub(crate) disabled_symbols: BTreeSet<Identifier>,
2021-03-23 05:13:53 +01:00
/// A map containing custom keywords and precedence to recognize.
pub(crate) custom_keywords: BTreeMap<Identifier, Option<Precedence>>,
2020-07-09 13:54:28 +02:00
/// Custom syntax.
2021-05-03 07:45:41 +02:00
pub(crate) custom_syntax: BTreeMap<Identifier, Box<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.
2021-04-25 09:27:58 +02:00
#[cfg(not(feature = "unchecked"))]
pub(crate) progress: Option<crate::fn_native::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,
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 {
2021-03-03 15:49:57 +01:00
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"))]
2021-02-19 08:50:48 +01:00
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
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"))]
2021-02-19 08:50:48 +01:00
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
2020-12-21 15:04:46 +01:00
if let Some(source) = _source {
2021-04-23 08:24:53 +02:00
println!("{}{:?} | {}", source, _pos, _s);
2021-04-22 17:02:25 +02:00
} else if _pos.is_none() {
println!("{}", _s);
2020-12-21 15:04:46 +01:00
} else {
println!("{:?} | {}", _pos, _s);
}
2020-12-12 04:47:18 +01:00
}
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-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"))]
2021-02-19 08:50:48 +01:00
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
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(),
2021-04-04 07:13:07 +02:00
empty_string: Default::default(),
2020-11-15 06:49:54 +01:00
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
2021-04-25 09:27:58 +02:00
#[cfg(not(feature = "unchecked"))]
2020-10-03 17:27:30 +02:00
progress: None,
// optimization level
2021-05-18 06:24:11 +02:00
optimization_level: Default::default(),
2020-10-03 17:27:30 +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-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
},
};
engine.global_namespace.internal = true;
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.
2021-03-04 11:13:47 +01:00
#[inline(always)]
pub fn new_raw() -> Self {
2021-04-17 12:40:16 +02:00
let mut engine = Self {
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(),
2021-04-04 07:13:07 +02:00
empty_string: Default::default(),
2020-11-15 06:49:54 +01:00
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(|_, _, _| {}),
2021-04-25 09:27:58 +02:00
#[cfg(not(feature = "unchecked"))]
progress: None,
2021-05-18 06:24:11 +02:00
optimization_level: Default::default(),
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
},
2021-04-17 12:40:16 +02:00
};
engine.global_namespace.internal = true;
2021-04-17 12:40:16 +02:00
engine
}
2021-03-01 07:54:20 +01:00
/// Search for a module within an imports stack.
2021-03-09 04:55:49 +01:00
#[inline]
2021-03-03 15:49:57 +01:00
pub(crate) fn search_imports(
2021-03-01 07:54:20 +01:00
&self,
mods: &Imports,
state: &mut State,
namespace: &NamespaceRef,
2021-03-03 15:49:57 +01:00
) -> Option<Shared<Module>> {
let root = &namespace[0].name;
2021-03-01 07:54:20 +01:00
// Qualified - check if the root module is directly indexed
let index = if state.always_search {
None
} else {
namespace.index()
};
2021-03-03 15:49:57 +01:00
if let Some(index) = index {
2021-03-01 07:54:20 +01:00
let offset = mods.len() - index.get();
2021-05-22 13:14:24 +02:00
Some(
mods.get(offset)
.expect("never fails because offset should be within range"),
)
2021-03-01 07:54:20 +01:00
} else {
mods.find(root)
2021-05-22 13:14:24 +02:00
.map(|n| {
mods.get(n)
.expect("never fails because the index came from `find`")
})
2021-03-01 07:54:20 +01:00
.or_else(|| self.global_sub_modules.get(root).cloned())
2021-03-03 15:49:57 +01:00
}
2021-03-01 07:54:20 +01:00
}
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 {
2021-04-05 17:59:15 +02:00
Expr::Variable(Some(_), _, _) => {
2021-04-05 17:06:48 +02:00
self.search_scope_only(scope, mods, state, lib, this_ptr, expr)
}
2021-04-05 17:59:15 +02:00
Expr::Variable(None, var_pos, v) => match v.as_ref() {
2021-04-05 17:06:48 +02:00
// Normal variable access
(_, None, _) => self.search_scope_only(scope, mods, state, lib, this_ptr, expr),
2020-10-11 15:58:11 +02:00
// Qualified variable
2021-04-05 17:59:15 +02:00
(_, Some((hash_var, modules)), var_name) => {
2021-03-03 15:49:57 +01:00
let module = self.search_imports(mods, state, modules).ok_or_else(|| {
EvalAltResult::ErrorModuleNotFound(
modules[0].name.to_string(),
modules[0].pos,
)
})?;
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, _) => {
2021-04-05 17:59:15 +02:00
*err_name = format!("{}{}", modules, var_name);
2020-12-24 16:22:50 +01:00
}
_ => (),
}
2021-04-05 17:59:15 +02:00
err.fill_position(*var_pos)
2020-12-24 16:22:50 +01:00
})?;
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);
2021-04-05 17:59:15 +02:00
Ok((target.into(), *var_pos))
2020-10-11 15:58:11 +02:00
}
},
_ => unreachable!("Expr::Variable expected, but gets {:?}", expr),
2020-10-11 15:58:11 +02:00
}
}
/// Search for a variable within the scope
2021-05-22 13:14:24 +02:00
///
/// # Panics
///
/// Panics if `expr` is not [`Expr::Variable`].
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>> {
2021-04-05 17:59:15 +02:00
// Make sure that the pointer indirection is taken only when absolutely necessary.
2020-10-11 15:58:11 +02:00
2021-04-05 17:59:15 +02:00
let (index, var_pos) = match expr {
// Check if the variable is `this`
Expr::Variable(None, pos, v) if v.0.is_none() && v.2 == KEYWORD_THIS => {
return if let Some(val) = this_ptr {
Ok(((*val).into(), *pos))
} else {
EvalAltResult::ErrorUnboundThis(*pos).into()
}
}
_ if state.always_search => (0, expr.position()),
Expr::Variable(Some(i), pos, _) => (i.get() as usize, *pos),
Expr::Variable(None, pos, v) => (v.0.map(NonZeroUsize::get).unwrap_or(0), *pos),
_ => unreachable!("Expr::Variable expected, but gets {:?}", expr),
2021-04-05 17:06:48 +02:00
};
2020-10-11 15:58:11 +02:00
// Check the variable resolver, if any
if let Some(ref resolve_var) = self.resolve_var {
let context = EvalContext {
engine: self,
scope,
2020-10-11 15:58:11 +02:00
mods,
state,
lib,
this_ptr,
level: 0,
};
2021-05-22 13:14:24 +02:00
if let Some(mut result) = resolve_var(
expr.get_variable_name(true)
.expect("`expr` should be `Variable`"),
index,
&context,
)
.map_err(|err| err.fill_position(var_pos))?
2020-10-11 15:58:11 +02:00
{
result.set_access_mode(AccessMode::ReadOnly);
2021-04-05 17:59:15 +02:00
return Ok((result.into(), var_pos));
2020-10-11 15:58:11 +02:00
}
}
2021-04-05 17:06:48 +02:00
let index = if index > 0 {
scope.len() - index
2020-10-11 15:58:11 +02:00
} else {
// Find the variable in the scope
2021-05-22 13:14:24 +02:00
let var_name = expr
.get_variable_name(true)
.expect("`expr` should be `Variable`");
2020-10-11 15:58:11 +02:00
scope
2021-04-05 17:59:15 +02:00
.get_index(var_name)
.ok_or_else(|| EvalAltResult::ErrorVariableNotFound(var_name.to_string(), var_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-04-05 17:59:15 +02:00
Ok((val.into(), var_pos))
2020-10-11 15:58:11 +02:00
}
2020-04-26 12:04:07 +02:00
/// Chain-evaluate a dot/index chain.
2021-03-03 15:49:57 +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,
root: (&str, Position),
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,
2021-03-23 13:04:54 +01:00
new_val: Option<((Dynamic, Position), (Option<OpAssignment>, Position))>,
2020-04-26 12:04:07 +02:00
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
2021-05-22 13:14:24 +02:00
fn match_chain_type(expr: &Expr) -> ChainType {
match expr {
#[cfg(not(feature = "no_index"))]
Expr::Index(_, _) => ChainType::Index,
#[cfg(not(feature = "no_object"))]
Expr::Dot(_, _) => ChainType::Dot,
_ => unreachable!("`expr` should only be `Index` or `Dot`, but got {:?}", expr),
}
}
2020-03-01 17:11:00 +01:00
2021-05-22 13:14:24 +02:00
let is_ref = target.is_ref();
2020-04-26 12:04:07 +02:00
// Pop the last index value
2021-05-22 13:14:24 +02:00
let idx_val = idx_values
.pop()
.expect("never fails because an index chain is never empty");
2020-03-01 17:11:00 +01:00
match chain_type {
#[cfg(not(feature = "no_index"))]
ChainType::Index => {
let pos = rhs.position();
match rhs {
// xxx[idx].expr... | xxx[idx][expr]...
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(
2021-05-18 15:38:09 +02:00
mods, state, lib, target, idx_val, idx_pos, false, true, level,
2020-08-01 06:21:15 +02:00
)?;
2021-05-22 13:14:24 +02:00
let rhs_chain = match_chain_type(rhs);
self.eval_dot_index_chain_helper(
mods, state, lib, this_ptr, obj_ptr, root, &x.rhs, idx_values,
rhs_chain, level, new_val,
)
2020-10-31 16:26:21 +01:00
.map_err(|err| err.fill_position(*x_pos))
}
// xxx[rhs] op= new_val
2020-08-08 10:24:10 +02:00
_ if new_val.is_some() => {
2021-05-22 13:14:24 +02:00
let ((mut new_val, new_pos), (op_info, op_pos)) =
new_val.expect("never fails because `new_val` is `Some`");
2021-01-02 16:30:10 +01:00
let idx_val = idx_val.as_index_value();
2021-03-23 13:04:54 +01:00
#[cfg(not(feature = "no_index"))]
2021-05-19 14:26:11 +02:00
let mut idx_val_for_setter = idx_val.clone();
2021-05-19 14:26:11 +02:00
match self.get_indexed_mut(
2021-05-18 15:38:09 +02:00
mods, state, lib, target, idx_val, pos, true, false, level,
) {
// Indexed value is a reference - update directly
2021-02-24 04:04:54 +01:00
Ok(obj_ptr) => {
self.eval_op_assignment(
mods, state, lib, op_info, op_pos, obj_ptr, root, new_val,
new_pos,
2021-02-24 04:04:54 +01:00
)?;
2021-05-19 14:26:11 +02:00
return Ok((Dynamic::UNIT, true));
}
2021-05-19 14:26:11 +02:00
// Can't index - try to call an index setter
#[cfg(not(feature = "no_index"))]
Err(err) if matches!(*err, EvalAltResult::ErrorIndexingType(_, _)) => {}
// Any other error
Err(err) => return Err(err),
}
2021-05-19 14:26:11 +02:00
// Try to call index setter
let hash_set =
FnCallHashes::from_native(crate::calc_fn_hash(FN_IDX_SET, 3));
let args = &mut [target, &mut idx_val_for_setter, &mut new_val];
self.exec_fn_call(
mods, state, lib, FN_IDX_SET, hash_set, args, is_ref, true, new_pos,
None, level,
)?;
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(
2021-05-18 15:38:09 +02:00
mods, state, lib, target, idx_val, pos, false, 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)
2021-04-20 17:28:04 +02:00
Expr::FnCall(x, pos) if !x.is_qualified() && new_val.is_none() => {
2021-04-20 16:26:08 +02:00
let FnCallExpr { name, hashes, .. } = x.as_ref();
let mut args = idx_val.as_fn_call_args();
self.make_method_call(
2021-04-20 16:26:08 +02:00
mods, state, lib, name, *hashes, target, &mut args, *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 op= ???
2021-04-17 07:36:51 +02:00
Expr::Property(x) if target.is::<Map>() && new_val.is_some() => {
2021-05-18 14:12:30 +02:00
let (name, pos) = &x.2;
2021-03-29 05:36:02 +02:00
let index = name.into();
2021-02-24 04:04:54 +01:00
let val = self.get_indexed_mut(
2021-05-18 15:38:09 +02:00
mods, state, lib, target, index, *pos, true, false, level,
)?;
2021-05-22 13:14:24 +02:00
let ((new_val, new_pos), (op_info, op_pos)) =
new_val.expect("never fails because `new_val` is `Some`");
2021-02-24 04:04:54 +01:00
self.eval_op_assignment(
mods, state, lib, op_info, op_pos, val, root, new_val, new_pos,
2021-02-24 04:04:54 +01:00
)?;
Ok((Dynamic::UNIT, true))
}
// {xxx:map}.id
2021-04-17 07:36:51 +02:00
Expr::Property(x) if target.is::<Map>() => {
2021-05-18 14:12:30 +02:00
let (name, pos) = &x.2;
2021-03-29 05:36:02 +02:00
let index = name.into();
2020-08-01 06:21:15 +02:00
let val = self.get_indexed_mut(
2021-05-18 15:38:09 +02:00
mods, state, lib, target, index, *pos, false, 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 op= ???
2020-08-08 10:24:10 +02:00
Expr::Property(x) if new_val.is_some() => {
2021-05-18 14:12:30 +02:00
let ((getter, hash_get), (setter, hash_set), (name, pos)) = x.as_ref();
2021-05-22 13:14:24 +02:00
let ((mut new_val, new_pos), (op_info, op_pos)) =
new_val.expect("never fails because `new_val` is `Some`");
if op_info.is_some() {
2021-04-20 16:26:08 +02:00
let hash = FnCallHashes::from_native(*hash_get);
let mut args = [target.as_mut()];
2021-05-18 15:38:09 +02:00
let (mut orig_val, _) = self
.exec_fn_call(
mods, state, lib, getter, hash, &mut args, is_ref, true, *pos,
None, level,
)
.or_else(|err| match *err {
// Try an indexer if property does not exist
EvalAltResult::ErrorDotExpr(_, _) => {
let prop = name.into();
self.get_indexed_mut(
mods, state, lib, target, prop, *pos, false, true,
level,
)
.map(|v| (v.take_or_clone(), false))
.map_err(
|idx_err| match *idx_err {
EvalAltResult::ErrorIndexingType(_, _) => err,
_ => idx_err,
},
)
}
_ => Err(err),
})?;
let obj_ptr = (&mut orig_val).into();
self.eval_op_assignment(
mods, state, lib, op_info, op_pos, obj_ptr, root, new_val, new_pos,
)?;
new_val = orig_val;
}
2021-04-20 16:26:08 +02:00
let hash = FnCallHashes::from_native(*hash_set);
let mut args = [target.as_mut(), &mut new_val];
2020-06-26 04:39:18 +02:00
self.exec_fn_call(
2021-03-08 08:30:32 +01:00
mods, state, lib, setter, hash, &mut args, is_ref, true, *pos, None,
2021-03-01 08:39:49 +01:00
level,
2020-06-26 04:39:18 +02:00
)
2021-05-18 14:12:30 +02:00
.or_else(|err| match *err {
// Try an indexer if property does not exist
EvalAltResult::ErrorDotExpr(_, _) => {
let mut prop = name.into();
let args = &mut [target, &mut prop, &mut new_val];
2021-05-19 14:26:11 +02:00
let hash_set =
FnCallHashes::from_native(crate::calc_fn_hash(FN_IDX_SET, 3));
2021-05-18 14:12:30 +02:00
self.exec_fn_call(
mods, state, lib, FN_IDX_SET, hash_set, args, is_ref, true,
*pos, None, level,
)
.map_err(
|idx_err| match *idx_err {
EvalAltResult::ErrorIndexingType(_, _) => err,
_ => idx_err,
},
)
}
_ => Err(err),
})
}
// xxx.id
Expr::Property(x) => {
2021-05-18 14:12:30 +02:00
let ((getter, hash_get), _, (name, pos)) = x.as_ref();
2021-04-20 16:26:08 +02:00
let hash = FnCallHashes::from_native(*hash_get);
2021-04-17 07:36:51 +02:00
let mut args = [target.as_mut()];
2020-06-26 04:39:18 +02:00
self.exec_fn_call(
2021-03-08 08:30:32 +01:00
mods, state, lib, getter, hash, &mut args, is_ref, true, *pos, None,
2021-03-01 08:39:49 +01:00
level,
2020-06-26 04:39:18 +02:00
)
2021-05-18 14:12:30 +02:00
.map_or_else(
|err| match *err {
// Try an indexer if property does not exist
EvalAltResult::ErrorDotExpr(_, _) => {
let prop = name.into();
self.get_indexed_mut(
2021-05-18 15:38:09 +02:00
mods, state, lib, target, prop, *pos, false, true, level,
2021-05-18 14:12:30 +02:00
)
.map(|v| (v.take_or_clone(), false))
.map_err(|idx_err| {
match *idx_err {
EvalAltResult::ErrorIndexingType(_, _) => err,
_ => idx_err,
}
})
}
_ => Err(err),
},
|(v, _)| Ok((v, false)),
)
}
2020-07-09 16:21:07 +02:00
// {xxx:map}.sub_lhs[expr] | {xxx:map}.sub_lhs.expr
2021-04-17 07:36:51 +02:00
Expr::Index(x, x_pos) | Expr::Dot(x, x_pos) if target.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) => {
2021-05-18 14:12:30 +02:00
let (name, pos) = &p.2;
2021-03-29 05:36:02 +02:00
let index = name.into();
2020-08-01 06:21:15 +02:00
self.get_indexed_mut(
2021-05-18 15:38:09 +02:00
mods, state, lib, target, index, *pos, false, 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
2021-04-20 17:28:04 +02:00
Expr::FnCall(x, pos) if !x.is_qualified() => {
2021-04-20 16:26:08 +02:00
let FnCallExpr { name, hashes, .. } = x.as_ref();
let mut args = idx_val.as_fn_call_args();
2020-12-12 04:15:09 +01:00
let (val, _) = self.make_method_call(
2021-04-20 16:26:08 +02:00
mods, state, lib, name, *hashes, target, &mut args, *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),
};
2021-05-22 13:14:24 +02:00
let rhs_chain = match_chain_type(rhs);
self.eval_dot_index_chain_helper(
mods, state, lib, this_ptr, &mut val, root, &x.rhs, idx_values,
rhs_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) => {
2021-05-18 14:12:30 +02:00
let ((getter, hash_get), (setter, hash_set), (name, pos)) =
2021-03-08 08:30:32 +01:00
p.as_ref();
2021-05-22 13:14:24 +02:00
let rhs_chain = match_chain_type(rhs);
2021-04-20 16:26:08 +02:00
let hash_get = FnCallHashes::from_native(*hash_get);
let hash_set = FnCallHashes::from_native(*hash_set);
2021-05-18 14:12:30 +02:00
let mut arg_values = [target.as_mut(), &mut Default::default()];
2020-07-09 16:21:07 +02:00
let args = &mut arg_values[..1];
2021-05-18 14:12:30 +02:00
let (mut val, updated) = self
.exec_fn_call(
mods, state, lib, getter, hash_get, args, is_ref, true,
*pos, None, level,
)
.or_else(|err| match *err {
// Try an indexer if property does not exist
EvalAltResult::ErrorDotExpr(_, _) => {
let prop = name.into();
self.get_indexed_mut(
2021-05-18 15:38:09 +02:00
mods, state, lib, target, prop, *pos, false, true,
level,
2021-05-18 14:12:30 +02:00
)
.map(|v| (v.take_or_clone(), false))
.map_err(
|idx_err| match *idx_err {
EvalAltResult::ErrorIndexingType(_, _) => err,
_ => idx_err,
},
)
}
_ => Err(err),
})?;
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(),
root,
2020-10-27 16:00:05 +01:00
&x.rhs,
idx_values,
2021-04-27 16:28:01 +02:00
rhs_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
2021-05-18 14:12:30 +02:00
let mut arg_values = [target.as_mut(), val];
let args = &mut arg_values;
2020-07-09 16:21:07 +02:00
self.exec_fn_call(
2021-05-18 14:12:30 +02:00
mods, state, lib, setter, hash_set, args, is_ref, true,
*pos, None, level,
2020-07-09 16:21:07 +02:00
)
.or_else(
|err| match *err {
2021-05-18 14:12:30 +02:00
// Try an indexer if property does not exist
2020-07-09 16:21:07 +02:00
EvalAltResult::ErrorDotExpr(_, _) => {
2021-05-18 14:12:30 +02:00
let mut prop = name.into();
let args = &mut [target.as_mut(), &mut prop, val];
2021-05-19 14:26:11 +02:00
let hash_set = FnCallHashes::from_native(
crate::calc_fn_hash(FN_IDX_SET, 3),
);
2021-05-18 14:12:30 +02:00
self.exec_fn_call(
mods, state, lib, FN_IDX_SET, hash_set, args,
is_ref, true, *pos, None, level,
)
.or_else(|idx_err| match *idx_err {
EvalAltResult::ErrorIndexingType(_, _) => {
// If there is no setter, no need to feed it back because
// the property is read-only
Ok((Dynamic::UNIT, false))
}
_ => Err(idx_err),
})
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
2021-04-20 17:28:04 +02:00
Expr::FnCall(f, pos) if !f.is_qualified() => {
2021-04-20 16:26:08 +02:00
let FnCallExpr { name, hashes, .. } = f.as_ref();
2021-05-22 13:14:24 +02:00
let rhs_chain = match_chain_type(rhs);
let mut args = idx_val.as_fn_call_args();
2020-12-12 04:15:09 +01:00
let (mut val, _) = self.make_method_call(
2021-04-20 16:26:08 +02:00
mods, state, lib, name, *hashes, target, &mut args, *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, root, &x.rhs, idx_values,
2021-04-27 16:28:01 +02:00
rhs_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
}
}
}
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,
2021-03-23 13:04:54 +01:00
new_val: Option<((Dynamic, Position), (Option<OpAssignment>, Position))>,
2021-03-02 08:02:28 +01:00
) -> RhaiResult {
2020-11-16 09:28:04 +01:00
let (crate::ast::BinaryExpr { lhs, rhs }, chain_type, op_pos) = match expr {
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_index"))]
2020-10-31 16:26:21 +01:00
Expr::Index(x, pos) => (x.as_ref(), ChainType::Index, *pos),
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
2020-10-31 16:26:21 +01:00
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[???]
Expr::Variable(_, var_pos, x) => {
2021-04-25 09:27:58 +02:00
#[cfg(not(feature = "unchecked"))]
self.inc_operations(state, *var_pos)?;
2020-06-26 04:39:18 +02:00
let (target, _) = self.search_namespace(scope, mods, state, lib, this_ptr, lhs)?;
2020-06-26 04:39:18 +02:00
let obj_ptr = &mut target.into();
let root = (x.2.as_str(), *var_pos);
2020-04-26 12:04:07 +02:00
self.eval_dot_index_chain_helper(
mods, state, lib, &mut None, obj_ptr, root, 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 => {
2021-03-04 03:24:14 +01:00
let value = self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?;
let obj_ptr = &mut value.into();
let root = ("", expr.position());
2020-04-26 12:04:07 +02:00
self.eval_dot_index_chain_helper(
mods, state, lib, this_ptr, obj_ptr, root, 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,
2021-04-27 16:28:01 +02:00
_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>> {
2021-04-25 09:27:58 +02:00
#[cfg(not(feature = "unchecked"))]
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 {
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
Expr::FnCall(x, _) if _parent_chain_type == ChainType::Dot && !x.is_qualified() => {
2021-03-09 11:11:43 +01:00
let mut arg_positions: StaticVec<_> = Default::default();
let mut arg_values = x
2020-10-31 07:13:45 +01:00
.args
.iter()
.inspect(|arg_expr| arg_positions.push(arg_expr.position()))
2020-10-31 07:13:45 +01:00
.map(|arg_expr| {
self.eval_expr(scope, mods, state, lib, this_ptr, arg_expr, level)
2021-03-09 11:11:43 +01:00
.map(Dynamic::flatten)
2020-10-31 07:13:45 +01:00
})
.collect::<Result<StaticVec<_>, _>>()?;
2020-04-26 12:04:07 +02:00
x.literal_args
.iter()
.inspect(|(_, pos)| arg_positions.push(*pos))
.for_each(|(v, _)| arg_values.push(v.clone()));
2021-03-09 11:11:43 +01:00
idx_values.push((arg_values, arg_positions).into());
2020-04-26 12:04:07 +02:00
}
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
Expr::FnCall(_, _) if _parent_chain_type == ChainType::Dot => {
unreachable!("function call in dot chain should not be namespace-qualified")
}
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
Expr::Property(x) if _parent_chain_type == ChainType::Dot => {
2021-05-18 14:12:30 +02:00
idx_values.push(ChainArgument::Property((x.2).1))
}
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 {
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
Expr::Property(x) if _parent_chain_type == ChainType::Dot => {
2021-05-18 14:12:30 +02:00
ChainArgument::Property((x.2).1)
}
Expr::Property(_) => unreachable!("unexpected Expr::Property for indexing"),
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
Expr::FnCall(x, _)
2021-04-27 16:28:01 +02:00
if _parent_chain_type == ChainType::Dot && !x.is_qualified() =>
{
2021-03-09 11:11:43 +01:00
let mut arg_positions: StaticVec<_> = Default::default();
let mut arg_values = x
2021-03-09 11:11:43 +01:00
.args
2020-10-31 16:26:21 +01:00
.iter()
.inspect(|arg_expr| arg_positions.push(arg_expr.position()))
2020-10-31 16:26:21 +01:00
.map(|arg_expr| {
self.eval_expr(scope, mods, state, lib, this_ptr, arg_expr, level)
2021-03-09 11:11:43 +01:00
.map(Dynamic::flatten)
2020-10-31 16:26:21 +01:00
})
2021-03-09 11:11:43 +01:00
.collect::<Result<StaticVec<_>, _>>()?;
x.literal_args
.iter()
.inspect(|(_, pos)| arg_positions.push(*pos))
.for_each(|(v, _)| arg_values.push(v.clone()));
2021-03-09 11:11:43 +01:00
(arg_values, arg_positions).into()
2020-10-31 16:26:21 +01:00
}
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
Expr::FnCall(_, _) if _parent_chain_type == ChainType::Dot => {
unreachable!("function call in dot chain should not be namespace-qualified")
}
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
expr if _parent_chain_type == ChainType::Dot => {
unreachable!("invalid dot expression: {:?}", expr);
}
#[cfg(not(feature = "no_index"))]
_ if _parent_chain_type == ChainType::Index => self
.eval_expr(scope, mods, state, lib, this_ptr, lhs, level)
.map(|v| (v.flatten(), lhs.position()).into())?,
2021-04-27 16:28:01 +02:00
expr => unreachable!("unknown chained expression: {:?}", expr),
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 {
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_index"))]
2020-10-31 16:26:21 +01:00
Expr::Index(_, _) => ChainType::Index,
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
2020-10-31 16:26:21 +01:00
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
}
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
_ if _parent_chain_type == ChainType::Dot => {
unreachable!("invalid dot expression: {:?}", expr);
}
#[cfg(not(feature = "no_index"))]
_ if _parent_chain_type == ChainType::Index => idx_values.push(
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)
.map(|v| (v.flatten(), expr.position()).into())?,
2020-10-15 17:30:30 +02:00
),
2021-04-27 16:28:01 +02:00
_ => unreachable!("unknown chained expression: {:?}", expr),
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,
2021-05-18 15:38:09 +02:00
mods: &mut Imports,
state: &mut State,
2021-05-18 15:38:09 +02:00
lib: &[&Module],
target: &'t mut Dynamic,
2021-05-18 15:38:09 +02:00
mut idx: Dynamic,
2020-04-26 12:04:07 +02:00
idx_pos: Position,
2020-07-26 09:53:22 +02:00
_create: bool,
2021-05-18 15:38:09 +02:00
indexers: bool,
level: usize,
) -> Result<Target<'t>, Box<EvalAltResult>> {
2021-04-25 09:27:58 +02:00
#[cfg(not(feature = "unchecked"))]
2020-12-20 16:25:11 +01:00
self.inc_operations(state, Position::NONE)?;
match target {
#[cfg(not(feature = "no_index"))]
2021-05-02 17:57:35 +02:00
Dynamic(Union::Array(arr, _, _)) => {
// val_array[idx]
2021-05-18 15:38:09 +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();
2021-04-24 08:47:20 +02:00
#[cfg(not(feature = "unchecked"))]
let arr_idx = if index < 0 {
// Count from end if negative
arr_len
- index
.checked_abs()
.ok_or_else(|| {
Box::new(EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos))
})
.and_then(|n| {
if n as usize > arr_len {
Err(EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos)
.into())
} else {
Ok(n as usize)
}
})?
} else {
index as usize
};
2021-04-24 08:47:20 +02:00
#[cfg(feature = "unchecked")]
let arr_idx = if index < 0 {
2021-04-25 09:27:58 +02:00
// Count from end if negative
2021-04-24 08:47:20 +02:00
arr_len - index.abs() as usize
} else {
index as usize
};
2021-04-25 09:27:58 +02:00
arr.get_mut(arr_idx)
.map(Target::from)
.ok_or_else(|| EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos).into())
}
2020-03-29 17:53:35 +02:00
#[cfg(not(feature = "no_object"))]
2021-05-02 17:57:35 +02:00
Dynamic(Union::Map(map, _, _)) => {
// val_map[idx]
2021-05-18 15:38:09 +02:00
let index = &*idx.read_lock::<ImmutableString>().ok_or_else(|| {
self.make_type_mismatch_err::<ImmutableString>(idx.type_name(), idx_pos)
2021-03-23 13:04:54 +01:00
})?;
2020-05-25 07:44:28 +02:00
2021-03-29 11:14:22 +02:00
if _create && !map.contains_key(index.as_str()) {
map.insert(index.clone().into(), Default::default());
2021-03-23 13:04:54 +01:00
}
2020-05-25 07:44:28 +02:00
2021-04-25 09:27:58 +02:00
Ok(map
2021-03-29 11:14:22 +02:00
.get_mut(index.as_str())
2021-03-23 13:04:54 +01:00
.map(Target::from)
2021-04-25 09:27:58 +02:00
.unwrap_or_else(|| Target::from(Dynamic::UNIT)))
}
2020-04-10 06:16:39 +02:00
#[cfg(not(feature = "no_index"))]
2021-05-02 17:57:35 +02:00
Dynamic(Union::Str(s, _, _)) => {
// val_string[idx]
2021-05-18 15:38:09 +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))?;
let (ch, offset) = if index >= 0 {
2021-04-25 09:27:58 +02:00
// Count from end if negative
2020-05-11 17:48:50 +02:00
let offset = index as usize;
(
s.chars().nth(offset).ok_or_else(|| {
2021-04-25 09:27:58 +02:00
let chars_len = s.chars().count();
EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos)
})?,
offset,
)
} else if let Some(index) = index.checked_abs() {
let offset = index as usize;
(
s.chars().rev().nth(offset - 1).ok_or_else(|| {
2021-04-25 09:27:58 +02:00
let chars_len = s.chars().count();
EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos)
})?,
offset,
)
} else {
2021-04-25 09:27:58 +02:00
let chars_len = s.chars().count();
return EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos).into();
};
2021-04-25 09:27:58 +02:00
Ok(Target::StringChar(target, offset, ch.into()))
}
2020-03-29 17:53:35 +02:00
2021-05-18 15:38:09 +02:00
_ if indexers => {
let args = &mut [target, &mut idx];
2021-05-19 14:26:11 +02:00
let hash_get = FnCallHashes::from_native(crate::calc_fn_hash(FN_IDX_GET, 2));
2021-04-24 08:47:20 +02:00
2021-04-25 09:27:58 +02:00
self.exec_fn_call(
2021-05-18 15:38:09 +02:00
mods, state, lib, FN_IDX_GET, hash_get, args, true, true, idx_pos, None, level,
2021-04-24 08:47:20 +02:00
)
2021-04-25 09:27:58 +02:00
.map(|(v, _)| v.into())
2021-04-24 08:47:20 +02:00
}
2021-04-25 09:27:58 +02:00
_ => EvalAltResult::ErrorIndexingType(
self.map_type_name(target.type_name()).into(),
Position::NONE,
)
.into(),
2020-03-04 15:00:01 +01: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,
2021-03-02 08:02:28 +01:00
) -> RhaiResult {
2021-04-25 09:27:58 +02:00
#[cfg(not(feature = "unchecked"))]
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-12-29 03:41:20 +01:00
2021-04-05 17:59:15 +02:00
Expr::Variable(None, var_pos, x) if x.0.is_none() && x.2 == KEYWORD_THIS => this_ptr
2020-12-29 03:41:20 +01:00
.as_deref()
.cloned()
2021-04-05 17:59:15 +02:00
.ok_or_else(|| EvalAltResult::ErrorUnboundThis(*var_pos).into()),
Expr::Variable(_, _, _) => self
2020-12-29 03:41:20 +01:00
.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
2021-03-10 15:12:48 +01:00
Expr::Stmt(x) if x.is_empty() => Ok(Dynamic::UNIT),
Expr::Stmt(x) => {
2021-04-16 07:15:11 +02:00
self.eval_stmt_block(scope, mods, state, lib, this_ptr, x, true, level)
2021-03-10 15:12:48 +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)
}
2021-04-04 07:13:07 +02:00
// `... ${...} ...`
Expr::InterpolatedString(x) => {
let mut pos = expr.position();
let mut result: Dynamic = self.empty_string.clone().into();
for expr in x.iter() {
let item = self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?;
self.eval_op_assignment(
mods,
state,
lib,
2021-04-24 05:55:40 +02:00
Some(OpAssignment::new(TOKEN_OP_CONCAT)),
2021-04-04 07:13:07 +02:00
pos,
(&mut result).into(),
("", Position::NONE),
2021-04-04 07:13:07 +02:00
item,
expr.position(),
)?;
pos = expr.position();
}
assert!(
result.is::<ImmutableString>(),
"interpolated string must be a string"
);
Ok(result)
}
2020-10-27 16:21:20 +01:00
#[cfg(not(feature = "no_index"))]
2020-11-15 05:07:35 +01:00
Expr::Array(x, _) => {
2021-03-23 05:13:53 +01:00
let mut arr = Array::with_capacity(x.len());
2020-11-15 05:07:35 +01:00
for item in x.as_ref() {
2021-03-04 03:24:14 +01:00
arr.push(
self.eval_expr(scope, mods, state, lib, this_ptr, item, level)?
.flatten(),
);
2020-11-15 05:07:35 +01:00
}
2021-04-04 07:13:07 +02:00
Ok(arr.into())
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, _) => {
2021-03-23 11:25:40 +01:00
let mut map = x.1.clone();
for (Ident { name: key, .. }, expr) in &x.0 {
2021-05-22 13:14:24 +02:00
let value_ref = map
.get_mut(key.as_str())
.expect("never fails because the template should contain all the keys");
*value_ref = self
2021-03-23 11:25:40 +01:00
.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.flatten();
2020-11-15 05:07:35 +01:00
}
2021-04-04 07:13:07 +02:00
Ok(map.into())
2020-11-15 05:07:35 +01:00
}
2020-10-27 16:21:20 +01:00
2021-04-21 12:16:24 +02:00
// Namespace-qualified function call
Expr::FnCall(x, pos) if x.is_qualified() => {
2020-11-10 16:26:50 +01:00
let FnCallExpr {
2020-10-31 07:13:45 +01:00
name,
2021-04-21 12:16:24 +02:00
namespace,
2021-04-20 16:26:08 +02:00
hashes,
2020-10-31 07:13:45 +01:00
args,
literal_args: c_args,
2020-10-31 07:13:45 +01:00
..
} = x.as_ref();
2021-05-22 13:14:24 +02:00
let namespace = namespace
.as_ref()
.expect("never fails because function call is qualified");
2021-04-21 12:16:24 +02:00
let hash = hashes.native_hash();
self.make_qualified_function_call(
scope, mods, state, lib, this_ptr, namespace, name, args, c_args, hash, *pos,
level,
2020-10-27 16:21:20 +01:00
)
}
2021-04-21 12:16:24 +02:00
// Normal function call
Expr::FnCall(x, pos) => {
2020-11-10 16:26:50 +01:00
let FnCallExpr {
2020-10-31 07:13:45 +01:00
name,
2021-04-21 12:16:24 +02:00
capture,
2021-04-20 16:26:08 +02:00
hashes,
2020-10-31 07:13:45 +01:00
args,
literal_args: c_args,
2020-10-31 07:13:45 +01:00
..
} = x.as_ref();
2021-04-21 12:16:24 +02:00
self.make_function_call(
scope, mods, state, lib, this_ptr, name, args, c_args, *hashes, *pos, *capture,
level,
2020-10-27 16:21:20 +01:00
)
}
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<_>>();
2021-05-22 13:14:24 +02:00
let key_token = custom.tokens.first().expect(
"never fails because a custom syntax stream must contain at least one token",
);
let custom_def = self
2021-05-22 13:14:24 +02:00
.custom_syntax.get(key_token)
.expect("never fails because the custom syntax leading token should match with definition");
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
};
2021-04-21 11:39:45 +02:00
#[cfg(not(feature = "unchecked"))]
self.check_data_size(&result)
.map_err(|err| err.fill_position(expr.position()))?;
result
2020-10-27 16:21:20 +01:00
}
/// Evaluate a statements block.
pub(crate) fn eval_stmt_block(
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: &[Stmt],
restore_prev_state: bool,
2020-11-04 04:49:02 +01:00
level: usize,
2021-03-02 08:02:28 +01:00
) -> RhaiResult {
2021-03-10 15:12:48 +01:00
if statements.is_empty() {
return Ok(Dynamic::UNIT);
}
2021-03-07 15:10:54 +01:00
let mut _extra_fn_resolution_cache = false;
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();
if restore_prev_state {
state.scope_level += 1;
}
let result = statements.iter().try_fold(Dynamic::UNIT, |_, stmt| {
let _mods_len = mods.len();
let r = self.eval_stmt(scope, mods, state, lib, this_ptr, stmt, level)?;
#[cfg(not(feature = "no_module"))]
if matches!(stmt, Stmt::Import(_, _, _)) {
// Get the extra modules - see if any functions are marked global.
// Without global functions, the extra modules never affect function resolution.
if mods
.scan_raw()
.skip(_mods_len)
.any(|(_, m)| m.contains_indexed_global_functions())
{
2021-03-07 15:10:54 +01:00
if _extra_fn_resolution_cache {
// When new module is imported with global functions and there is already
// a new cache, clear it - notice that this is expensive as all function
// resolutions must start again
2021-03-07 15:10:54 +01:00
state.fn_resolution_cache_mut().clear();
} else if restore_prev_state {
// When new module is imported with global functions, push a new cache
state.push_fn_resolution_cache();
2021-03-07 15:10:54 +01:00
_extra_fn_resolution_cache = true;
} else {
// When the block is to be evaluated in-place, just clear the current cache
state.fn_resolution_cache_mut().clear();
}
}
}
Ok(r)
});
2020-11-04 04:49:02 +01:00
2021-03-07 15:10:54 +01:00
if _extra_fn_resolution_cache {
// If imports list is modified, pop the functions lookup cache
state.pop_fn_resolution_cache();
}
if restore_prev_state {
scope.rewind(prev_scope_len);
mods.truncate(prev_mods_len);
state.scope_level -= 1;
2020-11-04 04:49:02 +01:00
// The impact of new local variables goes away at the end of a block
// 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
}
2021-02-24 04:04:54 +01:00
pub(crate) fn eval_op_assignment(
&self,
mods: &mut Imports,
state: &mut State,
lib: &[&Module],
2021-03-23 13:04:54 +01:00
op_info: Option<OpAssignment>,
2021-02-24 04:04:54 +01:00
op_pos: Position,
mut target: Target,
root: (&str, Position),
2021-02-24 04:04:54 +01:00
mut new_value: Dynamic,
new_value_pos: Position,
) -> Result<(), Box<EvalAltResult>> {
2021-04-17 07:36:51 +02:00
if target.is_read_only() {
// Assignment to constant variable
return EvalAltResult::ErrorAssignmentToConstant(root.0.to_string(), root.1).into();
2021-02-24 04:04:54 +01:00
}
2021-03-08 08:30:32 +01:00
if let Some(OpAssignment {
hash_op_assign,
hash_op,
op,
}) = op_info
{
2021-02-24 04:04:54 +01:00
let mut lock_guard;
let lhs_ptr_inner;
#[cfg(not(feature = "no_closure"))]
let target_is_shared = target.is_shared();
#[cfg(feature = "no_closure")]
let target_is_shared = false;
if target_is_shared {
2021-05-22 13:14:24 +02:00
lock_guard = target
.write_lock::<Dynamic>()
.expect("never fails when casting to `Dynamic`");
2021-04-17 07:36:51 +02:00
lhs_ptr_inner = &mut *lock_guard;
2021-02-24 04:04:54 +01:00
} else {
2021-04-17 07:36:51 +02:00
lhs_ptr_inner = &mut *target;
2021-02-24 04:04:54 +01:00
}
2021-03-23 13:04:54 +01:00
let hash = hash_op_assign;
2021-02-24 04:04:54 +01:00
let args = &mut [lhs_ptr_inner, &mut new_value];
2021-03-08 08:30:32 +01:00
match self.call_native_fn(mods, state, lib, op, hash, args, true, true, op_pos) {
2021-02-24 04:04:54 +01:00
Ok(_) => (),
2021-03-23 13:04:54 +01:00
Err(err) if matches!(err.as_ref(), EvalAltResult::ErrorFunctionNotFound(f, _) if f.starts_with(op)) =>
2021-02-24 04:04:54 +01:00
{
// Expand to `var = var op rhs`
let op = &op[..op.len() - 1]; // extract operator without =
// Run function
2021-03-23 13:04:54 +01:00
let (value, _) = self
.call_native_fn(mods, state, lib, op, hash_op, args, true, false, op_pos)?;
2021-02-24 04:04:54 +01:00
*args[0] = value.flatten();
}
err => return err.map(|_| ()),
}
2021-03-08 08:30:32 +01:00
Ok(())
} else {
// Normal assignment
target.set_value(new_value, new_value_pos)?;
2021-02-24 04:04:54 +01:00
Ok(())
}
}
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,
2021-03-02 08:02:28 +01:00
) -> RhaiResult {
2021-04-25 09:27:58 +02:00
#[cfg(not(feature = "unchecked"))]
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
2021-03-04 03:24:14 +01:00
Stmt::Expr(expr) => Ok(self
.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.flatten()),
2020-10-27 16:21:20 +01:00
// var op= rhs
2021-04-05 17:59:15 +02:00
Stmt::Assignment(x, op_pos) if x.0.is_variable_access(false) => {
2021-03-30 17:55:29 +02:00
let (lhs_expr, op_info, rhs_expr) = x.as_ref();
2021-02-24 04:04:54 +01:00
let rhs_val = self
2020-10-11 15:58:11 +02:00
.eval_expr(scope, mods, state, lib, this_ptr, rhs_expr, level)?
.flatten();
2021-02-24 04:04:54 +01:00
let (lhs_ptr, pos) =
2020-10-11 15:58:11 +02:00
self.search_namespace(scope, mods, state, lib, this_ptr, lhs_expr)?;
2021-05-22 13:14:24 +02:00
let var_name = lhs_expr
.get_variable_name(false)
.expect("never fails because `lhs_ptr` is a `Variable`s");
2020-10-11 15:58:11 +02:00
if !lhs_ptr.is_ref() {
2021-05-22 13:14:24 +02:00
return EvalAltResult::ErrorAssignmentToConstant(var_name.to_string(), pos)
.into();
2020-10-11 15:58:11 +02:00
}
2021-04-25 09:27:58 +02:00
#[cfg(not(feature = "unchecked"))]
2020-12-20 16:25:11 +01:00
self.inc_operations(state, pos)?;
self.eval_op_assignment(
mods,
state,
lib,
op_info.clone(),
*op_pos,
lhs_ptr,
2021-05-22 13:14:24 +02:00
(var_name, pos),
rhs_val,
rhs_expr.position(),
)?;
Ok(Dynamic::UNIT)
}
// lhs op= rhs
2020-10-27 16:21:20 +01:00
Stmt::Assignment(x, op_pos) => {
2021-03-30 17:55:29 +02:00
let (lhs_expr, op_info, rhs_expr) = x.as_ref();
2021-03-04 03:24:14 +01:00
let rhs_val = self
.eval_expr(scope, mods, state, lib, this_ptr, rhs_expr, level)?
.flatten();
2021-03-23 13:04:54 +01:00
let _new_val = Some(((rhs_val, rhs_expr.position()), (op_info.clone(), *op_pos)));
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)
2021-04-05 17:59:15 +02:00
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
2021-03-10 15:12:48 +01:00
Stmt::Block(statements, _) if statements.is_empty() => Ok(Dynamic::UNIT),
2020-10-27 11:18:19 +01:00
Stmt::Block(statements, _) => {
self.eval_stmt_block(scope, mods, state, lib, this_ptr, statements, true, 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
2021-04-21 11:39:45 +02:00
Stmt::If(expr, x, _) => {
let guard_val = 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()))?;
if guard_val {
if !x.0.is_empty() {
self.eval_stmt_block(scope, mods, state, lib, this_ptr, &x.0, true, level)
2021-04-16 07:15:11 +02:00
} else {
2021-04-21 11:39:45 +02:00
Ok(Dynamic::UNIT)
2021-04-16 07:15:11 +02:00
}
2021-04-21 11:39:45 +02:00
} else {
if !x.1.is_empty() {
self.eval_stmt_block(scope, mods, state, lib, this_ptr, &x.1, true, level)
} else {
Ok(Dynamic::UNIT)
}
}
}
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();
2021-03-05 03:33:48 +01:00
let value = self.eval_expr(scope, mods, state, lib, this_ptr, match_expr, level)?;
if value.is_hashable() {
let hasher = &mut get_hasher();
value.hash(hasher);
let hash = hasher.finish();
2021-04-16 06:04:33 +02:00
table.get(&hash).and_then(|t| {
if let Some(condition) = &t.0 {
match self
.eval_expr(scope, mods, state, lib, this_ptr, &condition, level)
.and_then(|v| {
v.as_bool().map_err(|err| {
self.make_type_mismatch_err::<bool>(
err,
condition.position(),
)
})
}) {
Ok(true) => (),
Ok(false) => return None,
Err(err) => return Some(Err(err)),
}
}
2021-03-30 17:55:29 +02:00
2021-04-16 07:15:11 +02:00
let statements = &t.1;
2021-04-16 06:04:33 +02:00
Some(if !statements.is_empty() {
2021-03-10 15:12:48 +01:00
self.eval_stmt_block(
scope, mods, state, lib, this_ptr, statements, true, level,
)
} else {
Ok(Dynamic::UNIT)
2021-04-16 06:04:33 +02:00
})
2021-03-10 15:12:48 +01:00
})
2020-11-14 16:43:36 +01:00
} else {
2021-03-05 03:33:48 +01:00
// Non-hashable values never match any specific clause
None
2020-11-14 16:43:36 +01:00
}
2021-03-05 03:33:48 +01:00
.unwrap_or_else(|| {
// Default match clause
2021-03-10 15:12:48 +01:00
if !def_stmt.is_empty() {
self.eval_stmt_block(
scope, mods, state, lib, this_ptr, def_stmt, true, level,
)
} else {
Ok(Dynamic::UNIT)
}
2021-03-05 03:33:48 +01:00
})
2020-11-14 16:43:36 +01:00
}
2020-03-06 16:49:52 +01:00
// While loop
2021-04-16 07:15:11 +02:00
Stmt::While(expr, body, _) => loop {
let condition = if !expr.is_unit() {
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()))?
} else {
true
};
2021-03-10 05:27:10 +01:00
2021-04-16 07:15:11 +02:00
if !condition {
return Ok(Dynamic::UNIT);
}
2021-04-21 11:39:45 +02:00
if !body.is_empty() {
match self.eval_stmt_block(scope, mods, state, lib, this_ptr, body, true, level)
{
Ok(_) => (),
Err(err) => match *err {
EvalAltResult::LoopBreak(false, _) => (),
EvalAltResult::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
_ => return Err(err),
},
}
2021-04-16 07:15:11 +02:00
}
},
2021-03-10 05:27:10 +01:00
2021-04-16 07:15:11 +02:00
// Do loop
Stmt::Do(body, expr, is_while, _) => loop {
if !body.is_empty() {
2021-03-10 05:27:10 +01:00
match self.eval_stmt_block(scope, mods, state, lib, this_ptr, body, true, level)
{
Ok(_) => (),
Err(err) => match *err {
2021-04-16 07:15:11 +02:00
EvalAltResult::LoopBreak(false, _) => continue,
EvalAltResult::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
_ => return Err(err),
},
2020-10-05 07:45:57 +02:00
}
2021-03-10 15:12:48 +01:00
}
2021-04-21 11:39:45 +02:00
let condition = self
2021-04-16 07:15:11 +02:00
.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.as_bool()
2021-04-21 11:39:45 +02:00
.map_err(|err| self.make_type_mismatch_err::<bool>(err, expr.position()))?;
if condition ^ *is_while {
return Ok(Dynamic::UNIT);
2020-11-20 15:23:37 +01:00
}
2021-04-16 07:15:11 +02:00
},
2020-03-01 17:11:00 +01:00
2020-03-06 16:49:52 +01:00
// For loop
2021-03-09 16:48:40 +01:00
Stmt::For(expr, x, _) => {
2021-04-16 07:15:11 +02:00
let (Ident { name, .. }, statements) = x.as_ref();
2021-03-04 03:24:14 +01:00
let iter_obj = self
.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.flatten();
2020-10-14 17:22:10 +02:00
let iter_type = iter_obj.type_id();
2020-03-01 17:11:00 +01:00
2021-03-01 07:54:20 +01:00
// lib should only contain scripts, so technically they cannot have iterators
// Search order:
// 1) Global namespace - functions registered via Engine::register_XXX
// 2) Global modules - packages
// 3) Imported modules - functions marked with global namespace
// 4) Global sub-modules - functions marked with global namespace
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))
})
2021-03-01 07:54:20 +01:00
.or_else(|| mods.get_iter(iter_type))
.or_else(|| {
self.global_sub_modules
.values()
.find_map(|m| m.get_qualified_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() {
2021-03-29 05:36:02 +02:00
name.to_string().into()
2020-10-28 12:11:17 +01:00
} 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
#[cfg(not(feature = "no_closure"))]
let loop_var_is_shared = loop_var.is_shared();
#[cfg(feature = "no_closure")]
let loop_var_is_shared = false;
if loop_var_is_shared {
2021-05-22 13:14:24 +02:00
let mut value_ref = loop_var
.write_lock()
.expect("never fails when casting to `Dynamic`");
*value_ref = 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
}
2021-04-25 09:27:58 +02:00
#[cfg(not(feature = "unchecked"))]
self.inc_operations(state, statements.position())?;
2020-03-01 17:11:00 +01:00
2021-03-10 15:12:48 +01:00
if statements.is_empty() {
continue;
}
2021-04-21 11:39:45 +02:00
let result = self.eval_stmt_block(
2021-03-10 05:27:10 +01:00
scope, mods, state, lib, this_ptr, statements, true, level,
2021-04-21 11:39:45 +02:00
);
match result {
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
2021-04-21 12:16:24 +02:00
// Namespace-qualified function call
Stmt::FnCall(x, pos) if x.is_qualified() => {
let FnCallExpr {
name,
namespace,
hashes,
args,
literal_args: c_args,
2021-04-21 12:16:24 +02:00
..
} = x.as_ref();
2021-05-22 13:14:24 +02:00
let namespace = namespace
.as_ref()
.expect("never fails because function call is qualified");
2021-04-21 12:16:24 +02:00
let hash = hashes.native_hash();
self.make_qualified_function_call(
scope, mods, state, lib, this_ptr, namespace, name, args, c_args, hash, *pos,
level,
)
}
// Normal function call
Stmt::FnCall(x, pos) => {
let FnCallExpr {
name,
capture,
hashes,
args,
literal_args: c_args,
2021-04-21 12:16:24 +02:00
..
} = x.as_ref();
self.make_function_call(
scope, mods, state, lib, this_ptr, name, args, c_args, *hashes, *pos, *capture,
level,
)
}
2020-10-20 17:16:03 +02:00
// Try/Catch statement
2020-11-06 09:27:40 +01:00
Stmt::TryCatch(x, _, _) => {
2021-04-16 07:15:11 +02:00
let (try_stmt, err_var, catch_stmt) = x.as_ref();
2020-10-20 17:16:03 +02:00
let result = self
2021-04-16 07:15:11 +02:00
.eval_stmt_block(scope, mods, state, lib, this_ptr, try_stmt, true, 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,
Err(err) if err.is_pseudo_error() => Err(err),
2020-12-29 03:41:20 +01:00
Err(err) if !err.is_catchable() => Err(err),
Err(mut err) => {
2021-02-28 07:38:34 +01:00
let err_value = match *err {
2020-12-29 03:41:20 +01:00
EvalAltResult::ErrorRuntime(ref x, _) => x.clone(),
2021-02-28 07:38:34 +01:00
#[cfg(feature = "no_object")]
2020-12-29 03:41:20 +01:00
_ => {
2021-02-28 07:38:34 +01:00
err.take_position();
2020-10-21 08:45:10 +02:00
err.to_string().into()
}
2021-02-28 07:38:34 +01:00
#[cfg(not(feature = "no_object"))]
_ => {
use crate::INT;
let mut err_map: Map = Default::default();
let err_pos = err.take_position();
err_map.insert("message".into(), err.to_string().into());
2021-05-25 04:54:48 +02:00
state
.source
.as_ref()
.map(|source| err_map.insert("source".into(), source.into()));
2021-02-28 07:38:34 +01:00
if err_pos.is_none() {
// No position info
} else {
2021-05-22 13:14:24 +02:00
let line = err_pos.line().expect("never fails because a non-NONE `Position` always has a line number") as INT;
let position = if err_pos.is_beginning_of_line() {
0
} else {
err_pos.position().expect("never fails because a non-NONE `Position` always has a character position")
} as INT;
err_map.insert("line".into(), line.into());
err_map.insert("position".into(), position.into());
2021-02-28 07:38:34 +01:00
}
err.dump_fields(&mut err_map);
err_map.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
2021-05-25 04:54:48 +02:00
err_var.as_ref().map(|Ident { name, .. }| {
scope.push(unsafe_cast_var_name_to_lifetime(name), err_value)
});
2020-10-20 17:16:03 +02:00
2021-03-10 05:27:10 +01:00
let result = self.eval_stmt_block(
2021-04-16 07:15:11 +02:00
scope, mods, state, lib, this_ptr, catch_stmt, true, level,
2021-03-10 05:27:10 +01:00
);
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
2021-05-02 17:57:35 +02:00
EvalAltResult::ErrorRuntime(Dynamic(Union::Unit(_, _, _)), pos) => {
2020-12-29 03:41:20 +01:00
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
2021-04-21 11:39:45 +02:00
Stmt::Return(ReturnType::Return, Some(expr), pos) => EvalAltResult::Return(
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.flatten(),
*pos,
)
.into(),
2020-03-03 11:15:20 +01:00
// Empty return
2021-03-09 16:30:48 +01:00
Stmt::Return(ReturnType::Return, None, pos) => {
2021-04-21 11:39:45 +02:00
EvalAltResult::Return(Dynamic::UNIT, *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
2021-04-21 11:39:45 +02:00
Stmt::Return(ReturnType::Exception, Some(expr), pos) => EvalAltResult::ErrorRuntime(
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.flatten(),
*pos,
)
.into(),
2020-03-01 17:11:00 +01:00
// Empty throw
2021-03-09 16:30:48 +01:00
Stmt::Return(ReturnType::Exception, None, pos) => {
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
2021-03-29 05:36:02 +02:00
Stmt::Let(expr, x, export, _) | Stmt::Const(expr, x, export, _) => {
let name = &x.name;
2020-10-09 07:25:53 +02:00
let entry_type = match stmt {
2021-03-10 05:27:10 +01:00
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
2021-03-09 16:30:48 +01:00
let value = self
.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.flatten();
2020-11-09 05:50:18 +01:00
let (var_name, _alias): (Cow<'_, str>, _) = if state.is_global() {
2021-04-17 11:25:35 +02:00
#[cfg(not(feature = "no_function"))]
2021-04-17 12:40:16 +02:00
if entry_type == AccessMode::ReadOnly && lib.iter().any(|&m| !m.is_empty()) {
let global = if let Some(index) = mods.find(KEYWORD_GLOBAL) {
2021-05-22 13:14:24 +02:00
match mods
.get_mut(index)
.expect("never fails because the index came from `find`")
{
m if m.internal => Some(m),
_ => None,
2021-04-17 12:40:16 +02:00
}
} else {
// Create automatic global module
2021-04-17 12:40:16 +02:00
let mut global = Module::new();
global.internal = true;
mods.push(KEYWORD_GLOBAL, global);
2021-05-22 13:14:24 +02:00
Some(
mods.get_mut(mods.len() - 1)
.expect("never fails because the global module was just added"),
)
};
2021-04-17 12:40:16 +02:00
if let Some(global) = global {
2021-05-25 04:54:48 +02:00
Shared::get_mut(global)
.expect("never fails because the global module is never shared")
.set_var(name.clone(), value.clone());
2021-04-17 12:40:16 +02:00
}
2021-04-17 11:25:35 +02:00
}
(
2021-03-09 16:30:48 +01:00
name.to_string().into(),
2021-03-10 05:27:10 +01:00
if *export { Some(name.clone()) } else { None },
)
2021-03-10 05:27:10 +01:00
} else if *export {
unreachable!("exported variable not on global level");
2020-10-28 12:11:17 +01:00
} else {
2021-03-09 16:30:48 +01:00
(unsafe_cast_var_name_to_lifetime(name).into(), None)
2020-10-28 12:11:17 +01:00
};
2021-03-09 16:30:48 +01:00
2021-03-04 03:24:14 +01:00
scope.push_dynamic_value(var_name, entry_type, value);
2020-11-09 05:50:18 +01:00
#[cfg(not(feature = "no_module"))]
2021-05-25 04:54:48 +02:00
_alias.map(|alias| 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"))]
2021-03-10 05:27:10 +01:00
Stmt::Import(expr, export, _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)?
2021-04-04 07:13:07 +02:00
.try_cast::<ImmutableString>()
{
2021-01-08 17:40:44 +01:00
use crate::ModuleResolver;
let source = state.source.as_ref().map(|s| s.as_str());
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, source, &path, expr_pos) {
2021-01-08 17:24:55 +01:00
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, source, &path, expr_pos)
})?;
2020-12-26 06:05:57 +01:00
2021-05-25 04:54:48 +02:00
export.as_ref().map(|x| x.name.clone()).map(|name| {
2020-12-26 06:05:57 +01:00
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();
2021-03-10 05:27:10 +01:00
mods.push(name, module);
2020-12-26 06:05:57 +01:00
} else {
2021-03-10 05:27:10 +01:00
mods.push(name, module);
}
2021-05-25 04:54:48 +02:00
});
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 {
2021-04-04 07:13:07 +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, _) => {
2021-03-09 16:30:48 +01:00
for (Ident { name, 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 {
2021-03-09 16:30:48 +01:00
return EvalAltResult::ErrorVariableNotFound(name.to_string(), *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"))]
2021-03-30 17:55:29 +02:00
Stmt::Share(name) => {
2021-05-25 04:54:48 +02:00
scope.get_index(name).map(|(index, _)| {
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.
2021-04-17 09:15:54 +02:00
*val = std::mem::take(val).into_shared();
2020-08-03 06:10:20 +02:00
}
2021-05-25 04:54:48 +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
};
2021-04-21 11:39:45 +02:00
#[cfg(not(feature = "unchecked"))]
self.check_data_size(&result)
.map_err(|err| err.fill_position(stmt.position()))?;
2020-06-13 18:09:16 +02:00
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"))]
2021-04-21 11:39:45 +02:00
fn check_data_size(&self, result: &RhaiResult) -> Result<(), Box<EvalAltResult>> {
2021-05-22 13:14:24 +02:00
let result = match result {
Err(_) => return Ok(()),
Ok(r) => r,
};
2021-01-06 06:46:53 +01:00
// If no data size limits, just return
2021-03-31 04:16:38 +02:00
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-03-31 04:16:38 +02:00
_has_limit = _has_limit || self.limits.max_array_size.is_some();
}
#[cfg(not(feature = "no_object"))]
{
2021-03-31 04:16:38 +02:00
_has_limit = _has_limit || self.limits.max_map_size.is_some();
}
2021-03-31 04:16:38 +02:00
if !_has_limit {
2021-04-21 11:39:45 +02:00
return Ok(());
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"))]
2021-05-02 17:57:35 +02: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 {
2021-05-02 17:57:35 +02: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"))]
2021-05-02 17:57:35 +02: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"))]
2021-05-02 17:57:35 +02: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"))]
2021-05-02 17:57:35 +02:00
Dynamic(Union::Array(_, _, _)) => {
2020-07-01 16:21:43 +02:00
let (a, m, _) = calc_size(value);
arrays += a;
maps += m;
}
2021-05-02 17:57:35 +02: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)
}
2021-05-02 17:57:35 +02: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
}
2021-05-22 13:14:24 +02:00
let (_arr, _map, s) = calc_size(result);
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)
{
2021-04-21 11:39:45 +02:00
return EvalAltResult::ErrorDataTooLarge(
"Length of string".to_string(),
Position::NONE,
)
.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)
{
2021-04-21 11:39:45 +02:00
return EvalAltResult::ErrorDataTooLarge("Size of array".to_string(), Position::NONE)
.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)
{
2021-04-21 11:39:45 +02:00
return EvalAltResult::ErrorDataTooLarge(
"Size of object map".to_string(),
Position::NONE,
)
.into();
2016-02-29 22:43:45 +01:00
}
2021-04-21 11:39:45 +02:00
Ok(())
2016-02-29 22:43:45 +01:00
}
/// Check if the number of operations stay within limit.
2021-04-25 09:27:58 +02:00
#[cfg(not(feature = "unchecked"))]
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;
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
2021-05-25 04:54:48 +02:00
if let Some(ref 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(())
}
2021-02-25 04:04:01 +01:00
/// Pretty-print a type name.
///
/// If a type is registered via [`register_type_with_name`][Engine::register_type_with_name],
/// the type name provided for the registration will be used.
2020-08-08 10:24:10 +02:00
#[inline(always)]
2021-02-25 04:04:01 +01:00
pub 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(|s| s.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(
self.map_type_name(type_name::<T>()).into(),
2021-02-28 07:38:34 +01:00
typ.into(),
2020-10-05 07:45:57 +02:00
pos,
)
.into()
}
2016-03-01 15:40:48 +01:00
}