rhai/src/engine.rs

3581 lines
139 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-12-27 15:02:34 +01:00
use crate::api::custom_syntax::CustomSyntax;
use crate::ast::{Expr, FnCallExpr, Ident, OpAssignment, Stmt, AST_OPTION_FLAGS::*};
use crate::func::call::FnResolutionCache;
use crate::func::native::{OnDebugCallback, OnParseTokenCallback, OnPrintCallback, OnVarCallback};
use crate::func::{get_hasher, CallableFunction, IteratorFn};
2021-12-25 16:49:14 +01:00
use crate::module::Namespace;
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-11-13 15:36:23 +01:00
use crate::tokenizer::Token;
use crate::types::dynamic::{map_std_type_name, AccessMode, Union, Variant};
2021-04-17 09:15:54 +02:00
use crate::{
2021-12-27 15:28:11 +01:00
Dynamic, Identifier, ImmutableString, Module, Position, RhaiError, RhaiResult, RhaiResultOf,
Scope, Shared, StaticVec, ERR, INT,
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-07-04 10:33:26 +02:00
iter::{FromIterator, Rev, Zip},
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
};
2021-03-14 03:47:29 +01:00
pub type Precedence = NonZeroU8;
2021-12-27 16:15:25 +01:00
pub const KEYWORD_PRINT: &str = "print";
pub const KEYWORD_DEBUG: &str = "debug";
pub const KEYWORD_TYPE_OF: &str = "type_of";
pub const KEYWORD_EVAL: &str = "eval";
pub const KEYWORD_FN_PTR: &str = "Fn";
pub const KEYWORD_FN_PTR_CALL: &str = "call";
pub const KEYWORD_FN_PTR_CURRY: &str = "curry";
#[cfg(not(feature = "no_closure"))]
pub const KEYWORD_IS_SHARED: &str = "is_shared";
pub const KEYWORD_IS_DEF_VAR: &str = "is_def_var";
#[cfg(not(feature = "no_function"))]
pub const KEYWORD_IS_DEF_FN: &str = "is_def_fn";
pub const KEYWORD_THIS: &str = "this";
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "no_module"))]
pub const KEYWORD_GLOBAL: &str = "global";
#[cfg(not(feature = "no_object"))]
pub const FN_GET: &str = "get$";
#[cfg(not(feature = "no_object"))]
pub const FN_SET: &str = "set$";
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
pub const FN_IDX_GET: &str = "index$get$";
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
pub const FN_IDX_SET: &str = "index$set$";
#[cfg(not(feature = "no_function"))]
pub const FN_ANONYMOUS: &str = "anon$";
2021-12-27 16:03:30 +01:00
2021-12-27 16:15:25 +01:00
/// Standard equality comparison operator.
2022-01-01 12:54:46 +01:00
///
/// Some standard functions (e.g. searching an [`Array`][crate::Array]) implicitly call this
/// function to compare two [`Dynamic`] values.
2021-12-27 16:15:25 +01:00
pub const OP_EQUALS: &str = Token::EqualsTo.literal_syntax();
2021-12-27 16:03:30 +01:00
2022-01-01 12:54:46 +01:00
/// Standard concatenation operator.
///
/// Used primarily to build up interpolated strings.
pub const OP_CONCAT: &str = Token::PlusAssign.literal_syntax();
/// Standard containment testing function.
///
/// The `in` operator is implemented as a call to this function.
2021-12-27 16:15:25 +01:00
pub const OP_CONTAINS: &str = "contains";
2021-12-27 16:03:30 +01:00
2021-12-27 16:15:25 +01:00
/// Standard exclusive range operator.
pub const OP_EXCLUSIVE_RANGE: &str = Token::ExclusiveRange.literal_syntax();
/// Standard inclusive range operator.
pub const OP_INCLUSIVE_RANGE: &str = Token::InclusiveRange.literal_syntax();
/// Method of chaining.
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
enum ChainType {
/// Indexing.
#[cfg(not(feature = "no_index"))]
Indexing,
/// Dotting.
#[cfg(not(feature = "no_object"))]
Dotting,
2021-04-27 16:28:01 +02:00
}
2020-11-01 16:42:00 +01:00
2022-01-02 16:26:38 +01:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
impl From<&Expr> for ChainType {
#[inline]
fn from(expr: &Expr) -> Self {
match expr {
#[cfg(not(feature = "no_index"))]
Expr::Index(_, _, _) => Self::Indexing,
#[cfg(not(feature = "no_object"))]
Expr::Dot(_, _, _) => Self::Dotting,
expr => unreachable!("Expr::Index or Expr::Dot expected but gets {:?}", expr),
}
}
}
2021-12-27 16:15:25 +01:00
/// Value of a chaining argument.
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
#[derive(Debug, Clone, Hash)]
enum ChainArgument {
/// Dot-property access.
#[cfg(not(feature = "no_object"))]
Property(Position),
/// Arguments to a dot method call.
/// Wrapped values are the arguments plus the [position][Position] of the first argument.
///
/// Since many dotted function calls have no arguments (e.g. `string.len()`), it is better to
/// reduce the size of [`ChainArgument`] by using a boxed slice.
#[cfg(not(feature = "no_object"))]
MethodCallArgs(Option<Box<[Dynamic]>>, Position),
/// Index value and [position][Position].
#[cfg(not(feature = "no_index"))]
IndexValue(Dynamic, Position),
2021-11-28 15:57:28 +01:00
}
2021-12-27 16:15:25 +01:00
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
impl ChainArgument {
/// Return the index value.
2021-07-04 10:33:26 +02:00
#[inline(always)]
2021-12-27 16:15:25 +01:00
#[cfg(not(feature = "no_index"))]
2021-07-04 10:33:26 +02:00
#[must_use]
2021-12-27 16:15:25 +01:00
pub fn into_index_value(self) -> Option<Dynamic> {
match self {
Self::IndexValue(value, _) => Some(value),
#[cfg(not(feature = "no_object"))]
_ => None,
}
2021-07-04 10:33:26 +02:00
}
2021-12-27 16:15:25 +01:00
/// Return the list of method call arguments.
///
/// # Panics
///
/// Panics if the [`ChainArgument`] is not [`MethodCallArgs`][ChainArgument::MethodCallArgs].
2020-12-29 03:41:20 +01:00
#[inline(always)]
2021-12-27 16:15:25 +01:00
#[cfg(not(feature = "no_object"))]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-12-27 16:15:25 +01:00
pub fn into_fn_call_args(self) -> (crate::FnArgsVec<Dynamic>, Position) {
match self {
Self::MethodCallArgs(None, pos) => (crate::FnArgsVec::new_const(), pos),
Self::MethodCallArgs(Some(mut values), pos) => {
(values.iter_mut().map(std::mem::take).collect(), pos)
}
2021-12-30 05:19:41 +01:00
x => unreachable!("ChainArgument::MethodCallArgs expected but gets {:?}", x),
2021-12-27 16:15:25 +01:00
}
2020-11-01 16:42:00 +01:00
}
2021-12-27 16:15:25 +01:00
/// Return the [position][Position].
2020-12-29 03:41:20 +01:00
#[inline(always)]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-04-17 12:40:16 +02:00
#[allow(dead_code)]
2021-12-27 16:15:25 +01:00
pub const fn position(&self) -> Position {
match self {
#[cfg(not(feature = "no_object"))]
ChainArgument::Property(pos) => *pos,
#[cfg(not(feature = "no_object"))]
ChainArgument::MethodCallArgs(_, pos) => *pos,
#[cfg(not(feature = "no_index"))]
ChainArgument::IndexValue(_, pos) => *pos,
}
2020-11-01 16:42:00 +01:00
}
2021-12-27 16:15:25 +01:00
/// Create n [`MethodCallArgs`][ChainArgument::MethodCallArgs].
2020-12-29 03:41:20 +01:00
#[inline(always)]
2021-12-27 16:15:25 +01:00
#[cfg(not(feature = "no_object"))]
#[must_use]
pub fn from_fn_call_args(values: crate::FnArgsVec<Dynamic>, pos: Position) -> Self {
if values.is_empty() {
Self::MethodCallArgs(None, pos)
} else {
Self::MethodCallArgs(Some(values.into_vec().into()), pos)
}
2020-11-01 16:42:00 +01:00
}
2021-12-27 16:15:25 +01:00
/// Create an [`IndexValue`][ChainArgument::IndexValue].
2020-12-29 03:41:20 +01:00
#[inline(always)]
2021-12-27 16:15:25 +01:00
#[cfg(not(feature = "no_index"))]
#[must_use]
pub const fn from_index_value(value: Dynamic, pos: Position) -> Self {
Self::IndexValue(value, pos)
2020-11-09 14:52:23 +01:00
}
2021-12-27 16:15:25 +01:00
}
/// A type that encapsulates a mutation target for an expression with side effects.
#[derive(Debug)]
pub enum Target<'a> {
2022-01-02 16:26:38 +01:00
/// The target is a mutable reference to a [`Dynamic`].
2021-12-27 16:15:25 +01:00
RefMut(&'a mut Dynamic),
2022-01-02 16:26:38 +01:00
/// The target is a mutable reference to a _shared_ [`Dynamic`].
2021-12-27 16:15:25 +01:00
#[cfg(not(feature = "no_closure"))]
2022-01-02 16:26:38 +01:00
SharedValue {
/// Lock guard to the shared [`Dynamic`].
source: crate::types::dynamic::DynamicWriteLock<'a, Dynamic>,
/// Copy of the value.
value: Dynamic,
},
/// The target is a temporary [`Dynamic`] value (i.e. its mutation can cause no side effects).
2021-12-27 16:15:25 +01:00
TempValue(Dynamic),
/// The target is a bit inside an [`INT`][crate::INT].
/// This is necessary because directly pointing to a bit inside an [`INT`][crate::INT] is impossible.
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Bit {
/// Mutable reference to the source [`Dynamic`].
source: &'a mut Dynamic,
/// Copy of the boolean bit, as a [`Dynamic`].
value: Dynamic,
/// Bit offset.
bit: u8,
},
2021-12-27 16:15:25 +01:00
/// The target is a range of bits inside an [`INT`][crate::INT].
/// This is necessary because directly pointing to a range of bits inside an [`INT`][crate::INT] is impossible.
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
BitField {
/// Mutable reference to the source [`Dynamic`].
source: &'a mut Dynamic,
/// Copy of the integer value of the bits, as a [`Dynamic`].
value: Dynamic,
/// Bitmask to apply to the source value (i.e. shifted)
mask: INT,
/// Number of bits to right-shift the source value.
shift: u8,
},
/// The target is a byte inside a [`Blob`][crate::Blob].
2021-12-27 16:15:25 +01:00
/// This is necessary because directly pointing to a byte (in [`Dynamic`] form) inside a blob is impossible.
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
BlobByte {
/// Mutable reference to the source [`Dynamic`].
source: &'a mut Dynamic,
/// Copy of the byte at the index, as a [`Dynamic`].
value: Dynamic,
/// Offset index.
index: usize,
},
/// The target is a character inside a string.
2021-12-27 16:15:25 +01:00
/// This is necessary because directly pointing to a char inside a String is impossible.
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
StringChar {
/// Mutable reference to the source [`Dynamic`].
source: &'a mut Dynamic,
/// Copy of the character at the offset, as a [`Dynamic`].
value: Dynamic,
/// Offset index.
index: usize,
},
2021-12-27 16:15:25 +01:00
}
impl<'a> Target<'a> {
/// Is the `Target` a reference pointing to other data?
2021-03-07 15:10:54 +01:00
#[allow(dead_code)]
#[inline]
2021-12-27 16:15:25 +01:00
#[must_use]
pub const fn is_ref(&self) -> bool {
match self {
Self::RefMut(_) => true,
#[cfg(not(feature = "no_closure"))]
2022-01-02 16:26:38 +01:00
Self::SharedValue { .. } => true,
2021-12-27 16:15:25 +01:00
Self::TempValue(_) => false,
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::Bit { .. }
| Self::BitField { .. }
| Self::BlobByte { .. }
| Self::StringChar { .. } => false,
2021-12-27 16:15:25 +01:00
}
}
2021-12-27 16:15:25 +01:00
/// Is the `Target` a temp value?
#[inline]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-12-27 16:15:25 +01:00
pub const fn is_temp_value(&self) -> bool {
match self {
Self::RefMut(_) => false,
#[cfg(not(feature = "no_closure"))]
2022-01-02 16:26:38 +01:00
Self::SharedValue { .. } => false,
2021-12-27 16:15:25 +01:00
Self::TempValue(_) => true,
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::Bit { .. }
| Self::BitField { .. }
| Self::BlobByte { .. }
| Self::StringChar { .. } => false,
2021-12-27 16:15:25 +01:00
}
}
2021-12-27 16:15:25 +01:00
/// Is the `Target` a shared value?
#[cfg(not(feature = "no_closure"))]
#[inline]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-12-27 16:15:25 +01:00
pub fn is_shared(&self) -> bool {
match self {
Self::RefMut(r) => r.is_shared(),
#[cfg(not(feature = "no_closure"))]
2022-01-02 16:26:38 +01:00
Self::SharedValue { .. } => true,
2021-12-27 16:15:25 +01:00
Self::TempValue(r) => r.is_shared(),
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::Bit { .. }
| Self::BitField { .. }
| Self::BlobByte { .. }
| Self::StringChar { .. } => false,
2021-12-27 16:15:25 +01:00
}
}
2021-12-27 16:15:25 +01:00
/// Is the `Target` a specific type?
#[allow(dead_code)]
#[inline]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-12-27 16:15:25 +01:00
pub fn is<T: Variant + Clone>(&self) -> bool {
match self {
Self::RefMut(r) => r.is::<T>(),
#[cfg(not(feature = "no_closure"))]
2022-01-02 16:26:38 +01:00
Self::SharedValue { source, .. } => source.is::<T>(),
2021-12-27 16:15:25 +01:00
Self::TempValue(r) => r.is::<T>(),
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::Bit { .. } => TypeId::of::<T>() == TypeId::of::<bool>(),
2021-12-27 16:15:25 +01:00
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::BitField { .. } => TypeId::of::<T>() == TypeId::of::<INT>(),
2021-12-27 16:15:25 +01:00
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::BlobByte { .. } => TypeId::of::<T>() == TypeId::of::<crate::Blob>(),
2021-12-27 16:15:25 +01:00
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::StringChar { .. } => TypeId::of::<T>() == TypeId::of::<char>(),
2021-12-27 16:15:25 +01:00
}
}
2021-12-27 16:15:25 +01:00
/// Get the value of the `Target` as a `Dynamic`, cloning a referenced value if necessary.
#[inline]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-12-27 16:15:25 +01:00
pub fn take_or_clone(self) -> Dynamic {
match self {
Self::RefMut(r) => r.clone(), // Referenced value is cloned
#[cfg(not(feature = "no_closure"))]
2022-01-02 16:26:38 +01:00
Self::SharedValue { value, .. } => value, // Original shared value is simply taken
2021-12-27 16:15:25 +01:00
Self::TempValue(v) => v, // Owned value is simply taken
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::Bit { value, .. } => value, // boolean is taken
2021-12-27 16:15:25 +01:00
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::BitField { value, .. } => value, // INT is taken
2021-12-27 16:15:25 +01:00
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::BlobByte { value, .. } => value, // byte is taken
2021-12-27 16:15:25 +01:00
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::StringChar { value, .. } => value, // char is taken
2021-12-27 16:15:25 +01:00
}
}
2021-12-27 16:15:25 +01:00
/// Take a `&mut Dynamic` reference from the `Target`.
#[inline(always)]
#[must_use]
2021-12-27 16:15:25 +01:00
pub fn take_ref(self) -> Option<&'a mut Dynamic> {
match self {
Self::RefMut(r) => Some(r),
_ => None,
}
}
2021-12-27 16:15:25 +01:00
/// Convert a shared or reference `Target` into a target with an owned value.
#[inline(always)]
#[must_use]
2022-01-04 15:16:20 +01:00
pub fn into_owned(self) -> Self {
match self {
Self::RefMut(r) => Self::TempValue(r.clone()),
#[cfg(not(feature = "no_closure"))]
Self::SharedValue { value, .. } => Self::TempValue(value),
_ => self,
}
2021-12-27 16:15:25 +01:00
}
/// Propagate a changed value back to the original source.
/// This has no effect for direct references.
#[inline]
pub fn propagate_changed_value(&mut self) -> RhaiResultOf<()> {
match self {
Self::RefMut(_) | Self::TempValue(_) => (),
#[cfg(not(feature = "no_closure"))]
2022-01-02 16:26:38 +01:00
Self::SharedValue { .. } => (),
2021-12-27 16:15:25 +01:00
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::Bit { source, value, bit } => {
2021-12-27 16:15:25 +01:00
// Replace the bit at the specified index position
2022-01-02 16:26:38 +01:00
let new_bit = value.as_bool().map_err(|err| {
2021-12-27 16:15:25 +01:00
Box::new(ERR::ErrorMismatchDataType(
"bool".to_string(),
err.to_string(),
Position::NONE,
))
})?;
2022-01-02 16:26:38 +01:00
let value = &mut *source.write_lock::<crate::INT>().expect("`INT`");
2021-12-27 16:15:25 +01:00
2022-01-02 16:26:38 +01:00
let index = *bit;
2021-12-27 16:15:25 +01:00
let mask = 1 << index;
if new_bit {
*value |= mask;
} else {
*value &= !mask;
}
}
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::BitField {
source,
value,
mask,
shift,
} => {
2021-12-27 16:15:25 +01:00
let shift = *shift;
let mask = *mask;
// Replace the bit at the specified index position
2022-01-02 16:26:38 +01:00
let new_value = value.as_int().map_err(|err| {
2021-12-27 16:15:25 +01:00
Box::new(ERR::ErrorMismatchDataType(
"integer".to_string(),
err.to_string(),
Position::NONE,
))
})?;
2021-12-27 16:15:25 +01:00
let new_value = (new_value << shift) & mask;
2022-01-02 16:26:38 +01:00
let value = &mut *source.write_lock::<crate::INT>().expect("`INT`");
2021-12-27 16:15:25 +01:00
*value &= !mask;
*value |= new_value;
}
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::BlobByte {
source,
value,
index,
} => {
2021-12-27 16:15:25 +01:00
// Replace the byte at the specified index position
2022-01-02 16:26:38 +01:00
let new_byte = value.as_int().map_err(|err| {
2021-12-27 16:15:25 +01:00
Box::new(ERR::ErrorMismatchDataType(
"INT".to_string(),
err.to_string(),
Position::NONE,
))
})?;
2022-01-02 16:26:38 +01:00
let value = &mut *source.write_lock::<crate::Blob>().expect("`Blob`");
2021-12-27 16:15:25 +01:00
let index = *index;
if index < value.len() {
value[index] = (new_byte & 0x00ff) as u8;
} else {
unreachable!("blob index out of bounds: {}", index);
}
}
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::StringChar {
source,
value,
index,
} => {
2021-12-27 16:15:25 +01:00
// Replace the character at the specified index position
2022-01-02 16:26:38 +01:00
let new_ch = value.as_char().map_err(|err| {
2021-12-27 16:15:25 +01:00
Box::new(ERR::ErrorMismatchDataType(
"char".to_string(),
err.to_string(),
Position::NONE,
))
})?;
2022-01-02 16:26:38 +01:00
let s = &mut *source
2021-12-27 16:15:25 +01:00
.write_lock::<ImmutableString>()
.expect("`ImmutableString`");
let index = *index;
*s = s
.chars()
.enumerate()
.map(|(i, ch)| if i == index { new_ch } else { ch })
.collect();
}
}
2021-12-27 16:15:25 +01:00
Ok(())
}
2021-12-27 16:15:25 +01:00
}
impl<'a> From<&'a mut Dynamic> for Target<'a> {
#[inline]
fn from(value: &'a mut Dynamic) -> Self {
#[cfg(not(feature = "no_closure"))]
if value.is_shared() {
// Cloning is cheap for a shared value
2022-01-02 16:26:38 +01:00
let val = value.clone();
let source = value.write_lock::<Dynamic>().expect("`Dynamic`");
return Self::SharedValue { source, value: val };
}
2021-12-27 16:15:25 +01:00
Self::RefMut(value)
}
2020-11-01 16:42:00 +01:00
}
2021-12-27 16:15:25 +01:00
impl Deref for Target<'_> {
type Target = Dynamic;
2021-07-04 10:33:26 +02:00
#[inline]
2021-12-27 16:15:25 +01:00
fn deref(&self) -> &Dynamic {
match self {
Self::RefMut(r) => *r,
#[cfg(not(feature = "no_closure"))]
2022-01-02 16:26:38 +01:00
Self::SharedValue { source, .. } => &**source,
2021-12-27 16:15:25 +01:00
Self::TempValue(ref r) => r,
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::Bit { ref value, .. }
| Self::BitField { ref value, .. }
| Self::BlobByte { ref value, .. }
| Self::StringChar { ref value, .. } => value,
2021-12-27 16:15:25 +01:00
}
2021-07-04 10:33:26 +02:00
}
}
2021-12-27 16:15:25 +01:00
impl AsRef<Dynamic> for Target<'_> {
#[inline(always)]
fn as_ref(&self) -> &Dynamic {
self
2021-07-04 10:33:26 +02:00
}
}
2021-12-27 16:15:25 +01:00
impl DerefMut for Target<'_> {
#[inline]
fn deref_mut(&mut self) -> &mut Dynamic {
match self {
Self::RefMut(r) => *r,
#[cfg(not(feature = "no_closure"))]
2022-01-02 16:26:38 +01:00
Self::SharedValue { source, .. } => &mut *source,
2021-12-27 16:15:25 +01:00
Self::TempValue(ref mut r) => r,
#[cfg(not(feature = "no_index"))]
2022-01-02 16:26:38 +01:00
Self::Bit { ref mut value, .. }
| Self::BitField { ref mut value, .. }
| Self::BlobByte { ref mut value, .. }
| Self::StringChar { ref mut value, .. } => value,
2021-12-27 16:15:25 +01:00
}
2021-07-04 10:33:26 +02:00
}
}
2021-12-27 16:15:25 +01:00
impl AsMut<Dynamic> for Target<'_> {
#[inline(always)]
fn as_mut(&mut self) -> &mut Dynamic {
self
2021-04-06 17:18:41 +02:00
}
}
2021-12-27 16:15:25 +01:00
impl<T: Into<Dynamic>> From<T> for Target<'_> {
#[inline(always)]
#[must_use]
fn from(value: T) -> Self {
Self::TempValue(value.into())
}
}
2021-12-15 05:06:17 +01:00
2021-12-27 16:15:25 +01:00
/// _(internals)_ A stack of imported [modules][Module] plus mutable global runtime states.
/// Exported under the `internals` feature only.
//
// # Implementation Notes
//
// 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.
#[derive(Clone)]
pub struct GlobalRuntimeState {
/// Stack of module names.
//
// We cannot use Cow<str> here because `eval` may load a [module][Module] and
// the module name will live beyond the AST of the eval script text.
keys: StaticVec<Identifier>,
2021-12-30 01:57:23 +01:00
/// Stack of imported [modules][Module].
2021-12-27 16:15:25 +01:00
modules: StaticVec<Shared<Module>>,
/// Source of the current context.
/// No source if the string is empty.
pub source: Identifier,
2021-12-27 16:15:25 +01:00
/// Number of operations performed.
pub num_operations: u64,
/// Number of modules loaded.
pub num_modules_loaded: usize,
/// Function call hashes to index getters and setters.
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
fn_hash_indexing: (u64, u64),
2021-12-30 01:57:23 +01:00
/// Embedded [module][Module] resolver.
2021-12-27 16:15:25 +01:00
#[cfg(not(feature = "no_module"))]
pub embedded_module_resolver: Option<Shared<crate::module::resolvers::StaticModuleResolver>>,
/// Cache of globally-defined constants.
#[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_function"))]
constants: Option<Shared<crate::Locked<BTreeMap<Identifier, Dynamic>>>>,
2020-10-15 17:30:30 +02:00
}
2021-12-27 16:15:25 +01:00
impl Default for GlobalRuntimeState {
2020-12-29 03:41:20 +01:00
#[inline(always)]
2021-12-27 16:15:25 +01:00
fn default() -> Self {
Self::new()
2020-10-15 17:30:30 +02:00
}
2021-12-27 16:15:25 +01:00
}
impl GlobalRuntimeState {
/// Create a new [`GlobalRuntimeState`].
2020-12-29 03:41:20 +01:00
#[inline(always)]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-12-27 16:15:25 +01:00
pub const fn new() -> Self {
Self {
keys: StaticVec::new_const(),
modules: StaticVec::new_const(),
source: Identifier::new_const(),
2021-12-27 16:15:25 +01:00
num_operations: 0,
num_modules_loaded: 0,
#[cfg(not(feature = "no_module"))]
embedded_module_resolver: None,
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
fn_hash_indexing: (0, 0),
#[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_function"))]
constants: None,
2020-10-15 17:30:30 +02:00
}
}
2021-12-27 16:15:25 +01:00
/// Get the length of the stack of globally-imported [modules][Module].
#[inline(always)]
#[must_use]
2021-12-27 16:15:25 +01:00
pub fn num_imported_modules(&self) -> usize {
self.keys.len()
}
2021-12-27 16:15:25 +01:00
/// Get the globally-imported [module][Module] at a particular index.
2020-12-29 03:41:20 +01:00
#[inline(always)]
2021-12-27 10:00:21 +01:00
#[must_use]
2021-12-27 16:15:25 +01:00
pub fn get_shared_module(&self, index: usize) -> Option<Shared<Module>> {
self.modules.get(index).cloned()
2020-10-15 17:30:30 +02:00
}
2021-12-27 16:15:25 +01:00
/// Get a mutable reference to the globally-imported [module][Module] at a particular index.
#[allow(dead_code)]
2020-12-29 03:41:20 +01:00
#[inline(always)]
2021-12-27 10:00:21 +01:00
#[must_use]
2021-12-27 16:15:25 +01:00
pub(crate) fn get_shared_module_mut(&mut self, index: usize) -> Option<&mut Shared<Module>> {
self.modules.get_mut(index)
2020-10-15 17:30:30 +02:00
}
2021-12-27 16:15:25 +01:00
/// Get the index of a globally-imported [module][Module] by name.
#[inline]
#[must_use]
2022-01-04 08:22:48 +01:00
pub fn find_module(&self, name: &str) -> Option<usize> {
2021-12-27 16:15:25 +01:00
let len = self.keys.len();
2020-10-15 17:30:30 +02:00
2021-12-27 16:15:25 +01:00
self.keys.iter().rev().enumerate().find_map(|(i, key)| {
if key == name {
Some(len - 1 - i)
} else {
None
}
})
2021-07-24 06:27:33 +02:00
}
2021-12-27 16:15:25 +01:00
/// Push an imported [module][Module] onto the stack.
#[inline(always)]
pub fn push_module(&mut self, name: impl Into<Identifier>, module: impl Into<Shared<Module>>) {
self.keys.push(name.into());
self.modules.push(module.into());
}
/// Truncate the stack of globally-imported [modules][Module] to a particular length.
#[inline(always)]
pub fn truncate_modules(&mut self, size: usize) {
self.keys.truncate(size);
self.modules.truncate(size);
}
/// Get an iterator to the stack of globally-imported [modules][Module] in reverse order.
2020-10-04 04:40:44 +02:00
#[allow(dead_code)]
#[inline]
2021-12-27 16:15:25 +01:00
pub fn iter_modules(&self) -> impl Iterator<Item = (&str, &Module)> {
self.keys
.iter()
.rev()
.zip(self.modules.iter().rev())
.map(|(name, module)| (name.as_str(), module.as_ref()))
2020-06-06 07:06:00 +02:00
}
2021-12-27 16:15:25 +01:00
/// Get an iterator to the stack of globally-imported [modules][Module] in reverse order.
#[allow(dead_code)]
#[inline]
pub(crate) fn iter_modules_raw(&self) -> impl Iterator<Item = (&Identifier, &Shared<Module>)> {
self.keys.iter().rev().zip(self.modules.iter().rev())
}
/// Get an iterator to the stack of globally-imported [modules][Module] in forward order.
#[allow(dead_code)]
#[inline]
pub(crate) fn scan_modules_raw(&self) -> impl Iterator<Item = (&Identifier, &Shared<Module>)> {
self.keys.iter().zip(self.modules.iter())
}
/// Does the specified function hash key exist in the stack of globally-imported [modules][Module]?
#[allow(dead_code)]
#[inline]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-12-27 16:15:25 +01:00
pub fn contains_fn(&self, hash: u64) -> bool {
self.modules.iter().any(|m| m.contains_qualified_fn(hash))
2020-05-16 05:42:56 +02:00
}
2021-12-27 16:15:25 +01:00
/// Get the specified function via its hash key from the stack of globally-imported [modules][Module].
#[inline]
2021-06-12 16:47:43 +02:00
#[must_use]
pub fn get_fn(&self, hash: u64) -> Option<(&CallableFunction, Option<&str>)> {
2021-12-27 16:15:25 +01:00
self.modules
.iter()
.rev()
.find_map(|m| m.get_qualified_fn(hash).map(|f| (f, m.id())))
2020-07-31 16:30:23 +02:00
}
2021-12-27 16:15:25 +01:00
/// Does the specified [`TypeId`][std::any::TypeId] iterator exist in the stack of
/// globally-imported [modules][Module]?
2020-07-26 09:53:22 +02:00
#[allow(dead_code)]
#[inline]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-12-27 16:15:25 +01:00
pub fn contains_iter(&self, id: TypeId) -> bool {
self.modules.iter().any(|m| m.contains_qualified_iter(id))
}
2021-12-27 16:15:25 +01:00
/// Get the specified [`TypeId`][std::any::TypeId] iterator from the stack of globally-imported
/// [modules][Module].
#[inline]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-12-27 16:15:25 +01:00
pub fn get_iter(&self, id: TypeId) -> Option<IteratorFn> {
self.modules
.iter()
.rev()
.find_map(|m| m.get_qualified_iter(id))
2020-05-16 05:42:56 +02:00
}
2021-12-27 16:15:25 +01:00
/// Get a mutable reference to the cache of globally-defined constants.
#[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_function"))]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-12-27 16:15:25 +01:00
pub(crate) fn constants_mut<'a>(
&'a mut self,
) -> Option<impl DerefMut<Target = BTreeMap<Identifier, Dynamic>> + 'a> {
if let Some(ref global_constants) = self.constants {
Some(crate::func::native::shared_write_lock(global_constants))
} else {
None
2020-10-11 15:58:11 +02:00
}
}
2021-12-27 16:15:25 +01:00
/// Set a constant into the cache of globally-defined constants.
#[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_function"))]
pub(crate) fn set_constant(&mut self, name: impl Into<Identifier>, value: Dynamic) {
if self.constants.is_none() {
let dict: crate::Locked<_> = BTreeMap::new().into();
self.constants = Some(dict.into());
2020-03-30 16:19:37 +02:00
}
2020-04-26 12:04:07 +02:00
2021-12-27 16:15:25 +01:00
crate::func::native::shared_write_lock(self.constants.as_mut().expect("`Some`"))
.insert(name.into(), value);
2020-03-30 16:19:37 +02:00
}
2021-12-27 16:15:25 +01:00
/// Get the pre-calculated index getter hash.
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
#[must_use]
pub(crate) fn hash_idx_get(&mut self) -> u64 {
if self.fn_hash_indexing != (0, 0) {
self.fn_hash_indexing.0
} else {
let n1 = crate::calc_fn_hash(FN_IDX_GET, 2);
let n2 = crate::calc_fn_hash(FN_IDX_SET, 3);
self.fn_hash_indexing = (n1, n2);
n1
}
2020-04-26 12:04:07 +02:00
}
2021-12-27 16:15:25 +01:00
/// Get the pre-calculated index setter hash.
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
#[must_use]
pub(crate) fn hash_idx_set(&mut self) -> u64 {
if self.fn_hash_indexing != (0, 0) {
self.fn_hash_indexing.1
} else {
let n1 = crate::calc_fn_hash(FN_IDX_GET, 2);
let n2 = crate::calc_fn_hash(FN_IDX_SET, 3);
self.fn_hash_indexing = (n1, n2);
n2
}
}
}
2021-12-27 16:15:25 +01:00
impl IntoIterator for GlobalRuntimeState {
type Item = (Identifier, Shared<Module>);
type IntoIter =
Zip<Rev<smallvec::IntoIter<[Identifier; 3]>>, Rev<smallvec::IntoIter<[Shared<Module>; 3]>>>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.keys
.into_iter()
.rev()
.zip(self.modules.into_iter().rev())
2021-04-17 07:36:51 +02:00
}
}
2021-12-27 16:15:25 +01:00
impl<K: Into<Identifier>, M: Into<Shared<Module>>> FromIterator<(K, M)> for GlobalRuntimeState {
fn from_iter<T: IntoIterator<Item = (K, M)>>(iter: T) -> Self {
let mut lib = Self::new();
lib.extend(iter);
lib
}
}
2021-12-27 16:15:25 +01:00
impl<K: Into<Identifier>, M: Into<Shared<Module>>> Extend<(K, M)> for GlobalRuntimeState {
fn extend<T: IntoIterator<Item = (K, M)>>(&mut self, iter: T) {
iter.into_iter().for_each(|(k, m)| {
self.keys.push(k.into());
self.modules.push(m.into());
})
2021-04-17 07:36:51 +02:00
}
}
2021-12-27 16:15:25 +01:00
impl fmt::Debug for GlobalRuntimeState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Imports")?;
f.debug_map()
.entries(self.keys.iter().zip(self.modules.iter()))
.finish()
}
}
2021-12-28 05:19:20 +01:00
/// _(internals)_ A type that holds all the current states of the [`Engine`].
/// Exported under the `internals` feature only.
2021-12-28 05:19:20 +01:00
#[derive(Debug, Clone)]
pub struct EvalState {
2021-12-30 01:57:23 +01:00
/// Force a [`Scope`] search by name.
///
2021-07-04 10:40:15 +02:00
/// Normally, access to variables are parsed with a relative offset into the [`Scope`] to avoid a lookup.
2021-12-30 01:57:23 +01:00
///
2021-07-26 04:03:46 +02:00
/// In some situation, e.g. after running an `eval` statement, or after a custom syntax statement,
/// subsequent offsets may become mis-aligned.
2021-12-30 01:57:23 +01:00
///
/// When that happens, this flag is turned on.
2021-07-04 10:40:15 +02:00
pub always_search_scope: bool,
2021-12-30 01:57:23 +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,
/// Stack of function resolution caches.
fn_resolution_caches: StaticVec<FnResolutionCache>,
2021-10-27 11:52:48 +02:00
}
2021-07-04 10:40:15 +02:00
impl EvalState {
/// Create a new [`EvalState`].
#[inline(always)]
#[must_use]
2021-11-25 10:09:00 +01:00
pub const fn new() -> Self {
2021-07-04 10:40:15 +02:00
Self {
2021-12-28 05:19:20 +01:00
always_search_scope: false,
scope_level: 0,
2021-11-25 10:09:00 +01:00
fn_resolution_caches: StaticVec::new_const(),
2021-07-04 10:40:15 +02:00
}
}
2021-11-27 07:24:36 +01:00
/// Get the number of function resolution cache(s) in the stack.
#[inline(always)]
#[must_use]
pub fn fn_resolution_caches_len(&self) -> usize {
self.fn_resolution_caches.len()
}
2021-03-13 11:46:08 +01:00
/// Get a mutable reference to the current function resolution cache.
#[inline]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-03-13 11:46:08 +01:00
pub fn fn_resolution_cache_mut(&mut self) -> &mut FnResolutionCache {
if self.fn_resolution_caches.is_empty() {
2021-05-22 13:14:24 +02:00
// Push a new function resolution cache if the stack is empty
self.push_fn_resolution_cache();
}
2022-01-06 04:07:52 +01:00
self.fn_resolution_caches.last_mut().unwrap()
}
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) {
self.fn_resolution_caches.push(BTreeMap::new());
}
2021-11-27 07:24:36 +01:00
/// Rewind the function resolution caches stack to a particular size.
2021-04-21 11:39:45 +02:00
#[inline(always)]
2021-11-27 07:24:36 +01:00
pub fn rewind_fn_resolution_caches(&mut self, len: usize) {
self.fn_resolution_caches.truncate(len);
}
2020-04-28 17:05:03 +02:00
}
2020-10-11 15:58:11 +02:00
/// Context of a script evaluation process.
#[derive(Debug)]
2021-06-29 17:17:31 +02:00
pub struct EvalContext<'a, 'x, 'px, 'm, 's, 'b, 't, 'pt> {
2022-01-02 08:14:55 +01:00
/// The current [`Engine`].
2021-03-03 15:49:57 +01:00
pub(crate) engine: &'a Engine,
2022-01-02 08:14:55 +01:00
/// The current [`Scope`].
2020-12-14 16:05:13 +01:00
pub(crate) scope: &'x mut Scope<'px>,
2022-01-02 08:14:55 +01:00
/// The current [`GlobalRuntimeState`].
2021-12-27 16:03:30 +01:00
pub(crate) global: &'m mut GlobalRuntimeState,
2022-01-02 08:14:55 +01:00
/// The current [evaluation state][EvalState].
2021-07-04 10:40:15 +02:00
pub(crate) state: &'s mut EvalState,
2022-01-02 08:14:55 +01:00
/// The current stack of imported [modules][Module].
2021-06-29 17:17:31 +02:00
pub(crate) lib: &'b [&'b Module],
2022-01-02 08:14:55 +01:00
/// The current bound `this` pointer, if any.
pub(crate) this_ptr: &'t mut Option<&'pt mut Dynamic>,
2022-01-02 08:14:55 +01:00
/// The current nesting level of function calls.
pub(crate) level: usize,
2020-10-11 15:58:11 +02:00
}
2021-07-04 10:40:15 +02:00
impl<'x, 'px, 'pt> EvalContext<'_, 'x, 'px, '_, '_, '_, '_, 'pt> {
2020-11-20 09:52:28 +01:00
/// The current [`Engine`].
#[inline(always)]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-06-29 17:17:31 +02:00
pub const 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-06-12 16:47:43 +02:00
#[must_use]
2021-01-01 10:05:06 +01:00
pub fn source(&self) -> Option<&str> {
2022-01-03 16:16:47 +01:00
match self.global.source.as_str() {
"" => None,
s => Some(s),
}
2020-12-21 16:12:45 +01:00
}
2020-12-14 16:05:13 +01:00
/// The current [`Scope`].
#[inline(always)]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-06-29 17:17:31 +02:00
pub const fn scope(&self) -> &Scope<'px> {
2020-12-14 16:05:13 +01:00
self.scope
}
/// Mutable reference to the current [`Scope`].
#[inline(always)]
2021-06-12 16:47:43 +02:00
#[must_use]
2020-12-14 16:05:13 +01:00
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)> {
2021-12-27 16:03:30 +01:00
self.global.iter_modules()
2021-01-01 10:05:06 +01:00
}
2021-12-27 16:03:30 +01:00
/// _(internals)_ The current [`GlobalRuntimeState`].
/// 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-06-12 16:47:43 +02:00
#[must_use]
2021-12-27 16:03:30 +01:00
pub const fn global_runtime_state(&self) -> &GlobalRuntimeState {
self.global
2020-10-11 15:58:11 +02:00
}
/// Get an iterator over the namespaces containing definition of all script-defined functions.
#[inline]
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-07-25 16:56:05 +02: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)]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-06-29 17:17:31 +02:00
pub const fn namespaces(&self) -> &[&Module] {
2021-01-01 10:05:06 +01:00
self.lib
}
/// The current bound `this` pointer, if any.
#[inline(always)]
2021-06-12 16:47:43 +02:00
#[must_use]
pub fn this_ptr(&self) -> Option<&Dynamic> {
self.this_ptr.as_ref().map(|v| &**v)
}
2021-07-04 10:40:15 +02:00
/// Mutable reference to the current bound `this` pointer, if any.
#[inline(always)]
#[must_use]
pub fn this_ptr_mut(&mut self) -> Option<&mut &'pt mut Dynamic> {
self.this_ptr.as_mut()
}
2020-10-11 15:58:11 +02:00
/// The current nesting level of function calls.
#[inline(always)]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-06-29 17:17:31 +02:00
pub const fn call_level(&self) -> usize {
2020-10-11 15:58:11 +02:00
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-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"))]
2021-05-29 12:33:29 +02:00
pub(crate) module_resolver: Option<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.
pub(crate) type_names: BTreeMap<Identifier, Identifier>,
2020-07-05 09:23:51 +02:00
2021-09-29 06:16:59 +02:00
/// An empty [`ImmutableString`] for cloning purposes.
pub(crate) empty_string: ImmutableString,
2021-04-04 07:13:07 +02:00
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>,
2021-09-24 12:00:48 +02:00
/// Callback closure to remap tokens during parsing.
pub(crate) token_mapper: Option<Box<OnParseTokenCallback>>,
2020-06-02 07:33:16 +02:00
/// Callback closure for implementing the `print` command.
2021-06-29 11:42:03 +02:00
pub(crate) print: Option<OnPrintCallback>,
2020-06-02 07:33:16 +02:00
/// Callback closure for implementing the `debug` command.
2021-06-29 11:42:03 +02:00
pub(crate) debug: Option<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"))]
2021-11-13 15:36:23 +01:00
pub(crate) progress: Option<crate::func::native::OnProgressCallback>,
2020-03-27 07:34:01 +01:00
2021-11-20 14:29:36 +01:00
/// Optimize the [`AST`][crate::AST] after compilation.
#[cfg(not(feature = "no_optimize"))]
pub(crate) optimization_level: crate::OptimizationLevel,
2020-07-26 09:53:22 +02:00
2021-12-03 04:16:35 +01:00
/// Language options.
pub(crate) options: crate::api::options::LanguageOptions,
2020-07-26 09:53:22 +02:00
/// Max limits.
#[cfg(not(feature = "unchecked"))]
2021-11-28 15:57:28 +01:00
pub(crate) limits: crate::api::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"))]
2022-01-04 08:22:48 +01:00
#[inline(always)]
2021-06-12 16:47:43 +02:00
#[must_use]
2022-01-04 08:22:48 +01:00
pub fn make_getter(id: &str) -> Identifier {
let mut buf = Identifier::new_const();
buf.push_str(FN_GET);
buf.push_str(id);
buf
2020-03-30 10:10:50 +02:00
}
/// Make setter function
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_object"))]
2022-01-04 08:22:48 +01:00
#[inline(always)]
2021-06-12 16:47:43 +02:00
#[must_use]
2022-01-04 08:22:48 +01:00
pub fn make_setter(id: &str) -> Identifier {
let mut buf = Identifier::new_const();
buf.push_str(FN_SET);
buf.push_str(id);
buf
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)]
2021-06-12 16:47:43 +02:00
#[must_use]
2022-01-04 08:22:48 +01:00
pub fn is_anonymous_fn(fn_name: &str) -> bool {
fn_name.starts_with(FN_ANONYMOUS)
2020-10-12 16:49:51 +02:00
}
2021-06-29 11:47:31 +02:00
/// Print to `stdout`
#[inline]
2021-06-29 11:47:31 +02:00
#[allow(unused_variables)]
fn print_to_stdout(s: &str) {
2020-04-19 12:33:02 +02:00
#[cfg(not(feature = "no_std"))]
2022-01-04 15:16:20 +01:00
#[cfg(not(target_arch = "wasm32"))]
#[cfg(not(target_arch = "wasm64"))]
2021-06-29 11:47:31 +02:00
println!("{}", s);
2020-04-19 12:33:02 +02:00
}
2021-06-29 11:47:31 +02:00
/// Debug to `stdout`
#[inline]
2021-06-29 11:47:31 +02:00
#[allow(unused_variables)]
fn debug_to_stdout(s: &str, source: Option<&str>, pos: Position) {
2020-12-12 04:47:18 +01:00
#[cfg(not(feature = "no_std"))]
2022-01-04 15:16:20 +01:00
#[cfg(not(target_arch = "wasm32"))]
#[cfg(not(target_arch = "wasm64"))]
2021-06-29 11:47:31 +02:00
if let Some(source) = source {
println!("{}{:?} | {}", source, pos, s);
} else if pos.is_none() {
println!("{}", s);
2020-12-21 15:04:46 +01:00
} else {
2021-06-29 11:47:31 +02:00
println!("{:?} | {}", pos, s);
2020-12-21 15:04:46 +01:00
}
2020-12-12 04:47:18 +01:00
}
2020-04-16 17:31:48 +02:00
impl Engine {
2021-06-29 11:47:31 +02:00
/// Create a new [`Engine`].
2020-11-10 16:26:50 +01:00
#[inline]
2021-06-12 16:47:43 +02:00
#[must_use]
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
2021-06-29 11:47:31 +02:00
let mut engine = Self::new_raw();
#[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_std"))]
2022-01-04 15:16:20 +01:00
#[cfg(not(target_arch = "wasm32"))]
#[cfg(not(target_arch = "wasm64"))]
2021-06-29 11:47:31 +02:00
{
engine.module_resolver =
Some(Box::new(crate::module::resolvers::FileModuleResolver::new()));
}
2020-10-03 17:27:30 +02:00
2021-06-29 11:47:31 +02:00
// default print/debug implementations
engine.print = Some(Box::new(print_to_stdout));
engine.debug = Some(Box::new(debug_to_stdout));
2020-10-03 17:27:30 +02:00
2020-12-22 16:45:14 +01:00
engine.register_global_module(StandardPackage::new().as_shared_module());
2020-10-03 17:27:30 +02:00
engine
2020-03-25 04:27:18 +01:00
}
2020-03-09 14:57:07 +01:00
2020-11-20 09:52:28 +01:00
/// Create a new [`Engine`] with minimal built-in functions.
2021-01-02 16:30:10 +01:00
///
/// Use [`register_global_module`][Engine::register_global_module] to add packages of functions.
#[inline]
2021-06-12 16:47:43 +02:00
#[must_use]
pub fn new_raw() -> Self {
2021-04-17 12:40:16 +02:00
let mut engine = Self {
2021-11-25 10:09:00 +01:00
global_modules: StaticVec::new_const(),
global_sub_modules: BTreeMap::new(),
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_module"))]
2021-05-29 12:33:29 +02:00
module_resolver: None,
type_names: BTreeMap::new(),
empty_string: ImmutableString::new(),
disabled_symbols: BTreeSet::new(),
custom_keywords: BTreeMap::new(),
custom_syntax: BTreeMap::new(),
2020-07-05 09:23:51 +02:00
2020-10-11 15:58:11 +02:00
resolve_var: None,
2021-09-24 12:00:48 +02:00
token_mapper: None,
2020-10-11 15:58:11 +02:00
2021-06-29 11:42:03 +02:00
print: None,
debug: None,
2021-04-25 09:27:58 +02:00
#[cfg(not(feature = "unchecked"))]
progress: None,
#[cfg(not(feature = "no_optimize"))]
2021-11-27 07:24:06 +01:00
optimization_level: crate::OptimizationLevel::default(),
2021-12-03 04:16:35 +01:00
options: crate::api::options::LanguageOptions::new(),
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "unchecked"))]
2021-11-28 15:57:28 +01:00
limits: crate::api::limits::Limits::new(),
2021-04-17 12:40:16 +02:00
};
// Add the global namespace module
let mut global_namespace = Module::new();
global_namespace.internal = true;
engine.global_modules.push(global_namespace.into());
2021-04-17 12:40:16 +02:00
engine
}
2021-09-26 15:18:52 +02:00
/// Get an empty [`ImmutableString`].
2021-09-26 15:25:29 +02:00
///
/// [`Engine`] keeps a single instance of an empty [`ImmutableString`] and uses this to create
/// shared instances for subsequent uses. This minimizes unnecessary allocations for empty strings.
2021-09-26 15:18:52 +02:00
#[inline(always)]
#[must_use]
2021-09-26 15:25:29 +02:00
pub fn const_empty_string(&self) -> ImmutableString {
2021-09-29 06:16:59 +02:00
self.empty_string.clone()
2021-09-26 15:18:52 +02:00
}
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-06-12 16:47:43 +02:00
#[must_use]
2021-03-03 15:49:57 +01:00
pub(crate) fn search_imports(
2021-03-01 07:54:20 +01:00
&self,
2021-12-27 16:03:30 +01:00
global: &GlobalRuntimeState,
2021-07-04 10:40:15 +02:00
state: &mut EvalState,
2021-12-25 16:49:14 +01:00
namespace: &Namespace,
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
2021-12-28 05:19:20 +01:00
let index = if state.always_search_scope {
2021-03-01 07:54:20 +01:00
None
} else {
namespace.index()
};
2021-03-03 15:49:57 +01:00
if let Some(index) = index {
2021-12-27 16:03:30 +01:00
let offset = global.num_imported_modules() - index.get();
2022-01-06 04:07:52 +01:00
Some(global.get_shared_module(offset).unwrap())
2021-03-01 07:54:20 +01:00
} else {
2021-12-27 16:03:30 +01:00
global
.find_module(root)
2022-01-06 04:07:52 +01:00
.map(|n| global.get_shared_module(n).unwrap())
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,
2021-12-27 16:03:30 +01:00
global: &mut GlobalRuntimeState,
2021-07-04 10:40:15 +02:00
state: &mut EvalState,
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,
2021-12-25 16:49:14 +01:00
) -> RhaiResultOf<(Target<'s>, Position)> {
2020-10-11 15:58:11 +02:00
match expr {
2021-04-05 17:59:15 +02:00
Expr::Variable(Some(_), _, _) => {
2021-12-27 16:03:30 +01:00
self.search_scope_only(scope, global, state, lib, this_ptr, expr)
2021-04-05 17:06:48 +02:00
}
2021-10-29 11:01:29 +02:00
Expr::Variable(None, _var_pos, v) => match v.as_ref() {
2021-04-05 17:06:48 +02:00
// Normal variable access
2021-12-27 16:03:30 +01:00
(_, None, _) => self.search_scope_only(scope, global, state, lib, this_ptr, expr),
2021-11-08 05:07:49 +01:00
2021-10-27 17:30:25 +02:00
// Qualified variable access
2021-10-29 11:01:29 +02:00
#[cfg(not(feature = "no_module"))]
2021-06-16 12:36:33 +02:00
(_, Some((namespace, hash_var)), var_name) => {
2021-12-27 16:03:30 +01:00
if let Some(module) = self.search_imports(global, state, namespace) {
2021-10-27 17:30:25 +02:00
// foo:bar::baz::VARIABLE
2021-10-29 11:10:28 +02:00
return match module.get_qualified_var(*hash_var) {
2021-10-27 17:30:25 +02:00
Ok(target) => {
let mut target = target.clone();
// Module variables are constant
target.set_access_mode(AccessMode::ReadOnly);
2021-10-29 11:01:29 +02:00
Ok((target.into(), *_var_pos))
2021-10-27 17:30:25 +02:00
}
Err(err) => Err(match *err {
2021-12-27 05:27:31 +01:00
ERR::ErrorVariableNotFound(_, _) => ERR::ErrorVariableNotFound(
format!(
"{}{}{}",
namespace,
Token::DoubleColon.literal_syntax(),
var_name
),
namespace[0].pos,
)
.into(),
_ => err.fill_position(*_var_pos),
}),
2021-10-29 11:10:28 +02:00
};
}
#[cfg(not(feature = "no_function"))]
if namespace.len() == 1 && namespace[0].name == KEYWORD_GLOBAL {
2021-10-27 17:30:25 +02:00
// global::VARIABLE
2021-12-27 16:03:30 +01:00
let global_constants = global.constants_mut();
if let Some(mut guard) = global_constants {
if let Some(value) = guard.get_mut(var_name) {
let mut target: Target = value.clone().into();
// Module variables are constant
target.set_access_mode(AccessMode::ReadOnly);
return Ok((target.into(), *_var_pos));
}
}
2021-12-27 05:27:31 +01:00
return Err(ERR::ErrorVariableNotFound(
format!(
"{}{}{}",
namespace,
Token::DoubleColon.literal_syntax(),
var_name
),
namespace[0].pos,
)
.into());
2021-10-27 11:52:48 +02:00
}
2021-10-29 11:10:28 +02:00
2021-12-27 05:27:31 +01:00
Err(ERR::ErrorModuleNotFound(namespace.to_string(), namespace[0].pos).into())
2020-10-11 15:58:11 +02:00
}
2021-11-08 05:07:49 +01:00
2021-10-29 11:01:29 +02:00
#[cfg(feature = "no_module")]
2021-10-29 11:10:28 +02:00
(_, Some((_, _)), _) => unreachable!("qualified access under no_module"),
2020-10-11 15:58:11 +02:00
},
2021-12-30 05:19:41 +01: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,
2021-12-27 16:03:30 +01:00
global: &mut GlobalRuntimeState,
2021-07-04 10:40:15 +02:00
state: &mut EvalState,
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,
2021-12-25 16:49:14 +01:00
) -> RhaiResultOf<(Target<'s>, Position)> {
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 {
2021-12-27 05:27:31 +01:00
Err(ERR::ErrorUnboundThis(*pos).into())
2021-04-05 17:59:15 +02:00
}
}
2021-12-28 05:19:20 +01:00
_ if state.always_search_scope => (0, expr.position()),
2021-04-05 17:59:15 +02:00
Expr::Variable(Some(i), pos, _) => (i.get() as usize, *pos),
Expr::Variable(None, pos, v) => (v.0.map(NonZeroUsize::get).unwrap_or(0), *pos),
2021-12-30 05:19:41 +01:00
_ => 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,
2021-12-27 16:03:30 +01:00
global,
2020-10-11 15:58:11 +02:00
state,
lib,
this_ptr,
level: 0,
};
2021-06-16 10:15:29 +02:00
match resolve_var(
2022-01-06 04:07:52 +01:00
expr.get_variable_name(true).expect("`Expr::Variable`"),
2021-05-22 13:14:24 +02:00
index,
&context,
2021-06-16 10:15:29 +02:00
) {
Ok(Some(mut result)) => {
result.set_access_mode(AccessMode::ReadOnly);
return Ok((result.into(), var_pos));
}
Ok(None) => (),
Err(err) => return Err(err.fill_position(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
2022-01-06 04:07:52 +01:00
let var_name = expr.get_variable_name(true).expect("`Expr::Variable`");
2020-10-11 15:58:11 +02:00
scope
2021-04-05 17:59:15 +02:00
.get_index(var_name)
2021-12-27 05:27:31 +01:00
.ok_or_else(|| ERR::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,
2021-12-27 16:03:30 +01:00
global: &mut GlobalRuntimeState,
2021-07-04 10:40:15 +02:00
state: &mut EvalState,
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-08-13 07:42:39 +02:00
terminate_chaining: bool,
2021-12-27 10:00:21 +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))>,
2021-12-25 16:49:14 +01:00
) -> RhaiResultOf<(Dynamic, bool)> {
2021-06-17 03:50:32 +02:00
let is_ref_mut = target.is_ref();
2021-08-13 07:42:39 +02:00
let _terminate_chaining = terminate_chaining;
2020-04-26 12:04:07 +02:00
// Pop the last index value
2022-01-06 04:07:52 +01:00
let idx_val = idx_values.pop().unwrap();
2020-03-01 17:11:00 +01:00
match chain_type {
#[cfg(not(feature = "no_index"))]
2021-07-24 06:27:33 +02:00
ChainType::Indexing => {
let pos = rhs.position();
let root_pos = idx_val.position();
2021-11-13 05:23:35 +01:00
let idx_val = idx_val.into_index_value().expect("`ChainType::Index`");
match rhs {
// xxx[idx].expr... | xxx[idx][expr]...
2021-07-24 06:27:33 +02:00
Expr::Dot(x, term, x_pos) | Expr::Index(x, term, x_pos)
if !_terminate_chaining =>
{
let mut idx_val_for_setter = idx_val.clone();
2020-10-27 16:00:05 +01:00
let idx_pos = x.lhs.position();
2022-01-02 16:26:38 +01:00
let rhs_chain = rhs.into();
let (try_setter, result) = {
let mut obj = self.get_indexed_mut(
2021-12-27 16:03:30 +01:00
global, state, lib, target, idx_val, idx_pos, false, true, level,
)?;
let is_obj_temp_val = obj.is_temp_value();
let obj_ptr = &mut obj;
match self.eval_dot_index_chain_helper(
2021-12-27 16:03:30 +01:00
global, state, lib, this_ptr, obj_ptr, root, &x.rhs, *term,
idx_values, rhs_chain, level, new_val,
) {
Ok((result, true)) if is_obj_temp_val => {
(Some(obj.take_or_clone()), (result, true))
}
Ok(result) => (None, result),
Err(err) => return Err(err.fill_position(*x_pos)),
}
};
if let Some(mut new_val) = try_setter {
// Try to call index setter if value is changed
2021-12-06 13:52:47 +01:00
let hash_set =
2021-12-27 16:03:30 +01:00
crate::ast::FnCallHashes::from_native(global.hash_idx_set());
let args = &mut [target, &mut idx_val_for_setter, &mut new_val];
if let Err(err) = self.exec_fn_call(
2021-12-27 16:03:30 +01:00
global, state, lib, FN_IDX_SET, hash_set, args, is_ref_mut, true,
root_pos, None, level,
) {
// Just ignore if there is no index setter
2021-12-27 05:27:31 +01:00
if !matches!(*err, ERR::ErrorFunctionNotFound(_, _)) {
return Err(err);
}
}
}
#[cfg(not(feature = "unchecked"))]
2022-01-05 06:14:18 +01:00
self.check_data_size(target.as_ref(), root.1)?;
Ok(result)
}
// xxx[rhs] op= new_val
2020-08-08 10:24:10 +02:00
_ if new_val.is_some() => {
2021-11-13 05:23:35 +01:00
let ((new_val, new_pos), (op_info, op_pos)) = new_val.expect("`Some`");
2021-05-19 14:26:11 +02:00
let mut idx_val_for_setter = idx_val.clone();
2021-06-11 13:59:50 +02:00
let try_setter = match self.get_indexed_mut(
2021-12-27 16:03:30 +01:00
global, state, lib, target, idx_val, pos, true, false, level,
) {
// Indexed value is a reference - update directly
2021-06-11 13:59:50 +02:00
Ok(ref mut obj_ptr) => {
2021-02-24 04:04:54 +01:00
self.eval_op_assignment(
2021-12-27 16:03:30 +01:00
global, state, lib, op_info, op_pos, obj_ptr, root, new_val,
2021-06-08 17:40:21 +02:00
)
.map_err(|err| err.fill_position(new_pos))?;
2021-06-11 13:59:50 +02:00
None
}
2021-05-19 14:26:11 +02:00
// Can't index - try to call an index setter
#[cfg(not(feature = "no_index"))]
2021-12-27 05:27:31 +01:00
Err(err) if matches!(*err, ERR::ErrorIndexingType(_, _)) => {
2021-06-11 13:59:50 +02:00
Some(new_val)
}
2021-05-19 14:26:11 +02:00
// Any other error
Err(err) => return Err(err),
2021-06-11 13:59:50 +02:00
};
2021-06-11 13:59:50 +02:00
if let Some(mut new_val) = try_setter {
// Try to call index setter
2021-12-06 13:52:47 +01:00
let hash_set =
2021-12-27 16:03:30 +01:00
crate::ast::FnCallHashes::from_native(global.hash_idx_set());
2021-06-11 13:59:50 +02:00
let args = &mut [target, &mut idx_val_for_setter, &mut new_val];
2021-05-19 14:26:11 +02:00
2021-06-11 13:59:50 +02:00
self.exec_fn_call(
2021-12-27 16:03:30 +01:00
global, state, lib, FN_IDX_SET, hash_set, args, is_ref_mut, true,
root_pos, None, level,
2021-06-11 13:59:50 +02:00
)?;
}
#[cfg(not(feature = "unchecked"))]
2022-01-05 06:14:18 +01:00
self.check_data_size(target.as_ref(), root.1)?;
2021-05-19 14:26:11 +02:00
2020-11-20 15:23:37 +01:00
Ok((Dynamic::UNIT, true))
2020-06-06 07:06:00 +02:00
}
// xxx[rhs]
2021-06-30 04:13:45 +02:00
_ => self
2021-12-27 16:03:30 +01:00
.get_indexed_mut(
global, state, lib, target, idx_val, pos, false, true, level,
)
2021-06-30 04:13:45 +02:00
.map(|v| (v.take_or_clone(), false)),
2020-04-26 12:04:07 +02:00
}
}
#[cfg(not(feature = "no_object"))]
2021-07-24 06:27:33 +02:00
ChainType::Dotting => {
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();
2021-12-27 10:00:21 +01:00
let call_args = &mut idx_val.into_fn_call_args();
self.make_method_call(
2021-12-27 16:03:30 +01:00
global, state, lib, name, *hashes, target, call_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-12-06 13:52:47 +01:00
Expr::Property(x) if target.is::<crate::Map>() && new_val.is_some() => {
2021-05-18 14:12:30 +02:00
let (name, pos) = &x.2;
2021-11-13 05:23:35 +01:00
let ((new_val, new_pos), (op_info, op_pos)) = new_val.expect("`Some`");
2021-03-29 05:36:02 +02:00
let index = name.into();
2021-06-11 13:59:50 +02:00
{
2021-06-13 11:41:34 +02:00
let val_target = &mut self.get_indexed_mut(
2021-12-27 16:03:30 +01:00
global, state, lib, target, index, *pos, true, false, level,
2021-06-11 13:59:50 +02:00
)?;
self.eval_op_assignment(
2021-12-27 16:03:30 +01:00
global, state, lib, op_info, op_pos, val_target, root, new_val,
2021-06-11 13:59:50 +02:00
)
.map_err(|err| err.fill_position(new_pos))?;
}
#[cfg(not(feature = "unchecked"))]
2022-01-05 06:14:18 +01:00
self.check_data_size(target.as_ref(), root.1)?;
Ok((Dynamic::UNIT, true))
}
// {xxx:map}.id
2021-12-06 13:52:47 +01:00
Expr::Property(x) if target.is::<crate::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-12-27 16:03:30 +01:00
global, state, lib, target, index, *pos, false, false, level,
2020-08-01 06:21:15 +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-11-13 05:23:35 +01:00
let ((mut new_val, new_pos), (op_info, op_pos)) = new_val.expect("`Some`");
if op_info.is_some() {
2021-12-06 13:52:47 +01:00
let hash = crate::ast::FnCallHashes::from_native(*hash_get);
2021-06-13 11:41:34 +02:00
let args = &mut [target.as_mut()];
2021-05-18 15:38:09 +02:00
let (mut orig_val, _) = self
.exec_fn_call(
2021-12-27 16:03:30 +01:00
global, state, lib, getter, hash, args, is_ref_mut, true, *pos,
2021-06-17 03:50:32 +02:00
None, level,
2021-05-18 15:38:09 +02:00
)
.or_else(|err| match *err {
// Try an indexer if property does not exist
2021-12-27 05:27:31 +01:00
ERR::ErrorDotExpr(_, _) => {
2021-05-18 15:38:09 +02:00
let prop = name.into();
self.get_indexed_mut(
2021-12-27 16:03:30 +01:00
global, state, lib, target, prop, *pos, false, true,
2021-05-18 15:38:09 +02:00
level,
)
.map(|v| (v.take_or_clone(), false))
.map_err(
|idx_err| match *idx_err {
2021-12-27 05:27:31 +01:00
ERR::ErrorIndexingType(_, _) => err,
2021-05-18 15:38:09 +02:00
_ => idx_err,
},
)
}
_ => Err(err),
})?;
2021-06-11 13:59:50 +02:00
self.eval_op_assignment(
2021-12-27 16:03:30 +01:00
global,
2021-06-11 13:59:50 +02:00
state,
lib,
op_info,
op_pos,
&mut (&mut orig_val).into(),
root,
new_val,
2021-06-08 17:40:21 +02:00
)
.map_err(|err| err.fill_position(new_pos))?;
2021-06-11 13:59:50 +02:00
#[cfg(not(feature = "unchecked"))]
2022-01-05 06:14:18 +01:00
self.check_data_size(target.as_ref(), root.1)?;
2021-06-11 13:59:50 +02:00
new_val = orig_val;
}
2021-12-06 13:52:47 +01:00
let hash = crate::ast::FnCallHashes::from_native(*hash_set);
2021-06-13 11:41:34 +02:00
let args = &mut [target.as_mut(), &mut new_val];
2020-06-26 04:39:18 +02:00
self.exec_fn_call(
2021-12-27 16:03:30 +01:00
global, state, lib, setter, hash, args, is_ref_mut, true, *pos, None,
2021-06-17 03:50:32 +02: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
2021-12-27 05:27:31 +01:00
ERR::ErrorDotExpr(_, _) => {
2021-06-13 11:41:34 +02:00
let args = &mut [target, &mut name.into(), &mut new_val];
2021-12-06 13:52:47 +01:00
let hash_set =
2021-12-27 16:03:30 +01:00
crate::ast::FnCallHashes::from_native(global.hash_idx_set());
let pos = Position::NONE;
2021-06-16 10:15:29 +02:00
2021-05-18 14:12:30 +02:00
self.exec_fn_call(
2021-12-27 16:03:30 +01:00
global, state, lib, FN_IDX_SET, hash_set, args, is_ref_mut,
true, pos, None, level,
2021-05-18 14:12:30 +02:00
)
.map_err(
|idx_err| match *idx_err {
2021-12-27 05:27:31 +01:00
ERR::ErrorIndexingType(_, _) => err,
2021-05-18 14:12:30 +02:00
_ => 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-12-06 13:52:47 +01:00
let hash = crate::ast::FnCallHashes::from_native(*hash_get);
2021-06-13 11:41:34 +02:00
let args = &mut [target.as_mut()];
2020-06-26 04:39:18 +02:00
self.exec_fn_call(
2021-12-27 16:03:30 +01:00
global, state, lib, getter, hash, args, is_ref_mut, true, *pos, None,
2021-06-17 03:50:32 +02: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
2021-12-27 05:27:31 +01:00
ERR::ErrorDotExpr(_, _) => {
2021-05-18 14:12:30 +02:00
let prop = name.into();
self.get_indexed_mut(
2021-12-27 16:03:30 +01:00
global, 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 {
2021-12-27 05:27:31 +01:00
ERR::ErrorIndexingType(_, _) => err,
2021-05-18 14:12:30 +02:00
_ => idx_err,
}
})
}
_ => Err(err),
},
2021-09-27 04:34:24 +02:00
// Assume getters are always pure
2021-05-18 14:12:30 +02:00
|(v, _)| Ok((v, false)),
)
}
2020-07-09 16:21:07 +02:00
// {xxx:map}.sub_lhs[expr] | {xxx:map}.sub_lhs.expr
2021-07-24 06:27:33 +02:00
Expr::Index(x, term, x_pos) | Expr::Dot(x, term, x_pos)
2021-12-06 13:52:47 +01:00
if target.is::<crate::Map>() =>
2021-07-24 06:27:33 +02:00
{
2021-06-13 11:41:34 +02:00
let val_target = &mut match x.lhs {
Expr::Property(ref 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-12-27 16:03:30 +01:00
global, 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-06-13 11:41:34 +02:00
Expr::FnCall(ref x, pos) if !x.is_qualified() => {
2021-04-20 16:26:08 +02:00
let FnCallExpr { name, hashes, .. } = x.as_ref();
2021-12-27 10:00:21 +01:00
let call_args = &mut idx_val.into_fn_call_args();
2020-12-12 04:15:09 +01:00
let (val, _) = self.make_method_call(
2021-12-27 16:03:30 +01:00
global, state, lib, name, *hashes, target, call_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
2021-06-13 11:41:34 +02:00
ref expr => unreachable!("invalid dot expression: {:?}", expr),
};
2022-01-02 16:26:38 +01:00
let rhs_chain = rhs.into();
self.eval_dot_index_chain_helper(
2021-12-27 16:03:30 +01:00
global, state, lib, this_ptr, val_target, root, &x.rhs, *term,
2021-07-24 06:27:33 +02:00
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
2021-07-24 06:27:33 +02:00
Expr::Index(x, term, x_pos) | Expr::Dot(x, term, x_pos) => {
2021-06-13 11:41:34 +02:00
match x.lhs {
2020-07-09 16:21:07 +02:00
// xxx.prop[expr] | xxx.prop.expr
2021-06-13 11:41:34 +02:00
Expr::Property(ref 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();
2022-01-02 16:26:38 +01:00
let rhs_chain = rhs.into();
2021-12-06 13:52:47 +01:00
let hash_get = crate::ast::FnCallHashes::from_native(*hash_get);
let hash_set = crate::ast::FnCallHashes::from_native(*hash_set);
let mut arg_values = [target.as_mut(), &mut Dynamic::UNIT.clone()];
2020-07-09 16:21:07 +02:00
let args = &mut arg_values[..1];
2021-09-27 04:34:24 +02:00
// Assume getters are always pure
let (mut val, _) = self
2021-05-18 14:12:30 +02:00
.exec_fn_call(
2021-12-27 16:03:30 +01:00
global, state, lib, getter, hash_get, args, is_ref_mut,
true, *pos, None, level,
2021-05-18 14:12:30 +02:00
)
.or_else(|err| match *err {
// Try an indexer if property does not exist
2021-12-27 05:27:31 +01:00
ERR::ErrorDotExpr(_, _) => {
2021-05-18 14:12:30 +02:00
let prop = name.into();
self.get_indexed_mut(
2021-12-27 16:03:30 +01:00
global, 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 {
2021-12-27 05:27:31 +01:00
ERR::ErrorIndexingType(_, _) => err,
2021-05-18 14:12:30 +02:00
_ => 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(
2021-12-27 16:03:30 +01:00
global,
state,
lib,
this_ptr,
&mut val.into(),
root,
2020-10-27 16:00:05 +01:00
&x.rhs,
2021-07-24 06:27:33 +02:00
*term,
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
2021-09-27 04:34:24 +02:00
if may_be_changed {
2020-07-09 16:21:07 +02:00
// 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-12-27 16:03:30 +01:00
global, state, lib, setter, hash_set, args, is_ref_mut,
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
2021-12-27 05:27:31 +01:00
ERR::ErrorDotExpr(_, _) => {
2021-06-13 11:41:34 +02:00
let args =
&mut [target.as_mut(), &mut name.into(), val];
2021-12-06 13:52:47 +01:00
let hash_set =
crate::ast::FnCallHashes::from_native(
2021-12-27 16:03:30 +01:00
global.hash_idx_set(),
2021-12-06 13:52:47 +01:00
);
2021-05-18 14:12:30 +02:00
self.exec_fn_call(
2021-12-27 16:03:30 +01:00
global, state, lib, FN_IDX_SET, hash_set, args,
2021-06-17 03:50:32 +02:00
is_ref_mut, true, *pos, None, level,
2021-05-18 14:12:30 +02:00
)
.or_else(|idx_err| match *idx_err {
2021-12-27 05:27:31 +01:00
ERR::ErrorIndexingType(_, _) => {
2021-05-18 14:12:30 +02:00
// 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
},
)?;
#[cfg(not(feature = "unchecked"))]
2022-01-05 06:14:18 +01:00
self.check_data_size(target.as_ref(), root.1)?;
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-06-13 11:41:34 +02:00
Expr::FnCall(ref f, pos) if !f.is_qualified() => {
2021-04-20 16:26:08 +02:00
let FnCallExpr { name, hashes, .. } = f.as_ref();
2022-01-02 16:26:38 +01:00
let rhs_chain = rhs.into();
2021-12-27 10:00:21 +01:00
let args = &mut idx_val.into_fn_call_args();
2020-12-12 04:15:09 +01:00
let (mut val, _) = self.make_method_call(
2021-12-27 16:03:30 +01:00
global, state, lib, name, *hashes, target, 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(
2021-12-27 16:03:30 +01:00
global, state, lib, this_ptr, target, root, &x.rhs, *term,
2021-07-24 06:27:33 +02:00
idx_values, rhs_chain, level, new_val,
)
2021-06-13 11:41:34 +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
2021-06-13 11:41:34 +02:00
ref expr => unreachable!("invalid dot expression: {:?}", expr),
2020-04-26 12:04:07 +02:00
}
}
// Syntax error
2021-12-27 05:27:31 +01:00
_ => Err(ERR::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,
2021-12-27 16:03:30 +01:00
global: &mut GlobalRuntimeState,
2021-07-04 10:40:15 +02:00
state: &mut EvalState,
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 {
2021-07-24 06:27:33 +02:00
let (crate::ast::BinaryExpr { lhs, rhs }, chain_type, term, op_pos) = match expr {
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_index"))]
2021-07-24 06:27:33 +02:00
Expr::Index(x, term, pos) => (x.as_ref(), ChainType::Indexing, *term, *pos),
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
2021-07-24 06:27:33 +02:00
Expr::Dot(x, term, pos) => (x.as_ref(), ChainType::Dotting, *term, *pos),
2021-12-30 05:19:41 +01:00
expr => unreachable!("Expr::Index or Expr::Dot expected but gets {:?}", expr),
2020-05-31 09:51:26 +02:00
};
2021-12-27 10:00:21 +01:00
let idx_values = &mut StaticVec::new_const();
2020-03-25 04:27:18 +01:00
2021-07-24 06:27:33 +02:00
self.eval_dot_index_chain_arguments(
2021-12-27 16:03:30 +01:00
scope, global, state, lib, this_ptr, rhs, term, chain_type, idx_values, 0, level,
)?;
2020-04-11 10:06:57 +02:00
2022-01-05 06:14:18 +01:00
let is_assignment = new_val.is_some();
let result = 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"))]
2021-12-27 16:03:30 +01:00
self.inc_operations(&mut global.num_operations, *var_pos)?;
2020-06-26 04:39:18 +02:00
2021-07-24 08:11:16 +02:00
let (mut target, _) =
2021-12-27 16:03:30 +01:00
self.search_namespace(scope, global, state, lib, this_ptr, lhs)?;
2021-07-24 08:11:16 +02:00
let obj_ptr = &mut target;
let root = (x.2.as_str(), *var_pos);
2021-07-24 06:27:33 +02:00
2020-04-26 12:04:07 +02:00
self.eval_dot_index_chain_helper(
2021-12-27 16:03:30 +01:00
global, state, lib, &mut None, obj_ptr, root, rhs, term, 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}[???] = ???
2022-01-05 06:14:18 +01:00
_ if is_assignment => unreachable!("cannot assign to an expression"),
2020-04-26 12:04:07 +02:00
// {expr}.??? or {expr}[???]
expr => {
2021-12-27 16:03:30 +01:00
let value = self.eval_expr(scope, global, state, lib, this_ptr, expr, level)?;
2021-03-04 03:24:14 +01:00
let obj_ptr = &mut value.into();
let root = ("", expr.position());
2020-04-26 12:04:07 +02:00
self.eval_dot_index_chain_helper(
2021-12-27 16:03:30 +01:00
global, state, lib, this_ptr, obj_ptr, root, rhs, term, idx_values, chain_type,
2021-07-24 06:27:33 +02:00
level, new_val,
2020-04-26 12:04:07 +02:00
)
2022-01-05 06:14:18 +01:00
.map(|(v, _)| if is_assignment { Dynamic::UNIT } else { v })
2020-10-31 16:26:21 +01:00
.map_err(|err| err.fill_position(op_pos))
}
2022-01-05 06:14:18 +01:00
};
if is_assignment {
result.map(|_| Dynamic::UNIT)
} else {
self.check_return_value(result, expr.position())
}
}
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")))]
2021-07-24 06:27:33 +02:00
fn eval_dot_index_chain_arguments(
&self,
scope: &mut Scope,
2021-12-27 16:03:30 +01:00
global: &mut GlobalRuntimeState,
2021-07-04 10:40:15 +02:00
state: &mut EvalState,
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-07-24 06:27:33 +02:00
terminate_chaining: bool,
2021-08-13 07:42:39 +02:00
parent_chain_type: ChainType,
2021-12-27 10:00:21 +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,
2021-12-25 16:49:14 +01:00
) -> RhaiResultOf<()> {
2021-04-25 09:27:58 +02:00
#[cfg(not(feature = "unchecked"))]
2021-12-27 16:03:30 +01:00
self.inc_operations(&mut global.num_operations, expr.position())?;
2020-05-17 16:19:49 +02:00
2021-08-13 07:42:39 +02:00
let _parent_chain_type = parent_chain_type;
2020-04-26 15:48:49 +02:00
match expr {
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
2021-07-24 06:27:33 +02:00
Expr::FnCall(x, _) if _parent_chain_type == ChainType::Dotting && !x.is_qualified() => {
2021-06-08 09:48:55 +02:00
let crate::ast::FnCallExpr {
args, constants, ..
} = x.as_ref();
2021-11-16 06:15:43 +01:00
let (values, pos) = args.iter().try_fold(
2021-12-27 15:28:11 +01:00
(crate::FnArgsVec::with_capacity(args.len()), Position::NONE),
2021-12-25 16:49:14 +01:00
|(mut values, mut pos), expr| -> RhaiResultOf<_> {
2021-11-16 06:15:43 +01:00
let (value, arg_pos) = self.get_arg_value(
2021-12-27 16:03:30 +01:00
scope, global, state, lib, this_ptr, level, expr, constants,
2021-11-16 06:15:43 +01:00
)?;
if values.is_empty() {
pos = arg_pos;
}
values.push(value.flatten());
Ok((values, pos))
},
)?;
2021-12-27 10:00:21 +01:00
idx_values.push(ChainArgument::from_fn_call_args(values, pos));
2020-04-26 12:04:07 +02:00
}
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
2021-07-24 06:27:33 +02:00
Expr::FnCall(_, _) if _parent_chain_type == ChainType::Dotting => {
unreachable!("function call in dot chain should not be namespace-qualified")
}
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
2021-07-24 06:27:33 +02:00
Expr::Property(x) if _parent_chain_type == ChainType::Dotting => {
2021-05-18 14:12:30 +02:00
idx_values.push(ChainArgument::Property((x.2).1))
}
Expr::Property(_) => unreachable!("unexpected Expr::Property for indexing"),
2021-07-24 06:27:33 +02:00
Expr::Index(x, term, _) | Expr::Dot(x, term, _) if !terminate_chaining => {
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
2021-12-27 10:00:21 +01:00
let lhs_arg_val = match lhs {
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
2021-07-24 06:27:33 +02:00
Expr::Property(x) if _parent_chain_type == ChainType::Dotting => {
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-07-24 06:27:33 +02:00
if _parent_chain_type == ChainType::Dotting && !x.is_qualified() =>
{
2021-06-08 09:48:55 +02:00
let crate::ast::FnCallExpr {
args, constants, ..
} = x.as_ref();
2021-12-27 10:00:21 +01:00
let (values, pos) = args.iter().try_fold(
2021-12-27 15:28:11 +01:00
(crate::FnArgsVec::with_capacity(args.len()), Position::NONE),
2021-12-27 10:00:21 +01:00
|(mut values, mut pos), expr| -> RhaiResultOf<_> {
let (value, arg_pos) = self.get_arg_value(
2021-12-27 16:03:30 +01:00
scope, global, state, lib, this_ptr, level, expr, constants,
2021-12-27 10:00:21 +01:00
)?;
if values.is_empty() {
pos = arg_pos
}
values.push(value.flatten());
Ok((values, pos))
},
)?;
ChainArgument::from_fn_call_args(values, pos)
2020-10-31 16:26:21 +01:00
}
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
2021-07-24 06:27:33 +02:00
Expr::FnCall(_, _) if _parent_chain_type == ChainType::Dotting => {
unreachable!("function call in dot chain should not be namespace-qualified")
}
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
2021-07-24 06:27:33 +02:00
expr if _parent_chain_type == ChainType::Dotting => {
2021-04-27 16:28:01 +02:00
unreachable!("invalid dot expression: {:?}", expr);
}
#[cfg(not(feature = "no_index"))]
2021-07-24 06:27:33 +02:00
_ if _parent_chain_type == ChainType::Indexing => self
2021-12-27 16:03:30 +01:00
.eval_expr(scope, global, state, lib, this_ptr, lhs, level)
2021-12-27 10:00:21 +01:00
.map(|v| ChainArgument::from_index_value(v.flatten(), lhs.position()))?,
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
2022-01-02 16:26:38 +01:00
let chain_type = expr.into();
2021-07-24 06:27:33 +02:00
self.eval_dot_index_chain_arguments(
2021-12-27 16:03:30 +01:00
scope, global, state, lib, this_ptr, rhs, *term, chain_type, idx_values, size,
2021-07-24 06:27:33 +02:00
level,
)?;
2020-04-26 12:04:07 +02:00
2021-12-27 10:00:21 +01:00
idx_values.push(lhs_arg_val);
2020-04-26 12:04:07 +02:00
}
2021-04-27 16:28:01 +02:00
#[cfg(not(feature = "no_object"))]
2021-07-24 06:27:33 +02:00
_ if _parent_chain_type == ChainType::Dotting => {
2021-04-27 16:28:01 +02:00
unreachable!("invalid dot expression: {:?}", expr);
}
#[cfg(not(feature = "no_index"))]
2021-07-24 06:27:33 +02:00
_ if _parent_chain_type == ChainType::Indexing => idx_values.push(
2021-12-27 16:03:30 +01:00
self.eval_expr(scope, global, state, lib, this_ptr, expr, level)
2021-12-27 10:00:21 +01:00
.map(|v| ChainArgument::from_index_value(v.flatten(), expr.position()))?,
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.
2021-06-08 17:40:21 +02:00
/// [`Position`] in [`EvalAltResult`] may be [`NONE`][Position::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-12-27 16:03:30 +01:00
global: &mut GlobalRuntimeState,
2021-07-04 10:40:15 +02:00
state: &mut EvalState,
2021-05-18 15:38:09 +02:00
lib: &[&Module],
target: &'t mut Dynamic,
2021-08-13 07:42:39 +02:00
idx: Dynamic,
2020-04-26 12:04:07 +02:00
idx_pos: Position,
2021-08-13 07:42:39 +02:00
add_if_not_found: bool,
use_indexers: bool,
2021-05-18 15:38:09 +02:00
level: usize,
2021-12-25 16:49:14 +01:00
) -> RhaiResultOf<Target<'t>> {
2021-04-25 09:27:58 +02:00
#[cfg(not(feature = "unchecked"))]
2021-12-27 16:03:30 +01:00
self.inc_operations(&mut global.num_operations, Position::NONE)?;
2021-08-13 07:42:39 +02:00
let mut idx = idx;
let _add_if_not_found = add_if_not_found;
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()
2021-06-12 16:47:43 +02:00
.map_err(|typ| self.make_type_mismatch_err::<crate::INT>(typ, 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()
2021-12-27 05:27:31 +01:00
.ok_or_else(|| ERR::ErrorArrayBounds(arr_len, index, idx_pos))
.and_then(|n| {
if n as usize > arr_len {
2021-12-27 05:27:31 +01:00
Err(ERR::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)
2021-12-27 05:27:31 +01:00
.ok_or_else(|| ERR::ErrorArrayBounds(arr_len, index, idx_pos).into())
}
2020-03-29 17:53:35 +02:00
2021-11-23 07:58:54 +01:00
#[cfg(not(feature = "no_index"))]
Dynamic(Union::Blob(arr, _, _)) => {
// val_blob[idx]
let index = idx
.as_int()
.map_err(|typ| self.make_type_mismatch_err::<crate::INT>(typ, idx_pos))?;
let arr_len = arr.len();
#[cfg(not(feature = "unchecked"))]
let arr_idx = if index < 0 {
// Count from end if negative
arr_len
- index
.checked_abs()
2021-12-27 05:27:31 +01:00
.ok_or_else(|| ERR::ErrorArrayBounds(arr_len, index, idx_pos))
2021-11-23 07:58:54 +01:00
.and_then(|n| {
if n as usize > arr_len {
2021-12-27 05:27:31 +01:00
Err(ERR::ErrorArrayBounds(arr_len, index, idx_pos).into())
2021-11-23 07:58:54 +01:00
} else {
Ok(n as usize)
}
})?
} else {
index as usize
};
#[cfg(feature = "unchecked")]
let arr_idx = if index < 0 {
// Count from end if negative
arr_len - index.abs() as usize
} else {
index as usize
};
2021-12-02 06:09:59 +01:00
let value = arr
.get(arr_idx)
.map(|&v| (v as INT).into())
2021-12-27 05:27:31 +01:00
.ok_or_else(|| Box::new(ERR::ErrorArrayBounds(arr_len, index, idx_pos)))?;
2022-01-02 16:26:38 +01:00
Ok(Target::BlobByte {
source: target,
value,
index: arr_idx,
})
2021-11-23 07:58:54 +01:00
}
#[cfg(not(feature = "no_object"))]
2021-05-02 17:57:35 +02:00
Dynamic(Union::Map(map, _, _)) => {
// val_map[idx]
2021-07-04 10:40:15 +02:00
let index = idx.read_lock::<ImmutableString>().ok_or_else(|| {
2021-05-18 15:38:09 +02:00
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-08-13 07:42:39 +02:00
if _add_if_not_found && !map.contains_key(index.as_str()) {
map.insert(index.clone().into(), Dynamic::UNIT);
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
2021-12-15 05:06:17 +01:00
#[cfg(not(feature = "no_index"))]
Dynamic(Union::Int(value, _, _))
2021-12-15 05:46:25 +01:00
if idx.is::<crate::ExclusiveRange>() || idx.is::<crate::InclusiveRange>() =>
2021-12-15 05:06:17 +01:00
{
#[cfg(not(feature = "only_i32"))]
type BASE = u64;
#[cfg(feature = "only_i32")]
type BASE = u32;
// val_int[range]
const BITS: usize = std::mem::size_of::<INT>() * 8;
2021-12-15 05:46:25 +01:00
let (shift, mask) = if let Some(range) = idx.read_lock::<crate::ExclusiveRange>() {
2021-12-15 05:06:17 +01:00
let start = range.start;
let end = range.end;
if start < 0 || start as usize >= BITS {
2021-12-27 05:27:31 +01:00
return Err(ERR::ErrorBitFieldBounds(BITS, start, idx_pos).into());
2021-12-15 05:06:17 +01:00
} else if end < 0 || end as usize >= BITS {
2021-12-27 05:27:31 +01:00
return Err(ERR::ErrorBitFieldBounds(BITS, end, idx_pos).into());
2021-12-15 05:06:17 +01:00
} else if end <= start {
(0, 0)
} else if end as usize == BITS && start == 0 {
// -1 = all bits set
(0, -1)
} else {
(
start as u8,
// 2^bits - 1
(((2 as BASE).pow((end - start) as u32) - 1) as INT) << start,
)
}
2021-12-15 05:46:25 +01:00
} else if let Some(range) = idx.read_lock::<crate::InclusiveRange>() {
2021-12-15 05:06:17 +01:00
let start = *range.start();
let end = *range.end();
if start < 0 || start as usize >= BITS {
2021-12-27 05:27:31 +01:00
return Err(ERR::ErrorBitFieldBounds(BITS, start, idx_pos).into());
2021-12-15 05:06:17 +01:00
} else if end < 0 || end as usize >= BITS {
2021-12-27 05:27:31 +01:00
return Err(ERR::ErrorBitFieldBounds(BITS, end, idx_pos).into());
2021-12-15 05:06:17 +01:00
} else if end < start {
(0, 0)
} else if end as usize == BITS - 1 && start == 0 {
// -1 = all bits set
(0, -1)
} else {
(
start as u8,
// 2^bits - 1
(((2 as BASE).pow((end - start + 1) as u32) - 1) as INT) << start,
)
}
} else {
2021-12-30 05:19:41 +01:00
unreachable!("Range or RangeInclusive expected but gets {:?}", idx);
2021-12-15 05:06:17 +01:00
};
let field_value = (*value & mask) >> shift;
2022-01-02 16:26:38 +01:00
Ok(Target::BitField {
source: target,
value: field_value.into(),
mask,
shift,
})
2021-12-15 05:06:17 +01:00
}
2021-06-02 08:29:18 +02:00
#[cfg(not(feature = "no_index"))]
Dynamic(Union::Int(value, _, _)) => {
// val_int[idx]
let index = idx
.as_int()
2021-06-12 16:47:43 +02:00
.map_err(|typ| self.make_type_mismatch_err::<crate::INT>(typ, idx_pos))?;
2021-06-02 08:29:18 +02:00
2021-12-15 05:06:17 +01:00
const BITS: usize = std::mem::size_of::<INT>() * 8;
2021-06-02 08:29:18 +02:00
let (bit_value, offset) = if index >= 0 {
let offset = index as usize;
(
2021-12-15 05:06:17 +01:00
if offset >= BITS {
2021-12-27 05:27:31 +01:00
return Err(ERR::ErrorBitFieldBounds(BITS, index, idx_pos).into());
2021-06-02 08:29:18 +02:00
} else {
(*value & (1 << offset)) != 0
},
2021-12-15 05:06:17 +01:00
offset as u8,
2021-06-02 08:29:18 +02:00
)
} else if let Some(abs_index) = index.checked_abs() {
let offset = abs_index as usize;
(
// Count from end if negative
2021-12-15 05:06:17 +01:00
if offset > BITS {
2021-12-27 05:27:31 +01:00
return Err(ERR::ErrorBitFieldBounds(BITS, index, idx_pos).into());
2021-06-02 08:29:18 +02:00
} else {
2021-12-15 05:06:17 +01:00
(*value & (1 << (BITS - offset))) != 0
2021-06-02 08:29:18 +02:00
},
2021-12-15 05:06:17 +01:00
offset as u8,
2021-06-02 08:29:18 +02:00
)
} else {
2021-12-27 05:27:31 +01:00
return Err(ERR::ErrorBitFieldBounds(BITS, index, idx_pos).into());
2021-06-02 08:29:18 +02:00
};
2022-01-02 16:26:38 +01:00
Ok(Target::Bit {
source: target,
value: bit_value.into(),
bit: offset,
})
2021-06-02 08:29:18 +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()
2021-06-12 16:47:43 +02:00
.map_err(|typ| self.make_type_mismatch_err::<crate::INT>(typ, idx_pos))?;
let (ch, offset) = if index >= 0 {
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();
2021-12-27 05:27:31 +01:00
ERR::ErrorStringBounds(chars_len, index, idx_pos)
})?,
offset,
)
2021-06-02 08:29:18 +02:00
} else if let Some(abs_index) = index.checked_abs() {
let offset = abs_index as usize;
(
2021-06-02 08:29:18 +02:00
// Count from end if negative
s.chars().rev().nth(offset - 1).ok_or_else(|| {
2021-04-25 09:27:58 +02:00
let chars_len = s.chars().count();
2021-12-27 05:27:31 +01:00
ERR::ErrorStringBounds(chars_len, index, idx_pos)
})?,
offset,
)
} else {
2021-04-25 09:27:58 +02:00
let chars_len = s.chars().count();
2021-12-27 05:27:31 +01:00
return Err(ERR::ErrorStringBounds(chars_len, index, idx_pos).into());
};
2022-01-02 16:26:38 +01:00
Ok(Target::StringChar {
source: target,
value: ch.into(),
index: offset,
})
}
2020-03-29 17:53:35 +02:00
2021-08-13 07:42:39 +02:00
_ if use_indexers => {
2021-05-18 15:38:09 +02:00
let args = &mut [target, &mut idx];
2021-12-27 16:03:30 +01:00
let hash_get = crate::ast::FnCallHashes::from_native(global.hash_idx_get());
let idx_pos = Position::NONE;
2021-04-24 08:47:20 +02:00
2021-04-25 09:27:58 +02:00
self.exec_fn_call(
2021-12-27 16:03:30 +01:00
global, 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
2021-12-27 05:27:31 +01:00
_ => Err(ERR::ErrorIndexingType(
format!(
"{} [{}]",
self.map_type_name(target.type_name()),
self.map_type_name(idx.type_name())
),
2021-04-25 09:27:58 +02:00
Position::NONE,
)
.into()),
2020-03-04 15:00:01 +01:00
}
}
2022-01-06 05:31:46 +01:00
/// Evaluate a function call expression.
fn eval_fn_call_expr(
&self,
scope: &mut Scope,
global: &mut GlobalRuntimeState,
state: &mut EvalState,
lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>,
expr: &FnCallExpr,
pos: Position,
level: usize,
) -> RhaiResult {
let FnCallExpr {
name,
namespace,
capture_parent_scope: capture,
hashes,
args,
constants,
..
} = expr;
let result = if let Some(namespace) = namespace.as_ref() {
// Qualified function call
let hash = hashes.native;
self.make_qualified_function_call(
scope, global, state, lib, this_ptr, namespace, name, args, constants, hash, pos,
level,
)
} else {
// Normal function call
self.make_function_call(
scope, global, state, lib, this_ptr, name, args, constants, *hashes, pos, *capture,
level,
)
};
self.check_return_value(result, pos)
2022-01-05 06:14:18 +01:00
}
2022-01-06 05:31:46 +01:00
/// Evaluate an expression.
pub(crate) fn eval_expr(
&self,
2020-03-27 07:34:01 +01:00
scope: &mut Scope,
2021-12-27 16:03:30 +01:00
global: &mut GlobalRuntimeState,
2021-07-04 10:40:15 +02:00
state: &mut EvalState,
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 {
// Coded this way for better branch prediction.
// Popular branches are lifted out of the `match` statement into their own branches.
// Function calls should account for a relatively larger portion of expressions because
// binary operators are also function calls.
if let Expr::FnCall(x, pos) = expr {
#[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut global.num_operations, expr.position())?;
return self.eval_fn_call_expr(scope, global, state, lib, this_ptr, x, *pos, level);
}
// Then variable access.
// We shouldn't do this for too many variants because, soon or later, the added comparisons
// will cost more than the mis-predicted `match` branch.
if let Expr::Variable(index, var_pos, x) = expr {
#[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut global.num_operations, expr.position())?;
return if index.is_none() && x.0.is_none() && x.2 == KEYWORD_THIS {
this_ptr
.as_deref()
.cloned()
.ok_or_else(|| ERR::ErrorUnboundThis(*var_pos).into())
} else {
self.search_namespace(scope, global, state, lib, this_ptr, expr)
.map(|(val, _)| val.take_or_clone())
};
}
2022-01-06 05:31:46 +01:00
#[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut global.num_operations, expr.position())?;
2022-01-05 06:14:18 +01:00
match expr {
2022-01-06 05:31:46 +01:00
// Constants
Expr::DynamicConstant(x, _) => Ok(x.as_ref().clone()),
Expr::IntegerConstant(x, _) => Ok((*x).into()),
#[cfg(not(feature = "no_float"))]
Expr::FloatConstant(x, _) => Ok((*x).into()),
Expr::StringConstant(x, _) => Ok(x.clone().into()),
Expr::CharConstant(x, _) => Ok((*x).into()),
Expr::BoolConstant(x, _) => Ok((*x).into()),
Expr::Unit(_) => Ok(Dynamic::UNIT),
2021-04-04 07:13:07 +02:00
// `... ${...} ...`
2021-06-29 12:41:03 +02:00
Expr::InterpolatedString(x, pos) => {
let mut pos = *pos;
2021-09-26 15:30:33 +02:00
let mut result: Dynamic = self.const_empty_string().into();
2021-04-04 07:13:07 +02:00
2022-01-05 06:14:18 +01:00
for expr in x.iter() {
2021-12-27 16:03:30 +01:00
let item = self.eval_expr(scope, global, state, lib, this_ptr, expr, level)?;
2021-06-11 13:59:50 +02:00
2021-04-04 07:13:07 +02:00
self.eval_op_assignment(
2021-12-27 16:03:30 +01:00
global,
2021-04-04 07:13:07 +02:00
state,
lib,
2021-12-17 09:55:24 +01:00
Some(OpAssignment::new(OP_CONCAT)),
2021-04-04 07:13:07 +02:00
pos,
2021-06-11 13:59:50 +02:00
&mut (&mut result).into(),
("", Position::NONE),
2021-04-04 07:13:07 +02:00
item,
2021-06-08 17:40:21 +02:00
)
.map_err(|err| err.fill_position(expr.position()))?;
2021-06-11 13:59:50 +02:00
2021-04-04 07:13:07 +02:00
pos = expr.position();
2021-06-11 13:59:50 +02:00
2022-01-06 06:40:03 +01:00
result = self.check_return_value(Ok(result), pos)?;
2022-01-05 06:14:18 +01:00
}
2021-04-04 07:13:07 +02:00
2022-01-06 06:40:03 +01:00
Ok(result)
2021-04-04 07:13:07 +02:00
}
2020-10-27 16:21:20 +01:00
#[cfg(not(feature = "no_index"))]
2022-01-05 06:14:18 +01:00
Expr::Array(x, _) => {
let mut arr = Dynamic::from_array(crate::Array::with_capacity(x.len()));
2020-10-27 16:21:20 +01:00
2022-01-06 06:40:03 +01:00
#[cfg(not(feature = "unchecked"))]
let mut sizes = (0, 0, 0);
2022-01-05 06:14:18 +01:00
for item_expr in x.iter() {
2022-01-06 06:40:03 +01:00
let value = self
.eval_expr(scope, global, state, lib, this_ptr, item_expr, level)?
.flatten();
2022-01-05 06:14:18 +01:00
2022-01-06 06:40:03 +01:00
#[cfg(not(feature = "unchecked"))]
let val_sizes = Self::calc_data_sizes(&value, true);
arr.write_lock::<crate::Array>()
.expect("`Array`")
.push(value);
#[cfg(not(feature = "unchecked"))]
if self.has_data_size_limit() {
sizes = (
sizes.0 + val_sizes.0,
sizes.1 + val_sizes.1,
sizes.2 + val_sizes.2,
);
self.raise_err_if_over_data_size_limit(sizes, item_expr.position())?;
}
2022-01-05 06:14:18 +01:00
}
Ok(arr)
2020-10-27 16:21:20 +01:00
}
2022-01-05 06:14:18 +01:00
#[cfg(not(feature = "no_object"))]
Expr::Map(x, _) => {
let mut map = Dynamic::from_map(x.1.clone());
2022-01-06 06:40:03 +01:00
#[cfg(not(feature = "unchecked"))]
let mut sizes = (0, 0, 0);
2022-01-05 06:14:18 +01:00
for (Ident { name, .. }, value_expr) in x.0.iter() {
2022-01-06 04:07:52 +01:00
let key = name.as_str();
let value = self
2022-01-05 06:14:18 +01:00
.eval_expr(scope, global, state, lib, this_ptr, value_expr, level)?
.flatten();
2022-01-06 06:40:03 +01:00
#[cfg(not(feature = "unchecked"))]
let val_sizes = Self::calc_data_sizes(&value, true);
2022-01-06 04:07:52 +01:00
*map.write_lock::<crate::Map>()
.expect("`Map`")
.get_mut(key)
.unwrap() = value;
2022-01-06 06:40:03 +01:00
#[cfg(not(feature = "unchecked"))]
if self.has_data_size_limit() {
sizes = (
sizes.0 + val_sizes.0,
sizes.1 + val_sizes.1,
sizes.2 + val_sizes.2,
);
self.raise_err_if_over_data_size_limit(sizes, value_expr.position())?;
}
2022-01-05 06:14:18 +01:00
}
Ok(map)
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
2021-12-27 16:03:30 +01:00
.eval_expr(scope, global, state, lib, this_ptr, &x.lhs, level)?
2020-10-27 16:21:20 +01:00
.as_bool()
2021-06-12 16:47:43 +02:00
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, x.lhs.position()))?
2020-10-27 16:21:20 +01:00
&& // Short-circuit using &&
self
2021-12-27 16:03:30 +01:00
.eval_expr(scope, global, state, lib, this_ptr, &x.rhs, level)?
2020-10-27 16:21:20 +01:00
.as_bool()
2021-06-12 16:47:43 +02:00
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, x.rhs.position()))?)
2020-10-27 16:21:20 +01:00
.into())
}
2020-10-31 16:26:21 +01:00
Expr::Or(x, _) => {
2020-10-27 16:21:20 +01:00
Ok((self
2021-12-27 16:03:30 +01:00
.eval_expr(scope, global, state, lib, this_ptr, &x.lhs, level)?
2020-10-27 16:21:20 +01:00
.as_bool()
2021-06-12 16:47:43 +02:00
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, x.lhs.position()))?
2020-10-27 16:21:20 +01:00
|| // Short-circuit using ||
self
2021-12-27 16:03:30 +01:00
.eval_expr(scope, global, state, lib, this_ptr, &x.rhs, level)?
2020-10-27 16:21:20 +01:00
.as_bool()
2021-06-12 16:47:43 +02:00
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, x.rhs.position()))?)
2020-10-27 16:21:20 +01:00
.into())
}
2020-10-31 16:26:21 +01:00
Expr::Custom(custom, _) => {
2021-10-25 16:41:42 +02:00
let expressions: StaticVec<_> = custom.inputs.iter().map(Into::into).collect();
2022-01-06 04:07:52 +01:00
let key_token = custom.tokens.first().unwrap();
let custom_def = self.custom_syntax.get(key_token).unwrap();
2020-10-27 16:21:20 +01:00
let mut context = EvalContext {
engine: self,
scope,
2021-12-27 16:03:30 +01:00
global,
2020-10-27 16:21:20 +01:00
state,
lib,
this_ptr,
level,
};
2022-01-05 06:14:18 +01:00
let result = (custom_def.func)(&mut context, &expressions);
self.check_return_value(result, expr.position())
2020-10-27 16:21:20 +01:00
}
2022-01-05 06:14:18 +01:00
Expr::Stmt(x) if x.is_empty() => Ok(Dynamic::UNIT),
Expr::Stmt(x) => {
self.eval_stmt_block(scope, global, state, lib, this_ptr, x, true, level)
}
#[cfg(not(feature = "no_index"))]
Expr::Index(_, _, _) => {
self.eval_dot_index_chain(scope, global, state, lib, this_ptr, expr, level, None)
}
#[cfg(not(feature = "no_object"))]
Expr::Dot(_, _, _) => {
self.eval_dot_index_chain(scope, global, state, lib, this_ptr, expr, level, None)
}
_ => unreachable!("expression cannot be evaluated: {:?}", expr),
}
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,
2021-12-27 16:03:30 +01:00
global: &mut GlobalRuntimeState,
2021-07-04 10:40:15 +02:00
state: &mut EvalState,
2020-11-04 04:49:02 +01:00
lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>,
statements: &[Stmt],
2021-11-27 07:24:36 +01:00
restore_orig_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-12-28 05:19:20 +01:00
let orig_always_search_scope = state.always_search_scope;
2021-11-27 07:24:36 +01:00
let orig_scope_len = scope.len();
2021-12-27 16:03:30 +01:00
let orig_mods_len = global.num_imported_modules();
2021-11-27 07:24:36 +01:00
let orig_fn_resolution_caches_len = state.fn_resolution_caches_len();
2021-12-28 10:50:49 +01:00
if restore_orig_state {
2021-12-28 05:19:20 +01:00
state.scope_level += 1;
}
2022-01-05 06:14:18 +01:00
let mut result = Dynamic::UNIT;
for stmt in statements {
2021-12-27 16:03:30 +01:00
let _mods_len = global.num_imported_modules();
2022-01-05 06:14:18 +01:00
result = self.eval_stmt(
2021-12-30 01:57:23 +01:00
scope,
global,
state,
lib,
this_ptr,
stmt,
restore_orig_state,
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.
2021-12-27 16:03:30 +01:00
if global
.scan_modules_raw()
.skip(_mods_len)
.any(|(_, m)| m.contains_indexed_global_functions())
{
2021-11-27 07:24:36 +01:00
if state.fn_resolution_caches_len() > orig_fn_resolution_caches_len {
// 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();
2021-11-27 07:24:36 +01:00
} else if restore_orig_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
} else {
// When the block is to be evaluated in-place, just clear the current cache
state.fn_resolution_cache_mut().clear();
}
}
}
2022-01-05 06:14:18 +01:00
}
2020-11-04 04:49:02 +01:00
2021-11-27 07:24:36 +01:00
// If imports list is modified, pop the functions lookup cache
state.rewind_fn_resolution_caches(orig_fn_resolution_caches_len);
2021-03-07 15:10:54 +01:00
2021-12-28 10:50:49 +01:00
if restore_orig_state {
2021-11-27 07:24:36 +01:00
scope.rewind(orig_scope_len);
2021-12-28 05:19:20 +01:00
state.scope_level -= 1;
2021-12-27 16:03:30 +01:00
global.truncate_modules(orig_mods_len);
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
2021-12-28 05:19:20 +01:00
state.always_search_scope = orig_always_search_scope;
}
2020-11-04 04:49:02 +01:00
2022-01-05 06:14:18 +01:00
Ok(result)
2020-11-04 04:49:02 +01:00
}
2021-06-08 17:40:21 +02:00
/// Evaluate an op-assignment statement.
/// [`Position`] in [`EvalAltResult`] is [`NONE`][Position::NONE] and should be set afterwards.
2021-02-24 04:04:54 +01:00
pub(crate) fn eval_op_assignment(
&self,
2021-12-27 16:03:30 +01:00
global: &mut GlobalRuntimeState,
2021-07-04 10:40:15 +02:00
state: &mut EvalState,
2021-02-24 04:04:54 +01:00
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,
2021-06-11 13:59:50 +02:00
target: &mut Target,
root: (&str, Position),
2021-08-13 07:42:39 +02:00
new_val: Dynamic,
2021-12-25 16:49:14 +01:00
) -> RhaiResultOf<()> {
2021-04-17 07:36:51 +02:00
if target.is_read_only() {
// Assignment to constant variable
2021-12-27 05:27:31 +01:00
return Err(ERR::ErrorAssignmentToConstant(root.0.to_string(), root.1).into());
2021-02-24 04:04:54 +01:00
}
2021-08-13 07:42:39 +02:00
let mut new_val = new_val;
2021-03-08 08:30:32 +01:00
if let Some(OpAssignment {
hash_op_assign,
hash_op,
op,
}) = op_info
{
2021-06-02 08:29:18 +02: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-11-13 05:23:35 +01:00
lock_guard = target.write_lock::<Dynamic>().expect("`Dynamic`");
2021-06-02 08:29:18 +02:00
lhs_ptr_inner = &mut *lock_guard;
} else {
lhs_ptr_inner = &mut *target;
}
2021-02-24 04:04:54 +01:00
2021-06-02 08:29:18 +02:00
let hash = hash_op_assign;
let args = &mut [lhs_ptr_inner, &mut new_val];
2021-02-24 04:04:54 +01:00
2021-12-27 16:03:30 +01:00
match self.call_native_fn(global, state, lib, op, hash, args, true, true, op_pos) {
2021-12-27 05:27:31 +01:00
Err(err) if matches!(*err, ERR::ErrorFunctionNotFound(ref f, _) if f.starts_with(op)) =>
2021-06-02 08:29:18 +02:00
{
// Expand to `var = var op rhs`
let op = &op[..op.len() - 1]; // extract operator without =
2021-02-24 04:04:54 +01:00
2021-06-02 08:29:18 +02:00
// Run function
let (value, _) = self.call_native_fn(
2021-12-27 16:03:30 +01:00
global, state, lib, op, hash_op, args, true, false, op_pos,
2021-06-02 08:29:18 +02:00
)?;
2021-02-24 04:04:54 +01:00
2021-06-02 08:29:18 +02:00
*args[0] = value.flatten();
}
err => return err.map(|_| ()),
2021-02-24 04:04:54 +01:00
}
}
2021-03-08 08:30:32 +01:00
} else {
// Normal assignment
2021-06-08 17:40:21 +02:00
*target.as_mut() = new_val;
2021-02-24 04:04:54 +01:00
}
2021-06-02 08:29:18 +02:00
2021-06-08 17:40:21 +02:00
target.propagate_changed_value()
2021-02-24 04:04:54 +01:00
}
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,
2021-12-27 16:03:30 +01:00
global: &mut GlobalRuntimeState,
2021-07-04 10:40:15 +02:00
state: &mut EvalState,
2020-10-27 16:21:20 +01:00
lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>,
stmt: &Stmt,
2021-12-30 01:57:23 +01:00
rewind_scope: bool,
2020-10-27 16:21:20 +01:00
level: usize,
2021-03-02 08:02:28 +01:00
) -> RhaiResult {
2021-04-25 09:27:58 +02:00
#[cfg(not(feature = "unchecked"))]
2021-12-27 16:03:30 +01:00
self.inc_operations(&mut global.num_operations, 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
2021-12-27 16:03:30 +01:00
.eval_expr(scope, global, state, lib, this_ptr, expr, level)?
2021-03-04 03:24:14 +01:00
.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
2021-12-27 16:03:30 +01:00
.eval_expr(scope, global, state, lib, this_ptr, rhs_expr, level)?
2020-10-11 15:58:11 +02:00
.flatten();
2021-06-11 13:59:50 +02:00
let (mut lhs_ptr, pos) =
2021-12-27 16:03:30 +01:00
self.search_namespace(scope, global, state, lib, this_ptr, lhs_expr)?;
2020-10-11 15:58:11 +02:00
2022-01-06 04:07:52 +01:00
let var_name = lhs_expr.get_variable_name(false).expect("`Expr::Variable`");
2021-05-22 13:14:24 +02:00
2020-10-11 15:58:11 +02:00
if !lhs_ptr.is_ref() {
2021-12-27 05:27:31 +01:00
return Err(ERR::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"))]
2021-12-27 16:03:30 +01:00
self.inc_operations(&mut global.num_operations, pos)?;
self.eval_op_assignment(
2021-12-27 16:03:30 +01:00
global,
state,
lib,
*op_info,
*op_pos,
2021-06-11 13:59:50 +02:00
&mut lhs_ptr,
2021-05-22 13:14:24 +02:00
(var_name, pos),
rhs_val,
2021-06-08 17:40:21 +02:00
)
.map_err(|err| err.fill_position(rhs_expr.position()))?;
#[cfg(not(feature = "unchecked"))]
if op_info.is_some() {
2022-01-05 06:14:18 +01:00
self.check_data_size(lhs_ptr.as_ref(), lhs_expr.position())?;
}
2021-06-11 13:59:50 +02:00
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
2021-12-27 16:03:30 +01:00
.eval_expr(scope, global, state, lib, this_ptr, rhs_expr, level)?
2021-03-04 03:24:14 +01:00
.flatten();
2021-07-24 08:11:16 +02:00
let _new_val = Some(((rhs_val, rhs_expr.position()), (*op_info, *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(_, _, _) => {
2021-12-30 05:19:41 +01:00
unreachable!("Expr::Variable case is already handled")
}
// idx_lhs[idx_expr] op= rhs
#[cfg(not(feature = "no_index"))]
2021-07-24 06:27:33 +02:00
Expr::Index(_, _, _) => {
self.eval_dot_index_chain(
2021-12-27 16:03:30 +01:00
scope, global, 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"))]
2021-07-24 06:27:33 +02:00
Expr::Dot(_, _, _) => {
self.eval_dot_index_chain(
2021-12-27 16:03:30 +01:00
scope, global, 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),
2021-12-28 10:50:49 +01:00
Stmt::Block(statements, _) => {
self.eval_stmt_block(scope, global, state, lib, this_ptr, statements, true, level)
}
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
2021-12-27 16:03:30 +01:00
.eval_expr(scope, global, state, lib, this_ptr, expr, level)?
2021-04-21 11:39:45 +02:00
.as_bool()
2021-06-12 16:47:43 +02:00
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, expr.position()))?;
2021-04-21 11:39:45 +02:00
if guard_val {
if !x.0.is_empty() {
2021-12-28 10:50:49 +01:00
self.eval_stmt_block(scope, global, 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() {
2021-12-28 10:50:49 +01:00
self.eval_stmt_block(scope, global, state, lib, this_ptr, &x.1, true, level)
2021-04-21 11:39:45 +02:00
} 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, _) => {
2021-12-15 05:06:17 +01:00
let (table, def_stmt, ranges) = x.as_ref();
2020-11-14 16:43:36 +01:00
2021-12-27 16:03:30 +01:00
let value =
self.eval_expr(scope, global, state, lib, this_ptr, match_expr, level)?;
2021-03-05 03:33:48 +01:00
2021-12-15 05:06:17 +01:00
let stmt_block = if value.is_hashable() {
2021-03-05 03:33:48 +01:00
let hasher = &mut get_hasher();
value.hash(hasher);
let hash = hasher.finish();
2021-12-15 05:06:17 +01:00
// First check hashes
if let Some(t) = table.get(&hash) {
if let Some(ref c) = t.0 {
if self
2021-12-27 16:03:30 +01:00
.eval_expr(scope, global, state, lib, this_ptr, &c, level)
2021-04-16 06:04:33 +02:00
.and_then(|v| {
2021-06-12 16:47:43 +02:00
v.as_bool().map_err(|typ| {
2021-12-15 05:06:17 +01:00
self.make_type_mismatch_err::<bool>(typ, c.position())
2021-04-16 06:04:33 +02:00
})
2021-12-15 05:06:17 +01:00
})?
{
Some(&t.1)
} else {
None
2021-04-16 06:04:33 +02:00
}
2021-12-15 05:06:17 +01:00
} else {
Some(&t.1)
2021-04-16 06:04:33 +02:00
}
2021-12-15 05:06:17 +01:00
} else if value.is::<INT>() && !ranges.is_empty() {
// Then check integer ranges
let value = value.as_int().expect("`INT`");
let mut result = None;
for (_, _, _, condition, stmt_block) in
ranges.iter().filter(|&&(start, end, inclusive, _, _)| {
(!inclusive && (start..end).contains(&value))
|| (inclusive && (start..=end).contains(&value))
})
{
if let Some(c) = condition {
if !self
2021-12-27 16:03:30 +01:00
.eval_expr(scope, global, state, lib, this_ptr, &c, level)
2021-12-15 05:06:17 +01:00
.and_then(|v| {
v.as_bool().map_err(|typ| {
self.make_type_mismatch_err::<bool>(typ, c.position())
})
})?
{
continue;
}
}
2021-03-30 17:55:29 +02:00
2021-12-15 05:06:17 +01:00
result = Some(stmt_block);
break;
}
2021-04-16 06:04:33 +02:00
2021-12-15 05:06:17 +01:00
result
} else {
// Nothing matches
None
}
2020-11-14 16:43:36 +01:00
} else {
2021-12-15 05:06:17 +01:00
// Non-hashable
2021-03-05 03:33:48 +01:00
None
2021-12-15 05:06:17 +01:00
};
if let Some(statements) = stmt_block {
if !statements.is_empty() {
self.eval_stmt_block(
2021-12-28 10:50:49 +01:00
scope, global, state, lib, this_ptr, statements, true, level,
2021-12-15 05:06:17 +01:00
)
} else {
Ok(Dynamic::UNIT)
}
} else {
2021-03-05 03:33:48 +01:00
// Default match clause
2021-03-10 15:12:48 +01:00
if !def_stmt.is_empty() {
self.eval_stmt_block(
2021-12-28 10:50:49 +01:00
scope, global, state, lib, this_ptr, def_stmt, true, level,
2021-03-10 15:12:48 +01:00
)
} else {
Ok(Dynamic::UNIT)
}
2021-12-15 05:06:17 +01:00
}
2020-11-14 16:43:36 +01:00
}
2021-08-04 11:40:26 +02:00
// Loop
Stmt::While(Expr::Unit(_), body, _) => loop {
if !body.is_empty() {
2021-12-28 10:50:49 +01:00
match self
.eval_stmt_block(scope, global, state, lib, this_ptr, body, true, level)
{
2021-08-04 11:40:26 +02:00
Ok(_) => (),
Err(err) => match *err {
2021-12-27 05:27:31 +01:00
ERR::LoopBreak(false, _) => (),
ERR::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
2021-08-04 11:40:26 +02:00
_ => return Err(err),
},
}
} else {
#[cfg(not(feature = "unchecked"))]
2021-12-27 16:03:30 +01:00
self.inc_operations(&mut global.num_operations, body.position())?;
2021-08-04 11:40:26 +02:00
}
},
2020-03-06 16:49:52 +01:00
// While loop
2021-04-16 07:15:11 +02:00
Stmt::While(expr, body, _) => loop {
2021-08-04 11:40:26 +02:00
let condition = self
2021-12-27 16:03:30 +01:00
.eval_expr(scope, global, state, lib, this_ptr, expr, level)?
2021-08-04 11:40:26 +02:00
.as_bool()
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, expr.position()))?;
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() {
2021-12-28 10:50:49 +01:00
match self
.eval_stmt_block(scope, global, state, lib, this_ptr, body, true, level)
{
2021-04-21 11:39:45 +02:00
Ok(_) => (),
Err(err) => match *err {
2021-12-27 05:27:31 +01:00
ERR::LoopBreak(false, _) => (),
ERR::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
2021-04-21 11:39:45 +02:00
_ => 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, options, _) => loop {
let is_while = !options.contains(AST_OPTION_NEGATED);
2021-04-16 07:15:11 +02:00
if !body.is_empty() {
2021-12-28 10:50:49 +01:00
match self
.eval_stmt_block(scope, global, state, lib, this_ptr, body, true, level)
{
Ok(_) => (),
Err(err) => match *err {
2021-12-27 05:27:31 +01:00
ERR::LoopBreak(false, _) => continue,
ERR::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-12-27 16:03:30 +01:00
.eval_expr(scope, global, state, lib, this_ptr, expr, level)?
2021-04-16 07:15:11 +02:00
.as_bool()
2021-06-12 16:47:43 +02:00
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, expr.position()))?;
2021-04-21 11:39:45 +02:00
if condition ^ is_while {
2021-04-21 11:39:45 +02:00
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-06-07 05:01:16 +02:00
let (Ident { name, .. }, counter, statements) = x.as_ref();
2021-03-04 03:24:14 +01:00
let iter_obj = self
2021-12-27 16:03:30 +01:00
.eval_expr(scope, global, state, lib, this_ptr, expr, level)?
2021-03-04 03:24:14 +01:00
.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
.global_modules
.iter()
.find_map(|m| m.get_iter(iter_type))
2021-12-27 16:03:30 +01:00
.or_else(|| global.get_iter(iter_type))
2021-03-01 07:54:20 +01:00
.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 {
2021-06-07 05:01:16 +02:00
// Add the loop variables
let orig_scope_len = scope.len();
2021-12-31 08:59:13 +01:00
let counter_index = if let Some(counter) = counter {
scope.push(unsafe_cast_var_name_to_lifetime(&counter.name), 0 as INT);
2021-10-18 09:09:07 +02:00
scope.len() - 1
2021-12-31 08:59:13 +01:00
} else {
usize::MAX
};
2021-06-07 05:01:16 +02:00
scope.push(unsafe_cast_var_name_to_lifetime(name), ());
2020-04-27 16:49:09 +02:00
let index = scope.len() - 1;
2020-03-01 17:11:00 +01:00
2021-06-07 05:01:16 +02:00
for (x, iter_value) in func(iter_obj).enumerate() {
// Increment counter
2021-12-31 08:59:13 +01:00
if counter_index < usize::MAX {
2021-06-07 05:01:16 +02:00
#[cfg(not(feature = "unchecked"))]
if x > INT::MAX as usize {
2021-12-27 05:27:31 +01:00
return Err(ERR::ErrorArithmetic(
2021-06-07 05:01:16 +02:00
format!("for-loop counter overflow: {}", x),
2021-11-13 05:23:35 +01:00
counter.as_ref().expect("`Some`").pos,
2021-06-07 05:01:16 +02:00
)
.into());
2021-06-07 05:01:16 +02:00
}
2021-12-31 08:59:13 +01:00
let index_value = (x as INT).into();
#[cfg(not(feature = "no_closure"))]
{
let index_var = scope.get_mut_by_index(counter_index);
if index_var.is_shared() {
*index_var.write_lock().expect("`Dynamic`") = index_value;
} else {
*index_var = index_value;
}
}
#[cfg(feature = "no_closure")]
{
*scope.get_mut_by_index(counter_index) = index_value;
}
2021-06-07 05:01:16 +02:00
}
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"))]
2021-12-31 08:59:13 +01:00
{
let loop_var = scope.get_mut_by_index(index);
if loop_var.is_shared() {
*loop_var.write_lock().expect("`Dynamic`") = value;
} else {
*loop_var = value;
}
}
#[cfg(feature = "no_closure")]
2021-12-31 08:59:13 +01:00
{
*scope.get_mut_by_index(index) = value;
2020-08-03 17:11:38 +02:00
}
2021-04-25 09:27:58 +02:00
#[cfg(not(feature = "unchecked"))]
2021-12-27 16:03:30 +01:00
self.inc_operations(&mut global.num_operations, 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-12-28 10:50:49 +01:00
scope, global, state, lib, this_ptr, statements, true, level,
2021-04-21 11:39:45 +02:00
);
match result {
Ok(_) => (),
Err(err) => match *err {
2021-12-27 05:27:31 +01:00
ERR::LoopBreak(false, _) => (),
ERR::LoopBreak(true, _) => break,
_ => return Err(err),
},
}
}
2020-04-11 12:09:03 +02:00
2021-06-07 05:01:16 +02:00
scope.rewind(orig_scope_len);
2020-11-20 15:23:37 +01:00
Ok(Dynamic::UNIT)
} else {
2021-12-27 05:27:31 +01:00
Err(ERR::ErrorFor(expr.position()).into())
}
}
2020-03-01 17:11:00 +01:00
// Continue/Break statement
Stmt::BreakLoop(options, pos) => {
2021-12-27 05:27:31 +01:00
Err(ERR::LoopBreak(options.contains(AST_OPTION_BREAK_OUT), *pos).into())
}
2020-03-01 17:11:00 +01:00
2022-01-05 06:14:18 +01:00
// Function call
2021-04-21 12:16:24 +02:00
Stmt::FnCall(x, pos) => {
2022-01-05 06:14:18 +01:00
self.eval_fn_call_expr(scope, global, state, lib, this_ptr, x, *pos, level)
2021-04-21 12:16:24 +02:00
}
2020-10-20 17:16:03 +02:00
// Try/Catch statement
2021-06-16 10:15:29 +02: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-12-28 10:50:49 +01:00
.eval_stmt_block(scope, global, 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 {
2021-12-27 05:27:31 +01:00
ERR::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"))]
_ => {
2021-12-06 13:52:47 +01:00
let mut err_map = crate::Map::new();
2021-02-28 07:38:34 +01:00
let err_pos = err.take_position();
err_map.insert("message".into(), err.to_string().into());
if !global.source.is_empty() {
err_map.insert("source".into(), global.source.clone().into());
2021-06-29 11:42:03 +02:00
}
2021-02-28 07:38:34 +01:00
if err_pos.is_none() {
// No position info
} else {
2022-01-06 04:07:52 +01:00
let line = err_pos.line().unwrap() as INT;
2021-05-22 13:14:24 +02:00
let position = if err_pos.is_beginning_of_line() {
0
} else {
2022-01-06 04:07:52 +01:00
err_pos.position().unwrap()
2021-05-22 13:14:24 +02:00
} 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();
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-12-28 10:50:49 +01:00
scope, global, 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
scope.rewind(orig_scope_len);
match result {
Ok(_) => Ok(Dynamic::UNIT),
Err(result_err) => match *result_err {
// Re-throw exception
2021-12-27 05:27:31 +01:00
ERR::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
}
}
// Throw value
Stmt::Return(options, Some(expr), pos) if options.contains(AST_OPTION_BREAK_OUT) => {
2021-12-27 05:27:31 +01:00
Err(ERR::ErrorRuntime(
2021-12-27 16:03:30 +01:00
self.eval_expr(scope, global, state, lib, this_ptr, expr, level)?
.flatten(),
*pos,
)
.into())
}
2020-03-03 11:15:20 +01:00
// Empty throw
Stmt::Return(options, None, pos) if options.contains(AST_OPTION_BREAK_OUT) => {
2021-12-27 05:27:31 +01:00
Err(ERR::ErrorRuntime(Dynamic::UNIT, *pos).into())
2020-03-03 11:15:20 +01:00
}
2020-03-01 17:11:00 +01:00
// Return value
2021-12-27 05:27:31 +01:00
Stmt::Return(_, Some(expr), pos) => Err(ERR::Return(
2021-12-27 16:03:30 +01:00
self.eval_expr(scope, global, state, lib, this_ptr, expr, level)?
2021-04-21 11:39:45 +02:00
.flatten(),
*pos,
)
.into()),
2020-03-01 17:11:00 +01:00
// Empty return
2021-12-27 05:27:31 +01:00
Stmt::Return(_, None, pos) => Err(ERR::Return(Dynamic::UNIT, *pos).into()),
2020-10-09 07:25:53 +02:00
// Let/const statement
Stmt::Var(expr, x, options, _) => {
2021-03-29 05:36:02 +02:00
let name = &x.name;
let entry_type = if options.contains(AST_OPTION_CONSTANT) {
AccessMode::ReadOnly
} else {
AccessMode::ReadWrite
2020-10-09 07:25:53 +02:00
};
let export = options.contains(AST_OPTION_PUBLIC);
2020-03-13 11:12:41 +01:00
2021-03-09 16:30:48 +01:00
let value = self
2021-12-27 16:03:30 +01:00
.eval_expr(scope, global, state, lib, this_ptr, expr, level)?
2021-03-09 16:30:48 +01:00
.flatten();
2021-12-30 01:57:23 +01:00
let (var_name, _alias): (Cow<'_, str>, _) = if !rewind_scope {
2021-04-17 11:25:35 +02:00
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "no_module"))]
2021-12-30 01:57:23 +01:00
if state.scope_level == 0
&& entry_type == AccessMode::ReadOnly
&& lib.iter().any(|&m| !m.is_empty())
{
// Add a global constant if at top level and there are functions
2021-12-27 16:03:30 +01:00
global.set_constant(name.clone(), value.clone());
2021-04-17 11:25:35 +02:00
}
(
2021-03-09 16:30:48 +01:00
name.to_string().into(),
if export { Some(name.clone()) } else { None },
)
} 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"))]
2021-12-27 16:03:30 +01:00
if global.num_modules_loaded >= self.max_modules() {
2021-12-27 05:27:31 +01:00
return Err(ERR::ErrorTooManyModules(*_pos).into());
}
2020-05-15 15:40:54 +02:00
if let Some(path) = self
2021-12-27 16:03:30 +01:00
.eval_expr(scope, global, 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;
2022-01-03 16:16:47 +01:00
let source = match global.source.as_str() {
"" => None,
s => Some(s),
};
2021-05-29 12:33:29 +02:00
let path_pos = expr.position();
2021-01-08 17:24:55 +01:00
2021-12-27 16:03:30 +01:00
let module = global
2021-07-26 04:03:46 +02:00
.embedded_module_resolver
2021-01-08 17:24:55 +01:00
.as_ref()
2021-05-29 12:33:29 +02:00
.and_then(|r| match r.resolve(self, source, &path, path_pos) {
2021-12-27 05:27:31 +01:00
Err(err) if matches!(*err, ERR::ErrorModuleNotFound(_, _)) => None,
2021-05-29 12:33:29 +02:00
result => Some(result),
})
.or_else(|| {
self.module_resolver
.as_ref()
.map(|r| r.resolve(self, source, &path, path_pos))
2021-01-08 17:24:55 +01:00
})
.unwrap_or_else(|| {
2021-12-27 05:27:31 +01:00
Err(ERR::ErrorModuleNotFound(path.to_string(), path_pos).into())
})?;
2020-12-26 06:05:57 +01:00
2021-07-24 08:11:16 +02:00
if let Some(name) = export.as_ref().map(|x| x.name.clone()) {
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
2021-11-13 15:36:23 +01:00
let mut module = crate::func::native::shared_take_or_clone(module);
2020-12-26 06:05:57 +01:00
module.build_index();
2021-12-27 16:03:30 +01:00
global.push_module(name, module);
2020-12-26 06:05:57 +01:00
} else {
2021-12-27 16:03:30 +01:00
global.push_module(name, module);
}
2021-07-24 08:11:16 +02:00
}
2020-05-15 15:40:54 +02:00
2021-12-27 16:03:30 +01:00
global.num_modules_loaded += 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-11-15 07:30:00 +01:00
list.iter().try_for_each(
|(Ident { name, pos, .. }, Ident { name: rename, .. })| {
// Mark scope variables as public
if let Some((index, _)) = scope.get_index(name) {
scope.add_entry_alias(
index,
if rename.is_empty() { name } else { rename }.clone(),
);
2021-12-25 16:49:14 +01:00
Ok(()) as RhaiResultOf<_>
2021-11-15 07:30:00 +01:00
} else {
2021-12-27 05:27:31 +01:00
Err(ERR::ErrorVariableNotFound(name.to_string(), *pos).into())
2021-11-15 07:30:00 +01: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-07-24 08:11:16 +02:00
if let Some((index, _)) = scope.get_index(name) {
2020-12-26 06:05:57 +01:00
let val = scope.get_mut_by_index(index);
2020-08-03 06:10:20 +02:00
2020-12-09 14:06:36 +01:00
if !val.is_shared() {
// Replace the variable with a shared value.
2021-04-17 09:15:54 +02:00
*val = std::mem::take(val).into_shared();
2020-08-03 06:10:20 +02:00
}
2021-07-24 08:11:16 +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
};
2022-01-05 06:14:18 +01:00
self.check_return_value(result, stmt.position())
2021-06-11 13:59:50 +02:00
}
2020-06-13 18:09:16 +02:00
2021-06-11 13:59:50 +02:00
/// Check a result to ensure that the data size is within allowable limit.
2022-01-05 06:14:18 +01:00
fn check_return_value(&self, mut result: RhaiResult, pos: Position) -> RhaiResult {
2022-01-06 06:40:03 +01:00
let _pos = pos;
2022-01-06 05:31:46 +01:00
match result {
Ok(ref mut r) => {
// Concentrate all empty strings into one instance to save memory
if let Dynamic(Union::Str(s, _, _)) = r {
if s.is_empty() {
if !s.ptr_eq(&self.empty_string) {
*s = self.const_empty_string();
}
return result;
}
}
2022-01-06 05:31:46 +01:00
#[cfg(not(feature = "unchecked"))]
2022-01-06 06:40:03 +01:00
self.check_data_size(&r, _pos)?;
2022-01-06 05:31:46 +01:00
}
_ => (),
2021-09-26 15:18:52 +02:00
}
result
2021-06-11 13:59:50 +02:00
}
2020-06-14 08:25:47 +02:00
2022-01-06 06:40:03 +01:00
/// Recursively calculate the sizes of a value.
///
/// Sizes returned are `(`[`Array`][crate::Array], [`Map`][crate::Map] and `String)`.
///
/// # Panics
///
/// Panics if any interior data is shared (should never happen).
#[cfg(not(feature = "unchecked"))]
2022-01-06 06:40:03 +01:00
fn calc_data_sizes(value: &Dynamic, top: bool) -> (usize, usize, usize) {
match value.0 {
#[cfg(not(feature = "no_index"))]
Union::Array(ref arr, _, _) => {
arr.iter()
.fold((0, 0, 0), |(arrays, maps, strings), value| match value.0 {
Union::Array(_, _, _) => {
let (a, m, s) = Self::calc_data_sizes(value, false);
(arrays + a + 1, maps + m, strings + s)
}
Union::Blob(ref a, _, _) => (arrays + 1 + a.len(), maps, strings),
#[cfg(not(feature = "no_object"))]
Union::Map(_, _, _) => {
let (a, m, s) = Self::calc_data_sizes(value, false);
(arrays + a + 1, maps + m, strings + s)
}
Union::Str(ref s, _, _) => (arrays + 1, maps, strings + s.len()),
_ => (arrays + 1, maps, strings),
})
}
#[cfg(not(feature = "no_index"))]
Union::Blob(ref arr, _, _) => (arr.len(), 0, 0),
#[cfg(not(feature = "no_object"))]
Union::Map(ref map, _, _) => {
map.values()
.fold((0, 0, 0), |(arrays, maps, strings), value| match value.0 {
#[cfg(not(feature = "no_index"))]
Union::Array(_, _, _) => {
let (a, m, s) = Self::calc_data_sizes(value, false);
(arrays + a, maps + m + 1, strings + s)
}
#[cfg(not(feature = "no_index"))]
Union::Blob(ref a, _, _) => (arrays + a.len(), maps, strings),
Union::Map(_, _, _) => {
let (a, m, s) = Self::calc_data_sizes(value, false);
(arrays + a, maps + m + 1, strings + s)
}
Union::Str(ref s, _, _) => (arrays, maps + 1, strings + s.len()),
_ => (arrays, maps + 1, strings),
})
}
Union::Str(ref s, _, _) => (0, 0, s.len()),
#[cfg(not(feature = "no_closure"))]
Union::Shared(_, _, _) if !top => {
unreachable!("shared values discovered within data: {}", value)
2020-06-13 18:09:16 +02:00
}
2022-01-06 06:40:03 +01:00
_ => (0, 0, 0),
2020-06-14 08:25:47 +02:00
}
2022-01-06 06:40:03 +01:00
}
/// Is there a data size limit set?
#[cfg(not(feature = "unchecked"))]
fn has_data_size_limit(&self) -> bool {
let mut _limited = self.limits.max_string_size.is_some();
2020-06-14 08:25:47 +02:00
2021-06-11 13:59:50 +02:00
#[cfg(not(feature = "no_index"))]
{
2022-01-06 06:40:03 +01:00
_limited = _limited || self.limits.max_array_size.is_some();
2021-06-11 13:59:50 +02:00
}
#[cfg(not(feature = "no_object"))]
{
2022-01-06 06:40:03 +01:00
_limited = _limited || self.limits.max_map_size.is_some();
2021-06-11 13:59:50 +02:00
}
2022-01-06 06:40:03 +01:00
_limited
}
2021-06-11 13:59:50 +02:00
2022-01-06 06:40:03 +01:00
/// Raise an error if any data size exceeds limit.
#[cfg(not(feature = "unchecked"))]
fn raise_err_if_over_data_size_limit(
&self,
sizes: (usize, usize, usize),
pos: Position,
) -> RhaiResultOf<()> {
let (_arr, _map, s) = sizes;
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)
{
2022-01-05 06:14:18 +01:00
return Err(ERR::ErrorDataTooLarge("Length of string".to_string(), pos).into());
}
#[cfg(not(feature = "no_index"))]
2021-01-06 06:46:53 +01:00
if _arr
> self
.limits
.max_array_size
.map_or(usize::MAX, NonZeroUsize::get)
{
2022-01-05 06:14:18 +01:00
return Err(ERR::ErrorDataTooLarge("Size of array".to_string(), pos).into());
}
#[cfg(not(feature = "no_object"))]
2021-01-06 06:46:53 +01:00
if _map
> self
.limits
.max_map_size
.map_or(usize::MAX, NonZeroUsize::get)
{
2022-01-05 06:14:18 +01:00
return Err(ERR::ErrorDataTooLarge("Size of object map".to_string(), pos).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
}
2022-01-06 06:40:03 +01:00
/// Check whether the size of a [`Dynamic`] is within limits.
#[cfg(not(feature = "unchecked"))]
#[inline]
2022-01-06 06:40:03 +01:00
fn check_data_size(&self, value: &Dynamic, pos: Position) -> RhaiResultOf<()> {
// If no data size limits, just return
if !self.has_data_size_limit() {
return Ok(());
}
let sizes = Self::calc_data_sizes(value, true);
self.raise_err_if_over_data_size_limit(sizes, pos)
}
/// Raise an error if the size of a [`Dynamic`] is out of limits (if any).
///
/// Not available under `unchecked`.
#[cfg(not(feature = "unchecked"))]
2022-01-06 06:40:03 +01:00
#[inline(always)]
pub fn ensure_data_size_within_limits(&self, value: &Dynamic) -> RhaiResultOf<()> {
self.check_data_size(value, Position::NONE)
2022-01-06 06:40:03 +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,
num_operations: &mut u64,
2020-12-20 16:25:11 +01:00
pos: Position,
2021-12-25 16:49:14 +01:00
) -> RhaiResultOf<()> {
*num_operations += 1;
2020-07-04 16:53:00 +02:00
// Guard against too many operations
if self.max_operations() > 0 && *num_operations > self.max_operations() {
2021-12-27 05:27:31 +01:00
return Err(ERR::ErrorTooManyOperations(pos).into());
}
// Report progress - only in steps
2021-05-25 04:54:48 +02:00
if let Some(ref progress) = self.progress {
if let Some(token) = progress(*num_operations) {
2020-11-02 04:04:45 +01:00
// Terminate script if progress returns a termination token
2021-12-27 05:27:31 +01:00
return Err(ERR::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.
#[inline]
2021-06-12 16:47:43 +02:00
#[must_use]
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
2021-12-27 05:27:31 +01:00
/// Make a `Box<`[`EvalAltResult<ErrorMismatchDataType>`][ERR::ErrorMismatchDataType]`>`.
#[inline]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-12-25 16:49:14 +01:00
pub(crate) fn make_type_mismatch_err<T>(&self, typ: &str, pos: Position) -> RhaiError {
2021-12-27 05:27:31 +01:00
ERR::ErrorMismatchDataType(self.map_type_name(type_name::<T>()).into(), typ.into(), pos)
.into()
2020-10-05 07:45:57 +02:00
}
2016-03-01 15:40:48 +01:00
}