Split Engine into eval folder.
This commit is contained in:
parent
ad0f7b7ce9
commit
a267ac5e54
26
src/README.md
Normal file
26
src/README.md
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
Source Structure
|
||||||
|
================
|
||||||
|
|
||||||
|
|
||||||
|
| Source file | Description |
|
||||||
|
| -------------- | ------------------------------------------------------------------------------- |
|
||||||
|
| `lib.rs` | Crate root |
|
||||||
|
| `engine.rs` | The scripting engine, defines the `Engine` type |
|
||||||
|
| `tokenizer.rs` | Script tokenizer/lexer |
|
||||||
|
| `parser.rs` | Script parser |
|
||||||
|
| `optimizer.rs` | Script optimizer |
|
||||||
|
| `unsafe.rs` | `unsafe` functions |
|
||||||
|
| `tests.rs` | Unit tests (not integration tests, which are in the `rhai/tests` sub-directory) |
|
||||||
|
|
||||||
|
|
||||||
|
| Sub-directory | Description |
|
||||||
|
| ------------- | ----------------------------------------------------- |
|
||||||
|
| `types` | Common data types (e.g. `Dynamic`, errors) |
|
||||||
|
| `api` | Public API for the scripting engine |
|
||||||
|
| `ast` | AST definition |
|
||||||
|
| `module` | Support for modules |
|
||||||
|
| `packages` | Pre-defined packages |
|
||||||
|
| `func` | Support for function calls |
|
||||||
|
| `eval` | Evaluation engine |
|
||||||
|
| `serde` | Support for [`serde`](https://crates.io/crates/serde) |
|
||||||
|
| `bin` | Pre-built CLI binaries (e.g. `rhai-run`, `rhai-repl`) |
|
@ -1,7 +1,7 @@
|
|||||||
//! Module that defines the `call_fn` API of [`Engine`].
|
//! Module that defines the `call_fn` API of [`Engine`].
|
||||||
#![cfg(not(feature = "no_function"))]
|
#![cfg(not(feature = "no_function"))]
|
||||||
|
|
||||||
use crate::engine::{EvalState, GlobalRuntimeState};
|
use crate::eval::{EvalState, GlobalRuntimeState};
|
||||||
use crate::types::dynamic::Variant;
|
use crate::types::dynamic::Variant;
|
||||||
use crate::{
|
use crate::{
|
||||||
Dynamic, Engine, FuncArgs, Position, RhaiResult, RhaiResultOf, Scope, StaticVec, AST, ERR,
|
Dynamic, Engine, FuncArgs, Position, RhaiResult, RhaiResultOf, Scope, StaticVec, AST, ERR,
|
||||||
|
@ -1,14 +1,14 @@
|
|||||||
//! Module implementing custom syntax for [`Engine`].
|
//! Module implementing custom syntax for [`Engine`].
|
||||||
|
|
||||||
use crate::ast::Expr;
|
use crate::ast::Expr;
|
||||||
use crate::engine::EvalContext;
|
|
||||||
use crate::func::native::SendSync;
|
use crate::func::native::SendSync;
|
||||||
use crate::parser::ParseResult;
|
use crate::parser::ParseResult;
|
||||||
use crate::r#unsafe::unsafe_try_cast;
|
use crate::r#unsafe::unsafe_try_cast;
|
||||||
use crate::tokenizer::{is_valid_identifier, Token};
|
use crate::tokenizer::{is_valid_identifier, Token};
|
||||||
use crate::types::dynamic::Variant;
|
use crate::types::dynamic::Variant;
|
||||||
use crate::{
|
use crate::{
|
||||||
Engine, Identifier, ImmutableString, LexError, Position, RhaiResult, Shared, StaticVec, INT,
|
Engine, EvalContext, Identifier, ImmutableString, LexError, Position, RhaiResult, Shared,
|
||||||
|
StaticVec, INT,
|
||||||
};
|
};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
//! Module that defines the public evaluation API of [`Engine`].
|
//! Module that defines the public evaluation API of [`Engine`].
|
||||||
|
|
||||||
use crate::engine::{EvalState, GlobalRuntimeState};
|
use crate::eval::{EvalState, GlobalRuntimeState};
|
||||||
use crate::parser::ParseState;
|
use crate::parser::ParseState;
|
||||||
use crate::types::dynamic::Variant;
|
use crate::types::dynamic::Variant;
|
||||||
use crate::{Dynamic, Engine, Module, Position, RhaiResult, RhaiResultOf, Scope, AST, ERR};
|
use crate::{Dynamic, Engine, Module, Position, RhaiResult, RhaiResultOf, Scope, AST, ERR};
|
||||||
|
@ -1,8 +1,7 @@
|
|||||||
//! Module that defines public event handlers for [`Engine`].
|
//! Module that defines public event handlers for [`Engine`].
|
||||||
|
|
||||||
use crate::engine::EvalContext;
|
|
||||||
use crate::func::SendSync;
|
use crate::func::SendSync;
|
||||||
use crate::{Dynamic, Engine, Position, RhaiResultOf};
|
use crate::{Dynamic, Engine, EvalContext, Position, RhaiResultOf};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
//! Module that defines the public evaluation API of [`Engine`].
|
//! Module that defines the public evaluation API of [`Engine`].
|
||||||
|
|
||||||
use crate::engine::{EvalState, GlobalRuntimeState};
|
use crate::eval::{EvalState, GlobalRuntimeState};
|
||||||
use crate::parser::ParseState;
|
use crate::parser::ParseState;
|
||||||
use crate::{Engine, Module, RhaiResultOf, Scope, AST};
|
use crate::{Engine, Module, RhaiResultOf, Scope, AST};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
|
3284
src/engine.rs
3284
src/engine.rs
File diff suppressed because it is too large
Load Diff
113
src/eval/chaining.rs
Normal file
113
src/eval/chaining.rs
Normal file
@ -0,0 +1,113 @@
|
|||||||
|
//! Types to support chaining operations (i.e. indexing and dotting).
|
||||||
|
#![cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
||||||
|
|
||||||
|
use crate::ast::Expr;
|
||||||
|
use crate::{Dynamic, Position};
|
||||||
|
use std::hash::Hash;
|
||||||
|
#[cfg(feature = "no_std")]
|
||||||
|
use std::prelude::v1::*;
|
||||||
|
|
||||||
|
/// Method of chaining.
|
||||||
|
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
|
||||||
|
pub enum ChainType {
|
||||||
|
/// Indexing.
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Indexing,
|
||||||
|
/// Dotting.
|
||||||
|
#[cfg(not(feature = "no_object"))]
|
||||||
|
Dotting,
|
||||||
|
}
|
||||||
|
|
||||||
|
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),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Value of a chaining argument.
|
||||||
|
#[derive(Debug, Clone, Hash)]
|
||||||
|
pub 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),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ChainArgument {
|
||||||
|
/// Return the index value.
|
||||||
|
#[inline(always)]
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
#[must_use]
|
||||||
|
pub fn into_index_value(self) -> Option<Dynamic> {
|
||||||
|
match self {
|
||||||
|
Self::IndexValue(value, _) => Some(value),
|
||||||
|
#[cfg(not(feature = "no_object"))]
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Return the list of method call arguments.
|
||||||
|
///
|
||||||
|
/// # Panics
|
||||||
|
///
|
||||||
|
/// Panics if the [`ChainArgument`] is not [`MethodCallArgs`][ChainArgument::MethodCallArgs].
|
||||||
|
#[inline(always)]
|
||||||
|
#[cfg(not(feature = "no_object"))]
|
||||||
|
#[must_use]
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
x => unreachable!("ChainArgument::MethodCallArgs expected but gets {:?}", x),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Return the [position][Position].
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Create n [`MethodCallArgs`][ChainArgument::MethodCallArgs].
|
||||||
|
#[inline(always)]
|
||||||
|
#[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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Create an [`IndexValue`][ChainArgument::IndexValue].
|
||||||
|
#[inline(always)]
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
#[must_use]
|
||||||
|
pub const fn from_index_value(value: Dynamic, pos: Position) -> Self {
|
||||||
|
Self::IndexValue(value, pos)
|
||||||
|
}
|
||||||
|
}
|
200
src/eval/data_check.rs
Normal file
200
src/eval/data_check.rs
Normal file
@ -0,0 +1,200 @@
|
|||||||
|
//! Data checks during evaluation.
|
||||||
|
|
||||||
|
use crate::types::dynamic::Union;
|
||||||
|
use crate::{Dynamic, Engine, Position, RhaiResult, RhaiResultOf, ERR};
|
||||||
|
use std::num::NonZeroUsize;
|
||||||
|
#[cfg(feature = "no_std")]
|
||||||
|
use std::prelude::v1::*;
|
||||||
|
|
||||||
|
impl Engine {
|
||||||
|
/// Check a result to ensure that the data size is within allowable limit.
|
||||||
|
pub(crate) fn check_return_value(&self, mut result: RhaiResult, pos: Position) -> RhaiResult {
|
||||||
|
let _pos = pos;
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "unchecked"))]
|
||||||
|
self.check_data_size(&r, _pos)?;
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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"))]
|
||||||
|
pub(crate) 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 => {
|
||||||
|
Self::calc_data_sizes(&*value.read_lock::<Dynamic>().unwrap(), true)
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "no_closure"))]
|
||||||
|
Union::Shared(_, _, _) => {
|
||||||
|
unreachable!("shared values discovered within data: {}", value)
|
||||||
|
}
|
||||||
|
_ => (0, 0, 0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Is there a data size limit set?
|
||||||
|
#[cfg(not(feature = "unchecked"))]
|
||||||
|
pub(crate) fn has_data_size_limit(&self) -> bool {
|
||||||
|
let mut _limited = self.limits.max_string_size.is_some();
|
||||||
|
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
{
|
||||||
|
_limited = _limited || self.limits.max_array_size.is_some();
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "no_object"))]
|
||||||
|
{
|
||||||
|
_limited = _limited || self.limits.max_map_size.is_some();
|
||||||
|
}
|
||||||
|
|
||||||
|
_limited
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Raise an error if any data size exceeds limit.
|
||||||
|
#[cfg(not(feature = "unchecked"))]
|
||||||
|
pub(crate) fn raise_err_if_over_data_size_limit(
|
||||||
|
&self,
|
||||||
|
sizes: (usize, usize, usize),
|
||||||
|
pos: Position,
|
||||||
|
) -> RhaiResultOf<()> {
|
||||||
|
let (_arr, _map, s) = sizes;
|
||||||
|
|
||||||
|
if s > self
|
||||||
|
.limits
|
||||||
|
.max_string_size
|
||||||
|
.map_or(usize::MAX, NonZeroUsize::get)
|
||||||
|
{
|
||||||
|
return Err(ERR::ErrorDataTooLarge("Length of string".to_string(), pos).into());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
if _arr
|
||||||
|
> self
|
||||||
|
.limits
|
||||||
|
.max_array_size
|
||||||
|
.map_or(usize::MAX, NonZeroUsize::get)
|
||||||
|
{
|
||||||
|
return Err(ERR::ErrorDataTooLarge("Size of array".to_string(), pos).into());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "no_object"))]
|
||||||
|
if _map
|
||||||
|
> self
|
||||||
|
.limits
|
||||||
|
.max_map_size
|
||||||
|
.map_or(usize::MAX, NonZeroUsize::get)
|
||||||
|
{
|
||||||
|
return Err(ERR::ErrorDataTooLarge("Size of object map".to_string(), pos).into());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check whether the size of a [`Dynamic`] is within limits.
|
||||||
|
#[cfg(not(feature = "unchecked"))]
|
||||||
|
pub(crate) 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"))]
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn ensure_data_size_within_limits(&self, value: &Dynamic) -> RhaiResultOf<()> {
|
||||||
|
self.check_data_size(value, Position::NONE)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if the number of operations stay within limit.
|
||||||
|
#[cfg(not(feature = "unchecked"))]
|
||||||
|
pub(crate) fn inc_operations(
|
||||||
|
&self,
|
||||||
|
num_operations: &mut u64,
|
||||||
|
pos: Position,
|
||||||
|
) -> RhaiResultOf<()> {
|
||||||
|
*num_operations += 1;
|
||||||
|
|
||||||
|
// Guard against too many operations
|
||||||
|
if self.max_operations() > 0 && *num_operations > self.max_operations() {
|
||||||
|
return Err(ERR::ErrorTooManyOperations(pos).into());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Report progress - only in steps
|
||||||
|
if let Some(ref progress) = self.progress {
|
||||||
|
if let Some(token) = progress(*num_operations) {
|
||||||
|
// Terminate script if progress returns a termination token
|
||||||
|
return Err(ERR::ErrorTerminated(token, pos).into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
101
src/eval/eval_context.rs
Normal file
101
src/eval/eval_context.rs
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
//! Evaluation context.
|
||||||
|
|
||||||
|
use super::{EvalState, GlobalRuntimeState};
|
||||||
|
use crate::{Dynamic, Engine, Module, Scope};
|
||||||
|
#[cfg(feature = "no_std")]
|
||||||
|
use std::prelude::v1::*;
|
||||||
|
|
||||||
|
/// Context of a script evaluation process.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct EvalContext<'a, 'x, 'px, 'm, 's, 'b, 't, 'pt> {
|
||||||
|
/// The current [`Engine`].
|
||||||
|
pub(crate) engine: &'a Engine,
|
||||||
|
/// The current [`Scope`].
|
||||||
|
pub(crate) scope: &'x mut Scope<'px>,
|
||||||
|
/// The current [`GlobalRuntimeState`].
|
||||||
|
pub(crate) global: &'m mut GlobalRuntimeState,
|
||||||
|
/// The current [evaluation state][EvalState].
|
||||||
|
pub(crate) state: &'s mut EvalState,
|
||||||
|
/// The current stack of imported [modules][Module].
|
||||||
|
pub(crate) lib: &'b [&'b Module],
|
||||||
|
/// The current bound `this` pointer, if any.
|
||||||
|
pub(crate) this_ptr: &'t mut Option<&'pt mut Dynamic>,
|
||||||
|
/// The current nesting level of function calls.
|
||||||
|
pub(crate) level: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'x, 'px, 'pt> EvalContext<'_, 'x, 'px, '_, '_, '_, '_, 'pt> {
|
||||||
|
/// The current [`Engine`].
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub const fn engine(&self) -> &Engine {
|
||||||
|
self.engine
|
||||||
|
}
|
||||||
|
/// The current source.
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub fn source(&self) -> Option<&str> {
|
||||||
|
match self.global.source.as_str() {
|
||||||
|
"" => None,
|
||||||
|
s => Some(s),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// The current [`Scope`].
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub const fn scope(&self) -> &Scope<'px> {
|
||||||
|
self.scope
|
||||||
|
}
|
||||||
|
/// Mutable reference to the current [`Scope`].
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub fn scope_mut(&mut self) -> &mut &'x mut Scope<'px> {
|
||||||
|
&mut self.scope
|
||||||
|
}
|
||||||
|
/// Get an iterator over the current set of modules imported via `import` statements.
|
||||||
|
#[cfg(not(feature = "no_module"))]
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn iter_imports(&self) -> impl Iterator<Item = (&str, &Module)> {
|
||||||
|
self.global.iter_modules()
|
||||||
|
}
|
||||||
|
/// _(internals)_ The current [`GlobalRuntimeState`].
|
||||||
|
/// Exported under the `internals` feature only.
|
||||||
|
#[cfg(feature = "internals")]
|
||||||
|
#[cfg(not(feature = "no_module"))]
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub const fn global_runtime_state(&self) -> &GlobalRuntimeState {
|
||||||
|
self.global
|
||||||
|
}
|
||||||
|
/// Get an iterator over the namespaces containing definition of all script-defined functions.
|
||||||
|
#[inline]
|
||||||
|
pub fn iter_namespaces(&self) -> impl Iterator<Item = &Module> {
|
||||||
|
self.lib.iter().cloned()
|
||||||
|
}
|
||||||
|
/// _(internals)_ The current set of namespaces containing definitions of all script-defined functions.
|
||||||
|
/// Exported under the `internals` feature only.
|
||||||
|
#[cfg(feature = "internals")]
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub const fn namespaces(&self) -> &[&Module] {
|
||||||
|
self.lib
|
||||||
|
}
|
||||||
|
/// The current bound `this` pointer, if any.
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub fn this_ptr(&self) -> Option<&Dynamic> {
|
||||||
|
self.this_ptr.as_ref().map(|v| &**v)
|
||||||
|
}
|
||||||
|
/// 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()
|
||||||
|
}
|
||||||
|
/// The current nesting level of function calls.
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub const fn call_level(&self) -> usize {
|
||||||
|
self.level
|
||||||
|
}
|
||||||
|
}
|
68
src/eval/eval_state.rs
Normal file
68
src/eval/eval_state.rs
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
//! Evaluation state.
|
||||||
|
|
||||||
|
use crate::func::call::FnResolutionCache;
|
||||||
|
use crate::StaticVec;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
#[cfg(feature = "no_std")]
|
||||||
|
use std::prelude::v1::*;
|
||||||
|
|
||||||
|
/// _(internals)_ A type that holds all the current states of the [`Engine`].
|
||||||
|
/// Exported under the `internals` feature only.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct EvalState {
|
||||||
|
/// Force a [`Scope`] search by name.
|
||||||
|
///
|
||||||
|
/// Normally, access to variables are parsed with a relative offset into the [`Scope`] to avoid a lookup.
|
||||||
|
///
|
||||||
|
/// In some situation, e.g. after running an `eval` statement, or after a custom syntax statement,
|
||||||
|
/// subsequent offsets may become mis-aligned.
|
||||||
|
///
|
||||||
|
/// When that happens, this flag is turned on.
|
||||||
|
pub always_search_scope: bool,
|
||||||
|
/// Level of the current scope.
|
||||||
|
///
|
||||||
|
/// The global (root) level is zero, a new block (or function call) is one level higher, and so on.
|
||||||
|
pub scope_level: usize,
|
||||||
|
/// Stack of function resolution caches.
|
||||||
|
fn_resolution_caches: StaticVec<FnResolutionCache>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EvalState {
|
||||||
|
/// Create a new [`EvalState`].
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub const fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
always_search_scope: false,
|
||||||
|
scope_level: 0,
|
||||||
|
fn_resolution_caches: StaticVec::new_const(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// 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()
|
||||||
|
}
|
||||||
|
/// Get a mutable reference to the current function resolution cache.
|
||||||
|
#[inline]
|
||||||
|
#[must_use]
|
||||||
|
pub fn fn_resolution_cache_mut(&mut self) -> &mut FnResolutionCache {
|
||||||
|
if self.fn_resolution_caches.is_empty() {
|
||||||
|
// Push a new function resolution cache if the stack is empty
|
||||||
|
self.push_fn_resolution_cache();
|
||||||
|
}
|
||||||
|
self.fn_resolution_caches.last_mut().unwrap()
|
||||||
|
}
|
||||||
|
/// Push an empty function resolution cache onto the stack and make it current.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn push_fn_resolution_cache(&mut self) {
|
||||||
|
self.fn_resolution_caches.push(BTreeMap::new());
|
||||||
|
}
|
||||||
|
/// Rewind the function resolution caches stack to a particular size.
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn rewind_fn_resolution_caches(&mut self, len: usize) {
|
||||||
|
self.fn_resolution_caches.truncate(len);
|
||||||
|
}
|
||||||
|
}
|
1387
src/eval/expr.rs
Normal file
1387
src/eval/expr.rs
Normal file
File diff suppressed because it is too large
Load Diff
271
src/eval/global_state.rs
Normal file
271
src/eval/global_state.rs
Normal file
@ -0,0 +1,271 @@
|
|||||||
|
//! Global runtime state.
|
||||||
|
|
||||||
|
use crate::engine::{FN_IDX_GET, FN_IDX_SET};
|
||||||
|
use crate::func::{CallableFunction, IteratorFn};
|
||||||
|
use crate::{Dynamic, Identifier, Module, Shared, StaticVec};
|
||||||
|
#[cfg(feature = "no_std")]
|
||||||
|
use std::prelude::v1::*;
|
||||||
|
use std::{
|
||||||
|
any::TypeId,
|
||||||
|
collections::BTreeMap,
|
||||||
|
fmt,
|
||||||
|
iter::{FromIterator, Rev, Zip},
|
||||||
|
ops::DerefMut,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// _(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>,
|
||||||
|
/// Stack of imported [modules][Module].
|
||||||
|
modules: StaticVec<Shared<Module>>,
|
||||||
|
/// Source of the current context.
|
||||||
|
/// No source if the string is empty.
|
||||||
|
pub source: Identifier,
|
||||||
|
/// 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),
|
||||||
|
/// Embedded [module][Module] resolver.
|
||||||
|
#[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>>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for GlobalRuntimeState {
|
||||||
|
#[inline(always)]
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GlobalRuntimeState {
|
||||||
|
/// Create a new [`GlobalRuntimeState`].
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub const fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
keys: StaticVec::new_const(),
|
||||||
|
modules: StaticVec::new_const(),
|
||||||
|
source: Identifier::new_const(),
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Get the length of the stack of globally-imported [modules][Module].
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub fn num_imported_modules(&self) -> usize {
|
||||||
|
self.keys.len()
|
||||||
|
}
|
||||||
|
/// Get the globally-imported [module][Module] at a particular index.
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub fn get_shared_module(&self, index: usize) -> Option<Shared<Module>> {
|
||||||
|
self.modules.get(index).cloned()
|
||||||
|
}
|
||||||
|
/// Get a mutable reference to the globally-imported [module][Module] at a particular index.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub(crate) fn get_shared_module_mut(&mut self, index: usize) -> Option<&mut Shared<Module>> {
|
||||||
|
self.modules.get_mut(index)
|
||||||
|
}
|
||||||
|
/// Get the index of a globally-imported [module][Module] by name.
|
||||||
|
#[inline]
|
||||||
|
#[must_use]
|
||||||
|
pub fn find_module(&self, name: &str) -> Option<usize> {
|
||||||
|
let len = self.keys.len();
|
||||||
|
|
||||||
|
self.keys.iter().rev().enumerate().find_map(|(i, key)| {
|
||||||
|
if key == name {
|
||||||
|
Some(len - 1 - i)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/// 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.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
#[inline]
|
||||||
|
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()))
|
||||||
|
}
|
||||||
|
/// 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]
|
||||||
|
#[must_use]
|
||||||
|
pub fn contains_fn(&self, hash: u64) -> bool {
|
||||||
|
self.modules.iter().any(|m| m.contains_qualified_fn(hash))
|
||||||
|
}
|
||||||
|
/// Get the specified function via its hash key from the stack of globally-imported [modules][Module].
|
||||||
|
#[inline]
|
||||||
|
#[must_use]
|
||||||
|
pub fn get_fn(&self, hash: u64) -> Option<(&CallableFunction, Option<&str>)> {
|
||||||
|
self.modules
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.find_map(|m| m.get_qualified_fn(hash).map(|f| (f, m.id())))
|
||||||
|
}
|
||||||
|
/// Does the specified [`TypeId`][std::any::TypeId] iterator exist in the stack of
|
||||||
|
/// globally-imported [modules][Module]?
|
||||||
|
#[allow(dead_code)]
|
||||||
|
#[inline]
|
||||||
|
#[must_use]
|
||||||
|
pub fn contains_iter(&self, id: TypeId) -> bool {
|
||||||
|
self.modules.iter().any(|m| m.contains_qualified_iter(id))
|
||||||
|
}
|
||||||
|
/// Get the specified [`TypeId`][std::any::TypeId] iterator from the stack of globally-imported
|
||||||
|
/// [modules][Module].
|
||||||
|
#[inline]
|
||||||
|
#[must_use]
|
||||||
|
pub fn get_iter(&self, id: TypeId) -> Option<IteratorFn> {
|
||||||
|
self.modules
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.find_map(|m| m.get_qualified_iter(id))
|
||||||
|
}
|
||||||
|
/// Get a mutable reference to the cache of globally-defined constants.
|
||||||
|
#[cfg(not(feature = "no_module"))]
|
||||||
|
#[cfg(not(feature = "no_function"))]
|
||||||
|
#[must_use]
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// 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());
|
||||||
|
}
|
||||||
|
|
||||||
|
crate::func::native::shared_write_lock(self.constants.as_mut().expect("`Some`"))
|
||||||
|
.insert(name.into(), value);
|
||||||
|
}
|
||||||
|
/// 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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());
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
15
src/eval/mod.rs
Normal file
15
src/eval/mod.rs
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
mod chaining;
|
||||||
|
mod data_check;
|
||||||
|
mod eval_context;
|
||||||
|
mod eval_state;
|
||||||
|
mod expr;
|
||||||
|
mod global_state;
|
||||||
|
mod stmt;
|
||||||
|
mod target;
|
||||||
|
|
||||||
|
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
||||||
|
pub use chaining::{ChainArgument, ChainType};
|
||||||
|
pub use eval_context::EvalContext;
|
||||||
|
pub use eval_state::EvalState;
|
||||||
|
pub use global_state::GlobalRuntimeState;
|
||||||
|
pub use target::Target;
|
820
src/eval/stmt.rs
Normal file
820
src/eval/stmt.rs
Normal file
@ -0,0 +1,820 @@
|
|||||||
|
//! Module defining functions for evaluating a statement.
|
||||||
|
|
||||||
|
use super::{EvalState, GlobalRuntimeState, Target};
|
||||||
|
use crate::ast::{Expr, Ident, OpAssignment, Stmt, AST_OPTION_FLAGS::*};
|
||||||
|
use crate::func::get_hasher;
|
||||||
|
use crate::r#unsafe::unsafe_cast_var_name_to_lifetime;
|
||||||
|
use crate::types::dynamic::{AccessMode, Union};
|
||||||
|
use crate::{
|
||||||
|
Dynamic, Engine, ImmutableString, Module, Position, RhaiResult, RhaiResultOf, Scope, ERR, INT,
|
||||||
|
};
|
||||||
|
#[cfg(feature = "no_std")]
|
||||||
|
use std::prelude::v1::*;
|
||||||
|
use std::{
|
||||||
|
borrow::Cow,
|
||||||
|
hash::{Hash, Hasher},
|
||||||
|
};
|
||||||
|
|
||||||
|
impl Engine {
|
||||||
|
/// Evaluate a statements block.
|
||||||
|
pub(crate) fn eval_stmt_block(
|
||||||
|
&self,
|
||||||
|
scope: &mut Scope,
|
||||||
|
global: &mut GlobalRuntimeState,
|
||||||
|
state: &mut EvalState,
|
||||||
|
lib: &[&Module],
|
||||||
|
this_ptr: &mut Option<&mut Dynamic>,
|
||||||
|
statements: &[Stmt],
|
||||||
|
restore_orig_state: bool,
|
||||||
|
level: usize,
|
||||||
|
) -> RhaiResult {
|
||||||
|
if statements.is_empty() {
|
||||||
|
return Ok(Dynamic::UNIT);
|
||||||
|
}
|
||||||
|
|
||||||
|
let orig_always_search_scope = state.always_search_scope;
|
||||||
|
let orig_scope_len = scope.len();
|
||||||
|
let orig_mods_len = global.num_imported_modules();
|
||||||
|
let orig_fn_resolution_caches_len = state.fn_resolution_caches_len();
|
||||||
|
|
||||||
|
if restore_orig_state {
|
||||||
|
state.scope_level += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut result = Dynamic::UNIT;
|
||||||
|
|
||||||
|
for stmt in statements {
|
||||||
|
let _mods_len = global.num_imported_modules();
|
||||||
|
|
||||||
|
result = self.eval_stmt(
|
||||||
|
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.
|
||||||
|
if global
|
||||||
|
.scan_modules_raw()
|
||||||
|
.skip(_mods_len)
|
||||||
|
.any(|(_, m)| m.contains_indexed_global_functions())
|
||||||
|
{
|
||||||
|
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
|
||||||
|
state.fn_resolution_cache_mut().clear();
|
||||||
|
} else if restore_orig_state {
|
||||||
|
// When new module is imported with global functions, push a new cache
|
||||||
|
state.push_fn_resolution_cache();
|
||||||
|
} else {
|
||||||
|
// When the block is to be evaluated in-place, just clear the current cache
|
||||||
|
state.fn_resolution_cache_mut().clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If imports list is modified, pop the functions lookup cache
|
||||||
|
state.rewind_fn_resolution_caches(orig_fn_resolution_caches_len);
|
||||||
|
|
||||||
|
if restore_orig_state {
|
||||||
|
scope.rewind(orig_scope_len);
|
||||||
|
state.scope_level -= 1;
|
||||||
|
global.truncate_modules(orig_mods_len);
|
||||||
|
|
||||||
|
// The impact of new local variables goes away at the end of a block
|
||||||
|
// because any new variables introduced will go out of scope
|
||||||
|
state.always_search_scope = orig_always_search_scope;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Evaluate an op-assignment statement.
|
||||||
|
/// [`Position`] in [`EvalAltResult`] is [`NONE`][Position::NONE] and should be set afterwards.
|
||||||
|
pub(crate) fn eval_op_assignment(
|
||||||
|
&self,
|
||||||
|
global: &mut GlobalRuntimeState,
|
||||||
|
state: &mut EvalState,
|
||||||
|
lib: &[&Module],
|
||||||
|
op_info: Option<OpAssignment>,
|
||||||
|
op_pos: Position,
|
||||||
|
target: &mut Target,
|
||||||
|
root: (&str, Position),
|
||||||
|
new_val: Dynamic,
|
||||||
|
) -> RhaiResultOf<()> {
|
||||||
|
if target.is_read_only() {
|
||||||
|
// Assignment to constant variable
|
||||||
|
return Err(ERR::ErrorAssignmentToConstant(root.0.to_string(), root.1).into());
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut new_val = new_val;
|
||||||
|
|
||||||
|
if let Some(OpAssignment {
|
||||||
|
hash_op_assign,
|
||||||
|
hash_op,
|
||||||
|
op,
|
||||||
|
}) = op_info
|
||||||
|
{
|
||||||
|
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 {
|
||||||
|
lock_guard = target.write_lock::<Dynamic>().expect("`Dynamic`");
|
||||||
|
lhs_ptr_inner = &mut *lock_guard;
|
||||||
|
} else {
|
||||||
|
lhs_ptr_inner = &mut *target;
|
||||||
|
}
|
||||||
|
|
||||||
|
let hash = hash_op_assign;
|
||||||
|
let args = &mut [lhs_ptr_inner, &mut new_val];
|
||||||
|
|
||||||
|
match self.call_native_fn(global, state, lib, op, hash, args, true, true, op_pos) {
|
||||||
|
Err(err) if matches!(*err, ERR::ErrorFunctionNotFound(ref f, _) if f.starts_with(op)) =>
|
||||||
|
{
|
||||||
|
// Expand to `var = var op rhs`
|
||||||
|
let op = &op[..op.len() - 1]; // extract operator without =
|
||||||
|
|
||||||
|
// Run function
|
||||||
|
let (value, _) = self.call_native_fn(
|
||||||
|
global, state, lib, op, hash_op, args, true, false, op_pos,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
*args[0] = value.flatten();
|
||||||
|
}
|
||||||
|
err => return err.map(|_| ()),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Normal assignment
|
||||||
|
*target.as_mut() = new_val;
|
||||||
|
}
|
||||||
|
|
||||||
|
target.propagate_changed_value()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Evaluate a statement.
|
||||||
|
///
|
||||||
|
/// # 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,
|
||||||
|
global: &mut GlobalRuntimeState,
|
||||||
|
state: &mut EvalState,
|
||||||
|
lib: &[&Module],
|
||||||
|
this_ptr: &mut Option<&mut Dynamic>,
|
||||||
|
stmt: &Stmt,
|
||||||
|
rewind_scope: bool,
|
||||||
|
level: usize,
|
||||||
|
) -> 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 statements.
|
||||||
|
if let Stmt::FnCall(x, pos) = stmt {
|
||||||
|
#[cfg(not(feature = "unchecked"))]
|
||||||
|
self.inc_operations(&mut global.num_operations, stmt.position())?;
|
||||||
|
|
||||||
|
return self.eval_fn_call_expr(scope, global, state, lib, this_ptr, x, *pos, level);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then assignments.
|
||||||
|
// 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 Stmt::Assignment(x, op_pos) = stmt {
|
||||||
|
#[cfg(not(feature = "unchecked"))]
|
||||||
|
self.inc_operations(&mut global.num_operations, stmt.position())?;
|
||||||
|
|
||||||
|
return if x.0.is_variable_access(false) {
|
||||||
|
let (lhs_expr, op_info, rhs_expr) = x.as_ref();
|
||||||
|
let rhs_val = self
|
||||||
|
.eval_expr(scope, global, state, lib, this_ptr, rhs_expr, level)?
|
||||||
|
.flatten();
|
||||||
|
let (mut lhs_ptr, pos) =
|
||||||
|
self.search_namespace(scope, global, state, lib, this_ptr, lhs_expr)?;
|
||||||
|
|
||||||
|
let var_name = lhs_expr.get_variable_name(false).expect("`Expr::Variable`");
|
||||||
|
|
||||||
|
if !lhs_ptr.is_ref() {
|
||||||
|
return Err(ERR::ErrorAssignmentToConstant(var_name.to_string(), pos).into());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "unchecked"))]
|
||||||
|
self.inc_operations(&mut global.num_operations, pos)?;
|
||||||
|
|
||||||
|
self.eval_op_assignment(
|
||||||
|
global,
|
||||||
|
state,
|
||||||
|
lib,
|
||||||
|
*op_info,
|
||||||
|
*op_pos,
|
||||||
|
&mut lhs_ptr,
|
||||||
|
(var_name, pos),
|
||||||
|
rhs_val,
|
||||||
|
)
|
||||||
|
.map_err(|err| err.fill_position(rhs_expr.position()))?;
|
||||||
|
|
||||||
|
Ok(Dynamic::UNIT)
|
||||||
|
} else {
|
||||||
|
let (lhs_expr, op_info, rhs_expr) = x.as_ref();
|
||||||
|
let rhs_val = self
|
||||||
|
.eval_expr(scope, global, state, lib, this_ptr, rhs_expr, level)?
|
||||||
|
.flatten();
|
||||||
|
let _new_val = Some(((rhs_val, rhs_expr.position()), (*op_info, *op_pos)));
|
||||||
|
|
||||||
|
// Must be either `var[index] op= val` or `var.prop op= val`
|
||||||
|
match lhs_expr {
|
||||||
|
// name op= rhs (handled above)
|
||||||
|
Expr::Variable(_, _, _) => {
|
||||||
|
unreachable!("Expr::Variable case is already handled")
|
||||||
|
}
|
||||||
|
// idx_lhs[idx_expr] op= rhs
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Expr::Index(_, _, _) => {
|
||||||
|
self.eval_dot_index_chain(
|
||||||
|
scope, global, state, lib, this_ptr, lhs_expr, level, _new_val,
|
||||||
|
)?;
|
||||||
|
Ok(Dynamic::UNIT)
|
||||||
|
}
|
||||||
|
// dot_lhs.dot_rhs op= rhs
|
||||||
|
#[cfg(not(feature = "no_object"))]
|
||||||
|
Expr::Dot(_, _, _) => {
|
||||||
|
self.eval_dot_index_chain(
|
||||||
|
scope, global, state, lib, this_ptr, lhs_expr, level, _new_val,
|
||||||
|
)?;
|
||||||
|
Ok(Dynamic::UNIT)
|
||||||
|
}
|
||||||
|
_ => unreachable!("cannot assign to expression: {:?}", lhs_expr),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "unchecked"))]
|
||||||
|
self.inc_operations(&mut global.num_operations, stmt.position())?;
|
||||||
|
|
||||||
|
match stmt {
|
||||||
|
// No-op
|
||||||
|
Stmt::Noop(_) => Ok(Dynamic::UNIT),
|
||||||
|
|
||||||
|
// Expression as statement
|
||||||
|
Stmt::Expr(expr) => Ok(self
|
||||||
|
.eval_expr(scope, global, state, lib, this_ptr, expr, level)?
|
||||||
|
.flatten()),
|
||||||
|
|
||||||
|
// Block scope
|
||||||
|
Stmt::Block(statements, _) if statements.is_empty() => Ok(Dynamic::UNIT),
|
||||||
|
Stmt::Block(statements, _) => {
|
||||||
|
self.eval_stmt_block(scope, global, state, lib, this_ptr, statements, true, level)
|
||||||
|
}
|
||||||
|
|
||||||
|
// If statement
|
||||||
|
Stmt::If(expr, x, _) => {
|
||||||
|
let guard_val = self
|
||||||
|
.eval_expr(scope, global, state, lib, this_ptr, expr, level)?
|
||||||
|
.as_bool()
|
||||||
|
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, expr.position()))?;
|
||||||
|
|
||||||
|
if guard_val {
|
||||||
|
if !x.0.is_empty() {
|
||||||
|
self.eval_stmt_block(scope, global, state, lib, this_ptr, &x.0, true, level)
|
||||||
|
} else {
|
||||||
|
Ok(Dynamic::UNIT)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if !x.1.is_empty() {
|
||||||
|
self.eval_stmt_block(scope, global, state, lib, this_ptr, &x.1, true, level)
|
||||||
|
} else {
|
||||||
|
Ok(Dynamic::UNIT)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Switch statement
|
||||||
|
Stmt::Switch(match_expr, x, _) => {
|
||||||
|
let (table, def_stmt, ranges) = x.as_ref();
|
||||||
|
|
||||||
|
let value =
|
||||||
|
self.eval_expr(scope, global, state, lib, this_ptr, match_expr, level)?;
|
||||||
|
|
||||||
|
let stmt_block = if value.is_hashable() {
|
||||||
|
let hasher = &mut get_hasher();
|
||||||
|
value.hash(hasher);
|
||||||
|
let hash = hasher.finish();
|
||||||
|
|
||||||
|
// First check hashes
|
||||||
|
if let Some(t) = table.get(&hash) {
|
||||||
|
if let Some(ref c) = t.0 {
|
||||||
|
if self
|
||||||
|
.eval_expr(scope, global, state, lib, this_ptr, &c, level)
|
||||||
|
.and_then(|v| {
|
||||||
|
v.as_bool().map_err(|typ| {
|
||||||
|
self.make_type_mismatch_err::<bool>(typ, c.position())
|
||||||
|
})
|
||||||
|
})?
|
||||||
|
{
|
||||||
|
Some(&t.1)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Some(&t.1)
|
||||||
|
}
|
||||||
|
} 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
|
||||||
|
.eval_expr(scope, global, state, lib, this_ptr, &c, level)
|
||||||
|
.and_then(|v| {
|
||||||
|
v.as_bool().map_err(|typ| {
|
||||||
|
self.make_type_mismatch_err::<bool>(typ, c.position())
|
||||||
|
})
|
||||||
|
})?
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result = Some(stmt_block);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
result
|
||||||
|
} else {
|
||||||
|
// Nothing matches
|
||||||
|
None
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Non-hashable
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(statements) = stmt_block {
|
||||||
|
if !statements.is_empty() {
|
||||||
|
self.eval_stmt_block(
|
||||||
|
scope, global, state, lib, this_ptr, statements, true, level,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Ok(Dynamic::UNIT)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Default match clause
|
||||||
|
if !def_stmt.is_empty() {
|
||||||
|
self.eval_stmt_block(
|
||||||
|
scope, global, state, lib, this_ptr, def_stmt, true, level,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Ok(Dynamic::UNIT)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Loop
|
||||||
|
Stmt::While(Expr::Unit(_), body, _) => loop {
|
||||||
|
if !body.is_empty() {
|
||||||
|
match self
|
||||||
|
.eval_stmt_block(scope, global, state, lib, this_ptr, body, true, level)
|
||||||
|
{
|
||||||
|
Ok(_) => (),
|
||||||
|
Err(err) => match *err {
|
||||||
|
ERR::LoopBreak(false, _) => (),
|
||||||
|
ERR::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
|
||||||
|
_ => return Err(err),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
#[cfg(not(feature = "unchecked"))]
|
||||||
|
self.inc_operations(&mut global.num_operations, body.position())?;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// While loop
|
||||||
|
Stmt::While(expr, body, _) => loop {
|
||||||
|
let condition = self
|
||||||
|
.eval_expr(scope, global, state, lib, this_ptr, expr, level)?
|
||||||
|
.as_bool()
|
||||||
|
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, expr.position()))?;
|
||||||
|
|
||||||
|
if !condition {
|
||||||
|
return Ok(Dynamic::UNIT);
|
||||||
|
}
|
||||||
|
if !body.is_empty() {
|
||||||
|
match self
|
||||||
|
.eval_stmt_block(scope, global, state, lib, this_ptr, body, true, level)
|
||||||
|
{
|
||||||
|
Ok(_) => (),
|
||||||
|
Err(err) => match *err {
|
||||||
|
ERR::LoopBreak(false, _) => (),
|
||||||
|
ERR::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
|
||||||
|
_ => return Err(err),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// Do loop
|
||||||
|
Stmt::Do(body, expr, options, _) => loop {
|
||||||
|
let is_while = !options.contains(AST_OPTION_NEGATED);
|
||||||
|
|
||||||
|
if !body.is_empty() {
|
||||||
|
match self
|
||||||
|
.eval_stmt_block(scope, global, state, lib, this_ptr, body, true, level)
|
||||||
|
{
|
||||||
|
Ok(_) => (),
|
||||||
|
Err(err) => match *err {
|
||||||
|
ERR::LoopBreak(false, _) => continue,
|
||||||
|
ERR::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
|
||||||
|
_ => return Err(err),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let condition = self
|
||||||
|
.eval_expr(scope, global, state, lib, this_ptr, expr, level)?
|
||||||
|
.as_bool()
|
||||||
|
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, expr.position()))?;
|
||||||
|
|
||||||
|
if condition ^ is_while {
|
||||||
|
return Ok(Dynamic::UNIT);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// For loop
|
||||||
|
Stmt::For(expr, x, _) => {
|
||||||
|
let (Ident { name, .. }, counter, statements) = x.as_ref();
|
||||||
|
let iter_obj = self
|
||||||
|
.eval_expr(scope, global, state, lib, this_ptr, expr, level)?
|
||||||
|
.flatten();
|
||||||
|
let iter_type = iter_obj.type_id();
|
||||||
|
|
||||||
|
// 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
|
||||||
|
let func = self
|
||||||
|
.global_modules
|
||||||
|
.iter()
|
||||||
|
.find_map(|m| m.get_iter(iter_type))
|
||||||
|
.or_else(|| global.get_iter(iter_type))
|
||||||
|
.or_else(|| {
|
||||||
|
self.global_sub_modules
|
||||||
|
.values()
|
||||||
|
.find_map(|m| m.get_qualified_iter(iter_type))
|
||||||
|
});
|
||||||
|
|
||||||
|
if let Some(func) = func {
|
||||||
|
// Add the loop variables
|
||||||
|
let orig_scope_len = scope.len();
|
||||||
|
let counter_index = if let Some(counter) = counter {
|
||||||
|
scope.push(unsafe_cast_var_name_to_lifetime(&counter.name), 0 as INT);
|
||||||
|
scope.len() - 1
|
||||||
|
} else {
|
||||||
|
usize::MAX
|
||||||
|
};
|
||||||
|
scope.push(unsafe_cast_var_name_to_lifetime(name), ());
|
||||||
|
let index = scope.len() - 1;
|
||||||
|
|
||||||
|
for (x, iter_value) in func(iter_obj).enumerate() {
|
||||||
|
// Increment counter
|
||||||
|
if counter_index < usize::MAX {
|
||||||
|
#[cfg(not(feature = "unchecked"))]
|
||||||
|
if x > INT::MAX as usize {
|
||||||
|
return Err(ERR::ErrorArithmetic(
|
||||||
|
format!("for-loop counter overflow: {}", x),
|
||||||
|
counter.as_ref().expect("`Some`").pos,
|
||||||
|
)
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let value = iter_value.flatten();
|
||||||
|
|
||||||
|
#[cfg(not(feature = "no_closure"))]
|
||||||
|
{
|
||||||
|
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")]
|
||||||
|
{
|
||||||
|
*scope.get_mut_by_index(index) = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "unchecked"))]
|
||||||
|
self.inc_operations(&mut global.num_operations, statements.position())?;
|
||||||
|
|
||||||
|
if statements.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let result = self.eval_stmt_block(
|
||||||
|
scope, global, state, lib, this_ptr, statements, true, level,
|
||||||
|
);
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(_) => (),
|
||||||
|
Err(err) => match *err {
|
||||||
|
ERR::LoopBreak(false, _) => (),
|
||||||
|
ERR::LoopBreak(true, _) => break,
|
||||||
|
_ => return Err(err),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
scope.rewind(orig_scope_len);
|
||||||
|
Ok(Dynamic::UNIT)
|
||||||
|
} else {
|
||||||
|
Err(ERR::ErrorFor(expr.position()).into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Continue/Break statement
|
||||||
|
Stmt::BreakLoop(options, pos) => {
|
||||||
|
Err(ERR::LoopBreak(options.contains(AST_OPTION_BREAK_OUT), *pos).into())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try/Catch statement
|
||||||
|
Stmt::TryCatch(x, _) => {
|
||||||
|
let (try_stmt, err_var, catch_stmt) = x.as_ref();
|
||||||
|
|
||||||
|
let result = self
|
||||||
|
.eval_stmt_block(scope, global, state, lib, this_ptr, try_stmt, true, level)
|
||||||
|
.map(|_| Dynamic::UNIT);
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(_) => result,
|
||||||
|
Err(err) if err.is_pseudo_error() => Err(err),
|
||||||
|
Err(err) if !err.is_catchable() => Err(err),
|
||||||
|
Err(mut err) => {
|
||||||
|
let err_value = match *err {
|
||||||
|
ERR::ErrorRuntime(ref x, _) => x.clone(),
|
||||||
|
|
||||||
|
#[cfg(feature = "no_object")]
|
||||||
|
_ => {
|
||||||
|
err.take_position();
|
||||||
|
err.to_string().into()
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "no_object"))]
|
||||||
|
_ => {
|
||||||
|
let mut err_map = crate::Map::new();
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
if err_pos.is_none() {
|
||||||
|
// No position info
|
||||||
|
} else {
|
||||||
|
let line = err_pos.line().unwrap() as INT;
|
||||||
|
let position = if err_pos.is_beginning_of_line() {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
err_pos.position().unwrap()
|
||||||
|
} as INT;
|
||||||
|
err_map.insert("line".into(), line.into());
|
||||||
|
err_map.insert("position".into(), position.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
err.dump_fields(&mut err_map);
|
||||||
|
err_map.into()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let orig_scope_len = scope.len();
|
||||||
|
|
||||||
|
err_var.as_ref().map(|Ident { name, .. }| {
|
||||||
|
scope.push(unsafe_cast_var_name_to_lifetime(name), err_value)
|
||||||
|
});
|
||||||
|
|
||||||
|
let result = self.eval_stmt_block(
|
||||||
|
scope, global, state, lib, this_ptr, catch_stmt, true, level,
|
||||||
|
);
|
||||||
|
|
||||||
|
scope.rewind(orig_scope_len);
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(_) => Ok(Dynamic::UNIT),
|
||||||
|
Err(result_err) => match *result_err {
|
||||||
|
// Re-throw exception
|
||||||
|
ERR::ErrorRuntime(Dynamic(Union::Unit(_, _, _)), pos) => {
|
||||||
|
err.set_position(pos);
|
||||||
|
Err(err)
|
||||||
|
}
|
||||||
|
_ => Err(result_err),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Throw value
|
||||||
|
Stmt::Return(options, Some(expr), pos) if options.contains(AST_OPTION_BREAK_OUT) => {
|
||||||
|
Err(ERR::ErrorRuntime(
|
||||||
|
self.eval_expr(scope, global, state, lib, this_ptr, expr, level)?
|
||||||
|
.flatten(),
|
||||||
|
*pos,
|
||||||
|
)
|
||||||
|
.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Empty throw
|
||||||
|
Stmt::Return(options, None, pos) if options.contains(AST_OPTION_BREAK_OUT) => {
|
||||||
|
Err(ERR::ErrorRuntime(Dynamic::UNIT, *pos).into())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return value
|
||||||
|
Stmt::Return(_, Some(expr), pos) => Err(ERR::Return(
|
||||||
|
self.eval_expr(scope, global, state, lib, this_ptr, expr, level)?
|
||||||
|
.flatten(),
|
||||||
|
*pos,
|
||||||
|
)
|
||||||
|
.into()),
|
||||||
|
|
||||||
|
// Empty return
|
||||||
|
Stmt::Return(_, None, pos) => Err(ERR::Return(Dynamic::UNIT, *pos).into()),
|
||||||
|
|
||||||
|
// Let/const statement
|
||||||
|
Stmt::Var(expr, x, options, _) => {
|
||||||
|
let name = &x.name;
|
||||||
|
let entry_type = if options.contains(AST_OPTION_CONSTANT) {
|
||||||
|
AccessMode::ReadOnly
|
||||||
|
} else {
|
||||||
|
AccessMode::ReadWrite
|
||||||
|
};
|
||||||
|
let export = options.contains(AST_OPTION_PUBLIC);
|
||||||
|
|
||||||
|
let value = self
|
||||||
|
.eval_expr(scope, global, state, lib, this_ptr, expr, level)?
|
||||||
|
.flatten();
|
||||||
|
|
||||||
|
let (var_name, _alias): (Cow<'_, str>, _) = if !rewind_scope {
|
||||||
|
#[cfg(not(feature = "no_function"))]
|
||||||
|
#[cfg(not(feature = "no_module"))]
|
||||||
|
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
|
||||||
|
global.set_constant(name.clone(), value.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
(
|
||||||
|
name.to_string().into(),
|
||||||
|
if export { Some(name.clone()) } else { None },
|
||||||
|
)
|
||||||
|
} else if export {
|
||||||
|
unreachable!("exported variable not on global level");
|
||||||
|
} else {
|
||||||
|
(unsafe_cast_var_name_to_lifetime(name).into(), None)
|
||||||
|
};
|
||||||
|
|
||||||
|
scope.push_dynamic_value(var_name, entry_type, value);
|
||||||
|
|
||||||
|
#[cfg(not(feature = "no_module"))]
|
||||||
|
_alias.map(|alias| scope.add_entry_alias(scope.len() - 1, alias));
|
||||||
|
|
||||||
|
Ok(Dynamic::UNIT)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Import statement
|
||||||
|
#[cfg(not(feature = "no_module"))]
|
||||||
|
Stmt::Import(expr, export, _pos) => {
|
||||||
|
// Guard against too many modules
|
||||||
|
#[cfg(not(feature = "unchecked"))]
|
||||||
|
if global.num_modules_loaded >= self.max_modules() {
|
||||||
|
return Err(ERR::ErrorTooManyModules(*_pos).into());
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(path) = self
|
||||||
|
.eval_expr(scope, global, state, lib, this_ptr, &expr, level)?
|
||||||
|
.try_cast::<ImmutableString>()
|
||||||
|
{
|
||||||
|
use crate::ModuleResolver;
|
||||||
|
|
||||||
|
let source = match global.source.as_str() {
|
||||||
|
"" => None,
|
||||||
|
s => Some(s),
|
||||||
|
};
|
||||||
|
let path_pos = expr.position();
|
||||||
|
|
||||||
|
let module = global
|
||||||
|
.embedded_module_resolver
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|r| match r.resolve(self, source, &path, path_pos) {
|
||||||
|
Err(err) if matches!(*err, ERR::ErrorModuleNotFound(_, _)) => None,
|
||||||
|
result => Some(result),
|
||||||
|
})
|
||||||
|
.or_else(|| {
|
||||||
|
self.module_resolver
|
||||||
|
.as_ref()
|
||||||
|
.map(|r| r.resolve(self, source, &path, path_pos))
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| {
|
||||||
|
Err(ERR::ErrorModuleNotFound(path.to_string(), path_pos).into())
|
||||||
|
})?;
|
||||||
|
|
||||||
|
if let Some(name) = export.as_ref().map(|x| x.name.clone()) {
|
||||||
|
if !module.is_indexed() {
|
||||||
|
// Index the module (making a clone copy if necessary) if it is not indexed
|
||||||
|
let mut module = crate::func::native::shared_take_or_clone(module);
|
||||||
|
module.build_index();
|
||||||
|
global.push_module(name, module);
|
||||||
|
} else {
|
||||||
|
global.push_module(name, module);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
global.num_modules_loaded += 1;
|
||||||
|
|
||||||
|
Ok(Dynamic::UNIT)
|
||||||
|
} else {
|
||||||
|
Err(self.make_type_mismatch_err::<ImmutableString>("", expr.position()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Export statement
|
||||||
|
#[cfg(not(feature = "no_module"))]
|
||||||
|
Stmt::Export(list, _) => {
|
||||||
|
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(),
|
||||||
|
);
|
||||||
|
Ok(()) as RhaiResultOf<_>
|
||||||
|
} else {
|
||||||
|
Err(ERR::ErrorVariableNotFound(name.to_string(), *pos).into())
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
Ok(Dynamic::UNIT)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Share statement
|
||||||
|
#[cfg(not(feature = "no_closure"))]
|
||||||
|
Stmt::Share(name) => {
|
||||||
|
if let Some((index, _)) = scope.get_index(name) {
|
||||||
|
let val = scope.get_mut_by_index(index);
|
||||||
|
|
||||||
|
if !val.is_shared() {
|
||||||
|
// Replace the variable with a shared value.
|
||||||
|
*val = std::mem::take(val).into_shared();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Dynamic::UNIT)
|
||||||
|
}
|
||||||
|
|
||||||
|
_ => unreachable!("statement cannot be evaluated: {:?}", stmt),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
389
src/eval/target.rs
Normal file
389
src/eval/target.rs
Normal file
@ -0,0 +1,389 @@
|
|||||||
|
//! Type to hold a mutable reference to the target of an evaluation.
|
||||||
|
|
||||||
|
use crate::types::dynamic::Variant;
|
||||||
|
use crate::{Dynamic, ImmutableString, Position, RhaiResultOf, ERR, INT};
|
||||||
|
#[cfg(feature = "no_std")]
|
||||||
|
use std::prelude::v1::*;
|
||||||
|
use std::{
|
||||||
|
any::TypeId,
|
||||||
|
ops::{Deref, DerefMut},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A type that encapsulates a mutation target for an expression with side effects.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum Target<'a> {
|
||||||
|
/// The target is a mutable reference to a [`Dynamic`].
|
||||||
|
RefMut(&'a mut Dynamic),
|
||||||
|
/// The target is a mutable reference to a _shared_ [`Dynamic`].
|
||||||
|
#[cfg(not(feature = "no_closure"))]
|
||||||
|
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).
|
||||||
|
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"))]
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
/// 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"))]
|
||||||
|
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].
|
||||||
|
/// This is necessary because directly pointing to a byte (in [`Dynamic`] form) inside a blob is impossible.
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
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.
|
||||||
|
/// This is necessary because directly pointing to a char inside a String is impossible.
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Target<'a> {
|
||||||
|
/// Is the [`Target`] a reference pointing to other data?
|
||||||
|
#[allow(dead_code)]
|
||||||
|
#[inline]
|
||||||
|
#[must_use]
|
||||||
|
pub const fn is_ref(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Self::RefMut(_) => true,
|
||||||
|
#[cfg(not(feature = "no_closure"))]
|
||||||
|
Self::SharedValue { .. } => true,
|
||||||
|
Self::TempValue(_) => false,
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::Bit { .. }
|
||||||
|
| Self::BitField { .. }
|
||||||
|
| Self::BlobByte { .. }
|
||||||
|
| Self::StringChar { .. } => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Is the [`Target`] a temp value?
|
||||||
|
#[inline]
|
||||||
|
#[must_use]
|
||||||
|
pub const fn is_temp_value(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Self::RefMut(_) => false,
|
||||||
|
#[cfg(not(feature = "no_closure"))]
|
||||||
|
Self::SharedValue { .. } => false,
|
||||||
|
Self::TempValue(_) => true,
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::Bit { .. }
|
||||||
|
| Self::BitField { .. }
|
||||||
|
| Self::BlobByte { .. }
|
||||||
|
| Self::StringChar { .. } => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Is the [`Target`] a shared value?
|
||||||
|
#[cfg(not(feature = "no_closure"))]
|
||||||
|
#[inline]
|
||||||
|
#[must_use]
|
||||||
|
pub fn is_shared(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Self::RefMut(r) => r.is_shared(),
|
||||||
|
#[cfg(not(feature = "no_closure"))]
|
||||||
|
Self::SharedValue { .. } => true,
|
||||||
|
Self::TempValue(r) => r.is_shared(),
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::Bit { .. }
|
||||||
|
| Self::BitField { .. }
|
||||||
|
| Self::BlobByte { .. }
|
||||||
|
| Self::StringChar { .. } => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Is the [`Target`] a specific type?
|
||||||
|
#[allow(dead_code)]
|
||||||
|
#[inline]
|
||||||
|
#[must_use]
|
||||||
|
pub fn is<T: Variant + Clone>(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Self::RefMut(r) => r.is::<T>(),
|
||||||
|
#[cfg(not(feature = "no_closure"))]
|
||||||
|
Self::SharedValue { source, .. } => source.is::<T>(),
|
||||||
|
Self::TempValue(r) => r.is::<T>(),
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::Bit { .. } => TypeId::of::<T>() == TypeId::of::<bool>(),
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::BitField { .. } => TypeId::of::<T>() == TypeId::of::<INT>(),
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::BlobByte { .. } => TypeId::of::<T>() == TypeId::of::<crate::Blob>(),
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::StringChar { .. } => TypeId::of::<T>() == TypeId::of::<char>(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Get the value of the [`Target`] as a [`Dynamic`], cloning a referenced value if necessary.
|
||||||
|
#[inline]
|
||||||
|
#[must_use]
|
||||||
|
pub fn take_or_clone(self) -> Dynamic {
|
||||||
|
match self {
|
||||||
|
Self::RefMut(r) => r.clone(), // Referenced value is cloned
|
||||||
|
#[cfg(not(feature = "no_closure"))]
|
||||||
|
Self::SharedValue { value, .. } => value, // Original shared value is simply taken
|
||||||
|
Self::TempValue(v) => v, // Owned value is simply taken
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::Bit { value, .. } => value, // boolean is taken
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::BitField { value, .. } => value, // INT is taken
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::BlobByte { value, .. } => value, // byte is taken
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::StringChar { value, .. } => value, // char is taken
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Take a `&mut Dynamic` reference from the `Target`.
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub fn take_ref(self) -> Option<&'a mut Dynamic> {
|
||||||
|
match self {
|
||||||
|
Self::RefMut(r) => Some(r),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Convert a shared or reference [`Target`] into a target with an owned value.
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Get the source [`Dynamic`] of the [`Target`].
|
||||||
|
#[allow(dead_code)]
|
||||||
|
#[inline]
|
||||||
|
#[must_use]
|
||||||
|
pub fn source(&self) -> &Dynamic {
|
||||||
|
match self {
|
||||||
|
Self::RefMut(r) => *r,
|
||||||
|
#[cfg(not(feature = "no_closure"))]
|
||||||
|
Self::SharedValue { source, .. } => source,
|
||||||
|
Self::TempValue(v) => v,
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::Bit { source, .. } => source,
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::BitField { source, .. } => source,
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::BlobByte { source, .. } => source,
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::StringChar { source, .. } => source,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// 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"))]
|
||||||
|
Self::SharedValue { .. } => (),
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::Bit { source, value, bit } => {
|
||||||
|
// Replace the bit at the specified index position
|
||||||
|
let new_bit = value.as_bool().map_err(|err| {
|
||||||
|
Box::new(ERR::ErrorMismatchDataType(
|
||||||
|
"bool".to_string(),
|
||||||
|
err.to_string(),
|
||||||
|
Position::NONE,
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let value = &mut *source.write_lock::<crate::INT>().expect("`INT`");
|
||||||
|
|
||||||
|
let index = *bit;
|
||||||
|
|
||||||
|
let mask = 1 << index;
|
||||||
|
if new_bit {
|
||||||
|
*value |= mask;
|
||||||
|
} else {
|
||||||
|
*value &= !mask;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::BitField {
|
||||||
|
source,
|
||||||
|
value,
|
||||||
|
mask,
|
||||||
|
shift,
|
||||||
|
} => {
|
||||||
|
let shift = *shift;
|
||||||
|
let mask = *mask;
|
||||||
|
|
||||||
|
// Replace the bit at the specified index position
|
||||||
|
let new_value = value.as_int().map_err(|err| {
|
||||||
|
Box::new(ERR::ErrorMismatchDataType(
|
||||||
|
"integer".to_string(),
|
||||||
|
err.to_string(),
|
||||||
|
Position::NONE,
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let new_value = (new_value << shift) & mask;
|
||||||
|
let value = &mut *source.write_lock::<crate::INT>().expect("`INT`");
|
||||||
|
|
||||||
|
*value &= !mask;
|
||||||
|
*value |= new_value;
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::BlobByte {
|
||||||
|
source,
|
||||||
|
value,
|
||||||
|
index,
|
||||||
|
} => {
|
||||||
|
// Replace the byte at the specified index position
|
||||||
|
let new_byte = value.as_int().map_err(|err| {
|
||||||
|
Box::new(ERR::ErrorMismatchDataType(
|
||||||
|
"INT".to_string(),
|
||||||
|
err.to_string(),
|
||||||
|
Position::NONE,
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let value = &mut *source.write_lock::<crate::Blob>().expect("`Blob`");
|
||||||
|
|
||||||
|
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"))]
|
||||||
|
Self::StringChar {
|
||||||
|
source,
|
||||||
|
value,
|
||||||
|
index,
|
||||||
|
} => {
|
||||||
|
// Replace the character at the specified index position
|
||||||
|
let new_ch = value.as_char().map_err(|err| {
|
||||||
|
Box::new(ERR::ErrorMismatchDataType(
|
||||||
|
"char".to_string(),
|
||||||
|
err.to_string(),
|
||||||
|
Position::NONE,
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let s = &mut *source
|
||||||
|
.write_lock::<ImmutableString>()
|
||||||
|
.expect("`ImmutableString`");
|
||||||
|
|
||||||
|
let index = *index;
|
||||||
|
|
||||||
|
*s = s
|
||||||
|
.chars()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, ch)| if i == index { new_ch } else { ch })
|
||||||
|
.collect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
let val = value.clone();
|
||||||
|
let source = value.write_lock::<Dynamic>().expect("`Dynamic`");
|
||||||
|
return Self::SharedValue { source, value: val };
|
||||||
|
}
|
||||||
|
|
||||||
|
Self::RefMut(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deref for Target<'_> {
|
||||||
|
type Target = Dynamic;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn deref(&self) -> &Dynamic {
|
||||||
|
match self {
|
||||||
|
Self::RefMut(r) => *r,
|
||||||
|
#[cfg(not(feature = "no_closure"))]
|
||||||
|
Self::SharedValue { source, .. } => &**source,
|
||||||
|
Self::TempValue(ref r) => r,
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::Bit { ref value, .. }
|
||||||
|
| Self::BitField { ref value, .. }
|
||||||
|
| Self::BlobByte { ref value, .. }
|
||||||
|
| Self::StringChar { ref value, .. } => value,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsRef<Dynamic> for Target<'_> {
|
||||||
|
#[inline(always)]
|
||||||
|
fn as_ref(&self) -> &Dynamic {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DerefMut for Target<'_> {
|
||||||
|
#[inline]
|
||||||
|
fn deref_mut(&mut self) -> &mut Dynamic {
|
||||||
|
match self {
|
||||||
|
Self::RefMut(r) => *r,
|
||||||
|
#[cfg(not(feature = "no_closure"))]
|
||||||
|
Self::SharedValue { source, .. } => &mut *source,
|
||||||
|
Self::TempValue(ref mut r) => r,
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Self::Bit { ref mut value, .. }
|
||||||
|
| Self::BitField { ref mut value, .. }
|
||||||
|
| Self::BlobByte { ref mut value, .. }
|
||||||
|
| Self::StringChar { ref mut value, .. } => value,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsMut<Dynamic> for Target<'_> {
|
||||||
|
#[inline(always)]
|
||||||
|
fn as_mut(&mut self) -> &mut Dynamic {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Into<Dynamic>> From<T> for Target<'_> {
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
fn from(value: T) -> Self {
|
||||||
|
Self::TempValue(value.into())
|
||||||
|
}
|
||||||
|
}
|
@ -6,9 +6,10 @@ use super::{get_builtin_binary_op_fn, get_builtin_op_assignment_fn};
|
|||||||
use crate::api::default_limits::MAX_DYNAMIC_PARAMETERS;
|
use crate::api::default_limits::MAX_DYNAMIC_PARAMETERS;
|
||||||
use crate::ast::{Expr, FnCallHashes, Stmt};
|
use crate::ast::{Expr, FnCallHashes, Stmt};
|
||||||
use crate::engine::{
|
use crate::engine::{
|
||||||
EvalState, GlobalRuntimeState, KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR,
|
KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, KEYWORD_FN_PTR_CALL, KEYWORD_FN_PTR_CURRY,
|
||||||
KEYWORD_FN_PTR_CALL, KEYWORD_FN_PTR_CURRY, KEYWORD_IS_DEF_VAR, KEYWORD_PRINT, KEYWORD_TYPE_OF,
|
KEYWORD_IS_DEF_VAR, KEYWORD_PRINT, KEYWORD_TYPE_OF,
|
||||||
};
|
};
|
||||||
|
use crate::eval::{EvalState, GlobalRuntimeState};
|
||||||
use crate::module::Namespace;
|
use crate::module::Namespace;
|
||||||
use crate::tokenizer::Token;
|
use crate::tokenizer::Token;
|
||||||
use crate::{
|
use crate::{
|
||||||
@ -720,7 +721,7 @@ impl Engine {
|
|||||||
lib: &[&Module],
|
lib: &[&Module],
|
||||||
fn_name: &str,
|
fn_name: &str,
|
||||||
mut hash: FnCallHashes,
|
mut hash: FnCallHashes,
|
||||||
target: &mut crate::engine::Target,
|
target: &mut crate::eval::Target,
|
||||||
(call_args, call_arg_pos): &mut (FnArgsVec<Dynamic>, Position),
|
(call_args, call_arg_pos): &mut (FnArgsVec<Dynamic>, Position),
|
||||||
pos: Position,
|
pos: Position,
|
||||||
level: usize,
|
level: usize,
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
use super::call::FnCallArgs;
|
use super::call::FnCallArgs;
|
||||||
use crate::ast::FnCallHashes;
|
use crate::ast::FnCallHashes;
|
||||||
use crate::engine::{EvalState, GlobalRuntimeState};
|
use crate::eval::{EvalState, GlobalRuntimeState};
|
||||||
use crate::plugin::PluginFunction;
|
use crate::plugin::PluginFunction;
|
||||||
use crate::tokenizer::{Token, TokenizeState};
|
use crate::tokenizer::{Token, TokenizeState};
|
||||||
use crate::types::dynamic::Variant;
|
use crate::types::dynamic::Variant;
|
||||||
|
@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
use super::call::FnCallArgs;
|
use super::call::FnCallArgs;
|
||||||
use crate::ast::ScriptFnDef;
|
use crate::ast::ScriptFnDef;
|
||||||
use crate::engine::{EvalState, GlobalRuntimeState};
|
use crate::eval::{EvalState, GlobalRuntimeState};
|
||||||
use crate::r#unsafe::unsafe_cast_var_name_to_lifetime;
|
use crate::r#unsafe::unsafe_cast_var_name_to_lifetime;
|
||||||
use crate::{Dynamic, Engine, Module, Position, RhaiError, RhaiResult, Scope, StaticVec, ERR};
|
use crate::{Dynamic, Engine, Module, Position, RhaiError, RhaiResult, Scope, StaticVec, ERR};
|
||||||
use std::mem;
|
use std::mem;
|
||||||
|
@ -72,6 +72,7 @@ use std::prelude::v1::*;
|
|||||||
mod api;
|
mod api;
|
||||||
mod ast;
|
mod ast;
|
||||||
mod engine;
|
mod engine;
|
||||||
|
mod eval;
|
||||||
mod func;
|
mod func;
|
||||||
mod module;
|
mod module;
|
||||||
mod optimizer;
|
mod optimizer;
|
||||||
@ -145,7 +146,8 @@ type InclusiveRange = std::ops::RangeInclusive<INT>;
|
|||||||
|
|
||||||
pub use api::custom_syntax::Expression;
|
pub use api::custom_syntax::Expression;
|
||||||
pub use ast::{FnAccess, AST};
|
pub use ast::{FnAccess, AST};
|
||||||
pub use engine::{Engine, EvalContext, OP_CONTAINS, OP_EQUALS};
|
pub use engine::{Engine, OP_CONTAINS, OP_EQUALS};
|
||||||
|
pub use eval::EvalContext;
|
||||||
pub use func::{NativeCallContext, RegisterNativeFunction};
|
pub use func::{NativeCallContext, RegisterNativeFunction};
|
||||||
pub use module::{FnNamespace, Module};
|
pub use module::{FnNamespace, Module};
|
||||||
pub use tokenizer::Position;
|
pub use tokenizer::Position;
|
||||||
@ -246,7 +248,7 @@ pub use ast::{
|
|||||||
pub use ast::FloatWrapper;
|
pub use ast::FloatWrapper;
|
||||||
|
|
||||||
#[cfg(feature = "internals")]
|
#[cfg(feature = "internals")]
|
||||||
pub use engine::{EvalState, GlobalRuntimeState};
|
pub use eval::{EvalState, GlobalRuntimeState};
|
||||||
|
|
||||||
#[cfg(feature = "internals")]
|
#[cfg(feature = "internals")]
|
||||||
pub use func::call::{FnResolutionCache, FnResolutionCacheEntry};
|
pub use func::call::{FnResolutionCache, FnResolutionCacheEntry};
|
||||||
|
@ -1554,7 +1554,7 @@ impl Module {
|
|||||||
engine: &crate::Engine,
|
engine: &crate::Engine,
|
||||||
) -> RhaiResultOf<Self> {
|
) -> RhaiResultOf<Self> {
|
||||||
let mut scope = scope;
|
let mut scope = scope;
|
||||||
let mut global = crate::engine::GlobalRuntimeState::new();
|
let mut global = crate::eval::GlobalRuntimeState::new();
|
||||||
let orig_mods_len = global.num_imported_modules();
|
let orig_mods_len = global.num_imported_modules();
|
||||||
|
|
||||||
// Run the script
|
// Run the script
|
||||||
|
@ -2,10 +2,8 @@
|
|||||||
#![cfg(not(feature = "no_optimize"))]
|
#![cfg(not(feature = "no_optimize"))]
|
||||||
|
|
||||||
use crate::ast::{Expr, OpAssignment, Stmt, AST_OPTION_FLAGS::*};
|
use crate::ast::{Expr, OpAssignment, Stmt, AST_OPTION_FLAGS::*};
|
||||||
use crate::engine::{
|
use crate::engine::{KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, KEYWORD_PRINT, KEYWORD_TYPE_OF};
|
||||||
EvalState, GlobalRuntimeState, KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, KEYWORD_PRINT,
|
use crate::eval::{EvalState, GlobalRuntimeState};
|
||||||
KEYWORD_TYPE_OF,
|
|
||||||
};
|
|
||||||
use crate::func::builtin::get_builtin_binary_op_fn;
|
use crate::func::builtin::get_builtin_binary_op_fn;
|
||||||
use crate::func::hashing::get_hasher;
|
use crate::func::hashing::get_hasher;
|
||||||
use crate::tokenizer::Token;
|
use crate::tokenizer::Token;
|
||||||
|
Loading…
Reference in New Issue
Block a user