commit
cfc02b9408
14
CHANGELOG.md
14
CHANGELOG.md
@ -9,6 +9,20 @@ Bug fixes
|
||||
|
||||
* 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
|
||||
=============
|
||||
|
@ -1,7 +1,7 @@
|
||||
//! Module that defines the `call_fn` API of [`Engine`].
|
||||
#![cfg(not(feature = "no_function"))]
|
||||
|
||||
use crate::eval::{EvalState, GlobalRuntimeState};
|
||||
use crate::eval::{Caches, GlobalRuntimeState};
|
||||
use crate::types::dynamic::Variant;
|
||||
use crate::{
|
||||
Dynamic, Engine, FuncArgs, Position, RhaiResult, RhaiResultOf, Scope, StaticVec, AST, ERR,
|
||||
@ -149,7 +149,7 @@ impl Engine {
|
||||
this_ptr: Option<&mut Dynamic>,
|
||||
arg_values: impl AsMut<[Dynamic]>,
|
||||
) -> RhaiResult {
|
||||
let state = &mut EvalState::new();
|
||||
let caches = &mut Caches::new();
|
||||
let global = &mut GlobalRuntimeState::new(self);
|
||||
|
||||
let statements = ast.statements();
|
||||
@ -157,7 +157,7 @@ impl Engine {
|
||||
let orig_scope_len = scope.len();
|
||||
|
||||
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 {
|
||||
scope.rewind(orig_scope_len);
|
||||
@ -181,7 +181,7 @@ impl Engine {
|
||||
self.call_script_fn(
|
||||
scope,
|
||||
global,
|
||||
state,
|
||||
caches,
|
||||
&[ast.as_ref()],
|
||||
&mut this_ptr,
|
||||
fn_def,
|
||||
|
@ -225,13 +225,8 @@ impl Engine {
|
||||
scripts.as_ref(),
|
||||
self.token_mapper.as_ref().map(Box::as_ref),
|
||||
);
|
||||
let mut state = ParseState::new(self, tokenizer_control);
|
||||
self.parse(
|
||||
&mut stream.peekable(),
|
||||
&mut state,
|
||||
scope,
|
||||
optimization_level,
|
||||
)
|
||||
let mut state = ParseState::new(self, scope, tokenizer_control);
|
||||
self.parse(&mut stream.peekable(), &mut state, optimization_level)
|
||||
}
|
||||
/// Compile a string containing an expression into an [`AST`],
|
||||
/// 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));
|
||||
|
||||
let mut peekable = stream.peekable();
|
||||
let mut state = ParseState::new(self, tokenizer_control);
|
||||
self.parse_global_expr(
|
||||
&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)
|
||||
let mut state = ParseState::new(self, scope, tokenizer_control);
|
||||
self.parse_global_expr(&mut peekable, &mut state, self.options.optimization_level)
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,7 @@
|
||||
//! Module implementing custom syntax for [`Engine`].
|
||||
|
||||
use crate::ast::Expr;
|
||||
use crate::eval::Caches;
|
||||
use crate::func::native::SendSync;
|
||||
use crate::parser::ParseResult;
|
||||
use crate::tokenizer::{is_valid_identifier, Token};
|
||||
@ -130,7 +131,7 @@ impl Deref for Expression<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
impl EvalContext<'_, '_, '_, '_, '_, '_, '_, '_, '_, '_> {
|
||||
impl EvalContext<'_, '_, '_, '_, '_, '_, '_, '_> {
|
||||
/// Evaluate an [expression tree][Expression].
|
||||
///
|
||||
/// # 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].
|
||||
#[inline(always)]
|
||||
pub fn eval_expression_tree(&mut self, expr: &Expression) -> RhaiResult {
|
||||
let mut caches;
|
||||
|
||||
self.engine.eval_expr(
|
||||
self.scope,
|
||||
self.global,
|
||||
self.state,
|
||||
match self.caches.as_mut() {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
caches = Caches::new();
|
||||
&mut caches
|
||||
}
|
||||
},
|
||||
self.lib,
|
||||
self.this_ptr,
|
||||
expr,
|
||||
|
@ -1,6 +1,6 @@
|
||||
//! 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::types::dynamic::Variant;
|
||||
use crate::{
|
||||
@ -116,13 +116,12 @@ impl Engine {
|
||||
let scripts = [script];
|
||||
let (stream, tokenizer_control) =
|
||||
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
|
||||
let ast = self.parse_global_expr(
|
||||
&mut stream.peekable(),
|
||||
&mut state,
|
||||
scope,
|
||||
#[cfg(not(feature = "no_optimize"))]
|
||||
OptimizationLevel::None,
|
||||
#[cfg(feature = "no_optimize")]
|
||||
@ -208,7 +207,7 @@ impl Engine {
|
||||
ast: &'a AST,
|
||||
level: usize,
|
||||
) -> RhaiResult {
|
||||
let mut state = EvalState::new();
|
||||
let mut caches = Caches::new();
|
||||
global.source = ast.source_raw().clone();
|
||||
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
@ -231,6 +230,6 @@ impl Engine {
|
||||
} else {
|
||||
&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
181
src/api/json.rs
Normal 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
|
||||
}
|
@ -8,6 +8,8 @@ pub mod run;
|
||||
|
||||
pub mod compile;
|
||||
|
||||
pub mod json;
|
||||
|
||||
pub mod files;
|
||||
|
||||
pub mod register;
|
||||
|
@ -1,6 +1,6 @@
|
||||
//! 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::{Engine, Module, RhaiResultOf, Scope, AST};
|
||||
#[cfg(feature = "no_std")]
|
||||
@ -24,12 +24,11 @@ impl Engine {
|
||||
let scripts = [script];
|
||||
let (stream, tokenizer_control) =
|
||||
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(
|
||||
&mut stream.peekable(),
|
||||
&mut state,
|
||||
scope,
|
||||
self.options.optimization_level,
|
||||
)?;
|
||||
|
||||
@ -43,7 +42,7 @@ impl Engine {
|
||||
/// Evaluate an [`AST`] with own scope, returning any error (if any).
|
||||
#[inline]
|
||||
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);
|
||||
global.source = ast.source_raw().clone();
|
||||
|
||||
@ -63,7 +62,7 @@ impl Engine {
|
||||
} else {
|
||||
&lib
|
||||
};
|
||||
self.eval_global_statements(scope, global, state, statements, lib, 0)?;
|
||||
self.eval_global_statements(scope, global, caches, statements, lib, 0)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
@ -832,6 +832,7 @@ impl Expr {
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Token::LeftBracket => true,
|
||||
Token::LeftParen => true,
|
||||
Token::Unit => true,
|
||||
Token::Bang => true,
|
||||
Token::DoubleColon => true,
|
||||
_ => false,
|
||||
|
115
src/ast/stmt.rs
115
src/ast/stmt.rs
@ -17,7 +17,9 @@ use std::{
|
||||
|
||||
/// _(internals)_ An op-assignment operator.
|
||||
/// 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> {
|
||||
/// Hash of the op-assignment call.
|
||||
pub hash_op_assign: u64,
|
||||
@ -27,9 +29,29 @@ pub struct OpAssignment<'a> {
|
||||
pub op_assign: &'a str,
|
||||
/// Underlying operator.
|
||||
pub op: &'a str,
|
||||
/// [Position] of the op-assignment operator.
|
||||
pub pos: Position,
|
||||
}
|
||||
|
||||
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`].
|
||||
///
|
||||
/// # Panics
|
||||
@ -37,8 +59,8 @@ impl OpAssignment<'_> {
|
||||
/// Panics if the name is not an op-assignment operator.
|
||||
#[must_use]
|
||||
#[inline(always)]
|
||||
pub fn new(name: &str) -> Self {
|
||||
Self::new_from_token(Token::lookup_from_syntax(name).expect("operator"))
|
||||
pub fn new_op_assignment(name: &str, pos: Position) -> Self {
|
||||
Self::new_op_assignment_from_token(Token::lookup_from_syntax(name).expect("operator"), pos)
|
||||
}
|
||||
/// Create a new [`OpAssignment`] from a [`Token`].
|
||||
///
|
||||
@ -46,7 +68,7 @@ impl OpAssignment<'_> {
|
||||
///
|
||||
/// Panics if the token is not an op-assignment operator.
|
||||
#[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
|
||||
.get_base_op_from_assignment()
|
||||
.expect("op-assignment operator")
|
||||
@ -56,6 +78,7 @@ impl OpAssignment<'_> {
|
||||
hash_op: calc_fn_hash(op_raw, 2),
|
||||
op_assign: op.literal_syntax(),
|
||||
op: op_raw,
|
||||
pos,
|
||||
}
|
||||
}
|
||||
/// 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.
|
||||
#[must_use]
|
||||
#[inline(always)]
|
||||
pub fn new_from_base(name: &str) -> Self {
|
||||
Self::new_from_base_token(Token::lookup_from_syntax(name).expect("operator"))
|
||||
pub fn new_op_assignment_from_base(name: &str, pos: Position) -> Self {
|
||||
Self::new_op_assignment_from_base_token(
|
||||
Token::lookup_from_syntax(name).expect("operator"),
|
||||
pos,
|
||||
)
|
||||
}
|
||||
/// 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.
|
||||
#[inline(always)]
|
||||
#[must_use]
|
||||
pub fn new_from_base_token(op: Token) -> Self {
|
||||
Self::new_from_token(op.convert_to_op_assignment().expect("operator"))
|
||||
pub fn new_op_assignment_from_base_token(op: Token, pos: Position) -> Self {
|
||||
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)]
|
||||
pub struct ConditionalStmtBlock {
|
||||
/// Optional condition.
|
||||
pub condition: Option<Expr>,
|
||||
/// Condition.
|
||||
pub condition: Expr,
|
||||
/// Statements block.
|
||||
pub statements: StmtBlock,
|
||||
}
|
||||
@ -93,7 +137,7 @@ impl<B: Into<StmtBlock>> From<B> for ConditionalStmtBlock {
|
||||
#[inline(always)]
|
||||
fn from(value: B) -> Self {
|
||||
Self {
|
||||
condition: None,
|
||||
condition: Expr::BoolConstant(true, Position::NONE),
|
||||
statements: value.into(),
|
||||
}
|
||||
}
|
||||
@ -102,16 +146,6 @@ impl<B: Into<StmtBlock>> From<B> for ConditionalStmtBlock {
|
||||
impl<B: Into<StmtBlock>> From<(Expr, B)> for ConditionalStmtBlock {
|
||||
#[inline(always)]
|
||||
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 {
|
||||
condition: value.0,
|
||||
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.
|
||||
/// Exported under the `internals` feature only.
|
||||
#[derive(Debug, Clone, Hash)]
|
||||
@ -375,7 +400,7 @@ pub enum Stmt {
|
||||
/// * [`CONSTANT`][ASTFlags::CONSTANT] = `const`
|
||||
Var(Box<(Ident, Expr, Option<NonZeroUsize>)>, ASTFlags, Position),
|
||||
/// expr op`=` expr
|
||||
Assignment(Box<(Option<OpAssignment<'static>>, BinaryExpr)>, Position),
|
||||
Assignment(Box<(OpAssignment<'static>, BinaryExpr)>),
|
||||
/// func `(` expr `,` ... `)`
|
||||
///
|
||||
/// 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 {
|
||||
Self::Noop(pos)
|
||||
| Self::BreakLoop(.., pos)
|
||||
| Self::Assignment(.., pos)
|
||||
| Self::FnCall(.., pos)
|
||||
| Self::If(.., pos)
|
||||
| Self::Switch(.., pos)
|
||||
@ -475,6 +499,8 @@ impl Stmt {
|
||||
| Self::Var(.., pos)
|
||||
| Self::TryCatch(.., pos) => *pos,
|
||||
|
||||
Self::Assignment(x) => x.0.pos,
|
||||
|
||||
Self::Block(x) => x.position(),
|
||||
|
||||
Self::Expr(x) => x.start_position(),
|
||||
@ -493,7 +519,6 @@ impl Stmt {
|
||||
match self {
|
||||
Self::Noop(pos)
|
||||
| Self::BreakLoop(.., pos)
|
||||
| Self::Assignment(.., pos)
|
||||
| Self::FnCall(.., pos)
|
||||
| Self::If(.., pos)
|
||||
| Self::Switch(.., pos)
|
||||
@ -504,6 +529,8 @@ impl Stmt {
|
||||
| Self::Var(.., 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::Expr(x) => {
|
||||
@ -593,12 +620,10 @@ impl Stmt {
|
||||
Self::Switch(x, ..) => {
|
||||
x.0.is_pure()
|
||||
&& x.1.cases.values().all(|block| {
|
||||
block.condition.as_ref().map(Expr::is_pure).unwrap_or(true)
|
||||
&& block.statements.iter().all(Stmt::is_pure)
|
||||
block.condition.is_pure() && block.statements.iter().all(Stmt::is_pure)
|
||||
})
|
||||
&& x.1.ranges.iter().all(|(.., block)| {
|
||||
block.condition.as_ref().map(Expr::is_pure).unwrap_or(true)
|
||||
&& block.statements.iter().all(Stmt::is_pure)
|
||||
block.condition.is_pure() && block.statements.iter().all(Stmt::is_pure)
|
||||
})
|
||||
&& x.1.def_case.iter().all(Stmt::is_pure)
|
||||
}
|
||||
@ -740,12 +765,7 @@ impl Stmt {
|
||||
return false;
|
||||
}
|
||||
for b in x.1.cases.values() {
|
||||
if !b
|
||||
.condition
|
||||
.as_ref()
|
||||
.map(|e| e.walk(path, on_node))
|
||||
.unwrap_or(true)
|
||||
{
|
||||
if !b.condition.walk(path, on_node) {
|
||||
return false;
|
||||
}
|
||||
for s in b.statements.iter() {
|
||||
@ -755,12 +775,7 @@ impl Stmt {
|
||||
}
|
||||
}
|
||||
for (.., b) in &x.1.ranges {
|
||||
if !b
|
||||
.condition
|
||||
.as_ref()
|
||||
.map(|e| e.walk(path, on_node))
|
||||
.unwrap_or(true)
|
||||
{
|
||||
if !b.condition.walk(path, on_node) {
|
||||
return false;
|
||||
}
|
||||
for s in b.statements.iter() {
|
||||
|
69
src/eval/cache.rs
Normal file
69
src/eval/cache.rs
Normal 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);
|
||||
}
|
||||
}
|
@ -1,7 +1,7 @@
|
||||
//! Types to support chaining operations (i.e. indexing and dotting).
|
||||
#![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::types::dynamic::Union;
|
||||
use crate::{Dynamic, Engine, Module, Position, RhaiResult, RhaiResultOf, Scope, StaticVec, ERR};
|
||||
@ -122,7 +122,7 @@ impl Engine {
|
||||
fn eval_dot_index_chain_helper(
|
||||
&self,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
target: &mut Target,
|
||||
@ -130,10 +130,10 @@ impl Engine {
|
||||
_parent: &Expr,
|
||||
rhs: &Expr,
|
||||
_parent_options: ASTFlags,
|
||||
idx_values: &mut StaticVec<super::ChainArgument>,
|
||||
idx_values: &mut StaticVec<ChainArgument>,
|
||||
chain_type: ChainType,
|
||||
level: usize,
|
||||
new_val: Option<((Dynamic, Position), (Option<OpAssignment>, Position))>,
|
||||
new_val: Option<(Dynamic, OpAssignment)>,
|
||||
) -> RhaiResultOf<(Dynamic, bool)> {
|
||||
let is_ref_mut = target.is_ref();
|
||||
|
||||
@ -155,7 +155,7 @@ impl Engine {
|
||||
if !_parent_options.contains(ASTFlags::BREAK) =>
|
||||
{
|
||||
#[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 idx_pos = x.lhs.start_position();
|
||||
@ -163,14 +163,14 @@ impl Engine {
|
||||
|
||||
let (try_setter, result) = {
|
||||
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 obj_ptr = &mut obj;
|
||||
|
||||
match self.eval_dot_index_chain_helper(
|
||||
global, state, lib, this_ptr, obj_ptr, root, rhs, &x.rhs, *options,
|
||||
idx_values, rhs_chain, level, new_val,
|
||||
global, caches, lib, this_ptr, obj_ptr, root, rhs, &x.rhs,
|
||||
*options, idx_values, rhs_chain, level, new_val,
|
||||
) {
|
||||
Ok((result, true)) if is_obj_temp_val => {
|
||||
(Some(obj.take_or_clone()), (result, true))
|
||||
@ -185,7 +185,7 @@ impl Engine {
|
||||
let idx = &mut idx_val_for_setter;
|
||||
let new_val = &mut new_val;
|
||||
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 {
|
||||
ERR::ErrorIndexingType(..) => Ok((Dynamic::UNIT, false)),
|
||||
@ -198,23 +198,21 @@ impl Engine {
|
||||
// xxx[rhs] op= new_val
|
||||
_ if new_val.is_some() => {
|
||||
#[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 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
|
||||
Ok(ref mut obj_ptr) => {
|
||||
self.eval_op_assignment(
|
||||
global, state, lib, op_info, op_pos, obj_ptr, root, new_val,
|
||||
level,
|
||||
)
|
||||
.map_err(|err| err.fill_position(new_pos))?;
|
||||
global, caches, lib, op_info, obj_ptr, root, new_val, level,
|
||||
)?;
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
self.check_data_size(obj_ptr, new_pos)?;
|
||||
self.check_data_size(obj_ptr, op_info.pos)?;
|
||||
None
|
||||
}
|
||||
// Indexed value cannot be referenced - use indexer
|
||||
@ -228,30 +226,29 @@ impl Engine {
|
||||
let idx = &mut idx_val2;
|
||||
|
||||
// Is this an op-assignment?
|
||||
if op_info.is_some() {
|
||||
if op_info.is_op_assignment() {
|
||||
let idx = &mut idx.clone();
|
||||
// Call the index getter to get the current value
|
||||
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();
|
||||
// Run the op-assignment
|
||||
self.eval_op_assignment(
|
||||
global, state, lib, op_info, op_pos, &mut res, root,
|
||||
new_val, level,
|
||||
)
|
||||
.map_err(|err| err.fill_position(new_pos))?;
|
||||
global, caches, lib, op_info, &mut res, root, new_val,
|
||||
level,
|
||||
)?;
|
||||
// Replace new value
|
||||
new_val = res.take_or_clone();
|
||||
#[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
|
||||
let new_val = &mut new_val;
|
||||
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]
|
||||
_ => {
|
||||
#[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(
|
||||
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))
|
||||
}
|
||||
@ -279,12 +276,11 @@ impl Engine {
|
||||
let call_args = &mut idx_val.into_fn_call_args();
|
||||
|
||||
#[cfg(feature = "debugging")]
|
||||
let reset_debugger = self.run_debugger_with_reset(
|
||||
scope, global, state, lib, this_ptr, rhs, level,
|
||||
)?;
|
||||
let reset_debugger =
|
||||
self.run_debugger_with_reset(scope, global, lib, this_ptr, rhs, level)?;
|
||||
|
||||
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")]
|
||||
@ -303,57 +299,55 @@ impl Engine {
|
||||
// {xxx:map}.id op= ???
|
||||
Expr::Property(x, pos) if target.is::<crate::Map>() && new_val.is_some() => {
|
||||
#[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 ((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(
|
||||
global, state, lib, target, index, *pos, true, false, level,
|
||||
global, caches, lib, target, index, *pos, true, false, level,
|
||||
)?;
|
||||
self.eval_op_assignment(
|
||||
global, state, lib, op_info, op_pos, val_target, root, new_val,
|
||||
level,
|
||||
)
|
||||
.map_err(|err| err.fill_position(new_pos))?;
|
||||
global, caches, lib, op_info, val_target, root, new_val, level,
|
||||
)?;
|
||||
}
|
||||
#[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))
|
||||
}
|
||||
// {xxx:map}.id
|
||||
Expr::Property(x, pos) if target.is::<crate::Map>() => {
|
||||
#[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 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))
|
||||
}
|
||||
// xxx.id op= ???
|
||||
Expr::Property(x, pos) if new_val.is_some() => {
|
||||
#[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 ((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 args = &mut [target.as_mut()];
|
||||
let (mut orig_val, ..) = self
|
||||
.exec_fn_call(
|
||||
None, global, state, lib, getter, hash, args, is_ref_mut, true,
|
||||
*pos, level,
|
||||
None, global, caches, lib, getter, hash, args, is_ref_mut,
|
||||
true, *pos, level,
|
||||
)
|
||||
.or_else(|err| match *err {
|
||||
// Try an indexer if property does not exist
|
||||
ERR::ErrorDotExpr(..) => {
|
||||
let mut prop = name.into();
|
||||
self.call_indexer_get(
|
||||
global, state, lib, target, &mut prop, level,
|
||||
global, caches, lib, target, &mut prop, level,
|
||||
)
|
||||
.map(|r| (r, false))
|
||||
.map_err(|e| {
|
||||
@ -370,10 +364,8 @@ impl Engine {
|
||||
let orig_val = &mut (&mut orig_val).into();
|
||||
|
||||
self.eval_op_assignment(
|
||||
global, state, lib, op_info, op_pos, orig_val, root, new_val,
|
||||
level,
|
||||
)
|
||||
.map_err(|err| err.fill_position(new_pos))?;
|
||||
global, caches, lib, op_info, orig_val, root, new_val, level,
|
||||
)?;
|
||||
}
|
||||
|
||||
new_val = orig_val;
|
||||
@ -382,7 +374,7 @@ impl Engine {
|
||||
let hash = crate::ast::FnCallHashes::from_native(*hash_set);
|
||||
let args = &mut [target.as_mut(), &mut new_val];
|
||||
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,
|
||||
)
|
||||
.or_else(|err| match *err {
|
||||
@ -391,7 +383,7 @@ impl Engine {
|
||||
let idx = &mut name.into();
|
||||
let new_val = &mut new_val;
|
||||
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 {
|
||||
ERR::ErrorIndexingType(..) => err,
|
||||
@ -404,13 +396,13 @@ impl Engine {
|
||||
// xxx.id
|
||||
Expr::Property(x, pos) => {
|
||||
#[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 hash = crate::ast::FnCallHashes::from_native(*hash_get);
|
||||
let args = &mut [target.as_mut()];
|
||||
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,
|
||||
)
|
||||
.map_or_else(
|
||||
@ -419,7 +411,7 @@ impl Engine {
|
||||
ERR::ErrorDotExpr(..) => {
|
||||
let mut prop = name.into();
|
||||
self.call_indexer_get(
|
||||
global, state, lib, target, &mut prop, level,
|
||||
global, caches, lib, target, &mut prop, level,
|
||||
)
|
||||
.map(|r| (r, false))
|
||||
.map_err(|e| match *e {
|
||||
@ -442,13 +434,11 @@ impl Engine {
|
||||
let val_target = &mut match x.lhs {
|
||||
Expr::Property(ref p, pos) => {
|
||||
#[cfg(feature = "debugging")]
|
||||
self.run_debugger(
|
||||
scope, global, state, lib, this_ptr, _node, level,
|
||||
)?;
|
||||
self.run_debugger(scope, global, lib, this_ptr, _node, level)?;
|
||||
|
||||
let index = p.2.clone().into();
|
||||
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
|
||||
@ -458,11 +448,11 @@ impl Engine {
|
||||
|
||||
#[cfg(feature = "debugging")]
|
||||
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(
|
||||
global, state, lib, name, *hashes, target, call_args, pos,
|
||||
global, caches, lib, name, *hashes, target, call_args, pos,
|
||||
level,
|
||||
);
|
||||
|
||||
@ -481,7 +471,7 @@ impl Engine {
|
||||
let rhs_chain = rhs.into();
|
||||
|
||||
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,
|
||||
)
|
||||
.map_err(|err| err.fill_position(*x_pos))
|
||||
@ -494,9 +484,7 @@ impl Engine {
|
||||
// xxx.prop[expr] | xxx.prop.expr
|
||||
Expr::Property(ref p, pos) => {
|
||||
#[cfg(feature = "debugging")]
|
||||
self.run_debugger(
|
||||
scope, global, state, lib, this_ptr, _node, level,
|
||||
)?;
|
||||
self.run_debugger(scope, global, lib, this_ptr, _node, level)?;
|
||||
|
||||
let ((getter, hash_get), (setter, hash_set), name) = p.as_ref();
|
||||
let rhs_chain = rhs.into();
|
||||
@ -508,7 +496,7 @@ impl Engine {
|
||||
// Assume getters are always pure
|
||||
let (mut val, ..) = self
|
||||
.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,
|
||||
)
|
||||
.or_else(|err| match *err {
|
||||
@ -516,7 +504,7 @@ impl Engine {
|
||||
ERR::ErrorDotExpr(..) => {
|
||||
let mut prop = name.into();
|
||||
self.call_indexer_get(
|
||||
global, state, lib, target, &mut prop, level,
|
||||
global, caches, lib, target, &mut prop, level,
|
||||
)
|
||||
.map(|r| (r, false))
|
||||
.map_err(
|
||||
@ -533,7 +521,7 @@ impl Engine {
|
||||
|
||||
let (result, may_be_changed) = self
|
||||
.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,
|
||||
)
|
||||
.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 args = &mut arg_values;
|
||||
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,
|
||||
)
|
||||
.or_else(
|
||||
@ -554,7 +542,7 @@ impl Engine {
|
||||
let idx = &mut name.into();
|
||||
let new_val = val;
|
||||
self.call_indexer_set(
|
||||
global, state, lib, target, idx, new_val,
|
||||
global, caches, lib, target, idx, new_val,
|
||||
is_ref_mut, level,
|
||||
)
|
||||
.or_else(|e| match *e {
|
||||
@ -581,11 +569,11 @@ impl Engine {
|
||||
|
||||
#[cfg(feature = "debugging")]
|
||||
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(
|
||||
global, state, lib, name, *hashes, target, args, pos, level,
|
||||
global, caches, lib, name, *hashes, target, args, pos, level,
|
||||
);
|
||||
|
||||
#[cfg(feature = "debugging")]
|
||||
@ -595,8 +583,8 @@ impl Engine {
|
||||
let val = &mut val.into();
|
||||
|
||||
self.eval_dot_index_chain_helper(
|
||||
global, state, lib, this_ptr, val, root, rhs, &x.rhs, *options,
|
||||
idx_values, rhs_chain, level, new_val,
|
||||
global, caches, lib, this_ptr, val, root, rhs, &x.rhs,
|
||||
*options, idx_values, rhs_chain, level, new_val,
|
||||
)
|
||||
.map_err(|err| err.fill_position(pos))
|
||||
}
|
||||
@ -620,12 +608,12 @@ impl Engine {
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
expr: &Expr,
|
||||
level: usize,
|
||||
new_val: Option<((Dynamic, Position), (Option<OpAssignment>, Position))>,
|
||||
new_val: Option<(Dynamic, OpAssignment)>,
|
||||
) -> RhaiResult {
|
||||
let (crate::ast::BinaryExpr { lhs, rhs }, chain_type, options, op_pos) = match expr {
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
@ -638,7 +626,7 @@ impl Engine {
|
||||
let idx_values = &mut StaticVec::new_const();
|
||||
|
||||
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();
|
||||
@ -647,19 +635,19 @@ impl Engine {
|
||||
// id.??? or id[???]
|
||||
Expr::Variable(x, .., var_pos) => {
|
||||
#[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"))]
|
||||
self.inc_operations(&mut global.num_operations, *var_pos)?;
|
||||
|
||||
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 root = (x.3.as_str(), *var_pos);
|
||||
|
||||
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,
|
||||
)
|
||||
.map(|(v, ..)| v)
|
||||
@ -669,11 +657,11 @@ impl Engine {
|
||||
_ if is_assignment => unreachable!("cannot assign to an expression"),
|
||||
// {expr}.??? or {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 root = ("", expr.start_position());
|
||||
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,
|
||||
)
|
||||
.map(|(v, ..)| if is_assignment { Dynamic::UNIT } else { v })
|
||||
@ -689,13 +677,13 @@ impl Engine {
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
expr: &Expr,
|
||||
parent_options: ASTFlags,
|
||||
_parent_chain_type: ChainType,
|
||||
idx_values: &mut StaticVec<super::ChainArgument>,
|
||||
idx_values: &mut StaticVec<ChainArgument>,
|
||||
size: usize,
|
||||
level: usize,
|
||||
) -> RhaiResultOf<()> {
|
||||
@ -713,7 +701,7 @@ impl Engine {
|
||||
(crate::FnArgsVec::with_capacity(args.len()), Position::NONE),
|
||||
|(mut values, mut pos), expr| {
|
||||
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() {
|
||||
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"))]
|
||||
Expr::MethodCall(..) if _parent_chain_type == ChainType::Dotting => {
|
||||
@ -731,7 +719,7 @@ impl Engine {
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
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"),
|
||||
|
||||
@ -744,7 +732,7 @@ impl Engine {
|
||||
let lhs_arg_val = match lhs {
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Expr::Property(.., pos) if _parent_chain_type == ChainType::Dotting => {
|
||||
super::ChainArgument::Property(*pos)
|
||||
ChainArgument::Property(*pos)
|
||||
}
|
||||
Expr::Property(..) => unreachable!("unexpected Expr::Property for indexing"),
|
||||
|
||||
@ -758,7 +746,7 @@ impl Engine {
|
||||
(crate::FnArgsVec::with_capacity(args.len()), Position::NONE),
|
||||
|(mut values, mut pos), expr| {
|
||||
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() {
|
||||
pos = arg_pos
|
||||
@ -767,7 +755,7 @@ impl Engine {
|
||||
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"))]
|
||||
Expr::MethodCall(..) if _parent_chain_type == ChainType::Dotting => {
|
||||
@ -779,12 +767,9 @@ impl Engine {
|
||||
}
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
_ 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| {
|
||||
super::ChainArgument::from_index_value(
|
||||
v.flatten(),
|
||||
lhs.start_position(),
|
||||
)
|
||||
ChainArgument::from_index_value(v.flatten(), lhs.start_position())
|
||||
})?,
|
||||
expr => unreachable!("unknown chained expression: {:?}", expr),
|
||||
};
|
||||
@ -793,7 +778,7 @@ impl Engine {
|
||||
let chain_type = expr.into();
|
||||
|
||||
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,
|
||||
)?;
|
||||
|
||||
@ -806,10 +791,8 @@ impl Engine {
|
||||
}
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
_ if _parent_chain_type == ChainType::Indexing => idx_values.push(
|
||||
self.eval_expr(scope, global, state, lib, this_ptr, expr, level)
|
||||
.map(|v| {
|
||||
super::ChainArgument::from_index_value(v.flatten(), expr.start_position())
|
||||
})?,
|
||||
self.eval_expr(scope, global, caches, lib, this_ptr, expr, level)
|
||||
.map(|v| ChainArgument::from_index_value(v.flatten(), expr.start_position()))?,
|
||||
),
|
||||
_ => unreachable!("unknown chained expression: {:?}", expr),
|
||||
}
|
||||
@ -823,7 +806,7 @@ impl Engine {
|
||||
fn call_indexer_get(
|
||||
&self,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
target: &mut Dynamic,
|
||||
idx: &mut Dynamic,
|
||||
@ -835,7 +818,7 @@ impl Engine {
|
||||
let pos = Position::NONE;
|
||||
|
||||
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)
|
||||
}
|
||||
@ -846,7 +829,7 @@ impl Engine {
|
||||
fn call_indexer_set(
|
||||
&self,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
target: &mut Dynamic,
|
||||
idx: &mut Dynamic,
|
||||
@ -860,7 +843,7 @@ impl Engine {
|
||||
let pos = Position::NONE;
|
||||
|
||||
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>(
|
||||
&self,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
target: &'t mut Dynamic,
|
||||
mut idx: Dynamic,
|
||||
@ -1064,7 +1047,7 @@ impl Engine {
|
||||
}
|
||||
|
||||
_ 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),
|
||||
|
||||
_ => Err(ERR::ErrorIndexingType(
|
||||
|
@ -1,7 +1,7 @@
|
||||
//! Module defining the debugging interface.
|
||||
#![cfg(feature = "debugging")]
|
||||
|
||||
use super::{EvalContext, EvalState, GlobalRuntimeState};
|
||||
use super::{EvalContext, GlobalRuntimeState};
|
||||
use crate::ast::{ASTNode, Expr, Stmt};
|
||||
use crate::{Dynamic, Engine, EvalAltResult, Identifier, Module, Position, RhaiResultOf, Scope};
|
||||
#[cfg(feature = "no_std")]
|
||||
@ -406,7 +406,6 @@ impl Engine {
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
lib: &[&Module],
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
node: impl Into<ASTNode<'a>>,
|
||||
@ -414,7 +413,7 @@ impl Engine {
|
||||
) -> RhaiResultOf<()> {
|
||||
if self.debugger.is_some() {
|
||||
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;
|
||||
}
|
||||
@ -434,14 +433,13 @@ impl Engine {
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
lib: &[&Module],
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
node: impl Into<ASTNode<'a>>,
|
||||
level: usize,
|
||||
) -> RhaiResultOf<Option<DebuggerStatus>> {
|
||||
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 {
|
||||
Ok(None)
|
||||
}
|
||||
@ -458,7 +456,6 @@ impl Engine {
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
lib: &[&Module],
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
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.
|
||||
///
|
||||
@ -504,7 +501,6 @@ impl Engine {
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
lib: &[&Module],
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
node: ASTNode<'a>,
|
||||
@ -522,7 +518,7 @@ impl Engine {
|
||||
engine: self,
|
||||
scope,
|
||||
global,
|
||||
state,
|
||||
caches: None,
|
||||
lib,
|
||||
this_ptr,
|
||||
level,
|
||||
|
@ -1,30 +1,30 @@
|
||||
//! Evaluation context.
|
||||
|
||||
use super::{EvalState, GlobalRuntimeState};
|
||||
use super::{Caches, GlobalRuntimeState};
|
||||
use crate::{Dynamic, Engine, Module, Scope};
|
||||
#[cfg(feature = "no_std")]
|
||||
use std::prelude::v1::*;
|
||||
|
||||
/// Context of a script evaluation process.
|
||||
#[derive(Debug)]
|
||||
pub struct EvalContext<'a, 'x, 'px, 'm, 'pm, 's, 'ps, 'b, 't, 'pt> {
|
||||
pub struct EvalContext<'a, 's, 'ps, 'm, 'pm, 'c, 't, 'pt> {
|
||||
/// The current [`Engine`].
|
||||
pub(crate) engine: &'a Engine,
|
||||
/// The current [`Scope`].
|
||||
pub(crate) scope: &'x mut Scope<'px>,
|
||||
pub(crate) scope: &'s mut Scope<'ps>,
|
||||
/// The current [`GlobalRuntimeState`].
|
||||
pub(crate) global: &'m mut GlobalRuntimeState<'pm>,
|
||||
/// The current [evaluation state][EvalState].
|
||||
pub(crate) state: &'s mut EvalState<'ps>,
|
||||
/// The current [caches][Caches], if available.
|
||||
pub(crate) caches: Option<&'c mut Caches>,
|
||||
/// 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.
|
||||
pub(crate) this_ptr: &'t mut Option<&'pt mut Dynamic>,
|
||||
/// The current nesting level of function calls.
|
||||
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`].
|
||||
#[inline(always)]
|
||||
#[must_use]
|
||||
@ -44,13 +44,13 @@ impl<'x, 'px, 'm, 'pm, 'pt> EvalContext<'_, 'x, 'px, 'm, 'pm, '_, '_, '_, '_, 'p
|
||||
/// The current [`Scope`].
|
||||
#[inline(always)]
|
||||
#[must_use]
|
||||
pub const fn scope(&self) -> &Scope<'px> {
|
||||
pub const fn scope(&self) -> &Scope<'ps> {
|
||||
self.scope
|
||||
}
|
||||
/// Get a mutable reference to the current [`Scope`].
|
||||
#[inline(always)]
|
||||
#[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
|
||||
}
|
||||
/// Get an iterator over the current set of modules imported via `import` statements,
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
@ -1,6 +1,6 @@
|
||||
//! 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::engine::{KEYWORD_THIS, OP_CONCAT};
|
||||
use crate::types::dynamic::AccessMode;
|
||||
@ -17,7 +17,6 @@ impl Engine {
|
||||
pub(crate) fn search_imports(
|
||||
&self,
|
||||
global: &GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
namespace: &crate::ast::Namespace,
|
||||
) -> Option<crate::Shared<Module>> {
|
||||
assert!(!namespace.is_empty());
|
||||
@ -25,7 +24,7 @@ impl Engine {
|
||||
let root = namespace.root();
|
||||
|
||||
// Qualified - check if the root module is directly indexed
|
||||
let index = if state.always_search_scope {
|
||||
let index = if global.always_search_scope {
|
||||
None
|
||||
} else {
|
||||
namespace.index()
|
||||
@ -48,7 +47,6 @@ impl Engine {
|
||||
&self,
|
||||
scope: &'s mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
lib: &[&Module],
|
||||
this_ptr: &'s mut Option<&mut Dynamic>,
|
||||
expr: &Expr,
|
||||
@ -56,24 +54,22 @@ impl Engine {
|
||||
) -> RhaiResultOf<(Target<'s>, Position)> {
|
||||
match expr {
|
||||
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() {
|
||||
// Normal variable access
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
(_, 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")]
|
||||
(_, (), ..) => {
|
||||
self.search_scope_only(scope, global, state, lib, this_ptr, expr, level)
|
||||
}
|
||||
(_, (), ..) => self.search_scope_only(scope, global, lib, this_ptr, expr, level),
|
||||
|
||||
// Qualified variable access
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
(_, namespace, hash_var, var_name) => {
|
||||
// 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) {
|
||||
// Module variables are constant
|
||||
target.set_access_mode(AccessMode::ReadOnly);
|
||||
@ -131,7 +127,6 @@ impl Engine {
|
||||
&self,
|
||||
scope: &'s mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
lib: &[&Module],
|
||||
this_ptr: &'s mut Option<&mut Dynamic>,
|
||||
expr: &Expr,
|
||||
@ -148,7 +143,7 @@ impl Engine {
|
||||
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(v, None, pos) => (v.0.map(NonZeroUsize::get).unwrap_or(0), *pos),
|
||||
_ => unreachable!("Expr::Variable expected but gets {:?}", expr),
|
||||
@ -160,7 +155,7 @@ impl Engine {
|
||||
engine: self,
|
||||
scope,
|
||||
global,
|
||||
state,
|
||||
caches: None,
|
||||
lib,
|
||||
this_ptr,
|
||||
level,
|
||||
@ -205,7 +200,7 @@ impl Engine {
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
expr: &FnCallExpr,
|
||||
@ -228,7 +223,7 @@ impl Engine {
|
||||
let hash = hashes.native;
|
||||
|
||||
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(
|
||||
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,
|
||||
)
|
||||
}
|
||||
@ -256,7 +251,7 @@ impl Engine {
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
expr: &Expr,
|
||||
@ -270,13 +265,13 @@ impl Engine {
|
||||
if let Expr::FnCall(x, ..) = expr {
|
||||
#[cfg(feature = "debugging")]
|
||||
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"))]
|
||||
self.inc_operations(&mut global.num_operations, expr.position())?;
|
||||
|
||||
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")]
|
||||
global.debugger.reset_status(reset_debugger);
|
||||
@ -289,7 +284,7 @@ impl Engine {
|
||||
// will cost more than the mis-predicted `match` branch.
|
||||
if let Expr::Variable(x, index, var_pos) = expr {
|
||||
#[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"))]
|
||||
self.inc_operations(&mut global.num_operations, expr.position())?;
|
||||
@ -300,14 +295,14 @@ impl Engine {
|
||||
.cloned()
|
||||
.ok_or_else(|| ERR::ErrorUnboundThis(*var_pos).into())
|
||||
} 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())
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(feature = "debugging")]
|
||||
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"))]
|
||||
self.inc_operations(&mut global.num_operations, expr.position())?;
|
||||
@ -325,12 +320,16 @@ impl Engine {
|
||||
|
||||
// `... ${...} ...`
|
||||
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 op_info = OpAssignment::new_op_assignment(OP_CONCAT, Position::NONE);
|
||||
let root = ("", Position::NONE);
|
||||
|
||||
for expr in x.iter() {
|
||||
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,
|
||||
err => {
|
||||
result = err;
|
||||
@ -338,23 +337,17 @@ impl Engine {
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(err) = self.eval_op_assignment(
|
||||
global,
|
||||
state,
|
||||
lib,
|
||||
Some(OpAssignment::new(OP_CONCAT)),
|
||||
expr.start_position(),
|
||||
&mut (&mut concat).into(),
|
||||
("", Position::NONE),
|
||||
item,
|
||||
level,
|
||||
) {
|
||||
result = Err(err.fill_position(expr.start_position()));
|
||||
op_info.pos = expr.start_position();
|
||||
|
||||
if let Err(err) = self
|
||||
.eval_op_assignment(global, caches, lib, op_info, target, root, item, level)
|
||||
{
|
||||
result = Err(err);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
result.map(|_| concat)
|
||||
result.map(|_| concat.take_or_clone())
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
@ -367,7 +360,7 @@ impl Engine {
|
||||
|
||||
for item_expr in x.iter() {
|
||||
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(),
|
||||
err => {
|
||||
@ -405,7 +398,7 @@ impl Engine {
|
||||
|
||||
for (key, value_expr) in x.0.iter() {
|
||||
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(),
|
||||
err => {
|
||||
@ -431,7 +424,7 @@ impl Engine {
|
||||
|
||||
Expr::And(x, ..) => {
|
||||
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| {
|
||||
v.as_bool().map_err(|typ| {
|
||||
self.make_type_mismatch_err::<bool>(typ, x.lhs.position())
|
||||
@ -439,7 +432,7 @@ impl Engine {
|
||||
});
|
||||
|
||||
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| {
|
||||
v.as_bool()
|
||||
.map_err(|typ| {
|
||||
@ -454,7 +447,7 @@ impl Engine {
|
||||
|
||||
Expr::Or(x, ..) => {
|
||||
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| {
|
||||
v.as_bool().map_err(|typ| {
|
||||
self.make_type_mismatch_err::<bool>(typ, x.lhs.position())
|
||||
@ -462,7 +455,7 @@ impl Engine {
|
||||
});
|
||||
|
||||
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| {
|
||||
v.as_bool()
|
||||
.map_err(|typ| {
|
||||
@ -491,7 +484,7 @@ impl Engine {
|
||||
engine: self,
|
||||
scope,
|
||||
global,
|
||||
state,
|
||||
caches: Some(caches),
|
||||
lib,
|
||||
this_ptr,
|
||||
level,
|
||||
@ -504,17 +497,17 @@ impl Engine {
|
||||
|
||||
Expr::Stmt(x) if x.is_empty() => Ok(Dynamic::UNIT),
|
||||
Expr::Stmt(x) => {
|
||||
self.eval_stmt_block(scope, global, state, lib, this_ptr, x, true, level)
|
||||
self.eval_stmt_block(scope, global, caches, lib, this_ptr, x, true, level)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Expr::Index(..) => {
|
||||
self.eval_dot_index_chain(scope, global, state, lib, this_ptr, expr, level, None)
|
||||
self.eval_dot_index_chain(scope, global, caches, lib, this_ptr, expr, level, None)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Expr::Dot(..) => {
|
||||
self.eval_dot_index_chain(scope, global, state, lib, this_ptr, expr, level, None)
|
||||
self.eval_dot_index_chain(scope, global, caches, lib, this_ptr, expr, level, None)
|
||||
}
|
||||
|
||||
_ => unreachable!("expression cannot be evaluated: {:?}", expr),
|
||||
|
@ -30,16 +30,31 @@ pub struct GlobalRuntimeState<'a> {
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
modules: crate::StaticVec<crate::Shared<crate::Module>>,
|
||||
/// Source of the current context.
|
||||
///
|
||||
/// No source if the string is empty.
|
||||
pub source: Identifier,
|
||||
/// Number of operations performed.
|
||||
pub num_operations: u64,
|
||||
/// Number of modules loaded.
|
||||
pub num_modules_loaded: usize,
|
||||
/// 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.
|
||||
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
||||
fn_hash_indexing: (u64, u64),
|
||||
/// Embedded [crate::Module][crate::Module] resolver.
|
||||
/// Embedded [module][crate::Module] resolver.
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
pub embedded_module_resolver:
|
||||
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.
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
pub(crate) constants: Option<GlobalConstants>,
|
||||
pub constants: Option<GlobalConstants>,
|
||||
/// Debugging interface.
|
||||
#[cfg(feature = "debugging")]
|
||||
pub debugger: super::Debugger,
|
||||
@ -71,6 +86,8 @@ impl GlobalRuntimeState<'_> {
|
||||
source: Identifier::new_const(),
|
||||
num_operations: 0,
|
||||
num_modules_loaded: 0,
|
||||
scope_level: 0,
|
||||
always_search_scope: false,
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
embedded_module_resolver: None,
|
||||
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
||||
@ -92,7 +109,7 @@ impl GlobalRuntimeState<'_> {
|
||||
pub fn num_imports(&self) -> usize {
|
||||
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`.
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
@ -101,7 +118,7 @@ impl GlobalRuntimeState<'_> {
|
||||
pub fn get_shared_import(&self, index: usize) -> Option<crate::Shared<crate::Module>> {
|
||||
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.
|
||||
///
|
||||
/// Not available under `no_module`.
|
||||
@ -115,7 +132,7 @@ impl GlobalRuntimeState<'_> {
|
||||
) -> Option<&mut crate::Shared<crate::Module>> {
|
||||
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`.
|
||||
#[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`.
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
|
@ -1,13 +1,14 @@
|
||||
mod cache;
|
||||
mod chaining;
|
||||
mod data_check;
|
||||
mod debugger;
|
||||
mod eval_context;
|
||||
mod eval_state;
|
||||
mod expr;
|
||||
mod global_state;
|
||||
mod stmt;
|
||||
mod target;
|
||||
|
||||
pub use cache::{Caches, FnResolutionCache, FnResolutionCacheEntry};
|
||||
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
||||
pub use chaining::{ChainArgument, ChainType};
|
||||
#[cfg(feature = "debugging")]
|
||||
@ -16,7 +17,6 @@ pub use debugger::{
|
||||
OnDebuggerCallback, OnDebuggingInit,
|
||||
};
|
||||
pub use eval_context::EvalContext;
|
||||
pub use eval_state::EvalState;
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
pub use global_state::GlobalConstants;
|
||||
|
183
src/eval/stmt.rs
183
src/eval/stmt.rs
@ -1,6 +1,6 @@
|
||||
//! 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::ast::{
|
||||
ASTFlags, BinaryExpr, Expr, Ident, OpAssignment, Stmt, SwitchCases, TryCatchBlock,
|
||||
@ -25,7 +25,7 @@ impl Engine {
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
statements: &[Stmt],
|
||||
@ -36,14 +36,14 @@ impl Engine {
|
||||
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();
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
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 {
|
||||
state.scope_level += 1;
|
||||
global.scope_level += 1;
|
||||
}
|
||||
|
||||
let mut result = Ok(Dynamic::UNIT);
|
||||
@ -55,7 +55,7 @@ impl Engine {
|
||||
result = self.eval_stmt(
|
||||
scope,
|
||||
global,
|
||||
state,
|
||||
caches,
|
||||
lib,
|
||||
this_ptr,
|
||||
stmt,
|
||||
@ -76,48 +76,46 @@ impl Engine {
|
||||
.skip(imports_len)
|
||||
.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
|
||||
// a new cache, clear it - notice that this is expensive as all function
|
||||
// resolutions must start again
|
||||
state.fn_resolution_cache_mut().clear();
|
||||
caches.fn_resolution_cache_mut().clear();
|
||||
} else if restore_orig_state {
|
||||
// When new module is imported with global functions, push a new cache
|
||||
state.push_fn_resolution_cache();
|
||||
caches.push_fn_resolution_cache();
|
||||
} else {
|
||||
// When the block is to be evaluated in-place, just clear the current cache
|
||||
state.fn_resolution_cache_mut().clear();
|
||||
caches.fn_resolution_cache_mut().clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If imports list is modified, pop the functions lookup cache
|
||||
state.rewind_fn_resolution_caches(orig_fn_resolution_caches_len);
|
||||
caches.rewind_fn_resolution_caches(orig_fn_resolution_caches_len);
|
||||
|
||||
if restore_orig_state {
|
||||
scope.rewind(orig_scope_len);
|
||||
state.scope_level -= 1;
|
||||
global.scope_level -= 1;
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
global.truncate_imports(orig_imports_len);
|
||||
|
||||
// The impact of new local variables goes away at the end of a block
|
||||
// because any new variables introduced will go out of scope
|
||||
state.always_search_scope = orig_always_search_scope;
|
||||
global.always_search_scope = orig_always_search_scope;
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Evaluate an op-assignment statement.
|
||||
/// [`Position`] in [`EvalAltResult`] is [`NONE`][Position::NONE] and should be set afterwards.
|
||||
pub(crate) fn eval_op_assignment(
|
||||
&self,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
op_info: Option<OpAssignment>,
|
||||
op_pos: Position,
|
||||
op_info: OpAssignment,
|
||||
target: &mut Target,
|
||||
root: (&str, Position),
|
||||
new_val: Dynamic,
|
||||
@ -130,13 +128,15 @@ impl Engine {
|
||||
|
||||
let mut new_val = new_val;
|
||||
|
||||
if let Some(OpAssignment {
|
||||
hash_op_assign,
|
||||
hash_op,
|
||||
op_assign,
|
||||
op,
|
||||
}) = op_info
|
||||
{
|
||||
if op_info.is_op_assignment() {
|
||||
let OpAssignment {
|
||||
hash_op_assign,
|
||||
hash_op,
|
||||
op_assign,
|
||||
op,
|
||||
pos: op_pos,
|
||||
} = op_info;
|
||||
|
||||
let mut lock_guard;
|
||||
let lhs_ptr_inner;
|
||||
|
||||
@ -157,7 +157,7 @@ impl Engine {
|
||||
let level = level + 1;
|
||||
|
||||
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(_) => {
|
||||
#[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)) =>
|
||||
{
|
||||
// Expand to `var = var op rhs`
|
||||
let (value, ..) = self.call_native_fn(
|
||||
global, state, lib, op, hash_op, args, true, false, op_pos, level,
|
||||
)?;
|
||||
let (value, ..) = self
|
||||
.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"))]
|
||||
self.check_data_size(&value, root.1)?;
|
||||
@ -182,7 +184,9 @@ impl Engine {
|
||||
*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.
|
||||
@ -197,7 +201,7 @@ impl Engine {
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
stmt: &Stmt,
|
||||
@ -206,7 +210,7 @@ impl Engine {
|
||||
) -> RhaiResult {
|
||||
#[cfg(feature = "debugging")]
|
||||
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.
|
||||
// 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())?;
|
||||
|
||||
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")]
|
||||
global.debugger.reset_status(reset_debugger);
|
||||
@ -228,7 +232,7 @@ impl Engine {
|
||||
// Then assignments.
|
||||
// We shouldn't do this for too many variants because, soon or later, the added comparisons
|
||||
// will cost more than the mis-predicted `match` branch.
|
||||
if let Stmt::Assignment(x, op_pos) = stmt {
|
||||
if let Stmt::Assignment(x, ..) = stmt {
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
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 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);
|
||||
|
||||
if let Ok(rhs_val) = rhs_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 {
|
||||
let (mut lhs_ptr, pos) = search_val;
|
||||
@ -261,9 +265,8 @@ impl Engine {
|
||||
let lhs_ptr = &mut lhs_ptr;
|
||||
|
||||
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)
|
||||
} else {
|
||||
search_result.map(|_| Dynamic::UNIT)
|
||||
@ -275,11 +278,11 @@ impl Engine {
|
||||
let (op_info, BinaryExpr { lhs, rhs }) = x.as_ref();
|
||||
|
||||
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);
|
||||
|
||||
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`
|
||||
match lhs {
|
||||
@ -291,14 +294,14 @@ impl Engine {
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Expr::Index(..) => self
|
||||
.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),
|
||||
// dot_lhs.dot_rhs op= rhs
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Expr::Dot(..) => self
|
||||
.eval_dot_index_chain(
|
||||
scope, global, state, lib, this_ptr, lhs, level, _new_val,
|
||||
scope, global, caches, lib, this_ptr, lhs, level, _new_val,
|
||||
)
|
||||
.map(|_| Dynamic::UNIT),
|
||||
_ => unreachable!("cannot assign to expression: {:?}", lhs),
|
||||
@ -323,21 +326,21 @@ impl Engine {
|
||||
|
||||
// Expression as statement
|
||||
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),
|
||||
|
||||
// Block scope
|
||||
Stmt::Block(statements, ..) if statements.is_empty() => Ok(Dynamic::UNIT),
|
||||
Stmt::Block(statements, ..) => {
|
||||
self.eval_stmt_block(scope, global, state, lib, this_ptr, statements, true, level)
|
||||
}
|
||||
Stmt::Block(statements, ..) => self.eval_stmt_block(
|
||||
scope, global, caches, lib, this_ptr, statements, true, level,
|
||||
),
|
||||
|
||||
// If statement
|
||||
Stmt::If(x, ..) => {
|
||||
let (expr, if_block, else_block) = x.as_ref();
|
||||
|
||||
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| {
|
||||
v.as_bool().map_err(|typ| {
|
||||
self.make_type_mismatch_err::<bool>(typ, expr.position())
|
||||
@ -348,7 +351,7 @@ impl Engine {
|
||||
Ok(true) => {
|
||||
if !if_block.is_empty() {
|
||||
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 {
|
||||
Ok(Dynamic::UNIT)
|
||||
@ -357,7 +360,7 @@ impl Engine {
|
||||
Ok(false) => {
|
||||
if !else_block.is_empty() {
|
||||
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 {
|
||||
Ok(Dynamic::UNIT)
|
||||
@ -378,7 +381,8 @@ impl Engine {
|
||||
},
|
||||
) = 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 {
|
||||
let stmt_block_result = if value.is_hashable() {
|
||||
@ -388,21 +392,16 @@ impl Engine {
|
||||
|
||||
// First check hashes
|
||||
if let Some(case_block) = cases.get(&hash) {
|
||||
let cond_result = case_block
|
||||
.condition
|
||||
.as_ref()
|
||||
.map(|cond| {
|
||||
self.eval_expr(scope, global, state, lib, this_ptr, cond, level)
|
||||
.and_then(|v| {
|
||||
v.as_bool().map_err(|typ| {
|
||||
self.make_type_mismatch_err::<bool>(
|
||||
typ,
|
||||
cond.position(),
|
||||
)
|
||||
})
|
||||
let cond_result = match case_block.condition {
|
||||
Expr::BoolConstant(b, ..) => Ok(b),
|
||||
ref c => self
|
||||
.eval_expr(scope, global, caches, lib, this_ptr, c, level)
|
||||
.and_then(|v| {
|
||||
v.as_bool().map_err(|typ| {
|
||||
self.make_type_mismatch_err::<bool>(typ, c.position())
|
||||
})
|
||||
})
|
||||
.unwrap_or(Ok(true));
|
||||
}),
|
||||
};
|
||||
|
||||
match cond_result {
|
||||
Ok(true) => Ok(Some(&case_block.statements)),
|
||||
@ -420,23 +419,19 @@ impl Engine {
|
||||
|| (inclusive && (start..=end).contains(&value))
|
||||
})
|
||||
{
|
||||
let cond_result = block
|
||||
.condition
|
||||
.as_ref()
|
||||
.map(|cond| {
|
||||
self.eval_expr(
|
||||
scope, global, state, lib, this_ptr, cond, level,
|
||||
)
|
||||
let cond_result = match block.condition {
|
||||
Expr::BoolConstant(b, ..) => Ok(b),
|
||||
ref c => self
|
||||
.eval_expr(scope, global, caches, lib, this_ptr, c, level)
|
||||
.and_then(|v| {
|
||||
v.as_bool().map_err(|typ| {
|
||||
self.make_type_mismatch_err::<bool>(
|
||||
typ,
|
||||
cond.position(),
|
||||
c.position(),
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
.unwrap_or(Ok(true));
|
||||
}),
|
||||
};
|
||||
|
||||
match cond_result {
|
||||
Ok(true) => result = Ok(Some(&block.statements)),
|
||||
@ -460,7 +455,7 @@ impl Engine {
|
||||
if let Ok(Some(statements)) = stmt_block_result {
|
||||
if !statements.is_empty() {
|
||||
self.eval_stmt_block(
|
||||
scope, global, state, lib, this_ptr, statements, true, level,
|
||||
scope, global, caches, lib, this_ptr, statements, true, level,
|
||||
)
|
||||
} else {
|
||||
Ok(Dynamic::UNIT)
|
||||
@ -469,7 +464,7 @@ impl Engine {
|
||||
// Default match clause
|
||||
if !def_case.is_empty() {
|
||||
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 {
|
||||
Ok(Dynamic::UNIT)
|
||||
@ -488,7 +483,7 @@ impl Engine {
|
||||
|
||||
if !body.is_empty() {
|
||||
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(_) => (),
|
||||
Err(err) => match *err {
|
||||
@ -508,7 +503,7 @@ impl Engine {
|
||||
let (expr, body) = x.as_ref();
|
||||
|
||||
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| {
|
||||
v.as_bool().map_err(|typ| {
|
||||
self.make_type_mismatch_err::<bool>(typ, expr.position())
|
||||
@ -519,9 +514,9 @@ impl Engine {
|
||||
Ok(false) => break Ok(Dynamic::UNIT),
|
||||
Ok(true) if body.is_empty() => (),
|
||||
Ok(true) => {
|
||||
match self
|
||||
.eval_stmt_block(scope, global, state, lib, this_ptr, body, true, level)
|
||||
{
|
||||
match self.eval_stmt_block(
|
||||
scope, global, caches, lib, this_ptr, body, true, level,
|
||||
) {
|
||||
Ok(_) => (),
|
||||
Err(err) => match *err {
|
||||
ERR::LoopBreak(false, ..) => (),
|
||||
@ -541,7 +536,7 @@ impl Engine {
|
||||
|
||||
if !body.is_empty() {
|
||||
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(_) => (),
|
||||
Err(err) => match *err {
|
||||
@ -553,7 +548,7 @@ impl Engine {
|
||||
}
|
||||
|
||||
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| {
|
||||
v.as_bool().map_err(|typ| {
|
||||
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 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);
|
||||
|
||||
if let Ok(iter_obj) = iter_result {
|
||||
@ -671,7 +666,7 @@ impl Engine {
|
||||
}
|
||||
|
||||
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 {
|
||||
@ -715,7 +710,7 @@ impl Engine {
|
||||
} = x.as_ref();
|
||||
|
||||
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);
|
||||
|
||||
match result {
|
||||
@ -767,7 +762,7 @@ impl Engine {
|
||||
let result = self.eval_stmt_block(
|
||||
scope,
|
||||
global,
|
||||
state,
|
||||
caches,
|
||||
lib,
|
||||
this_ptr,
|
||||
catch_block,
|
||||
@ -794,7 +789,7 @@ impl Engine {
|
||||
|
||||
// Throw value
|
||||
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())),
|
||||
|
||||
// Empty throw
|
||||
@ -804,7 +799,7 @@ impl Engine {
|
||||
|
||||
// Return value
|
||||
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())),
|
||||
|
||||
// Empty return
|
||||
@ -828,7 +823,7 @@ impl Engine {
|
||||
// Check variable definition filter
|
||||
let result = if let Some(ref filter) = self.def_var_filter {
|
||||
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 info = VarDefInfo {
|
||||
name: var_name,
|
||||
@ -840,7 +835,7 @@ impl Engine {
|
||||
engine: self,
|
||||
scope,
|
||||
global,
|
||||
state,
|
||||
caches: None,
|
||||
lib,
|
||||
this_ptr,
|
||||
level,
|
||||
@ -864,7 +859,7 @@ impl Engine {
|
||||
} else {
|
||||
// Evaluate initial value
|
||||
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);
|
||||
|
||||
if let Ok(mut value) = value_result {
|
||||
@ -872,7 +867,7 @@ impl Engine {
|
||||
// Put global constants into global module
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
if state.scope_level == 0
|
||||
if global.scope_level == 0
|
||||
&& access == AccessMode::ReadOnly
|
||||
&& lib.iter().any(|&m| !m.is_empty())
|
||||
{
|
||||
@ -927,7 +922,7 @@ impl Engine {
|
||||
}
|
||||
|
||||
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| {
|
||||
let typ = v.type_name();
|
||||
v.try_cast::<crate::ImmutableString>().ok_or_else(|| {
|
||||
|
@ -272,6 +272,8 @@ impl<'a> Target<'a> {
|
||||
}
|
||||
/// Propagate a changed value back to the original source.
|
||||
/// This has no effect for direct references.
|
||||
///
|
||||
/// [`Position`] in [`EvalAltResult`] is [`NONE`][Position::NONE] and should be set afterwards.
|
||||
#[inline]
|
||||
pub fn propagate_changed_value(&mut self) -> RhaiResultOf<()> {
|
||||
match self {
|
||||
|
119
src/func/call.rs
119
src/func/call.rs
@ -9,7 +9,7 @@ use crate::engine::{
|
||||
KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, KEYWORD_FN_PTR_CALL, KEYWORD_FN_PTR_CURRY,
|
||||
KEYWORD_IS_DEF_VAR, KEYWORD_PRINT, KEYWORD_TYPE_OF,
|
||||
};
|
||||
use crate::eval::{EvalState, GlobalRuntimeState};
|
||||
use crate::eval::{Caches, FnResolutionCacheEntry, GlobalRuntimeState};
|
||||
use crate::{
|
||||
calc_fn_hash, calc_fn_params_hash, combine_hashes, Dynamic, Engine, FnArgsVec, FnPtr,
|
||||
Identifier, ImmutableString, Module, OptimizationLevel, Position, RhaiError, RhaiResult,
|
||||
@ -19,7 +19,6 @@ use crate::{
|
||||
use std::prelude::v1::*;
|
||||
use std::{
|
||||
any::{type_name, TypeId},
|
||||
collections::BTreeMap,
|
||||
convert::TryFrom,
|
||||
mem,
|
||||
};
|
||||
@ -128,24 +127,6 @@ pub fn ensure_no_data_race(
|
||||
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 {
|
||||
/// Generate the signature for a function call.
|
||||
#[inline]
|
||||
@ -196,7 +177,7 @@ impl Engine {
|
||||
fn resolve_fn<'s>(
|
||||
&self,
|
||||
_global: &GlobalRuntimeState,
|
||||
state: &'s mut EvalState,
|
||||
state: &'s mut Caches,
|
||||
lib: &[&Module],
|
||||
fn_name: &str,
|
||||
hash_script: u64,
|
||||
@ -344,7 +325,7 @@ impl Engine {
|
||||
pub(crate) fn call_native_fn(
|
||||
&self,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
name: &str,
|
||||
hash: u64,
|
||||
@ -362,7 +343,7 @@ impl Engine {
|
||||
// Check if function access already in the cache
|
||||
let func = self.resolve_fn(
|
||||
global,
|
||||
state,
|
||||
caches,
|
||||
lib,
|
||||
name,
|
||||
hash,
|
||||
@ -438,9 +419,7 @@ impl Engine {
|
||||
Ok(ref r) => crate::eval::DebuggerEvent::FunctionExitWithValue(r),
|
||||
Err(ref err) => crate::eval::DebuggerEvent::FunctionExitWithError(err),
|
||||
};
|
||||
match self
|
||||
.run_debugger_raw(scope, global, state, lib, &mut None, node, event, level)
|
||||
{
|
||||
match self.run_debugger_raw(scope, global, lib, &mut None, node, event, level) {
|
||||
Ok(_) => (),
|
||||
Err(err) => _result = Err(err),
|
||||
}
|
||||
@ -576,7 +555,7 @@ impl Engine {
|
||||
&self,
|
||||
_scope: Option<&mut Scope>,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
fn_name: &str,
|
||||
hashes: FnCallHashes,
|
||||
@ -619,7 +598,7 @@ impl Engine {
|
||||
false
|
||||
} else {
|
||||
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(),
|
||||
false,
|
||||
@ -650,7 +629,7 @@ impl Engine {
|
||||
if let Some(FnResolutionCacheEntry { func, mut source }) = self
|
||||
.resolve_fn(
|
||||
global,
|
||||
state,
|
||||
caches,
|
||||
lib,
|
||||
fn_name,
|
||||
hashes.script,
|
||||
@ -687,7 +666,7 @@ impl Engine {
|
||||
self.call_script_fn(
|
||||
scope,
|
||||
global,
|
||||
state,
|
||||
caches,
|
||||
lib,
|
||||
&mut Some(*first_arg),
|
||||
func,
|
||||
@ -706,7 +685,7 @@ impl Engine {
|
||||
}
|
||||
|
||||
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
|
||||
@ -724,7 +703,7 @@ impl Engine {
|
||||
// Native function call
|
||||
let hash = hashes.native;
|
||||
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,
|
||||
scope: &mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
statements: &[Stmt],
|
||||
lib: &[&Module],
|
||||
level: usize,
|
||||
) -> RhaiResult {
|
||||
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 {
|
||||
ERR::Return(out, ..) => Ok(out),
|
||||
@ -757,7 +736,7 @@ impl Engine {
|
||||
pub(crate) fn make_method_call(
|
||||
&self,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
fn_name: &str,
|
||||
mut hash: FnCallHashes,
|
||||
@ -786,7 +765,7 @@ impl Engine {
|
||||
|
||||
// Map it to name(args) in function-call style
|
||||
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,
|
||||
)
|
||||
}
|
||||
@ -822,7 +801,7 @@ impl Engine {
|
||||
|
||||
// Map it to name(args) in function-call style
|
||||
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,
|
||||
)
|
||||
}
|
||||
@ -892,7 +871,7 @@ impl Engine {
|
||||
args.extend(call_args.iter_mut());
|
||||
|
||||
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,
|
||||
)
|
||||
}
|
||||
@ -914,7 +893,7 @@ impl Engine {
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
arg_expr: &Expr,
|
||||
@ -924,7 +903,7 @@ impl Engine {
|
||||
if self.debugger.is_some() {
|
||||
if let Some(value) = arg_expr.get_literal_value() {
|
||||
#[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()));
|
||||
}
|
||||
}
|
||||
@ -935,7 +914,7 @@ impl Engine {
|
||||
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
|
||||
#[cfg(feature = "debugging")]
|
||||
@ -949,7 +928,7 @@ impl Engine {
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
fn_name: &str,
|
||||
@ -973,7 +952,7 @@ impl Engine {
|
||||
KEYWORD_FN_PTR_CALL if total_args >= 1 => {
|
||||
let arg = first_arg.unwrap();
|
||||
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>() {
|
||||
let typ = self.map_type_name(arg_value.type_name());
|
||||
@ -1006,7 +985,7 @@ impl Engine {
|
||||
KEYWORD_FN_PTR if total_args == 1 => {
|
||||
let arg = first_arg.unwrap();
|
||||
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
|
||||
return arg_value
|
||||
@ -1021,7 +1000,7 @@ impl Engine {
|
||||
KEYWORD_FN_PTR_CURRY if total_args > 1 => {
|
||||
let first = first_arg.unwrap();
|
||||
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>() {
|
||||
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.
|
||||
let fn_curry = a_expr.iter().try_fold(fn_curry, |mut curried, expr| {
|
||||
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);
|
||||
Ok::<_, RhaiError>(curried)
|
||||
})?;
|
||||
@ -1046,7 +1025,7 @@ impl Engine {
|
||||
crate::engine::KEYWORD_IS_SHARED if total_args == 1 => {
|
||||
let arg = first_arg.unwrap();
|
||||
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());
|
||||
}
|
||||
|
||||
@ -1055,14 +1034,14 @@ impl Engine {
|
||||
crate::engine::KEYWORD_IS_DEF_FN if total_args == 2 => {
|
||||
let first = first_arg.unwrap();
|
||||
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
|
||||
.into_immutable_string()
|
||||
.map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, 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
|
||||
.as_int()
|
||||
@ -1072,7 +1051,7 @@ impl Engine {
|
||||
false
|
||||
} else {
|
||||
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());
|
||||
}
|
||||
@ -1081,7 +1060,7 @@ impl Engine {
|
||||
KEYWORD_IS_DEF_VAR if total_args == 1 => {
|
||||
let arg = first_arg.unwrap();
|
||||
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
|
||||
.into_immutable_string()
|
||||
.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 arg = first_arg.unwrap();
|
||||
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
|
||||
.into_immutable_string()
|
||||
.map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, pos))?;
|
||||
let result = self.eval_script_expr_in_place(
|
||||
scope,
|
||||
global,
|
||||
state,
|
||||
caches,
|
||||
lib,
|
||||
script,
|
||||
pos,
|
||||
@ -1111,7 +1090,7 @@ impl Engine {
|
||||
// IMPORTANT! If the eval defines new variables in the current scope,
|
||||
// all variable offsets from this point on will be mis-aligned.
|
||||
if scope.len() != orig_scope_len {
|
||||
state.always_search_scope = true;
|
||||
global.always_search_scope = true;
|
||||
}
|
||||
|
||||
return result.map_err(|err| {
|
||||
@ -1143,7 +1122,7 @@ impl Engine {
|
||||
.map(|&v| v)
|
||||
.chain(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()))
|
||||
})?;
|
||||
args.extend(curry.iter_mut());
|
||||
@ -1154,7 +1133,7 @@ impl Engine {
|
||||
|
||||
return self
|
||||
.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,
|
||||
)
|
||||
.map(|(v, ..)| v);
|
||||
@ -1171,16 +1150,16 @@ impl Engine {
|
||||
let first_expr = first_arg.unwrap();
|
||||
|
||||
#[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(...)
|
||||
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()))
|
||||
})?;
|
||||
|
||||
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() {
|
||||
target = target.into_owned();
|
||||
@ -1210,7 +1189,7 @@ impl Engine {
|
||||
.into_iter()
|
||||
.chain(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()))
|
||||
})?;
|
||||
args.extend(curry.iter_mut());
|
||||
@ -1219,7 +1198,7 @@ impl Engine {
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@ -1230,7 +1209,7 @@ impl Engine {
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
namespace: &crate::ast::Namespace,
|
||||
@ -1252,20 +1231,20 @@ impl Engine {
|
||||
// and avoid cloning the value
|
||||
if !args_expr.is_empty() && args_expr[0].is_variable_access(true) {
|
||||
#[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(...)
|
||||
arg_values.push(Dynamic::UNIT);
|
||||
|
||||
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()))
|
||||
})?;
|
||||
|
||||
// Get target reference to first argument
|
||||
let first_arg = &args_expr[0];
|
||||
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"))]
|
||||
self.inc_operations(&mut global.num_operations, _pos)?;
|
||||
@ -1289,7 +1268,7 @@ impl Engine {
|
||||
} else {
|
||||
// func(..., ...) or func(mod::x, ...)
|
||||
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()))
|
||||
})?;
|
||||
args.extend(arg_values.iter_mut());
|
||||
@ -1298,7 +1277,7 @@ impl Engine {
|
||||
|
||||
// Search for the root namespace
|
||||
let module = self
|
||||
.search_imports(global, state, namespace)
|
||||
.search_imports(global, namespace)
|
||||
.ok_or_else(|| ERR::ErrorModuleNotFound(namespace.to_string(), namespace.position()))?;
|
||||
|
||||
// First search script-defined functions in namespace (can override built-in)
|
||||
@ -1370,7 +1349,7 @@ impl Engine {
|
||||
mem::swap(&mut global.source, &mut source);
|
||||
|
||||
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;
|
||||
@ -1410,7 +1389,7 @@ impl Engine {
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
script: &str,
|
||||
_pos: Position,
|
||||
@ -1448,6 +1427,6 @@ impl Engine {
|
||||
}
|
||||
|
||||
// Evaluate the AST
|
||||
self.eval_global_statements(scope, global, state, statements, lib, level)
|
||||
self.eval_global_statements(scope, global, caches, statements, lib, level)
|
||||
}
|
||||
}
|
||||
|
@ -3,7 +3,7 @@
|
||||
use super::call::FnCallArgs;
|
||||
use crate::api::events::VarDefInfo;
|
||||
use crate::ast::FnCallHashes;
|
||||
use crate::eval::{EvalState, GlobalRuntimeState};
|
||||
use crate::eval::{Caches, GlobalRuntimeState};
|
||||
use crate::plugin::PluginFunction;
|
||||
use crate::tokenizer::{Token, TokenizeState};
|
||||
use crate::types::dynamic::Variant;
|
||||
@ -311,7 +311,7 @@ impl<'a> NativeCallContext<'a> {
|
||||
.global
|
||||
.cloned()
|
||||
.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 args_len = args.len();
|
||||
@ -330,7 +330,7 @@ impl<'a> NativeCallContext<'a> {
|
||||
.exec_fn_call(
|
||||
None,
|
||||
&mut global,
|
||||
&mut state,
|
||||
&mut caches,
|
||||
self.lib,
|
||||
fn_name,
|
||||
hash,
|
||||
|
@ -5,9 +5,8 @@
|
||||
use super::call::FnCallArgs;
|
||||
use super::callable_function::CallableFunction;
|
||||
use super::native::{FnAny, SendSync};
|
||||
use crate::tokenizer::Position;
|
||||
use crate::types::dynamic::{DynamicWriteLock, Variant};
|
||||
use crate::{reify, Dynamic, NativeCallContext, RhaiResultOf, ERR};
|
||||
use crate::{reify, Dynamic, NativeCallContext, RhaiResultOf};
|
||||
#[cfg(feature = "no_std")]
|
||||
use std::prelude::v1::*;
|
||||
use std::{any::TypeId, mem};
|
||||
@ -102,9 +101,11 @@ macro_rules! check_constant {
|
||||
_ => false,
|
||||
};
|
||||
if deny {
|
||||
return Err(
|
||||
ERR::ErrorAssignmentToConstant(String::new(), Position::NONE).into(),
|
||||
);
|
||||
return Err(crate::ERR::ErrorAssignmentToConstant(
|
||||
String::new(),
|
||||
crate::Position::NONE,
|
||||
)
|
||||
.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -3,7 +3,7 @@
|
||||
|
||||
use super::call::FnCallArgs;
|
||||
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 std::mem;
|
||||
#[cfg(feature = "no_std")]
|
||||
@ -26,7 +26,7 @@ impl Engine {
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
global: &mut GlobalRuntimeState,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
fn_def: &ScriptFnDef,
|
||||
@ -109,7 +109,7 @@ impl Engine {
|
||||
}
|
||||
|
||||
// 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"))]
|
||||
let mut lib_merged = crate::StaticVec::with_capacity(lib.len() + 1);
|
||||
@ -128,7 +128,7 @@ impl Engine {
|
||||
if fn_lib.is_empty() {
|
||||
lib
|
||||
} else {
|
||||
state.push_fn_resolution_cache();
|
||||
caches.push_fn_resolution_cache();
|
||||
lib_merged.push(fn_lib.as_ref());
|
||||
lib_merged.extend(lib.iter().cloned());
|
||||
&lib_merged
|
||||
@ -142,7 +142,7 @@ impl Engine {
|
||||
#[cfg(feature = "debugging")]
|
||||
{
|
||||
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
|
||||
@ -150,7 +150,7 @@ impl Engine {
|
||||
.eval_stmt_block(
|
||||
scope,
|
||||
global,
|
||||
state,
|
||||
caches,
|
||||
lib,
|
||||
this_ptr,
|
||||
&fn_def.body,
|
||||
@ -193,8 +193,7 @@ impl Engine {
|
||||
Ok(ref r) => crate::eval::DebuggerEvent::FunctionExitWithValue(r),
|
||||
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(_) => (),
|
||||
Err(err) => _result = Err(err),
|
||||
}
|
||||
@ -221,7 +220,7 @@ impl Engine {
|
||||
}
|
||||
|
||||
// Restore state
|
||||
state.rewind_fn_resolution_caches(orig_fn_resolution_caches_len);
|
||||
caches.rewind_fn_resolution_caches(orig_fn_resolution_caches_len);
|
||||
|
||||
_result
|
||||
}
|
||||
@ -231,11 +230,11 @@ impl Engine {
|
||||
pub(crate) fn has_script_fn(
|
||||
&self,
|
||||
_global: Option<&GlobalRuntimeState>,
|
||||
state: &mut EvalState,
|
||||
caches: &mut Caches,
|
||||
lib: &[&Module],
|
||||
hash_script: u64,
|
||||
) -> 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()) {
|
||||
return result;
|
||||
|
@ -237,6 +237,9 @@ pub type Blob = Vec<u8>;
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
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"))]
|
||||
pub use module::ModuleResolver;
|
||||
|
||||
@ -294,10 +297,7 @@ pub use ast::EncapsulatedEnviron;
|
||||
pub use ast::FloatWrapper;
|
||||
|
||||
#[cfg(feature = "internals")]
|
||||
pub use eval::{EvalState, GlobalRuntimeState};
|
||||
|
||||
#[cfg(feature = "internals")]
|
||||
pub use func::call::{FnResolutionCache, FnResolutionCacheEntry};
|
||||
pub use eval::{Caches, FnResolutionCache, FnResolutionCacheEntry, GlobalRuntimeState};
|
||||
|
||||
/// 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.
|
||||
|
@ -1742,9 +1742,12 @@ impl Module {
|
||||
|
||||
/// Create a new [`Module`] by evaluating an [`AST`][crate::AST].
|
||||
///
|
||||
/// The entire [`AST`][crate::AST] is encapsulated into each function, allowing functions
|
||||
/// to cross-call each other. Functions in the global namespace, plus all functions
|
||||
/// defined in the [`Module`], are _merged_ into a _unified_ namespace before each call.
|
||||
/// The entire [`AST`][crate::AST] is encapsulated into each function, allowing functions to
|
||||
/// cross-call each other.
|
||||
///
|
||||
/// 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.
|
||||
///
|
||||
/// # Example
|
||||
@ -1781,8 +1784,15 @@ impl Module {
|
||||
/// _merged_ into a _unified_ namespace before each call.
|
||||
///
|
||||
/// 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"))]
|
||||
pub(crate) fn eval_ast_as_new_raw(
|
||||
pub fn eval_ast_as_new_raw(
|
||||
engine: &crate::Engine,
|
||||
scope: crate::Scope,
|
||||
global: &mut crate::eval::GlobalRuntimeState,
|
||||
|
@ -201,17 +201,15 @@ impl FileModuleResolver {
|
||||
/// Is a particular path cached?
|
||||
#[inline]
|
||||
#[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 {
|
||||
return false;
|
||||
}
|
||||
|
||||
let file_path = self.get_file_path(path.as_ref(), source_path);
|
||||
|
||||
let cache = locked_read(&self.cache);
|
||||
|
||||
if !cache.is_empty() {
|
||||
cache.contains_key(&file_path)
|
||||
cache.contains_key(path.as_ref())
|
||||
} else {
|
||||
false
|
||||
}
|
||||
@ -227,20 +225,14 @@ impl FileModuleResolver {
|
||||
/// The next time this path is resolved, the script file will be loaded once again.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn clear_cache_for_path(
|
||||
&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));
|
||||
|
||||
pub fn clear_cache_for_path(&mut self, path: impl AsRef<Path>) -> Option<Shared<Module>> {
|
||||
locked_write(&self.cache)
|
||||
.remove_entry(&file_path)
|
||||
.remove_entry(path.as_ref())
|
||||
.map(|(.., v)| v)
|
||||
}
|
||||
/// Construct a full file path.
|
||||
#[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 mut file_path;
|
||||
@ -274,9 +266,9 @@ impl FileModuleResolver {
|
||||
.as_ref()
|
||||
.and_then(|g| g.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() {
|
||||
#[cfg(not(feature = "sync"))]
|
||||
@ -351,7 +343,7 @@ impl ModuleResolver for FileModuleResolver {
|
||||
pos: Position,
|
||||
) -> Option<RhaiResultOf<crate::AST>> {
|
||||
// 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
|
||||
Some(
|
||||
|
167
src/optimizer.rs
167
src/optimizer.rs
@ -3,7 +3,7 @@
|
||||
|
||||
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::eval::{EvalState, GlobalRuntimeState};
|
||||
use crate::eval::{Caches, GlobalRuntimeState};
|
||||
use crate::func::builtin::get_builtin_binary_op_fn;
|
||||
use crate::func::hashing::get_hasher;
|
||||
use crate::tokenizer::{Span, Token};
|
||||
@ -139,7 +139,7 @@ impl<'a> OptimizerState<'a> {
|
||||
self.engine
|
||||
.call_native_fn(
|
||||
&mut GlobalRuntimeState::new(&self.engine),
|
||||
&mut EvalState::new(),
|
||||
&mut Caches::new(),
|
||||
lib,
|
||||
fn_name,
|
||||
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 {
|
||||
// var = var op expr => var op= expr
|
||||
Stmt::Assignment(x, ..)
|
||||
if x.0.is_none()
|
||||
if !x.0.is_op_assignment()
|
||||
&& x.1.lhs.is_variable_access(true)
|
||||
&& matches!(&x.1.rhs, Expr::FnCall(x2, ..)
|
||||
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 {
|
||||
Expr::FnCall(ref mut x2, ..) => {
|
||||
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]);
|
||||
}
|
||||
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
|
||||
if let Some(block) = cases.get_mut(&hash) {
|
||||
if let Some(mut condition) = mem::take(&mut block.condition) {
|
||||
// switch const { case if condition => stmt, _ => def } => if condition { stmt } else { def }
|
||||
optimize_expr(&mut condition, state, false);
|
||||
|
||||
let def_stmt =
|
||||
optimize_stmt_block(mem::take(def_case), state, true, true, false);
|
||||
|
||||
*stmt = Stmt::If(
|
||||
(
|
||||
condition,
|
||||
match mem::take(&mut block.condition) {
|
||||
Expr::BoolConstant(true, ..) => {
|
||||
// Promote the matched case
|
||||
let statements = optimize_stmt_block(
|
||||
mem::take(&mut block.statements),
|
||||
StmtBlock::new_with_span(
|
||||
def_stmt,
|
||||
def_case.span_or_else(*pos, Position::NONE),
|
||||
),
|
||||
)
|
||||
.into(),
|
||||
match_expr.start_position(),
|
||||
);
|
||||
} else {
|
||||
// Promote the matched case
|
||||
let statements = optimize_stmt_block(
|
||||
mem::take(&mut block.statements),
|
||||
state,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
);
|
||||
*stmt = (statements, block.statements.span()).into();
|
||||
state,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
);
|
||||
*stmt = (statements, block.statements.span()).into();
|
||||
}
|
||||
mut condition => {
|
||||
// switch const { case if condition => stmt, _ => def } => if condition { stmt } else { def }
|
||||
optimize_expr(&mut condition, state, false);
|
||||
|
||||
let def_stmt =
|
||||
optimize_stmt_block(mem::take(def_case), state, true, true, false);
|
||||
|
||||
*stmt = Stmt::If(
|
||||
(
|
||||
condition,
|
||||
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();
|
||||
@ -571,7 +574,11 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
|
||||
let value = value.as_int().expect("`INT`");
|
||||
|
||||
// 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
|
||||
ranges
|
||||
.iter_mut()
|
||||
@ -580,30 +587,38 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
|
||||
|| (inclusive && (start..=end).contains(&value))
|
||||
})
|
||||
{
|
||||
if let Some(mut condition) = mem::take(&mut block.condition) {
|
||||
// switch const { range if condition => stmt, _ => def } => if condition { stmt } else { def }
|
||||
optimize_expr(&mut condition, state, false);
|
||||
match mem::take(&mut block.condition) {
|
||||
Expr::BoolConstant(true, ..) => {
|
||||
// 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 =
|
||||
optimize_stmt_block(mem::take(def_case), state, true, true, false);
|
||||
*stmt = Stmt::If(
|
||||
(
|
||||
condition,
|
||||
mem::take(&mut block.statements),
|
||||
StmtBlock::new_with_span(
|
||||
def_stmt,
|
||||
def_case.span_or_else(*pos, Position::NONE),
|
||||
),
|
||||
)
|
||||
.into(),
|
||||
match_expr.start_position(),
|
||||
);
|
||||
} else {
|
||||
// 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();
|
||||
let def_stmt = optimize_stmt_block(
|
||||
mem::take(def_case),
|
||||
state,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
);
|
||||
*stmt = Stmt::If(
|
||||
(
|
||||
condition,
|
||||
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();
|
||||
@ -632,12 +647,14 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
|
||||
*block.statements =
|
||||
optimize_stmt_block(statements, state, preserve_result, true, false);
|
||||
|
||||
if let Some(mut condition) = mem::take(&mut block.condition) {
|
||||
optimize_expr(&mut condition, state, false);
|
||||
match condition {
|
||||
Expr::Unit(..) | Expr::BoolConstant(true, ..) => state.set_dirty(),
|
||||
_ => block.condition = Some(condition),
|
||||
optimize_expr(&mut block.condition, state, false);
|
||||
|
||||
match block.condition {
|
||||
Expr::Unit(pos) => {
|
||||
block.condition = Expr::BoolConstant(true, pos);
|
||||
state.set_dirty()
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
return;
|
||||
@ -669,18 +686,20 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
|
||||
*block.statements =
|
||||
optimize_stmt_block(statements, state, preserve_result, true, false);
|
||||
|
||||
if let Some(mut condition) = mem::take(&mut block.condition) {
|
||||
optimize_expr(&mut condition, state, false);
|
||||
match condition {
|
||||
Expr::Unit(..) | Expr::BoolConstant(true, ..) => state.set_dirty(),
|
||||
_ => block.condition = Some(condition),
|
||||
optimize_expr(&mut block.condition, state, false);
|
||||
|
||||
match block.condition {
|
||||
Expr::Unit(pos) => {
|
||||
block.condition = Expr::BoolConstant(true, pos);
|
||||
state.set_dirty();
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
// Remove false cases
|
||||
cases.retain(|_, block| match block.condition {
|
||||
Some(Expr::BoolConstant(false, ..)) => {
|
||||
Expr::BoolConstant(false, ..) => {
|
||||
state.set_dirty();
|
||||
false
|
||||
}
|
||||
@ -693,18 +712,20 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
|
||||
*block.statements =
|
||||
optimize_stmt_block(statements, state, preserve_result, true, false);
|
||||
|
||||
if let Some(mut condition) = mem::take(&mut block.condition) {
|
||||
optimize_expr(&mut condition, state, false);
|
||||
match condition {
|
||||
Expr::Unit(..) | Expr::BoolConstant(true, ..) => state.set_dirty(),
|
||||
_ => block.condition = Some(condition),
|
||||
optimize_expr(&mut block.condition, state, false);
|
||||
|
||||
match block.condition {
|
||||
Expr::Unit(pos) => {
|
||||
block.condition = Expr::BoolConstant(true, pos);
|
||||
state.set_dirty();
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
// Remove false ranges
|
||||
ranges.retain(|(.., block)| match block.condition {
|
||||
Some(Expr::BoolConstant(false, ..)) => {
|
||||
Expr::BoolConstant(false, ..) => {
|
||||
state.set_dirty();
|
||||
false
|
||||
}
|
||||
|
@ -2,7 +2,7 @@
|
||||
|
||||
use crate::engine::OP_EQUALS;
|
||||
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")]
|
||||
use std::prelude::v1::*;
|
||||
|
||||
@ -266,4 +266,26 @@ mod map_functions {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
155
src/parser.rs
155
src/parser.rs
@ -8,7 +8,7 @@ use crate::ast::{
|
||||
OpAssignment, ScriptFnDef, Stmt, StmtBlock, StmtBlockContainer, SwitchCases, TryCatchBlock,
|
||||
};
|
||||
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::tokenizer::{
|
||||
is_keyword_function, is_valid_function_name, is_valid_identifier, Token, TokenStream,
|
||||
@ -47,6 +47,8 @@ pub struct ParseState<'e> {
|
||||
pub tokenizer_control: TokenizerControl,
|
||||
/// Interned strings.
|
||||
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.
|
||||
pub stack: Scope<'e>,
|
||||
/// 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`].
|
||||
#[inline(always)]
|
||||
#[must_use]
|
||||
pub fn new(engine: &Engine, tokenizer_control: TokenizerControl) -> Self {
|
||||
pub fn new(engine: &Engine, scope: &'e Scope, tokenizer_control: TokenizerControl) -> Self {
|
||||
Self {
|
||||
tokenizer_control,
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
@ -80,6 +82,7 @@ impl<'e> ParseState<'e> {
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
allow_capture: true,
|
||||
interned_strings: StringsInterner::new(),
|
||||
scope,
|
||||
stack: Scope::new(),
|
||||
block_stack_len: 0,
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
@ -426,10 +429,6 @@ impl Engine {
|
||||
let mut settings = settings;
|
||||
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())?;
|
||||
|
||||
match input.next().expect(NEVER_ENDS) {
|
||||
@ -453,6 +452,7 @@ impl Engine {
|
||||
state: &mut ParseState,
|
||||
lib: &mut FnLib,
|
||||
id: Identifier,
|
||||
no_args: bool,
|
||||
capture_parent_scope: bool,
|
||||
#[cfg(not(feature = "no_module"))] namespace: crate::ast::Namespace,
|
||||
settings: ParseSettings,
|
||||
@ -460,7 +460,11 @@ impl Engine {
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
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"))]
|
||||
let mut namespace = namespace;
|
||||
@ -479,7 +483,9 @@ impl Engine {
|
||||
Token::LexError(err) => return Err(err.clone().into_err(*token_pos)),
|
||||
// id()
|
||||
Token::RightParen => {
|
||||
eat_token(input, Token::RightParen);
|
||||
if !no_args {
|
||||
eat_token(input, Token::RightParen);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
let hash = if !namespace.is_empty() {
|
||||
@ -897,7 +903,7 @@ impl Engine {
|
||||
}
|
||||
|
||||
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) {
|
||||
return Err(PERR::DuplicatedProperty(s.to_string()).into_err(pos));
|
||||
}
|
||||
@ -1041,7 +1047,7 @@ impl Engine {
|
||||
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)),
|
||||
|
||||
@ -1054,9 +1060,14 @@ impl Engine {
|
||||
Some(self.parse_expr(input, state, lib, settings.level_up())?);
|
||||
|
||||
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 {
|
||||
None
|
||||
Expr::BoolConstant(true, Position::NONE)
|
||||
};
|
||||
(case_expr, condition)
|
||||
}
|
||||
@ -1196,6 +1207,11 @@ impl Engine {
|
||||
let root_expr = match token {
|
||||
Token::EOF => return Err(PERR::UnexpectedEOF.into_err(settings.pos)),
|
||||
|
||||
Token::Unit => {
|
||||
input.next();
|
||||
Expr::Unit(settings.pos)
|
||||
}
|
||||
|
||||
Token::IntegerConstant(..)
|
||||
| Token::CharConstant(..)
|
||||
| Token::StringConstant(..)
|
||||
@ -1213,13 +1229,13 @@ impl Engine {
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
Token::FloatConstant(x) => {
|
||||
let x = *x;
|
||||
input.next().expect(NEVER_ENDS);
|
||||
input.next();
|
||||
Expr::FloatConstant(x, settings.pos)
|
||||
}
|
||||
#[cfg(feature = "decimal")]
|
||||
Token::DecimalConstant(x) => {
|
||||
let x = (*x).into();
|
||||
input.next().expect(NEVER_ENDS);
|
||||
input.next();
|
||||
Expr::DynamicConstant(Box::new(x), settings.pos)
|
||||
}
|
||||
|
||||
@ -1230,6 +1246,7 @@ impl Engine {
|
||||
stmt => unreachable!("Stmt::Block expected but gets {:?}", stmt),
|
||||
}
|
||||
}
|
||||
|
||||
// ( - grouped expression
|
||||
Token::LeftParen => self.parse_paren_expr(input, state, lib, settings.level_up())?,
|
||||
|
||||
@ -1247,7 +1264,8 @@ impl Engine {
|
||||
// | ...
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
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"))]
|
||||
{
|
||||
@ -1283,6 +1301,10 @@ impl Engine {
|
||||
if settings.options.strict_var
|
||||
&& !settings.is_closure_scope
|
||||
&& index.is_none()
|
||||
&& !matches!(
|
||||
state.scope.get_index(name),
|
||||
Some((_, AccessMode::ReadOnly))
|
||||
)
|
||||
{
|
||||
// If the parent scope is not inside another capturing closure
|
||||
// then we can conclude that the captured variable doesn't exist.
|
||||
@ -1396,7 +1418,7 @@ impl Engine {
|
||||
|
||||
match input.peek().expect(NEVER_ENDS).0 {
|
||||
// Function call
|
||||
Token::LeftParen | Token::Bang => {
|
||||
Token::LeftParen | Token::Bang | Token::Unit => {
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
{
|
||||
// Once the identifier consumed we must enable next variables capturing
|
||||
@ -1426,7 +1448,10 @@ impl Engine {
|
||||
_ => {
|
||||
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(
|
||||
PERR::VariableUndefined(s.to_string()).into_err(settings.pos)
|
||||
);
|
||||
@ -1462,11 +1487,13 @@ impl Engine {
|
||||
|
||||
match input.peek().expect(NEVER_ENDS).0 {
|
||||
// Function call is allowed to have reserved keyword
|
||||
Token::LeftParen | Token::Bang if is_keyword_function(&s) => Expr::Variable(
|
||||
(None, ns, 0, state.get_identifier("", s)).into(),
|
||||
None,
|
||||
settings.pos,
|
||||
),
|
||||
Token::LeftParen | Token::Bang | Token::Unit if is_keyword_function(&s) => {
|
||||
Expr::Variable(
|
||||
(None, ns, 0, state.get_identifier("", s)).into(),
|
||||
None,
|
||||
settings.pos,
|
||||
)
|
||||
}
|
||||
// Access to `this` as a variable is OK within a function scope
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
_ if &*s == KEYWORD_THIS && settings.is_function_scope => Expr::Variable(
|
||||
@ -1526,30 +1553,33 @@ impl Engine {
|
||||
// Qualified function call with !
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
(Expr::Variable(x, ..), Token::Bang) if !x.1.is_empty() => {
|
||||
return if !match_token(input, Token::LeftParen).0 {
|
||||
Err(LexError::UnexpectedInput(Token::Bang.syntax().to_string())
|
||||
.into_err(tail_pos))
|
||||
} else {
|
||||
Err(LexError::ImproperSymbol(
|
||||
return match input.peek().expect(NEVER_ENDS) {
|
||||
(Token::LeftParen | Token::Unit, ..) => {
|
||||
Err(LexError::UnexpectedInput(Token::Bang.syntax().to_string())
|
||||
.into_err(tail_pos))
|
||||
}
|
||||
_ => Err(LexError::ImproperSymbol(
|
||||
"!".to_string(),
|
||||
"'!' cannot be used to call module functions".to_string(),
|
||||
)
|
||||
.into_err(tail_pos))
|
||||
.into_err(tail_pos)),
|
||||
};
|
||||
}
|
||||
// Function call with !
|
||||
(Expr::Variable(x, .., pos), Token::Bang) => {
|
||||
match match_token(input, Token::LeftParen) {
|
||||
(false, pos) => {
|
||||
match input.peek().expect(NEVER_ENDS) {
|
||||
(Token::LeftParen | Token::Unit, ..) => (),
|
||||
(_, pos) => {
|
||||
return Err(PERR::MissingToken(
|
||||
Token::LeftParen.syntax().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;
|
||||
settings.pos = pos;
|
||||
self.parse_fn_call(
|
||||
@ -1557,6 +1587,7 @@ impl Engine {
|
||||
state,
|
||||
lib,
|
||||
name,
|
||||
no_args,
|
||||
true,
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
_ns,
|
||||
@ -1564,7 +1595,7 @@ impl Engine {
|
||||
)?
|
||||
}
|
||||
// Function call
|
||||
(Expr::Variable(x, .., pos), Token::LeftParen) => {
|
||||
(Expr::Variable(x, .., pos), t @ (Token::LeftParen | Token::Unit)) => {
|
||||
let (.., _ns, _, name) = *x;
|
||||
settings.pos = pos;
|
||||
self.parse_fn_call(
|
||||
@ -1572,6 +1603,7 @@ impl Engine {
|
||||
state,
|
||||
lib,
|
||||
name,
|
||||
t == Token::Unit,
|
||||
false,
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
_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 {
|
||||
// const_expr = rhs
|
||||
@ -1816,10 +1852,9 @@ impl Engine {
|
||||
Err(PERR::AssignmentToConstant("".into()).into_err(lhs.start_position()))
|
||||
}
|
||||
// var (non-indexed) = rhs
|
||||
Expr::Variable(ref x, None, _) if x.0.is_none() => Ok(Stmt::Assignment(
|
||||
(op_info, (lhs, rhs).into()).into(),
|
||||
op_pos,
|
||||
)),
|
||||
Expr::Variable(ref x, None, _) if x.0.is_none() => {
|
||||
Ok(Stmt::Assignment((op_info, (lhs, rhs).into()).into()))
|
||||
}
|
||||
// var (indexed) = rhs
|
||||
Expr::Variable(ref x, i, var_pos) => {
|
||||
let (index, .., name) = x.as_ref();
|
||||
@ -1832,10 +1867,9 @@ impl Engine {
|
||||
.get_mut_by_index(state.stack.len() - index)
|
||||
.access_mode()
|
||||
{
|
||||
AccessMode::ReadWrite => Ok(Stmt::Assignment(
|
||||
(op_info, (lhs, rhs).into()).into(),
|
||||
op_pos,
|
||||
)),
|
||||
AccessMode::ReadWrite => {
|
||||
Ok(Stmt::Assignment((op_info, (lhs, rhs).into()).into()))
|
||||
}
|
||||
// Constant values cannot be assigned to
|
||||
AccessMode::ReadOnly => {
|
||||
Err(PERR::AssignmentToConstant(name.to_string()).into_err(var_pos))
|
||||
@ -1854,10 +1888,9 @@ impl Engine {
|
||||
None => {
|
||||
match x.lhs {
|
||||
// var[???] = rhs, var.??? = rhs
|
||||
Expr::Variable(..) => Ok(Stmt::Assignment(
|
||||
(op_info, (lhs, rhs).into()).into(),
|
||||
op_pos,
|
||||
)),
|
||||
Expr::Variable(..) => {
|
||||
Ok(Stmt::Assignment((op_info, (lhs, rhs).into()).into()))
|
||||
}
|
||||
// expr[???] = rhs, expr.??? = rhs
|
||||
ref expr => Err(PERR::AssignmentToInvalidLHS("".to_string())
|
||||
.into_err(expr.position())),
|
||||
@ -1986,7 +2019,7 @@ impl Engine {
|
||||
))
|
||||
}
|
||||
// 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 {
|
||||
Expr::Dot(x, term, pos) => (x, term, pos, true),
|
||||
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) {
|
||||
(b @ Token::True, pos) | (b @ Token::False, pos) => {
|
||||
(b @ (Token::True | Token::False), pos) => {
|
||||
inputs.push(Expr::BoolConstant(b == Token::True, pos));
|
||||
segments.push(state.get_interned_string("", b.literal_syntax()));
|
||||
tokens.push(state.get_identifier("", CUSTOM_SYNTAX_MARKER_BOOL));
|
||||
@ -2686,7 +2719,7 @@ impl Engine {
|
||||
engine: self,
|
||||
scope: &mut state.stack,
|
||||
global: &mut GlobalRuntimeState::new(self),
|
||||
state: &mut EvalState::new(),
|
||||
caches: None,
|
||||
lib: &[],
|
||||
this_ptr: &mut None,
|
||||
level,
|
||||
@ -2993,7 +3026,7 @@ impl Engine {
|
||||
comments.push(comment);
|
||||
|
||||
match input.peek().expect(NEVER_ENDS) {
|
||||
(Token::Fn, ..) | (Token::Private, ..) => break,
|
||||
(Token::Fn | Token::Private, ..) => break,
|
||||
(Token::Comment(..), ..) => (),
|
||||
_ => return Err(PERR::WrongDocComment.into_err(comments_pos)),
|
||||
}
|
||||
@ -3039,7 +3072,8 @@ impl Engine {
|
||||
|
||||
match input.next().expect(NEVER_ENDS) {
|
||||
(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"))]
|
||||
{
|
||||
@ -3263,14 +3297,21 @@ impl Engine {
|
||||
Err(_) => return Err(PERR::FnMissingName.into_err(pos)),
|
||||
};
|
||||
|
||||
match input.peek().expect(NEVER_ENDS) {
|
||||
(Token::LeftParen, ..) => eat_token(input, Token::LeftParen),
|
||||
let no_params = match input.peek().expect(NEVER_ENDS) {
|
||||
(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)),
|
||||
};
|
||||
|
||||
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);
|
||||
|
||||
loop {
|
||||
@ -3504,7 +3545,6 @@ impl Engine {
|
||||
&self,
|
||||
input: &mut TokenStream,
|
||||
state: &mut ParseState,
|
||||
_scope: &Scope,
|
||||
_optimization_level: OptimizationLevel,
|
||||
) -> ParseResult<AST> {
|
||||
let mut functions = BTreeMap::new();
|
||||
@ -3546,7 +3586,7 @@ impl Engine {
|
||||
#[cfg(not(feature = "no_optimize"))]
|
||||
return Ok(crate::optimizer::optimize_into_ast(
|
||||
self,
|
||||
_scope,
|
||||
state.scope,
|
||||
statements,
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
StaticVec::new_const(),
|
||||
@ -3628,7 +3668,6 @@ impl Engine {
|
||||
&self,
|
||||
input: &mut TokenStream,
|
||||
state: &mut ParseState,
|
||||
_scope: &Scope,
|
||||
_optimization_level: OptimizationLevel,
|
||||
) -> ParseResult<AST> {
|
||||
let (statements, _lib) = self.parse_global_level(input, state)?;
|
||||
@ -3636,7 +3675,7 @@ impl Engine {
|
||||
#[cfg(not(feature = "no_optimize"))]
|
||||
return Ok(crate::optimizer::optimize_into_ast(
|
||||
self,
|
||||
_scope,
|
||||
state.scope,
|
||||
statements,
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
_lib,
|
||||
|
@ -382,6 +382,8 @@ pub enum Token {
|
||||
LeftBracket,
|
||||
/// `]`
|
||||
RightBracket,
|
||||
/// `()`
|
||||
Unit,
|
||||
/// `+`
|
||||
Plus,
|
||||
/// `+` (unary)
|
||||
@ -558,6 +560,7 @@ impl Token {
|
||||
RightParen => ")",
|
||||
LeftBracket => "[",
|
||||
RightBracket => "]",
|
||||
Unit => "()",
|
||||
Plus => "+",
|
||||
UnaryPlus => "+",
|
||||
Minus => "-",
|
||||
@ -754,6 +757,7 @@ impl Token {
|
||||
")" => RightParen,
|
||||
"[" => LeftBracket,
|
||||
"]" => RightBracket,
|
||||
"()" => Unit,
|
||||
"+" => Plus,
|
||||
"-" => Minus,
|
||||
"*" => Multiply,
|
||||
@ -1702,6 +1706,12 @@ fn get_next_token_inner(
|
||||
('{', ..) => return Some((Token::LeftBrace, start_pos)),
|
||||
('}', ..) => return Some((Token::RightBrace, start_pos)),
|
||||
|
||||
// Unit
|
||||
('(', ')') => {
|
||||
eat_next(stream, pos);
|
||||
return Some((Token::Unit, start_pos));
|
||||
}
|
||||
|
||||
// Parentheses
|
||||
('(', '*') => {
|
||||
eat_next(stream, pos);
|
||||
|
@ -51,7 +51,8 @@ impl fmt::Display for LexError {
|
||||
Self::ImproperSymbol(s, d) if d.is_empty() => {
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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"#)?;
|
||||
|
||||
assert_eq!(x["a"].clone_cast::<INT>(), 1);
|
||||
assert_eq!(x["b"].clone_cast::<bool>(), true);
|
||||
assert_eq!(x["a"].as_int().unwrap(), 1);
|
||||
assert_eq!(x["b"].as_bool().unwrap(), true);
|
||||
assert_eq!(x["c$"].clone_cast::<String>(), "hello");
|
||||
|
||||
Ok(())
|
||||
@ -143,8 +143,8 @@ fn test_map_return() -> Result<(), Box<EvalAltResult>> {
|
||||
|
||||
let x = engine.eval::<Map>(r#"#{a: 1, b: true, "c$": "hello"}"#)?;
|
||||
|
||||
assert_eq!(x["a"].clone_cast::<INT>(), 1);
|
||||
assert_eq!(x["b"].clone_cast::<bool>(), true);
|
||||
assert_eq!(x["a"].as_int().unwrap(), 1);
|
||||
assert_eq!(x["b"].as_bool().unwrap(), true);
|
||||
assert_eq!(x["c$"].clone_cast::<String>(), "hello");
|
||||
|
||||
Ok(())
|
||||
@ -182,17 +182,17 @@ fn test_map_for() -> Result<(), Box<EvalAltResult>> {
|
||||
fn test_map_json() -> Result<(), Box<EvalAltResult>> {
|
||||
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)?;
|
||||
|
||||
assert!(!map.contains_key("x"));
|
||||
|
||||
assert_eq!(map["a"].clone_cast::<INT>(), 1);
|
||||
assert_eq!(map["b"].clone_cast::<bool>(), true);
|
||||
assert_eq!(map["c"].clone_cast::<INT>(), 42);
|
||||
assert_eq!(map["a"].as_int().unwrap(), 1);
|
||||
assert_eq!(map["b"].as_bool().unwrap(), true);
|
||||
assert_eq!(map["c"].as_int().unwrap(), 42);
|
||||
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"))]
|
||||
{
|
||||
@ -218,12 +218,37 @@ fn test_map_json() -> Result<(), Box<EvalAltResult>> {
|
||||
);
|
||||
}
|
||||
|
||||
engine.parse_json(&format!("#{}", json), true)?;
|
||||
engine.parse_json(json, true)?;
|
||||
|
||||
assert!(matches!(
|
||||
*engine.parse_json(" 123", true).expect_err("should error"),
|
||||
EvalAltResult::ErrorParsing(ParseErrorType::MissingToken(token, ..), ..)
|
||||
if token == "{"
|
||||
*engine.parse_json("123", true).expect_err("should error"),
|
||||
EvalAltResult::ErrorMismatchOutputType(..)
|
||||
));
|
||||
|
||||
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(())
|
||||
|
@ -56,6 +56,10 @@ fn test_options_allow() -> Result<(), Box<EvalAltResult>> {
|
||||
fn test_options_strict_var() -> Result<(), Box<EvalAltResult>> {
|
||||
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 };")?;
|
||||
|
||||
#[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());
|
||||
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"))]
|
||||
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 };")?;
|
||||
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(())
|
||||
|
@ -17,6 +17,6 @@ fn test_unit_eq() -> Result<(), Box<EvalAltResult>> {
|
||||
#[test]
|
||||
fn test_unit_with_spaces() -> Result<(), Box<EvalAltResult>> {
|
||||
let engine = Engine::new();
|
||||
engine.run("let x = ( ); x")?;
|
||||
engine.run("let x = ( ); x").expect_err("should error");
|
||||
Ok(())
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user