Merge pull request #564 from schungx/master
Bug fixes and some enhancements.
This commit is contained in:
commit
6b57331c60
15
CHANGELOG.md
15
CHANGELOG.md
@ -8,6 +8,21 @@ Bug fixes
|
|||||||
---------
|
---------
|
||||||
|
|
||||||
* Self-contained `AST` now works properly with `Engine::call_fn`.
|
* Self-contained `AST` now works properly with `Engine::call_fn`.
|
||||||
|
* Missing `to_int` from `Decimal` is added.
|
||||||
|
* Parsing of index expressions is relaxed and many cases no longer result in an index-type error to allow for custom indexers.
|
||||||
|
* Merging or combining a self-contained `AST` into another `AST` now works properly.
|
||||||
|
|
||||||
|
Deprecated API's
|
||||||
|
----------------
|
||||||
|
|
||||||
|
* `FnPtr::num_curried` is deprecated in favor of `FnPtr::curry().len()`.
|
||||||
|
|
||||||
|
Enhancements
|
||||||
|
------------
|
||||||
|
|
||||||
|
* `EvalAltResult::IndexNotFound` is added to aid in raising errors for indexers.
|
||||||
|
* `Engine::def_tag`, `Engine::def_tag_mut` and `Engine::set_tag` are added to manage a default value for the custom evaluation state, accessible via `EvalState::tag()` (which is the same as `NativeCallContext::tag()`).
|
||||||
|
* Originally, the debugger's custom state uses the same state as `EvalState::tag()` (which is the same as `NativeCallContext::tag()`). It is now split into its own variable accessible under `Debugger::state()`.
|
||||||
|
|
||||||
|
|
||||||
Version 1.7.0
|
Version 1.7.0
|
||||||
|
@ -187,7 +187,7 @@ impl Engine {
|
|||||||
///
|
///
|
||||||
/// # WARNING - Low Level API
|
/// # WARNING - Low Level API
|
||||||
///
|
///
|
||||||
/// This function is very low level.
|
/// This function is _extremely_ low level.
|
||||||
///
|
///
|
||||||
/// A [`GlobalRuntimeState`] and [`Caches`] need to be passed into the function, which can be
|
/// A [`GlobalRuntimeState`] and [`Caches`] need to be passed into the function, which can be
|
||||||
/// created via [`GlobalRuntimeState::new`] and [`Caches::new`].
|
/// created via [`GlobalRuntimeState::new`] and [`Caches::new`].
|
||||||
|
@ -201,11 +201,7 @@ impl Engine {
|
|||||||
scope: &Scope,
|
scope: &Scope,
|
||||||
scripts: impl AsRef<[S]>,
|
scripts: impl AsRef<[S]>,
|
||||||
) -> ParseResult<AST> {
|
) -> ParseResult<AST> {
|
||||||
self.compile_with_scope_and_optimization_level(
|
self.compile_with_scope_and_optimization_level(scope, scripts, self.optimization_level)
|
||||||
scope,
|
|
||||||
scripts,
|
|
||||||
self.options.optimization_level,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
/// Join a list of strings and compile into an [`AST`] using own scope at a specific optimization level.
|
/// Join a list of strings and compile into an [`AST`] using own scope at a specific optimization level.
|
||||||
///
|
///
|
||||||
@ -296,6 +292,6 @@ impl Engine {
|
|||||||
|
|
||||||
let mut peekable = stream.peekable();
|
let mut peekable = stream.peekable();
|
||||||
let mut state = ParseState::new(self, scope, tokenizer_control);
|
let mut state = ParseState::new(self, scope, tokenizer_control);
|
||||||
self.parse_global_expr(&mut peekable, &mut state, self.options.optimization_level)
|
self.parse_global_expr(&mut peekable, &mut state, self.optimization_level)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,14 +1,13 @@
|
|||||||
//! Module implementing custom syntax for [`Engine`].
|
//! Module implementing custom syntax for [`Engine`].
|
||||||
|
|
||||||
use crate::ast::Expr;
|
use crate::ast::Expr;
|
||||||
use crate::eval::Caches;
|
|
||||||
use crate::func::native::SendSync;
|
use crate::func::native::SendSync;
|
||||||
use crate::parser::ParseResult;
|
use crate::parser::ParseResult;
|
||||||
use crate::tokenizer::{is_valid_identifier, Token};
|
use crate::tokenizer::{is_valid_identifier, Token};
|
||||||
use crate::types::dynamic::Variant;
|
use crate::types::dynamic::Variant;
|
||||||
use crate::{
|
use crate::{
|
||||||
reify, Engine, EvalContext, Identifier, ImmutableString, LexError, Position, RhaiResult,
|
reify, Engine, EvalContext, Identifier, ImmutableString, LexError, Position, RhaiResult,
|
||||||
Shared, StaticVec,
|
StaticVec,
|
||||||
};
|
};
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
@ -65,6 +64,15 @@ impl<'a> From<&'a Expr> for Expression<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Expression<'_> {
|
impl Expression<'_> {
|
||||||
|
/// Evaluate this [expression tree][Expression] within an [evaluation context][`EvalContext`].
|
||||||
|
///
|
||||||
|
/// # WARNING - Low Level API
|
||||||
|
///
|
||||||
|
/// This function is very low level. It evaluates an expression from an [`AST`][crate::AST].
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn eval_with_context(&self, context: &mut EvalContext) -> RhaiResult {
|
||||||
|
context.eval_expression_tree(self)
|
||||||
|
}
|
||||||
/// Get the value of this expression if it is a variable name or a string constant.
|
/// Get the value of this expression if it is a variable name or a string constant.
|
||||||
///
|
///
|
||||||
/// Returns [`None`] also if the constant is not of the specified type.
|
/// Returns [`None`] also if the constant is not of the specified type.
|
||||||
@ -131,41 +139,13 @@ impl Deref for Expression<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EvalContext<'_, '_, '_, '_, '_, '_, '_, '_> {
|
|
||||||
/// Evaluate an [expression tree][Expression].
|
|
||||||
///
|
|
||||||
/// # WARNING - Low Level API
|
|
||||||
///
|
|
||||||
/// 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,
|
|
||||||
match self.caches.as_mut() {
|
|
||||||
Some(c) => c,
|
|
||||||
None => {
|
|
||||||
caches = Caches::new();
|
|
||||||
&mut caches
|
|
||||||
}
|
|
||||||
},
|
|
||||||
self.lib,
|
|
||||||
self.this_ptr,
|
|
||||||
expr,
|
|
||||||
self.level,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Definition of a custom syntax definition.
|
/// Definition of a custom syntax definition.
|
||||||
pub struct CustomSyntax {
|
pub struct CustomSyntax {
|
||||||
/// A parsing function to return the next token in a custom syntax based on the
|
/// A parsing function to return the next token in a custom syntax based on the
|
||||||
/// symbols parsed so far.
|
/// symbols parsed so far.
|
||||||
pub parse: Box<FnCustomSyntaxParse>,
|
pub parse: Box<FnCustomSyntaxParse>,
|
||||||
/// Custom syntax implementation function.
|
/// Custom syntax implementation function.
|
||||||
pub func: Shared<FnCustomSyntaxEval>,
|
pub func: Box<FnCustomSyntaxEval>,
|
||||||
/// Any variables added/removed in the scope?
|
/// Any variables added/removed in the scope?
|
||||||
pub scope_may_be_changed: bool,
|
pub scope_may_be_changed: bool,
|
||||||
}
|
}
|
||||||
@ -356,7 +336,7 @@ impl Engine {
|
|||||||
key.into(),
|
key.into(),
|
||||||
CustomSyntax {
|
CustomSyntax {
|
||||||
parse: Box::new(parse),
|
parse: Box::new(parse),
|
||||||
func: (Box::new(func) as Box<FnCustomSyntaxEval>).into(),
|
func: Box::new(func),
|
||||||
scope_may_be_changed,
|
scope_may_be_changed,
|
||||||
}
|
}
|
||||||
.into(),
|
.into(),
|
||||||
|
@ -259,6 +259,19 @@ impl<T> From<EvalAltResult> for RhaiResultOf<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl FnPtr {
|
impl FnPtr {
|
||||||
|
/// Get the number of curried arguments.
|
||||||
|
///
|
||||||
|
/// # Deprecated
|
||||||
|
///
|
||||||
|
/// This method is deprecated. Use [`curry().len()`][`FnPtr::curry`] instead.
|
||||||
|
///
|
||||||
|
/// This method will be removed in the next major version.
|
||||||
|
#[deprecated(since = "1.8.0", note = "use `curry().len()` instead")]
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub fn num_curried(&self) -> usize {
|
||||||
|
self.curry().len()
|
||||||
|
}
|
||||||
/// Call the function pointer with curried arguments (if any).
|
/// Call the function pointer with curried arguments (if any).
|
||||||
/// The function may be script-defined (not available under `no_function`) or native Rust.
|
/// The function may be script-defined (not available under `no_function`) or native Rust.
|
||||||
///
|
///
|
||||||
|
@ -67,7 +67,7 @@ impl Engine {
|
|||||||
let ast = self.compile_with_scope_and_optimization_level(
|
let ast = self.compile_with_scope_and_optimization_level(
|
||||||
scope,
|
scope,
|
||||||
&[script],
|
&[script],
|
||||||
self.options.optimization_level,
|
self.optimization_level,
|
||||||
)?;
|
)?;
|
||||||
self.eval_ast_with_scope(scope, &ast)
|
self.eval_ast_with_scope(scope, &ast)
|
||||||
}
|
}
|
||||||
|
@ -119,8 +119,8 @@ impl Engine {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
let scope = &Scope::new();
|
let scope = Scope::new();
|
||||||
let mut state = ParseState::new(self, scope, tokenizer_control);
|
let mut state = ParseState::new(self, &scope, tokenizer_control);
|
||||||
|
|
||||||
let ast = self.parse_global_expr(
|
let ast = self.parse_global_expr(
|
||||||
&mut stream.peekable(),
|
&mut stream.peekable(),
|
||||||
@ -156,11 +156,13 @@ pub fn format_map_as_json(map: &Map) -> String {
|
|||||||
let mut result = String::from('{');
|
let mut result = String::from('{');
|
||||||
|
|
||||||
for (key, value) in map {
|
for (key, value) in map {
|
||||||
|
use std::fmt::Write;
|
||||||
|
|
||||||
if result.len() > 1 {
|
if result.len() > 1 {
|
||||||
result.push(',');
|
result.push(',');
|
||||||
}
|
}
|
||||||
|
|
||||||
result.push_str(&format!("{:?}", key));
|
write!(result, "{:?}", key).unwrap();
|
||||||
result.push(':');
|
result.push(':');
|
||||||
|
|
||||||
if let Some(val) = value.read_lock::<Map>() {
|
if let Some(val) = value.read_lock::<Map>() {
|
||||||
@ -171,7 +173,7 @@ pub fn format_map_as_json(map: &Map) -> String {
|
|||||||
if value.is::<()>() {
|
if value.is::<()>() {
|
||||||
result.push_str("null");
|
result.push_str("null");
|
||||||
} else {
|
} else {
|
||||||
result.push_str(&format!("{:?}", value));
|
write!(result, "{:?}", value).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -30,7 +30,7 @@ pub mod deprecated;
|
|||||||
|
|
||||||
use crate::engine::Precedence;
|
use crate::engine::Precedence;
|
||||||
use crate::tokenizer::Token;
|
use crate::tokenizer::Token;
|
||||||
use crate::{Engine, Identifier};
|
use crate::{Dynamic, Engine, Identifier};
|
||||||
|
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
@ -195,4 +195,23 @@ impl Engine {
|
|||||||
|
|
||||||
Ok(self)
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the default value of the custom state for each evaluation run.
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub fn default_tag(&self) -> &Dynamic {
|
||||||
|
&self.def_tag
|
||||||
|
}
|
||||||
|
/// Get a mutable reference to the default value of the custom state for each evaluation run.
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub fn default_tag_mut(&mut self) -> &mut Dynamic {
|
||||||
|
&mut self.def_tag
|
||||||
|
}
|
||||||
|
/// Set the default value of the custom state for each evaluation run.
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn set_default_tag(&mut self, value: impl Into<Dynamic>) -> &mut Self {
|
||||||
|
self.def_tag = value.into();
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,7 +9,7 @@ impl Engine {
|
|||||||
/// Not available under `no_optimize`.
|
/// Not available under `no_optimize`.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn set_optimization_level(&mut self, optimization_level: OptimizationLevel) -> &mut Self {
|
pub fn set_optimization_level(&mut self, optimization_level: OptimizationLevel) -> &mut Self {
|
||||||
self.options.optimization_level = optimization_level;
|
self.optimization_level = optimization_level;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -20,7 +20,7 @@ impl Engine {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn optimization_level(&self) -> OptimizationLevel {
|
pub const fn optimization_level(&self) -> OptimizationLevel {
|
||||||
self.options.optimization_level
|
self.optimization_level
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Optimize the [`AST`] with constants defined in an external Scope.
|
/// Optimize the [`AST`] with constants defined in an external Scope.
|
||||||
|
@ -1,62 +1,49 @@
|
|||||||
//! Settings for [`Engine`]'s language options.
|
//! Settings for [`Engine`]'s language options.
|
||||||
|
|
||||||
use crate::{Engine, OptimizationLevel};
|
use crate::Engine;
|
||||||
|
use bitflags::bitflags;
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
|
|
||||||
/// A type containing all language options for the [`Engine`].
|
bitflags! {
|
||||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
|
/// Bit-flags containing all language options for the [`Engine`].
|
||||||
pub struct LanguageOptions {
|
pub struct LangOptions: u8 {
|
||||||
/// Script optimization level.
|
/// Is `if`-expression allowed?
|
||||||
pub optimization_level: OptimizationLevel,
|
const IF_EXPR = 0b_00000001;
|
||||||
/// Is `if`-expression allowed?
|
/// Is `switch` expression allowed?
|
||||||
pub allow_if_expr: bool,
|
const SWITCH_EXPR = 0b_00000010;
|
||||||
/// Is `switch` expression allowed?
|
/// Is statement-expression allowed?
|
||||||
pub allow_switch_expr: bool,
|
const STMT_EXPR = 0b_00000100;
|
||||||
/// Is statement-expression allowed?
|
/// Is anonymous function allowed?
|
||||||
pub allow_stmt_expr: bool,
|
#[cfg(not(feature = "no_function"))]
|
||||||
/// Is anonymous function allowed?
|
const ANON_FN = 0b_00001000;
|
||||||
#[cfg(not(feature = "no_function"))]
|
/// Is looping allowed?
|
||||||
pub allow_anonymous_fn: bool,
|
const LOOPING = 0b_00010000;
|
||||||
/// Is looping allowed?
|
/// Is variables shadowing allowed?
|
||||||
pub allow_looping: bool,
|
const SHADOW = 0b_00100000;
|
||||||
/// Is variables shadowing allowed?
|
/// Strict variables mode?
|
||||||
pub allow_shadowing: bool,
|
const STRICT_VAR = 0b_01000000;
|
||||||
/// Strict variables mode?
|
/// Raise error if an object map property does not exist?
|
||||||
pub strict_var: bool,
|
/// Returns `()` if `false`.
|
||||||
/// Raise error if an object map property does not exist?
|
#[cfg(not(feature = "no_object"))]
|
||||||
/// Returns `()` if `false`.
|
const FAIL_ON_INVALID_MAP_PROPERTY = 0b_10000000;
|
||||||
#[cfg(not(feature = "no_object"))]
|
|
||||||
pub fail_on_invalid_map_property: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LanguageOptions {
|
|
||||||
/// Create a new [`Options`] with default values.
|
|
||||||
#[inline(always)]
|
|
||||||
pub const fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
#[cfg(not(feature = "no_optimize"))]
|
|
||||||
optimization_level: OptimizationLevel::Simple,
|
|
||||||
#[cfg(feature = "no_optimize")]
|
|
||||||
optimization_level: (),
|
|
||||||
|
|
||||||
allow_if_expr: true,
|
|
||||||
allow_switch_expr: true,
|
|
||||||
allow_stmt_expr: true,
|
|
||||||
#[cfg(not(feature = "no_function"))]
|
|
||||||
allow_anonymous_fn: true,
|
|
||||||
allow_looping: true,
|
|
||||||
strict_var: false,
|
|
||||||
allow_shadowing: true,
|
|
||||||
#[cfg(not(feature = "no_object"))]
|
|
||||||
fail_on_invalid_map_property: false,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for LanguageOptions {
|
impl LangOptions {
|
||||||
fn default() -> Self {
|
/// Create a new [`Options`] with default values.
|
||||||
Self::new()
|
#[inline(always)]
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::IF_EXPR | Self::SWITCH_EXPR | Self::STMT_EXPR | Self::LOOPING | Self::SHADOW | {
|
||||||
|
#[cfg(not(feature = "no_function"))]
|
||||||
|
{
|
||||||
|
Self::ANON_FN
|
||||||
|
}
|
||||||
|
#[cfg(feature = "no_function")]
|
||||||
|
{
|
||||||
|
Self::empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -65,34 +52,34 @@ impl Engine {
|
|||||||
/// Default is `true`.
|
/// Default is `true`.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub const fn allow_if_expression(&self) -> bool {
|
pub const fn allow_if_expression(&self) -> bool {
|
||||||
self.options.allow_if_expr
|
self.options.contains(LangOptions::IF_EXPR)
|
||||||
}
|
}
|
||||||
/// Set whether `if`-expression is allowed.
|
/// Set whether `if`-expression is allowed.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn set_allow_if_expression(&mut self, enable: bool) {
|
pub fn set_allow_if_expression(&mut self, enable: bool) {
|
||||||
self.options.allow_if_expr = enable;
|
self.options.set(LangOptions::IF_EXPR, enable)
|
||||||
}
|
}
|
||||||
/// Is `switch` expression allowed?
|
/// Is `switch` expression allowed?
|
||||||
/// Default is `true`.
|
/// Default is `true`.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub const fn allow_switch_expression(&self) -> bool {
|
pub const fn allow_switch_expression(&self) -> bool {
|
||||||
self.options.allow_switch_expr
|
self.options.contains(LangOptions::SWITCH_EXPR)
|
||||||
}
|
}
|
||||||
/// Set whether `switch` expression is allowed.
|
/// Set whether `switch` expression is allowed.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn set_allow_switch_expression(&mut self, enable: bool) {
|
pub fn set_allow_switch_expression(&mut self, enable: bool) {
|
||||||
self.options.allow_switch_expr = enable;
|
self.options.set(LangOptions::SWITCH_EXPR, enable);
|
||||||
}
|
}
|
||||||
/// Is statement-expression allowed?
|
/// Is statement-expression allowed?
|
||||||
/// Default is `true`.
|
/// Default is `true`.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub const fn allow_statement_expression(&self) -> bool {
|
pub const fn allow_statement_expression(&self) -> bool {
|
||||||
self.options.allow_stmt_expr
|
self.options.contains(LangOptions::STMT_EXPR)
|
||||||
}
|
}
|
||||||
/// Set whether statement-expression is allowed.
|
/// Set whether statement-expression is allowed.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn set_allow_statement_expression(&mut self, enable: bool) {
|
pub fn set_allow_statement_expression(&mut self, enable: bool) {
|
||||||
self.options.allow_stmt_expr = enable;
|
self.options.set(LangOptions::STMT_EXPR, enable);
|
||||||
}
|
}
|
||||||
/// Is anonymous function allowed?
|
/// Is anonymous function allowed?
|
||||||
/// Default is `true`.
|
/// Default is `true`.
|
||||||
@ -101,7 +88,7 @@ impl Engine {
|
|||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub const fn allow_anonymous_fn(&self) -> bool {
|
pub const fn allow_anonymous_fn(&self) -> bool {
|
||||||
self.options.allow_anonymous_fn
|
self.options.contains(LangOptions::ANON_FN)
|
||||||
}
|
}
|
||||||
/// Set whether anonymous function is allowed.
|
/// Set whether anonymous function is allowed.
|
||||||
///
|
///
|
||||||
@ -109,40 +96,40 @@ impl Engine {
|
|||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn set_allow_anonymous_fn(&mut self, enable: bool) {
|
pub fn set_allow_anonymous_fn(&mut self, enable: bool) {
|
||||||
self.options.allow_anonymous_fn = enable;
|
self.options.set(LangOptions::ANON_FN, enable);
|
||||||
}
|
}
|
||||||
/// Is looping allowed?
|
/// Is looping allowed?
|
||||||
/// Default is `true`.
|
/// Default is `true`.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub const fn allow_looping(&self) -> bool {
|
pub const fn allow_looping(&self) -> bool {
|
||||||
self.options.allow_looping
|
self.options.contains(LangOptions::LOOPING)
|
||||||
}
|
}
|
||||||
/// Set whether looping is allowed.
|
/// Set whether looping is allowed.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn set_allow_looping(&mut self, enable: bool) {
|
pub fn set_allow_looping(&mut self, enable: bool) {
|
||||||
self.options.allow_looping = enable;
|
self.options.set(LangOptions::LOOPING, enable);
|
||||||
}
|
}
|
||||||
/// Is variables shadowing allowed?
|
/// Is variables shadowing allowed?
|
||||||
/// Default is `true`.
|
/// Default is `true`.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub const fn allow_shadowing(&self) -> bool {
|
pub const fn allow_shadowing(&self) -> bool {
|
||||||
self.options.allow_shadowing
|
self.options.contains(LangOptions::SHADOW)
|
||||||
}
|
}
|
||||||
/// Set whether variables shadowing is allowed.
|
/// Set whether variables shadowing is allowed.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn set_allow_shadowing(&mut self, enable: bool) {
|
pub fn set_allow_shadowing(&mut self, enable: bool) {
|
||||||
self.options.allow_shadowing = enable;
|
self.options.set(LangOptions::SHADOW, enable);
|
||||||
}
|
}
|
||||||
/// Is strict variables mode enabled?
|
/// Is strict variables mode enabled?
|
||||||
/// Default is `false`.
|
/// Default is `false`.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub const fn strict_variables(&self) -> bool {
|
pub const fn strict_variables(&self) -> bool {
|
||||||
self.options.strict_var
|
self.options.contains(LangOptions::STRICT_VAR)
|
||||||
}
|
}
|
||||||
/// Set whether strict variables mode is enabled.
|
/// Set whether strict variables mode is enabled.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn set_strict_variables(&mut self, enable: bool) {
|
pub fn set_strict_variables(&mut self, enable: bool) {
|
||||||
self.options.strict_var = enable;
|
self.options.set(LangOptions::STRICT_VAR, enable);
|
||||||
}
|
}
|
||||||
/// Raise error if an object map property does not exist?
|
/// Raise error if an object map property does not exist?
|
||||||
/// Default is `false`.
|
/// Default is `false`.
|
||||||
@ -151,7 +138,8 @@ impl Engine {
|
|||||||
#[cfg(not(feature = "no_object"))]
|
#[cfg(not(feature = "no_object"))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub const fn fail_on_invalid_map_property(&self) -> bool {
|
pub const fn fail_on_invalid_map_property(&self) -> bool {
|
||||||
self.options.fail_on_invalid_map_property
|
self.options
|
||||||
|
.contains(LangOptions::FAIL_ON_INVALID_MAP_PROPERTY)
|
||||||
}
|
}
|
||||||
/// Set whether to raise error if an object map property does not exist.
|
/// Set whether to raise error if an object map property does not exist.
|
||||||
///
|
///
|
||||||
@ -159,6 +147,7 @@ impl Engine {
|
|||||||
#[cfg(not(feature = "no_object"))]
|
#[cfg(not(feature = "no_object"))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn set_fail_on_invalid_map_property(&mut self, enable: bool) {
|
pub fn set_fail_on_invalid_map_property(&mut self, enable: bool) {
|
||||||
self.options.fail_on_invalid_map_property = enable;
|
self.options
|
||||||
|
.set(LangOptions::FAIL_ON_INVALID_MAP_PROPERTY, enable);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -26,11 +26,7 @@ impl Engine {
|
|||||||
self.lex_raw(&scripts, self.token_mapper.as_ref().map(Box::as_ref));
|
self.lex_raw(&scripts, self.token_mapper.as_ref().map(Box::as_ref));
|
||||||
let mut state = ParseState::new(self, scope, tokenizer_control);
|
let mut state = ParseState::new(self, scope, tokenizer_control);
|
||||||
|
|
||||||
let ast = self.parse(
|
let ast = self.parse(&mut stream.peekable(), &mut state, self.optimization_level)?;
|
||||||
&mut stream.peekable(),
|
|
||||||
&mut state,
|
|
||||||
self.options.optimization_level,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
self.run_ast_with_scope(scope, &ast)
|
self.run_ast_with_scope(scope, &ast)
|
||||||
}
|
}
|
||||||
|
@ -506,7 +506,7 @@ impl AST {
|
|||||||
lib
|
lib
|
||||||
};
|
};
|
||||||
|
|
||||||
if !other.source.is_empty() {
|
let mut _ast = if !other.source.is_empty() {
|
||||||
Self::new_with_source(
|
Self::new_with_source(
|
||||||
merged,
|
merged,
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
@ -519,7 +519,31 @@ impl AST {
|
|||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
lib,
|
lib,
|
||||||
)
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(not(feature = "no_module"))]
|
||||||
|
match (
|
||||||
|
self.resolver().map_or(0, |r| r.len()),
|
||||||
|
other.resolver().map_or(0, |r| r.len()),
|
||||||
|
) {
|
||||||
|
(0, 0) => (),
|
||||||
|
(_, 0) => {
|
||||||
|
_ast.set_resolver(self.resolver().unwrap().clone());
|
||||||
|
}
|
||||||
|
(0, _) => {
|
||||||
|
_ast.set_resolver(other.resolver().unwrap().clone());
|
||||||
|
}
|
||||||
|
(_, _) => {
|
||||||
|
let mut resolver = (**self.resolver().unwrap()).clone();
|
||||||
|
let other_resolver = (**other.resolver().unwrap()).clone();
|
||||||
|
for (k, v) in other_resolver {
|
||||||
|
resolver.insert(k, crate::func::shared_take_or_clone(v));
|
||||||
|
}
|
||||||
|
_ast.set_resolver(resolver);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_ast
|
||||||
}
|
}
|
||||||
/// Combine one [`AST`] with another. The second [`AST`] is consumed.
|
/// Combine one [`AST`] with another. The second [`AST`] is consumed.
|
||||||
///
|
///
|
||||||
@ -594,6 +618,27 @@ impl AST {
|
|||||||
crate::func::native::shared_make_mut(&mut self.lib)
|
crate::func::native::shared_make_mut(&mut self.lib)
|
||||||
.merge_filtered(&other.lib, &_filter);
|
.merge_filtered(&other.lib, &_filter);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "no_module"))]
|
||||||
|
match (
|
||||||
|
self.resolver.as_ref().map_or(0, |r| r.len()),
|
||||||
|
other.resolver.as_ref().map_or(0, |r| r.len()),
|
||||||
|
) {
|
||||||
|
(_, 0) => (),
|
||||||
|
(0, _) => {
|
||||||
|
self.set_resolver(other.resolver.unwrap());
|
||||||
|
}
|
||||||
|
(_, _) => {
|
||||||
|
let resolver =
|
||||||
|
crate::func::native::shared_make_mut(self.resolver.as_mut().unwrap());
|
||||||
|
let other_resolver =
|
||||||
|
crate::func::native::shared_take_or_clone(other.resolver.unwrap());
|
||||||
|
for (k, v) in other_resolver {
|
||||||
|
resolver.insert(k, crate::func::shared_take_or_clone(v));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
/// Filter out the functions, retaining only some based on a filter predicate.
|
/// Filter out the functions, retaining only some based on a filter predicate.
|
||||||
|
@ -799,6 +799,8 @@ impl Expr {
|
|||||||
match token {
|
match token {
|
||||||
#[cfg(not(feature = "no_object"))]
|
#[cfg(not(feature = "no_object"))]
|
||||||
Token::Period => return true,
|
Token::Period => return true,
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
Token::LeftBracket => return true,
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -823,15 +825,9 @@ impl Expr {
|
|||||||
| Self::Index(..)
|
| Self::Index(..)
|
||||||
| Self::Array(..)
|
| Self::Array(..)
|
||||||
| Self::Map(..)
|
| Self::Map(..)
|
||||||
| Self::Custom(..) => match token {
|
| Self::Custom(..) => false,
|
||||||
#[cfg(not(feature = "no_index"))]
|
|
||||||
Token::LeftBracket => true,
|
|
||||||
_ => false,
|
|
||||||
},
|
|
||||||
|
|
||||||
Self::Variable(..) => match token {
|
Self::Variable(..) => match token {
|
||||||
#[cfg(not(feature = "no_index"))]
|
|
||||||
Token::LeftBracket => true,
|
|
||||||
Token::LeftParen => true,
|
Token::LeftParen => true,
|
||||||
Token::Unit => true,
|
Token::Unit => true,
|
||||||
Token::Bang => true,
|
Token::Bang => true,
|
||||||
@ -840,8 +836,6 @@ impl Expr {
|
|||||||
},
|
},
|
||||||
|
|
||||||
Self::Property(..) => match token {
|
Self::Property(..) => match token {
|
||||||
#[cfg(not(feature = "no_index"))]
|
|
||||||
Token::LeftBracket => true,
|
|
||||||
Token::LeftParen => true,
|
Token::LeftParen => true,
|
||||||
_ => false,
|
_ => false,
|
||||||
},
|
},
|
||||||
|
@ -15,7 +15,7 @@ pub enum FnAccess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bitflags! {
|
bitflags! {
|
||||||
/// _(internals)_ A type that holds a configuration option with bit-flags.
|
/// _(internals)_ Bit-flags containing [`AST`][crate::AST] node configuration options.
|
||||||
/// Exported under the `internals` feature only.
|
/// Exported under the `internals` feature only.
|
||||||
pub struct ASTFlags: u8 {
|
pub struct ASTFlags: u8 {
|
||||||
/// No options for the [`AST`][crate::AST] node.
|
/// No options for the [`AST`][crate::AST] node.
|
||||||
|
@ -17,8 +17,8 @@ use std::{
|
|||||||
///
|
///
|
||||||
/// Not available under `no_module`.
|
/// Not available under `no_module`.
|
||||||
///
|
///
|
||||||
/// A [`u64`] offset to the current [stack of imported modules][crate::GlobalRuntimeState] is
|
/// A [`u64`] offset to the current stack of imported [modules][crate::Module] in the
|
||||||
/// cached for quick search purposes.
|
/// [global runtime state][crate::GlobalRuntimeState] is cached for quick search purposes.
|
||||||
///
|
///
|
||||||
/// A [`StaticVec`] is used because the vast majority of namespace-qualified access contains only
|
/// A [`StaticVec`] is used because the vast majority of namespace-qualified access contains only
|
||||||
/// one level, and it is wasteful to always allocate a [`Vec`] with one element.
|
/// one level, and it is wasteful to always allocate a [`Vec`] with one element.
|
||||||
|
@ -60,7 +60,12 @@ fn print_current_source(
|
|||||||
lines: &[String],
|
lines: &[String],
|
||||||
window: (usize, usize),
|
window: (usize, usize),
|
||||||
) {
|
) {
|
||||||
let current_source = &mut *context.tag_mut().write_lock::<ImmutableString>().unwrap();
|
let current_source = &mut *context
|
||||||
|
.global_runtime_state_mut()
|
||||||
|
.debugger
|
||||||
|
.state_mut()
|
||||||
|
.write_lock::<ImmutableString>()
|
||||||
|
.unwrap();
|
||||||
let src = source.unwrap_or("");
|
let src = source.unwrap_or("");
|
||||||
if src != current_source {
|
if src != current_source {
|
||||||
println!(
|
println!(
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
//! Main module defining the script evaluation [`Engine`].
|
//! Main module defining the script evaluation [`Engine`].
|
||||||
|
|
||||||
use crate::api::custom_syntax::CustomSyntax;
|
use crate::api::custom_syntax::CustomSyntax;
|
||||||
use crate::api::options::LanguageOptions;
|
use crate::api::options::LangOptions;
|
||||||
use crate::func::native::{
|
use crate::func::native::{
|
||||||
OnDebugCallback, OnDefVarCallback, OnParseTokenCallback, OnPrintCallback, OnVarCallback,
|
OnDebugCallback, OnDefVarCallback, OnParseTokenCallback, OnPrintCallback, OnVarCallback,
|
||||||
};
|
};
|
||||||
@ -9,7 +9,8 @@ use crate::packages::{Package, StandardPackage};
|
|||||||
use crate::tokenizer::Token;
|
use crate::tokenizer::Token;
|
||||||
use crate::types::dynamic::Union;
|
use crate::types::dynamic::Union;
|
||||||
use crate::{
|
use crate::{
|
||||||
Dynamic, Identifier, ImmutableString, Module, Position, RhaiResult, Shared, StaticVec,
|
Dynamic, Identifier, ImmutableString, Module, OptimizationLevel, Position, RhaiResult, Shared,
|
||||||
|
StaticVec,
|
||||||
};
|
};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
@ -112,7 +113,7 @@ pub struct Engine {
|
|||||||
/// A map containing custom keywords and precedence to recognize.
|
/// A map containing custom keywords and precedence to recognize.
|
||||||
pub(crate) custom_keywords: BTreeMap<Identifier, Option<Precedence>>,
|
pub(crate) custom_keywords: BTreeMap<Identifier, Option<Precedence>>,
|
||||||
/// Custom syntax.
|
/// Custom syntax.
|
||||||
pub(crate) custom_syntax: BTreeMap<Identifier, Box<CustomSyntax>>,
|
pub(crate) custom_syntax: BTreeMap<Identifier, CustomSyntax>,
|
||||||
/// Callback closure for filtering variable definition.
|
/// Callback closure for filtering variable definition.
|
||||||
pub(crate) def_var_filter: Option<Box<OnDefVarCallback>>,
|
pub(crate) def_var_filter: Option<Box<OnDefVarCallback>>,
|
||||||
/// Callback closure for resolving variable access.
|
/// Callback closure for resolving variable access.
|
||||||
@ -129,7 +130,13 @@ pub struct Engine {
|
|||||||
pub(crate) progress: Option<Box<crate::func::native::OnProgressCallback>>,
|
pub(crate) progress: Option<Box<crate::func::native::OnProgressCallback>>,
|
||||||
|
|
||||||
/// Language options.
|
/// Language options.
|
||||||
pub(crate) options: LanguageOptions,
|
pub(crate) options: LangOptions,
|
||||||
|
|
||||||
|
/// Default value for the custom state.
|
||||||
|
pub(crate) def_tag: Dynamic,
|
||||||
|
|
||||||
|
/// Script optimization level.
|
||||||
|
pub(crate) optimization_level: OptimizationLevel,
|
||||||
|
|
||||||
/// Max limits.
|
/// Max limits.
|
||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
@ -155,7 +162,14 @@ impl fmt::Debug for Engine {
|
|||||||
|
|
||||||
f.field("disabled_symbols", &self.disabled_symbols)
|
f.field("disabled_symbols", &self.disabled_symbols)
|
||||||
.field("custom_keywords", &self.custom_keywords)
|
.field("custom_keywords", &self.custom_keywords)
|
||||||
.field("custom_syntax", &(!self.custom_syntax.is_empty()))
|
.field(
|
||||||
|
"custom_syntax",
|
||||||
|
&self
|
||||||
|
.custom_syntax
|
||||||
|
.keys()
|
||||||
|
.map(|s| s.as_str())
|
||||||
|
.collect::<String>(),
|
||||||
|
)
|
||||||
.field("def_var_filter", &self.def_var_filter.is_some())
|
.field("def_var_filter", &self.def_var_filter.is_some())
|
||||||
.field("resolve_var", &self.resolve_var.is_some())
|
.field("resolve_var", &self.resolve_var.is_some())
|
||||||
.field("token_mapper", &self.token_mapper.is_some());
|
.field("token_mapper", &self.token_mapper.is_some());
|
||||||
@ -267,7 +281,14 @@ impl Engine {
|
|||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
progress: None,
|
progress: None,
|
||||||
|
|
||||||
options: LanguageOptions::new(),
|
options: LangOptions::new(),
|
||||||
|
|
||||||
|
def_tag: Dynamic::UNIT,
|
||||||
|
|
||||||
|
#[cfg(not(feature = "no_optimize"))]
|
||||||
|
optimization_level: OptimizationLevel::Simple,
|
||||||
|
#[cfg(feature = "no_optimize")]
|
||||||
|
optimization_level: (),
|
||||||
|
|
||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
limits: crate::api::limits::Limits::new(),
|
limits: crate::api::limits::Limits::new(),
|
||||||
|
@ -13,8 +13,7 @@ pub struct FnResolutionCacheEntry {
|
|||||||
/// Function.
|
/// Function.
|
||||||
pub func: CallableFunction,
|
pub func: CallableFunction,
|
||||||
/// Optional source.
|
/// Optional source.
|
||||||
/// No source if the string is empty.
|
pub source: Option<Box<Identifier>>,
|
||||||
pub source: Identifier,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// _(internals)_ A function resolution cache.
|
/// _(internals)_ A function resolution cache.
|
||||||
@ -22,7 +21,7 @@ pub struct FnResolutionCacheEntry {
|
|||||||
///
|
///
|
||||||
/// [`FnResolutionCacheEntry`] is [`Box`]ed in order to pack as many entries inside a single B-Tree
|
/// [`FnResolutionCacheEntry`] is [`Box`]ed in order to pack as many entries inside a single B-Tree
|
||||||
/// level as possible.
|
/// level as possible.
|
||||||
pub type FnResolutionCache = BTreeMap<u64, Option<Box<FnResolutionCacheEntry>>>;
|
pub type FnResolutionCache = BTreeMap<u64, Option<FnResolutionCacheEntry>>;
|
||||||
|
|
||||||
/// _(internals)_ A type containing system-wide caches.
|
/// _(internals)_ A type containing system-wide caches.
|
||||||
/// Exported under the `internals` feature only.
|
/// Exported under the `internals` feature only.
|
||||||
|
@ -335,12 +335,11 @@ impl Engine {
|
|||||||
let (mut new_val, op_info) = new_val.expect("`Some`");
|
let (mut new_val, op_info) = new_val.expect("`Some`");
|
||||||
|
|
||||||
if op_info.is_op_assignment() {
|
if op_info.is_op_assignment() {
|
||||||
let hash = crate::ast::FnCallHashes::from_native(*hash_get);
|
|
||||||
let args = &mut [target.as_mut()];
|
let args = &mut [target.as_mut()];
|
||||||
let (mut orig_val, ..) = self
|
let (mut orig_val, ..) = self
|
||||||
.exec_fn_call(
|
.call_native_fn(
|
||||||
None, global, caches, lib, getter, hash, args, is_ref_mut,
|
global, caches, lib, getter, *hash_get, args, is_ref_mut,
|
||||||
true, *pos, level,
|
false, *pos, level,
|
||||||
)
|
)
|
||||||
.or_else(|err| match *err {
|
.or_else(|err| match *err {
|
||||||
// Try an indexer if property does not exist
|
// Try an indexer if property does not exist
|
||||||
@ -371,10 +370,9 @@ impl Engine {
|
|||||||
new_val = orig_val;
|
new_val = orig_val;
|
||||||
}
|
}
|
||||||
|
|
||||||
let hash = crate::ast::FnCallHashes::from_native(*hash_set);
|
|
||||||
let args = &mut [target.as_mut(), &mut new_val];
|
let args = &mut [target.as_mut(), &mut new_val];
|
||||||
self.exec_fn_call(
|
self.call_native_fn(
|
||||||
None, global, caches, lib, setter, hash, args, is_ref_mut, true, *pos,
|
global, caches, lib, setter, *hash_set, args, is_ref_mut, false, *pos,
|
||||||
level,
|
level,
|
||||||
)
|
)
|
||||||
.or_else(|err| match *err {
|
.or_else(|err| match *err {
|
||||||
@ -399,10 +397,9 @@ impl Engine {
|
|||||||
self.run_debugger(scope, global, lib, this_ptr, rhs, level)?;
|
self.run_debugger(scope, global, lib, this_ptr, rhs, level)?;
|
||||||
|
|
||||||
let ((getter, hash_get), _, name) = x.as_ref();
|
let ((getter, hash_get), _, name) = x.as_ref();
|
||||||
let hash = crate::ast::FnCallHashes::from_native(*hash_get);
|
|
||||||
let args = &mut [target.as_mut()];
|
let args = &mut [target.as_mut()];
|
||||||
self.exec_fn_call(
|
self.call_native_fn(
|
||||||
None, global, caches, lib, getter, hash, args, is_ref_mut, true, *pos,
|
global, caches, lib, getter, *hash_get, args, is_ref_mut, false, *pos,
|
||||||
level,
|
level,
|
||||||
)
|
)
|
||||||
.map_or_else(
|
.map_or_else(
|
||||||
@ -488,16 +485,14 @@ impl Engine {
|
|||||||
|
|
||||||
let ((getter, hash_get), (setter, hash_set), name) = p.as_ref();
|
let ((getter, hash_get), (setter, hash_set), name) = p.as_ref();
|
||||||
let rhs_chain = rhs.into();
|
let rhs_chain = rhs.into();
|
||||||
let hash_get = crate::ast::FnCallHashes::from_native(*hash_get);
|
|
||||||
let hash_set = crate::ast::FnCallHashes::from_native(*hash_set);
|
|
||||||
let mut arg_values = [target.as_mut(), &mut Dynamic::UNIT.clone()];
|
let mut arg_values = [target.as_mut(), &mut Dynamic::UNIT.clone()];
|
||||||
let args = &mut arg_values[..1];
|
let args = &mut arg_values[..1];
|
||||||
|
|
||||||
// Assume getters are always pure
|
// Assume getters are always pure
|
||||||
let (mut val, ..) = self
|
let (mut val, ..) = self
|
||||||
.exec_fn_call(
|
.call_native_fn(
|
||||||
None, global, caches, lib, getter, hash_get, args,
|
global, caches, lib, getter, *hash_get, args, is_ref_mut,
|
||||||
is_ref_mut, true, pos, level,
|
false, pos, level,
|
||||||
)
|
)
|
||||||
.or_else(|err| match *err {
|
.or_else(|err| match *err {
|
||||||
// Try an indexer if property does not exist
|
// Try an indexer if property does not exist
|
||||||
@ -531,9 +526,9 @@ impl Engine {
|
|||||||
// Re-use args because the first &mut parameter will not be consumed
|
// Re-use args because the first &mut parameter will not be consumed
|
||||||
let mut arg_values = [target.as_mut(), val.as_mut()];
|
let mut arg_values = [target.as_mut(), val.as_mut()];
|
||||||
let args = &mut arg_values;
|
let args = &mut arg_values;
|
||||||
self.exec_fn_call(
|
self.call_native_fn(
|
||||||
None, global, caches, lib, setter, hash_set, args,
|
global, caches, lib, setter, *hash_set, args, is_ref_mut,
|
||||||
is_ref_mut, true, pos, level,
|
false, pos, level,
|
||||||
)
|
)
|
||||||
.or_else(
|
.or_else(
|
||||||
|err| match *err {
|
|err| match *err {
|
||||||
@ -813,12 +808,13 @@ impl Engine {
|
|||||||
level: usize,
|
level: usize,
|
||||||
) -> RhaiResultOf<Dynamic> {
|
) -> RhaiResultOf<Dynamic> {
|
||||||
let args = &mut [target, idx];
|
let args = &mut [target, idx];
|
||||||
let hash_get = crate::ast::FnCallHashes::from_native(global.hash_idx_get());
|
let hash = global.hash_idx_get();
|
||||||
let fn_name = crate::engine::FN_IDX_GET;
|
let fn_name = crate::engine::FN_IDX_GET;
|
||||||
let pos = Position::NONE;
|
let pos = Position::NONE;
|
||||||
|
let level = level + 1;
|
||||||
|
|
||||||
self.exec_fn_call(
|
self.call_native_fn(
|
||||||
None, global, caches, lib, fn_name, hash_get, args, true, true, pos, level,
|
global, caches, lib, fn_name, hash, args, true, false, pos, level,
|
||||||
)
|
)
|
||||||
.map(|(r, ..)| r)
|
.map(|(r, ..)| r)
|
||||||
}
|
}
|
||||||
@ -837,13 +833,14 @@ impl Engine {
|
|||||||
is_ref_mut: bool,
|
is_ref_mut: bool,
|
||||||
level: usize,
|
level: usize,
|
||||||
) -> RhaiResultOf<(Dynamic, bool)> {
|
) -> RhaiResultOf<(Dynamic, bool)> {
|
||||||
let hash_set = crate::ast::FnCallHashes::from_native(global.hash_idx_set());
|
let hash = global.hash_idx_set();
|
||||||
let args = &mut [target, idx, new_val];
|
let args = &mut [target, idx, new_val];
|
||||||
let fn_name = crate::engine::FN_IDX_SET;
|
let fn_name = crate::engine::FN_IDX_SET;
|
||||||
let pos = Position::NONE;
|
let pos = Position::NONE;
|
||||||
|
let level = level + 1;
|
||||||
|
|
||||||
self.exec_fn_call(
|
self.call_native_fn(
|
||||||
None, global, caches, lib, fn_name, hash_set, args, is_ref_mut, true, pos, level,
|
global, caches, lib, fn_name, hash, args, is_ref_mut, false, pos, level,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -253,17 +253,20 @@ pub struct Debugger {
|
|||||||
break_points: Vec<BreakPoint>,
|
break_points: Vec<BreakPoint>,
|
||||||
/// The current function call stack.
|
/// The current function call stack.
|
||||||
call_stack: Vec<CallStackFrame>,
|
call_stack: Vec<CallStackFrame>,
|
||||||
|
/// The current state.
|
||||||
|
state: Dynamic,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Debugger {
|
impl Debugger {
|
||||||
/// Create a new [`Debugger`].
|
/// Create a new [`Debugger`].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn new(status: DebuggerStatus) -> Self {
|
pub fn new(status: DebuggerStatus, state: Dynamic) -> Self {
|
||||||
Self {
|
Self {
|
||||||
status,
|
status,
|
||||||
break_points: Vec::new(),
|
break_points: Vec::new(),
|
||||||
call_stack: Vec::new(),
|
call_stack: Vec::new(),
|
||||||
|
state,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// Get the current call stack.
|
/// Get the current call stack.
|
||||||
@ -374,6 +377,23 @@ impl Debugger {
|
|||||||
pub fn break_points_mut(&mut self) -> &mut Vec<BreakPoint> {
|
pub fn break_points_mut(&mut self) -> &mut Vec<BreakPoint> {
|
||||||
&mut self.break_points
|
&mut self.break_points
|
||||||
}
|
}
|
||||||
|
/// Get the custom state.
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub fn state(&self) -> &Dynamic {
|
||||||
|
&self.state
|
||||||
|
}
|
||||||
|
/// Get a mutable reference to the custom state.
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub fn state_mut(&mut self) -> &mut Dynamic {
|
||||||
|
&mut self.state
|
||||||
|
}
|
||||||
|
/// Set the custom state.
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn set_state(&mut self, state: impl Into<Dynamic>) {
|
||||||
|
self.state = state.into();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Engine {
|
impl Engine {
|
||||||
@ -496,15 +516,7 @@ impl Engine {
|
|||||||
Some(source.as_str())
|
Some(source.as_str())
|
||||||
};
|
};
|
||||||
|
|
||||||
let context = crate::EvalContext {
|
let context = crate::EvalContext::new(self, scope, global, None, lib, this_ptr, level);
|
||||||
engine: self,
|
|
||||||
scope,
|
|
||||||
global,
|
|
||||||
caches: None,
|
|
||||||
lib,
|
|
||||||
this_ptr,
|
|
||||||
level,
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Some((.., ref on_debugger)) = self.debugger {
|
if let Some((.., ref on_debugger)) = self.debugger {
|
||||||
let command = on_debugger(context, event, node, source, node.position())?;
|
let command = on_debugger(context, event, node, source, node.position())?;
|
||||||
|
@ -1,34 +1,56 @@
|
|||||||
//! Evaluation context.
|
//! Evaluation context.
|
||||||
|
|
||||||
use super::{Caches, GlobalRuntimeState};
|
use super::{Caches, GlobalRuntimeState};
|
||||||
use crate::{Dynamic, Engine, Module, Scope};
|
use crate::{Dynamic, Engine, Expression, Module, RhaiResult, Scope};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
|
|
||||||
/// Context of a script evaluation process.
|
/// Context of a script evaluation process.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct EvalContext<'a, 's, 'ps, 'm, 'pm, 'c, 't, 'pt> {
|
pub struct EvalContext<'a, 's, 'ps, 'g, 'pg, 'c, 't, 'pt> {
|
||||||
/// The current [`Engine`].
|
/// The current [`Engine`].
|
||||||
pub(crate) engine: &'a Engine,
|
engine: &'a Engine,
|
||||||
/// The current [`Scope`].
|
/// The current [`Scope`].
|
||||||
pub(crate) scope: &'s mut Scope<'ps>,
|
scope: &'s mut Scope<'ps>,
|
||||||
/// The current [`GlobalRuntimeState`].
|
/// The current [`GlobalRuntimeState`].
|
||||||
pub(crate) global: &'m mut GlobalRuntimeState<'pm>,
|
global: &'g mut GlobalRuntimeState<'pg>,
|
||||||
/// The current [caches][Caches], if available.
|
/// The current [caches][Caches], if available.
|
||||||
pub(crate) caches: Option<&'c mut Caches>,
|
caches: Option<&'c mut Caches>,
|
||||||
/// The current stack of imported [modules][Module].
|
/// The current stack of imported [modules][Module].
|
||||||
pub(crate) lib: &'a [&'a Module],
|
lib: &'a [&'a Module],
|
||||||
/// The current bound `this` pointer, if any.
|
/// The current bound `this` pointer, if any.
|
||||||
pub(crate) this_ptr: &'t mut Option<&'pt mut Dynamic>,
|
this_ptr: &'t mut Option<&'pt mut Dynamic>,
|
||||||
/// The current nesting level of function calls.
|
/// The current nesting level of function calls.
|
||||||
pub(crate) level: usize,
|
level: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'s, 'ps, 'm, 'pm, 'pt> EvalContext<'_, 's, 'ps, 'm, 'pm, '_, '_, 'pt> {
|
impl<'a, 's, 'ps, 'g, 'pg, 'c, 't, 'pt> EvalContext<'a, 's, 'ps, 'g, 'pg, 'c, 't, 'pt> {
|
||||||
|
/// Create a new [`EvalContext`].
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub fn new(
|
||||||
|
engine: &'a Engine,
|
||||||
|
scope: &'s mut Scope<'ps>,
|
||||||
|
global: &'g mut GlobalRuntimeState<'pg>,
|
||||||
|
caches: Option<&'c mut Caches>,
|
||||||
|
lib: &'a [&'a Module],
|
||||||
|
this_ptr: &'t mut Option<&'pt mut Dynamic>,
|
||||||
|
level: usize,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
engine,
|
||||||
|
scope,
|
||||||
|
global,
|
||||||
|
caches,
|
||||||
|
lib,
|
||||||
|
this_ptr,
|
||||||
|
level,
|
||||||
|
}
|
||||||
|
}
|
||||||
/// The current [`Engine`].
|
/// The current [`Engine`].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn engine(&self) -> &Engine {
|
pub const fn engine(&self) -> &'a Engine {
|
||||||
self.engine
|
self.engine
|
||||||
}
|
}
|
||||||
/// The current source.
|
/// The current source.
|
||||||
@ -85,7 +107,7 @@ impl<'s, 'ps, 'm, 'pm, 'pt> EvalContext<'_, 's, 'ps, 'm, 'pm, '_, '_, 'pt> {
|
|||||||
#[cfg(feature = "internals")]
|
#[cfg(feature = "internals")]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn global_runtime_state_mut(&mut self) -> &mut &'m mut GlobalRuntimeState<'pm> {
|
pub fn global_runtime_state_mut(&mut self) -> &mut &'g mut GlobalRuntimeState<'pg> {
|
||||||
&mut self.global
|
&mut self.global
|
||||||
}
|
}
|
||||||
/// Get an iterator over the namespaces containing definition of all script-defined functions.
|
/// Get an iterator over the namespaces containing definition of all script-defined functions.
|
||||||
@ -110,8 +132,8 @@ impl<'s, 'ps, 'm, 'pm, 'pt> EvalContext<'_, 's, 'ps, 'm, 'pm, '_, '_, 'pt> {
|
|||||||
/// Mutable reference to the current bound `this` pointer, if any.
|
/// Mutable reference to the current bound `this` pointer, if any.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn this_ptr_mut(&mut self) -> Option<&mut &'pt mut Dynamic> {
|
pub fn this_ptr_mut(&mut self) -> &mut Option<&'pt mut Dynamic> {
|
||||||
self.this_ptr.as_mut()
|
&mut self.this_ptr
|
||||||
}
|
}
|
||||||
/// The current nesting level of function calls.
|
/// The current nesting level of function calls.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
@ -119,4 +141,29 @@ impl<'s, 'ps, 'm, 'pm, 'pt> EvalContext<'_, 's, 'ps, 'm, 'pm, '_, '_, 'pt> {
|
|||||||
pub const fn call_level(&self) -> usize {
|
pub const fn call_level(&self) -> usize {
|
||||||
self.level
|
self.level
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Evaluate an [expression tree][Expression] within this [evaluation context][`EvalContext`].
|
||||||
|
///
|
||||||
|
/// # WARNING - Low Level API
|
||||||
|
///
|
||||||
|
/// 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 new_caches = Caches::new();
|
||||||
|
|
||||||
|
let caches = match self.caches.as_mut() {
|
||||||
|
Some(c) => c,
|
||||||
|
None => &mut new_caches,
|
||||||
|
};
|
||||||
|
|
||||||
|
self.engine.eval_expr(
|
||||||
|
self.scope,
|
||||||
|
self.global,
|
||||||
|
caches,
|
||||||
|
self.lib,
|
||||||
|
self.this_ptr,
|
||||||
|
expr,
|
||||||
|
self.level,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -151,15 +151,7 @@ impl Engine {
|
|||||||
|
|
||||||
// Check the variable resolver, if any
|
// Check the variable resolver, if any
|
||||||
if let Some(ref resolve_var) = self.resolve_var {
|
if let Some(ref resolve_var) = self.resolve_var {
|
||||||
let context = EvalContext {
|
let context = EvalContext::new(self, scope, global, None, lib, this_ptr, level);
|
||||||
engine: self,
|
|
||||||
scope,
|
|
||||||
global,
|
|
||||||
caches: None,
|
|
||||||
lib,
|
|
||||||
this_ptr,
|
|
||||||
level,
|
|
||||||
};
|
|
||||||
let var_name = expr.get_variable_name(true).expect("`Expr::Variable`");
|
let var_name = expr.get_variable_name(true).expect("`Expr::Variable`");
|
||||||
match resolve_var(var_name, index, context) {
|
match resolve_var(var_name, index, context) {
|
||||||
Ok(Some(mut result)) => {
|
Ok(Some(mut result)) => {
|
||||||
@ -480,15 +472,8 @@ impl Engine {
|
|||||||
*pos,
|
*pos,
|
||||||
))
|
))
|
||||||
})?;
|
})?;
|
||||||
let mut context = EvalContext {
|
let mut context =
|
||||||
engine: self,
|
EvalContext::new(self, scope, global, Some(caches), lib, this_ptr, level);
|
||||||
scope,
|
|
||||||
global,
|
|
||||||
caches: Some(caches),
|
|
||||||
lib,
|
|
||||||
this_ptr,
|
|
||||||
level,
|
|
||||||
};
|
|
||||||
|
|
||||||
let result = (custom_def.func)(&mut context, &expressions);
|
let result = (custom_def.func)(&mut context, &expressions);
|
||||||
|
|
||||||
|
@ -78,8 +78,6 @@ impl GlobalRuntimeState<'_> {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn new(engine: &Engine) -> Self {
|
pub fn new(engine: &Engine) -> Self {
|
||||||
let _engine = engine;
|
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
keys: crate::StaticVec::new_const(),
|
keys: crate::StaticVec::new_const(),
|
||||||
@ -98,21 +96,21 @@ impl GlobalRuntimeState<'_> {
|
|||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
constants: None,
|
constants: None,
|
||||||
|
|
||||||
#[cfg(not(feature = "debugging"))]
|
tag: engine.default_tag().clone(),
|
||||||
tag: Dynamic::UNIT,
|
|
||||||
#[cfg(feature = "debugging")]
|
|
||||||
tag: if let Some((ref init, ..)) = engine.debugger {
|
|
||||||
init()
|
|
||||||
} else {
|
|
||||||
Dynamic::UNIT
|
|
||||||
},
|
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
debugger: crate::eval::Debugger::new(if engine.debugger.is_some() {
|
debugger: crate::eval::Debugger::new(
|
||||||
crate::eval::DebuggerStatus::Init
|
if engine.debugger.is_some() {
|
||||||
} else {
|
crate::eval::DebuggerStatus::Init
|
||||||
crate::eval::DebuggerStatus::CONTINUE
|
} else {
|
||||||
}),
|
crate::eval::DebuggerStatus::CONTINUE
|
||||||
|
},
|
||||||
|
if let Some((ref init, ..)) = engine.debugger {
|
||||||
|
init()
|
||||||
|
} else {
|
||||||
|
Dynamic::UNIT
|
||||||
|
},
|
||||||
|
),
|
||||||
|
|
||||||
dummy: PhantomData::default(),
|
dummy: PhantomData::default(),
|
||||||
}
|
}
|
||||||
|
@ -831,15 +831,7 @@ impl Engine {
|
|||||||
nesting_level,
|
nesting_level,
|
||||||
will_shadow,
|
will_shadow,
|
||||||
};
|
};
|
||||||
let context = EvalContext {
|
let context = EvalContext::new(self, scope, global, None, lib, this_ptr, level);
|
||||||
engine: self,
|
|
||||||
scope,
|
|
||||||
global,
|
|
||||||
caches: None,
|
|
||||||
lib,
|
|
||||||
this_ptr,
|
|
||||||
level,
|
|
||||||
};
|
|
||||||
|
|
||||||
match filter(true, info, context) {
|
match filter(true, info, context) {
|
||||||
Ok(true) => None,
|
Ok(true) => None,
|
||||||
|
117
src/func/call.rs
117
src/func/call.rs
@ -12,8 +12,8 @@ use crate::engine::{
|
|||||||
use crate::eval::{Caches, FnResolutionCacheEntry, GlobalRuntimeState};
|
use crate::eval::{Caches, FnResolutionCacheEntry, GlobalRuntimeState};
|
||||||
use crate::{
|
use crate::{
|
||||||
calc_fn_hash, calc_fn_params_hash, combine_hashes, Dynamic, Engine, FnArgsVec, FnPtr,
|
calc_fn_hash, calc_fn_params_hash, combine_hashes, Dynamic, Engine, FnArgsVec, FnPtr,
|
||||||
Identifier, ImmutableString, Module, OptimizationLevel, Position, RhaiError, RhaiResult,
|
ImmutableString, Module, OptimizationLevel, Position, RhaiError, RhaiResult, RhaiResultOf,
|
||||||
RhaiResultOf, Scope, ERR,
|
Scope, ERR,
|
||||||
};
|
};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
@ -214,14 +214,14 @@ impl Engine {
|
|||||||
.find_map(|&m| {
|
.find_map(|&m| {
|
||||||
m.get_fn(hash).cloned().map(|func| FnResolutionCacheEntry {
|
m.get_fn(hash).cloned().map(|func| FnResolutionCacheEntry {
|
||||||
func,
|
func,
|
||||||
source: m.id_raw().clone(),
|
source: m.id().map(|s| Box::new(s.into())),
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.or_else(|| {
|
.or_else(|| {
|
||||||
self.global_modules.iter().find_map(|m| {
|
self.global_modules.iter().find_map(|m| {
|
||||||
m.get_fn(hash).cloned().map(|func| FnResolutionCacheEntry {
|
m.get_fn(hash).cloned().map(|func| FnResolutionCacheEntry {
|
||||||
func,
|
func,
|
||||||
source: m.id_raw().clone(),
|
source: m.id().map(|s| Box::new(s.into())),
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
@ -232,8 +232,7 @@ impl Engine {
|
|||||||
_global.get_qualified_fn(hash).map(|(func, source)| {
|
_global.get_qualified_fn(hash).map(|(func, source)| {
|
||||||
FnResolutionCacheEntry {
|
FnResolutionCacheEntry {
|
||||||
func: func.clone(),
|
func: func.clone(),
|
||||||
source: source
|
source: source.map(|s| Box::new(s.into())),
|
||||||
.map_or_else(|| Identifier::new_const(), Into::into),
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@ -242,7 +241,7 @@ impl Engine {
|
|||||||
m.get_qualified_fn(hash).cloned().map(|func| {
|
m.get_qualified_fn(hash).cloned().map(|func| {
|
||||||
FnResolutionCacheEntry {
|
FnResolutionCacheEntry {
|
||||||
func,
|
func,
|
||||||
source: m.id_raw().clone(),
|
source: m.id().map(|s| Box::new(s.into())),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@ -250,7 +249,7 @@ impl Engine {
|
|||||||
|
|
||||||
match func {
|
match func {
|
||||||
// Specific version found
|
// Specific version found
|
||||||
Some(f) => return Some(Box::new(f)),
|
Some(f) => return Some(f),
|
||||||
|
|
||||||
// Stop when all permutations are exhausted
|
// Stop when all permutations are exhausted
|
||||||
None if bitmask >= max_bitmask => {
|
None if bitmask >= max_bitmask => {
|
||||||
@ -265,7 +264,7 @@ impl Engine {
|
|||||||
func: CallableFunction::from_method(
|
func: CallableFunction::from_method(
|
||||||
Box::new(f) as Box<FnAny>
|
Box::new(f) as Box<FnAny>
|
||||||
),
|
),
|
||||||
source: Identifier::new_const(),
|
source: None,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
@ -276,10 +275,9 @@ impl Engine {
|
|||||||
func: CallableFunction::from_method(
|
func: CallableFunction::from_method(
|
||||||
Box::new(f) as Box<FnAny>
|
Box::new(f) as Box<FnAny>
|
||||||
),
|
),
|
||||||
source: Identifier::new_const(),
|
source: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
.map(Box::new)
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -308,7 +306,7 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
result.as_ref().map(Box::as_ref)
|
result.as_ref()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// # Main Entry-Point
|
/// # Main Entry-Point
|
||||||
@ -370,9 +368,10 @@ impl Engine {
|
|||||||
backup.change_first_arg_to_copy(args);
|
backup.change_first_arg_to_copy(args);
|
||||||
}
|
}
|
||||||
|
|
||||||
let source = match (source.as_str(), parent_source.as_str()) {
|
let source = match (source, parent_source.as_str()) {
|
||||||
("", "") => None,
|
(None, "") => None,
|
||||||
("", s) | (s, ..) => Some(s),
|
(None, s) => Some(s),
|
||||||
|
(Some(s), ..) => Some(s.as_str()),
|
||||||
};
|
};
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
@ -626,7 +625,7 @@ impl Engine {
|
|||||||
|
|
||||||
// Script-defined function call?
|
// Script-defined function call?
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
if let Some(FnResolutionCacheEntry { func, mut source }) = self
|
if let Some(FnResolutionCacheEntry { func, ref source }) = self
|
||||||
.resolve_fn(
|
.resolve_fn(
|
||||||
global,
|
global,
|
||||||
caches,
|
caches,
|
||||||
@ -657,7 +656,13 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
mem::swap(&mut global.source, &mut source);
|
let orig_source = mem::replace(
|
||||||
|
&mut global.source,
|
||||||
|
source
|
||||||
|
.as_ref()
|
||||||
|
.map(|s| (**s).clone())
|
||||||
|
.unwrap_or(crate::Identifier::new_const()),
|
||||||
|
);
|
||||||
|
|
||||||
let result = if _is_method_call {
|
let result = if _is_method_call {
|
||||||
// Method call of script function - map first argument to `this`
|
// Method call of script function - map first argument to `this`
|
||||||
@ -695,7 +700,7 @@ impl Engine {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Restore the original source
|
// Restore the original source
|
||||||
mem::swap(&mut global.source, &mut source);
|
global.source = orig_source;
|
||||||
|
|
||||||
return Ok((result?, false));
|
return Ok((result?, false));
|
||||||
}
|
}
|
||||||
@ -731,6 +736,42 @@ impl Engine {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Evaluate an argument.
|
||||||
|
#[inline]
|
||||||
|
pub(crate) fn get_arg_value(
|
||||||
|
&self,
|
||||||
|
scope: &mut Scope,
|
||||||
|
global: &mut GlobalRuntimeState,
|
||||||
|
caches: &mut Caches,
|
||||||
|
lib: &[&Module],
|
||||||
|
this_ptr: &mut Option<&mut Dynamic>,
|
||||||
|
arg_expr: &Expr,
|
||||||
|
level: usize,
|
||||||
|
) -> RhaiResultOf<(Dynamic, Position)> {
|
||||||
|
#[cfg(feature = "debugging")]
|
||||||
|
if self.debugger.is_some() {
|
||||||
|
if let Some(value) = arg_expr.get_literal_value() {
|
||||||
|
#[cfg(feature = "debugging")]
|
||||||
|
self.run_debugger(scope, global, lib, this_ptr, arg_expr, level)?;
|
||||||
|
return Ok((value, arg_expr.start_position()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do not match function exit for arguments
|
||||||
|
#[cfg(feature = "debugging")]
|
||||||
|
let reset_debugger = global.debugger.clear_status_if(|status| {
|
||||||
|
matches!(status, crate::eval::DebuggerStatus::FunctionExit(..))
|
||||||
|
});
|
||||||
|
|
||||||
|
let result = self.eval_expr(scope, global, caches, lib, this_ptr, arg_expr, level);
|
||||||
|
|
||||||
|
// Restore function exit status
|
||||||
|
#[cfg(feature = "debugging")]
|
||||||
|
global.debugger.reset_status(reset_debugger);
|
||||||
|
|
||||||
|
Ok((result?, arg_expr.start_position()))
|
||||||
|
}
|
||||||
|
|
||||||
/// Call a dot method.
|
/// Call a dot method.
|
||||||
#[cfg(not(feature = "no_object"))]
|
#[cfg(not(feature = "no_object"))]
|
||||||
pub(crate) fn make_method_call(
|
pub(crate) fn make_method_call(
|
||||||
@ -757,7 +798,7 @@ impl Engine {
|
|||||||
// Recalculate hashes
|
// Recalculate hashes
|
||||||
let new_hash = calc_fn_hash(fn_name, args_len).into();
|
let new_hash = calc_fn_hash(fn_name, args_len).into();
|
||||||
// Arguments are passed as-is, adding the curried arguments
|
// Arguments are passed as-is, adding the curried arguments
|
||||||
let mut curry = FnArgsVec::with_capacity(fn_ptr.num_curried());
|
let mut curry = FnArgsVec::with_capacity(fn_ptr.curry().len());
|
||||||
curry.extend(fn_ptr.curry().iter().cloned());
|
curry.extend(fn_ptr.curry().iter().cloned());
|
||||||
let mut args = FnArgsVec::with_capacity(curry.len() + call_args.len());
|
let mut args = FnArgsVec::with_capacity(curry.len() + call_args.len());
|
||||||
args.extend(curry.iter_mut());
|
args.extend(curry.iter_mut());
|
||||||
@ -792,7 +833,7 @@ impl Engine {
|
|||||||
calc_fn_hash(fn_name, args_len + 1),
|
calc_fn_hash(fn_name, args_len + 1),
|
||||||
);
|
);
|
||||||
// Replace the first argument with the object pointer, adding the curried arguments
|
// Replace the first argument with the object pointer, adding the curried arguments
|
||||||
let mut curry = FnArgsVec::with_capacity(fn_ptr.num_curried());
|
let mut curry = FnArgsVec::with_capacity(fn_ptr.curry().len());
|
||||||
curry.extend(fn_ptr.curry().iter().cloned());
|
curry.extend(fn_ptr.curry().iter().cloned());
|
||||||
let mut args = FnArgsVec::with_capacity(curry.len() + call_args.len() + 1);
|
let mut args = FnArgsVec::with_capacity(curry.len() + call_args.len() + 1);
|
||||||
args.push(target.as_mut());
|
args.push(target.as_mut());
|
||||||
@ -887,42 +928,6 @@ impl Engine {
|
|||||||
Ok((result, updated))
|
Ok((result, updated))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluate an argument.
|
|
||||||
#[inline]
|
|
||||||
pub(crate) fn get_arg_value(
|
|
||||||
&self,
|
|
||||||
scope: &mut Scope,
|
|
||||||
global: &mut GlobalRuntimeState,
|
|
||||||
caches: &mut Caches,
|
|
||||||
lib: &[&Module],
|
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
|
||||||
arg_expr: &Expr,
|
|
||||||
level: usize,
|
|
||||||
) -> RhaiResultOf<(Dynamic, Position)> {
|
|
||||||
#[cfg(feature = "debugging")]
|
|
||||||
if self.debugger.is_some() {
|
|
||||||
if let Some(value) = arg_expr.get_literal_value() {
|
|
||||||
#[cfg(feature = "debugging")]
|
|
||||||
self.run_debugger(scope, global, lib, this_ptr, arg_expr, level)?;
|
|
||||||
return Ok((value, arg_expr.start_position()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do not match function exit for arguments
|
|
||||||
#[cfg(feature = "debugging")]
|
|
||||||
let reset_debugger = global.debugger.clear_status_if(|status| {
|
|
||||||
matches!(status, crate::eval::DebuggerStatus::FunctionExit(..))
|
|
||||||
});
|
|
||||||
|
|
||||||
let result = self.eval_expr(scope, global, caches, lib, this_ptr, arg_expr, level);
|
|
||||||
|
|
||||||
// Restore function exit status
|
|
||||||
#[cfg(feature = "debugging")]
|
|
||||||
global.debugger.reset_status(reset_debugger);
|
|
||||||
|
|
||||||
Ok((result?, arg_expr.start_position()))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Call a function in normal function-call style.
|
/// Call a function in normal function-call style.
|
||||||
pub(crate) fn make_function_call(
|
pub(crate) fn make_function_call(
|
||||||
&self,
|
&self,
|
||||||
|
@ -44,7 +44,7 @@
|
|||||||
//! # #[cfg(not(target_family = "wasm"))]
|
//! # #[cfg(not(target_family = "wasm"))]
|
||||||
//! #
|
//! #
|
||||||
//! // Evaluate the script, expecting a 'bool' result
|
//! // Evaluate the script, expecting a 'bool' result
|
||||||
//! let result = engine.eval_file::<bool>("my_script.rhai".into())?;
|
//! let result: bool = engine.eval_file("my_script.rhai".into())?;
|
||||||
//!
|
//!
|
||||||
//! assert_eq!(result, true);
|
//! assert_eq!(result, true);
|
||||||
//!
|
//!
|
||||||
|
@ -81,7 +81,7 @@ impl Ord for FnMetadata {
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct FuncInfo {
|
pub struct FuncInfo {
|
||||||
/// Function instance.
|
/// Function instance.
|
||||||
pub func: Shared<CallableFunction>,
|
pub func: CallableFunction,
|
||||||
/// Parameter types (if applicable).
|
/// Parameter types (if applicable).
|
||||||
pub param_types: StaticVec<TypeId>,
|
pub param_types: StaticVec<TypeId>,
|
||||||
/// Function metadata.
|
/// Function metadata.
|
||||||
@ -246,7 +246,7 @@ pub struct Module {
|
|||||||
functions: BTreeMap<u64, Box<FuncInfo>>,
|
functions: BTreeMap<u64, Box<FuncInfo>>,
|
||||||
/// Flattened collection of all external Rust functions, native or scripted.
|
/// Flattened collection of all external Rust functions, native or scripted.
|
||||||
/// including those in sub-modules.
|
/// including those in sub-modules.
|
||||||
all_functions: BTreeMap<u64, Shared<CallableFunction>>,
|
all_functions: BTreeMap<u64, CallableFunction>,
|
||||||
/// Iterator functions, keyed by the type producing the iterator.
|
/// Iterator functions, keyed by the type producing the iterator.
|
||||||
type_iterators: BTreeMap<TypeId, Shared<IteratorFn>>,
|
type_iterators: BTreeMap<TypeId, Shared<IteratorFn>>,
|
||||||
/// Flattened collection of iterator functions, including those in sub-modules.
|
/// Flattened collection of iterator functions, including those in sub-modules.
|
||||||
@ -1452,7 +1452,7 @@ impl Module {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub(crate) fn get_fn(&self, hash_fn: u64) -> Option<&CallableFunction> {
|
pub(crate) fn get_fn(&self, hash_fn: u64) -> Option<&CallableFunction> {
|
||||||
if !self.functions.is_empty() {
|
if !self.functions.is_empty() {
|
||||||
self.functions.get(&hash_fn).map(|f| f.func.as_ref())
|
self.functions.get(&hash_fn).map(|f| &f.func)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@ -1479,9 +1479,7 @@ impl Module {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub(crate) fn get_qualified_fn(&self, hash_qualified_fn: u64) -> Option<&CallableFunction> {
|
pub(crate) fn get_qualified_fn(&self, hash_qualified_fn: u64) -> Option<&CallableFunction> {
|
||||||
if !self.all_functions.is_empty() {
|
if !self.all_functions.is_empty() {
|
||||||
self.all_functions
|
self.all_functions.get(&hash_qualified_fn)
|
||||||
.get(&hash_qualified_fn)
|
|
||||||
.map(|f| f.as_ref())
|
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@ -1932,7 +1930,7 @@ impl Module {
|
|||||||
module: &'a Module,
|
module: &'a Module,
|
||||||
path: &mut Vec<&'a str>,
|
path: &mut Vec<&'a str>,
|
||||||
variables: &mut BTreeMap<u64, Dynamic>,
|
variables: &mut BTreeMap<u64, Dynamic>,
|
||||||
functions: &mut BTreeMap<u64, Shared<CallableFunction>>,
|
functions: &mut BTreeMap<u64, CallableFunction>,
|
||||||
type_iterators: &mut BTreeMap<TypeId, Shared<IteratorFn>>,
|
type_iterators: &mut BTreeMap<TypeId, Shared<IteratorFn>>,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
let mut contains_indexed_global_functions = false;
|
let mut contains_indexed_global_functions = false;
|
||||||
|
@ -639,15 +639,15 @@ pub mod array_functions {
|
|||||||
///
|
///
|
||||||
/// print(y); // prints "[0, 2, 6, 12, 20]"
|
/// print(y); // prints "[0, 2, 6, 12, 20]"
|
||||||
/// ```
|
/// ```
|
||||||
#[rhai_fn(return_raw, pure)]
|
#[rhai_fn(return_raw)]
|
||||||
pub fn map(ctx: NativeCallContext, array: &mut Array, mapper: FnPtr) -> RhaiResultOf<Array> {
|
pub fn map(ctx: NativeCallContext, array: Array, mapper: FnPtr) -> RhaiResultOf<Array> {
|
||||||
if array.is_empty() {
|
if array.is_empty() {
|
||||||
return Ok(array.clone());
|
return Ok(array);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut ar = Array::with_capacity(array.len());
|
let mut ar = Array::with_capacity(array.len());
|
||||||
|
|
||||||
for (i, item) in array.iter().enumerate() {
|
for (i, item) in array.into_iter().enumerate() {
|
||||||
ar.push(
|
ar.push(
|
||||||
mapper
|
mapper
|
||||||
.call_raw(&ctx, None, [item.clone()])
|
.call_raw(&ctx, None, [item.clone()])
|
||||||
@ -655,7 +655,7 @@ pub mod array_functions {
|
|||||||
ERR::ErrorFunctionNotFound(fn_sig, ..)
|
ERR::ErrorFunctionNotFound(fn_sig, ..)
|
||||||
if fn_sig.starts_with(mapper.fn_name()) =>
|
if fn_sig.starts_with(mapper.fn_name()) =>
|
||||||
{
|
{
|
||||||
mapper.call_raw(&ctx, None, [item.clone(), (i as INT).into()])
|
mapper.call_raw(&ctx, None, [item, (i as INT).into()])
|
||||||
}
|
}
|
||||||
_ => Err(err),
|
_ => Err(err),
|
||||||
})
|
})
|
||||||
@ -699,10 +699,10 @@ pub mod array_functions {
|
|||||||
///
|
///
|
||||||
/// print(y); // prints "[0, 2, 6, 12, 20]"
|
/// print(y); // prints "[0, 2, 6, 12, 20]"
|
||||||
/// ```
|
/// ```
|
||||||
#[rhai_fn(name = "map", return_raw, pure)]
|
#[rhai_fn(name = "map", return_raw)]
|
||||||
pub fn map_by_fn_name(
|
pub fn map_by_fn_name(
|
||||||
ctx: NativeCallContext,
|
ctx: NativeCallContext,
|
||||||
array: &mut Array,
|
array: Array,
|
||||||
mapper: &str,
|
mapper: &str,
|
||||||
) -> RhaiResultOf<Array> {
|
) -> RhaiResultOf<Array> {
|
||||||
map(ctx, array, FnPtr::new(mapper)?)
|
map(ctx, array, FnPtr::new(mapper)?)
|
||||||
@ -729,15 +729,15 @@ pub mod array_functions {
|
|||||||
///
|
///
|
||||||
/// print(y); // prints "[12, 20]"
|
/// print(y); // prints "[12, 20]"
|
||||||
/// ```
|
/// ```
|
||||||
#[rhai_fn(return_raw, pure)]
|
#[rhai_fn(return_raw)]
|
||||||
pub fn filter(ctx: NativeCallContext, array: &mut Array, filter: FnPtr) -> RhaiResultOf<Array> {
|
pub fn filter(ctx: NativeCallContext, array: Array, filter: FnPtr) -> RhaiResultOf<Array> {
|
||||||
if array.is_empty() {
|
if array.is_empty() {
|
||||||
return Ok(array.clone());
|
return Ok(array);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut ar = Array::new();
|
let mut ar = Array::new();
|
||||||
|
|
||||||
for (i, item) in array.iter().enumerate() {
|
for (i, item) in array.into_iter().enumerate() {
|
||||||
if filter
|
if filter
|
||||||
.call_raw(&ctx, None, [item.clone()])
|
.call_raw(&ctx, None, [item.clone()])
|
||||||
.or_else(|err| match *err {
|
.or_else(|err| match *err {
|
||||||
@ -759,7 +759,7 @@ pub mod array_functions {
|
|||||||
.as_bool()
|
.as_bool()
|
||||||
.unwrap_or(false)
|
.unwrap_or(false)
|
||||||
{
|
{
|
||||||
ar.push(item.clone());
|
ar.push(item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -790,10 +790,10 @@ pub mod array_functions {
|
|||||||
///
|
///
|
||||||
/// print(y); // prints "[12, 20]"
|
/// print(y); // prints "[12, 20]"
|
||||||
/// ```
|
/// ```
|
||||||
#[rhai_fn(name = "filter", return_raw, pure)]
|
#[rhai_fn(name = "filter", return_raw)]
|
||||||
pub fn filter_by_fn_name(
|
pub fn filter_by_fn_name(
|
||||||
ctx: NativeCallContext,
|
ctx: NativeCallContext,
|
||||||
array: &mut Array,
|
array: Array,
|
||||||
filter_func: &str,
|
filter_func: &str,
|
||||||
) -> RhaiResultOf<Array> {
|
) -> RhaiResultOf<Array> {
|
||||||
filter(ctx, array, FnPtr::new(filter_func)?)
|
filter(ctx, array, FnPtr::new(filter_func)?)
|
||||||
|
@ -311,10 +311,10 @@ mod float_functions {
|
|||||||
pub fn is_infinite(x: FLOAT) -> bool {
|
pub fn is_infinite(x: FLOAT) -> bool {
|
||||||
x.is_infinite()
|
x.is_infinite()
|
||||||
}
|
}
|
||||||
/// Return the integral part of the floating-point number.
|
/// Convert the floating-point number into an integer.
|
||||||
#[rhai_fn(name = "to_int", return_raw)]
|
#[rhai_fn(name = "to_int", return_raw)]
|
||||||
pub fn f32_to_int(x: f32) -> RhaiResultOf<INT> {
|
pub fn f32_to_int(x: f32) -> RhaiResultOf<INT> {
|
||||||
if cfg!(not(feature = "unchecked")) && x > (INT::MAX as f32) {
|
if cfg!(not(feature = "unchecked")) && (x > (INT::MAX as f32) || x < (INT::MIN as f32)) {
|
||||||
Err(
|
Err(
|
||||||
ERR::ErrorArithmetic(format!("Integer overflow: to_int({})", x), Position::NONE)
|
ERR::ErrorArithmetic(format!("Integer overflow: to_int({})", x), Position::NONE)
|
||||||
.into(),
|
.into(),
|
||||||
@ -323,10 +323,10 @@ mod float_functions {
|
|||||||
Ok(x.trunc() as INT)
|
Ok(x.trunc() as INT)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// Return the integral part of the floating-point number.
|
/// Convert the floating-point number into an integer.
|
||||||
#[rhai_fn(name = "to_int", return_raw)]
|
#[rhai_fn(name = "to_int", return_raw)]
|
||||||
pub fn f64_to_int(x: f64) -> RhaiResultOf<INT> {
|
pub fn f64_to_int(x: f64) -> RhaiResultOf<INT> {
|
||||||
if cfg!(not(feature = "unchecked")) && x > (INT::MAX as f64) {
|
if cfg!(not(feature = "unchecked")) && (x > (INT::MAX as f64) || x < (INT::MIN as f64)) {
|
||||||
Err(
|
Err(
|
||||||
ERR::ErrorArithmetic(format!("Integer overflow: to_int({})", x), Position::NONE)
|
ERR::ErrorArithmetic(format!("Integer overflow: to_int({})", x), Position::NONE)
|
||||||
.into(),
|
.into(),
|
||||||
@ -365,6 +365,7 @@ mod float_functions {
|
|||||||
#[cfg(feature = "decimal")]
|
#[cfg(feature = "decimal")]
|
||||||
#[export_module]
|
#[export_module]
|
||||||
mod decimal_functions {
|
mod decimal_functions {
|
||||||
|
use num_traits::ToPrimitive;
|
||||||
use rust_decimal::{
|
use rust_decimal::{
|
||||||
prelude::{FromStr, RoundingStrategy},
|
prelude::{FromStr, RoundingStrategy},
|
||||||
Decimal, MathematicalOps,
|
Decimal, MathematicalOps,
|
||||||
@ -553,6 +554,30 @@ mod decimal_functions {
|
|||||||
|
|
||||||
Ok(x.round_dp_with_strategy(digits as u32, RoundingStrategy::MidpointTowardZero))
|
Ok(x.round_dp_with_strategy(digits as u32, RoundingStrategy::MidpointTowardZero))
|
||||||
}
|
}
|
||||||
|
/// Convert the decimal number into an integer.
|
||||||
|
#[rhai_fn(return_raw)]
|
||||||
|
pub fn to_int(x: Decimal) -> RhaiResultOf<INT> {
|
||||||
|
let n = x.to_i64().and_then(|n| {
|
||||||
|
#[cfg(feature = "only_i32")]
|
||||||
|
return if n > (INT::MAX as i64) || n < (INT::MIN as i64) {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(n as i32)
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(not(feature = "only_i32"))]
|
||||||
|
return Some(n);
|
||||||
|
});
|
||||||
|
|
||||||
|
match n {
|
||||||
|
Some(n) => Ok(n),
|
||||||
|
_ => Err(ERR::ErrorArithmetic(
|
||||||
|
format!("Integer overflow: to_int({})", x),
|
||||||
|
Position::NONE,
|
||||||
|
)
|
||||||
|
.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
/// Return the integral part of the decimal number.
|
/// Return the integral part of the decimal number.
|
||||||
#[rhai_fn(name = "int", get = "int")]
|
#[rhai_fn(name = "int", get = "int")]
|
||||||
pub fn int(x: Decimal) -> Decimal {
|
pub fn int(x: Decimal) -> Decimal {
|
||||||
|
@ -195,12 +195,16 @@ mod print_debug_functions {
|
|||||||
result.push_str("#{");
|
result.push_str("#{");
|
||||||
|
|
||||||
map.iter_mut().enumerate().for_each(|(i, (k, v))| {
|
map.iter_mut().enumerate().for_each(|(i, (k, v))| {
|
||||||
result.push_str(&format!(
|
use std::fmt::Write;
|
||||||
|
|
||||||
|
write!(
|
||||||
|
result,
|
||||||
"{:?}: {}{}",
|
"{:?}: {}{}",
|
||||||
k,
|
k,
|
||||||
&print_with_func(FUNC_TO_DEBUG, &ctx, v),
|
&print_with_func(FUNC_TO_DEBUG, &ctx, v),
|
||||||
if i < len - 1 { ", " } else { "" }
|
if i < len - 1 { ", " } else { "" }
|
||||||
));
|
)
|
||||||
|
.unwrap();
|
||||||
});
|
});
|
||||||
|
|
||||||
result.push('}');
|
result.push('}');
|
||||||
|
275
src/parser.rs
275
src/parser.rs
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
use crate::api::custom_syntax::{markers::*, CustomSyntax};
|
use crate::api::custom_syntax::{markers::*, CustomSyntax};
|
||||||
use crate::api::events::VarDefInfo;
|
use crate::api::events::VarDefInfo;
|
||||||
use crate::api::options::LanguageOptions;
|
use crate::api::options::LangOptions;
|
||||||
use crate::ast::{
|
use crate::ast::{
|
||||||
ASTFlags, BinaryExpr, ConditionalStmtBlock, CustomExpr, Expr, FnCallExpr, FnCallHashes, Ident,
|
ASTFlags, BinaryExpr, ConditionalStmtBlock, CustomExpr, Expr, FnCallExpr, FnCallHashes, Ident,
|
||||||
OpAssignment, ScriptFnDef, Stmt, StmtBlock, StmtBlockContainer, SwitchCases, TryCatchBlock,
|
OpAssignment, ScriptFnDef, Stmt, StmtBlock, StmtBlockContainer, SwitchCases, TryCatchBlock,
|
||||||
@ -215,7 +215,7 @@ struct ParseSettings {
|
|||||||
/// Is the current position inside a loop?
|
/// Is the current position inside a loop?
|
||||||
is_breakable: bool,
|
is_breakable: bool,
|
||||||
/// Language options in effect (overrides Engine options).
|
/// Language options in effect (overrides Engine options).
|
||||||
options: LanguageOptions,
|
options: LangOptions,
|
||||||
/// Current expression nesting level.
|
/// Current expression nesting level.
|
||||||
level: usize,
|
level: usize,
|
||||||
/// Current position.
|
/// Current position.
|
||||||
@ -387,6 +387,7 @@ fn match_token(input: &mut TokenStream, token: Token) -> (bool, Position) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Parse a variable name.
|
/// Parse a variable name.
|
||||||
|
#[inline]
|
||||||
fn parse_var_name(input: &mut TokenStream) -> ParseResult<(SmartString, Position)> {
|
fn parse_var_name(input: &mut TokenStream) -> ParseResult<(SmartString, Position)> {
|
||||||
match input.next().expect(NEVER_ENDS) {
|
match input.next().expect(NEVER_ENDS) {
|
||||||
// Variable name
|
// Variable name
|
||||||
@ -403,6 +404,7 @@ fn parse_var_name(input: &mut TokenStream) -> ParseResult<(SmartString, Position
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Parse a symbol.
|
/// Parse a symbol.
|
||||||
|
#[inline]
|
||||||
fn parse_symbol(input: &mut TokenStream) -> ParseResult<(SmartString, Position)> {
|
fn parse_symbol(input: &mut TokenStream) -> ParseResult<(SmartString, Position)> {
|
||||||
match input.next().expect(NEVER_ENDS) {
|
match input.next().expect(NEVER_ENDS) {
|
||||||
// Symbol
|
// Symbol
|
||||||
@ -499,7 +501,10 @@ impl Engine {
|
|||||||
#[cfg(feature = "no_function")]
|
#[cfg(feature = "no_function")]
|
||||||
let relax = false;
|
let relax = false;
|
||||||
|
|
||||||
if !relax && settings.options.strict_var && index.is_none() {
|
if !relax
|
||||||
|
&& settings.options.contains(LangOptions::STRICT_VAR)
|
||||||
|
&& index.is_none()
|
||||||
|
{
|
||||||
return Err(PERR::ModuleUndefined(namespace.root().to_string())
|
return Err(PERR::ModuleUndefined(namespace.root().to_string())
|
||||||
.into_err(namespace.position()));
|
.into_err(namespace.position()));
|
||||||
}
|
}
|
||||||
@ -559,7 +564,10 @@ impl Engine {
|
|||||||
#[cfg(feature = "no_function")]
|
#[cfg(feature = "no_function")]
|
||||||
let relax = false;
|
let relax = false;
|
||||||
|
|
||||||
if !relax && settings.options.strict_var && index.is_none() {
|
if !relax
|
||||||
|
&& settings.options.contains(LangOptions::STRICT_VAR)
|
||||||
|
&& index.is_none()
|
||||||
|
{
|
||||||
return Err(PERR::ModuleUndefined(namespace.root().to_string())
|
return Err(PERR::ModuleUndefined(namespace.root().to_string())
|
||||||
.into_err(namespace.position()));
|
.into_err(namespace.position()));
|
||||||
}
|
}
|
||||||
@ -631,6 +639,7 @@ impl Engine {
|
|||||||
state: &mut ParseState,
|
state: &mut ParseState,
|
||||||
lib: &mut FnLib,
|
lib: &mut FnLib,
|
||||||
lhs: Expr,
|
lhs: Expr,
|
||||||
|
check_index_type: bool,
|
||||||
settings: ParseSettings,
|
settings: ParseSettings,
|
||||||
) -> ParseResult<Expr> {
|
) -> ParseResult<Expr> {
|
||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
@ -640,113 +649,100 @@ impl Engine {
|
|||||||
|
|
||||||
let idx_expr = self.parse_expr(input, state, lib, settings.level_up())?;
|
let idx_expr = self.parse_expr(input, state, lib, settings.level_up())?;
|
||||||
|
|
||||||
// Check type of indexing - must be integer or string
|
// Check types of indexing that cannot be overridden
|
||||||
match idx_expr {
|
// - arrays, maps, strings, bit-fields
|
||||||
Expr::IntegerConstant(.., pos) => match lhs {
|
match lhs {
|
||||||
Expr::IntegerConstant(..)
|
_ if !check_index_type => (),
|
||||||
| Expr::Array(..)
|
|
||||||
| Expr::StringConstant(..)
|
|
||||||
| Expr::InterpolatedString(..) => (),
|
|
||||||
|
|
||||||
Expr::Map(..) => {
|
Expr::Map(..) => match idx_expr {
|
||||||
|
// lhs[int]
|
||||||
|
Expr::IntegerConstant(..) => {
|
||||||
return Err(PERR::MalformedIndexExpr(
|
return Err(PERR::MalformedIndexExpr(
|
||||||
"Object map access expects string index, not a number".into(),
|
"Object map expects string index, not a number".into(),
|
||||||
)
|
|
||||||
.into_err(pos))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(feature = "no_float"))]
|
|
||||||
Expr::FloatConstant(..) => {
|
|
||||||
return Err(PERR::MalformedIndexExpr(
|
|
||||||
"Only arrays, object maps and strings can be indexed".into(),
|
|
||||||
)
|
|
||||||
.into_err(lhs.start_position()))
|
|
||||||
}
|
|
||||||
|
|
||||||
Expr::CharConstant(..)
|
|
||||||
| Expr::And(..)
|
|
||||||
| Expr::Or(..)
|
|
||||||
| Expr::BoolConstant(..)
|
|
||||||
| Expr::Unit(..) => {
|
|
||||||
return Err(PERR::MalformedIndexExpr(
|
|
||||||
"Only arrays, object maps and strings can be indexed".into(),
|
|
||||||
)
|
|
||||||
.into_err(lhs.start_position()))
|
|
||||||
}
|
|
||||||
|
|
||||||
_ => (),
|
|
||||||
},
|
|
||||||
|
|
||||||
// lhs[string]
|
|
||||||
Expr::StringConstant(..) | Expr::InterpolatedString(..) => match lhs {
|
|
||||||
Expr::Map(..) => (),
|
|
||||||
|
|
||||||
Expr::Array(..) | Expr::StringConstant(..) | Expr::InterpolatedString(..) => {
|
|
||||||
return Err(PERR::MalformedIndexExpr(
|
|
||||||
"Array or string expects numeric index, not a string".into(),
|
|
||||||
)
|
)
|
||||||
.into_err(idx_expr.start_position()))
|
.into_err(idx_expr.start_position()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// lhs[string]
|
||||||
|
Expr::StringConstant(..) | Expr::InterpolatedString(..) => (),
|
||||||
|
|
||||||
|
// lhs[float]
|
||||||
#[cfg(not(feature = "no_float"))]
|
#[cfg(not(feature = "no_float"))]
|
||||||
Expr::FloatConstant(..) => {
|
Expr::FloatConstant(..) => {
|
||||||
return Err(PERR::MalformedIndexExpr(
|
return Err(PERR::MalformedIndexExpr(
|
||||||
"Only arrays, object maps and strings can be indexed".into(),
|
"Object map expects string index, not a float".into(),
|
||||||
)
|
)
|
||||||
.into_err(lhs.start_position()))
|
.into_err(idx_expr.start_position()))
|
||||||
}
|
}
|
||||||
|
// lhs[char]
|
||||||
Expr::CharConstant(..)
|
Expr::CharConstant(..) => {
|
||||||
| Expr::And(..)
|
|
||||||
| Expr::Or(..)
|
|
||||||
| Expr::BoolConstant(..)
|
|
||||||
| Expr::Unit(..) => {
|
|
||||||
return Err(PERR::MalformedIndexExpr(
|
return Err(PERR::MalformedIndexExpr(
|
||||||
"Only arrays, object maps and strings can be indexed".into(),
|
"Object map expects string index, not a character".into(),
|
||||||
)
|
)
|
||||||
.into_err(lhs.start_position()))
|
.into_err(idx_expr.start_position()))
|
||||||
|
}
|
||||||
|
// lhs[()]
|
||||||
|
Expr::Unit(..) => {
|
||||||
|
return Err(PERR::MalformedIndexExpr(
|
||||||
|
"Object map expects string index, not ()".into(),
|
||||||
|
)
|
||||||
|
.into_err(idx_expr.start_position()))
|
||||||
|
}
|
||||||
|
// lhs[??? && ???], lhs[??? || ???], lhs[true], lhs[false]
|
||||||
|
Expr::And(..) | Expr::Or(..) | Expr::BoolConstant(..) => {
|
||||||
|
return Err(PERR::MalformedIndexExpr(
|
||||||
|
"Object map expects string index, not a boolean".into(),
|
||||||
|
)
|
||||||
|
.into_err(idx_expr.start_position()))
|
||||||
}
|
}
|
||||||
|
|
||||||
_ => (),
|
_ => (),
|
||||||
},
|
},
|
||||||
|
|
||||||
// lhs[float]
|
Expr::IntegerConstant(..)
|
||||||
#[cfg(not(feature = "no_float"))]
|
| Expr::Array(..)
|
||||||
x @ Expr::FloatConstant(..) => {
|
| Expr::StringConstant(..)
|
||||||
return Err(PERR::MalformedIndexExpr(
|
| Expr::InterpolatedString(..) => match idx_expr {
|
||||||
"Array access expects integer index, not a float".into(),
|
// lhs[int]
|
||||||
)
|
Expr::IntegerConstant(..) => (),
|
||||||
.into_err(x.start_position()))
|
|
||||||
}
|
// lhs[string]
|
||||||
// lhs[char]
|
Expr::StringConstant(..) | Expr::InterpolatedString(..) => {
|
||||||
x @ Expr::CharConstant(..) => {
|
return Err(PERR::MalformedIndexExpr(
|
||||||
return Err(PERR::MalformedIndexExpr(
|
"Array, string or bit-field expects numeric index, not a string".into(),
|
||||||
"Array access expects integer index, not a character".into(),
|
)
|
||||||
)
|
.into_err(idx_expr.start_position()))
|
||||||
.into_err(x.start_position()))
|
}
|
||||||
}
|
// lhs[float]
|
||||||
// lhs[()]
|
#[cfg(not(feature = "no_float"))]
|
||||||
x @ Expr::Unit(..) => {
|
Expr::FloatConstant(..) => {
|
||||||
return Err(PERR::MalformedIndexExpr(
|
return Err(PERR::MalformedIndexExpr(
|
||||||
"Array access expects integer index, not ()".into(),
|
"Array, string or bit-field expects integer index, not a float".into(),
|
||||||
)
|
)
|
||||||
.into_err(x.start_position()))
|
.into_err(idx_expr.start_position()))
|
||||||
}
|
}
|
||||||
// lhs[??? && ???], lhs[??? || ???]
|
// lhs[char]
|
||||||
x @ Expr::And(..) | x @ Expr::Or(..) => {
|
Expr::CharConstant(..) => {
|
||||||
return Err(PERR::MalformedIndexExpr(
|
return Err(PERR::MalformedIndexExpr(
|
||||||
"Array access expects integer index, not a boolean".into(),
|
"Array, string or bit-field expects integer index, not a character".into(),
|
||||||
)
|
)
|
||||||
.into_err(x.start_position()))
|
.into_err(idx_expr.start_position()))
|
||||||
}
|
}
|
||||||
// lhs[true], lhs[false]
|
// lhs[()]
|
||||||
x @ Expr::BoolConstant(..) => {
|
Expr::Unit(..) => {
|
||||||
return Err(PERR::MalformedIndexExpr(
|
return Err(PERR::MalformedIndexExpr(
|
||||||
"Array access expects integer index, not a boolean".into(),
|
"Array, string or bit-field expects integer index, not ()".into(),
|
||||||
)
|
)
|
||||||
.into_err(x.start_position()))
|
.into_err(idx_expr.start_position()))
|
||||||
}
|
}
|
||||||
// All other expressions
|
// lhs[??? && ???], lhs[??? || ???], lhs[true], lhs[false]
|
||||||
|
Expr::And(..) | Expr::Or(..) | Expr::BoolConstant(..) => {
|
||||||
|
return Err(PERR::MalformedIndexExpr(
|
||||||
|
"Array, string or bit-field expects integer index, not a boolean".into(),
|
||||||
|
)
|
||||||
|
.into_err(idx_expr.start_position()))
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
},
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -767,6 +763,7 @@ impl Engine {
|
|||||||
state,
|
state,
|
||||||
lib,
|
lib,
|
||||||
idx_expr,
|
idx_expr,
|
||||||
|
false,
|
||||||
settings.level_up(),
|
settings.level_up(),
|
||||||
)?;
|
)?;
|
||||||
// Indexing binds to right
|
// Indexing binds to right
|
||||||
@ -1243,7 +1240,7 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// { - block statement as expression
|
// { - block statement as expression
|
||||||
Token::LeftBrace if settings.options.allow_stmt_expr => {
|
Token::LeftBrace if settings.options.contains(LangOptions::STMT_EXPR) => {
|
||||||
match self.parse_block(input, state, lib, settings.level_up())? {
|
match self.parse_block(input, state, lib, settings.level_up())? {
|
||||||
block @ Stmt::Block(..) => Expr::Stmt(Box::new(block.into())),
|
block @ Stmt::Block(..) => Expr::Stmt(Box::new(block.into())),
|
||||||
stmt => unreachable!("Stmt::Block expected but gets {:?}", stmt),
|
stmt => unreachable!("Stmt::Block expected but gets {:?}", stmt),
|
||||||
@ -1254,19 +1251,21 @@ impl Engine {
|
|||||||
Token::LeftParen => self.parse_paren_expr(input, state, lib, settings.level_up())?,
|
Token::LeftParen => self.parse_paren_expr(input, state, lib, settings.level_up())?,
|
||||||
|
|
||||||
// If statement is allowed to act as expressions
|
// If statement is allowed to act as expressions
|
||||||
Token::If if settings.options.allow_if_expr => Expr::Stmt(Box::new(
|
Token::If if settings.options.contains(LangOptions::IF_EXPR) => Expr::Stmt(Box::new(
|
||||||
self.parse_if(input, state, lib, settings.level_up())?
|
self.parse_if(input, state, lib, settings.level_up())?
|
||||||
.into(),
|
.into(),
|
||||||
)),
|
)),
|
||||||
// Switch statement is allowed to act as expressions
|
// Switch statement is allowed to act as expressions
|
||||||
Token::Switch if settings.options.allow_switch_expr => Expr::Stmt(Box::new(
|
Token::Switch if settings.options.contains(LangOptions::SWITCH_EXPR) => {
|
||||||
self.parse_switch(input, state, lib, settings.level_up())?
|
Expr::Stmt(Box::new(
|
||||||
.into(),
|
self.parse_switch(input, state, lib, settings.level_up())?
|
||||||
)),
|
.into(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
// | ...
|
// | ...
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
Token::Pipe | Token::Or if settings.options.allow_anonymous_fn => {
|
Token::Pipe | Token::Or if settings.options.contains(LangOptions::ANON_FN) => {
|
||||||
let mut new_state =
|
let mut new_state =
|
||||||
ParseState::new(self, state.scope, state.tokenizer_control.clone());
|
ParseState::new(self, state.scope, state.tokenizer_control.clone());
|
||||||
|
|
||||||
@ -1275,6 +1274,17 @@ impl Engine {
|
|||||||
new_state.max_expr_depth = self.max_function_expr_depth();
|
new_state.max_expr_depth = self.max_function_expr_depth();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut options = self.options;
|
||||||
|
options.set(
|
||||||
|
LangOptions::STRICT_VAR,
|
||||||
|
if cfg!(feature = "no_closure") {
|
||||||
|
settings.options.contains(LangOptions::STRICT_VAR)
|
||||||
|
} else {
|
||||||
|
// A capturing closure can access variables not defined locally
|
||||||
|
false
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
let new_settings = ParseSettings {
|
let new_settings = ParseSettings {
|
||||||
is_global: false,
|
is_global: false,
|
||||||
is_function_scope: true,
|
is_function_scope: true,
|
||||||
@ -1282,15 +1292,7 @@ impl Engine {
|
|||||||
is_closure_scope: true,
|
is_closure_scope: true,
|
||||||
is_breakable: false,
|
is_breakable: false,
|
||||||
level: 0,
|
level: 0,
|
||||||
options: LanguageOptions {
|
options,
|
||||||
strict_var: if cfg!(feature = "no_closure") {
|
|
||||||
settings.options.strict_var
|
|
||||||
} else {
|
|
||||||
// A capturing closure can access variables not defined locally
|
|
||||||
false
|
|
||||||
},
|
|
||||||
..self.options
|
|
||||||
},
|
|
||||||
..settings
|
..settings
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -1301,7 +1303,7 @@ impl Engine {
|
|||||||
|crate::ast::Ident { name, pos }| {
|
|crate::ast::Ident { name, pos }| {
|
||||||
let index = state.access_var(name, *pos);
|
let index = state.access_var(name, *pos);
|
||||||
|
|
||||||
if settings.options.strict_var
|
if settings.options.contains(LangOptions::STRICT_VAR)
|
||||||
&& !settings.is_closure_scope
|
&& !settings.is_closure_scope
|
||||||
&& index.is_none()
|
&& index.is_none()
|
||||||
&& !state.scope.contains(name)
|
&& !state.scope.contains(name)
|
||||||
@ -1448,7 +1450,7 @@ impl Engine {
|
|||||||
_ => {
|
_ => {
|
||||||
let index = state.access_var(&s, settings.pos);
|
let index = state.access_var(&s, settings.pos);
|
||||||
|
|
||||||
if settings.options.strict_var
|
if settings.options.contains(LangOptions::STRICT_VAR)
|
||||||
&& index.is_none()
|
&& index.is_none()
|
||||||
&& !state.scope.contains(&s)
|
&& !state.scope.contains(&s)
|
||||||
{
|
{
|
||||||
@ -1628,7 +1630,7 @@ impl Engine {
|
|||||||
// Indexing
|
// Indexing
|
||||||
#[cfg(not(feature = "no_index"))]
|
#[cfg(not(feature = "no_index"))]
|
||||||
(expr, Token::LeftBracket) => {
|
(expr, Token::LeftBracket) => {
|
||||||
self.parse_index_chain(input, state, lib, expr, settings.level_up())?
|
self.parse_index_chain(input, state, lib, expr, true, settings.level_up())?
|
||||||
}
|
}
|
||||||
// Property access
|
// Property access
|
||||||
#[cfg(not(feature = "no_object"))]
|
#[cfg(not(feature = "no_object"))]
|
||||||
@ -1683,7 +1685,10 @@ impl Engine {
|
|||||||
#[cfg(feature = "no_function")]
|
#[cfg(feature = "no_function")]
|
||||||
let relax = false;
|
let relax = false;
|
||||||
|
|
||||||
if !relax && settings.options.strict_var && index.is_none() {
|
if !relax
|
||||||
|
&& settings.options.contains(LangOptions::STRICT_VAR)
|
||||||
|
&& index.is_none()
|
||||||
|
{
|
||||||
return Err(PERR::ModuleUndefined(namespace.root().to_string())
|
return Err(PERR::ModuleUndefined(namespace.root().to_string())
|
||||||
.into_err(namespace.position()));
|
.into_err(namespace.position()));
|
||||||
}
|
}
|
||||||
@ -2715,15 +2720,16 @@ impl Engine {
|
|||||||
nesting_level: level,
|
nesting_level: level,
|
||||||
will_shadow,
|
will_shadow,
|
||||||
};
|
};
|
||||||
let context = EvalContext {
|
let mut this_ptr = None;
|
||||||
engine: self,
|
let context = EvalContext::new(
|
||||||
scope: &mut state.stack,
|
self,
|
||||||
global: &mut state.global,
|
&mut state.stack,
|
||||||
caches: None,
|
&mut state.global,
|
||||||
lib: &[],
|
None,
|
||||||
this_ptr: &mut None,
|
&[],
|
||||||
|
&mut this_ptr,
|
||||||
level,
|
level,
|
||||||
};
|
);
|
||||||
|
|
||||||
match filter(false, info, context) {
|
match filter(false, info, context) {
|
||||||
Ok(true) => (),
|
Ok(true) => (),
|
||||||
@ -3080,6 +3086,12 @@ impl Engine {
|
|||||||
new_state.max_expr_depth = self.max_function_expr_depth();
|
new_state.max_expr_depth = self.max_function_expr_depth();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut options = self.options;
|
||||||
|
options.set(
|
||||||
|
LangOptions::STRICT_VAR,
|
||||||
|
settings.options.contains(LangOptions::STRICT_VAR),
|
||||||
|
);
|
||||||
|
|
||||||
let new_settings = ParseSettings {
|
let new_settings = ParseSettings {
|
||||||
is_global: false,
|
is_global: false,
|
||||||
is_function_scope: true,
|
is_function_scope: true,
|
||||||
@ -3087,10 +3099,7 @@ impl Engine {
|
|||||||
is_closure_scope: false,
|
is_closure_scope: false,
|
||||||
is_breakable: false,
|
is_breakable: false,
|
||||||
level: 0,
|
level: 0,
|
||||||
options: LanguageOptions {
|
options,
|
||||||
strict_var: settings.options.strict_var,
|
|
||||||
..self.options
|
|
||||||
},
|
|
||||||
pos,
|
pos,
|
||||||
..settings
|
..settings
|
||||||
};
|
};
|
||||||
@ -3549,6 +3558,11 @@ impl Engine {
|
|||||||
) -> ParseResult<AST> {
|
) -> ParseResult<AST> {
|
||||||
let mut functions = BTreeMap::new();
|
let mut functions = BTreeMap::new();
|
||||||
|
|
||||||
|
let mut options = self.options;
|
||||||
|
options.remove(LangOptions::IF_EXPR | LangOptions::SWITCH_EXPR | LangOptions::STMT_EXPR);
|
||||||
|
#[cfg(not(feature = "no_function"))]
|
||||||
|
options.remove(LangOptions::ANON_FN);
|
||||||
|
|
||||||
let settings = ParseSettings {
|
let settings = ParseSettings {
|
||||||
is_global: true,
|
is_global: true,
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
@ -3558,14 +3572,7 @@ impl Engine {
|
|||||||
is_closure_scope: false,
|
is_closure_scope: false,
|
||||||
is_breakable: false,
|
is_breakable: false,
|
||||||
level: 0,
|
level: 0,
|
||||||
options: LanguageOptions {
|
options,
|
||||||
allow_if_expr: false,
|
|
||||||
allow_switch_expr: false,
|
|
||||||
allow_stmt_expr: false,
|
|
||||||
#[cfg(not(feature = "no_function"))]
|
|
||||||
allow_anonymous_fn: false,
|
|
||||||
..self.options
|
|
||||||
},
|
|
||||||
pos: Position::NONE,
|
pos: Position::NONE,
|
||||||
};
|
};
|
||||||
let expr = self.parse_expr(input, state, &mut functions, settings)?;
|
let expr = self.parse_expr(input, state, &mut functions, settings)?;
|
||||||
|
@ -42,6 +42,8 @@ pub enum EvalAltResult {
|
|||||||
ErrorVariableNotFound(String, Position),
|
ErrorVariableNotFound(String, Position),
|
||||||
/// Access of an unknown object map property. Wrapped value is the property name.
|
/// Access of an unknown object map property. Wrapped value is the property name.
|
||||||
ErrorPropertyNotFound(String, Position),
|
ErrorPropertyNotFound(String, Position),
|
||||||
|
/// Access of an invalid index. Wrapped value is the index name.
|
||||||
|
ErrorIndexNotFound(Dynamic, Position),
|
||||||
/// Call to an unknown function. Wrapped value is the function signature.
|
/// Call to an unknown function. Wrapped value is the function signature.
|
||||||
ErrorFunctionNotFound(String, Position),
|
ErrorFunctionNotFound(String, Position),
|
||||||
/// Usage of an unknown [module][crate::Module]. Wrapped value is the [module][crate::Module] name.
|
/// Usage of an unknown [module][crate::Module]. Wrapped value is the [module][crate::Module] name.
|
||||||
@ -149,10 +151,11 @@ impl fmt::Display for EvalAltResult {
|
|||||||
}
|
}
|
||||||
Self::ErrorInModule(s, err, ..) => write!(f, "Error in module '{}' > {}", s, err)?,
|
Self::ErrorInModule(s, err, ..) => write!(f, "Error in module '{}' > {}", s, err)?,
|
||||||
|
|
||||||
Self::ErrorVariableExists(s, ..) => write!(f, "Variable is already defined: {}", s)?,
|
Self::ErrorVariableExists(s, ..) => write!(f, "Variable already defined: {}", s)?,
|
||||||
Self::ErrorForbiddenVariable(s, ..) => write!(f, "Forbidden variable name: {}", s)?,
|
Self::ErrorForbiddenVariable(s, ..) => write!(f, "Forbidden variable name: {}", s)?,
|
||||||
Self::ErrorVariableNotFound(s, ..) => write!(f, "Variable not found: {}", s)?,
|
Self::ErrorVariableNotFound(s, ..) => write!(f, "Variable not found: {}", s)?,
|
||||||
Self::ErrorPropertyNotFound(s, ..) => write!(f, "Property not found: {}", s)?,
|
Self::ErrorPropertyNotFound(s, ..) => write!(f, "Property not found: {}", s)?,
|
||||||
|
Self::ErrorIndexNotFound(s, ..) => write!(f, "Invalid index: {}", s)?,
|
||||||
Self::ErrorFunctionNotFound(s, ..) => write!(f, "Function not found: {}", s)?,
|
Self::ErrorFunctionNotFound(s, ..) => write!(f, "Function not found: {}", s)?,
|
||||||
Self::ErrorModuleNotFound(s, ..) => write!(f, "Module not found: {}", s)?,
|
Self::ErrorModuleNotFound(s, ..) => write!(f, "Module not found: {}", s)?,
|
||||||
Self::ErrorDataRace(s, ..) => {
|
Self::ErrorDataRace(s, ..) => {
|
||||||
@ -162,9 +165,9 @@ impl fmt::Display for EvalAltResult {
|
|||||||
"" => f.write_str("Malformed dot expression"),
|
"" => f.write_str("Malformed dot expression"),
|
||||||
s => f.write_str(s),
|
s => f.write_str(s),
|
||||||
}?,
|
}?,
|
||||||
Self::ErrorIndexingType(s, ..) => write!(f, "Indexer not registered: {}", s)?,
|
Self::ErrorIndexingType(s, ..) => write!(f, "Indexer unavailable: {}", s)?,
|
||||||
Self::ErrorUnboundThis(..) => f.write_str("'this' is not bound")?,
|
Self::ErrorUnboundThis(..) => f.write_str("'this' not bound")?,
|
||||||
Self::ErrorFor(..) => f.write_str("For loop expects a type that is iterable")?,
|
Self::ErrorFor(..) => f.write_str("For loop expects an iterable type")?,
|
||||||
Self::ErrorTooManyOperations(..) => f.write_str("Too many operations")?,
|
Self::ErrorTooManyOperations(..) => f.write_str("Too many operations")?,
|
||||||
Self::ErrorTooManyModules(..) => f.write_str("Too many modules imported")?,
|
Self::ErrorTooManyModules(..) => f.write_str("Too many modules imported")?,
|
||||||
Self::ErrorStackOverflow(..) => f.write_str("Stack overflow")?,
|
Self::ErrorStackOverflow(..) => f.write_str("Stack overflow")?,
|
||||||
@ -181,14 +184,14 @@ impl fmt::Display for EvalAltResult {
|
|||||||
|
|
||||||
Self::ErrorAssignmentToConstant(s, ..) => write!(f, "Cannot modify constant: {}", s)?,
|
Self::ErrorAssignmentToConstant(s, ..) => write!(f, "Cannot modify constant: {}", s)?,
|
||||||
Self::ErrorMismatchOutputType(e, a, ..) => match (a.as_str(), e.as_str()) {
|
Self::ErrorMismatchOutputType(e, a, ..) => match (a.as_str(), e.as_str()) {
|
||||||
("", e) => write!(f, "Output type is incorrect, expecting {}", e),
|
("", e) => write!(f, "Output type incorrect, expecting {}", e),
|
||||||
(a, "") => write!(f, "Output type is incorrect: {}", a),
|
(a, "") => write!(f, "Output type incorrect: {}", a),
|
||||||
(a, e) => write!(f, "Output type is incorrect: {} (expecting {})", a, e),
|
(a, e) => write!(f, "Output type incorrect: {} (expecting {})", a, e),
|
||||||
}?,
|
}?,
|
||||||
Self::ErrorMismatchDataType(e, a, ..) => match (a.as_str(), e.as_str()) {
|
Self::ErrorMismatchDataType(e, a, ..) => match (a.as_str(), e.as_str()) {
|
||||||
("", e) => write!(f, "Data type is incorrect, expecting {}", e),
|
("", e) => write!(f, "Data type incorrect, expecting {}", e),
|
||||||
(a, "") => write!(f, "Data type is incorrect: {}", a),
|
(a, "") => write!(f, "Data type incorrect: {}", a),
|
||||||
(a, e) => write!(f, "Data type is incorrect: {} (expecting {})", a, e),
|
(a, e) => write!(f, "Data type incorrect: {} (expecting {})", a, e),
|
||||||
}?,
|
}?,
|
||||||
Self::ErrorArithmetic(s, ..) => match s.as_str() {
|
Self::ErrorArithmetic(s, ..) => match s.as_str() {
|
||||||
"" => f.write_str("Arithmetic error"),
|
"" => f.write_str("Arithmetic error"),
|
||||||
@ -204,12 +207,12 @@ impl fmt::Display for EvalAltResult {
|
|||||||
0 => write!(f, "Array index {} out of bounds: array is empty", index),
|
0 => write!(f, "Array index {} out of bounds: array is empty", index),
|
||||||
1 => write!(
|
1 => write!(
|
||||||
f,
|
f,
|
||||||
"Array index {} out of bounds: only 1 element in the array",
|
"Array index {} out of bounds: only 1 element in array",
|
||||||
index
|
index
|
||||||
),
|
),
|
||||||
_ => write!(
|
_ => write!(
|
||||||
f,
|
f,
|
||||||
"Array index {} out of bounds: only {} elements in the array",
|
"Array index {} out of bounds: only {} elements in array",
|
||||||
index, max
|
index, max
|
||||||
),
|
),
|
||||||
}?,
|
}?,
|
||||||
@ -217,18 +220,18 @@ impl fmt::Display for EvalAltResult {
|
|||||||
0 => write!(f, "String index {} out of bounds: string is empty", index),
|
0 => write!(f, "String index {} out of bounds: string is empty", index),
|
||||||
1 => write!(
|
1 => write!(
|
||||||
f,
|
f,
|
||||||
"String index {} out of bounds: only 1 character in the string",
|
"String index {} out of bounds: only 1 character in string",
|
||||||
index
|
index
|
||||||
),
|
),
|
||||||
_ => write!(
|
_ => write!(
|
||||||
f,
|
f,
|
||||||
"String index {} out of bounds: only {} characters in the string",
|
"String index {} out of bounds: only {} characters in string",
|
||||||
index, max
|
index, max
|
||||||
),
|
),
|
||||||
}?,
|
}?,
|
||||||
Self::ErrorBitFieldBounds(max, index, ..) => write!(
|
Self::ErrorBitFieldBounds(max, index, ..) => write!(
|
||||||
f,
|
f,
|
||||||
"Bit-field index {} out of bounds: only {} bits in the bit-field",
|
"Bit-field index {} out of bounds: only {} bits in bit-field",
|
||||||
index, max
|
index, max
|
||||||
)?,
|
)?,
|
||||||
Self::ErrorDataTooLarge(typ, ..) => write!(f, "{} exceeds maximum limit", typ)?,
|
Self::ErrorDataTooLarge(typ, ..) => write!(f, "{} exceeds maximum limit", typ)?,
|
||||||
@ -291,6 +294,7 @@ impl EvalAltResult {
|
|||||||
| Self::ErrorForbiddenVariable(..)
|
| Self::ErrorForbiddenVariable(..)
|
||||||
| Self::ErrorVariableNotFound(..)
|
| Self::ErrorVariableNotFound(..)
|
||||||
| Self::ErrorPropertyNotFound(..)
|
| Self::ErrorPropertyNotFound(..)
|
||||||
|
| Self::ErrorIndexNotFound(..)
|
||||||
| Self::ErrorModuleNotFound(..)
|
| Self::ErrorModuleNotFound(..)
|
||||||
| Self::ErrorDataRace(..)
|
| Self::ErrorDataRace(..)
|
||||||
| Self::ErrorAssignmentToConstant(..)
|
| Self::ErrorAssignmentToConstant(..)
|
||||||
@ -388,6 +392,9 @@ impl EvalAltResult {
|
|||||||
| Self::ErrorAssignmentToConstant(v, ..) => {
|
| Self::ErrorAssignmentToConstant(v, ..) => {
|
||||||
map.insert("variable".into(), v.into());
|
map.insert("variable".into(), v.into());
|
||||||
}
|
}
|
||||||
|
Self::ErrorIndexNotFound(v, ..) => {
|
||||||
|
map.insert("index".into(), v.clone());
|
||||||
|
}
|
||||||
Self::ErrorModuleNotFound(m, ..) => {
|
Self::ErrorModuleNotFound(m, ..) => {
|
||||||
map.insert("module".into(), m.into());
|
map.insert("module".into(), m.into());
|
||||||
}
|
}
|
||||||
@ -448,6 +455,7 @@ impl EvalAltResult {
|
|||||||
| Self::ErrorForbiddenVariable(.., pos)
|
| Self::ErrorForbiddenVariable(.., pos)
|
||||||
| Self::ErrorVariableNotFound(.., pos)
|
| Self::ErrorVariableNotFound(.., pos)
|
||||||
| Self::ErrorPropertyNotFound(.., pos)
|
| Self::ErrorPropertyNotFound(.., pos)
|
||||||
|
| Self::ErrorIndexNotFound(.., pos)
|
||||||
| Self::ErrorModuleNotFound(.., pos)
|
| Self::ErrorModuleNotFound(.., pos)
|
||||||
| Self::ErrorDataRace(.., pos)
|
| Self::ErrorDataRace(.., pos)
|
||||||
| Self::ErrorAssignmentToConstant(.., pos)
|
| Self::ErrorAssignmentToConstant(.., pos)
|
||||||
@ -499,6 +507,7 @@ impl EvalAltResult {
|
|||||||
| Self::ErrorForbiddenVariable(.., pos)
|
| Self::ErrorForbiddenVariable(.., pos)
|
||||||
| Self::ErrorVariableNotFound(.., pos)
|
| Self::ErrorVariableNotFound(.., pos)
|
||||||
| Self::ErrorPropertyNotFound(.., pos)
|
| Self::ErrorPropertyNotFound(.., pos)
|
||||||
|
| Self::ErrorIndexNotFound(.., pos)
|
||||||
| Self::ErrorModuleNotFound(.., pos)
|
| Self::ErrorModuleNotFound(.., pos)
|
||||||
| Self::ErrorDataRace(.., pos)
|
| Self::ErrorDataRace(.., pos)
|
||||||
| Self::ErrorAssignmentToConstant(.., pos)
|
| Self::ErrorAssignmentToConstant(.., pos)
|
||||||
|
@ -88,12 +88,6 @@ impl FnPtr {
|
|||||||
pub fn is_curried(&self) -> bool {
|
pub fn is_curried(&self) -> bool {
|
||||||
!self.1.is_empty()
|
!self.1.is_empty()
|
||||||
}
|
}
|
||||||
/// Get the number of curried arguments.
|
|
||||||
#[inline(always)]
|
|
||||||
#[must_use]
|
|
||||||
pub fn num_curried(&self) -> usize {
|
|
||||||
self.1.len()
|
|
||||||
}
|
|
||||||
/// Does the function pointer refer to an anonymous function?
|
/// Does the function pointer refer to an anonymous function?
|
||||||
///
|
///
|
||||||
/// Not available under `no_function`.
|
/// Not available under `no_function`.
|
||||||
@ -219,8 +213,8 @@ impl FnPtr {
|
|||||||
let mut arg_values = arg_values.as_mut();
|
let mut arg_values = arg_values.as_mut();
|
||||||
let mut args_data;
|
let mut args_data;
|
||||||
|
|
||||||
if self.num_curried() > 0 {
|
if self.is_curried() {
|
||||||
args_data = StaticVec::with_capacity(self.num_curried() + arg_values.len());
|
args_data = StaticVec::with_capacity(self.curry().len() + arg_values.len());
|
||||||
args_data.extend(self.curry().iter().cloned());
|
args_data.extend(self.curry().iter().cloned());
|
||||||
args_data.extend(arg_values.iter_mut().map(mem::take));
|
args_data.extend(arg_values.iter_mut().map(mem::take));
|
||||||
arg_values = args_data.as_mut();
|
arg_values = args_data.as_mut();
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
#![cfg(not(feature = "no_index"))]
|
#![cfg(not(feature = "no_index"))]
|
||||||
use rhai::{Array, Dynamic, Engine, EvalAltResult, INT};
|
use rhai::{Array, Dynamic, Engine, EvalAltResult, ParseErrorType, INT};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_arrays() -> Result<(), Box<EvalAltResult>> {
|
fn test_arrays() -> Result<(), Box<EvalAltResult>> {
|
||||||
@ -172,6 +172,53 @@ fn test_arrays() -> Result<(), Box<EvalAltResult>> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_array_index_types() -> Result<(), Box<EvalAltResult>> {
|
||||||
|
let engine = Engine::new();
|
||||||
|
|
||||||
|
engine.compile("[1, 2, 3][0]['x']")?;
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
*engine
|
||||||
|
.compile("[1, 2, 3]['x']")
|
||||||
|
.expect_err("should error")
|
||||||
|
.0,
|
||||||
|
ParseErrorType::MalformedIndexExpr(..)
|
||||||
|
));
|
||||||
|
|
||||||
|
#[cfg(not(feature = "no_float"))]
|
||||||
|
assert!(matches!(
|
||||||
|
*engine
|
||||||
|
.compile("[1, 2, 3][123.456]")
|
||||||
|
.expect_err("should error")
|
||||||
|
.0,
|
||||||
|
ParseErrorType::MalformedIndexExpr(..)
|
||||||
|
));
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
*engine.compile("[1, 2, 3][()]").expect_err("should error").0,
|
||||||
|
ParseErrorType::MalformedIndexExpr(..)
|
||||||
|
));
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
*engine
|
||||||
|
.compile(r#"[1, 2, 3]["hello"]"#)
|
||||||
|
.expect_err("should error")
|
||||||
|
.0,
|
||||||
|
ParseErrorType::MalformedIndexExpr(..)
|
||||||
|
));
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
*engine
|
||||||
|
.compile("[1, 2, 3][true && false]")
|
||||||
|
.expect_err("should error")
|
||||||
|
.0,
|
||||||
|
ParseErrorType::MalformedIndexExpr(..)
|
||||||
|
));
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg(not(feature = "no_object"))]
|
#[cfg(not(feature = "no_object"))]
|
||||||
fn test_array_with_structs() -> Result<(), Box<EvalAltResult>> {
|
fn test_array_with_structs() -> Result<(), Box<EvalAltResult>> {
|
||||||
|
@ -57,10 +57,18 @@ fn test_debugger_state() -> Result<(), Box<EvalAltResult>> {
|
|||||||
},
|
},
|
||||||
|mut context, _, _, _, _| {
|
|mut context, _, _, _, _| {
|
||||||
// Print debugger state - which is an object map
|
// Print debugger state - which is an object map
|
||||||
println!("Current state = {}", context.tag());
|
println!(
|
||||||
|
"Current state = {}",
|
||||||
|
context.global_runtime_state_mut().debugger.state()
|
||||||
|
);
|
||||||
|
|
||||||
// Modify state
|
// Modify state
|
||||||
let mut state = context.tag_mut().write_lock::<Map>().unwrap();
|
let mut state = context
|
||||||
|
.global_runtime_state_mut()
|
||||||
|
.debugger
|
||||||
|
.state_mut()
|
||||||
|
.write_lock::<Map>()
|
||||||
|
.unwrap();
|
||||||
let hello = state.get("hello").unwrap().as_int().unwrap();
|
let hello = state.get("hello").unwrap().as_int().unwrap();
|
||||||
state.insert("hello".into(), (hello + 1).into());
|
state.insert("hello".into(), (hello + 1).into());
|
||||||
state.insert("foo".into(), true.into());
|
state.insert("foo".into(), true.into());
|
||||||
|
@ -314,14 +314,13 @@ fn test_get_set_indexer() -> Result<(), Box<EvalAltResult>> {
|
|||||||
.register_type_with_name::<MyMap>("MyMap")
|
.register_type_with_name::<MyMap>("MyMap")
|
||||||
.register_fn("new_map", || MyMap::new())
|
.register_fn("new_map", || MyMap::new())
|
||||||
.register_indexer_get_result(|map: &mut MyMap, index: &str| {
|
.register_indexer_get_result(|map: &mut MyMap, index: &str| {
|
||||||
map.get(index)
|
map.get(index).cloned().ok_or_else(|| {
|
||||||
.cloned()
|
EvalAltResult::ErrorIndexNotFound(index.into(), rhai::Position::NONE).into()
|
||||||
.ok_or_else(|| format!("Index `{}` not found!", index).into())
|
})
|
||||||
})
|
})
|
||||||
.register_indexer_set(|map: &mut MyMap, index: &str, value: INT| {
|
.register_indexer_set(|map: &mut MyMap, index: &str, value: INT| {
|
||||||
map.insert(index.to_string(), value);
|
map.insert(index.to_string(), value);
|
||||||
})
|
});
|
||||||
.register_fn("to_string", |map: &mut MyMap| format!("{:?}", map));
|
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
engine.eval::<INT>(
|
engine.eval::<INT>(
|
||||||
|
@ -124,6 +124,57 @@ fn test_map_prop() -> Result<(), Box<EvalAltResult>> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
#[test]
|
||||||
|
fn test_map_index_types() -> Result<(), Box<EvalAltResult>> {
|
||||||
|
let engine = Engine::new();
|
||||||
|
|
||||||
|
engine.compile(r#"#{a:1, b:2, c:3}["a"]['x']"#)?;
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
*engine
|
||||||
|
.compile("#{a:1, b:2, c:3}['x']")
|
||||||
|
.expect_err("should error")
|
||||||
|
.0,
|
||||||
|
ParseErrorType::MalformedIndexExpr(..)
|
||||||
|
));
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
*engine
|
||||||
|
.compile("#{a:1, b:2, c:3}[1]")
|
||||||
|
.expect_err("should error")
|
||||||
|
.0,
|
||||||
|
ParseErrorType::MalformedIndexExpr(..)
|
||||||
|
));
|
||||||
|
|
||||||
|
#[cfg(not(feature = "no_float"))]
|
||||||
|
assert!(matches!(
|
||||||
|
*engine
|
||||||
|
.compile("#{a:1, b:2, c:3}[123.456]")
|
||||||
|
.expect_err("should error")
|
||||||
|
.0,
|
||||||
|
ParseErrorType::MalformedIndexExpr(..)
|
||||||
|
));
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
*engine
|
||||||
|
.compile("#{a:1, b:2, c:3}[()]")
|
||||||
|
.expect_err("should error")
|
||||||
|
.0,
|
||||||
|
ParseErrorType::MalformedIndexExpr(..)
|
||||||
|
));
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
*engine
|
||||||
|
.compile("#{a:1, b:2, c:3}[true && false]")
|
||||||
|
.expect_err("should error")
|
||||||
|
.0,
|
||||||
|
ParseErrorType::MalformedIndexExpr(..)
|
||||||
|
));
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_map_assign() -> Result<(), Box<EvalAltResult>> {
|
fn test_map_assign() -> Result<(), Box<EvalAltResult>> {
|
||||||
let engine = Engine::new();
|
let engine = Engine::new();
|
||||||
|
@ -282,6 +282,23 @@ fn test_module_resolver() -> Result<(), Box<EvalAltResult>> {
|
|||||||
let result: INT = engine.call_fn(&mut Scope::new(), &ast, "foo", (2 as INT,))?;
|
let result: INT = engine.call_fn(&mut Scope::new(), &ast, "foo", (2 as INT,))?;
|
||||||
|
|
||||||
assert_eq!(result, 84);
|
assert_eq!(result, 84);
|
||||||
|
|
||||||
|
let mut ast2 = engine.compile("fn foo(x) { 42 }")?;
|
||||||
|
|
||||||
|
#[cfg(feature = "internals")]
|
||||||
|
let len = ast.resolver().unwrap().len();
|
||||||
|
|
||||||
|
ast2 += ast;
|
||||||
|
|
||||||
|
#[cfg(feature = "internals")]
|
||||||
|
{
|
||||||
|
assert!(ast2.resolver().is_some());
|
||||||
|
assert_eq!(ast2.resolver().unwrap().len(), len);
|
||||||
|
}
|
||||||
|
|
||||||
|
let result: INT = engine.call_fn(&mut Scope::new(), &ast2, "foo", (2 as INT,))?;
|
||||||
|
|
||||||
|
assert_eq!(result, 84);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
Loading…
Reference in New Issue
Block a user