Merge pull request #554 from schungx/master

New enhancements.
This commit is contained in:
Stephen Chung 2022-04-21 16:16:16 +08:00 committed by GitHub
commit cfc02b9408
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 992 additions and 792 deletions

View File

@ -9,6 +9,20 @@ Bug fixes
* Compound assignments now work properly with indexers. * Compound assignments now work properly with indexers.
Script-breaking changes
-----------------------
* _Strict Variables Mode_ no longer returns an error when an undeclared variable matches a constant in the provided external `Scope`.
Enhancements
------------
* `Module::eval_ast_as_new_raw` is made public as a low-level API.
* Improper `switch` case condition syntax is now caught at parse time.
* `Engine::parse_json` now natively handles nested JSON inputs (using a token remap filter) without needing to replace `{` with `#{`.
* `to_json` is added to object maps to cheaply convert it to JSON format (`()` is mapped to `null`, all other data types must be supported by JSON)
* A global function `format_map_as_json` is provided which is the same as `to_json` for object maps.
Version 1.6.1 Version 1.6.1
============= =============

View File

@ -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::eval::{EvalState, GlobalRuntimeState}; use crate::eval::{Caches, 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,
@ -149,7 +149,7 @@ impl Engine {
this_ptr: Option<&mut Dynamic>, this_ptr: Option<&mut Dynamic>,
arg_values: impl AsMut<[Dynamic]>, arg_values: impl AsMut<[Dynamic]>,
) -> RhaiResult { ) -> RhaiResult {
let state = &mut EvalState::new(); let caches = &mut Caches::new();
let global = &mut GlobalRuntimeState::new(self); let global = &mut GlobalRuntimeState::new(self);
let statements = ast.statements(); let statements = ast.statements();
@ -157,7 +157,7 @@ impl Engine {
let orig_scope_len = scope.len(); let orig_scope_len = scope.len();
if eval_ast && !statements.is_empty() { if eval_ast && !statements.is_empty() {
self.eval_global_statements(scope, global, state, statements, &[ast.as_ref()], 0)?; self.eval_global_statements(scope, global, caches, statements, &[ast.as_ref()], 0)?;
if rewind_scope { if rewind_scope {
scope.rewind(orig_scope_len); scope.rewind(orig_scope_len);
@ -181,7 +181,7 @@ impl Engine {
self.call_script_fn( self.call_script_fn(
scope, scope,
global, global,
state, caches,
&[ast.as_ref()], &[ast.as_ref()],
&mut this_ptr, &mut this_ptr,
fn_def, fn_def,

View File

@ -225,13 +225,8 @@ impl Engine {
scripts.as_ref(), scripts.as_ref(),
self.token_mapper.as_ref().map(Box::as_ref), self.token_mapper.as_ref().map(Box::as_ref),
); );
let mut state = ParseState::new(self, tokenizer_control); let mut state = ParseState::new(self, scope, tokenizer_control);
self.parse( self.parse(&mut stream.peekable(), &mut state, optimization_level)
&mut stream.peekable(),
&mut state,
scope,
optimization_level,
)
} }
/// Compile a string containing an expression into an [`AST`], /// Compile a string containing an expression into an [`AST`],
/// which can be used later for evaluation. /// which can be used later for evaluation.
@ -300,118 +295,7 @@ impl Engine {
self.lex_raw(&scripts, self.token_mapper.as_ref().map(Box::as_ref)); self.lex_raw(&scripts, self.token_mapper.as_ref().map(Box::as_ref));
let mut peekable = stream.peekable(); let mut peekable = stream.peekable();
let mut state = ParseState::new(self, tokenizer_control); let mut state = ParseState::new(self, scope, tokenizer_control);
self.parse_global_expr( self.parse_global_expr(&mut peekable, &mut state, self.options.optimization_level)
&mut peekable,
&mut state,
scope,
self.options.optimization_level,
)
}
/// Parse a JSON string into an [object map][crate::Map].
/// This is a light-weight alternative to using, say,
/// [`serde_json`](https://crates.io/crates/serde_json) to deserialize the JSON.
///
/// Not available under `no_object`.
///
/// The JSON string must be an object hash. It cannot be a simple scalar value.
///
/// Set `has_null` to `true` in order to map `null` values to `()`.
/// Setting it to `false` will cause an [`ErrorVariableNotFound`][crate::EvalAltResult::ErrorVariableNotFound] error during parsing.
///
/// # JSON With Sub-Objects
///
/// This method assumes no sub-objects in the JSON string. That is because the syntax
/// of a JSON sub-object (or object hash), `{ .. }`, is different from Rhai's syntax, `#{ .. }`.
/// Parsing a JSON string with sub-objects will cause a syntax error.
///
/// If it is certain that the character `{` never appears in any text string within the JSON object,
/// which is a valid assumption for many use cases, then globally replace `{` with `#{` before calling this method.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, Map};
///
/// let engine = Engine::new();
///
/// let map = engine.parse_json(
/// r#"{"a":123, "b":42, "c":{"x":false, "y":true}, "d":null}"#
/// .replace("{", "#{").as_str(),
/// true)?;
///
/// assert_eq!(map.len(), 4);
/// assert_eq!(map["a"].as_int().expect("a should exist"), 123);
/// assert_eq!(map["b"].as_int().expect("b should exist"), 42);
/// assert!(map["d"].is::<()>());
///
/// let c = map["c"].read_lock::<Map>().expect("c should exist");
/// assert_eq!(c["x"].as_bool().expect("x should be bool"), false);
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_object"))]
#[inline(always)]
pub fn parse_json(
&self,
json: impl AsRef<str>,
has_null: bool,
) -> crate::RhaiResultOf<crate::Map> {
use crate::tokenizer::Token;
fn parse_json_inner(
engine: &Engine,
json: &str,
has_null: bool,
) -> crate::RhaiResultOf<crate::Map> {
let mut scope = Scope::new();
let json_text = json.trim_start();
let scripts = if json_text.starts_with(Token::MapStart.literal_syntax()) {
[json_text, ""]
} else if json_text.starts_with(Token::LeftBrace.literal_syntax()) {
["#", json_text]
} else {
return Err(crate::PERR::MissingToken(
Token::LeftBrace.syntax().into(),
"to start a JSON object hash".into(),
)
.into_err(crate::Position::new(
1,
(json.len() - json_text.len() + 1) as u16,
))
.into());
};
let (stream, tokenizer_control) = engine.lex_raw(
&scripts,
if has_null {
Some(&|token, _, _| {
match token {
// If `null` is present, make sure `null` is treated as a variable
Token::Reserved(s) if &*s == "null" => Token::Identifier(s),
_ => token,
}
})
} else {
None
},
);
let mut state = ParseState::new(engine, tokenizer_control);
let ast = engine.parse_global_expr(
&mut stream.peekable(),
&mut state,
&scope,
#[cfg(not(feature = "no_optimize"))]
OptimizationLevel::None,
#[cfg(feature = "no_optimize")]
OptimizationLevel::default(),
)?;
if has_null {
scope.push_constant("null", ());
}
engine.eval_ast_with_scope(&mut scope, &ast)
}
parse_json_inner(self, json.as_ref(), has_null)
} }
} }

View File

@ -1,6 +1,7 @@
//! Module implementing custom syntax for [`Engine`]. //! Module implementing custom syntax for [`Engine`].
use crate::ast::Expr; use crate::ast::Expr;
use crate::eval::Caches;
use crate::func::native::SendSync; use crate::func::native::SendSync;
use crate::parser::ParseResult; use crate::parser::ParseResult;
use crate::tokenizer::{is_valid_identifier, Token}; use crate::tokenizer::{is_valid_identifier, Token};
@ -130,7 +131,7 @@ impl Deref for Expression<'_> {
} }
} }
impl EvalContext<'_, '_, '_, '_, '_, '_, '_, '_, '_, '_> { impl EvalContext<'_, '_, '_, '_, '_, '_, '_, '_> {
/// Evaluate an [expression tree][Expression]. /// Evaluate an [expression tree][Expression].
/// ///
/// # WARNING - Low Level API /// # WARNING - Low Level API
@ -138,10 +139,18 @@ impl EvalContext<'_, '_, '_, '_, '_, '_, '_, '_, '_, '_> {
/// This function is very low level. It evaluates an expression from an [`AST`][crate::AST]. /// This function is very low level. It evaluates an expression from an [`AST`][crate::AST].
#[inline(always)] #[inline(always)]
pub fn eval_expression_tree(&mut self, expr: &Expression) -> RhaiResult { pub fn eval_expression_tree(&mut self, expr: &Expression) -> RhaiResult {
let mut caches;
self.engine.eval_expr( self.engine.eval_expr(
self.scope, self.scope,
self.global, self.global,
self.state, match self.caches.as_mut() {
Some(c) => c,
None => {
caches = Caches::new();
&mut caches
}
},
self.lib, self.lib,
self.this_ptr, self.this_ptr,
expr, expr,

View File

@ -1,6 +1,6 @@
//! Module that defines the public evaluation API of [`Engine`]. //! Module that defines the public evaluation API of [`Engine`].
use crate::eval::{EvalState, GlobalRuntimeState}; use crate::eval::{Caches, GlobalRuntimeState};
use crate::parser::ParseState; use crate::parser::ParseState;
use crate::types::dynamic::Variant; use crate::types::dynamic::Variant;
use crate::{ use crate::{
@ -116,13 +116,12 @@ impl Engine {
let scripts = [script]; let scripts = [script];
let (stream, tokenizer_control) = let (stream, tokenizer_control) =
self.lex_raw(&scripts, self.token_mapper.as_ref().map(Box::as_ref)); self.lex_raw(&scripts, self.token_mapper.as_ref().map(Box::as_ref));
let mut state = ParseState::new(self, tokenizer_control); let mut state = ParseState::new(self, scope, tokenizer_control);
// No need to optimize a lone expression // No need to optimize a lone expression
let ast = self.parse_global_expr( let ast = self.parse_global_expr(
&mut stream.peekable(), &mut stream.peekable(),
&mut state, &mut state,
scope,
#[cfg(not(feature = "no_optimize"))] #[cfg(not(feature = "no_optimize"))]
OptimizationLevel::None, OptimizationLevel::None,
#[cfg(feature = "no_optimize")] #[cfg(feature = "no_optimize")]
@ -208,7 +207,7 @@ impl Engine {
ast: &'a AST, ast: &'a AST,
level: usize, level: usize,
) -> RhaiResult { ) -> RhaiResult {
let mut state = EvalState::new(); let mut caches = Caches::new();
global.source = ast.source_raw().clone(); global.source = ast.source_raw().clone();
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
@ -231,6 +230,6 @@ impl Engine {
} else { } else {
&lib[..] &lib[..]
}; };
self.eval_global_statements(scope, global, &mut state, statements, lib, level) self.eval_global_statements(scope, global, &mut caches, statements, lib, level)
} }
} }

181
src/api/json.rs Normal file
View File

@ -0,0 +1,181 @@
//! Module that defines JSON manipulation functions for [`Engine`].
#![cfg(not(feature = "no_object"))]
use crate::parser::ParseState;
use crate::tokenizer::Token;
use crate::{Engine, LexError, Map, OptimizationLevel, RhaiResultOf, Scope};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
impl Engine {
/// Parse a JSON string into an [object map][Map].
///
/// This is a light-weight alternative to using, say, [`serde_json`](https://crates.io/crates/serde_json)
/// to deserialize the JSON.
///
/// Not available under `no_object`.
///
/// The JSON string must be an object hash. It cannot be a simple primitive value.
///
/// Set `has_null` to `true` in order to map `null` values to `()`.
/// Setting it to `false` causes a syntax error for any `null` value.
///
/// JSON sub-objects are handled transparently.
///
/// This function can be used together with [`format_map_as_json`] to work with JSON texts
/// without using the [`serde`](https://crates.io/crates/serde) crate (which is heavy).
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, Map};
///
/// let engine = Engine::new();
///
/// let map = engine.parse_json(r#"
/// {
/// "a": 123,
/// "b": 42,
/// "c": {
/// "x": false,
/// "y": true,
/// "z": '$'
/// },
/// "d": null
/// }"#, true)?;
///
/// assert_eq!(map.len(), 4);
/// assert_eq!(map["a"].as_int().expect("a should exist"), 123);
/// assert_eq!(map["b"].as_int().expect("b should exist"), 42);
/// assert_eq!(map["d"].as_unit().expect("d should exist"), ());
///
/// let c = map["c"].read_lock::<Map>().expect("c should exist");
/// assert_eq!(c["x"].as_bool().expect("x should be bool"), false);
/// assert_eq!(c["y"].as_bool().expect("y should be bool"), true);
/// assert_eq!(c["z"].as_char().expect("z should be char"), '$');
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn parse_json(&self, json: impl AsRef<str>, has_null: bool) -> RhaiResultOf<Map> {
let scripts = [json.as_ref()];
let (stream, tokenizer_control) = self.lex_raw(
&scripts,
if has_null {
Some(&|token, _, _| {
match token {
// `null` => `()`
Token::Reserved(s) if &*s == "null" => Token::Unit,
// `{` => `#{`
Token::LeftBrace => Token::MapStart,
// Disallowed syntax
t @ (Token::Unit | Token::MapStart) => Token::LexError(
LexError::ImproperSymbol(
t.literal_syntax().to_string(),
"".to_string(),
)
.into(),
),
Token::InterpolatedString(..) => Token::LexError(
LexError::ImproperSymbol(
"interpolated string".to_string(),
"".to_string(),
)
.into(),
),
// All others
_ => token,
}
})
} else {
Some(&|token, _, _| {
match token {
Token::Reserved(s) if &*s == "null" => Token::LexError(
LexError::ImproperSymbol("null".to_string(), "".to_string()).into(),
),
// `{` => `#{`
Token::LeftBrace => Token::MapStart,
// Disallowed syntax
t @ (Token::Unit | Token::MapStart) => Token::LexError(
LexError::ImproperSymbol(
t.literal_syntax().to_string(),
"Invalid JSON syntax".to_string(),
)
.into(),
),
Token::InterpolatedString(..) => Token::LexError(
LexError::ImproperSymbol(
"interpolated string".to_string(),
"Invalid JSON syntax".to_string(),
)
.into(),
),
// All others
_ => token,
}
})
},
);
let scope = &Scope::new();
let mut state = ParseState::new(self, scope, tokenizer_control);
let ast = self.parse_global_expr(
&mut stream.peekable(),
&mut state,
#[cfg(not(feature = "no_optimize"))]
OptimizationLevel::None,
#[cfg(feature = "no_optimize")]
OptimizationLevel::default(),
)?;
self.eval_ast(&ast)
}
}
/// Return the JSON representation of an [object map][Map].
///
/// Not available under `no_std`.
///
/// This function can be used together with [`Engine::parse_json`] to work with JSON texts
/// without using the [`serde`](https://crates.io/crates/serde) crate (which is heavy).
///
/// # Data types
///
/// Only the following data types should be kept inside the object map: [`INT`][crate::INT],
/// [`FLOAT`][crate::FLOAT], [`ImmutableString`][crate::ImmutableString], `char`, `bool`, `()`,
/// [`Array`][crate::Array], [`Map`].
///
/// # Errors
///
/// Data types not supported by JSON serialize into formats that may invalidate the result.
#[inline]
pub fn format_map_as_json(map: &Map) -> String {
let mut result = String::from('{');
for (key, value) in map {
if result.len() > 1 {
result.push(',');
}
result.push_str(&format!("{:?}", key));
result.push(':');
if let Some(val) = value.read_lock::<Map>() {
result.push_str(&format_map_as_json(&*val));
continue;
}
if value.is::<()>() {
result.push_str("null");
} else {
result.push_str(&format!("{:?}", value));
}
}
result.push('}');
result
}

View File

@ -8,6 +8,8 @@ pub mod run;
pub mod compile; pub mod compile;
pub mod json;
pub mod files; pub mod files;
pub mod register; pub mod register;

View File

@ -1,6 +1,6 @@
//! Module that defines the public evaluation API of [`Engine`]. //! Module that defines the public evaluation API of [`Engine`].
use crate::eval::{EvalState, GlobalRuntimeState}; use crate::eval::{Caches, 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")]
@ -24,12 +24,11 @@ impl Engine {
let scripts = [script]; let scripts = [script];
let (stream, tokenizer_control) = let (stream, tokenizer_control) =
self.lex_raw(&scripts, self.token_mapper.as_ref().map(Box::as_ref)); self.lex_raw(&scripts, self.token_mapper.as_ref().map(Box::as_ref));
let mut state = ParseState::new(self, tokenizer_control); let mut state = ParseState::new(self, scope, tokenizer_control);
let ast = self.parse( let ast = self.parse(
&mut stream.peekable(), &mut stream.peekable(),
&mut state, &mut state,
scope,
self.options.optimization_level, self.options.optimization_level,
)?; )?;
@ -43,7 +42,7 @@ impl Engine {
/// Evaluate an [`AST`] with own scope, returning any error (if any). /// Evaluate an [`AST`] with own scope, returning any error (if any).
#[inline] #[inline]
pub fn run_ast_with_scope(&self, scope: &mut Scope, ast: &AST) -> RhaiResultOf<()> { pub fn run_ast_with_scope(&self, scope: &mut Scope, ast: &AST) -> RhaiResultOf<()> {
let state = &mut EvalState::new(); let caches = &mut Caches::new();
let global = &mut GlobalRuntimeState::new(self); let global = &mut GlobalRuntimeState::new(self);
global.source = ast.source_raw().clone(); global.source = ast.source_raw().clone();
@ -63,7 +62,7 @@ impl Engine {
} else { } else {
&lib &lib
}; };
self.eval_global_statements(scope, global, state, statements, lib, 0)?; self.eval_global_statements(scope, global, caches, statements, lib, 0)?;
} }
Ok(()) Ok(())
} }

View File

@ -832,6 +832,7 @@ impl Expr {
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Token::LeftBracket => true, Token::LeftBracket => true,
Token::LeftParen => true, Token::LeftParen => true,
Token::Unit => true,
Token::Bang => true, Token::Bang => true,
Token::DoubleColon => true, Token::DoubleColon => true,
_ => false, _ => false,

View File

@ -17,7 +17,9 @@ use std::{
/// _(internals)_ An op-assignment operator. /// _(internals)_ An op-assignment operator.
/// Exported under the `internals` feature only. /// Exported under the `internals` feature only.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] ///
/// This type may hold a straight assignment (i.e. not an op-assignment).
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub struct OpAssignment<'a> { pub struct OpAssignment<'a> {
/// Hash of the op-assignment call. /// Hash of the op-assignment call.
pub hash_op_assign: u64, pub hash_op_assign: u64,
@ -27,9 +29,29 @@ pub struct OpAssignment<'a> {
pub op_assign: &'a str, pub op_assign: &'a str,
/// Underlying operator. /// Underlying operator.
pub op: &'a str, pub op: &'a str,
/// [Position] of the op-assignment operator.
pub pos: Position,
} }
impl OpAssignment<'_> { impl OpAssignment<'_> {
/// Create a new [`OpAssignment`] that is only a straight assignment.
#[must_use]
#[inline(always)]
pub const fn new_assignment(pos: Position) -> Self {
Self {
hash_op_assign: 0,
hash_op: 0,
op_assign: "=",
op: "=",
pos,
}
}
/// Is this an op-assignment?
#[must_use]
#[inline(always)]
pub const fn is_op_assignment(&self) -> bool {
self.hash_op_assign != 0 || self.hash_op != 0
}
/// Create a new [`OpAssignment`]. /// Create a new [`OpAssignment`].
/// ///
/// # Panics /// # Panics
@ -37,8 +59,8 @@ impl OpAssignment<'_> {
/// Panics if the name is not an op-assignment operator. /// Panics if the name is not an op-assignment operator.
#[must_use] #[must_use]
#[inline(always)] #[inline(always)]
pub fn new(name: &str) -> Self { pub fn new_op_assignment(name: &str, pos: Position) -> Self {
Self::new_from_token(Token::lookup_from_syntax(name).expect("operator")) Self::new_op_assignment_from_token(Token::lookup_from_syntax(name).expect("operator"), pos)
} }
/// Create a new [`OpAssignment`] from a [`Token`]. /// Create a new [`OpAssignment`] from a [`Token`].
/// ///
@ -46,7 +68,7 @@ impl OpAssignment<'_> {
/// ///
/// Panics if the token is not an op-assignment operator. /// Panics if the token is not an op-assignment operator.
#[must_use] #[must_use]
pub fn new_from_token(op: Token) -> Self { pub fn new_op_assignment_from_token(op: Token, pos: Position) -> Self {
let op_raw = op let op_raw = op
.get_base_op_from_assignment() .get_base_op_from_assignment()
.expect("op-assignment operator") .expect("op-assignment operator")
@ -56,6 +78,7 @@ impl OpAssignment<'_> {
hash_op: calc_fn_hash(op_raw, 2), hash_op: calc_fn_hash(op_raw, 2),
op_assign: op.literal_syntax(), op_assign: op.literal_syntax(),
op: op_raw, op: op_raw,
pos,
} }
} }
/// Create a new [`OpAssignment`] from a base operator. /// Create a new [`OpAssignment`] from a base operator.
@ -65,8 +88,11 @@ impl OpAssignment<'_> {
/// Panics if the name is not an operator that can be converted into an op-operator. /// Panics if the name is not an operator that can be converted into an op-operator.
#[must_use] #[must_use]
#[inline(always)] #[inline(always)]
pub fn new_from_base(name: &str) -> Self { pub fn new_op_assignment_from_base(name: &str, pos: Position) -> Self {
Self::new_from_base_token(Token::lookup_from_syntax(name).expect("operator")) Self::new_op_assignment_from_base_token(
Token::lookup_from_syntax(name).expect("operator"),
pos,
)
} }
/// Convert a [`Token`] into a new [`OpAssignment`]. /// Convert a [`Token`] into a new [`OpAssignment`].
/// ///
@ -75,16 +101,34 @@ impl OpAssignment<'_> {
/// Panics if the token is cannot be converted into an op-assignment operator. /// Panics if the token is cannot be converted into an op-assignment operator.
#[inline(always)] #[inline(always)]
#[must_use] #[must_use]
pub fn new_from_base_token(op: Token) -> Self { pub fn new_op_assignment_from_base_token(op: Token, pos: Position) -> Self {
Self::new_from_token(op.convert_to_op_assignment().expect("operator")) Self::new_op_assignment_from_token(op.convert_to_op_assignment().expect("operator"), pos)
} }
} }
/// A statements block with an optional condition. impl fmt::Debug for OpAssignment<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.is_op_assignment() {
f.debug_struct("OpAssignment")
.field("hash_op_assign", &self.hash_op_assign)
.field("hash_op", &self.hash_op)
.field("op_assign", &self.op_assign)
.field("op", &self.op)
.field("pos", &self.pos)
.finish()
} else {
fmt::Debug::fmt(&self.pos, f)
}
}
}
/// A statements block with a condition.
///
/// The condition may simply be [`Expr::BoolConstant`] with `true` if there is actually no condition.
#[derive(Debug, Clone, Hash)] #[derive(Debug, Clone, Hash)]
pub struct ConditionalStmtBlock { pub struct ConditionalStmtBlock {
/// Optional condition. /// Condition.
pub condition: Option<Expr>, pub condition: Expr,
/// Statements block. /// Statements block.
pub statements: StmtBlock, pub statements: StmtBlock,
} }
@ -93,7 +137,7 @@ impl<B: Into<StmtBlock>> From<B> for ConditionalStmtBlock {
#[inline(always)] #[inline(always)]
fn from(value: B) -> Self { fn from(value: B) -> Self {
Self { Self {
condition: None, condition: Expr::BoolConstant(true, Position::NONE),
statements: value.into(), statements: value.into(),
} }
} }
@ -102,16 +146,6 @@ impl<B: Into<StmtBlock>> From<B> for ConditionalStmtBlock {
impl<B: Into<StmtBlock>> From<(Expr, B)> for ConditionalStmtBlock { impl<B: Into<StmtBlock>> From<(Expr, B)> for ConditionalStmtBlock {
#[inline(always)] #[inline(always)]
fn from(value: (Expr, B)) -> Self { fn from(value: (Expr, B)) -> Self {
Self {
condition: Some(value.0),
statements: value.1.into(),
}
}
}
impl<B: Into<StmtBlock>> From<(Option<Expr>, B)> for ConditionalStmtBlock {
#[inline(always)]
fn from(value: (Option<Expr>, B)) -> Self {
Self { Self {
condition: value.0, condition: value.0,
statements: value.1.into(), statements: value.1.into(),
@ -119,15 +153,6 @@ impl<B: Into<StmtBlock>> From<(Option<Expr>, B)> for ConditionalStmtBlock {
} }
} }
impl ConditionalStmtBlock {
/// Does the condition exist?
#[inline(always)]
#[must_use]
pub const fn has_condition(&self) -> bool {
self.condition.is_some()
}
}
/// _(internals)_ A type containing all cases for a `switch` statement. /// _(internals)_ A type containing all cases for a `switch` statement.
/// Exported under the `internals` feature only. /// Exported under the `internals` feature only.
#[derive(Debug, Clone, Hash)] #[derive(Debug, Clone, Hash)]
@ -375,7 +400,7 @@ pub enum Stmt {
/// * [`CONSTANT`][ASTFlags::CONSTANT] = `const` /// * [`CONSTANT`][ASTFlags::CONSTANT] = `const`
Var(Box<(Ident, Expr, Option<NonZeroUsize>)>, ASTFlags, Position), Var(Box<(Ident, Expr, Option<NonZeroUsize>)>, ASTFlags, Position),
/// expr op`=` expr /// expr op`=` expr
Assignment(Box<(Option<OpAssignment<'static>>, BinaryExpr)>, Position), Assignment(Box<(OpAssignment<'static>, BinaryExpr)>),
/// func `(` expr `,` ... `)` /// func `(` expr `,` ... `)`
/// ///
/// Note - this is a duplicate of [`Expr::FnCall`] to cover the very common pattern of a single /// Note - this is a duplicate of [`Expr::FnCall`] to cover the very common pattern of a single
@ -464,7 +489,6 @@ impl Stmt {
match self { match self {
Self::Noop(pos) Self::Noop(pos)
| Self::BreakLoop(.., pos) | Self::BreakLoop(.., pos)
| Self::Assignment(.., pos)
| Self::FnCall(.., pos) | Self::FnCall(.., pos)
| Self::If(.., pos) | Self::If(.., pos)
| Self::Switch(.., pos) | Self::Switch(.., pos)
@ -475,6 +499,8 @@ impl Stmt {
| Self::Var(.., pos) | Self::Var(.., pos)
| Self::TryCatch(.., pos) => *pos, | Self::TryCatch(.., pos) => *pos,
Self::Assignment(x) => x.0.pos,
Self::Block(x) => x.position(), Self::Block(x) => x.position(),
Self::Expr(x) => x.start_position(), Self::Expr(x) => x.start_position(),
@ -493,7 +519,6 @@ impl Stmt {
match self { match self {
Self::Noop(pos) Self::Noop(pos)
| Self::BreakLoop(.., pos) | Self::BreakLoop(.., pos)
| Self::Assignment(.., pos)
| Self::FnCall(.., pos) | Self::FnCall(.., pos)
| Self::If(.., pos) | Self::If(.., pos)
| Self::Switch(.., pos) | Self::Switch(.., pos)
@ -504,6 +529,8 @@ impl Stmt {
| Self::Var(.., pos) | Self::Var(.., pos)
| Self::TryCatch(.., pos) => *pos = new_pos, | Self::TryCatch(.., pos) => *pos = new_pos,
Self::Assignment(x) => x.0.pos = new_pos,
Self::Block(x) => x.set_position(new_pos, x.end_position()), Self::Block(x) => x.set_position(new_pos, x.end_position()),
Self::Expr(x) => { Self::Expr(x) => {
@ -593,12 +620,10 @@ impl Stmt {
Self::Switch(x, ..) => { Self::Switch(x, ..) => {
x.0.is_pure() x.0.is_pure()
&& x.1.cases.values().all(|block| { && x.1.cases.values().all(|block| {
block.condition.as_ref().map(Expr::is_pure).unwrap_or(true) block.condition.is_pure() && block.statements.iter().all(Stmt::is_pure)
&& block.statements.iter().all(Stmt::is_pure)
}) })
&& x.1.ranges.iter().all(|(.., block)| { && x.1.ranges.iter().all(|(.., block)| {
block.condition.as_ref().map(Expr::is_pure).unwrap_or(true) block.condition.is_pure() && block.statements.iter().all(Stmt::is_pure)
&& block.statements.iter().all(Stmt::is_pure)
}) })
&& x.1.def_case.iter().all(Stmt::is_pure) && x.1.def_case.iter().all(Stmt::is_pure)
} }
@ -740,12 +765,7 @@ impl Stmt {
return false; return false;
} }
for b in x.1.cases.values() { for b in x.1.cases.values() {
if !b if !b.condition.walk(path, on_node) {
.condition
.as_ref()
.map(|e| e.walk(path, on_node))
.unwrap_or(true)
{
return false; return false;
} }
for s in b.statements.iter() { for s in b.statements.iter() {
@ -755,12 +775,7 @@ impl Stmt {
} }
} }
for (.., b) in &x.1.ranges { for (.., b) in &x.1.ranges {
if !b if !b.condition.walk(path, on_node) {
.condition
.as_ref()
.map(|e| e.walk(path, on_node))
.unwrap_or(true)
{
return false; return false;
} }
for s in b.statements.iter() { for s in b.statements.iter() {

69
src/eval/cache.rs Normal file
View File

@ -0,0 +1,69 @@
//! System caches.
use crate::func::CallableFunction;
use crate::{Identifier, StaticVec};
use std::collections::BTreeMap;
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
/// _(internals)_ An entry in a function resolution cache.
/// Exported under the `internals` feature only.
#[derive(Debug, Clone)]
pub struct FnResolutionCacheEntry {
/// Function.
pub func: CallableFunction,
/// Optional source.
/// No source if the string is empty.
pub source: Identifier,
}
/// _(internals)_ A function resolution cache.
/// Exported under the `internals` feature only.
///
/// [`FnResolutionCacheEntry`] is [`Box`]ed in order to pack as many entries inside a single B-Tree
/// level as possible.
pub type FnResolutionCache = BTreeMap<u64, Option<Box<FnResolutionCacheEntry>>>;
/// _(internals)_ A type containing system-wide caches.
/// Exported under the `internals` feature only.
///
/// The following caches are contained inside this type:
/// * A stack of [function resolution caches][FnResolutionCache]
#[derive(Debug, Clone)]
pub struct Caches(StaticVec<FnResolutionCache>);
impl Caches {
/// Create an empty [`Caches`].
#[inline(always)]
#[must_use]
pub const fn new() -> Self {
Self(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.0.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.0.is_empty() {
// Push a new function resolution cache if the stack is empty
self.push_fn_resolution_cache();
}
self.0.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.0.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.0.truncate(len);
}
}

View File

@ -1,7 +1,7 @@
//! Types to support chaining operations (i.e. indexing and dotting). //! Types to support chaining operations (i.e. indexing and dotting).
#![cfg(any(not(feature = "no_index"), not(feature = "no_object")))] #![cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
use super::{EvalState, GlobalRuntimeState, Target}; use super::{Caches, GlobalRuntimeState, Target};
use crate::ast::{ASTFlags, Expr, OpAssignment}; use crate::ast::{ASTFlags, Expr, OpAssignment};
use crate::types::dynamic::Union; use crate::types::dynamic::Union;
use crate::{Dynamic, Engine, Module, Position, RhaiResult, RhaiResultOf, Scope, StaticVec, ERR}; use crate::{Dynamic, Engine, Module, Position, RhaiResult, RhaiResultOf, Scope, StaticVec, ERR};
@ -122,7 +122,7 @@ impl Engine {
fn eval_dot_index_chain_helper( fn eval_dot_index_chain_helper(
&self, &self,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>, this_ptr: &mut Option<&mut Dynamic>,
target: &mut Target, target: &mut Target,
@ -130,10 +130,10 @@ impl Engine {
_parent: &Expr, _parent: &Expr,
rhs: &Expr, rhs: &Expr,
_parent_options: ASTFlags, _parent_options: ASTFlags,
idx_values: &mut StaticVec<super::ChainArgument>, idx_values: &mut StaticVec<ChainArgument>,
chain_type: ChainType, chain_type: ChainType,
level: usize, level: usize,
new_val: Option<((Dynamic, Position), (Option<OpAssignment>, Position))>, new_val: Option<(Dynamic, OpAssignment)>,
) -> RhaiResultOf<(Dynamic, bool)> { ) -> RhaiResultOf<(Dynamic, bool)> {
let is_ref_mut = target.is_ref(); let is_ref_mut = target.is_ref();
@ -155,7 +155,7 @@ impl Engine {
if !_parent_options.contains(ASTFlags::BREAK) => if !_parent_options.contains(ASTFlags::BREAK) =>
{ {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger(scope, global, state, lib, this_ptr, _parent, level)?; self.run_debugger(scope, global, lib, this_ptr, _parent, level)?;
let mut idx_val_for_setter = idx_val.clone(); let mut idx_val_for_setter = idx_val.clone();
let idx_pos = x.lhs.start_position(); let idx_pos = x.lhs.start_position();
@ -163,14 +163,14 @@ impl Engine {
let (try_setter, result) = { let (try_setter, result) = {
let mut obj = self.get_indexed_mut( let mut obj = self.get_indexed_mut(
global, state, lib, target, idx_val, idx_pos, false, true, level, global, caches, lib, target, idx_val, idx_pos, false, true, level,
)?; )?;
let is_obj_temp_val = obj.is_temp_value(); let is_obj_temp_val = obj.is_temp_value();
let obj_ptr = &mut obj; let obj_ptr = &mut obj;
match self.eval_dot_index_chain_helper( match self.eval_dot_index_chain_helper(
global, state, lib, this_ptr, obj_ptr, root, rhs, &x.rhs, *options, global, caches, lib, this_ptr, obj_ptr, root, rhs, &x.rhs,
idx_values, rhs_chain, level, new_val, *options, idx_values, rhs_chain, level, new_val,
) { ) {
Ok((result, true)) if is_obj_temp_val => { Ok((result, true)) if is_obj_temp_val => {
(Some(obj.take_or_clone()), (result, true)) (Some(obj.take_or_clone()), (result, true))
@ -185,7 +185,7 @@ impl Engine {
let idx = &mut idx_val_for_setter; let idx = &mut idx_val_for_setter;
let new_val = &mut new_val; let new_val = &mut new_val;
self.call_indexer_set( self.call_indexer_set(
global, state, lib, target, idx, new_val, is_ref_mut, level, global, caches, lib, target, idx, new_val, is_ref_mut, level,
) )
.or_else(|e| match *e { .or_else(|e| match *e {
ERR::ErrorIndexingType(..) => Ok((Dynamic::UNIT, false)), ERR::ErrorIndexingType(..) => Ok((Dynamic::UNIT, false)),
@ -198,23 +198,21 @@ impl Engine {
// xxx[rhs] op= new_val // xxx[rhs] op= new_val
_ if new_val.is_some() => { _ if new_val.is_some() => {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger(scope, global, state, lib, this_ptr, _parent, level)?; self.run_debugger(scope, global, lib, this_ptr, _parent, level)?;
let ((new_val, new_pos), (op_info, op_pos)) = new_val.expect("`Some`"); let (new_val, op_info) = new_val.expect("`Some`");
let mut idx_val2 = idx_val.clone(); let mut idx_val2 = idx_val.clone();
let try_setter = match self.get_indexed_mut( let try_setter = match self.get_indexed_mut(
global, state, lib, target, idx_val, pos, true, false, level, global, caches, lib, target, idx_val, pos, true, false, level,
) { ) {
// Indexed value is not a temp value - update directly // Indexed value is not a temp value - update directly
Ok(ref mut obj_ptr) => { Ok(ref mut obj_ptr) => {
self.eval_op_assignment( self.eval_op_assignment(
global, state, lib, op_info, op_pos, obj_ptr, root, new_val, global, caches, lib, op_info, obj_ptr, root, new_val, level,
level, )?;
)
.map_err(|err| err.fill_position(new_pos))?;
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
self.check_data_size(obj_ptr, new_pos)?; self.check_data_size(obj_ptr, op_info.pos)?;
None None
} }
// Indexed value cannot be referenced - use indexer // Indexed value cannot be referenced - use indexer
@ -228,30 +226,29 @@ impl Engine {
let idx = &mut idx_val2; let idx = &mut idx_val2;
// Is this an op-assignment? // Is this an op-assignment?
if op_info.is_some() { if op_info.is_op_assignment() {
let idx = &mut idx.clone(); let idx = &mut idx.clone();
// Call the index getter to get the current value // Call the index getter to get the current value
if let Ok(val) = if let Ok(val) =
self.call_indexer_get(global, state, lib, target, idx, level) self.call_indexer_get(global, caches, lib, target, idx, level)
{ {
let mut res = val.into(); let mut res = val.into();
// Run the op-assignment // Run the op-assignment
self.eval_op_assignment( self.eval_op_assignment(
global, state, lib, op_info, op_pos, &mut res, root, global, caches, lib, op_info, &mut res, root, new_val,
new_val, level, level,
) )?;
.map_err(|err| err.fill_position(new_pos))?;
// Replace new value // Replace new value
new_val = res.take_or_clone(); new_val = res.take_or_clone();
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
self.check_data_size(&new_val, new_pos)?; self.check_data_size(&new_val, op_info.pos)?;
} }
} }
// Try to call index setter // Try to call index setter
let new_val = &mut new_val; let new_val = &mut new_val;
self.call_indexer_set( self.call_indexer_set(
global, state, lib, target, idx, new_val, is_ref_mut, level, global, caches, lib, target, idx, new_val, is_ref_mut, level,
)?; )?;
} }
@ -260,10 +257,10 @@ impl Engine {
// xxx[rhs] // xxx[rhs]
_ => { _ => {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger(scope, global, state, lib, this_ptr, _parent, level)?; self.run_debugger(scope, global, lib, this_ptr, _parent, level)?;
self.get_indexed_mut( self.get_indexed_mut(
global, state, lib, target, idx_val, pos, false, true, level, global, caches, lib, target, idx_val, pos, false, true, level,
) )
.map(|v| (v.take_or_clone(), false)) .map(|v| (v.take_or_clone(), false))
} }
@ -279,12 +276,11 @@ impl Engine {
let call_args = &mut idx_val.into_fn_call_args(); let call_args = &mut idx_val.into_fn_call_args();
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
let reset_debugger = self.run_debugger_with_reset( let reset_debugger =
scope, global, state, lib, this_ptr, rhs, level, self.run_debugger_with_reset(scope, global, lib, this_ptr, rhs, level)?;
)?;
let result = self.make_method_call( let result = self.make_method_call(
global, state, lib, name, *hashes, target, call_args, *pos, level, global, caches, lib, name, *hashes, target, call_args, *pos, level,
); );
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
@ -303,57 +299,55 @@ impl Engine {
// {xxx:map}.id op= ??? // {xxx:map}.id op= ???
Expr::Property(x, pos) if target.is::<crate::Map>() && new_val.is_some() => { Expr::Property(x, pos) if target.is::<crate::Map>() && new_val.is_some() => {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger(scope, global, state, lib, this_ptr, rhs, level)?; self.run_debugger(scope, global, lib, this_ptr, rhs, level)?;
let index = x.2.clone().into(); let index = x.2.clone().into();
let ((new_val, new_pos), (op_info, op_pos)) = new_val.expect("`Some`"); let (new_val, op_info) = new_val.expect("`Some`");
{ {
let val_target = &mut self.get_indexed_mut( let val_target = &mut self.get_indexed_mut(
global, state, lib, target, index, *pos, true, false, level, global, caches, lib, target, index, *pos, true, false, level,
)?; )?;
self.eval_op_assignment( self.eval_op_assignment(
global, state, lib, op_info, op_pos, val_target, root, new_val, global, caches, lib, op_info, val_target, root, new_val, level,
level, )?;
)
.map_err(|err| err.fill_position(new_pos))?;
} }
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
self.check_data_size(target.source(), new_pos)?; self.check_data_size(target.source(), op_info.pos)?;
Ok((Dynamic::UNIT, true)) Ok((Dynamic::UNIT, true))
} }
// {xxx:map}.id // {xxx:map}.id
Expr::Property(x, pos) if target.is::<crate::Map>() => { Expr::Property(x, pos) if target.is::<crate::Map>() => {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger(scope, global, state, lib, this_ptr, rhs, level)?; self.run_debugger(scope, global, lib, this_ptr, rhs, level)?;
let index = x.2.clone().into(); let index = x.2.clone().into();
let val = self.get_indexed_mut( let val = self.get_indexed_mut(
global, state, lib, target, index, *pos, false, false, level, global, caches, lib, target, index, *pos, false, false, level,
)?; )?;
Ok((val.take_or_clone(), false)) Ok((val.take_or_clone(), false))
} }
// xxx.id op= ??? // xxx.id op= ???
Expr::Property(x, pos) if new_val.is_some() => { Expr::Property(x, pos) if new_val.is_some() => {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger(scope, global, state, lib, this_ptr, rhs, level)?; self.run_debugger(scope, global, lib, this_ptr, rhs, level)?;
let ((getter, hash_get), (setter, hash_set), name) = x.as_ref(); let ((getter, hash_get), (setter, hash_set), name) = x.as_ref();
let ((mut new_val, new_pos), (op_info, op_pos)) = new_val.expect("`Some`"); let (mut new_val, op_info) = new_val.expect("`Some`");
if op_info.is_some() { if op_info.is_op_assignment() {
let hash = crate::ast::FnCallHashes::from_native(*hash_get); let hash = crate::ast::FnCallHashes::from_native(*hash_get);
let args = &mut [target.as_mut()]; let args = &mut [target.as_mut()];
let (mut orig_val, ..) = self let (mut orig_val, ..) = self
.exec_fn_call( .exec_fn_call(
None, global, state, lib, getter, hash, args, is_ref_mut, true, None, global, caches, lib, getter, hash, args, is_ref_mut,
*pos, level, true, *pos, level,
) )
.or_else(|err| match *err { .or_else(|err| match *err {
// Try an indexer if property does not exist // Try an indexer if property does not exist
ERR::ErrorDotExpr(..) => { ERR::ErrorDotExpr(..) => {
let mut prop = name.into(); let mut prop = name.into();
self.call_indexer_get( self.call_indexer_get(
global, state, lib, target, &mut prop, level, global, caches, lib, target, &mut prop, level,
) )
.map(|r| (r, false)) .map(|r| (r, false))
.map_err(|e| { .map_err(|e| {
@ -370,10 +364,8 @@ impl Engine {
let orig_val = &mut (&mut orig_val).into(); let orig_val = &mut (&mut orig_val).into();
self.eval_op_assignment( self.eval_op_assignment(
global, state, lib, op_info, op_pos, orig_val, root, new_val, global, caches, lib, op_info, orig_val, root, new_val, level,
level, )?;
)
.map_err(|err| err.fill_position(new_pos))?;
} }
new_val = orig_val; new_val = orig_val;
@ -382,7 +374,7 @@ impl Engine {
let hash = crate::ast::FnCallHashes::from_native(*hash_set); let hash = crate::ast::FnCallHashes::from_native(*hash_set);
let args = &mut [target.as_mut(), &mut new_val]; let args = &mut [target.as_mut(), &mut new_val];
self.exec_fn_call( self.exec_fn_call(
None, global, state, lib, setter, hash, args, is_ref_mut, true, *pos, None, global, caches, lib, setter, hash, args, is_ref_mut, true, *pos,
level, level,
) )
.or_else(|err| match *err { .or_else(|err| match *err {
@ -391,7 +383,7 @@ impl Engine {
let idx = &mut name.into(); let idx = &mut name.into();
let new_val = &mut new_val; let new_val = &mut new_val;
self.call_indexer_set( self.call_indexer_set(
global, state, lib, target, idx, new_val, is_ref_mut, level, global, caches, lib, target, idx, new_val, is_ref_mut, level,
) )
.map_err(|e| match *e { .map_err(|e| match *e {
ERR::ErrorIndexingType(..) => err, ERR::ErrorIndexingType(..) => err,
@ -404,13 +396,13 @@ impl Engine {
// xxx.id // xxx.id
Expr::Property(x, pos) => { Expr::Property(x, pos) => {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger(scope, global, state, lib, this_ptr, rhs, level)?; self.run_debugger(scope, global, lib, this_ptr, rhs, level)?;
let ((getter, hash_get), _, name) = x.as_ref(); let ((getter, hash_get), _, name) = x.as_ref();
let hash = crate::ast::FnCallHashes::from_native(*hash_get); let hash = crate::ast::FnCallHashes::from_native(*hash_get);
let args = &mut [target.as_mut()]; let args = &mut [target.as_mut()];
self.exec_fn_call( self.exec_fn_call(
None, global, state, lib, getter, hash, args, is_ref_mut, true, *pos, None, global, caches, lib, getter, hash, args, is_ref_mut, true, *pos,
level, level,
) )
.map_or_else( .map_or_else(
@ -419,7 +411,7 @@ impl Engine {
ERR::ErrorDotExpr(..) => { ERR::ErrorDotExpr(..) => {
let mut prop = name.into(); let mut prop = name.into();
self.call_indexer_get( self.call_indexer_get(
global, state, lib, target, &mut prop, level, global, caches, lib, target, &mut prop, level,
) )
.map(|r| (r, false)) .map(|r| (r, false))
.map_err(|e| match *e { .map_err(|e| match *e {
@ -442,13 +434,11 @@ impl Engine {
let val_target = &mut match x.lhs { let val_target = &mut match x.lhs {
Expr::Property(ref p, pos) => { Expr::Property(ref p, pos) => {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger( self.run_debugger(scope, global, lib, this_ptr, _node, level)?;
scope, global, state, lib, this_ptr, _node, level,
)?;
let index = p.2.clone().into(); let index = p.2.clone().into();
self.get_indexed_mut( self.get_indexed_mut(
global, state, lib, target, index, pos, false, true, level, global, caches, lib, target, index, pos, false, true, level,
)? )?
} }
// {xxx:map}.fn_name(arg_expr_list)[expr] | {xxx:map}.fn_name(arg_expr_list).expr // {xxx:map}.fn_name(arg_expr_list)[expr] | {xxx:map}.fn_name(arg_expr_list).expr
@ -458,11 +448,11 @@ impl Engine {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
let reset_debugger = self.run_debugger_with_reset( let reset_debugger = self.run_debugger_with_reset(
scope, global, state, lib, this_ptr, _node, level, scope, global, lib, this_ptr, _node, level,
)?; )?;
let result = self.make_method_call( let result = self.make_method_call(
global, state, lib, name, *hashes, target, call_args, pos, global, caches, lib, name, *hashes, target, call_args, pos,
level, level,
); );
@ -481,7 +471,7 @@ impl Engine {
let rhs_chain = rhs.into(); let rhs_chain = rhs.into();
self.eval_dot_index_chain_helper( self.eval_dot_index_chain_helper(
global, state, lib, this_ptr, val_target, root, rhs, &x.rhs, *options, global, caches, lib, this_ptr, val_target, root, rhs, &x.rhs, *options,
idx_values, rhs_chain, level, new_val, idx_values, rhs_chain, level, new_val,
) )
.map_err(|err| err.fill_position(*x_pos)) .map_err(|err| err.fill_position(*x_pos))
@ -494,9 +484,7 @@ impl Engine {
// xxx.prop[expr] | xxx.prop.expr // xxx.prop[expr] | xxx.prop.expr
Expr::Property(ref p, pos) => { Expr::Property(ref p, pos) => {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger( self.run_debugger(scope, global, lib, this_ptr, _node, level)?;
scope, global, state, lib, this_ptr, _node, level,
)?;
let ((getter, hash_get), (setter, hash_set), name) = p.as_ref(); let ((getter, hash_get), (setter, hash_set), name) = p.as_ref();
let rhs_chain = rhs.into(); let rhs_chain = rhs.into();
@ -508,7 +496,7 @@ impl Engine {
// Assume getters are always pure // Assume getters are always pure
let (mut val, ..) = self let (mut val, ..) = self
.exec_fn_call( .exec_fn_call(
None, global, state, lib, getter, hash_get, args, None, global, caches, lib, getter, hash_get, args,
is_ref_mut, true, pos, level, is_ref_mut, true, pos, level,
) )
.or_else(|err| match *err { .or_else(|err| match *err {
@ -516,7 +504,7 @@ impl Engine {
ERR::ErrorDotExpr(..) => { ERR::ErrorDotExpr(..) => {
let mut prop = name.into(); let mut prop = name.into();
self.call_indexer_get( self.call_indexer_get(
global, state, lib, target, &mut prop, level, global, caches, lib, target, &mut prop, level,
) )
.map(|r| (r, false)) .map(|r| (r, false))
.map_err( .map_err(
@ -533,7 +521,7 @@ impl Engine {
let (result, may_be_changed) = self let (result, may_be_changed) = self
.eval_dot_index_chain_helper( .eval_dot_index_chain_helper(
global, state, lib, this_ptr, val, root, rhs, &x.rhs, global, caches, lib, this_ptr, val, root, rhs, &x.rhs,
*options, idx_values, rhs_chain, level, new_val, *options, idx_values, rhs_chain, level, new_val,
) )
.map_err(|err| err.fill_position(*x_pos))?; .map_err(|err| err.fill_position(*x_pos))?;
@ -544,7 +532,7 @@ impl Engine {
let mut arg_values = [target.as_mut(), val.as_mut()]; let mut arg_values = [target.as_mut(), val.as_mut()];
let args = &mut arg_values; let args = &mut arg_values;
self.exec_fn_call( self.exec_fn_call(
None, global, state, lib, setter, hash_set, args, None, global, caches, lib, setter, hash_set, args,
is_ref_mut, true, pos, level, is_ref_mut, true, pos, level,
) )
.or_else( .or_else(
@ -554,7 +542,7 @@ impl Engine {
let idx = &mut name.into(); let idx = &mut name.into();
let new_val = val; let new_val = val;
self.call_indexer_set( self.call_indexer_set(
global, state, lib, target, idx, new_val, global, caches, lib, target, idx, new_val,
is_ref_mut, level, is_ref_mut, level,
) )
.or_else(|e| match *e { .or_else(|e| match *e {
@ -581,11 +569,11 @@ impl Engine {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
let reset_debugger = self.run_debugger_with_reset( let reset_debugger = self.run_debugger_with_reset(
scope, global, state, lib, this_ptr, _node, level, scope, global, lib, this_ptr, _node, level,
)?; )?;
let result = self.make_method_call( let result = self.make_method_call(
global, state, lib, name, *hashes, target, args, pos, level, global, caches, lib, name, *hashes, target, args, pos, level,
); );
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
@ -595,8 +583,8 @@ impl Engine {
let val = &mut val.into(); let val = &mut val.into();
self.eval_dot_index_chain_helper( self.eval_dot_index_chain_helper(
global, state, lib, this_ptr, val, root, rhs, &x.rhs, *options, global, caches, lib, this_ptr, val, root, rhs, &x.rhs,
idx_values, rhs_chain, level, new_val, *options, idx_values, rhs_chain, level, new_val,
) )
.map_err(|err| err.fill_position(pos)) .map_err(|err| err.fill_position(pos))
} }
@ -620,12 +608,12 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>, this_ptr: &mut Option<&mut Dynamic>,
expr: &Expr, expr: &Expr,
level: usize, level: usize,
new_val: Option<((Dynamic, Position), (Option<OpAssignment>, Position))>, new_val: Option<(Dynamic, OpAssignment)>,
) -> RhaiResult { ) -> RhaiResult {
let (crate::ast::BinaryExpr { lhs, rhs }, chain_type, options, op_pos) = match expr { let (crate::ast::BinaryExpr { lhs, rhs }, chain_type, options, op_pos) = match expr {
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
@ -638,7 +626,7 @@ impl Engine {
let idx_values = &mut StaticVec::new_const(); let idx_values = &mut StaticVec::new_const();
self.eval_dot_index_chain_arguments( self.eval_dot_index_chain_arguments(
scope, global, state, lib, this_ptr, rhs, options, chain_type, idx_values, 0, level, scope, global, caches, lib, this_ptr, rhs, options, chain_type, idx_values, 0, level,
)?; )?;
let is_assignment = new_val.is_some(); let is_assignment = new_val.is_some();
@ -647,19 +635,19 @@ impl Engine {
// id.??? or id[???] // id.??? or id[???]
Expr::Variable(x, .., var_pos) => { Expr::Variable(x, .., var_pos) => {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger(scope, global, state, lib, this_ptr, lhs, level)?; self.run_debugger(scope, global, lib, this_ptr, lhs, level)?;
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut global.num_operations, *var_pos)?; self.inc_operations(&mut global.num_operations, *var_pos)?;
let (mut target, ..) = let (mut target, ..) =
self.search_namespace(scope, global, state, lib, this_ptr, lhs, level)?; self.search_namespace(scope, global, lib, this_ptr, lhs, level)?;
let obj_ptr = &mut target; let obj_ptr = &mut target;
let root = (x.3.as_str(), *var_pos); let root = (x.3.as_str(), *var_pos);
self.eval_dot_index_chain_helper( self.eval_dot_index_chain_helper(
global, state, lib, &mut None, obj_ptr, root, expr, rhs, options, idx_values, global, caches, lib, &mut None, obj_ptr, root, expr, rhs, options, idx_values,
chain_type, level, new_val, chain_type, level, new_val,
) )
.map(|(v, ..)| v) .map(|(v, ..)| v)
@ -669,11 +657,11 @@ impl Engine {
_ if is_assignment => unreachable!("cannot assign to an expression"), _ if is_assignment => unreachable!("cannot assign to an expression"),
// {expr}.??? or {expr}[???] // {expr}.??? or {expr}[???]
expr => { expr => {
let value = self.eval_expr(scope, global, state, lib, this_ptr, expr, level)?; let value = self.eval_expr(scope, global, caches, lib, this_ptr, expr, level)?;
let obj_ptr = &mut value.into(); let obj_ptr = &mut value.into();
let root = ("", expr.start_position()); let root = ("", expr.start_position());
self.eval_dot_index_chain_helper( self.eval_dot_index_chain_helper(
global, state, lib, this_ptr, obj_ptr, root, expr, rhs, options, idx_values, global, caches, lib, this_ptr, obj_ptr, root, expr, rhs, options, idx_values,
chain_type, level, new_val, chain_type, level, new_val,
) )
.map(|(v, ..)| if is_assignment { Dynamic::UNIT } else { v }) .map(|(v, ..)| if is_assignment { Dynamic::UNIT } else { v })
@ -689,13 +677,13 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>, this_ptr: &mut Option<&mut Dynamic>,
expr: &Expr, expr: &Expr,
parent_options: ASTFlags, parent_options: ASTFlags,
_parent_chain_type: ChainType, _parent_chain_type: ChainType,
idx_values: &mut StaticVec<super::ChainArgument>, idx_values: &mut StaticVec<ChainArgument>,
size: usize, size: usize,
level: usize, level: usize,
) -> RhaiResultOf<()> { ) -> RhaiResultOf<()> {
@ -713,7 +701,7 @@ impl Engine {
(crate::FnArgsVec::with_capacity(args.len()), Position::NONE), (crate::FnArgsVec::with_capacity(args.len()), Position::NONE),
|(mut values, mut pos), expr| { |(mut values, mut pos), expr| {
let (value, arg_pos) = let (value, arg_pos) =
self.get_arg_value(scope, global, state, lib, this_ptr, expr, level)?; self.get_arg_value(scope, global, caches, lib, this_ptr, expr, level)?;
if values.is_empty() { if values.is_empty() {
pos = arg_pos; pos = arg_pos;
} }
@ -722,7 +710,7 @@ impl Engine {
}, },
)?; )?;
idx_values.push(super::ChainArgument::from_fn_call_args(values, pos)); idx_values.push(ChainArgument::from_fn_call_args(values, pos));
} }
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Expr::MethodCall(..) if _parent_chain_type == ChainType::Dotting => { Expr::MethodCall(..) if _parent_chain_type == ChainType::Dotting => {
@ -731,7 +719,7 @@ impl Engine {
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Expr::Property(.., pos) if _parent_chain_type == ChainType::Dotting => { Expr::Property(.., pos) if _parent_chain_type == ChainType::Dotting => {
idx_values.push(super::ChainArgument::Property(*pos)) idx_values.push(ChainArgument::Property(*pos))
} }
Expr::Property(..) => unreachable!("unexpected Expr::Property for indexing"), Expr::Property(..) => unreachable!("unexpected Expr::Property for indexing"),
@ -744,7 +732,7 @@ impl Engine {
let lhs_arg_val = match lhs { let lhs_arg_val = match lhs {
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Expr::Property(.., pos) if _parent_chain_type == ChainType::Dotting => { Expr::Property(.., pos) if _parent_chain_type == ChainType::Dotting => {
super::ChainArgument::Property(*pos) ChainArgument::Property(*pos)
} }
Expr::Property(..) => unreachable!("unexpected Expr::Property for indexing"), Expr::Property(..) => unreachable!("unexpected Expr::Property for indexing"),
@ -758,7 +746,7 @@ impl Engine {
(crate::FnArgsVec::with_capacity(args.len()), Position::NONE), (crate::FnArgsVec::with_capacity(args.len()), Position::NONE),
|(mut values, mut pos), expr| { |(mut values, mut pos), expr| {
let (value, arg_pos) = self.get_arg_value( let (value, arg_pos) = self.get_arg_value(
scope, global, state, lib, this_ptr, expr, level, scope, global, caches, lib, this_ptr, expr, level,
)?; )?;
if values.is_empty() { if values.is_empty() {
pos = arg_pos pos = arg_pos
@ -767,7 +755,7 @@ impl Engine {
Ok::<_, crate::RhaiError>((values, pos)) Ok::<_, crate::RhaiError>((values, pos))
}, },
)?; )?;
super::ChainArgument::from_fn_call_args(values, pos) ChainArgument::from_fn_call_args(values, pos)
} }
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Expr::MethodCall(..) if _parent_chain_type == ChainType::Dotting => { Expr::MethodCall(..) if _parent_chain_type == ChainType::Dotting => {
@ -779,12 +767,9 @@ impl Engine {
} }
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
_ if _parent_chain_type == ChainType::Indexing => self _ if _parent_chain_type == ChainType::Indexing => self
.eval_expr(scope, global, state, lib, this_ptr, lhs, level) .eval_expr(scope, global, caches, lib, this_ptr, lhs, level)
.map(|v| { .map(|v| {
super::ChainArgument::from_index_value( ChainArgument::from_index_value(v.flatten(), lhs.start_position())
v.flatten(),
lhs.start_position(),
)
})?, })?,
expr => unreachable!("unknown chained expression: {:?}", expr), expr => unreachable!("unknown chained expression: {:?}", expr),
}; };
@ -793,7 +778,7 @@ impl Engine {
let chain_type = expr.into(); let chain_type = expr.into();
self.eval_dot_index_chain_arguments( self.eval_dot_index_chain_arguments(
scope, global, state, lib, this_ptr, rhs, *options, chain_type, idx_values, scope, global, caches, lib, this_ptr, rhs, *options, chain_type, idx_values,
size, level, size, level,
)?; )?;
@ -806,10 +791,8 @@ impl Engine {
} }
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
_ if _parent_chain_type == ChainType::Indexing => idx_values.push( _ if _parent_chain_type == ChainType::Indexing => idx_values.push(
self.eval_expr(scope, global, state, lib, this_ptr, expr, level) self.eval_expr(scope, global, caches, lib, this_ptr, expr, level)
.map(|v| { .map(|v| ChainArgument::from_index_value(v.flatten(), expr.start_position()))?,
super::ChainArgument::from_index_value(v.flatten(), expr.start_position())
})?,
), ),
_ => unreachable!("unknown chained expression: {:?}", expr), _ => unreachable!("unknown chained expression: {:?}", expr),
} }
@ -823,7 +806,7 @@ impl Engine {
fn call_indexer_get( fn call_indexer_get(
&self, &self,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
target: &mut Dynamic, target: &mut Dynamic,
idx: &mut Dynamic, idx: &mut Dynamic,
@ -835,7 +818,7 @@ impl Engine {
let pos = Position::NONE; let pos = Position::NONE;
self.exec_fn_call( self.exec_fn_call(
None, global, state, lib, fn_name, hash_get, args, true, true, pos, level, None, global, caches, lib, fn_name, hash_get, args, true, true, pos, level,
) )
.map(|(r, ..)| r) .map(|(r, ..)| r)
} }
@ -846,7 +829,7 @@ impl Engine {
fn call_indexer_set( fn call_indexer_set(
&self, &self,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
target: &mut Dynamic, target: &mut Dynamic,
idx: &mut Dynamic, idx: &mut Dynamic,
@ -860,7 +843,7 @@ impl Engine {
let pos = Position::NONE; let pos = Position::NONE;
self.exec_fn_call( self.exec_fn_call(
None, global, state, lib, fn_name, hash_set, args, is_ref_mut, true, pos, level, None, global, caches, lib, fn_name, hash_set, args, is_ref_mut, true, pos, level,
) )
} }
@ -869,7 +852,7 @@ impl Engine {
fn get_indexed_mut<'t>( fn get_indexed_mut<'t>(
&self, &self,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
target: &'t mut Dynamic, target: &'t mut Dynamic,
mut idx: Dynamic, mut idx: Dynamic,
@ -1064,7 +1047,7 @@ impl Engine {
} }
_ if use_indexers => self _ if use_indexers => self
.call_indexer_get(global, state, lib, target, &mut idx, level) .call_indexer_get(global, caches, lib, target, &mut idx, level)
.map(Into::into), .map(Into::into),
_ => Err(ERR::ErrorIndexingType( _ => Err(ERR::ErrorIndexingType(

View File

@ -1,7 +1,7 @@
//! Module defining the debugging interface. //! Module defining the debugging interface.
#![cfg(feature = "debugging")] #![cfg(feature = "debugging")]
use super::{EvalContext, EvalState, GlobalRuntimeState}; use super::{EvalContext, GlobalRuntimeState};
use crate::ast::{ASTNode, Expr, Stmt}; use crate::ast::{ASTNode, Expr, Stmt};
use crate::{Dynamic, Engine, EvalAltResult, Identifier, Module, Position, RhaiResultOf, Scope}; use crate::{Dynamic, Engine, EvalAltResult, Identifier, Module, Position, RhaiResultOf, Scope};
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
@ -406,7 +406,6 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState,
lib: &[&Module], lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>, this_ptr: &mut Option<&mut Dynamic>,
node: impl Into<ASTNode<'a>>, node: impl Into<ASTNode<'a>>,
@ -414,7 +413,7 @@ impl Engine {
) -> RhaiResultOf<()> { ) -> RhaiResultOf<()> {
if self.debugger.is_some() { if self.debugger.is_some() {
if let Some(cmd) = if let Some(cmd) =
self.run_debugger_with_reset_raw(scope, global, state, lib, this_ptr, node, level)? self.run_debugger_with_reset_raw(scope, global, lib, this_ptr, node, level)?
{ {
global.debugger.status = cmd; global.debugger.status = cmd;
} }
@ -434,14 +433,13 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState,
lib: &[&Module], lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>, this_ptr: &mut Option<&mut Dynamic>,
node: impl Into<ASTNode<'a>>, node: impl Into<ASTNode<'a>>,
level: usize, level: usize,
) -> RhaiResultOf<Option<DebuggerStatus>> { ) -> RhaiResultOf<Option<DebuggerStatus>> {
if self.debugger.is_some() { if self.debugger.is_some() {
self.run_debugger_with_reset_raw(scope, global, state, lib, this_ptr, node, level) self.run_debugger_with_reset_raw(scope, global, lib, this_ptr, node, level)
} else { } else {
Ok(None) Ok(None)
} }
@ -458,7 +456,6 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState,
lib: &[&Module], lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>, this_ptr: &mut Option<&mut Dynamic>,
node: impl Into<ASTNode<'a>>, node: impl Into<ASTNode<'a>>,
@ -490,7 +487,7 @@ impl Engine {
} }
}; };
self.run_debugger_raw(scope, global, state, lib, this_ptr, node, event, level) self.run_debugger_raw(scope, global, lib, this_ptr, node, event, level)
} }
/// Run the debugger callback unconditionally. /// Run the debugger callback unconditionally.
/// ///
@ -504,7 +501,6 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState,
lib: &[&Module], lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>, this_ptr: &mut Option<&mut Dynamic>,
node: ASTNode<'a>, node: ASTNode<'a>,
@ -522,7 +518,7 @@ impl Engine {
engine: self, engine: self,
scope, scope,
global, global,
state, caches: None,
lib, lib,
this_ptr, this_ptr,
level, level,

View File

@ -1,30 +1,30 @@
//! Evaluation context. //! Evaluation context.
use super::{EvalState, GlobalRuntimeState}; use super::{Caches, GlobalRuntimeState};
use crate::{Dynamic, Engine, Module, Scope}; use crate::{Dynamic, Engine, Module, Scope};
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
use std::prelude::v1::*; use std::prelude::v1::*;
/// Context of a script evaluation process. /// Context of a script evaluation process.
#[derive(Debug)] #[derive(Debug)]
pub struct EvalContext<'a, 'x, 'px, 'm, 'pm, 's, 'ps, 'b, 't, 'pt> { pub struct EvalContext<'a, 's, 'ps, 'm, 'pm, 'c, 't, 'pt> {
/// The current [`Engine`]. /// The current [`Engine`].
pub(crate) engine: &'a Engine, pub(crate) engine: &'a Engine,
/// The current [`Scope`]. /// The current [`Scope`].
pub(crate) scope: &'x mut Scope<'px>, pub(crate) scope: &'s mut Scope<'ps>,
/// The current [`GlobalRuntimeState`]. /// The current [`GlobalRuntimeState`].
pub(crate) global: &'m mut GlobalRuntimeState<'pm>, pub(crate) global: &'m mut GlobalRuntimeState<'pm>,
/// The current [evaluation state][EvalState]. /// The current [caches][Caches], if available.
pub(crate) state: &'s mut EvalState<'ps>, pub(crate) caches: Option<&'c mut Caches>,
/// The current stack of imported [modules][Module]. /// The current stack of imported [modules][Module].
pub(crate) lib: &'b [&'b Module], pub(crate) lib: &'a [&'a Module],
/// The current bound `this` pointer, if any. /// The current bound `this` pointer, if any.
pub(crate) this_ptr: &'t mut Option<&'pt mut Dynamic>, pub(crate) this_ptr: &'t mut Option<&'pt mut Dynamic>,
/// The current nesting level of function calls. /// The current nesting level of function calls.
pub(crate) level: usize, pub(crate) level: usize,
} }
impl<'x, 'px, 'm, 'pm, 'pt> EvalContext<'_, 'x, 'px, 'm, 'pm, '_, '_, '_, '_, 'pt> { impl<'s, 'ps, 'm, 'pm, 'pt> EvalContext<'_, 's, 'ps, 'm, 'pm, '_, '_, 'pt> {
/// The current [`Engine`]. /// The current [`Engine`].
#[inline(always)] #[inline(always)]
#[must_use] #[must_use]
@ -44,13 +44,13 @@ impl<'x, 'px, 'm, 'pm, 'pt> EvalContext<'_, 'x, 'px, 'm, 'pm, '_, '_, '_, '_, 'p
/// The current [`Scope`]. /// The current [`Scope`].
#[inline(always)] #[inline(always)]
#[must_use] #[must_use]
pub const fn scope(&self) -> &Scope<'px> { pub const fn scope(&self) -> &Scope<'ps> {
self.scope self.scope
} }
/// Get a mutable reference to the current [`Scope`]. /// Get a mutable reference to the current [`Scope`].
#[inline(always)] #[inline(always)]
#[must_use] #[must_use]
pub fn scope_mut(&mut self) -> &mut &'x mut Scope<'px> { pub fn scope_mut(&mut self) -> &mut &'s mut Scope<'ps> {
&mut self.scope &mut self.scope
} }
/// Get an iterator over the current set of modules imported via `import` statements, /// Get an iterator over the current set of modules imported via `import` statements,

View File

@ -1,72 +0,0 @@
//! Evaluation state.
use crate::func::call::FnResolutionCache;
use crate::StaticVec;
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{collections::BTreeMap, marker::PhantomData};
/// _(internals)_ A type that holds all the current states of the [`Engine`][crate::Engine].
/// Exported under the `internals` feature only.
#[derive(Debug, Clone)]
pub struct EvalState<'a> {
/// Force a [`Scope`][crate::Scope] search by name.
///
/// Normally, access to variables are parsed with a relative offset into the
/// [`Scope`][crate::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>,
/// Take care of the lifetime parameter
dummy: PhantomData<&'a ()>,
}
impl EvalState<'_> {
/// Create a new [`EvalState`].
#[inline(always)]
#[must_use]
pub fn new() -> Self {
Self {
always_search_scope: false,
scope_level: 0,
fn_resolution_caches: StaticVec::new_const(),
dummy: Default::default(),
}
}
/// 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);
}
}

View File

@ -1,6 +1,6 @@
//! Module defining functions for evaluating an expression. //! Module defining functions for evaluating an expression.
use super::{EvalContext, EvalState, GlobalRuntimeState, Target}; use super::{Caches, EvalContext, GlobalRuntimeState, Target};
use crate::ast::{Expr, FnCallExpr, OpAssignment}; use crate::ast::{Expr, FnCallExpr, OpAssignment};
use crate::engine::{KEYWORD_THIS, OP_CONCAT}; use crate::engine::{KEYWORD_THIS, OP_CONCAT};
use crate::types::dynamic::AccessMode; use crate::types::dynamic::AccessMode;
@ -17,7 +17,6 @@ impl Engine {
pub(crate) fn search_imports( pub(crate) fn search_imports(
&self, &self,
global: &GlobalRuntimeState, global: &GlobalRuntimeState,
state: &mut EvalState,
namespace: &crate::ast::Namespace, namespace: &crate::ast::Namespace,
) -> Option<crate::Shared<Module>> { ) -> Option<crate::Shared<Module>> {
assert!(!namespace.is_empty()); assert!(!namespace.is_empty());
@ -25,7 +24,7 @@ impl Engine {
let root = namespace.root(); let root = namespace.root();
// Qualified - check if the root module is directly indexed // Qualified - check if the root module is directly indexed
let index = if state.always_search_scope { let index = if global.always_search_scope {
None None
} else { } else {
namespace.index() namespace.index()
@ -48,7 +47,6 @@ impl Engine {
&self, &self,
scope: &'s mut Scope, scope: &'s mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState,
lib: &[&Module], lib: &[&Module],
this_ptr: &'s mut Option<&mut Dynamic>, this_ptr: &'s mut Option<&mut Dynamic>,
expr: &Expr, expr: &Expr,
@ -56,24 +54,22 @@ impl Engine {
) -> RhaiResultOf<(Target<'s>, Position)> { ) -> RhaiResultOf<(Target<'s>, Position)> {
match expr { match expr {
Expr::Variable(_, Some(_), _) => { Expr::Variable(_, Some(_), _) => {
self.search_scope_only(scope, global, state, lib, this_ptr, expr, level) self.search_scope_only(scope, global, lib, this_ptr, expr, level)
} }
Expr::Variable(v, None, _var_pos) => match v.as_ref() { Expr::Variable(v, None, _var_pos) => match v.as_ref() {
// Normal variable access // Normal variable access
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
(_, ns, ..) if ns.is_empty() => { (_, ns, ..) if ns.is_empty() => {
self.search_scope_only(scope, global, state, lib, this_ptr, expr, level) self.search_scope_only(scope, global, lib, this_ptr, expr, level)
} }
#[cfg(feature = "no_module")] #[cfg(feature = "no_module")]
(_, (), ..) => { (_, (), ..) => self.search_scope_only(scope, global, lib, this_ptr, expr, level),
self.search_scope_only(scope, global, state, lib, this_ptr, expr, level)
}
// Qualified variable access // Qualified variable access
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
(_, namespace, hash_var, var_name) => { (_, namespace, hash_var, var_name) => {
// foo:bar::baz::VARIABLE // foo:bar::baz::VARIABLE
if let Some(module) = self.search_imports(global, state, namespace) { if let Some(module) = self.search_imports(global, namespace) {
return if let Some(mut target) = module.get_qualified_var(*hash_var) { return if let Some(mut target) = module.get_qualified_var(*hash_var) {
// Module variables are constant // Module variables are constant
target.set_access_mode(AccessMode::ReadOnly); target.set_access_mode(AccessMode::ReadOnly);
@ -131,7 +127,6 @@ impl Engine {
&self, &self,
scope: &'s mut Scope, scope: &'s mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState,
lib: &[&Module], lib: &[&Module],
this_ptr: &'s mut Option<&mut Dynamic>, this_ptr: &'s mut Option<&mut Dynamic>,
expr: &Expr, expr: &Expr,
@ -148,7 +143,7 @@ impl Engine {
Err(ERR::ErrorUnboundThis(*pos).into()) Err(ERR::ErrorUnboundThis(*pos).into())
} }
} }
_ if state.always_search_scope => (0, expr.start_position()), _ if global.always_search_scope => (0, expr.start_position()),
Expr::Variable(.., Some(i), pos) => (i.get() as usize, *pos), Expr::Variable(.., Some(i), pos) => (i.get() as usize, *pos),
Expr::Variable(v, None, pos) => (v.0.map(NonZeroUsize::get).unwrap_or(0), *pos), Expr::Variable(v, None, pos) => (v.0.map(NonZeroUsize::get).unwrap_or(0), *pos),
_ => unreachable!("Expr::Variable expected but gets {:?}", expr), _ => unreachable!("Expr::Variable expected but gets {:?}", expr),
@ -160,7 +155,7 @@ impl Engine {
engine: self, engine: self,
scope, scope,
global, global,
state, caches: None,
lib, lib,
this_ptr, this_ptr,
level, level,
@ -205,7 +200,7 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>, this_ptr: &mut Option<&mut Dynamic>,
expr: &FnCallExpr, expr: &FnCallExpr,
@ -228,7 +223,7 @@ impl Engine {
let hash = hashes.native; let hash = hashes.native;
return self.make_qualified_function_call( return self.make_qualified_function_call(
scope, global, state, lib, this_ptr, namespace, name, args, hash, pos, level, scope, global, caches, lib, this_ptr, namespace, name, args, hash, pos, level,
); );
} }
@ -239,7 +234,7 @@ impl Engine {
); );
self.make_function_call( self.make_function_call(
scope, global, state, lib, this_ptr, name, first_arg, args, *hashes, *capture, pos, scope, global, caches, lib, this_ptr, name, first_arg, args, *hashes, *capture, pos,
level, level,
) )
} }
@ -256,7 +251,7 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>, this_ptr: &mut Option<&mut Dynamic>,
expr: &Expr, expr: &Expr,
@ -270,13 +265,13 @@ impl Engine {
if let Expr::FnCall(x, ..) = expr { if let Expr::FnCall(x, ..) = expr {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
let reset_debugger = let reset_debugger =
self.run_debugger_with_reset(scope, global, state, lib, this_ptr, expr, level)?; self.run_debugger_with_reset(scope, global, lib, this_ptr, expr, level)?;
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut global.num_operations, expr.position())?; self.inc_operations(&mut global.num_operations, expr.position())?;
let result = let result =
self.eval_fn_call_expr(scope, global, state, lib, this_ptr, x, x.pos, level); self.eval_fn_call_expr(scope, global, caches, lib, this_ptr, x, x.pos, level);
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
global.debugger.reset_status(reset_debugger); global.debugger.reset_status(reset_debugger);
@ -289,7 +284,7 @@ impl Engine {
// will cost more than the mis-predicted `match` branch. // will cost more than the mis-predicted `match` branch.
if let Expr::Variable(x, index, var_pos) = expr { if let Expr::Variable(x, index, var_pos) = expr {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger(scope, global, state, lib, this_ptr, expr, level)?; self.run_debugger(scope, global, lib, this_ptr, expr, level)?;
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut global.num_operations, expr.position())?; self.inc_operations(&mut global.num_operations, expr.position())?;
@ -300,14 +295,14 @@ impl Engine {
.cloned() .cloned()
.ok_or_else(|| ERR::ErrorUnboundThis(*var_pos).into()) .ok_or_else(|| ERR::ErrorUnboundThis(*var_pos).into())
} else { } else {
self.search_namespace(scope, global, state, lib, this_ptr, expr, level) self.search_namespace(scope, global, lib, this_ptr, expr, level)
.map(|(val, ..)| val.take_or_clone()) .map(|(val, ..)| val.take_or_clone())
}; };
} }
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
let reset_debugger = let reset_debugger =
self.run_debugger_with_reset(scope, global, state, lib, this_ptr, expr, level)?; self.run_debugger_with_reset(scope, global, lib, this_ptr, expr, level)?;
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut global.num_operations, expr.position())?; self.inc_operations(&mut global.num_operations, expr.position())?;
@ -325,12 +320,16 @@ impl Engine {
// `... ${...} ...` // `... ${...} ...`
Expr::InterpolatedString(x, _) => { Expr::InterpolatedString(x, _) => {
let mut concat: Dynamic = self.const_empty_string().into(); let mut concat = self.const_empty_string().into();
let target = &mut concat;
let mut result = Ok(Dynamic::UNIT); let mut result = Ok(Dynamic::UNIT);
let mut op_info = OpAssignment::new_op_assignment(OP_CONCAT, Position::NONE);
let root = ("", Position::NONE);
for expr in x.iter() { for expr in x.iter() {
let item = let item =
match self.eval_expr(scope, global, state, lib, this_ptr, expr, level) { match self.eval_expr(scope, global, caches, lib, this_ptr, expr, level) {
Ok(r) => r, Ok(r) => r,
err => { err => {
result = err; result = err;
@ -338,23 +337,17 @@ impl Engine {
} }
}; };
if let Err(err) = self.eval_op_assignment( op_info.pos = expr.start_position();
global,
state, if let Err(err) = self
lib, .eval_op_assignment(global, caches, lib, op_info, target, root, item, level)
Some(OpAssignment::new(OP_CONCAT)), {
expr.start_position(), result = Err(err);
&mut (&mut concat).into(),
("", Position::NONE),
item,
level,
) {
result = Err(err.fill_position(expr.start_position()));
break; break;
} }
} }
result.map(|_| concat) result.map(|_| concat.take_or_clone())
} }
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
@ -367,7 +360,7 @@ impl Engine {
for item_expr in x.iter() { for item_expr in x.iter() {
let value = match self let value = match self
.eval_expr(scope, global, state, lib, this_ptr, item_expr, level) .eval_expr(scope, global, caches, lib, this_ptr, item_expr, level)
{ {
Ok(r) => r.flatten(), Ok(r) => r.flatten(),
err => { err => {
@ -405,7 +398,7 @@ impl Engine {
for (key, value_expr) in x.0.iter() { for (key, value_expr) in x.0.iter() {
let value = match self let value = match self
.eval_expr(scope, global, state, lib, this_ptr, value_expr, level) .eval_expr(scope, global, caches, lib, this_ptr, value_expr, level)
{ {
Ok(r) => r.flatten(), Ok(r) => r.flatten(),
err => { err => {
@ -431,7 +424,7 @@ impl Engine {
Expr::And(x, ..) => { Expr::And(x, ..) => {
let lhs = self let lhs = self
.eval_expr(scope, global, state, lib, this_ptr, &x.lhs, level) .eval_expr(scope, global, caches, lib, this_ptr, &x.lhs, level)
.and_then(|v| { .and_then(|v| {
v.as_bool().map_err(|typ| { v.as_bool().map_err(|typ| {
self.make_type_mismatch_err::<bool>(typ, x.lhs.position()) self.make_type_mismatch_err::<bool>(typ, x.lhs.position())
@ -439,7 +432,7 @@ impl Engine {
}); });
if let Ok(true) = lhs { if let Ok(true) = lhs {
self.eval_expr(scope, global, state, lib, this_ptr, &x.rhs, level) self.eval_expr(scope, global, caches, lib, this_ptr, &x.rhs, level)
.and_then(|v| { .and_then(|v| {
v.as_bool() v.as_bool()
.map_err(|typ| { .map_err(|typ| {
@ -454,7 +447,7 @@ impl Engine {
Expr::Or(x, ..) => { Expr::Or(x, ..) => {
let lhs = self let lhs = self
.eval_expr(scope, global, state, lib, this_ptr, &x.lhs, level) .eval_expr(scope, global, caches, lib, this_ptr, &x.lhs, level)
.and_then(|v| { .and_then(|v| {
v.as_bool().map_err(|typ| { v.as_bool().map_err(|typ| {
self.make_type_mismatch_err::<bool>(typ, x.lhs.position()) self.make_type_mismatch_err::<bool>(typ, x.lhs.position())
@ -462,7 +455,7 @@ impl Engine {
}); });
if let Ok(false) = lhs { if let Ok(false) = lhs {
self.eval_expr(scope, global, state, lib, this_ptr, &x.rhs, level) self.eval_expr(scope, global, caches, lib, this_ptr, &x.rhs, level)
.and_then(|v| { .and_then(|v| {
v.as_bool() v.as_bool()
.map_err(|typ| { .map_err(|typ| {
@ -491,7 +484,7 @@ impl Engine {
engine: self, engine: self,
scope, scope,
global, global,
state, caches: Some(caches),
lib, lib,
this_ptr, this_ptr,
level, level,
@ -504,17 +497,17 @@ impl Engine {
Expr::Stmt(x) if x.is_empty() => Ok(Dynamic::UNIT), Expr::Stmt(x) if x.is_empty() => Ok(Dynamic::UNIT),
Expr::Stmt(x) => { Expr::Stmt(x) => {
self.eval_stmt_block(scope, global, state, lib, this_ptr, x, true, level) self.eval_stmt_block(scope, global, caches, lib, this_ptr, x, true, level)
} }
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Expr::Index(..) => { Expr::Index(..) => {
self.eval_dot_index_chain(scope, global, state, lib, this_ptr, expr, level, None) self.eval_dot_index_chain(scope, global, caches, lib, this_ptr, expr, level, None)
} }
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Expr::Dot(..) => { Expr::Dot(..) => {
self.eval_dot_index_chain(scope, global, state, lib, this_ptr, expr, level, None) self.eval_dot_index_chain(scope, global, caches, lib, this_ptr, expr, level, None)
} }
_ => unreachable!("expression cannot be evaluated: {:?}", expr), _ => unreachable!("expression cannot be evaluated: {:?}", expr),

View File

@ -30,16 +30,31 @@ pub struct GlobalRuntimeState<'a> {
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
modules: crate::StaticVec<crate::Shared<crate::Module>>, modules: crate::StaticVec<crate::Shared<crate::Module>>,
/// Source of the current context. /// Source of the current context.
///
/// No source if the string is empty. /// No source if the string is empty.
pub source: Identifier, pub source: Identifier,
/// Number of operations performed. /// Number of operations performed.
pub num_operations: u64, pub num_operations: u64,
/// Number of modules loaded. /// Number of modules loaded.
pub num_modules_loaded: usize, pub num_modules_loaded: usize,
/// 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,
/// Force a [`Scope`][crate::Scope] search by name.
///
/// Normally, access to variables are parsed with a relative offset into the
/// [`Scope`][crate::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,
/// Function call hashes to index getters and setters. /// Function call hashes to index getters and setters.
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))] #[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
fn_hash_indexing: (u64, u64), fn_hash_indexing: (u64, u64),
/// Embedded [crate::Module][crate::Module] resolver. /// Embedded [module][crate::Module] resolver.
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
pub embedded_module_resolver: pub embedded_module_resolver:
Option<crate::Shared<crate::module::resolvers::StaticModuleResolver>>, Option<crate::Shared<crate::module::resolvers::StaticModuleResolver>>,
@ -48,7 +63,7 @@ pub struct GlobalRuntimeState<'a> {
/// Interior mutability is needed because it is shared in order to aid in cloning. /// Interior mutability is needed because it is shared in order to aid in cloning.
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
pub(crate) constants: Option<GlobalConstants>, pub constants: Option<GlobalConstants>,
/// Debugging interface. /// Debugging interface.
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
pub debugger: super::Debugger, pub debugger: super::Debugger,
@ -71,6 +86,8 @@ impl GlobalRuntimeState<'_> {
source: Identifier::new_const(), source: Identifier::new_const(),
num_operations: 0, num_operations: 0,
num_modules_loaded: 0, num_modules_loaded: 0,
scope_level: 0,
always_search_scope: false,
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
embedded_module_resolver: None, embedded_module_resolver: None,
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))] #[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
@ -92,7 +109,7 @@ impl GlobalRuntimeState<'_> {
pub fn num_imports(&self) -> usize { pub fn num_imports(&self) -> usize {
self.keys.len() self.keys.len()
} }
/// Get the globally-imported [crate::Module][crate::Module] at a particular index. /// Get the globally-imported [module][crate::Module] at a particular index.
/// ///
/// Not available under `no_module`. /// Not available under `no_module`.
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
@ -101,7 +118,7 @@ impl GlobalRuntimeState<'_> {
pub fn get_shared_import(&self, index: usize) -> Option<crate::Shared<crate::Module>> { pub fn get_shared_import(&self, index: usize) -> Option<crate::Shared<crate::Module>> {
self.modules.get(index).cloned() self.modules.get(index).cloned()
} }
/// Get a mutable reference to the globally-imported [crate::Module][crate::Module] at a /// Get a mutable reference to the globally-imported [module][crate::Module] at a
/// particular index. /// particular index.
/// ///
/// Not available under `no_module`. /// Not available under `no_module`.
@ -115,7 +132,7 @@ impl GlobalRuntimeState<'_> {
) -> Option<&mut crate::Shared<crate::Module>> { ) -> Option<&mut crate::Shared<crate::Module>> {
self.modules.get_mut(index) self.modules.get_mut(index)
} }
/// Get the index of a globally-imported [crate::Module][crate::Module] by name. /// Get the index of a globally-imported [module][crate::Module] by name.
/// ///
/// Not available under `no_module`. /// Not available under `no_module`.
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
@ -132,7 +149,7 @@ impl GlobalRuntimeState<'_> {
} }
}) })
} }
/// Push an imported [crate::Module][crate::Module] onto the stack. /// Push an imported [module][crate::Module] onto the stack.
/// ///
/// Not available under `no_module`. /// Not available under `no_module`.
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]

View File

@ -1,13 +1,14 @@
mod cache;
mod chaining; mod chaining;
mod data_check; mod data_check;
mod debugger; mod debugger;
mod eval_context; mod eval_context;
mod eval_state;
mod expr; mod expr;
mod global_state; mod global_state;
mod stmt; mod stmt;
mod target; mod target;
pub use cache::{Caches, FnResolutionCache, FnResolutionCacheEntry};
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))] #[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
pub use chaining::{ChainArgument, ChainType}; pub use chaining::{ChainArgument, ChainType};
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
@ -16,7 +17,6 @@ pub use debugger::{
OnDebuggerCallback, OnDebuggingInit, OnDebuggerCallback, OnDebuggingInit,
}; };
pub use eval_context::EvalContext; pub use eval_context::EvalContext;
pub use eval_state::EvalState;
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
pub use global_state::GlobalConstants; pub use global_state::GlobalConstants;

View File

@ -1,6 +1,6 @@
//! Module defining functions for evaluating a statement. //! Module defining functions for evaluating a statement.
use super::{EvalContext, EvalState, GlobalRuntimeState, Target}; use super::{Caches, EvalContext, GlobalRuntimeState, Target};
use crate::api::events::VarDefInfo; use crate::api::events::VarDefInfo;
use crate::ast::{ use crate::ast::{
ASTFlags, BinaryExpr, Expr, Ident, OpAssignment, Stmt, SwitchCases, TryCatchBlock, ASTFlags, BinaryExpr, Expr, Ident, OpAssignment, Stmt, SwitchCases, TryCatchBlock,
@ -25,7 +25,7 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>, this_ptr: &mut Option<&mut Dynamic>,
statements: &[Stmt], statements: &[Stmt],
@ -36,14 +36,14 @@ impl Engine {
return Ok(Dynamic::UNIT); return Ok(Dynamic::UNIT);
} }
let orig_always_search_scope = state.always_search_scope; let orig_always_search_scope = global.always_search_scope;
let orig_scope_len = scope.len(); let orig_scope_len = scope.len();
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
let orig_imports_len = global.num_imports(); let orig_imports_len = global.num_imports();
let orig_fn_resolution_caches_len = state.fn_resolution_caches_len(); let orig_fn_resolution_caches_len = caches.fn_resolution_caches_len();
if restore_orig_state { if restore_orig_state {
state.scope_level += 1; global.scope_level += 1;
} }
let mut result = Ok(Dynamic::UNIT); let mut result = Ok(Dynamic::UNIT);
@ -55,7 +55,7 @@ impl Engine {
result = self.eval_stmt( result = self.eval_stmt(
scope, scope,
global, global,
state, caches,
lib, lib,
this_ptr, this_ptr,
stmt, stmt,
@ -76,48 +76,46 @@ impl Engine {
.skip(imports_len) .skip(imports_len)
.any(|(.., m)| m.contains_indexed_global_functions()) .any(|(.., m)| m.contains_indexed_global_functions())
{ {
if state.fn_resolution_caches_len() > orig_fn_resolution_caches_len { if caches.fn_resolution_caches_len() > orig_fn_resolution_caches_len {
// When new module is imported with global functions and there is already // 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 // a new cache, clear it - notice that this is expensive as all function
// resolutions must start again // resolutions must start again
state.fn_resolution_cache_mut().clear(); caches.fn_resolution_cache_mut().clear();
} else if restore_orig_state { } else if restore_orig_state {
// When new module is imported with global functions, push a new cache // When new module is imported with global functions, push a new cache
state.push_fn_resolution_cache(); caches.push_fn_resolution_cache();
} else { } else {
// When the block is to be evaluated in-place, just clear the current cache // When the block is to be evaluated in-place, just clear the current cache
state.fn_resolution_cache_mut().clear(); caches.fn_resolution_cache_mut().clear();
} }
} }
} }
} }
// If imports list is modified, pop the functions lookup cache // If imports list is modified, pop the functions lookup cache
state.rewind_fn_resolution_caches(orig_fn_resolution_caches_len); caches.rewind_fn_resolution_caches(orig_fn_resolution_caches_len);
if restore_orig_state { if restore_orig_state {
scope.rewind(orig_scope_len); scope.rewind(orig_scope_len);
state.scope_level -= 1; global.scope_level -= 1;
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
global.truncate_imports(orig_imports_len); global.truncate_imports(orig_imports_len);
// The impact of new local variables goes away at the end of a block // The impact of new local variables goes away at the end of a block
// because any new variables introduced will go out of scope // because any new variables introduced will go out of scope
state.always_search_scope = orig_always_search_scope; global.always_search_scope = orig_always_search_scope;
} }
result result
} }
/// Evaluate an op-assignment statement. /// Evaluate an op-assignment statement.
/// [`Position`] in [`EvalAltResult`] is [`NONE`][Position::NONE] and should be set afterwards.
pub(crate) fn eval_op_assignment( pub(crate) fn eval_op_assignment(
&self, &self,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
op_info: Option<OpAssignment>, op_info: OpAssignment,
op_pos: Position,
target: &mut Target, target: &mut Target,
root: (&str, Position), root: (&str, Position),
new_val: Dynamic, new_val: Dynamic,
@ -130,13 +128,15 @@ impl Engine {
let mut new_val = new_val; let mut new_val = new_val;
if let Some(OpAssignment { if op_info.is_op_assignment() {
hash_op_assign, let OpAssignment {
hash_op, hash_op_assign,
op_assign, hash_op,
op, op_assign,
}) = op_info op,
{ pos: op_pos,
} = op_info;
let mut lock_guard; let mut lock_guard;
let lhs_ptr_inner; let lhs_ptr_inner;
@ -157,7 +157,7 @@ impl Engine {
let level = level + 1; let level = level + 1;
match self.call_native_fn( match self.call_native_fn(
global, state, lib, op_assign, hash, args, true, true, op_pos, level, global, caches, lib, op_assign, hash, args, true, true, op_pos, level,
) { ) {
Ok(_) => { Ok(_) => {
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
@ -166,9 +166,11 @@ impl Engine {
Err(err) if matches!(*err, ERR::ErrorFunctionNotFound(ref f, ..) if f.starts_with(op_assign)) => Err(err) if matches!(*err, ERR::ErrorFunctionNotFound(ref f, ..) if f.starts_with(op_assign)) =>
{ {
// Expand to `var = var op rhs` // Expand to `var = var op rhs`
let (value, ..) = self.call_native_fn( let (value, ..) = self
global, state, lib, op, hash_op, args, true, false, op_pos, level, .call_native_fn(
)?; global, caches, lib, op, hash_op, args, true, false, op_pos, level,
)
.map_err(|err| err.fill_position(op_info.pos))?;
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
self.check_data_size(&value, root.1)?; self.check_data_size(&value, root.1)?;
@ -182,7 +184,9 @@ impl Engine {
*target.as_mut() = new_val; *target.as_mut() = new_val;
} }
target.propagate_changed_value() target
.propagate_changed_value()
.map_err(|err| err.fill_position(op_info.pos))
} }
/// Evaluate a statement. /// Evaluate a statement.
@ -197,7 +201,7 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>, this_ptr: &mut Option<&mut Dynamic>,
stmt: &Stmt, stmt: &Stmt,
@ -206,7 +210,7 @@ impl Engine {
) -> RhaiResult { ) -> RhaiResult {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
let reset_debugger = let reset_debugger =
self.run_debugger_with_reset(scope, global, state, lib, this_ptr, stmt, level)?; self.run_debugger_with_reset(scope, global, lib, this_ptr, stmt, level)?;
// Coded this way for better branch prediction. // Coded this way for better branch prediction.
// Popular branches are lifted out of the `match` statement into their own branches. // Popular branches are lifted out of the `match` statement into their own branches.
@ -217,7 +221,7 @@ impl Engine {
self.inc_operations(&mut global.num_operations, stmt.position())?; self.inc_operations(&mut global.num_operations, stmt.position())?;
let result = let result =
self.eval_fn_call_expr(scope, global, state, lib, this_ptr, x, x.pos, level); self.eval_fn_call_expr(scope, global, caches, lib, this_ptr, x, x.pos, level);
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
global.debugger.reset_status(reset_debugger); global.debugger.reset_status(reset_debugger);
@ -228,7 +232,7 @@ impl Engine {
// Then assignments. // Then assignments.
// We shouldn't do this for too many variants because, soon or later, the added comparisons // 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. // will cost more than the mis-predicted `match` branch.
if let Stmt::Assignment(x, op_pos) = stmt { if let Stmt::Assignment(x, ..) = stmt {
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut global.num_operations, stmt.position())?; self.inc_operations(&mut global.num_operations, stmt.position())?;
@ -236,12 +240,12 @@ impl Engine {
let (op_info, BinaryExpr { lhs, rhs }) = x.as_ref(); let (op_info, BinaryExpr { lhs, rhs }) = x.as_ref();
let rhs_result = self let rhs_result = self
.eval_expr(scope, global, state, lib, this_ptr, rhs, level) .eval_expr(scope, global, caches, lib, this_ptr, rhs, level)
.map(Dynamic::flatten); .map(Dynamic::flatten);
if let Ok(rhs_val) = rhs_result { if let Ok(rhs_val) = rhs_result {
let search_result = let search_result =
self.search_namespace(scope, global, state, lib, this_ptr, lhs, level); self.search_namespace(scope, global, lib, this_ptr, lhs, level);
if let Ok(search_val) = search_result { if let Ok(search_val) = search_result {
let (mut lhs_ptr, pos) = search_val; let (mut lhs_ptr, pos) = search_val;
@ -261,9 +265,8 @@ impl Engine {
let lhs_ptr = &mut lhs_ptr; let lhs_ptr = &mut lhs_ptr;
self.eval_op_assignment( self.eval_op_assignment(
global, state, lib, *op_info, *op_pos, lhs_ptr, root, rhs_val, level, global, caches, lib, *op_info, lhs_ptr, root, rhs_val, level,
) )
.map_err(|err| err.fill_position(rhs.start_position()))
.map(|_| Dynamic::UNIT) .map(|_| Dynamic::UNIT)
} else { } else {
search_result.map(|_| Dynamic::UNIT) search_result.map(|_| Dynamic::UNIT)
@ -275,11 +278,11 @@ impl Engine {
let (op_info, BinaryExpr { lhs, rhs }) = x.as_ref(); let (op_info, BinaryExpr { lhs, rhs }) = x.as_ref();
let rhs_result = self let rhs_result = self
.eval_expr(scope, global, state, lib, this_ptr, rhs, level) .eval_expr(scope, global, caches, lib, this_ptr, rhs, level)
.map(Dynamic::flatten); .map(Dynamic::flatten);
if let Ok(rhs_val) = rhs_result { if let Ok(rhs_val) = rhs_result {
let _new_val = Some(((rhs_val, rhs.start_position()), (*op_info, *op_pos))); let _new_val = Some((rhs_val, *op_info));
// Must be either `var[index] op= val` or `var.prop op= val` // Must be either `var[index] op= val` or `var.prop op= val`
match lhs { match lhs {
@ -291,14 +294,14 @@ impl Engine {
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Expr::Index(..) => self Expr::Index(..) => self
.eval_dot_index_chain( .eval_dot_index_chain(
scope, global, state, lib, this_ptr, lhs, level, _new_val, scope, global, caches, lib, this_ptr, lhs, level, _new_val,
) )
.map(|_| Dynamic::UNIT), .map(|_| Dynamic::UNIT),
// dot_lhs.dot_rhs op= rhs // dot_lhs.dot_rhs op= rhs
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Expr::Dot(..) => self Expr::Dot(..) => self
.eval_dot_index_chain( .eval_dot_index_chain(
scope, global, state, lib, this_ptr, lhs, level, _new_val, scope, global, caches, lib, this_ptr, lhs, level, _new_val,
) )
.map(|_| Dynamic::UNIT), .map(|_| Dynamic::UNIT),
_ => unreachable!("cannot assign to expression: {:?}", lhs), _ => unreachable!("cannot assign to expression: {:?}", lhs),
@ -323,21 +326,21 @@ impl Engine {
// Expression as statement // Expression as statement
Stmt::Expr(expr) => self Stmt::Expr(expr) => self
.eval_expr(scope, global, state, lib, this_ptr, expr, level) .eval_expr(scope, global, caches, lib, this_ptr, expr, level)
.map(Dynamic::flatten), .map(Dynamic::flatten),
// Block scope // Block scope
Stmt::Block(statements, ..) if statements.is_empty() => Ok(Dynamic::UNIT), Stmt::Block(statements, ..) if statements.is_empty() => Ok(Dynamic::UNIT),
Stmt::Block(statements, ..) => { Stmt::Block(statements, ..) => self.eval_stmt_block(
self.eval_stmt_block(scope, global, state, lib, this_ptr, statements, true, level) scope, global, caches, lib, this_ptr, statements, true, level,
} ),
// If statement // If statement
Stmt::If(x, ..) => { Stmt::If(x, ..) => {
let (expr, if_block, else_block) = x.as_ref(); let (expr, if_block, else_block) = x.as_ref();
let guard_val = self let guard_val = self
.eval_expr(scope, global, state, lib, this_ptr, expr, level) .eval_expr(scope, global, caches, lib, this_ptr, expr, level)
.and_then(|v| { .and_then(|v| {
v.as_bool().map_err(|typ| { v.as_bool().map_err(|typ| {
self.make_type_mismatch_err::<bool>(typ, expr.position()) self.make_type_mismatch_err::<bool>(typ, expr.position())
@ -348,7 +351,7 @@ impl Engine {
Ok(true) => { Ok(true) => {
if !if_block.is_empty() { if !if_block.is_empty() {
self.eval_stmt_block( self.eval_stmt_block(
scope, global, state, lib, this_ptr, if_block, true, level, scope, global, caches, lib, this_ptr, if_block, true, level,
) )
} else { } else {
Ok(Dynamic::UNIT) Ok(Dynamic::UNIT)
@ -357,7 +360,7 @@ impl Engine {
Ok(false) => { Ok(false) => {
if !else_block.is_empty() { if !else_block.is_empty() {
self.eval_stmt_block( self.eval_stmt_block(
scope, global, state, lib, this_ptr, else_block, true, level, scope, global, caches, lib, this_ptr, else_block, true, level,
) )
} else { } else {
Ok(Dynamic::UNIT) Ok(Dynamic::UNIT)
@ -378,7 +381,8 @@ impl Engine {
}, },
) = x.as_ref(); ) = x.as_ref();
let value_result = self.eval_expr(scope, global, state, lib, this_ptr, expr, level); let value_result =
self.eval_expr(scope, global, caches, lib, this_ptr, expr, level);
if let Ok(value) = value_result { if let Ok(value) = value_result {
let stmt_block_result = if value.is_hashable() { let stmt_block_result = if value.is_hashable() {
@ -388,21 +392,16 @@ impl Engine {
// First check hashes // First check hashes
if let Some(case_block) = cases.get(&hash) { if let Some(case_block) = cases.get(&hash) {
let cond_result = case_block let cond_result = match case_block.condition {
.condition Expr::BoolConstant(b, ..) => Ok(b),
.as_ref() ref c => self
.map(|cond| { .eval_expr(scope, global, caches, lib, this_ptr, c, level)
self.eval_expr(scope, global, state, lib, this_ptr, cond, level) .and_then(|v| {
.and_then(|v| { v.as_bool().map_err(|typ| {
v.as_bool().map_err(|typ| { self.make_type_mismatch_err::<bool>(typ, c.position())
self.make_type_mismatch_err::<bool>(
typ,
cond.position(),
)
})
}) })
}) }),
.unwrap_or(Ok(true)); };
match cond_result { match cond_result {
Ok(true) => Ok(Some(&case_block.statements)), Ok(true) => Ok(Some(&case_block.statements)),
@ -420,23 +419,19 @@ impl Engine {
|| (inclusive && (start..=end).contains(&value)) || (inclusive && (start..=end).contains(&value))
}) })
{ {
let cond_result = block let cond_result = match block.condition {
.condition Expr::BoolConstant(b, ..) => Ok(b),
.as_ref() ref c => self
.map(|cond| { .eval_expr(scope, global, caches, lib, this_ptr, c, level)
self.eval_expr(
scope, global, state, lib, this_ptr, cond, level,
)
.and_then(|v| { .and_then(|v| {
v.as_bool().map_err(|typ| { v.as_bool().map_err(|typ| {
self.make_type_mismatch_err::<bool>( self.make_type_mismatch_err::<bool>(
typ, typ,
cond.position(), c.position(),
) )
}) })
}) }),
}) };
.unwrap_or(Ok(true));
match cond_result { match cond_result {
Ok(true) => result = Ok(Some(&block.statements)), Ok(true) => result = Ok(Some(&block.statements)),
@ -460,7 +455,7 @@ impl Engine {
if let Ok(Some(statements)) = stmt_block_result { if let Ok(Some(statements)) = stmt_block_result {
if !statements.is_empty() { if !statements.is_empty() {
self.eval_stmt_block( self.eval_stmt_block(
scope, global, state, lib, this_ptr, statements, true, level, scope, global, caches, lib, this_ptr, statements, true, level,
) )
} else { } else {
Ok(Dynamic::UNIT) Ok(Dynamic::UNIT)
@ -469,7 +464,7 @@ impl Engine {
// Default match clause // Default match clause
if !def_case.is_empty() { if !def_case.is_empty() {
self.eval_stmt_block( self.eval_stmt_block(
scope, global, state, lib, this_ptr, def_case, true, level, scope, global, caches, lib, this_ptr, def_case, true, level,
) )
} else { } else {
Ok(Dynamic::UNIT) Ok(Dynamic::UNIT)
@ -488,7 +483,7 @@ impl Engine {
if !body.is_empty() { if !body.is_empty() {
match self match self
.eval_stmt_block(scope, global, state, lib, this_ptr, body, true, level) .eval_stmt_block(scope, global, caches, lib, this_ptr, body, true, level)
{ {
Ok(_) => (), Ok(_) => (),
Err(err) => match *err { Err(err) => match *err {
@ -508,7 +503,7 @@ impl Engine {
let (expr, body) = x.as_ref(); let (expr, body) = x.as_ref();
let condition = self let condition = self
.eval_expr(scope, global, state, lib, this_ptr, expr, level) .eval_expr(scope, global, caches, lib, this_ptr, expr, level)
.and_then(|v| { .and_then(|v| {
v.as_bool().map_err(|typ| { v.as_bool().map_err(|typ| {
self.make_type_mismatch_err::<bool>(typ, expr.position()) self.make_type_mismatch_err::<bool>(typ, expr.position())
@ -519,9 +514,9 @@ impl Engine {
Ok(false) => break Ok(Dynamic::UNIT), Ok(false) => break Ok(Dynamic::UNIT),
Ok(true) if body.is_empty() => (), Ok(true) if body.is_empty() => (),
Ok(true) => { Ok(true) => {
match self match self.eval_stmt_block(
.eval_stmt_block(scope, global, state, lib, this_ptr, body, true, level) scope, global, caches, lib, this_ptr, body, true, level,
{ ) {
Ok(_) => (), Ok(_) => (),
Err(err) => match *err { Err(err) => match *err {
ERR::LoopBreak(false, ..) => (), ERR::LoopBreak(false, ..) => (),
@ -541,7 +536,7 @@ impl Engine {
if !body.is_empty() { if !body.is_empty() {
match self match self
.eval_stmt_block(scope, global, state, lib, this_ptr, body, true, level) .eval_stmt_block(scope, global, caches, lib, this_ptr, body, true, level)
{ {
Ok(_) => (), Ok(_) => (),
Err(err) => match *err { Err(err) => match *err {
@ -553,7 +548,7 @@ impl Engine {
} }
let condition = self let condition = self
.eval_expr(scope, global, state, lib, this_ptr, &expr, level) .eval_expr(scope, global, caches, lib, this_ptr, &expr, level)
.and_then(|v| { .and_then(|v| {
v.as_bool().map_err(|typ| { v.as_bool().map_err(|typ| {
self.make_type_mismatch_err::<bool>(typ, expr.position()) self.make_type_mismatch_err::<bool>(typ, expr.position())
@ -572,7 +567,7 @@ impl Engine {
let (var_name, counter, expr, statements) = x.as_ref(); let (var_name, counter, expr, statements) = x.as_ref();
let iter_result = self let iter_result = self
.eval_expr(scope, global, state, lib, this_ptr, expr, level) .eval_expr(scope, global, caches, lib, this_ptr, expr, level)
.map(Dynamic::flatten); .map(Dynamic::flatten);
if let Ok(iter_obj) = iter_result { if let Ok(iter_obj) = iter_result {
@ -671,7 +666,7 @@ impl Engine {
} }
let result = self.eval_stmt_block( let result = self.eval_stmt_block(
scope, global, state, lib, this_ptr, statements, true, level, scope, global, caches, lib, this_ptr, statements, true, level,
); );
match result { match result {
@ -715,7 +710,7 @@ impl Engine {
} = x.as_ref(); } = x.as_ref();
let result = self let result = self
.eval_stmt_block(scope, global, state, lib, this_ptr, try_block, true, level) .eval_stmt_block(scope, global, caches, lib, this_ptr, try_block, true, level)
.map(|_| Dynamic::UNIT); .map(|_| Dynamic::UNIT);
match result { match result {
@ -767,7 +762,7 @@ impl Engine {
let result = self.eval_stmt_block( let result = self.eval_stmt_block(
scope, scope,
global, global,
state, caches,
lib, lib,
this_ptr, this_ptr,
catch_block, catch_block,
@ -794,7 +789,7 @@ impl Engine {
// Throw value // Throw value
Stmt::Return(Some(expr), options, pos) if options.contains(ASTFlags::BREAK) => self Stmt::Return(Some(expr), options, pos) if options.contains(ASTFlags::BREAK) => self
.eval_expr(scope, global, state, lib, this_ptr, expr, level) .eval_expr(scope, global, caches, lib, this_ptr, expr, level)
.and_then(|v| Err(ERR::ErrorRuntime(v.flatten(), *pos).into())), .and_then(|v| Err(ERR::ErrorRuntime(v.flatten(), *pos).into())),
// Empty throw // Empty throw
@ -804,7 +799,7 @@ impl Engine {
// Return value // Return value
Stmt::Return(Some(expr), .., pos) => self Stmt::Return(Some(expr), .., pos) => self
.eval_expr(scope, global, state, lib, this_ptr, expr, level) .eval_expr(scope, global, caches, lib, this_ptr, expr, level)
.and_then(|v| Err(ERR::Return(v.flatten(), *pos).into())), .and_then(|v| Err(ERR::Return(v.flatten(), *pos).into())),
// Empty return // Empty return
@ -828,7 +823,7 @@ impl Engine {
// Check variable definition filter // Check variable definition filter
let result = if let Some(ref filter) = self.def_var_filter { let result = if let Some(ref filter) = self.def_var_filter {
let will_shadow = scope.contains(var_name); let will_shadow = scope.contains(var_name);
let nesting_level = state.scope_level; let nesting_level = global.scope_level;
let is_const = access == AccessMode::ReadOnly; let is_const = access == AccessMode::ReadOnly;
let info = VarDefInfo { let info = VarDefInfo {
name: var_name, name: var_name,
@ -840,7 +835,7 @@ impl Engine {
engine: self, engine: self,
scope, scope,
global, global,
state, caches: None,
lib, lib,
this_ptr, this_ptr,
level, level,
@ -864,7 +859,7 @@ impl Engine {
} else { } else {
// Evaluate initial value // Evaluate initial value
let value_result = self let value_result = self
.eval_expr(scope, global, state, lib, this_ptr, expr, level) .eval_expr(scope, global, caches, lib, this_ptr, expr, level)
.map(Dynamic::flatten); .map(Dynamic::flatten);
if let Ok(mut value) = value_result { if let Ok(mut value) = value_result {
@ -872,7 +867,7 @@ impl Engine {
// Put global constants into global module // Put global constants into global module
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
if state.scope_level == 0 if global.scope_level == 0
&& access == AccessMode::ReadOnly && access == AccessMode::ReadOnly
&& lib.iter().any(|&m| !m.is_empty()) && lib.iter().any(|&m| !m.is_empty())
{ {
@ -927,7 +922,7 @@ impl Engine {
} }
let path_result = self let path_result = self
.eval_expr(scope, global, state, lib, this_ptr, &expr, level) .eval_expr(scope, global, caches, lib, this_ptr, &expr, level)
.and_then(|v| { .and_then(|v| {
let typ = v.type_name(); let typ = v.type_name();
v.try_cast::<crate::ImmutableString>().ok_or_else(|| { v.try_cast::<crate::ImmutableString>().ok_or_else(|| {

View File

@ -272,6 +272,8 @@ impl<'a> Target<'a> {
} }
/// Propagate a changed value back to the original source. /// Propagate a changed value back to the original source.
/// This has no effect for direct references. /// This has no effect for direct references.
///
/// [`Position`] in [`EvalAltResult`] is [`NONE`][Position::NONE] and should be set afterwards.
#[inline] #[inline]
pub fn propagate_changed_value(&mut self) -> RhaiResultOf<()> { pub fn propagate_changed_value(&mut self) -> RhaiResultOf<()> {
match self { match self {

View File

@ -9,7 +9,7 @@ use crate::engine::{
KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, KEYWORD_FN_PTR_CALL, KEYWORD_FN_PTR_CURRY, KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, 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::eval::{Caches, FnResolutionCacheEntry, GlobalRuntimeState};
use crate::{ use crate::{
calc_fn_hash, calc_fn_params_hash, combine_hashes, Dynamic, Engine, FnArgsVec, FnPtr, calc_fn_hash, calc_fn_params_hash, combine_hashes, Dynamic, Engine, FnArgsVec, FnPtr,
Identifier, ImmutableString, Module, OptimizationLevel, Position, RhaiError, RhaiResult, Identifier, ImmutableString, Module, OptimizationLevel, Position, RhaiError, RhaiResult,
@ -19,7 +19,6 @@ use crate::{
use std::prelude::v1::*; use std::prelude::v1::*;
use std::{ use std::{
any::{type_name, TypeId}, any::{type_name, TypeId},
collections::BTreeMap,
convert::TryFrom, convert::TryFrom,
mem, mem,
}; };
@ -128,24 +127,6 @@ pub fn ensure_no_data_race(
Ok(()) Ok(())
} }
/// _(internals)_ An entry in a function resolution cache.
/// Exported under the `internals` feature only.
#[derive(Debug, Clone)]
pub struct FnResolutionCacheEntry {
/// Function.
pub func: CallableFunction,
/// Optional source.
/// No source if the string is empty.
pub source: Identifier,
}
/// _(internals)_ A function resolution cache.
/// Exported under the `internals` feature only.
///
/// [`FnResolutionCacheEntry`] is [`Box`]ed in order to pack as many entries inside a single B-Tree
/// level as possible.
pub type FnResolutionCache = BTreeMap<u64, Option<Box<FnResolutionCacheEntry>>>;
impl Engine { impl Engine {
/// Generate the signature for a function call. /// Generate the signature for a function call.
#[inline] #[inline]
@ -196,7 +177,7 @@ impl Engine {
fn resolve_fn<'s>( fn resolve_fn<'s>(
&self, &self,
_global: &GlobalRuntimeState, _global: &GlobalRuntimeState,
state: &'s mut EvalState, state: &'s mut Caches,
lib: &[&Module], lib: &[&Module],
fn_name: &str, fn_name: &str,
hash_script: u64, hash_script: u64,
@ -344,7 +325,7 @@ impl Engine {
pub(crate) fn call_native_fn( pub(crate) fn call_native_fn(
&self, &self,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
name: &str, name: &str,
hash: u64, hash: u64,
@ -362,7 +343,7 @@ impl Engine {
// Check if function access already in the cache // Check if function access already in the cache
let func = self.resolve_fn( let func = self.resolve_fn(
global, global,
state, caches,
lib, lib,
name, name,
hash, hash,
@ -438,9 +419,7 @@ impl Engine {
Ok(ref r) => crate::eval::DebuggerEvent::FunctionExitWithValue(r), Ok(ref r) => crate::eval::DebuggerEvent::FunctionExitWithValue(r),
Err(ref err) => crate::eval::DebuggerEvent::FunctionExitWithError(err), Err(ref err) => crate::eval::DebuggerEvent::FunctionExitWithError(err),
}; };
match self match self.run_debugger_raw(scope, global, lib, &mut None, node, event, level) {
.run_debugger_raw(scope, global, state, lib, &mut None, node, event, level)
{
Ok(_) => (), Ok(_) => (),
Err(err) => _result = Err(err), Err(err) => _result = Err(err),
} }
@ -576,7 +555,7 @@ impl Engine {
&self, &self,
_scope: Option<&mut Scope>, _scope: Option<&mut Scope>,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
fn_name: &str, fn_name: &str,
hashes: FnCallHashes, hashes: FnCallHashes,
@ -619,7 +598,7 @@ impl Engine {
false false
} else { } else {
let hash_script = calc_fn_hash(fn_name.as_str(), num_params as usize); let hash_script = calc_fn_hash(fn_name.as_str(), num_params as usize);
self.has_script_fn(Some(global), state, lib, hash_script) self.has_script_fn(Some(global), caches, lib, hash_script)
} }
.into(), .into(),
false, false,
@ -650,7 +629,7 @@ impl Engine {
if let Some(FnResolutionCacheEntry { func, mut source }) = self if let Some(FnResolutionCacheEntry { func, mut source }) = self
.resolve_fn( .resolve_fn(
global, global,
state, caches,
lib, lib,
fn_name, fn_name,
hashes.script, hashes.script,
@ -687,7 +666,7 @@ impl Engine {
self.call_script_fn( self.call_script_fn(
scope, scope,
global, global,
state, caches,
lib, lib,
&mut Some(*first_arg), &mut Some(*first_arg),
func, func,
@ -706,7 +685,7 @@ impl Engine {
} }
let result = self.call_script_fn( let result = self.call_script_fn(
scope, global, state, lib, &mut None, func, args, true, pos, level, scope, global, caches, lib, &mut None, func, args, true, pos, level,
); );
// Restore the original reference // Restore the original reference
@ -724,7 +703,7 @@ impl Engine {
// Native function call // Native function call
let hash = hashes.native; let hash = hashes.native;
self.call_native_fn( self.call_native_fn(
global, state, lib, fn_name, hash, args, is_ref_mut, false, pos, level, global, caches, lib, fn_name, hash, args, is_ref_mut, false, pos, level,
) )
} }
@ -735,13 +714,13 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
statements: &[Stmt], statements: &[Stmt],
lib: &[&Module], lib: &[&Module],
level: usize, level: usize,
) -> RhaiResult { ) -> RhaiResult {
self.eval_stmt_block( self.eval_stmt_block(
scope, global, state, lib, &mut None, statements, false, level, scope, global, caches, lib, &mut None, statements, false, level,
) )
.or_else(|err| match *err { .or_else(|err| match *err {
ERR::Return(out, ..) => Ok(out), ERR::Return(out, ..) => Ok(out),
@ -757,7 +736,7 @@ impl Engine {
pub(crate) fn make_method_call( pub(crate) fn make_method_call(
&self, &self,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
fn_name: &str, fn_name: &str,
mut hash: FnCallHashes, mut hash: FnCallHashes,
@ -786,7 +765,7 @@ impl Engine {
// Map it to name(args) in function-call style // Map it to name(args) in function-call style
self.exec_fn_call( self.exec_fn_call(
None, global, state, lib, fn_name, new_hash, &mut args, false, false, pos, None, global, caches, lib, fn_name, new_hash, &mut args, false, false, pos,
level, level,
) )
} }
@ -822,7 +801,7 @@ impl Engine {
// Map it to name(args) in function-call style // Map it to name(args) in function-call style
self.exec_fn_call( self.exec_fn_call(
None, global, state, lib, fn_name, new_hash, &mut args, is_ref_mut, true, pos, None, global, caches, lib, fn_name, new_hash, &mut args, is_ref_mut, true, pos,
level, level,
) )
} }
@ -892,7 +871,7 @@ impl Engine {
args.extend(call_args.iter_mut()); args.extend(call_args.iter_mut());
self.exec_fn_call( self.exec_fn_call(
None, global, state, lib, fn_name, hash, &mut args, is_ref_mut, true, pos, None, global, caches, lib, fn_name, hash, &mut args, is_ref_mut, true, pos,
level, level,
) )
} }
@ -914,7 +893,7 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>, this_ptr: &mut Option<&mut Dynamic>,
arg_expr: &Expr, arg_expr: &Expr,
@ -924,7 +903,7 @@ impl Engine {
if self.debugger.is_some() { if self.debugger.is_some() {
if let Some(value) = arg_expr.get_literal_value() { if let Some(value) = arg_expr.get_literal_value() {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger(scope, global, state, lib, this_ptr, arg_expr, level)?; self.run_debugger(scope, global, lib, this_ptr, arg_expr, level)?;
return Ok((value, arg_expr.start_position())); return Ok((value, arg_expr.start_position()));
} }
} }
@ -935,7 +914,7 @@ impl Engine {
matches!(status, crate::eval::DebuggerStatus::FunctionExit(..)) matches!(status, crate::eval::DebuggerStatus::FunctionExit(..))
}); });
let result = self.eval_expr(scope, global, state, lib, this_ptr, arg_expr, level); let result = self.eval_expr(scope, global, caches, lib, this_ptr, arg_expr, level);
// Restore function exit status // Restore function exit status
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
@ -949,7 +928,7 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>, this_ptr: &mut Option<&mut Dynamic>,
fn_name: &str, fn_name: &str,
@ -973,7 +952,7 @@ impl Engine {
KEYWORD_FN_PTR_CALL if total_args >= 1 => { KEYWORD_FN_PTR_CALL if total_args >= 1 => {
let arg = first_arg.unwrap(); let arg = first_arg.unwrap();
let (arg_value, arg_pos) = let (arg_value, arg_pos) =
self.get_arg_value(scope, global, state, lib, this_ptr, arg, level)?; self.get_arg_value(scope, global, caches, lib, this_ptr, arg, level)?;
if !arg_value.is::<FnPtr>() { if !arg_value.is::<FnPtr>() {
let typ = self.map_type_name(arg_value.type_name()); let typ = self.map_type_name(arg_value.type_name());
@ -1006,7 +985,7 @@ impl Engine {
KEYWORD_FN_PTR if total_args == 1 => { KEYWORD_FN_PTR if total_args == 1 => {
let arg = first_arg.unwrap(); let arg = first_arg.unwrap();
let (arg_value, arg_pos) = let (arg_value, arg_pos) =
self.get_arg_value(scope, global, state, lib, this_ptr, arg, level)?; self.get_arg_value(scope, global, caches, lib, this_ptr, arg, level)?;
// Fn - only in function call style // Fn - only in function call style
return arg_value return arg_value
@ -1021,7 +1000,7 @@ impl Engine {
KEYWORD_FN_PTR_CURRY if total_args > 1 => { KEYWORD_FN_PTR_CURRY if total_args > 1 => {
let first = first_arg.unwrap(); let first = first_arg.unwrap();
let (arg_value, arg_pos) = let (arg_value, arg_pos) =
self.get_arg_value(scope, global, state, lib, this_ptr, first, level)?; self.get_arg_value(scope, global, caches, lib, this_ptr, first, level)?;
if !arg_value.is::<FnPtr>() { if !arg_value.is::<FnPtr>() {
let typ = self.map_type_name(arg_value.type_name()); let typ = self.map_type_name(arg_value.type_name());
@ -1033,7 +1012,7 @@ impl Engine {
// Append the new curried arguments to the existing list. // Append the new curried arguments to the existing list.
let fn_curry = a_expr.iter().try_fold(fn_curry, |mut curried, expr| { let fn_curry = a_expr.iter().try_fold(fn_curry, |mut curried, expr| {
let (value, ..) = let (value, ..) =
self.get_arg_value(scope, global, state, lib, this_ptr, expr, level)?; self.get_arg_value(scope, global, caches, lib, this_ptr, expr, level)?;
curried.push(value); curried.push(value);
Ok::<_, RhaiError>(curried) Ok::<_, RhaiError>(curried)
})?; })?;
@ -1046,7 +1025,7 @@ impl Engine {
crate::engine::KEYWORD_IS_SHARED if total_args == 1 => { crate::engine::KEYWORD_IS_SHARED if total_args == 1 => {
let arg = first_arg.unwrap(); let arg = first_arg.unwrap();
let (arg_value, ..) = let (arg_value, ..) =
self.get_arg_value(scope, global, state, lib, this_ptr, arg, level)?; self.get_arg_value(scope, global, caches, lib, this_ptr, arg, level)?;
return Ok(arg_value.is_shared().into()); return Ok(arg_value.is_shared().into());
} }
@ -1055,14 +1034,14 @@ impl Engine {
crate::engine::KEYWORD_IS_DEF_FN if total_args == 2 => { crate::engine::KEYWORD_IS_DEF_FN if total_args == 2 => {
let first = first_arg.unwrap(); let first = first_arg.unwrap();
let (arg_value, arg_pos) = let (arg_value, arg_pos) =
self.get_arg_value(scope, global, state, lib, this_ptr, first, level)?; self.get_arg_value(scope, global, caches, lib, this_ptr, first, level)?;
let fn_name = arg_value let fn_name = arg_value
.into_immutable_string() .into_immutable_string()
.map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, arg_pos))?; .map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, arg_pos))?;
let (arg_value, arg_pos) = let (arg_value, arg_pos) =
self.get_arg_value(scope, global, state, lib, this_ptr, &a_expr[0], level)?; self.get_arg_value(scope, global, caches, lib, this_ptr, &a_expr[0], level)?;
let num_params = arg_value let num_params = arg_value
.as_int() .as_int()
@ -1072,7 +1051,7 @@ impl Engine {
false false
} else { } else {
let hash_script = calc_fn_hash(&fn_name, num_params as usize); let hash_script = calc_fn_hash(&fn_name, num_params as usize);
self.has_script_fn(Some(global), state, lib, hash_script) self.has_script_fn(Some(global), caches, lib, hash_script)
} }
.into()); .into());
} }
@ -1081,7 +1060,7 @@ impl Engine {
KEYWORD_IS_DEF_VAR if total_args == 1 => { KEYWORD_IS_DEF_VAR if total_args == 1 => {
let arg = first_arg.unwrap(); let arg = first_arg.unwrap();
let (arg_value, arg_pos) = let (arg_value, arg_pos) =
self.get_arg_value(scope, global, state, lib, this_ptr, arg, level)?; self.get_arg_value(scope, global, caches, lib, this_ptr, arg, level)?;
let var_name = arg_value let var_name = arg_value
.into_immutable_string() .into_immutable_string()
.map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, arg_pos))?; .map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, arg_pos))?;
@ -1094,14 +1073,14 @@ impl Engine {
let orig_scope_len = scope.len(); let orig_scope_len = scope.len();
let arg = first_arg.unwrap(); let arg = first_arg.unwrap();
let (arg_value, pos) = let (arg_value, pos) =
self.get_arg_value(scope, global, state, lib, this_ptr, arg, level)?; self.get_arg_value(scope, global, caches, lib, this_ptr, arg, level)?;
let script = &arg_value let script = &arg_value
.into_immutable_string() .into_immutable_string()
.map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, pos))?; .map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, pos))?;
let result = self.eval_script_expr_in_place( let result = self.eval_script_expr_in_place(
scope, scope,
global, global,
state, caches,
lib, lib,
script, script,
pos, pos,
@ -1111,7 +1090,7 @@ impl Engine {
// IMPORTANT! If the eval defines new variables in the current scope, // IMPORTANT! If the eval defines new variables in the current scope,
// all variable offsets from this point on will be mis-aligned. // all variable offsets from this point on will be mis-aligned.
if scope.len() != orig_scope_len { if scope.len() != orig_scope_len {
state.always_search_scope = true; global.always_search_scope = true;
} }
return result.map_err(|err| { return result.map_err(|err| {
@ -1143,7 +1122,7 @@ impl Engine {
.map(|&v| v) .map(|&v| v)
.chain(a_expr.iter()) .chain(a_expr.iter())
.try_for_each(|expr| { .try_for_each(|expr| {
self.get_arg_value(scope, global, state, lib, this_ptr, expr, level) self.get_arg_value(scope, global, caches, lib, this_ptr, expr, level)
.map(|(value, ..)| arg_values.push(value.flatten())) .map(|(value, ..)| arg_values.push(value.flatten()))
})?; })?;
args.extend(curry.iter_mut()); args.extend(curry.iter_mut());
@ -1154,7 +1133,7 @@ impl Engine {
return self return self
.exec_fn_call( .exec_fn_call(
scope, global, state, lib, name, hashes, &mut args, is_ref_mut, false, pos, scope, global, caches, lib, name, hashes, &mut args, is_ref_mut, false, pos,
level, level,
) )
.map(|(v, ..)| v); .map(|(v, ..)| v);
@ -1171,16 +1150,16 @@ impl Engine {
let first_expr = first_arg.unwrap(); let first_expr = first_arg.unwrap();
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger(scope, global, state, lib, this_ptr, first_expr, level)?; self.run_debugger(scope, global, lib, this_ptr, first_expr, level)?;
// func(x, ...) -> x.func(...) // func(x, ...) -> x.func(...)
a_expr.iter().try_for_each(|expr| { a_expr.iter().try_for_each(|expr| {
self.get_arg_value(scope, global, state, lib, this_ptr, expr, level) self.get_arg_value(scope, global, caches, lib, this_ptr, expr, level)
.map(|(value, ..)| arg_values.push(value.flatten())) .map(|(value, ..)| arg_values.push(value.flatten()))
})?; })?;
let (mut target, _pos) = let (mut target, _pos) =
self.search_namespace(scope, global, state, lib, this_ptr, first_expr, level)?; self.search_namespace(scope, global, lib, this_ptr, first_expr, level)?;
if target.as_ref().is_read_only() { if target.as_ref().is_read_only() {
target = target.into_owned(); target = target.into_owned();
@ -1210,7 +1189,7 @@ impl Engine {
.into_iter() .into_iter()
.chain(a_expr.iter()) .chain(a_expr.iter())
.try_for_each(|expr| { .try_for_each(|expr| {
self.get_arg_value(scope, global, state, lib, this_ptr, expr, level) self.get_arg_value(scope, global, caches, lib, this_ptr, expr, level)
.map(|(value, ..)| arg_values.push(value.flatten())) .map(|(value, ..)| arg_values.push(value.flatten()))
})?; })?;
args.extend(curry.iter_mut()); args.extend(curry.iter_mut());
@ -1219,7 +1198,7 @@ impl Engine {
} }
self.exec_fn_call( self.exec_fn_call(
None, global, state, lib, name, hashes, &mut args, is_ref_mut, false, pos, level, None, global, caches, lib, name, hashes, &mut args, is_ref_mut, false, pos, level,
) )
.map(|(v, ..)| v) .map(|(v, ..)| v)
} }
@ -1230,7 +1209,7 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>, this_ptr: &mut Option<&mut Dynamic>,
namespace: &crate::ast::Namespace, namespace: &crate::ast::Namespace,
@ -1252,20 +1231,20 @@ impl Engine {
// and avoid cloning the value // and avoid cloning the value
if !args_expr.is_empty() && args_expr[0].is_variable_access(true) { if !args_expr.is_empty() && args_expr[0].is_variable_access(true) {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger(scope, global, state, lib, this_ptr, &args_expr[0], level)?; self.run_debugger(scope, global, lib, this_ptr, &args_expr[0], level)?;
// func(x, ...) -> x.func(...) // func(x, ...) -> x.func(...)
arg_values.push(Dynamic::UNIT); arg_values.push(Dynamic::UNIT);
args_expr.iter().skip(1).try_for_each(|expr| { args_expr.iter().skip(1).try_for_each(|expr| {
self.get_arg_value(scope, global, state, lib, this_ptr, expr, level) self.get_arg_value(scope, global, caches, lib, this_ptr, expr, level)
.map(|(value, ..)| arg_values.push(value.flatten())) .map(|(value, ..)| arg_values.push(value.flatten()))
})?; })?;
// Get target reference to first argument // Get target reference to first argument
let first_arg = &args_expr[0]; let first_arg = &args_expr[0];
let (target, _pos) = let (target, _pos) =
self.search_scope_only(scope, global, state, lib, this_ptr, first_arg, level)?; self.search_scope_only(scope, global, lib, this_ptr, first_arg, level)?;
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut global.num_operations, _pos)?; self.inc_operations(&mut global.num_operations, _pos)?;
@ -1289,7 +1268,7 @@ impl Engine {
} else { } else {
// func(..., ...) or func(mod::x, ...) // func(..., ...) or func(mod::x, ...)
args_expr.iter().try_for_each(|expr| { args_expr.iter().try_for_each(|expr| {
self.get_arg_value(scope, global, state, lib, this_ptr, expr, level) self.get_arg_value(scope, global, caches, lib, this_ptr, expr, level)
.map(|(value, ..)| arg_values.push(value.flatten())) .map(|(value, ..)| arg_values.push(value.flatten()))
})?; })?;
args.extend(arg_values.iter_mut()); args.extend(arg_values.iter_mut());
@ -1298,7 +1277,7 @@ impl Engine {
// Search for the root namespace // Search for the root namespace
let module = self let module = self
.search_imports(global, state, namespace) .search_imports(global, namespace)
.ok_or_else(|| ERR::ErrorModuleNotFound(namespace.to_string(), namespace.position()))?; .ok_or_else(|| ERR::ErrorModuleNotFound(namespace.to_string(), namespace.position()))?;
// First search script-defined functions in namespace (can override built-in) // First search script-defined functions in namespace (can override built-in)
@ -1370,7 +1349,7 @@ impl Engine {
mem::swap(&mut global.source, &mut source); mem::swap(&mut global.source, &mut source);
let result = self.call_script_fn( let result = self.call_script_fn(
new_scope, global, state, lib, &mut None, fn_def, &mut args, true, pos, level, new_scope, global, caches, lib, &mut None, fn_def, &mut args, true, pos, level,
); );
global.source = source; global.source = source;
@ -1410,7 +1389,7 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
script: &str, script: &str,
_pos: Position, _pos: Position,
@ -1448,6 +1427,6 @@ impl Engine {
} }
// Evaluate the AST // Evaluate the AST
self.eval_global_statements(scope, global, state, statements, lib, level) self.eval_global_statements(scope, global, caches, statements, lib, level)
} }
} }

View File

@ -3,7 +3,7 @@
use super::call::FnCallArgs; use super::call::FnCallArgs;
use crate::api::events::VarDefInfo; use crate::api::events::VarDefInfo;
use crate::ast::FnCallHashes; use crate::ast::FnCallHashes;
use crate::eval::{EvalState, GlobalRuntimeState}; use crate::eval::{Caches, 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;
@ -311,7 +311,7 @@ impl<'a> NativeCallContext<'a> {
.global .global
.cloned() .cloned()
.unwrap_or_else(|| GlobalRuntimeState::new(self.engine())); .unwrap_or_else(|| GlobalRuntimeState::new(self.engine()));
let mut state = EvalState::new(); let mut caches = Caches::new();
let fn_name = fn_name.as_ref(); let fn_name = fn_name.as_ref();
let args_len = args.len(); let args_len = args.len();
@ -330,7 +330,7 @@ impl<'a> NativeCallContext<'a> {
.exec_fn_call( .exec_fn_call(
None, None,
&mut global, &mut global,
&mut state, &mut caches,
self.lib, self.lib,
fn_name, fn_name,
hash, hash,

View File

@ -5,9 +5,8 @@
use super::call::FnCallArgs; use super::call::FnCallArgs;
use super::callable_function::CallableFunction; use super::callable_function::CallableFunction;
use super::native::{FnAny, SendSync}; use super::native::{FnAny, SendSync};
use crate::tokenizer::Position;
use crate::types::dynamic::{DynamicWriteLock, Variant}; use crate::types::dynamic::{DynamicWriteLock, Variant};
use crate::{reify, Dynamic, NativeCallContext, RhaiResultOf, ERR}; use crate::{reify, Dynamic, NativeCallContext, RhaiResultOf};
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
use std::prelude::v1::*; use std::prelude::v1::*;
use std::{any::TypeId, mem}; use std::{any::TypeId, mem};
@ -102,9 +101,11 @@ macro_rules! check_constant {
_ => false, _ => false,
}; };
if deny { if deny {
return Err( return Err(crate::ERR::ErrorAssignmentToConstant(
ERR::ErrorAssignmentToConstant(String::new(), Position::NONE).into(), String::new(),
); crate::Position::NONE,
)
.into());
} }
} }
} }

View File

@ -3,7 +3,7 @@
use super::call::FnCallArgs; use super::call::FnCallArgs;
use crate::ast::ScriptFnDef; use crate::ast::ScriptFnDef;
use crate::eval::{EvalState, GlobalRuntimeState}; use crate::eval::{Caches, GlobalRuntimeState};
use crate::{Dynamic, Engine, Module, Position, RhaiError, RhaiResult, Scope, ERR}; use crate::{Dynamic, Engine, Module, Position, RhaiError, RhaiResult, Scope, ERR};
use std::mem; use std::mem;
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
@ -26,7 +26,7 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
global: &mut GlobalRuntimeState, global: &mut GlobalRuntimeState,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>, this_ptr: &mut Option<&mut Dynamic>,
fn_def: &ScriptFnDef, fn_def: &ScriptFnDef,
@ -109,7 +109,7 @@ impl Engine {
} }
// Merge in encapsulated environment, if any // Merge in encapsulated environment, if any
let orig_fn_resolution_caches_len = state.fn_resolution_caches_len(); let orig_fn_resolution_caches_len = caches.fn_resolution_caches_len();
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
let mut lib_merged = crate::StaticVec::with_capacity(lib.len() + 1); let mut lib_merged = crate::StaticVec::with_capacity(lib.len() + 1);
@ -128,7 +128,7 @@ impl Engine {
if fn_lib.is_empty() { if fn_lib.is_empty() {
lib lib
} else { } else {
state.push_fn_resolution_cache(); caches.push_fn_resolution_cache();
lib_merged.push(fn_lib.as_ref()); lib_merged.push(fn_lib.as_ref());
lib_merged.extend(lib.iter().cloned()); lib_merged.extend(lib.iter().cloned());
&lib_merged &lib_merged
@ -142,7 +142,7 @@ impl Engine {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
{ {
let node = crate::ast::Stmt::Noop(fn_def.body.position()); let node = crate::ast::Stmt::Noop(fn_def.body.position());
self.run_debugger(scope, global, state, lib, this_ptr, &node, level)?; self.run_debugger(scope, global, lib, this_ptr, &node, level)?;
} }
// Evaluate the function // Evaluate the function
@ -150,7 +150,7 @@ impl Engine {
.eval_stmt_block( .eval_stmt_block(
scope, scope,
global, global,
state, caches,
lib, lib,
this_ptr, this_ptr,
&fn_def.body, &fn_def.body,
@ -193,8 +193,7 @@ impl Engine {
Ok(ref r) => crate::eval::DebuggerEvent::FunctionExitWithValue(r), Ok(ref r) => crate::eval::DebuggerEvent::FunctionExitWithValue(r),
Err(ref err) => crate::eval::DebuggerEvent::FunctionExitWithError(err), Err(ref err) => crate::eval::DebuggerEvent::FunctionExitWithError(err),
}; };
match self.run_debugger_raw(scope, global, state, lib, this_ptr, node, event, level) match self.run_debugger_raw(scope, global, lib, this_ptr, node, event, level) {
{
Ok(_) => (), Ok(_) => (),
Err(err) => _result = Err(err), Err(err) => _result = Err(err),
} }
@ -221,7 +220,7 @@ impl Engine {
} }
// Restore state // Restore state
state.rewind_fn_resolution_caches(orig_fn_resolution_caches_len); caches.rewind_fn_resolution_caches(orig_fn_resolution_caches_len);
_result _result
} }
@ -231,11 +230,11 @@ impl Engine {
pub(crate) fn has_script_fn( pub(crate) fn has_script_fn(
&self, &self,
_global: Option<&GlobalRuntimeState>, _global: Option<&GlobalRuntimeState>,
state: &mut EvalState, caches: &mut Caches,
lib: &[&Module], lib: &[&Module],
hash_script: u64, hash_script: u64,
) -> bool { ) -> bool {
let cache = state.fn_resolution_cache_mut(); let cache = caches.fn_resolution_cache_mut();
if let Some(result) = cache.get(&hash_script).map(|v| v.is_some()) { if let Some(result) = cache.get(&hash_script).map(|v| v.is_some()) {
return result; return result;

View File

@ -237,6 +237,9 @@ pub type Blob = Vec<u8>;
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
pub type Map = std::collections::BTreeMap<Identifier, Dynamic>; pub type Map = std::collections::BTreeMap<Identifier, Dynamic>;
#[cfg(not(feature = "no_object"))]
pub use api::json::format_map_as_json;
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
pub use module::ModuleResolver; pub use module::ModuleResolver;
@ -294,10 +297,7 @@ pub use ast::EncapsulatedEnviron;
pub use ast::FloatWrapper; pub use ast::FloatWrapper;
#[cfg(feature = "internals")] #[cfg(feature = "internals")]
pub use eval::{EvalState, GlobalRuntimeState}; pub use eval::{Caches, FnResolutionCache, FnResolutionCacheEntry, GlobalRuntimeState};
#[cfg(feature = "internals")]
pub use func::call::{FnResolutionCache, FnResolutionCacheEntry};
/// Alias to [`smallvec::SmallVec<[T; 3]>`](https://crates.io/crates/smallvec), which is a /// Alias to [`smallvec::SmallVec<[T; 3]>`](https://crates.io/crates/smallvec), which is a
/// specialized [`Vec`] backed by a small, inline, fixed-size array when there are ≤ 3 items stored. /// specialized [`Vec`] backed by a small, inline, fixed-size array when there are ≤ 3 items stored.

View File

@ -1742,9 +1742,12 @@ impl Module {
/// Create a new [`Module`] by evaluating an [`AST`][crate::AST]. /// Create a new [`Module`] by evaluating an [`AST`][crate::AST].
/// ///
/// The entire [`AST`][crate::AST] is encapsulated into each function, allowing functions /// The entire [`AST`][crate::AST] is encapsulated into each function, allowing functions to
/// to cross-call each other. Functions in the global namespace, plus all functions /// cross-call each other.
/// defined in the [`Module`], are _merged_ into a _unified_ namespace before each call. ///
/// Functions in the global namespace, plus all functions defined in the [`Module`], are
/// _merged_ into a _unified_ namespace before each call.
///
/// Therefore, all functions will be found. /// Therefore, all functions will be found.
/// ///
/// # Example /// # Example
@ -1781,8 +1784,15 @@ impl Module {
/// _merged_ into a _unified_ namespace before each call. /// _merged_ into a _unified_ namespace before each call.
/// ///
/// Therefore, all functions will be found. /// Therefore, all functions will be found.
///
/// # WARNING - Low Level API
///
/// This function is very low level.
///
/// In particular, the [`global`][crate::eval::GlobalRuntimeState] parameter allows the
/// entire calling environment to be encapsulated, including automatic global constants.
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
pub(crate) fn eval_ast_as_new_raw( pub fn eval_ast_as_new_raw(
engine: &crate::Engine, engine: &crate::Engine,
scope: crate::Scope, scope: crate::Scope,
global: &mut crate::eval::GlobalRuntimeState, global: &mut crate::eval::GlobalRuntimeState,

View File

@ -201,17 +201,15 @@ impl FileModuleResolver {
/// Is a particular path cached? /// Is a particular path cached?
#[inline] #[inline]
#[must_use] #[must_use]
pub fn is_cached(&self, path: impl AsRef<str>, source_path: Option<&str>) -> bool { pub fn is_cached(&self, path: impl AsRef<Path>) -> bool {
if !self.cache_enabled { if !self.cache_enabled {
return false; return false;
} }
let file_path = self.get_file_path(path.as_ref(), source_path);
let cache = locked_read(&self.cache); let cache = locked_read(&self.cache);
if !cache.is_empty() { if !cache.is_empty() {
cache.contains_key(&file_path) cache.contains_key(path.as_ref())
} else { } else {
false false
} }
@ -227,20 +225,14 @@ impl FileModuleResolver {
/// The next time this path is resolved, the script file will be loaded once again. /// The next time this path is resolved, the script file will be loaded once again.
#[inline] #[inline]
#[must_use] #[must_use]
pub fn clear_cache_for_path( pub fn clear_cache_for_path(&mut self, path: impl AsRef<Path>) -> Option<Shared<Module>> {
&mut self,
path: impl AsRef<str>,
source_path: Option<impl AsRef<str>>,
) -> Option<Shared<Module>> {
let file_path = self.get_file_path(path.as_ref(), source_path.as_ref().map(<_>::as_ref));
locked_write(&self.cache) locked_write(&self.cache)
.remove_entry(&file_path) .remove_entry(path.as_ref())
.map(|(.., v)| v) .map(|(.., v)| v)
} }
/// Construct a full file path. /// Construct a full file path.
#[must_use] #[must_use]
fn get_file_path(&self, path: &str, source_path: Option<&str>) -> PathBuf { pub fn get_file_path(&self, path: &str, source_path: Option<&Path>) -> PathBuf {
let path = Path::new(path); let path = Path::new(path);
let mut file_path; let mut file_path;
@ -274,9 +266,9 @@ impl FileModuleResolver {
.as_ref() .as_ref()
.and_then(|g| g.source()) .and_then(|g| g.source())
.or(source) .or(source)
.and_then(|p| Path::new(p).parent().map(|p| p.to_string_lossy())); .and_then(|p| Path::new(p).parent());
let file_path = self.get_file_path(path, source_path.as_ref().map(|p| p.as_ref())); let file_path = self.get_file_path(path, source_path);
if self.is_cache_enabled() { if self.is_cache_enabled() {
#[cfg(not(feature = "sync"))] #[cfg(not(feature = "sync"))]
@ -351,7 +343,7 @@ impl ModuleResolver for FileModuleResolver {
pos: Position, pos: Position,
) -> Option<RhaiResultOf<crate::AST>> { ) -> Option<RhaiResultOf<crate::AST>> {
// Construct the script file path // Construct the script file path
let file_path = self.get_file_path(path, source_path); let file_path = self.get_file_path(path, source_path.map(|s| Path::new(s)));
// Load the script file and compile it // Load the script file and compile it
Some( Some(

View File

@ -3,7 +3,7 @@
use crate::ast::{ASTFlags, Expr, OpAssignment, Stmt, StmtBlock, StmtBlockContainer, SwitchCases}; use crate::ast::{ASTFlags, Expr, OpAssignment, Stmt, StmtBlock, StmtBlockContainer, SwitchCases};
use crate::engine::{KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, KEYWORD_PRINT, KEYWORD_TYPE_OF}; use crate::engine::{KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, KEYWORD_PRINT, KEYWORD_TYPE_OF};
use crate::eval::{EvalState, GlobalRuntimeState}; use crate::eval::{Caches, GlobalRuntimeState};
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::{Span, Token}; use crate::tokenizer::{Span, Token};
@ -139,7 +139,7 @@ impl<'a> OptimizerState<'a> {
self.engine self.engine
.call_native_fn( .call_native_fn(
&mut GlobalRuntimeState::new(&self.engine), &mut GlobalRuntimeState::new(&self.engine),
&mut EvalState::new(), &mut Caches::new(),
lib, lib,
fn_name, fn_name,
calc_fn_hash(&fn_name, arg_values.len()), calc_fn_hash(&fn_name, arg_values.len()),
@ -426,7 +426,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
match stmt { match stmt {
// var = var op expr => var op= expr // var = var op expr => var op= expr
Stmt::Assignment(x, ..) Stmt::Assignment(x, ..)
if x.0.is_none() if !x.0.is_op_assignment()
&& x.1.lhs.is_variable_access(true) && x.1.lhs.is_variable_access(true)
&& matches!(&x.1.rhs, Expr::FnCall(x2, ..) && matches!(&x.1.rhs, Expr::FnCall(x2, ..)
if Token::lookup_from_syntax(&x2.name).map(|t| t.has_op_assignment()).unwrap_or(false) if Token::lookup_from_syntax(&x2.name).map(|t| t.has_op_assignment()).unwrap_or(false)
@ -437,7 +437,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
match x.1.rhs { match x.1.rhs {
Expr::FnCall(ref mut x2, ..) => { Expr::FnCall(ref mut x2, ..) => {
state.set_dirty(); state.set_dirty();
x.0 = Some(OpAssignment::new_from_base(&x2.name)); x.0 = OpAssignment::new_op_assignment_from_base(&x2.name, x2.pos);
x.1.rhs = mem::take(&mut x2.args[1]); x.1.rhs = mem::take(&mut x2.args[1]);
} }
ref expr => unreachable!("Expr::FnCall expected but gets {:?}", expr), ref expr => unreachable!("Expr::FnCall expected but gets {:?}", expr),
@ -531,35 +531,38 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
// First check hashes // First check hashes
if let Some(block) = cases.get_mut(&hash) { if let Some(block) = cases.get_mut(&hash) {
if let Some(mut condition) = mem::take(&mut block.condition) { match mem::take(&mut block.condition) {
// switch const { case if condition => stmt, _ => def } => if condition { stmt } else { def } Expr::BoolConstant(true, ..) => {
optimize_expr(&mut condition, state, false); // Promote the matched case
let statements = optimize_stmt_block(
let def_stmt =
optimize_stmt_block(mem::take(def_case), state, true, true, false);
*stmt = Stmt::If(
(
condition,
mem::take(&mut block.statements), mem::take(&mut block.statements),
StmtBlock::new_with_span( state,
def_stmt, true,
def_case.span_or_else(*pos, Position::NONE), true,
), false,
) );
.into(), *stmt = (statements, block.statements.span()).into();
match_expr.start_position(), }
); mut condition => {
} else { // switch const { case if condition => stmt, _ => def } => if condition { stmt } else { def }
// Promote the matched case optimize_expr(&mut condition, state, false);
let statements = optimize_stmt_block(
mem::take(&mut block.statements), let def_stmt =
state, optimize_stmt_block(mem::take(def_case), state, true, true, false);
true,
true, *stmt = Stmt::If(
false, (
); condition,
*stmt = (statements, block.statements.span()).into(); mem::take(&mut block.statements),
StmtBlock::new_with_span(
def_stmt,
def_case.span_or_else(*pos, Position::NONE),
),
)
.into(),
match_expr.start_position(),
);
}
} }
state.set_dirty(); state.set_dirty();
@ -571,7 +574,11 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
let value = value.as_int().expect("`INT`"); let value = value.as_int().expect("`INT`");
// Only one range or all ranges without conditions // Only one range or all ranges without conditions
if ranges.len() == 1 || ranges.iter().all(|(.., c)| !c.has_condition()) { if ranges.len() == 1
|| ranges
.iter()
.all(|(.., c)| matches!(c.condition, Expr::BoolConstant(true, ..)))
{
for (.., block) in for (.., block) in
ranges ranges
.iter_mut() .iter_mut()
@ -580,30 +587,38 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
|| (inclusive && (start..=end).contains(&value)) || (inclusive && (start..=end).contains(&value))
}) })
{ {
if let Some(mut condition) = mem::take(&mut block.condition) { match mem::take(&mut block.condition) {
// switch const { range if condition => stmt, _ => def } => if condition { stmt } else { def } Expr::BoolConstant(true, ..) => {
optimize_expr(&mut condition, state, false); // Promote the matched case
let statements = mem::take(&mut *block.statements);
let statements =
optimize_stmt_block(statements, state, true, true, false);
*stmt = (statements, block.statements.span()).into();
}
mut condition => {
// switch const { range if condition => stmt, _ => def } => if condition { stmt } else { def }
optimize_expr(&mut condition, state, false);
let def_stmt = let def_stmt = optimize_stmt_block(
optimize_stmt_block(mem::take(def_case), state, true, true, false); mem::take(def_case),
*stmt = Stmt::If( state,
( true,
condition, true,
mem::take(&mut block.statements), false,
StmtBlock::new_with_span( );
def_stmt, *stmt = Stmt::If(
def_case.span_or_else(*pos, Position::NONE), (
), condition,
) mem::take(&mut block.statements),
.into(), StmtBlock::new_with_span(
match_expr.start_position(), def_stmt,
); def_case.span_or_else(*pos, Position::NONE),
} else { ),
// Promote the matched case )
let statements = mem::take(&mut *block.statements); .into(),
let statements = match_expr.start_position(),
optimize_stmt_block(statements, state, true, true, false); );
*stmt = (statements, block.statements.span()).into(); }
} }
state.set_dirty(); state.set_dirty();
@ -632,12 +647,14 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
*block.statements = *block.statements =
optimize_stmt_block(statements, state, preserve_result, true, false); optimize_stmt_block(statements, state, preserve_result, true, false);
if let Some(mut condition) = mem::take(&mut block.condition) { optimize_expr(&mut block.condition, state, false);
optimize_expr(&mut condition, state, false);
match condition { match block.condition {
Expr::Unit(..) | Expr::BoolConstant(true, ..) => state.set_dirty(), Expr::Unit(pos) => {
_ => block.condition = Some(condition), block.condition = Expr::BoolConstant(true, pos);
state.set_dirty()
} }
_ => (),
} }
} }
return; return;
@ -669,18 +686,20 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
*block.statements = *block.statements =
optimize_stmt_block(statements, state, preserve_result, true, false); optimize_stmt_block(statements, state, preserve_result, true, false);
if let Some(mut condition) = mem::take(&mut block.condition) { optimize_expr(&mut block.condition, state, false);
optimize_expr(&mut condition, state, false);
match condition { match block.condition {
Expr::Unit(..) | Expr::BoolConstant(true, ..) => state.set_dirty(), Expr::Unit(pos) => {
_ => block.condition = Some(condition), block.condition = Expr::BoolConstant(true, pos);
state.set_dirty();
} }
_ => (),
} }
} }
// Remove false cases // Remove false cases
cases.retain(|_, block| match block.condition { cases.retain(|_, block| match block.condition {
Some(Expr::BoolConstant(false, ..)) => { Expr::BoolConstant(false, ..) => {
state.set_dirty(); state.set_dirty();
false false
} }
@ -693,18 +712,20 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
*block.statements = *block.statements =
optimize_stmt_block(statements, state, preserve_result, true, false); optimize_stmt_block(statements, state, preserve_result, true, false);
if let Some(mut condition) = mem::take(&mut block.condition) { optimize_expr(&mut block.condition, state, false);
optimize_expr(&mut condition, state, false);
match condition { match block.condition {
Expr::Unit(..) | Expr::BoolConstant(true, ..) => state.set_dirty(), Expr::Unit(pos) => {
_ => block.condition = Some(condition), block.condition = Expr::BoolConstant(true, pos);
state.set_dirty();
} }
_ => (),
} }
} }
// Remove false ranges // Remove false ranges
ranges.retain(|(.., block)| match block.condition { ranges.retain(|(.., block)| match block.condition {
Some(Expr::BoolConstant(false, ..)) => { Expr::BoolConstant(false, ..) => {
state.set_dirty(); state.set_dirty();
false false
} }

View File

@ -2,7 +2,7 @@
use crate::engine::OP_EQUALS; use crate::engine::OP_EQUALS;
use crate::plugin::*; use crate::plugin::*;
use crate::{def_package, Dynamic, ImmutableString, Map, RhaiResultOf, INT}; use crate::{def_package, format_map_as_json, Dynamic, ImmutableString, Map, RhaiResultOf, INT};
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
use std::prelude::v1::*; use std::prelude::v1::*;
@ -266,4 +266,26 @@ mod map_functions {
map.values().cloned().collect() map.values().cloned().collect()
} }
} }
/// Return the JSON representation of the object map.
///
/// # Data types
///
/// Only the following data types should be kept inside the object map:
/// `INT`, `FLOAT`, `ImmutableString`, `char`, `bool`, `()`, `Array`, `Map`.
///
/// # Errors
///
/// Data types not supported by JSON serialize into formats that may
/// invalidate the result.
///
/// # Example
///
/// ```rhai
/// let m = #{a:1, b:2, c:3};
///
/// print(m.to_json()); // prints {"a":1, "b":2, "c":3}
/// ```
pub fn to_json(map: &mut Map) -> String {
format_map_as_json(map)
}
} }

View File

@ -8,7 +8,7 @@ use crate::ast::{
OpAssignment, ScriptFnDef, Stmt, StmtBlock, StmtBlockContainer, SwitchCases, TryCatchBlock, OpAssignment, ScriptFnDef, Stmt, StmtBlock, StmtBlockContainer, SwitchCases, TryCatchBlock,
}; };
use crate::engine::{Precedence, KEYWORD_THIS, OP_CONTAINS}; use crate::engine::{Precedence, KEYWORD_THIS, OP_CONTAINS};
use crate::eval::{EvalState, GlobalRuntimeState}; use crate::eval::GlobalRuntimeState;
use crate::func::hashing::get_hasher; use crate::func::hashing::get_hasher;
use crate::tokenizer::{ use crate::tokenizer::{
is_keyword_function, is_valid_function_name, is_valid_identifier, Token, TokenStream, is_keyword_function, is_valid_function_name, is_valid_identifier, Token, TokenStream,
@ -47,6 +47,8 @@ pub struct ParseState<'e> {
pub tokenizer_control: TokenizerControl, pub tokenizer_control: TokenizerControl,
/// Interned strings. /// Interned strings.
interned_strings: StringsInterner, interned_strings: StringsInterner,
/// External [scope][Scope] with constants.
pub scope: &'e Scope<'e>,
/// Encapsulates a local stack with variable names to simulate an actual runtime scope. /// Encapsulates a local stack with variable names to simulate an actual runtime scope.
pub stack: Scope<'e>, pub stack: Scope<'e>,
/// Size of the local variables stack upon entry of the current block scope. /// Size of the local variables stack upon entry of the current block scope.
@ -72,7 +74,7 @@ impl<'e> ParseState<'e> {
/// Create a new [`ParseState`]. /// Create a new [`ParseState`].
#[inline(always)] #[inline(always)]
#[must_use] #[must_use]
pub fn new(engine: &Engine, tokenizer_control: TokenizerControl) -> Self { pub fn new(engine: &Engine, scope: &'e Scope, tokenizer_control: TokenizerControl) -> Self {
Self { Self {
tokenizer_control, tokenizer_control,
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
@ -80,6 +82,7 @@ impl<'e> ParseState<'e> {
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
allow_capture: true, allow_capture: true,
interned_strings: StringsInterner::new(), interned_strings: StringsInterner::new(),
scope,
stack: Scope::new(), stack: Scope::new(),
block_stack_len: 0, block_stack_len: 0,
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
@ -426,10 +429,6 @@ impl Engine {
let mut settings = settings; let mut settings = settings;
settings.pos = eat_token(input, Token::LeftParen); settings.pos = eat_token(input, Token::LeftParen);
if match_token(input, Token::RightParen).0 {
return Ok(Expr::Unit(settings.pos));
}
let expr = self.parse_expr(input, state, lib, settings.level_up())?; let expr = self.parse_expr(input, state, lib, settings.level_up())?;
match input.next().expect(NEVER_ENDS) { match input.next().expect(NEVER_ENDS) {
@ -453,6 +452,7 @@ impl Engine {
state: &mut ParseState, state: &mut ParseState,
lib: &mut FnLib, lib: &mut FnLib,
id: Identifier, id: Identifier,
no_args: bool,
capture_parent_scope: bool, capture_parent_scope: bool,
#[cfg(not(feature = "no_module"))] namespace: crate::ast::Namespace, #[cfg(not(feature = "no_module"))] namespace: crate::ast::Namespace,
settings: ParseSettings, settings: ParseSettings,
@ -460,7 +460,11 @@ impl Engine {
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
settings.ensure_level_within_max_limit(state.max_expr_depth)?; settings.ensure_level_within_max_limit(state.max_expr_depth)?;
let (token, token_pos) = input.peek().expect(NEVER_ENDS); let (token, token_pos) = if no_args {
&(Token::RightParen, Position::NONE)
} else {
input.peek().expect(NEVER_ENDS)
};
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
let mut namespace = namespace; let mut namespace = namespace;
@ -479,7 +483,9 @@ impl Engine {
Token::LexError(err) => return Err(err.clone().into_err(*token_pos)), Token::LexError(err) => return Err(err.clone().into_err(*token_pos)),
// id() // id()
Token::RightParen => { Token::RightParen => {
eat_token(input, Token::RightParen); if !no_args {
eat_token(input, Token::RightParen);
}
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
let hash = if !namespace.is_empty() { let hash = if !namespace.is_empty() {
@ -897,7 +903,7 @@ impl Engine {
} }
let (name, pos) = match input.next().expect(NEVER_ENDS) { let (name, pos) = match input.next().expect(NEVER_ENDS) {
(Token::Identifier(s), pos) | (Token::StringConstant(s), pos) => { (Token::Identifier(s) | Token::StringConstant(s), pos) => {
if map.iter().any(|(p, ..)| **p == s) { if map.iter().any(|(p, ..)| **p == s) {
return Err(PERR::DuplicatedProperty(s.to_string()).into_err(pos)); return Err(PERR::DuplicatedProperty(s.to_string()).into_err(pos));
} }
@ -1041,7 +1047,7 @@ impl Engine {
return Err(PERR::WrongSwitchCaseCondition.into_err(if_pos)); return Err(PERR::WrongSwitchCaseCondition.into_err(if_pos));
} }
(None, None) (None, Expr::BoolConstant(true, Position::NONE))
} }
(Token::Underscore, pos) => return Err(PERR::DuplicatedSwitchCase.into_err(*pos)), (Token::Underscore, pos) => return Err(PERR::DuplicatedSwitchCase.into_err(*pos)),
@ -1054,9 +1060,14 @@ impl Engine {
Some(self.parse_expr(input, state, lib, settings.level_up())?); Some(self.parse_expr(input, state, lib, settings.level_up())?);
let condition = if match_token(input, Token::If).0 { let condition = if match_token(input, Token::If).0 {
Some(self.parse_expr(input, state, lib, settings.level_up())?) ensure_not_statement_expr(input, "a boolean")?;
let guard = self
.parse_expr(input, state, lib, settings.level_up())?
.ensure_bool_expr()?;
ensure_not_assignment(input)?;
guard
} else { } else {
None Expr::BoolConstant(true, Position::NONE)
}; };
(case_expr, condition) (case_expr, condition)
} }
@ -1196,6 +1207,11 @@ impl Engine {
let root_expr = match token { let root_expr = match token {
Token::EOF => return Err(PERR::UnexpectedEOF.into_err(settings.pos)), Token::EOF => return Err(PERR::UnexpectedEOF.into_err(settings.pos)),
Token::Unit => {
input.next();
Expr::Unit(settings.pos)
}
Token::IntegerConstant(..) Token::IntegerConstant(..)
| Token::CharConstant(..) | Token::CharConstant(..)
| Token::StringConstant(..) | Token::StringConstant(..)
@ -1213,13 +1229,13 @@ impl Engine {
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
Token::FloatConstant(x) => { Token::FloatConstant(x) => {
let x = *x; let x = *x;
input.next().expect(NEVER_ENDS); input.next();
Expr::FloatConstant(x, settings.pos) Expr::FloatConstant(x, settings.pos)
} }
#[cfg(feature = "decimal")] #[cfg(feature = "decimal")]
Token::DecimalConstant(x) => { Token::DecimalConstant(x) => {
let x = (*x).into(); let x = (*x).into();
input.next().expect(NEVER_ENDS); input.next();
Expr::DynamicConstant(Box::new(x), settings.pos) Expr::DynamicConstant(Box::new(x), settings.pos)
} }
@ -1230,6 +1246,7 @@ impl Engine {
stmt => unreachable!("Stmt::Block expected but gets {:?}", stmt), stmt => unreachable!("Stmt::Block expected but gets {:?}", stmt),
} }
} }
// ( - grouped expression // ( - grouped expression
Token::LeftParen => self.parse_paren_expr(input, state, lib, settings.level_up())?, Token::LeftParen => self.parse_paren_expr(input, state, lib, settings.level_up())?,
@ -1247,7 +1264,8 @@ impl Engine {
// | ... // | ...
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
Token::Pipe | Token::Or if settings.options.allow_anonymous_fn => { Token::Pipe | Token::Or if settings.options.allow_anonymous_fn => {
let mut new_state = ParseState::new(self, state.tokenizer_control.clone()); let mut new_state =
ParseState::new(self, state.scope, state.tokenizer_control.clone());
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
{ {
@ -1283,6 +1301,10 @@ impl Engine {
if settings.options.strict_var if settings.options.strict_var
&& !settings.is_closure_scope && !settings.is_closure_scope
&& index.is_none() && index.is_none()
&& !matches!(
state.scope.get_index(name),
Some((_, AccessMode::ReadOnly))
)
{ {
// If the parent scope is not inside another capturing closure // If the parent scope is not inside another capturing closure
// then we can conclude that the captured variable doesn't exist. // then we can conclude that the captured variable doesn't exist.
@ -1396,7 +1418,7 @@ impl Engine {
match input.peek().expect(NEVER_ENDS).0 { match input.peek().expect(NEVER_ENDS).0 {
// Function call // Function call
Token::LeftParen | Token::Bang => { Token::LeftParen | Token::Bang | Token::Unit => {
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
{ {
// Once the identifier consumed we must enable next variables capturing // Once the identifier consumed we must enable next variables capturing
@ -1426,7 +1448,10 @@ impl Engine {
_ => { _ => {
let index = state.access_var(&s, settings.pos); let index = state.access_var(&s, settings.pos);
if settings.options.strict_var && index.is_none() { if settings.options.strict_var
&& index.is_none()
&& !matches!(state.scope.get_index(&s), Some((_, AccessMode::ReadOnly)))
{
return Err( return Err(
PERR::VariableUndefined(s.to_string()).into_err(settings.pos) PERR::VariableUndefined(s.to_string()).into_err(settings.pos)
); );
@ -1462,11 +1487,13 @@ impl Engine {
match input.peek().expect(NEVER_ENDS).0 { match input.peek().expect(NEVER_ENDS).0 {
// Function call is allowed to have reserved keyword // Function call is allowed to have reserved keyword
Token::LeftParen | Token::Bang if is_keyword_function(&s) => Expr::Variable( Token::LeftParen | Token::Bang | Token::Unit if is_keyword_function(&s) => {
(None, ns, 0, state.get_identifier("", s)).into(), Expr::Variable(
None, (None, ns, 0, state.get_identifier("", s)).into(),
settings.pos, None,
), settings.pos,
)
}
// Access to `this` as a variable is OK within a function scope // Access to `this` as a variable is OK within a function scope
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
_ if &*s == KEYWORD_THIS && settings.is_function_scope => Expr::Variable( _ if &*s == KEYWORD_THIS && settings.is_function_scope => Expr::Variable(
@ -1526,30 +1553,33 @@ impl Engine {
// Qualified function call with ! // Qualified function call with !
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
(Expr::Variable(x, ..), Token::Bang) if !x.1.is_empty() => { (Expr::Variable(x, ..), Token::Bang) if !x.1.is_empty() => {
return if !match_token(input, Token::LeftParen).0 { return match input.peek().expect(NEVER_ENDS) {
Err(LexError::UnexpectedInput(Token::Bang.syntax().to_string()) (Token::LeftParen | Token::Unit, ..) => {
.into_err(tail_pos)) Err(LexError::UnexpectedInput(Token::Bang.syntax().to_string())
} else { .into_err(tail_pos))
Err(LexError::ImproperSymbol( }
_ => Err(LexError::ImproperSymbol(
"!".to_string(), "!".to_string(),
"'!' cannot be used to call module functions".to_string(), "'!' cannot be used to call module functions".to_string(),
) )
.into_err(tail_pos)) .into_err(tail_pos)),
}; };
} }
// Function call with ! // Function call with !
(Expr::Variable(x, .., pos), Token::Bang) => { (Expr::Variable(x, .., pos), Token::Bang) => {
match match_token(input, Token::LeftParen) { match input.peek().expect(NEVER_ENDS) {
(false, pos) => { (Token::LeftParen | Token::Unit, ..) => (),
(_, pos) => {
return Err(PERR::MissingToken( return Err(PERR::MissingToken(
Token::LeftParen.syntax().into(), Token::LeftParen.syntax().into(),
"to start arguments list of function call".into(), "to start arguments list of function call".into(),
) )
.into_err(pos)) .into_err(*pos))
} }
_ => (),
} }
let no_args = input.next().expect(NEVER_ENDS).0 == Token::Unit;
let (.., _ns, _, name) = *x; let (.., _ns, _, name) = *x;
settings.pos = pos; settings.pos = pos;
self.parse_fn_call( self.parse_fn_call(
@ -1557,6 +1587,7 @@ impl Engine {
state, state,
lib, lib,
name, name,
no_args,
true, true,
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
_ns, _ns,
@ -1564,7 +1595,7 @@ impl Engine {
)? )?
} }
// Function call // Function call
(Expr::Variable(x, .., pos), Token::LeftParen) => { (Expr::Variable(x, .., pos), t @ (Token::LeftParen | Token::Unit)) => {
let (.., _ns, _, name) = *x; let (.., _ns, _, name) = *x;
settings.pos = pos; settings.pos = pos;
self.parse_fn_call( self.parse_fn_call(
@ -1572,6 +1603,7 @@ impl Engine {
state, state,
lib, lib,
name, name,
t == Token::Unit,
false, false,
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
_ns, _ns,
@ -1808,7 +1840,11 @@ impl Engine {
} }
} }
let op_info = op.map(OpAssignment::new_from_token); let op_info = if let Some(op) = op {
OpAssignment::new_op_assignment_from_token(op, op_pos)
} else {
OpAssignment::new_assignment(op_pos)
};
match lhs { match lhs {
// const_expr = rhs // const_expr = rhs
@ -1816,10 +1852,9 @@ impl Engine {
Err(PERR::AssignmentToConstant("".into()).into_err(lhs.start_position())) Err(PERR::AssignmentToConstant("".into()).into_err(lhs.start_position()))
} }
// var (non-indexed) = rhs // var (non-indexed) = rhs
Expr::Variable(ref x, None, _) if x.0.is_none() => Ok(Stmt::Assignment( Expr::Variable(ref x, None, _) if x.0.is_none() => {
(op_info, (lhs, rhs).into()).into(), Ok(Stmt::Assignment((op_info, (lhs, rhs).into()).into()))
op_pos, }
)),
// var (indexed) = rhs // var (indexed) = rhs
Expr::Variable(ref x, i, var_pos) => { Expr::Variable(ref x, i, var_pos) => {
let (index, .., name) = x.as_ref(); let (index, .., name) = x.as_ref();
@ -1832,10 +1867,9 @@ impl Engine {
.get_mut_by_index(state.stack.len() - index) .get_mut_by_index(state.stack.len() - index)
.access_mode() .access_mode()
{ {
AccessMode::ReadWrite => Ok(Stmt::Assignment( AccessMode::ReadWrite => {
(op_info, (lhs, rhs).into()).into(), Ok(Stmt::Assignment((op_info, (lhs, rhs).into()).into()))
op_pos, }
)),
// Constant values cannot be assigned to // Constant values cannot be assigned to
AccessMode::ReadOnly => { AccessMode::ReadOnly => {
Err(PERR::AssignmentToConstant(name.to_string()).into_err(var_pos)) Err(PERR::AssignmentToConstant(name.to_string()).into_err(var_pos))
@ -1854,10 +1888,9 @@ impl Engine {
None => { None => {
match x.lhs { match x.lhs {
// var[???] = rhs, var.??? = rhs // var[???] = rhs, var.??? = rhs
Expr::Variable(..) => Ok(Stmt::Assignment( Expr::Variable(..) => {
(op_info, (lhs, rhs).into()).into(), Ok(Stmt::Assignment((op_info, (lhs, rhs).into()).into()))
op_pos, }
)),
// expr[???] = rhs, expr.??? = rhs // expr[???] = rhs, expr.??? = rhs
ref expr => Err(PERR::AssignmentToInvalidLHS("".to_string()) ref expr => Err(PERR::AssignmentToInvalidLHS("".to_string())
.into_err(expr.position())), .into_err(expr.position())),
@ -1986,7 +2019,7 @@ impl Engine {
)) ))
} }
// lhs.dot_lhs.dot_rhs or lhs.dot_lhs[idx_rhs] // lhs.dot_lhs.dot_rhs or lhs.dot_lhs[idx_rhs]
(lhs, rhs @ Expr::Dot(..)) | (lhs, rhs @ Expr::Index(..)) => { (lhs, rhs @ (Expr::Dot(..) | Expr::Index(..))) => {
let (x, term, pos, is_dot) = match rhs { let (x, term, pos, is_dot) = match rhs {
Expr::Dot(x, term, pos) => (x, term, pos, true), Expr::Dot(x, term, pos) => (x, term, pos, true),
Expr::Index(x, term, pos) => (x, term, pos, false), Expr::Index(x, term, pos) => (x, term, pos, false),
@ -2318,7 +2351,7 @@ impl Engine {
} }
} }
CUSTOM_SYNTAX_MARKER_BOOL => match input.next().expect(NEVER_ENDS) { CUSTOM_SYNTAX_MARKER_BOOL => match input.next().expect(NEVER_ENDS) {
(b @ Token::True, pos) | (b @ Token::False, pos) => { (b @ (Token::True | Token::False), pos) => {
inputs.push(Expr::BoolConstant(b == Token::True, pos)); inputs.push(Expr::BoolConstant(b == Token::True, pos));
segments.push(state.get_interned_string("", b.literal_syntax())); segments.push(state.get_interned_string("", b.literal_syntax()));
tokens.push(state.get_identifier("", CUSTOM_SYNTAX_MARKER_BOOL)); tokens.push(state.get_identifier("", CUSTOM_SYNTAX_MARKER_BOOL));
@ -2686,7 +2719,7 @@ impl Engine {
engine: self, engine: self,
scope: &mut state.stack, scope: &mut state.stack,
global: &mut GlobalRuntimeState::new(self), global: &mut GlobalRuntimeState::new(self),
state: &mut EvalState::new(), caches: None,
lib: &[], lib: &[],
this_ptr: &mut None, this_ptr: &mut None,
level, level,
@ -2993,7 +3026,7 @@ impl Engine {
comments.push(comment); comments.push(comment);
match input.peek().expect(NEVER_ENDS) { match input.peek().expect(NEVER_ENDS) {
(Token::Fn, ..) | (Token::Private, ..) => break, (Token::Fn | Token::Private, ..) => break,
(Token::Comment(..), ..) => (), (Token::Comment(..), ..) => (),
_ => return Err(PERR::WrongDocComment.into_err(comments_pos)), _ => return Err(PERR::WrongDocComment.into_err(comments_pos)),
} }
@ -3039,7 +3072,8 @@ impl Engine {
match input.next().expect(NEVER_ENDS) { match input.next().expect(NEVER_ENDS) {
(Token::Fn, pos) => { (Token::Fn, pos) => {
let mut new_state = ParseState::new(self, state.tokenizer_control.clone()); let mut new_state =
ParseState::new(self, state.scope, state.tokenizer_control.clone());
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
{ {
@ -3263,14 +3297,21 @@ impl Engine {
Err(_) => return Err(PERR::FnMissingName.into_err(pos)), Err(_) => return Err(PERR::FnMissingName.into_err(pos)),
}; };
match input.peek().expect(NEVER_ENDS) { let no_params = match input.peek().expect(NEVER_ENDS) {
(Token::LeftParen, ..) => eat_token(input, Token::LeftParen), (Token::LeftParen, ..) => {
eat_token(input, Token::LeftParen);
match_token(input, Token::RightParen).0
}
(Token::Unit, ..) => {
eat_token(input, Token::Unit);
true
}
(.., pos) => return Err(PERR::FnMissingParams(name.to_string()).into_err(*pos)), (.., pos) => return Err(PERR::FnMissingParams(name.to_string()).into_err(*pos)),
}; };
let mut params = StaticVec::new_const(); let mut params = StaticVec::new_const();
if !match_token(input, Token::RightParen).0 { if !no_params {
let sep_err = format!("to separate the parameters of function '{}'", name); let sep_err = format!("to separate the parameters of function '{}'", name);
loop { loop {
@ -3504,7 +3545,6 @@ impl Engine {
&self, &self,
input: &mut TokenStream, input: &mut TokenStream,
state: &mut ParseState, state: &mut ParseState,
_scope: &Scope,
_optimization_level: OptimizationLevel, _optimization_level: OptimizationLevel,
) -> ParseResult<AST> { ) -> ParseResult<AST> {
let mut functions = BTreeMap::new(); let mut functions = BTreeMap::new();
@ -3546,7 +3586,7 @@ impl Engine {
#[cfg(not(feature = "no_optimize"))] #[cfg(not(feature = "no_optimize"))]
return Ok(crate::optimizer::optimize_into_ast( return Ok(crate::optimizer::optimize_into_ast(
self, self,
_scope, state.scope,
statements, statements,
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
StaticVec::new_const(), StaticVec::new_const(),
@ -3628,7 +3668,6 @@ impl Engine {
&self, &self,
input: &mut TokenStream, input: &mut TokenStream,
state: &mut ParseState, state: &mut ParseState,
_scope: &Scope,
_optimization_level: OptimizationLevel, _optimization_level: OptimizationLevel,
) -> ParseResult<AST> { ) -> ParseResult<AST> {
let (statements, _lib) = self.parse_global_level(input, state)?; let (statements, _lib) = self.parse_global_level(input, state)?;
@ -3636,7 +3675,7 @@ impl Engine {
#[cfg(not(feature = "no_optimize"))] #[cfg(not(feature = "no_optimize"))]
return Ok(crate::optimizer::optimize_into_ast( return Ok(crate::optimizer::optimize_into_ast(
self, self,
_scope, state.scope,
statements, statements,
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
_lib, _lib,

View File

@ -382,6 +382,8 @@ pub enum Token {
LeftBracket, LeftBracket,
/// `]` /// `]`
RightBracket, RightBracket,
/// `()`
Unit,
/// `+` /// `+`
Plus, Plus,
/// `+` (unary) /// `+` (unary)
@ -558,6 +560,7 @@ impl Token {
RightParen => ")", RightParen => ")",
LeftBracket => "[", LeftBracket => "[",
RightBracket => "]", RightBracket => "]",
Unit => "()",
Plus => "+", Plus => "+",
UnaryPlus => "+", UnaryPlus => "+",
Minus => "-", Minus => "-",
@ -754,6 +757,7 @@ impl Token {
")" => RightParen, ")" => RightParen,
"[" => LeftBracket, "[" => LeftBracket,
"]" => RightBracket, "]" => RightBracket,
"()" => Unit,
"+" => Plus, "+" => Plus,
"-" => Minus, "-" => Minus,
"*" => Multiply, "*" => Multiply,
@ -1702,6 +1706,12 @@ fn get_next_token_inner(
('{', ..) => return Some((Token::LeftBrace, start_pos)), ('{', ..) => return Some((Token::LeftBrace, start_pos)),
('}', ..) => return Some((Token::RightBrace, start_pos)), ('}', ..) => return Some((Token::RightBrace, start_pos)),
// Unit
('(', ')') => {
eat_next(stream, pos);
return Some((Token::Unit, start_pos));
}
// Parentheses // Parentheses
('(', '*') => { ('(', '*') => {
eat_next(stream, pos); eat_next(stream, pos);

View File

@ -51,7 +51,8 @@ impl fmt::Display for LexError {
Self::ImproperSymbol(s, d) if d.is_empty() => { Self::ImproperSymbol(s, d) if d.is_empty() => {
write!(f, "Invalid symbol encountered: '{}'", s) write!(f, "Invalid symbol encountered: '{}'", s)
} }
Self::ImproperSymbol(.., d) => f.write_str(d), Self::ImproperSymbol(s, d) if s.is_empty() => f.write_str(d),
Self::ImproperSymbol(s, d) => write!(f, "{}: '{}'", d, s),
} }
} }
} }

View File

@ -130,8 +130,8 @@ fn test_map_assign() -> Result<(), Box<EvalAltResult>> {
let x = engine.eval::<Map>(r#"let x = #{a: 1, b: true, "c$": "hello"}; x"#)?; let x = engine.eval::<Map>(r#"let x = #{a: 1, b: true, "c$": "hello"}; x"#)?;
assert_eq!(x["a"].clone_cast::<INT>(), 1); assert_eq!(x["a"].as_int().unwrap(), 1);
assert_eq!(x["b"].clone_cast::<bool>(), true); assert_eq!(x["b"].as_bool().unwrap(), true);
assert_eq!(x["c$"].clone_cast::<String>(), "hello"); assert_eq!(x["c$"].clone_cast::<String>(), "hello");
Ok(()) Ok(())
@ -143,8 +143,8 @@ fn test_map_return() -> Result<(), Box<EvalAltResult>> {
let x = engine.eval::<Map>(r#"#{a: 1, b: true, "c$": "hello"}"#)?; let x = engine.eval::<Map>(r#"#{a: 1, b: true, "c$": "hello"}"#)?;
assert_eq!(x["a"].clone_cast::<INT>(), 1); assert_eq!(x["a"].as_int().unwrap(), 1);
assert_eq!(x["b"].clone_cast::<bool>(), true); assert_eq!(x["b"].as_bool().unwrap(), true);
assert_eq!(x["c$"].clone_cast::<String>(), "hello"); assert_eq!(x["c$"].clone_cast::<String>(), "hello");
Ok(()) Ok(())
@ -182,17 +182,17 @@ fn test_map_for() -> Result<(), Box<EvalAltResult>> {
fn test_map_json() -> Result<(), Box<EvalAltResult>> { fn test_map_json() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
let json = r#"{"a":1, "b":true, "c":42, "$d e f!":"hello", "z":null}"#; let json = r#"{"a":1, "b":true, "c":41+1, "$d e f!":"hello", "z":null}"#;
let map = engine.parse_json(json, true)?; let map = engine.parse_json(json, true)?;
assert!(!map.contains_key("x")); assert!(!map.contains_key("x"));
assert_eq!(map["a"].clone_cast::<INT>(), 1); assert_eq!(map["a"].as_int().unwrap(), 1);
assert_eq!(map["b"].clone_cast::<bool>(), true); assert_eq!(map["b"].as_bool().unwrap(), true);
assert_eq!(map["c"].clone_cast::<INT>(), 42); assert_eq!(map["c"].as_int().unwrap(), 42);
assert_eq!(map["$d e f!"].clone_cast::<String>(), "hello"); assert_eq!(map["$d e f!"].clone_cast::<String>(), "hello");
assert_eq!(map["z"].clone_cast::<()>(), ()); assert_eq!(map["z"].as_unit().unwrap(), ());
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
{ {
@ -218,12 +218,37 @@ fn test_map_json() -> Result<(), Box<EvalAltResult>> {
); );
} }
engine.parse_json(&format!("#{}", json), true)?; engine.parse_json(json, true)?;
assert!(matches!( assert!(matches!(
*engine.parse_json(" 123", true).expect_err("should error"), *engine.parse_json("123", true).expect_err("should error"),
EvalAltResult::ErrorParsing(ParseErrorType::MissingToken(token, ..), ..) EvalAltResult::ErrorMismatchOutputType(..)
if token == "{" ));
assert!(matches!(
*engine
.parse_json("#{a:123}", true)
.expect_err("should error"),
EvalAltResult::ErrorParsing(..)
));
assert!(matches!(
*engine.parse_json("{a:()}", true).expect_err("should error"),
EvalAltResult::ErrorParsing(..)
));
assert!(matches!(
*engine
.parse_json("#{a:123+456}", true)
.expect_err("should error"),
EvalAltResult::ErrorParsing(..)
));
assert!(matches!(
*engine
.parse_json("{a:`hello${world}`}", true)
.expect_err("should error"),
EvalAltResult::ErrorParsing(..)
)); ));
Ok(()) Ok(())

View File

@ -56,6 +56,10 @@ fn test_options_allow() -> Result<(), Box<EvalAltResult>> {
fn test_options_strict_var() -> Result<(), Box<EvalAltResult>> { fn test_options_strict_var() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new(); let mut engine = Engine::new();
let mut scope = Scope::new();
scope.push_constant("x", 42 as INT);
scope.push_constant("y", 0 as INT);
engine.compile("let x = if y { z } else { w };")?; engine.compile("let x = if y { z } else { w };")?;
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
@ -79,6 +83,11 @@ fn test_options_strict_var() -> Result<(), Box<EvalAltResult>> {
assert!(engine.compile("let x = if y { z } else { w };").is_err()); assert!(engine.compile("let x = if y { z } else { w };").is_err());
engine.compile("let y = 42; let x = y;")?; engine.compile("let y = 42; let x = y;")?;
assert_eq!(
engine.eval_with_scope::<INT>(&mut scope, "{ let y = 42; x * y }")?,
42 * 42
);
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
assert!(engine.compile("fn foo(x) { x + y }").is_err()); assert!(engine.compile("fn foo(x) { x + y }").is_err());
@ -103,6 +112,11 @@ fn test_options_strict_var() -> Result<(), Box<EvalAltResult>> {
engine.compile("let x = 42; let f = |y| { || x + y };")?; engine.compile("let x = 42; let f = |y| { || x + y };")?;
assert!(engine.compile("fn foo() { |y| { || x + y } }").is_err()); assert!(engine.compile("fn foo() { |y| { || x + y } }").is_err());
} }
#[cfg(not(feature = "no_optimize"))]
assert_eq!(
engine.eval_with_scope::<INT>(&mut scope, "fn foo(z) { x * y + z } foo(1)")?,
1
);
} }
Ok(()) Ok(())

View File

@ -17,6 +17,6 @@ fn test_unit_eq() -> Result<(), Box<EvalAltResult>> {
#[test] #[test]
fn test_unit_with_spaces() -> Result<(), Box<EvalAltResult>> { fn test_unit_with_spaces() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
engine.run("let x = ( ); x")?; engine.run("let x = ( ); x").expect_err("should error");
Ok(()) Ok(())
} }