Merge branch 'rhaiscript:main' into static_hash_finetune
This commit is contained in:
commit
ad080ff944
16
CHANGELOG.md
16
CHANGELOG.md
@ -4,6 +4,11 @@ Rhai Release Notes
|
|||||||
Version 1.11.0
|
Version 1.11.0
|
||||||
==============
|
==============
|
||||||
|
|
||||||
|
Speed Improvements
|
||||||
|
------------------
|
||||||
|
|
||||||
|
* Due to a code refactor, built-in operators for standard types now run even faster, in certain cases by 20-30%.
|
||||||
|
|
||||||
Bug fixes
|
Bug fixes
|
||||||
---------
|
---------
|
||||||
|
|
||||||
@ -12,10 +17,10 @@ Bug fixes
|
|||||||
* Functions marked `global` in `import`ed modules with no alias names now work properly.
|
* Functions marked `global` in `import`ed modules with no alias names now work properly.
|
||||||
* Incorrect loop optimizations that are too aggressive (e.g. unrolling a `do { ... } until true` with a `break` statement inside) and cause crashes are removed.
|
* Incorrect loop optimizations that are too aggressive (e.g. unrolling a `do { ... } until true` with a `break` statement inside) and cause crashes are removed.
|
||||||
|
|
||||||
Speed Improvements
|
Breaking changes
|
||||||
------------------
|
----------------
|
||||||
|
|
||||||
* Due to a code refactor, built-in operators for standard types now run even faster, in certain cases by 20-30%.
|
* `NativeCallContext::new` is completely deprecated and unimplemented (always panics) in favor of new API's.
|
||||||
|
|
||||||
New features
|
New features
|
||||||
------------
|
------------
|
||||||
@ -41,6 +46,11 @@ New features
|
|||||||
|
|
||||||
* `Scope` is now serializable and deserializable via `serde`.
|
* `Scope` is now serializable and deserializable via `serde`.
|
||||||
|
|
||||||
|
### Store and recreate `NativeCallContext`
|
||||||
|
|
||||||
|
* A convenient API is added to store a `NativeCallContext` into a new `NativeCallContextStore` type.
|
||||||
|
* This allows a `NativeCallContext` to be stored and recreated later on.
|
||||||
|
|
||||||
### Call native Rust functions in `NativeCallContext`
|
### Call native Rust functions in `NativeCallContext`
|
||||||
|
|
||||||
* `NativeCallContext::call_native_fn` is added to call registered native Rust functions only.
|
* `NativeCallContext::call_native_fn` is added to call registered native Rust functions only.
|
||||||
|
@ -4,8 +4,8 @@
|
|||||||
use crate::eval::{Caches, GlobalRuntimeState};
|
use crate::eval::{Caches, GlobalRuntimeState};
|
||||||
use crate::types::dynamic::Variant;
|
use crate::types::dynamic::Variant;
|
||||||
use crate::{
|
use crate::{
|
||||||
reify, Dynamic, Engine, FuncArgs, Position, RhaiResult, RhaiResultOf, Scope, StaticVec, AST,
|
reify, Dynamic, Engine, FuncArgs, Position, RhaiResult, RhaiResultOf, Scope, SharedModule,
|
||||||
ERR,
|
StaticVec, AST, ERR,
|
||||||
};
|
};
|
||||||
use std::any::{type_name, TypeId};
|
use std::any::{type_name, TypeId};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
@ -248,8 +248,10 @@ impl Engine {
|
|||||||
arg_values: &mut [Dynamic],
|
arg_values: &mut [Dynamic],
|
||||||
) -> RhaiResult {
|
) -> RhaiResult {
|
||||||
let statements = ast.statements();
|
let statements = ast.statements();
|
||||||
let lib = &[ast.as_ref()];
|
let lib = &[AsRef::<SharedModule>::as_ref(ast).clone()];
|
||||||
let mut this_ptr = this_ptr;
|
|
||||||
|
let mut no_this_ptr = Dynamic::NULL;
|
||||||
|
let this_ptr = this_ptr.unwrap_or(&mut no_this_ptr);
|
||||||
|
|
||||||
let orig_scope_len = scope.len();
|
let orig_scope_len = scope.len();
|
||||||
|
|
||||||
@ -258,9 +260,13 @@ impl Engine {
|
|||||||
&mut global.embedded_module_resolver,
|
&mut global.embedded_module_resolver,
|
||||||
ast.resolver().cloned(),
|
ast.resolver().cloned(),
|
||||||
);
|
);
|
||||||
|
#[cfg(not(feature = "no_module"))]
|
||||||
|
let global = &mut *crate::types::RestoreOnDrop::lock(global, move |g| {
|
||||||
|
g.embedded_module_resolver = orig_embedded_module_resolver
|
||||||
|
});
|
||||||
|
|
||||||
let result = if eval_ast && !statements.is_empty() {
|
let result = if eval_ast && !statements.is_empty() {
|
||||||
let r = self.eval_global_statements(global, caches, lib, 0, scope, statements);
|
let r = self.eval_global_statements(global, caches, lib, scope, statements);
|
||||||
|
|
||||||
if rewind_scope {
|
if rewind_scope {
|
||||||
scope.rewind(orig_scope_len);
|
scope.rewind(orig_scope_len);
|
||||||
@ -271,42 +277,34 @@ impl Engine {
|
|||||||
Ok(Dynamic::UNIT)
|
Ok(Dynamic::UNIT)
|
||||||
}
|
}
|
||||||
.and_then(|_| {
|
.and_then(|_| {
|
||||||
let mut args: StaticVec<_> = arg_values.iter_mut().collect();
|
let args = &mut arg_values.iter_mut().collect::<StaticVec<_>>();
|
||||||
|
|
||||||
// Check for data race.
|
// Check for data race.
|
||||||
#[cfg(not(feature = "no_closure"))]
|
#[cfg(not(feature = "no_closure"))]
|
||||||
crate::func::ensure_no_data_race(name, &args, false).map(|_| Dynamic::UNIT)?;
|
crate::func::ensure_no_data_race(name, args, false).map(|_| Dynamic::UNIT)?;
|
||||||
|
|
||||||
if let Some(fn_def) = ast.shared_lib().get_script_fn(name, args.len()) {
|
if let Some(fn_def) = ast.shared_lib().get_script_fn(name, args.len()) {
|
||||||
self.call_script_fn(
|
self.call_script_fn(
|
||||||
global,
|
global,
|
||||||
caches,
|
caches,
|
||||||
lib,
|
lib,
|
||||||
0,
|
|
||||||
scope,
|
scope,
|
||||||
&mut this_ptr,
|
this_ptr,
|
||||||
fn_def,
|
fn_def,
|
||||||
&mut args,
|
args,
|
||||||
rewind_scope,
|
rewind_scope,
|
||||||
Position::NONE,
|
Position::NONE,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
Err(ERR::ErrorFunctionNotFound(name.into(), Position::NONE).into())
|
Err(ERR::ErrorFunctionNotFound(name.into(), Position::NONE).into())
|
||||||
}
|
}
|
||||||
});
|
})?;
|
||||||
|
|
||||||
#[cfg(not(feature = "no_module"))]
|
|
||||||
{
|
|
||||||
global.embedded_module_resolver = orig_embedded_module_resolver;
|
|
||||||
}
|
|
||||||
|
|
||||||
let result = result?;
|
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
if self.debugger.is_some() {
|
if self.debugger.is_some() {
|
||||||
global.debugger.status = crate::eval::DebuggerStatus::Terminate;
|
global.debugger.status = crate::eval::DebuggerStatus::Terminate;
|
||||||
let node = &crate::ast::Stmt::Noop(Position::NONE);
|
let node = &crate::ast::Stmt::Noop(Position::NONE);
|
||||||
self.run_debugger(global, caches, lib, 0, scope, &mut this_ptr, node)?;
|
self.run_debugger(global, caches, lib, scope, this_ptr, node)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(result)
|
Ok(result)
|
||||||
|
@ -4,7 +4,7 @@ use crate::func::RegisterNativeFunction;
|
|||||||
use crate::types::dynamic::Variant;
|
use crate::types::dynamic::Variant;
|
||||||
use crate::{
|
use crate::{
|
||||||
Dynamic, Engine, EvalAltResult, FnPtr, Identifier, ImmutableString, NativeCallContext,
|
Dynamic, Engine, EvalAltResult, FnPtr, Identifier, ImmutableString, NativeCallContext,
|
||||||
Position, RhaiResult, RhaiResultOf, Scope, AST,
|
Position, RhaiResult, RhaiResultOf, Scope, SharedModule, AST,
|
||||||
};
|
};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
@ -354,6 +354,26 @@ impl Dynamic {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl NativeCallContext<'_> {
|
impl NativeCallContext<'_> {
|
||||||
|
/// Create a new [`NativeCallContext`].
|
||||||
|
///
|
||||||
|
/// # Unimplemented
|
||||||
|
///
|
||||||
|
/// This method is deprecated. It is no longer implemented and always panics.
|
||||||
|
///
|
||||||
|
/// Use [`FnPtr::call`] to call a function pointer directly.
|
||||||
|
///
|
||||||
|
/// This method will be removed in the next major version.
|
||||||
|
#[deprecated(
|
||||||
|
since = "1.3.0",
|
||||||
|
note = "use `FnPtr::call` to call a function pointer directly."
|
||||||
|
)]
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
pub fn new(engine: &Engine, fn_name: &str, lib: &[SharedModule]) -> Self {
|
||||||
|
unimplemented!("`NativeCallContext::new` is deprecated");
|
||||||
|
}
|
||||||
|
|
||||||
/// Call a function inside the call context.
|
/// Call a function inside the call context.
|
||||||
///
|
///
|
||||||
/// # Deprecated
|
/// # Deprecated
|
||||||
|
@ -188,17 +188,19 @@ impl Engine {
|
|||||||
let global = &mut GlobalRuntimeState::new(self);
|
let global = &mut GlobalRuntimeState::new(self);
|
||||||
let caches = &mut Caches::new();
|
let caches = &mut Caches::new();
|
||||||
|
|
||||||
let result = self.eval_ast_with_scope_raw(global, caches, 0, scope, ast)?;
|
let result = self.eval_ast_with_scope_raw(global, caches, scope, ast)?;
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
if self.debugger.is_some() {
|
if self.debugger.is_some() {
|
||||||
global.debugger.status = crate::eval::DebuggerStatus::Terminate;
|
global.debugger.status = crate::eval::DebuggerStatus::Terminate;
|
||||||
let lib = &[
|
let lib = &[
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
ast.as_ref(),
|
AsRef::<crate::SharedModule>::as_ref(ast).clone(),
|
||||||
];
|
];
|
||||||
|
let mut this = Dynamic::NULL;
|
||||||
let node = &crate::ast::Stmt::Noop(Position::NONE);
|
let node = &crate::ast::Stmt::Noop(Position::NONE);
|
||||||
self.run_debugger(global, caches, lib, 0, scope, &mut None, node)?;
|
|
||||||
|
self.run_debugger(global, caches, lib, scope, &mut this, node)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let typ = self.map_type_name(result.type_name());
|
let typ = self.map_type_name(result.type_name());
|
||||||
@ -214,7 +216,7 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
ast: &'a AST,
|
ast: &'a AST,
|
||||||
) -> RhaiResult {
|
) -> RhaiResult {
|
||||||
@ -225,6 +227,10 @@ impl Engine {
|
|||||||
&mut global.embedded_module_resolver,
|
&mut global.embedded_module_resolver,
|
||||||
ast.resolver().cloned(),
|
ast.resolver().cloned(),
|
||||||
);
|
);
|
||||||
|
#[cfg(not(feature = "no_module"))]
|
||||||
|
let global = &mut *crate::types::RestoreOnDrop::lock(global, move |g| {
|
||||||
|
g.embedded_module_resolver = orig_embedded_module_resolver
|
||||||
|
});
|
||||||
|
|
||||||
let statements = ast.statements();
|
let statements = ast.statements();
|
||||||
|
|
||||||
@ -232,23 +238,12 @@ impl Engine {
|
|||||||
return Ok(Dynamic::UNIT);
|
return Ok(Dynamic::UNIT);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut _lib = &[
|
let lib = &[
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
ast.as_ref(),
|
AsRef::<crate::SharedModule>::as_ref(ast).clone(),
|
||||||
][..];
|
];
|
||||||
#[cfg(not(feature = "no_function"))]
|
|
||||||
if !ast.has_functions() {
|
|
||||||
_lib = &[];
|
|
||||||
}
|
|
||||||
|
|
||||||
let result = self.eval_global_statements(global, caches, _lib, level, scope, statements);
|
self.eval_global_statements(global, caches, lib, scope, statements)
|
||||||
|
|
||||||
#[cfg(not(feature = "no_module"))]
|
|
||||||
{
|
|
||||||
global.embedded_module_resolver = orig_embedded_module_resolver;
|
|
||||||
}
|
|
||||||
|
|
||||||
result
|
|
||||||
}
|
}
|
||||||
/// _(internals)_ Evaluate a list of statements with no `this` pointer.
|
/// _(internals)_ Evaluate a list of statements with no `this` pointer.
|
||||||
/// Exported under the `internals` feature only.
|
/// Exported under the `internals` feature only.
|
||||||
@ -264,12 +259,12 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&crate::Module],
|
lib: &[crate::SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
statements: &[crate::ast::Stmt],
|
statements: &[crate::ast::Stmt],
|
||||||
) -> RhaiResult {
|
) -> RhaiResult {
|
||||||
self.eval_global_statements(global, caches, lib, level, scope, statements)
|
self.eval_global_statements(global, caches, lib, scope, statements)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -4,6 +4,7 @@ use crate::func::{FnCallArgs, RegisterNativeFunction, SendSync};
|
|||||||
use crate::types::dynamic::Variant;
|
use crate::types::dynamic::Variant;
|
||||||
use crate::{
|
use crate::{
|
||||||
Engine, FnAccess, FnNamespace, Identifier, Module, NativeCallContext, RhaiResultOf, Shared,
|
Engine, FnAccess, FnNamespace, Identifier, Module, NativeCallContext, RhaiResultOf, Shared,
|
||||||
|
SharedModule,
|
||||||
};
|
};
|
||||||
use std::any::{type_name, TypeId};
|
use std::any::{type_name, TypeId};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
@ -636,7 +637,7 @@ impl Engine {
|
|||||||
/// When searching for functions, modules loaded later are preferred. In other words, loaded
|
/// When searching for functions, modules loaded later are preferred. In other words, loaded
|
||||||
/// modules are searched in reverse order.
|
/// modules are searched in reverse order.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn register_global_module(&mut self, module: Shared<Module>) -> &mut Self {
|
pub fn register_global_module(&mut self, module: SharedModule) -> &mut Self {
|
||||||
// Insert the module into the front.
|
// Insert the module into the front.
|
||||||
// The first module is always the global namespace.
|
// The first module is always the global namespace.
|
||||||
self.global_modules.insert(1, module);
|
self.global_modules.insert(1, module);
|
||||||
@ -680,12 +681,12 @@ impl Engine {
|
|||||||
pub fn register_static_module(
|
pub fn register_static_module(
|
||||||
&mut self,
|
&mut self,
|
||||||
name: impl AsRef<str>,
|
name: impl AsRef<str>,
|
||||||
module: Shared<Module>,
|
module: SharedModule,
|
||||||
) -> &mut Self {
|
) -> &mut Self {
|
||||||
fn register_static_module_raw(
|
fn register_static_module_raw(
|
||||||
root: &mut std::collections::BTreeMap<Identifier, Shared<Module>>,
|
root: &mut std::collections::BTreeMap<Identifier, SharedModule>,
|
||||||
name: &str,
|
name: &str,
|
||||||
module: Shared<Module>,
|
module: SharedModule,
|
||||||
) {
|
) {
|
||||||
let separator = crate::tokenizer::Token::DoubleColon.syntax();
|
let separator = crate::tokenizer::Token::DoubleColon.syntax();
|
||||||
let separator = separator.as_ref();
|
let separator = separator.as_ref();
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
use crate::eval::{Caches, GlobalRuntimeState};
|
use crate::eval::{Caches, GlobalRuntimeState};
|
||||||
use crate::parser::ParseState;
|
use crate::parser::ParseState;
|
||||||
use crate::{Engine, Module, RhaiResultOf, Scope, AST};
|
use crate::{Engine, RhaiResultOf, Scope, SharedModule, AST};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
|
|
||||||
@ -122,16 +122,16 @@ impl Engine {
|
|||||||
|
|
||||||
let statements = ast.statements();
|
let statements = ast.statements();
|
||||||
if !statements.is_empty() {
|
if !statements.is_empty() {
|
||||||
let lib = [
|
let lib: &[SharedModule] = &[
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
ast.as_ref(),
|
AsRef::<SharedModule>::as_ref(ast).clone(),
|
||||||
];
|
];
|
||||||
let lib = if lib.first().map_or(true, |m: &&Module| m.is_empty()) {
|
let lib = if lib.first().map_or(true, |m| m.is_empty()) {
|
||||||
&lib[0..0]
|
&[][..]
|
||||||
} else {
|
} else {
|
||||||
&lib
|
&lib
|
||||||
};
|
};
|
||||||
self.eval_global_statements(global, caches, lib, 0, scope, statements)?;
|
self.eval_global_statements(global, caches, lib, scope, statements)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
@ -139,10 +139,11 @@ impl Engine {
|
|||||||
global.debugger.status = crate::eval::DebuggerStatus::Terminate;
|
global.debugger.status = crate::eval::DebuggerStatus::Terminate;
|
||||||
let lib = &[
|
let lib = &[
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
ast.as_ref(),
|
AsRef::<crate::SharedModule>::as_ref(ast).clone(),
|
||||||
];
|
];
|
||||||
|
let mut this = crate::Dynamic::NULL;
|
||||||
let node = &crate::ast::Stmt::Noop(crate::Position::NONE);
|
let node = &crate::ast::Stmt::Noop(crate::Position::NONE);
|
||||||
self.run_debugger(global, caches, lib, 0, scope, &mut None, node)?;
|
self.run_debugger(global, caches, lib, scope, &mut this, node)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -28,7 +28,7 @@ pub struct AST {
|
|||||||
body: StmtBlock,
|
body: StmtBlock,
|
||||||
/// Script-defined functions.
|
/// Script-defined functions.
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
lib: crate::Shared<crate::Module>,
|
lib: crate::SharedModule,
|
||||||
/// Embedded module resolver, if any.
|
/// Embedded module resolver, if any.
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
resolver: Option<crate::Shared<crate::module::resolvers::StaticModuleResolver>>,
|
resolver: Option<crate::Shared<crate::module::resolvers::StaticModuleResolver>>,
|
||||||
@ -74,7 +74,7 @@ impl AST {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub(crate) fn new(
|
pub(crate) fn new(
|
||||||
statements: impl IntoIterator<Item = Stmt>,
|
statements: impl IntoIterator<Item = Stmt>,
|
||||||
#[cfg(not(feature = "no_function"))] functions: impl Into<crate::Shared<crate::Module>>,
|
#[cfg(not(feature = "no_function"))] functions: impl Into<crate::SharedModule>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
source: None,
|
source: None,
|
||||||
@ -94,7 +94,7 @@ impl AST {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn new(
|
pub fn new(
|
||||||
statements: impl IntoIterator<Item = Stmt>,
|
statements: impl IntoIterator<Item = Stmt>,
|
||||||
#[cfg(not(feature = "no_function"))] functions: impl Into<crate::Shared<crate::Module>>,
|
#[cfg(not(feature = "no_function"))] functions: impl Into<crate::SharedModule>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
source: None,
|
source: None,
|
||||||
@ -113,7 +113,7 @@ impl AST {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub(crate) fn new_with_source(
|
pub(crate) fn new_with_source(
|
||||||
statements: impl IntoIterator<Item = Stmt>,
|
statements: impl IntoIterator<Item = Stmt>,
|
||||||
#[cfg(not(feature = "no_function"))] functions: impl Into<crate::Shared<crate::Module>>,
|
#[cfg(not(feature = "no_function"))] functions: impl Into<crate::SharedModule>,
|
||||||
source: impl Into<ImmutableString>,
|
source: impl Into<ImmutableString>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let mut ast = Self::new(
|
let mut ast = Self::new(
|
||||||
@ -131,7 +131,7 @@ impl AST {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn new_with_source(
|
pub fn new_with_source(
|
||||||
statements: impl IntoIterator<Item = Stmt>,
|
statements: impl IntoIterator<Item = Stmt>,
|
||||||
#[cfg(not(feature = "no_function"))] functions: impl Into<crate::Shared<crate::Module>>,
|
#[cfg(not(feature = "no_function"))] functions: impl Into<crate::SharedModule>,
|
||||||
source: impl Into<ImmutableString>,
|
source: impl Into<ImmutableString>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let mut ast = Self::new(
|
let mut ast = Self::new(
|
||||||
@ -267,7 +267,7 @@ impl AST {
|
|||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub(crate) const fn shared_lib(&self) -> &crate::Shared<crate::Module> {
|
pub(crate) const fn shared_lib(&self) -> &crate::SharedModule {
|
||||||
&self.lib
|
&self.lib
|
||||||
}
|
}
|
||||||
/// _(internals)_ Get the internal shared [`Module`][crate::Module] containing all script-defined functions.
|
/// _(internals)_ Get the internal shared [`Module`][crate::Module] containing all script-defined functions.
|
||||||
@ -278,7 +278,7 @@ impl AST {
|
|||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn shared_lib(&self) -> &crate::Shared<crate::Module> {
|
pub const fn shared_lib(&self) -> &crate::SharedModule {
|
||||||
&self.lib
|
&self.lib
|
||||||
}
|
}
|
||||||
/// Get the embedded [module resolver][crate::ModuleResolver].
|
/// Get the embedded [module resolver][crate::ModuleResolver].
|
||||||
@ -957,19 +957,19 @@ impl AsRef<crate::Module> for AST {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
impl Borrow<crate::Shared<crate::Module>> for AST {
|
impl Borrow<crate::SharedModule> for AST {
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
fn borrow(&self) -> &crate::Shared<crate::Module> {
|
fn borrow(&self) -> &crate::SharedModule {
|
||||||
self.shared_lib()
|
self.shared_lib()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
impl AsRef<crate::Shared<crate::Module>> for AST {
|
impl AsRef<crate::SharedModule> for AST {
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
fn as_ref(&self) -> &crate::Shared<crate::Module> {
|
fn as_ref(&self) -> &crate::SharedModule {
|
||||||
self.shared_lib()
|
self.shared_lib()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -20,9 +20,9 @@ use std::{fmt, hash::Hash};
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct EncapsulatedEnviron {
|
pub struct EncapsulatedEnviron {
|
||||||
/// Functions defined within the same [`AST`][crate::AST].
|
/// Functions defined within the same [`AST`][crate::AST].
|
||||||
pub lib: crate::Shared<crate::Module>,
|
pub lib: crate::SharedModule,
|
||||||
/// Imported [modules][crate::Module].
|
/// Imported [modules][crate::Module].
|
||||||
pub imports: Box<[(ImmutableString, crate::Shared<crate::Module>)]>,
|
pub imports: Box<[(ImmutableString, crate::SharedModule)]>,
|
||||||
/// Globally-defined constants.
|
/// Globally-defined constants.
|
||||||
pub constants: Option<crate::eval::GlobalConstants>,
|
pub constants: Option<crate::eval::GlobalConstants>,
|
||||||
}
|
}
|
||||||
|
@ -9,7 +9,8 @@ use crate::packages::{Package, StandardPackage};
|
|||||||
use crate::tokenizer::Token;
|
use crate::tokenizer::Token;
|
||||||
use crate::types::StringsInterner;
|
use crate::types::StringsInterner;
|
||||||
use crate::{
|
use crate::{
|
||||||
Dynamic, Identifier, ImmutableString, Locked, Module, OptimizationLevel, Shared, StaticVec,
|
Dynamic, Identifier, ImmutableString, Locked, Module, OptimizationLevel, SharedModule,
|
||||||
|
StaticVec,
|
||||||
};
|
};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
@ -91,10 +92,10 @@ pub const OP_INCLUSIVE_RANGE: &str = Token::InclusiveRange.literal_syntax();
|
|||||||
/// ```
|
/// ```
|
||||||
pub struct Engine {
|
pub struct Engine {
|
||||||
/// A collection of all modules loaded into the global namespace of the Engine.
|
/// A collection of all modules loaded into the global namespace of the Engine.
|
||||||
pub(crate) global_modules: StaticVec<Shared<Module>>,
|
pub(crate) global_modules: StaticVec<SharedModule>,
|
||||||
/// A collection of all sub-modules directly loaded into the Engine.
|
/// A collection of all sub-modules directly loaded into the Engine.
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
pub(crate) global_sub_modules: std::collections::BTreeMap<Identifier, Shared<Module>>,
|
pub(crate) global_sub_modules: std::collections::BTreeMap<Identifier, SharedModule>,
|
||||||
|
|
||||||
/// A module resolution service.
|
/// A module resolution service.
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
|
@ -3,7 +3,6 @@
|
|||||||
use crate::func::{CallableFunction, StraightHashMap};
|
use crate::func::{CallableFunction, StraightHashMap};
|
||||||
use crate::types::BloomFilterU64;
|
use crate::types::BloomFilterU64;
|
||||||
use crate::{ImmutableString, StaticVec};
|
use crate::{ImmutableString, StaticVec};
|
||||||
use std::marker::PhantomData;
|
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
|
|
||||||
@ -45,21 +44,18 @@ impl FnResolutionCache {
|
|||||||
/// The following caches are contained inside this type:
|
/// The following caches are contained inside this type:
|
||||||
/// * A stack of [function resolution caches][FnResolutionCache]
|
/// * A stack of [function resolution caches][FnResolutionCache]
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Caches<'a> {
|
pub struct Caches {
|
||||||
/// Stack of [function resolution caches][FnResolutionCache].
|
/// Stack of [function resolution caches][FnResolutionCache].
|
||||||
stack: StaticVec<FnResolutionCache>,
|
stack: StaticVec<FnResolutionCache>,
|
||||||
/// Take care of the lifetime parameter.
|
|
||||||
dummy: PhantomData<&'a ()>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Caches<'_> {
|
impl Caches {
|
||||||
/// Create an empty [`Caches`].
|
/// Create an empty [`Caches`].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn new() -> Self {
|
pub const fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
stack: StaticVec::new_const(),
|
stack: StaticVec::new_const(),
|
||||||
dummy: PhantomData,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// Get the number of function resolution cache(s) in the stack.
|
/// Get the number of function resolution cache(s) in the stack.
|
||||||
|
@ -4,7 +4,10 @@
|
|||||||
use super::{Caches, GlobalRuntimeState, Target};
|
use super::{Caches, GlobalRuntimeState, Target};
|
||||||
use crate::ast::{ASTFlags, Expr, OpAssignment};
|
use crate::ast::{ASTFlags, Expr, OpAssignment};
|
||||||
use crate::types::dynamic::Union;
|
use crate::types::dynamic::Union;
|
||||||
use crate::{Dynamic, Engine, FnArgsVec, Module, Position, RhaiResult, RhaiResultOf, Scope, ERR};
|
use crate::types::RestoreOnDrop;
|
||||||
|
use crate::{
|
||||||
|
Dynamic, Engine, FnArgsVec, Position, RhaiResult, RhaiResultOf, Scope, SharedModule, ERR,
|
||||||
|
};
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
@ -40,9 +43,8 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
this_ptr: &mut Dynamic,
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
|
||||||
target: &mut Target,
|
target: &mut Target,
|
||||||
root: (&str, Position),
|
root: (&str, Position),
|
||||||
_parent: &Expr,
|
_parent: &Expr,
|
||||||
@ -73,7 +75,7 @@ impl Engine {
|
|||||||
if !parent_options.contains(ASTFlags::BREAK) =>
|
if !parent_options.contains(ASTFlags::BREAK) =>
|
||||||
{
|
{
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
self.run_debugger(global, caches, lib, level, scope, this_ptr, _parent)?;
|
self.run_debugger(global, caches, lib, scope, this_ptr, _parent)?;
|
||||||
|
|
||||||
let idx_val = &mut idx_values.pop().unwrap();
|
let idx_val = &mut idx_values.pop().unwrap();
|
||||||
let mut idx_val_for_setter = idx_val.clone();
|
let mut idx_val_for_setter = idx_val.clone();
|
||||||
@ -82,13 +84,13 @@ impl Engine {
|
|||||||
|
|
||||||
let (try_setter, result) = {
|
let (try_setter, result) = {
|
||||||
let mut obj = self.get_indexed_mut(
|
let mut obj = self.get_indexed_mut(
|
||||||
global, caches, lib, level, target, idx_val, idx_pos, false, true,
|
global, caches, lib, target, idx_val, idx_pos, false, true,
|
||||||
)?;
|
)?;
|
||||||
let is_obj_temp_val = obj.is_temp_value();
|
let is_obj_temp_val = obj.is_temp_value();
|
||||||
let obj_ptr = &mut obj;
|
let obj_ptr = &mut obj;
|
||||||
|
|
||||||
match self.eval_dot_index_chain_helper(
|
match self.eval_dot_index_chain_helper(
|
||||||
global, caches, lib, level, this_ptr, obj_ptr, root, rhs, *options,
|
global, caches, lib, this_ptr, obj_ptr, root, rhs, *options,
|
||||||
&x.rhs, idx_values, rhs_chain, new_val,
|
&x.rhs, idx_values, rhs_chain, new_val,
|
||||||
) {
|
) {
|
||||||
Ok((result, true)) if is_obj_temp_val => {
|
Ok((result, true)) if is_obj_temp_val => {
|
||||||
@ -104,7 +106,7 @@ impl Engine {
|
|||||||
let idx = &mut idx_val_for_setter;
|
let idx = &mut idx_val_for_setter;
|
||||||
let new_val = &mut new_val;
|
let new_val = &mut new_val;
|
||||||
self.call_indexer_set(
|
self.call_indexer_set(
|
||||||
global, caches, lib, level, target, idx, new_val, is_ref_mut,
|
global, caches, lib, target, idx, new_val, is_ref_mut,
|
||||||
)
|
)
|
||||||
.or_else(|e| match *e {
|
.or_else(|e| match *e {
|
||||||
ERR::ErrorIndexingType(..) => Ok((Dynamic::UNIT, false)),
|
ERR::ErrorIndexingType(..) => Ok((Dynamic::UNIT, false)),
|
||||||
@ -117,19 +119,19 @@ impl Engine {
|
|||||||
// xxx[rhs] op= new_val
|
// xxx[rhs] op= new_val
|
||||||
_ if new_val.is_some() => {
|
_ if new_val.is_some() => {
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
self.run_debugger(global, caches, lib, level, scope, this_ptr, _parent)?;
|
self.run_debugger(global, caches, lib, scope, this_ptr, _parent)?;
|
||||||
|
|
||||||
let (new_val, op_info) = new_val.take().expect("`Some`");
|
let (new_val, op_info) = new_val.take().expect("`Some`");
|
||||||
let idx_val = &mut idx_values.pop().unwrap();
|
let idx_val = &mut idx_values.pop().unwrap();
|
||||||
let idx = &mut idx_val.clone();
|
let idx = &mut idx_val.clone();
|
||||||
|
|
||||||
let try_setter = match self.get_indexed_mut(
|
let try_setter = match self
|
||||||
global, caches, lib, level, target, idx, pos, true, false,
|
.get_indexed_mut(global, caches, lib, target, idx, pos, true, false)
|
||||||
) {
|
{
|
||||||
// Indexed value is not a temp value - update directly
|
// Indexed value is not a temp value - update directly
|
||||||
Ok(ref mut obj_ptr) => {
|
Ok(ref mut obj_ptr) => {
|
||||||
self.eval_op_assignment(
|
self.eval_op_assignment(
|
||||||
global, caches, lib, level, op_info, obj_ptr, root, new_val,
|
global, caches, lib, op_info, obj_ptr, root, new_val,
|
||||||
)?;
|
)?;
|
||||||
self.check_data_size(obj_ptr, op_info.pos)?;
|
self.check_data_size(obj_ptr, op_info.pos)?;
|
||||||
None
|
None
|
||||||
@ -148,13 +150,12 @@ impl Engine {
|
|||||||
|
|
||||||
// Call the index getter to get the current value
|
// Call the index getter to get the current value
|
||||||
if let Ok(val) =
|
if let Ok(val) =
|
||||||
self.call_indexer_get(global, caches, lib, level, target, idx)
|
self.call_indexer_get(global, caches, lib, target, idx)
|
||||||
{
|
{
|
||||||
let mut val = val.into();
|
let mut val = val.into();
|
||||||
// Run the op-assignment
|
// Run the op-assignment
|
||||||
self.eval_op_assignment(
|
self.eval_op_assignment(
|
||||||
global, caches, lib, level, op_info, &mut val, root,
|
global, caches, lib, op_info, &mut val, root, new_val,
|
||||||
new_val,
|
|
||||||
)?;
|
)?;
|
||||||
// Replace new value
|
// Replace new value
|
||||||
new_val = val.take_or_clone();
|
new_val = val.take_or_clone();
|
||||||
@ -166,7 +167,7 @@ impl Engine {
|
|||||||
let new_val = &mut new_val;
|
let new_val = &mut new_val;
|
||||||
|
|
||||||
self.call_indexer_set(
|
self.call_indexer_set(
|
||||||
global, caches, lib, level, target, idx_val, new_val, is_ref_mut,
|
global, caches, lib, target, idx_val, new_val, is_ref_mut,
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -175,13 +176,11 @@ impl Engine {
|
|||||||
// xxx[rhs]
|
// xxx[rhs]
|
||||||
_ => {
|
_ => {
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
self.run_debugger(global, caches, lib, level, scope, this_ptr, _parent)?;
|
self.run_debugger(global, caches, lib, scope, this_ptr, _parent)?;
|
||||||
|
|
||||||
let idx_val = &mut idx_values.pop().unwrap();
|
let idx_val = &mut idx_values.pop().unwrap();
|
||||||
|
|
||||||
self.get_indexed_mut(
|
self.get_indexed_mut(global, caches, lib, target, idx_val, pos, false, true)
|
||||||
global, caches, lib, level, target, idx_val, pos, false, true,
|
|
||||||
)
|
|
||||||
.map(|v| (v.take_or_clone(), false))
|
.map(|v| (v.take_or_clone(), false))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -198,29 +197,28 @@ impl Engine {
|
|||||||
// xxx.fn_name(arg_expr_list)
|
// xxx.fn_name(arg_expr_list)
|
||||||
Expr::MethodCall(x, pos) if !x.is_qualified() && new_val.is_none() => {
|
Expr::MethodCall(x, pos) if !x.is_qualified() && new_val.is_none() => {
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
let reset_debugger = self.run_debugger_with_reset(
|
let reset = self
|
||||||
global, caches, lib, level, scope, this_ptr, rhs,
|
.run_debugger_with_reset(global, caches, lib, scope, this_ptr, rhs)?;
|
||||||
)?;
|
#[cfg(feature = "debugging")]
|
||||||
|
let global = &mut *RestoreOnDrop::lock(global, move |g| {
|
||||||
|
g.debugger.reset_status(reset)
|
||||||
|
});
|
||||||
|
|
||||||
let crate::ast::FnCallExpr {
|
let crate::ast::FnCallExpr {
|
||||||
name, hashes, args, ..
|
name, hashes, args, ..
|
||||||
} = &**x;
|
} = &**x;
|
||||||
|
|
||||||
|
// Truncate the index values upon exit
|
||||||
let offset = idx_values.len() - args.len();
|
let offset = idx_values.len() - args.len();
|
||||||
|
let idx_values =
|
||||||
|
&mut *RestoreOnDrop::lock(idx_values, move |v| v.truncate(offset));
|
||||||
|
|
||||||
let call_args = &mut idx_values[offset..];
|
let call_args = &mut idx_values[offset..];
|
||||||
let pos1 = args.get(0).map_or(Position::NONE, Expr::position);
|
let pos1 = args.get(0).map_or(Position::NONE, Expr::position);
|
||||||
|
|
||||||
let result = self.make_method_call(
|
self.make_method_call(
|
||||||
global, caches, lib, level, name, *hashes, target, call_args, pos1,
|
global, caches, lib, name, *hashes, target, call_args, pos1, *pos,
|
||||||
*pos,
|
)
|
||||||
);
|
|
||||||
|
|
||||||
idx_values.truncate(offset);
|
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
|
||||||
global.debugger.reset_status(reset_debugger);
|
|
||||||
|
|
||||||
result
|
|
||||||
}
|
}
|
||||||
// xxx.fn_name(...) = ???
|
// xxx.fn_name(...) = ???
|
||||||
Expr::MethodCall(..) if new_val.is_some() => {
|
Expr::MethodCall(..) if new_val.is_some() => {
|
||||||
@ -233,16 +231,16 @@ impl Engine {
|
|||||||
// {xxx:map}.id op= ???
|
// {xxx:map}.id op= ???
|
||||||
Expr::Property(x, pos) if target.is::<crate::Map>() && new_val.is_some() => {
|
Expr::Property(x, pos) if target.is::<crate::Map>() && new_val.is_some() => {
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
self.run_debugger(global, caches, lib, level, scope, this_ptr, rhs)?;
|
self.run_debugger(global, caches, lib, scope, this_ptr, rhs)?;
|
||||||
|
|
||||||
let index = &mut x.2.clone().into();
|
let index = &mut x.2.clone().into();
|
||||||
let (new_val, op_info) = new_val.take().expect("`Some`");
|
let (new_val, op_info) = new_val.take().expect("`Some`");
|
||||||
{
|
{
|
||||||
let val_target = &mut self.get_indexed_mut(
|
let val_target = &mut self.get_indexed_mut(
|
||||||
global, caches, lib, level, target, index, *pos, true, false,
|
global, caches, lib, target, index, *pos, true, false,
|
||||||
)?;
|
)?;
|
||||||
self.eval_op_assignment(
|
self.eval_op_assignment(
|
||||||
global, caches, lib, level, op_info, val_target, root, new_val,
|
global, caches, lib, op_info, val_target, root, new_val,
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
self.check_data_size(target.source(), op_info.pos)?;
|
self.check_data_size(target.source(), op_info.pos)?;
|
||||||
@ -251,18 +249,18 @@ impl Engine {
|
|||||||
// {xxx:map}.id
|
// {xxx:map}.id
|
||||||
Expr::Property(x, pos) if target.is::<crate::Map>() => {
|
Expr::Property(x, pos) if target.is::<crate::Map>() => {
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
self.run_debugger(global, caches, lib, level, scope, this_ptr, rhs)?;
|
self.run_debugger(global, caches, lib, scope, this_ptr, rhs)?;
|
||||||
|
|
||||||
let index = &mut x.2.clone().into();
|
let index = &mut x.2.clone().into();
|
||||||
let val = self.get_indexed_mut(
|
let val = self.get_indexed_mut(
|
||||||
global, caches, lib, level, target, index, *pos, false, false,
|
global, caches, lib, target, index, *pos, false, false,
|
||||||
)?;
|
)?;
|
||||||
Ok((val.take_or_clone(), false))
|
Ok((val.take_or_clone(), false))
|
||||||
}
|
}
|
||||||
// xxx.id op= ???
|
// xxx.id op= ???
|
||||||
Expr::Property(x, pos) if new_val.is_some() => {
|
Expr::Property(x, pos) if new_val.is_some() => {
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
self.run_debugger(global, caches, lib, level, scope, this_ptr, rhs)?;
|
self.run_debugger(global, caches, lib, scope, this_ptr, rhs)?;
|
||||||
|
|
||||||
let ((getter, hash_get), (setter, hash_set), name) = &**x;
|
let ((getter, hash_get), (setter, hash_set), name) = &**x;
|
||||||
let (mut new_val, op_info) = new_val.take().expect("`Some`");
|
let (mut new_val, op_info) = new_val.take().expect("`Some`");
|
||||||
@ -271,15 +269,15 @@ impl Engine {
|
|||||||
let args = &mut [target.as_mut()];
|
let args = &mut [target.as_mut()];
|
||||||
let (mut orig_val, ..) = self
|
let (mut orig_val, ..) = self
|
||||||
.exec_native_fn_call(
|
.exec_native_fn_call(
|
||||||
global, caches, lib, level, getter, None, *hash_get, args,
|
global, caches, lib, getter, None, *hash_get, args, is_ref_mut,
|
||||||
is_ref_mut, *pos,
|
*pos,
|
||||||
)
|
)
|
||||||
.or_else(|err| match *err {
|
.or_else(|err| match *err {
|
||||||
// Try an indexer if property does not exist
|
// Try an indexer if property does not exist
|
||||||
ERR::ErrorDotExpr(..) => {
|
ERR::ErrorDotExpr(..) => {
|
||||||
let mut prop = name.into();
|
let mut prop = name.into();
|
||||||
self.call_indexer_get(
|
self.call_indexer_get(
|
||||||
global, caches, lib, level, target, &mut prop,
|
global, caches, lib, target, &mut prop,
|
||||||
)
|
)
|
||||||
.map(|r| (r, false))
|
.map(|r| (r, false))
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
@ -296,7 +294,7 @@ impl Engine {
|
|||||||
let orig_val = &mut (&mut orig_val).into();
|
let orig_val = &mut (&mut orig_val).into();
|
||||||
|
|
||||||
self.eval_op_assignment(
|
self.eval_op_assignment(
|
||||||
global, caches, lib, level, op_info, orig_val, root, new_val,
|
global, caches, lib, op_info, orig_val, root, new_val,
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -305,8 +303,7 @@ impl Engine {
|
|||||||
|
|
||||||
let args = &mut [target.as_mut(), &mut new_val];
|
let args = &mut [target.as_mut(), &mut new_val];
|
||||||
self.exec_native_fn_call(
|
self.exec_native_fn_call(
|
||||||
global, caches, lib, level, setter, None, *hash_set, args, is_ref_mut,
|
global, caches, lib, setter, None, *hash_set, args, is_ref_mut, *pos,
|
||||||
*pos,
|
|
||||||
)
|
)
|
||||||
.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
|
||||||
@ -314,7 +311,7 @@ impl Engine {
|
|||||||
let idx = &mut name.into();
|
let idx = &mut name.into();
|
||||||
let new_val = &mut new_val;
|
let new_val = &mut new_val;
|
||||||
self.call_indexer_set(
|
self.call_indexer_set(
|
||||||
global, caches, lib, level, target, idx, new_val, is_ref_mut,
|
global, caches, lib, target, idx, new_val, is_ref_mut,
|
||||||
)
|
)
|
||||||
.map_err(|e| match *e {
|
.map_err(|e| match *e {
|
||||||
ERR::ErrorIndexingType(..) => err,
|
ERR::ErrorIndexingType(..) => err,
|
||||||
@ -327,22 +324,19 @@ impl Engine {
|
|||||||
// xxx.id
|
// xxx.id
|
||||||
Expr::Property(x, pos) => {
|
Expr::Property(x, pos) => {
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
self.run_debugger(global, caches, lib, level, scope, this_ptr, rhs)?;
|
self.run_debugger(global, caches, lib, scope, this_ptr, rhs)?;
|
||||||
|
|
||||||
let ((getter, hash_get), _, name) = &**x;
|
let ((getter, hash_get), _, name) = &**x;
|
||||||
let args = &mut [target.as_mut()];
|
let args = &mut [target.as_mut()];
|
||||||
self.exec_native_fn_call(
|
self.exec_native_fn_call(
|
||||||
global, caches, lib, level, getter, None, *hash_get, args, is_ref_mut,
|
global, caches, lib, getter, None, *hash_get, args, is_ref_mut, *pos,
|
||||||
*pos,
|
|
||||||
)
|
)
|
||||||
.map_or_else(
|
.map_or_else(
|
||||||
|err| match *err {
|
|err| match *err {
|
||||||
// Try an indexer if property does not exist
|
// Try an indexer if property does not exist
|
||||||
ERR::ErrorDotExpr(..) => {
|
ERR::ErrorDotExpr(..) => {
|
||||||
let mut prop = name.into();
|
let mut prop = name.into();
|
||||||
self.call_indexer_get(
|
self.call_indexer_get(global, caches, lib, target, &mut prop)
|
||||||
global, caches, lib, level, target, &mut prop,
|
|
||||||
)
|
|
||||||
.map(|r| (r, false))
|
.map(|r| (r, false))
|
||||||
.map_err(|e| match *e {
|
.map_err(|e| match *e {
|
||||||
ERR::ErrorIndexingType(..) => err,
|
ERR::ErrorIndexingType(..) => err,
|
||||||
@ -364,41 +358,43 @@ impl Engine {
|
|||||||
let val_target = &mut match x.lhs {
|
let val_target = &mut match x.lhs {
|
||||||
Expr::Property(ref p, pos) => {
|
Expr::Property(ref p, pos) => {
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
self.run_debugger(
|
self.run_debugger(global, caches, lib, scope, this_ptr, _node)?;
|
||||||
global, caches, lib, level, scope, this_ptr, _node,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
let index = &mut p.2.clone().into();
|
let index = &mut p.2.clone().into();
|
||||||
self.get_indexed_mut(
|
self.get_indexed_mut(
|
||||||
global, caches, lib, level, target, index, pos, false, true,
|
global, caches, lib, target, index, pos, false, true,
|
||||||
)?
|
)?
|
||||||
}
|
}
|
||||||
// {xxx:map}.fn_name(arg_expr_list)[expr] | {xxx:map}.fn_name(arg_expr_list).expr
|
// {xxx:map}.fn_name(arg_expr_list)[expr] | {xxx:map}.fn_name(arg_expr_list).expr
|
||||||
Expr::MethodCall(ref x, pos) if !x.is_qualified() => {
|
Expr::MethodCall(ref x, pos) if !x.is_qualified() => {
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
let reset_debugger = self.run_debugger_with_reset(
|
let reset = self.run_debugger_with_reset(
|
||||||
global, caches, lib, level, scope, this_ptr, _node,
|
global, caches, lib, scope, this_ptr, _node,
|
||||||
)?;
|
)?;
|
||||||
|
#[cfg(feature = "debugging")]
|
||||||
|
let global = &mut *RestoreOnDrop::lock(global, move |g| {
|
||||||
|
g.debugger.reset_status(reset)
|
||||||
|
});
|
||||||
|
|
||||||
let crate::ast::FnCallExpr {
|
let crate::ast::FnCallExpr {
|
||||||
name, hashes, args, ..
|
name, hashes, args, ..
|
||||||
} = &**x;
|
} = &**x;
|
||||||
|
|
||||||
|
// Truncate the index values upon exit
|
||||||
let offset = idx_values.len() - args.len();
|
let offset = idx_values.len() - args.len();
|
||||||
|
let idx_values = &mut *RestoreOnDrop::lock(idx_values, move |v| {
|
||||||
|
v.truncate(offset)
|
||||||
|
});
|
||||||
|
|
||||||
let call_args = &mut idx_values[offset..];
|
let call_args = &mut idx_values[offset..];
|
||||||
let pos1 = args.get(0).map_or(Position::NONE, Expr::position);
|
let pos1 = args.get(0).map_or(Position::NONE, Expr::position);
|
||||||
|
|
||||||
let result = self.make_method_call(
|
self.make_method_call(
|
||||||
global, caches, lib, level, name, *hashes, target, call_args,
|
global, caches, lib, name, *hashes, target, call_args, pos1,
|
||||||
pos1, pos,
|
pos,
|
||||||
);
|
)?
|
||||||
|
.0
|
||||||
idx_values.truncate(offset);
|
.into()
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
|
||||||
global.debugger.reset_status(reset_debugger);
|
|
||||||
|
|
||||||
result?.0.into()
|
|
||||||
}
|
}
|
||||||
// {xxx:map}.module::fn_name(...) - syntax error
|
// {xxx:map}.module::fn_name(...) - syntax error
|
||||||
Expr::MethodCall(..) => unreachable!(
|
Expr::MethodCall(..) => unreachable!(
|
||||||
@ -410,8 +406,8 @@ impl Engine {
|
|||||||
let rhs_chain = rhs.into();
|
let rhs_chain = rhs.into();
|
||||||
|
|
||||||
self.eval_dot_index_chain_helper(
|
self.eval_dot_index_chain_helper(
|
||||||
global, caches, lib, level, this_ptr, val_target, root, rhs, *options,
|
global, caches, lib, this_ptr, val_target, root, rhs, *options, &x.rhs,
|
||||||
&x.rhs, idx_values, rhs_chain, new_val,
|
idx_values, rhs_chain, new_val,
|
||||||
)
|
)
|
||||||
.map_err(|err| err.fill_position(*x_pos))
|
.map_err(|err| err.fill_position(*x_pos))
|
||||||
}
|
}
|
||||||
@ -423,9 +419,7 @@ impl Engine {
|
|||||||
// xxx.prop[expr] | xxx.prop.expr
|
// xxx.prop[expr] | xxx.prop.expr
|
||||||
Expr::Property(ref p, pos) => {
|
Expr::Property(ref p, pos) => {
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
self.run_debugger(
|
self.run_debugger(global, caches, lib, scope, this_ptr, _node)?;
|
||||||
global, caches, lib, level, scope, this_ptr, _node,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
let ((getter, hash_get), (setter, hash_set), name) = &**p;
|
let ((getter, hash_get), (setter, hash_set), name) = &**p;
|
||||||
let rhs_chain = rhs.into();
|
let rhs_chain = rhs.into();
|
||||||
@ -435,7 +429,7 @@ impl Engine {
|
|||||||
// Assume getters are always pure
|
// Assume getters are always pure
|
||||||
let (mut val, ..) = self
|
let (mut val, ..) = self
|
||||||
.exec_native_fn_call(
|
.exec_native_fn_call(
|
||||||
global, caches, lib, level, getter, None, *hash_get, args,
|
global, caches, lib, getter, None, *hash_get, args,
|
||||||
is_ref_mut, pos,
|
is_ref_mut, pos,
|
||||||
)
|
)
|
||||||
.or_else(|err| match *err {
|
.or_else(|err| match *err {
|
||||||
@ -443,7 +437,7 @@ impl Engine {
|
|||||||
ERR::ErrorDotExpr(..) => {
|
ERR::ErrorDotExpr(..) => {
|
||||||
let mut prop = name.into();
|
let mut prop = name.into();
|
||||||
self.call_indexer_get(
|
self.call_indexer_get(
|
||||||
global, caches, lib, level, target, &mut prop,
|
global, caches, lib, target, &mut prop,
|
||||||
)
|
)
|
||||||
.map(|r| (r, false))
|
.map(|r| (r, false))
|
||||||
.map_err(
|
.map_err(
|
||||||
@ -460,8 +454,8 @@ impl Engine {
|
|||||||
|
|
||||||
let (result, may_be_changed) = self
|
let (result, may_be_changed) = self
|
||||||
.eval_dot_index_chain_helper(
|
.eval_dot_index_chain_helper(
|
||||||
global, caches, lib, level, this_ptr, val, root, rhs,
|
global, caches, lib, this_ptr, val, root, rhs, *options,
|
||||||
*options, &x.rhs, idx_values, rhs_chain, new_val,
|
&x.rhs, idx_values, rhs_chain, new_val,
|
||||||
)
|
)
|
||||||
.map_err(|err| err.fill_position(*x_pos))?;
|
.map_err(|err| err.fill_position(*x_pos))?;
|
||||||
|
|
||||||
@ -471,7 +465,7 @@ impl Engine {
|
|||||||
let mut arg_values = [target.as_mut(), val.as_mut()];
|
let mut arg_values = [target.as_mut(), val.as_mut()];
|
||||||
let args = &mut arg_values;
|
let args = &mut arg_values;
|
||||||
self.exec_native_fn_call(
|
self.exec_native_fn_call(
|
||||||
global, caches, lib, level, setter, None, *hash_set, args,
|
global, caches, lib, setter, None, *hash_set, args,
|
||||||
is_ref_mut, pos,
|
is_ref_mut, pos,
|
||||||
)
|
)
|
||||||
.or_else(
|
.or_else(
|
||||||
@ -481,8 +475,8 @@ impl Engine {
|
|||||||
let idx = &mut name.into();
|
let idx = &mut name.into();
|
||||||
let new_val = val;
|
let new_val = val;
|
||||||
self.call_indexer_set(
|
self.call_indexer_set(
|
||||||
global, caches, lib, level, target, idx,
|
global, caches, lib, target, idx, new_val,
|
||||||
new_val, is_ref_mut,
|
is_ref_mut,
|
||||||
)
|
)
|
||||||
.or_else(|e| match *e {
|
.or_else(|e| match *e {
|
||||||
// If there is no setter, no need to feed it
|
// If there is no setter, no need to feed it
|
||||||
@ -502,35 +496,42 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
// xxx.fn_name(arg_expr_list)[expr] | xxx.fn_name(arg_expr_list).expr
|
// xxx.fn_name(arg_expr_list)[expr] | xxx.fn_name(arg_expr_list).expr
|
||||||
Expr::MethodCall(ref f, pos) if !f.is_qualified() => {
|
Expr::MethodCall(ref f, pos) if !f.is_qualified() => {
|
||||||
|
let val = {
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
let reset_debugger = self.run_debugger_with_reset(
|
let reset = self.run_debugger_with_reset(
|
||||||
global, caches, lib, level, scope, this_ptr, _node,
|
global, caches, lib, scope, this_ptr, _node,
|
||||||
)?;
|
)?;
|
||||||
|
#[cfg(feature = "debugging")]
|
||||||
|
let global = &mut *RestoreOnDrop::lock(global, move |g| {
|
||||||
|
g.debugger.reset_status(reset)
|
||||||
|
});
|
||||||
|
|
||||||
let crate::ast::FnCallExpr {
|
let crate::ast::FnCallExpr {
|
||||||
name, hashes, args, ..
|
name, hashes, args, ..
|
||||||
} = &**f;
|
} = &**f;
|
||||||
let rhs_chain = rhs.into();
|
|
||||||
|
|
||||||
|
// Truncate the index values upon exit
|
||||||
let offset = idx_values.len() - args.len();
|
let offset = idx_values.len() - args.len();
|
||||||
|
let idx_values =
|
||||||
|
&mut *RestoreOnDrop::lock(idx_values, move |v| {
|
||||||
|
v.truncate(offset)
|
||||||
|
});
|
||||||
|
|
||||||
let call_args = &mut idx_values[offset..];
|
let call_args = &mut idx_values[offset..];
|
||||||
let pos1 = args.get(0).map_or(Position::NONE, Expr::position);
|
let pos1 = args.get(0).map_or(Position::NONE, Expr::position);
|
||||||
|
|
||||||
let result = self.make_method_call(
|
self.make_method_call(
|
||||||
global, caches, lib, level, name, *hashes, target, call_args,
|
global, caches, lib, name, *hashes, target, call_args,
|
||||||
pos1, pos,
|
pos1, pos,
|
||||||
);
|
)?
|
||||||
|
.0
|
||||||
|
};
|
||||||
|
|
||||||
idx_values.truncate(offset);
|
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
|
||||||
global.debugger.reset_status(reset_debugger);
|
|
||||||
|
|
||||||
let (val, _) = &mut result?;
|
|
||||||
let val = &mut val.into();
|
let val = &mut val.into();
|
||||||
|
let rhs_chain = rhs.into();
|
||||||
|
|
||||||
self.eval_dot_index_chain_helper(
|
self.eval_dot_index_chain_helper(
|
||||||
global, caches, lib, level, this_ptr, val, root, rhs, *options,
|
global, caches, lib, this_ptr, val, root, rhs, *options,
|
||||||
&x.rhs, idx_values, rhs_chain, new_val,
|
&x.rhs, idx_values, rhs_chain, new_val,
|
||||||
)
|
)
|
||||||
.map_err(|err| err.fill_position(pos))
|
.map_err(|err| err.fill_position(pos))
|
||||||
@ -555,10 +556,9 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
this_ptr: &mut Dynamic,
|
||||||
expr: &Expr,
|
expr: &Expr,
|
||||||
new_val: &mut Option<(Dynamic, &OpAssignment)>,
|
new_val: &mut Option<(Dynamic, &OpAssignment)>,
|
||||||
) -> RhaiResult {
|
) -> RhaiResult {
|
||||||
@ -597,8 +597,7 @@ impl Engine {
|
|||||||
// All other patterns - evaluate the arguments chain
|
// All other patterns - evaluate the arguments chain
|
||||||
_ => {
|
_ => {
|
||||||
self.eval_dot_index_chain_arguments(
|
self.eval_dot_index_chain_arguments(
|
||||||
global, caches, lib, level, scope, this_ptr, rhs, options, chain_type,
|
global, caches, lib, scope, this_ptr, rhs, options, chain_type, idx_values,
|
||||||
idx_values,
|
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -607,18 +606,19 @@ impl Engine {
|
|||||||
// id.??? or id[???]
|
// id.??? or id[???]
|
||||||
Expr::Variable(x, .., var_pos) => {
|
Expr::Variable(x, .., var_pos) => {
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
self.run_debugger(global, caches, lib, level, scope, this_ptr, lhs)?;
|
self.run_debugger(global, caches, lib, scope, this_ptr, lhs)?;
|
||||||
self.track_operation(global, *var_pos)?;
|
self.track_operation(global, *var_pos)?;
|
||||||
|
|
||||||
let (mut target, ..) =
|
let (mut target, ..) =
|
||||||
self.search_namespace(global, caches, lib, level, scope, this_ptr, lhs)?;
|
self.search_namespace(global, caches, lib, scope, this_ptr, lhs)?;
|
||||||
|
|
||||||
let obj_ptr = &mut target;
|
let obj_ptr = &mut target;
|
||||||
let root = (x.3.as_str(), *var_pos);
|
let root = (x.3.as_str(), *var_pos);
|
||||||
|
let mut this = Dynamic::NULL;
|
||||||
|
|
||||||
self.eval_dot_index_chain_helper(
|
self.eval_dot_index_chain_helper(
|
||||||
global, caches, lib, level, &mut None, obj_ptr, root, expr, options, rhs,
|
global, caches, lib, &mut this, obj_ptr, root, expr, options, rhs, idx_values,
|
||||||
idx_values, chain_type, new_val,
|
chain_type, new_val,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
// {expr}.??? = ??? or {expr}[???] = ???
|
// {expr}.??? = ??? or {expr}[???] = ???
|
||||||
@ -626,14 +626,14 @@ impl Engine {
|
|||||||
// {expr}.??? or {expr}[???]
|
// {expr}.??? or {expr}[???]
|
||||||
expr => {
|
expr => {
|
||||||
let value = self
|
let value = self
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, expr)?
|
.eval_expr(global, caches, lib, scope, this_ptr, expr)?
|
||||||
.flatten();
|
.flatten();
|
||||||
let obj_ptr = &mut value.into();
|
let obj_ptr = &mut value.into();
|
||||||
let root = ("", expr.start_position());
|
let root = ("", expr.start_position());
|
||||||
|
|
||||||
self.eval_dot_index_chain_helper(
|
self.eval_dot_index_chain_helper(
|
||||||
global, caches, lib, level, this_ptr, obj_ptr, root, expr, options, rhs,
|
global, caches, lib, this_ptr, obj_ptr, root, expr, options, rhs, idx_values,
|
||||||
idx_values, chain_type, new_val,
|
chain_type, new_val,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -646,10 +646,9 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
this_ptr: &mut Dynamic,
|
||||||
expr: &Expr,
|
expr: &Expr,
|
||||||
parent_options: ASTFlags,
|
parent_options: ASTFlags,
|
||||||
parent_chain_type: ChainType,
|
parent_chain_type: ChainType,
|
||||||
@ -664,7 +663,7 @@ impl Engine {
|
|||||||
{
|
{
|
||||||
for arg_expr in &x.args {
|
for arg_expr in &x.args {
|
||||||
idx_values.push(
|
idx_values.push(
|
||||||
self.get_arg_value(global, caches, lib, level, scope, this_ptr, arg_expr)?
|
self.get_arg_value(global, caches, lib, scope, this_ptr, arg_expr)?
|
||||||
.0
|
.0
|
||||||
.flatten(),
|
.flatten(),
|
||||||
);
|
);
|
||||||
@ -698,9 +697,7 @@ impl Engine {
|
|||||||
{
|
{
|
||||||
for arg_expr in &x.args {
|
for arg_expr in &x.args {
|
||||||
_arg_values.push(
|
_arg_values.push(
|
||||||
self.get_arg_value(
|
self.get_arg_value(global, caches, lib, scope, this_ptr, arg_expr)?
|
||||||
global, caches, lib, level, scope, this_ptr, arg_expr,
|
|
||||||
)?
|
|
||||||
.0
|
.0
|
||||||
.flatten(),
|
.flatten(),
|
||||||
);
|
);
|
||||||
@ -717,7 +714,7 @@ impl Engine {
|
|||||||
#[cfg(not(feature = "no_index"))]
|
#[cfg(not(feature = "no_index"))]
|
||||||
_ if parent_chain_type == ChainType::Indexing => {
|
_ if parent_chain_type == ChainType::Indexing => {
|
||||||
_arg_values.push(
|
_arg_values.push(
|
||||||
self.eval_expr(global, caches, lib, level, scope, this_ptr, lhs)?
|
self.eval_expr(global, caches, lib, scope, this_ptr, lhs)?
|
||||||
.flatten(),
|
.flatten(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -728,8 +725,7 @@ impl Engine {
|
|||||||
let chain_type = expr.into();
|
let chain_type = expr.into();
|
||||||
|
|
||||||
self.eval_dot_index_chain_arguments(
|
self.eval_dot_index_chain_arguments(
|
||||||
global, caches, lib, level, scope, this_ptr, rhs, *options, chain_type,
|
global, caches, lib, scope, this_ptr, rhs, *options, chain_type, idx_values,
|
||||||
idx_values,
|
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
if !_arg_values.is_empty() {
|
if !_arg_values.is_empty() {
|
||||||
@ -743,7 +739,7 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
#[cfg(not(feature = "no_index"))]
|
#[cfg(not(feature = "no_index"))]
|
||||||
_ if parent_chain_type == ChainType::Indexing => idx_values.push(
|
_ if parent_chain_type == ChainType::Indexing => idx_values.push(
|
||||||
self.eval_expr(global, caches, lib, level, scope, this_ptr, expr)?
|
self.eval_expr(global, caches, lib, scope, this_ptr, expr)?
|
||||||
.flatten(),
|
.flatten(),
|
||||||
),
|
),
|
||||||
_ => unreachable!("unknown chained expression: {:?}", expr),
|
_ => unreachable!("unknown chained expression: {:?}", expr),
|
||||||
@ -758,8 +754,7 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
target: &mut Dynamic,
|
target: &mut Dynamic,
|
||||||
idx: &mut Dynamic,
|
idx: &mut Dynamic,
|
||||||
) -> RhaiResultOf<Dynamic> {
|
) -> RhaiResultOf<Dynamic> {
|
||||||
@ -767,11 +762,11 @@ impl Engine {
|
|||||||
let hash = 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_native_fn_call(
|
global.level += 1;
|
||||||
global, caches, lib, level, fn_name, None, hash, args, true, pos,
|
let global = &mut *RestoreOnDrop::lock(global, move |g| g.level -= 1);
|
||||||
)
|
|
||||||
|
self.exec_native_fn_call(global, caches, lib, fn_name, None, hash, args, true, pos)
|
||||||
.map(|(r, ..)| r)
|
.map(|(r, ..)| r)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -781,8 +776,7 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
target: &mut Dynamic,
|
target: &mut Dynamic,
|
||||||
idx: &mut Dynamic,
|
idx: &mut Dynamic,
|
||||||
new_val: &mut Dynamic,
|
new_val: &mut Dynamic,
|
||||||
@ -792,10 +786,12 @@ impl Engine {
|
|||||||
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;
|
|
||||||
|
global.level += 1;
|
||||||
|
let global = &mut *RestoreOnDrop::lock(global, move |g| g.level -= 1);
|
||||||
|
|
||||||
self.exec_native_fn_call(
|
self.exec_native_fn_call(
|
||||||
global, caches, lib, level, fn_name, None, hash, args, is_ref_mut, pos,
|
global, caches, lib, fn_name, None, hash, args, is_ref_mut, pos,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -805,8 +801,7 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
target: &'t mut Dynamic,
|
target: &'t mut Dynamic,
|
||||||
idx: &mut Dynamic,
|
idx: &mut Dynamic,
|
||||||
idx_pos: Position,
|
idx_pos: Position,
|
||||||
@ -1015,7 +1010,7 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_ if use_indexers => self
|
_ if use_indexers => self
|
||||||
.call_indexer_get(global, caches, lib, level, target, idx)
|
.call_indexer_get(global, caches, lib, target, idx)
|
||||||
.map(Into::into),
|
.map(Into::into),
|
||||||
|
|
||||||
_ => Err(ERR::ErrorIndexingType(
|
_ => Err(ERR::ErrorIndexingType(
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
use super::{Caches, EvalContext, GlobalRuntimeState};
|
use super::{Caches, EvalContext, GlobalRuntimeState};
|
||||||
use crate::ast::{ASTNode, Expr, Stmt};
|
use crate::ast::{ASTNode, Expr, Stmt};
|
||||||
use crate::{
|
use crate::{
|
||||||
Dynamic, Engine, EvalAltResult, ImmutableString, Module, Position, RhaiResultOf, Scope,
|
Dynamic, Engine, EvalAltResult, ImmutableString, Position, RhaiResultOf, Scope, SharedModule,
|
||||||
};
|
};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
@ -413,15 +413,14 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
this_ptr: &mut Dynamic,
|
||||||
node: impl Into<ASTNode<'a>>,
|
node: impl Into<ASTNode<'a>>,
|
||||||
) -> RhaiResultOf<()> {
|
) -> RhaiResultOf<()> {
|
||||||
if self.debugger.is_some() {
|
if self.debugger.is_some() {
|
||||||
if let Some(cmd) =
|
if let Some(cmd) =
|
||||||
self.run_debugger_with_reset_raw(global, caches, lib, level, scope, this_ptr, node)?
|
self.run_debugger_with_reset_raw(global, caches, lib, scope, this_ptr, node)?
|
||||||
{
|
{
|
||||||
global.debugger.status = cmd;
|
global.debugger.status = cmd;
|
||||||
}
|
}
|
||||||
@ -440,14 +439,13 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
this_ptr: &mut Dynamic,
|
||||||
node: impl Into<ASTNode<'a>>,
|
node: impl Into<ASTNode<'a>>,
|
||||||
) -> RhaiResultOf<Option<DebuggerStatus>> {
|
) -> RhaiResultOf<Option<DebuggerStatus>> {
|
||||||
if self.debugger.is_some() {
|
if self.debugger.is_some() {
|
||||||
self.run_debugger_with_reset_raw(global, caches, lib, level, scope, this_ptr, node)
|
self.run_debugger_with_reset_raw(global, caches, lib, scope, this_ptr, node)
|
||||||
} else {
|
} else {
|
||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
@ -463,10 +461,9 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
this_ptr: &mut Dynamic,
|
||||||
node: impl Into<ASTNode<'a>>,
|
node: impl Into<ASTNode<'a>>,
|
||||||
) -> RhaiResultOf<Option<DebuggerStatus>> {
|
) -> RhaiResultOf<Option<DebuggerStatus>> {
|
||||||
let node = node.into();
|
let node = node.into();
|
||||||
@ -497,7 +494,7 @@ impl Engine {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
self.run_debugger_raw(global, caches, lib, level, scope, this_ptr, node, event)
|
self.run_debugger_raw(global, caches, lib, scope, this_ptr, node, event)
|
||||||
}
|
}
|
||||||
/// Run the debugger callback unconditionally.
|
/// Run the debugger callback unconditionally.
|
||||||
///
|
///
|
||||||
@ -510,17 +507,15 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
this_ptr: &mut Dynamic,
|
||||||
node: ASTNode<'a>,
|
node: ASTNode<'a>,
|
||||||
event: DebuggerEvent,
|
event: DebuggerEvent,
|
||||||
) -> Result<Option<DebuggerStatus>, Box<crate::EvalAltResult>> {
|
) -> Result<Option<DebuggerStatus>, Box<crate::EvalAltResult>> {
|
||||||
let src = global.source_raw().cloned();
|
let src = global.source_raw().cloned();
|
||||||
let src = src.as_ref().map(|s| s.as_str());
|
let src = src.as_ref().map(|s| s.as_str());
|
||||||
let context =
|
let context = crate::EvalContext::new(self, global, caches, lib, scope, this_ptr);
|
||||||
crate::EvalContext::new(self, global, Some(caches), lib, level, scope, this_ptr);
|
|
||||||
|
|
||||||
if let Some((.., ref on_debugger)) = self.debugger {
|
if let Some((.., ref on_debugger)) = self.debugger {
|
||||||
let command = on_debugger(context, event, node, src, node.position())?;
|
let command = on_debugger(context, event, node, src, node.position())?;
|
||||||
@ -546,12 +541,12 @@ impl Engine {
|
|||||||
// Bump a level if it is a function call
|
// Bump a level if it is a function call
|
||||||
let level = match node {
|
let level = match node {
|
||||||
ASTNode::Expr(Expr::FnCall(..)) | ASTNode::Stmt(Stmt::FnCall(..)) => {
|
ASTNode::Expr(Expr::FnCall(..)) | ASTNode::Stmt(Stmt::FnCall(..)) => {
|
||||||
level + 1
|
global.level + 1
|
||||||
}
|
}
|
||||||
ASTNode::Stmt(Stmt::Expr(e)) if matches!(**e, Expr::FnCall(..)) => {
|
ASTNode::Stmt(Stmt::Expr(e)) if matches!(**e, Expr::FnCall(..)) => {
|
||||||
level + 1
|
global.level + 1
|
||||||
}
|
}
|
||||||
_ => level,
|
_ => global.level,
|
||||||
};
|
};
|
||||||
global.debugger.status = DebuggerStatus::FunctionExit(level);
|
global.debugger.status = DebuggerStatus::FunctionExit(level);
|
||||||
Ok(None)
|
Ok(None)
|
||||||
|
@ -1,42 +1,39 @@
|
|||||||
//! Evaluation context.
|
//! Evaluation context.
|
||||||
|
|
||||||
use super::{Caches, GlobalRuntimeState};
|
use super::{Caches, GlobalRuntimeState};
|
||||||
use crate::{Dynamic, Engine, Module, Scope};
|
use crate::{Dynamic, Engine, Module, Scope, SharedModule};
|
||||||
#[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)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub struct EvalContext<'a, 's, 'ps, 'g, 'pg, 'c, 'pc, 't, 'pt> {
|
pub struct EvalContext<'a, 's, 'ps, 'g, 'c, 't> {
|
||||||
/// The current [`Engine`].
|
/// The current [`Engine`].
|
||||||
engine: &'a Engine,
|
engine: &'a Engine,
|
||||||
/// The current [`Scope`].
|
/// The current [`Scope`].
|
||||||
scope: &'s mut Scope<'ps>,
|
scope: &'s mut Scope<'ps>,
|
||||||
/// The current [`GlobalRuntimeState`].
|
/// The current [`GlobalRuntimeState`].
|
||||||
global: &'g mut GlobalRuntimeState<'pg>,
|
global: &'g mut GlobalRuntimeState,
|
||||||
/// The current [caches][Caches], if available.
|
/// The current [caches][Caches], if available.
|
||||||
caches: Option<&'c mut Caches<'pc>>,
|
caches: &'c mut Caches,
|
||||||
/// The current stack of imported [modules][Module].
|
/// The current stack of imported [modules][Module].
|
||||||
lib: &'a [&'a Module],
|
lib: &'a [SharedModule],
|
||||||
/// The current bound `this` pointer, if any.
|
/// The current bound `this` pointer, if any.
|
||||||
this_ptr: &'t mut Option<&'pt mut Dynamic>,
|
this_ptr: &'t mut Dynamic,
|
||||||
/// The current nesting level of function calls.
|
|
||||||
level: usize,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, 's, 'ps, 'g, 'pg, 'c, 'pc, 't, 'pt> EvalContext<'a, 's, 'ps, 'g, 'pg, 'c, 'pc, 't, 'pt> {
|
impl<'a, 's, 'ps, 'g, 'c, 't> EvalContext<'a, 's, 'ps, 'g, 'c, 't> {
|
||||||
/// Create a new [`EvalContext`].
|
/// Create a new [`EvalContext`].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn new(
|
pub fn new(
|
||||||
engine: &'a Engine,
|
engine: &'a Engine,
|
||||||
global: &'g mut GlobalRuntimeState<'pg>,
|
global: &'g mut GlobalRuntimeState,
|
||||||
caches: Option<&'c mut Caches<'pc>>,
|
caches: &'c mut Caches,
|
||||||
lib: &'a [&'a Module],
|
lib: &'a [SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &'s mut Scope<'ps>,
|
scope: &'s mut Scope<'ps>,
|
||||||
this_ptr: &'t mut Option<&'pt mut Dynamic>,
|
this_ptr: &'t mut Dynamic,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
engine,
|
engine,
|
||||||
@ -45,7 +42,6 @@ impl<'a, 's, 'ps, 'g, 'pg, 'c, 'pc, 't, 'pt> EvalContext<'a, 's, 'ps, 'g, 'pg, '
|
|||||||
caches,
|
caches,
|
||||||
lib,
|
lib,
|
||||||
this_ptr,
|
this_ptr,
|
||||||
level,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// The current [`Engine`].
|
/// The current [`Engine`].
|
||||||
@ -104,39 +100,47 @@ impl<'a, 's, 'ps, 'g, 'pg, 'c, 'pc, 't, 'pt> EvalContext<'a, 's, 'ps, 'g, 'pg, '
|
|||||||
#[cfg(feature = "internals")]
|
#[cfg(feature = "internals")]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn global_runtime_state_mut(&mut self) -> &mut &'g mut GlobalRuntimeState<'pg> {
|
pub fn global_runtime_state_mut(&mut self) -> &mut GlobalRuntimeState {
|
||||||
&mut self.global
|
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.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn iter_namespaces(&self) -> impl Iterator<Item = &Module> {
|
pub fn iter_namespaces(&self) -> impl Iterator<Item = &Module> {
|
||||||
self.lib.iter().copied()
|
self.lib.iter().map(|m| m.as_ref())
|
||||||
}
|
}
|
||||||
/// _(internals)_ The current set of namespaces containing definitions of all script-defined functions.
|
/// _(internals)_ The current set of namespaces containing definitions of all script-defined functions.
|
||||||
/// Exported under the `internals` feature only.
|
/// Exported under the `internals` feature only.
|
||||||
#[cfg(feature = "internals")]
|
#[cfg(feature = "internals")]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn namespaces(&self) -> &[&Module] {
|
pub const fn namespaces(&self) -> &[SharedModule] {
|
||||||
self.lib
|
self.lib
|
||||||
}
|
}
|
||||||
/// The current bound `this` pointer, if any.
|
/// The current bound `this` pointer, if any.
|
||||||
#[inline(always)]
|
#[inline]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn this_ptr(&self) -> Option<&Dynamic> {
|
pub fn this_ptr(&self) -> Option<&Dynamic> {
|
||||||
self.this_ptr.as_ref().map(|v| &**v)
|
if self.this_ptr.is_null() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(self.this_ptr)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
/// Mutable reference to the current bound `this` pointer, if any.
|
/// Mutable reference to the current bound `this` pointer, if any.
|
||||||
#[inline(always)]
|
#[inline]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn this_ptr_mut(&mut self) -> &mut Option<&'pt mut Dynamic> {
|
pub fn this_ptr_mut(&mut self) -> Option<&mut Dynamic> {
|
||||||
self.this_ptr
|
if self.this_ptr.is_null() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(self.this_ptr)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
/// The current nesting level of function calls.
|
/// The current nesting level of function calls.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn call_level(&self) -> usize {
|
pub const fn call_level(&self) -> usize {
|
||||||
self.level
|
self.global.level
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluate an [expression tree][crate::Expression] within this [evaluation context][`EvalContext`].
|
/// Evaluate an [expression tree][crate::Expression] within this [evaluation context][`EvalContext`].
|
||||||
@ -173,19 +177,11 @@ impl<'a, 's, 'ps, 'g, 'pg, 'c, 'pc, 't, 'pt> EvalContext<'a, 's, 'ps, 'g, 'pg, '
|
|||||||
) -> crate::RhaiResult {
|
) -> crate::RhaiResult {
|
||||||
let expr: &crate::ast::Expr = expr;
|
let expr: &crate::ast::Expr = expr;
|
||||||
|
|
||||||
let mut new_caches = Caches::new();
|
|
||||||
|
|
||||||
let caches = match self.caches.as_mut() {
|
|
||||||
Some(c) => c,
|
|
||||||
None => &mut new_caches,
|
|
||||||
};
|
|
||||||
|
|
||||||
match expr {
|
match expr {
|
||||||
crate::ast::Expr::Stmt(statements) => self.engine.eval_stmt_block(
|
crate::ast::Expr::Stmt(statements) => self.engine.eval_stmt_block(
|
||||||
self.global,
|
self.global,
|
||||||
caches,
|
self.caches,
|
||||||
self.lib,
|
self.lib,
|
||||||
self.level,
|
|
||||||
self.scope,
|
self.scope,
|
||||||
self.this_ptr,
|
self.this_ptr,
|
||||||
statements,
|
statements,
|
||||||
@ -193,9 +189,8 @@ impl<'a, 's, 'ps, 'g, 'pg, 'c, 'pc, 't, 'pt> EvalContext<'a, 's, 'ps, 'g, 'pg, '
|
|||||||
),
|
),
|
||||||
_ => self.engine.eval_expr(
|
_ => self.engine.eval_expr(
|
||||||
self.global,
|
self.global,
|
||||||
caches,
|
self.caches,
|
||||||
self.lib,
|
self.lib,
|
||||||
self.level,
|
|
||||||
self.scope,
|
self.scope,
|
||||||
self.this_ptr,
|
self.this_ptr,
|
||||||
expr,
|
expr,
|
||||||
|
188
src/eval/expr.rs
188
src/eval/expr.rs
@ -4,7 +4,7 @@ use super::{Caches, EvalContext, GlobalRuntimeState, Target};
|
|||||||
use crate::ast::{Expr, OpAssignment};
|
use crate::ast::{Expr, OpAssignment};
|
||||||
use crate::engine::{KEYWORD_THIS, OP_CONCAT};
|
use crate::engine::{KEYWORD_THIS, OP_CONCAT};
|
||||||
use crate::types::dynamic::AccessMode;
|
use crate::types::dynamic::AccessMode;
|
||||||
use crate::{Dynamic, Engine, Module, Position, RhaiResult, RhaiResultOf, Scope, ERR};
|
use crate::{Dynamic, Engine, Position, RhaiResult, RhaiResultOf, Scope, SharedModule, ERR};
|
||||||
use std::num::NonZeroUsize;
|
use std::num::NonZeroUsize;
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
@ -18,7 +18,7 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &GlobalRuntimeState,
|
global: &GlobalRuntimeState,
|
||||||
namespace: &crate::ast::Namespace,
|
namespace: &crate::ast::Namespace,
|
||||||
) -> Option<crate::Shared<Module>> {
|
) -> Option<SharedModule> {
|
||||||
assert!(!namespace.is_empty());
|
assert!(!namespace.is_empty());
|
||||||
|
|
||||||
let root = namespace.root();
|
let root = namespace.root();
|
||||||
@ -51,26 +51,24 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &'s mut Scope,
|
scope: &'s mut Scope,
|
||||||
this_ptr: &'s mut Option<&mut Dynamic>,
|
this_ptr: &'s mut Dynamic,
|
||||||
expr: &Expr,
|
expr: &Expr,
|
||||||
) -> RhaiResultOf<(Target<'s>, Position)> {
|
) -> RhaiResultOf<(Target<'s>, Position)> {
|
||||||
match expr {
|
match expr {
|
||||||
Expr::Variable(_, Some(_), _) => {
|
Expr::Variable(_, Some(_), _) => {
|
||||||
self.search_scope_only(global, caches, lib, level, scope, this_ptr, expr)
|
self.search_scope_only(global, caches, lib, scope, this_ptr, expr)
|
||||||
}
|
}
|
||||||
Expr::Variable(v, None, _var_pos) => match &**v {
|
Expr::Variable(v, None, _var_pos) => match &**v {
|
||||||
// Normal variable access
|
// Normal variable access
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
(_, ns, ..) if ns.is_empty() => {
|
(_, ns, ..) if ns.is_empty() => {
|
||||||
self.search_scope_only(global, caches, lib, level, scope, this_ptr, expr)
|
self.search_scope_only(global, caches, lib, scope, this_ptr, expr)
|
||||||
}
|
}
|
||||||
#[cfg(feature = "no_module")]
|
#[cfg(feature = "no_module")]
|
||||||
(_, (), ..) => {
|
(_, (), ..) => self.search_scope_only(global, caches, lib, scope, this_ptr, expr),
|
||||||
self.search_scope_only(global, caches, lib, level, scope, this_ptr, expr)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Qualified variable access
|
// Qualified variable access
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
@ -137,10 +135,10 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &'s mut Scope,
|
scope: &'s mut Scope,
|
||||||
this_ptr: &'s mut Option<&mut Dynamic>,
|
this_ptr: &'s mut Dynamic,
|
||||||
expr: &Expr,
|
expr: &Expr,
|
||||||
) -> RhaiResultOf<(Target<'s>, Position)> {
|
) -> RhaiResultOf<(Target<'s>, Position)> {
|
||||||
// Make sure that the pointer indirection is taken only when absolutely necessary.
|
// Make sure that the pointer indirection is taken only when absolutely necessary.
|
||||||
@ -148,10 +146,11 @@ impl Engine {
|
|||||||
let (index, var_pos) = match expr {
|
let (index, var_pos) = match expr {
|
||||||
// Check if the variable is `this`
|
// Check if the variable is `this`
|
||||||
Expr::Variable(v, None, pos) if v.0.is_none() && v.3 == KEYWORD_THIS => {
|
Expr::Variable(v, None, pos) if v.0.is_none() && v.3 == KEYWORD_THIS => {
|
||||||
return this_ptr.as_mut().map_or_else(
|
return if this_ptr.is_null() {
|
||||||
|| Err(ERR::ErrorUnboundThis(*pos).into()),
|
Err(ERR::ErrorUnboundThis(*pos).into())
|
||||||
|val| Ok(((*val).into(), *pos)),
|
} else {
|
||||||
)
|
Ok((this_ptr.into(), *pos))
|
||||||
|
};
|
||||||
}
|
}
|
||||||
_ if global.always_search_scope => (0, expr.start_position()),
|
_ if global.always_search_scope => (0, expr.start_position()),
|
||||||
Expr::Variable(.., Some(i), pos) => (i.get() as usize, *pos),
|
Expr::Variable(.., Some(i), pos) => (i.get() as usize, *pos),
|
||||||
@ -160,7 +159,7 @@ impl Engine {
|
|||||||
Expr::Variable(v, None, pos)
|
Expr::Variable(v, None, pos)
|
||||||
if lib
|
if lib
|
||||||
.iter()
|
.iter()
|
||||||
.flat_map(|&m| m.iter_script_fn())
|
.flat_map(|m| m.iter_script_fn())
|
||||||
.any(|(_, _, f, ..)| f == v.3.as_str()) =>
|
.any(|(_, _, f, ..)| f == v.3.as_str()) =>
|
||||||
{
|
{
|
||||||
let val: Dynamic =
|
let val: Dynamic =
|
||||||
@ -173,7 +172,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::new(self, global, Some(caches), lib, level, scope, this_ptr);
|
let context = EvalContext::new(self, global, caches, lib, scope, this_ptr);
|
||||||
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)) => {
|
||||||
@ -221,10 +220,10 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
this_ptr: &mut Dynamic,
|
||||||
expr: &Expr,
|
expr: &Expr,
|
||||||
) -> RhaiResult {
|
) -> RhaiResult {
|
||||||
// Coded this way for better branch prediction.
|
// Coded this way for better branch prediction.
|
||||||
@ -234,18 +233,15 @@ impl Engine {
|
|||||||
// binary operators are also function calls.
|
// binary operators are also function calls.
|
||||||
if let Expr::FnCall(x, pos) = expr {
|
if let Expr::FnCall(x, pos) = expr {
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
let reset_debugger =
|
let reset = self.run_debugger_with_reset(global, caches, lib, scope, this_ptr, expr)?;
|
||||||
self.run_debugger_with_reset(global, caches, lib, level, scope, this_ptr, expr)?;
|
#[cfg(feature = "debugging")]
|
||||||
|
let global = &mut *crate::types::RestoreOnDrop::lock(global, move |g| {
|
||||||
|
g.debugger.reset_status(reset)
|
||||||
|
});
|
||||||
|
|
||||||
self.track_operation(global, expr.position())?;
|
self.track_operation(global, expr.position())?;
|
||||||
|
|
||||||
let result =
|
return self.eval_fn_call_expr(global, caches, lib, scope, this_ptr, x, *pos);
|
||||||
self.eval_fn_call_expr(global, caches, lib, level, scope, this_ptr, x, *pos);
|
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
|
||||||
global.debugger.reset_status(reset_debugger);
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Then variable access.
|
// Then variable access.
|
||||||
@ -253,28 +249,32 @@ impl Engine {
|
|||||||
// will cost more than the mis-predicted `match` branch.
|
// will cost more than the mis-predicted `match` branch.
|
||||||
if let Expr::Variable(x, index, var_pos) = expr {
|
if let Expr::Variable(x, index, var_pos) = expr {
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
self.run_debugger(global, caches, lib, level, scope, this_ptr, expr)?;
|
self.run_debugger(global, caches, lib, scope, this_ptr, expr)?;
|
||||||
|
|
||||||
self.track_operation(global, expr.position())?;
|
self.track_operation(global, expr.position())?;
|
||||||
|
|
||||||
return if index.is_none() && x.0.is_none() && x.3 == KEYWORD_THIS {
|
return if index.is_none() && x.0.is_none() && x.3 == KEYWORD_THIS {
|
||||||
this_ptr
|
if this_ptr.is_null() {
|
||||||
.as_deref()
|
ERR::ErrorUnboundThis(*var_pos).into()
|
||||||
.cloned()
|
|
||||||
.ok_or_else(|| ERR::ErrorUnboundThis(*var_pos).into())
|
|
||||||
} else {
|
} else {
|
||||||
self.search_namespace(global, caches, lib, level, scope, this_ptr, expr)
|
Ok(this_ptr.clone())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.search_namespace(global, caches, lib, scope, this_ptr, expr)
|
||||||
.map(|(val, ..)| val.take_or_clone())
|
.map(|(val, ..)| val.take_or_clone())
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
let reset_debugger =
|
let reset = self.run_debugger_with_reset(global, caches, lib, scope, this_ptr, expr)?;
|
||||||
self.run_debugger_with_reset(global, caches, lib, level, scope, this_ptr, expr)?;
|
#[cfg(feature = "debugging")]
|
||||||
|
let global = &mut *crate::types::RestoreOnDrop::lock(global, move |g| {
|
||||||
|
g.debugger.reset_status(reset)
|
||||||
|
});
|
||||||
|
|
||||||
self.track_operation(global, expr.position())?;
|
self.track_operation(global, expr.position())?;
|
||||||
|
|
||||||
let result = match expr {
|
match expr {
|
||||||
// Constants
|
// Constants
|
||||||
Expr::DynamicConstant(x, ..) => Ok(x.as_ref().clone()),
|
Expr::DynamicConstant(x, ..) => Ok(x.as_ref().clone()),
|
||||||
Expr::IntegerConstant(x, ..) => Ok((*x).into()),
|
Expr::IntegerConstant(x, ..) => Ok((*x).into()),
|
||||||
@ -296,14 +296,11 @@ impl Engine {
|
|||||||
let result = x
|
let result = x
|
||||||
.iter()
|
.iter()
|
||||||
.try_for_each(|expr| {
|
.try_for_each(|expr| {
|
||||||
let item =
|
let item = self.eval_expr(global, caches, lib, scope, this_ptr, expr)?;
|
||||||
self.eval_expr(global, caches, lib, level, scope, this_ptr, expr)?;
|
|
||||||
|
|
||||||
op_info.pos = expr.start_position();
|
op_info.pos = expr.start_position();
|
||||||
|
|
||||||
self.eval_op_assignment(
|
self.eval_op_assignment(global, caches, lib, &op_info, target, root, item)
|
||||||
global, caches, lib, level, &op_info, target, root, item,
|
|
||||||
)
|
|
||||||
})
|
})
|
||||||
.map(|_| concat.take_or_clone());
|
.map(|_| concat.take_or_clone());
|
||||||
|
|
||||||
@ -320,7 +317,7 @@ impl Engine {
|
|||||||
crate::Array::with_capacity(x.len()),
|
crate::Array::with_capacity(x.len()),
|
||||||
|mut array, item_expr| {
|
|mut array, item_expr| {
|
||||||
let value = self
|
let value = self
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, item_expr)?
|
.eval_expr(global, caches, lib, scope, this_ptr, item_expr)?
|
||||||
.flatten();
|
.flatten();
|
||||||
|
|
||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
@ -352,7 +349,7 @@ impl Engine {
|
|||||||
x.0.iter()
|
x.0.iter()
|
||||||
.try_fold(x.1.clone(), |mut map, (key, value_expr)| {
|
.try_fold(x.1.clone(), |mut map, (key, value_expr)| {
|
||||||
let value = self
|
let value = self
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, value_expr)?
|
.eval_expr(global, caches, lib, scope, this_ptr, value_expr)?
|
||||||
.flatten();
|
.flatten();
|
||||||
|
|
||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
@ -374,60 +371,33 @@ impl Engine {
|
|||||||
.map(Into::into)
|
.map(Into::into)
|
||||||
}
|
}
|
||||||
|
|
||||||
Expr::And(x, ..) => {
|
Expr::And(x, ..) => Ok((self
|
||||||
let lhs = self
|
.eval_expr(global, caches, lib, scope, this_ptr, &x.lhs)?
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, &x.lhs)
|
.as_bool()
|
||||||
.and_then(|v| {
|
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, x.lhs.position()))?
|
||||||
v.as_bool().map_err(|typ| {
|
&& self
|
||||||
self.make_type_mismatch_err::<bool>(typ, x.lhs.position())
|
.eval_expr(global, caches, lib, scope, this_ptr, &x.rhs)?
|
||||||
})
|
.as_bool()
|
||||||
});
|
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, x.rhs.position()))?)
|
||||||
|
.into()),
|
||||||
|
|
||||||
match lhs {
|
Expr::Or(x, ..) => Ok((self
|
||||||
Ok(true) => self
|
.eval_expr(global, caches, lib, scope, this_ptr, &x.lhs)?
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, &x.rhs)
|
.as_bool()
|
||||||
.and_then(|v| {
|
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, x.lhs.position()))?
|
||||||
v.as_bool()
|
|| self
|
||||||
.map_err(|typ| {
|
.eval_expr(global, caches, lib, scope, this_ptr, &x.rhs)?
|
||||||
self.make_type_mismatch_err::<bool>(typ, x.rhs.position())
|
.as_bool()
|
||||||
})
|
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, x.rhs.position()))?)
|
||||||
.map(Into::into)
|
.into()),
|
||||||
}),
|
|
||||||
_ => lhs.map(Into::into),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Expr::Or(x, ..) => {
|
|
||||||
let lhs = self
|
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, &x.lhs)
|
|
||||||
.and_then(|v| {
|
|
||||||
v.as_bool().map_err(|typ| {
|
|
||||||
self.make_type_mismatch_err::<bool>(typ, x.lhs.position())
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
match lhs {
|
|
||||||
Ok(false) => self
|
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, &x.rhs)
|
|
||||||
.and_then(|v| {
|
|
||||||
v.as_bool()
|
|
||||||
.map_err(|typ| {
|
|
||||||
self.make_type_mismatch_err::<bool>(typ, x.rhs.position())
|
|
||||||
})
|
|
||||||
.map(Into::into)
|
|
||||||
}),
|
|
||||||
_ => lhs.map(Into::into),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Expr::Coalesce(x, ..) => {
|
Expr::Coalesce(x, ..) => {
|
||||||
let lhs = self.eval_expr(global, caches, lib, level, scope, this_ptr, &x.lhs);
|
let value = self.eval_expr(global, caches, lib, scope, this_ptr, &x.lhs)?;
|
||||||
|
|
||||||
match lhs {
|
if value.is::<()>() {
|
||||||
Ok(value) if value.is::<()>() => {
|
self.eval_expr(global, caches, lib, scope, this_ptr, &x.rhs)
|
||||||
self.eval_expr(global, caches, lib, level, scope, this_ptr, &x.rhs)
|
} else {
|
||||||
}
|
Ok(value)
|
||||||
_ => lhs,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -445,8 +415,7 @@ impl Engine {
|
|||||||
*pos,
|
*pos,
|
||||||
))
|
))
|
||||||
})?;
|
})?;
|
||||||
let mut context =
|
let mut context = EvalContext::new(self, global, caches, lib, scope, this_ptr);
|
||||||
EvalContext::new(self, global, Some(caches), lib, level, scope, this_ptr);
|
|
||||||
|
|
||||||
let result = (custom_def.func)(&mut context, &expressions, &custom.state);
|
let result = (custom_def.func)(&mut context, &expressions, &custom.state);
|
||||||
|
|
||||||
@ -454,24 +423,19 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Expr::Stmt(x) if x.is_empty() => Ok(Dynamic::UNIT),
|
Expr::Stmt(x) if x.is_empty() => Ok(Dynamic::UNIT),
|
||||||
Expr::Stmt(x) => {
|
Expr::Stmt(x) => self.eval_stmt_block(global, caches, lib, scope, this_ptr, x, true),
|
||||||
self.eval_stmt_block(global, caches, lib, level, scope, this_ptr, x, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(feature = "no_index"))]
|
#[cfg(not(feature = "no_index"))]
|
||||||
Expr::Index(..) => self
|
Expr::Index(..) => {
|
||||||
.eval_dot_index_chain(global, caches, lib, level, scope, this_ptr, expr, &mut None),
|
self.eval_dot_index_chain(global, caches, lib, scope, this_ptr, expr, &mut None)
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "no_object"))]
|
#[cfg(not(feature = "no_object"))]
|
||||||
Expr::Dot(..) => self
|
Expr::Dot(..) => {
|
||||||
.eval_dot_index_chain(global, caches, lib, level, scope, this_ptr, expr, &mut None),
|
self.eval_dot_index_chain(global, caches, lib, scope, this_ptr, expr, &mut None)
|
||||||
|
}
|
||||||
|
|
||||||
_ => unreachable!("expression cannot be evaluated: {:?}", expr),
|
_ => unreachable!("expression cannot be evaluated: {:?}", expr),
|
||||||
};
|
}
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
|
||||||
global.debugger.reset_status(reset_debugger);
|
|
||||||
|
|
||||||
result
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
//! Global runtime state.
|
//! Global runtime state.
|
||||||
|
|
||||||
use crate::{Dynamic, Engine, ImmutableString};
|
use crate::{Dynamic, Engine, ImmutableString};
|
||||||
|
use std::fmt;
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
use std::{fmt, marker::PhantomData};
|
|
||||||
|
|
||||||
/// Collection of globally-defined constants.
|
/// Collection of globally-defined constants.
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
@ -22,13 +22,13 @@ pub type GlobalConstants =
|
|||||||
// Most usage will be looking up a particular key from the list and then getting the module that
|
// Most usage will be looking up a particular key from the list and then getting the module that
|
||||||
// corresponds to that key.
|
// corresponds to that key.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct GlobalRuntimeState<'a> {
|
pub struct GlobalRuntimeState {
|
||||||
/// Names of imported [modules][crate::Module].
|
/// Names of imported [modules][crate::Module].
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
imports: crate::StaticVec<ImmutableString>,
|
imports: crate::StaticVec<ImmutableString>,
|
||||||
/// Stack of imported [modules][crate::Module].
|
/// Stack of imported [modules][crate::Module].
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
modules: crate::StaticVec<crate::Shared<crate::Module>>,
|
modules: crate::StaticVec<crate::SharedModule>,
|
||||||
/// Source of the current context.
|
/// Source of the current context.
|
||||||
///
|
///
|
||||||
/// No source if the string is empty.
|
/// No source if the string is empty.
|
||||||
@ -38,6 +38,8 @@ pub struct GlobalRuntimeState<'a> {
|
|||||||
/// Number of modules loaded.
|
/// Number of modules loaded.
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
pub num_modules_loaded: usize,
|
pub num_modules_loaded: usize,
|
||||||
|
/// The current nesting level of function calls.
|
||||||
|
pub level: usize,
|
||||||
/// Level of the current scope.
|
/// Level of the current scope.
|
||||||
///
|
///
|
||||||
/// The global (root) level is zero, a new block (or function call) is one level higher, and so on.
|
/// The global (root) level is zero, a new block (or function call) is one level higher, and so on.
|
||||||
@ -70,11 +72,9 @@ pub struct GlobalRuntimeState<'a> {
|
|||||||
/// Debugging interface.
|
/// Debugging interface.
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
pub debugger: super::Debugger,
|
pub debugger: super::Debugger,
|
||||||
/// Take care of the lifetime parameter.
|
|
||||||
dummy: PhantomData<&'a ()>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GlobalRuntimeState<'_> {
|
impl GlobalRuntimeState {
|
||||||
/// Create a new [`GlobalRuntimeState`] based on an [`Engine`].
|
/// Create a new [`GlobalRuntimeState`] based on an [`Engine`].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
@ -89,6 +89,7 @@ impl GlobalRuntimeState<'_> {
|
|||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
num_modules_loaded: 0,
|
num_modules_loaded: 0,
|
||||||
scope_level: 0,
|
scope_level: 0,
|
||||||
|
level: 0,
|
||||||
always_search_scope: false,
|
always_search_scope: false,
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
embedded_module_resolver: None,
|
embedded_module_resolver: None,
|
||||||
@ -112,8 +113,6 @@ impl GlobalRuntimeState<'_> {
|
|||||||
None => Dynamic::UNIT,
|
None => Dynamic::UNIT,
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
|
|
||||||
dummy: PhantomData::default(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// Get the length of the stack of globally-imported [modules][crate::Module].
|
/// Get the length of the stack of globally-imported [modules][crate::Module].
|
||||||
@ -131,7 +130,7 @@ impl GlobalRuntimeState<'_> {
|
|||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn get_shared_import(&self, index: usize) -> Option<crate::Shared<crate::Module>> {
|
pub fn get_shared_import(&self, index: usize) -> Option<crate::SharedModule> {
|
||||||
self.modules.get(index).cloned()
|
self.modules.get(index).cloned()
|
||||||
}
|
}
|
||||||
/// Get a mutable reference to the globally-imported [module][crate::Module] at a
|
/// Get a mutable reference to the globally-imported [module][crate::Module] at a
|
||||||
@ -145,7 +144,7 @@ impl GlobalRuntimeState<'_> {
|
|||||||
pub(crate) fn get_shared_import_mut(
|
pub(crate) fn get_shared_import_mut(
|
||||||
&mut self,
|
&mut self,
|
||||||
index: usize,
|
index: usize,
|
||||||
) -> Option<&mut crate::Shared<crate::Module>> {
|
) -> Option<&mut crate::SharedModule> {
|
||||||
self.modules.get_mut(index)
|
self.modules.get_mut(index)
|
||||||
}
|
}
|
||||||
/// Get the index of a globally-imported [module][crate::Module] by name.
|
/// Get the index of a globally-imported [module][crate::Module] by name.
|
||||||
@ -169,7 +168,7 @@ impl GlobalRuntimeState<'_> {
|
|||||||
pub fn push_import(
|
pub fn push_import(
|
||||||
&mut self,
|
&mut self,
|
||||||
name: impl Into<ImmutableString>,
|
name: impl Into<ImmutableString>,
|
||||||
module: impl Into<crate::Shared<crate::Module>>,
|
module: impl Into<crate::SharedModule>,
|
||||||
) {
|
) {
|
||||||
self.imports.push(name.into());
|
self.imports.push(name.into());
|
||||||
self.modules.push(module.into());
|
self.modules.push(module.into());
|
||||||
@ -202,7 +201,7 @@ impl GlobalRuntimeState<'_> {
|
|||||||
#[inline]
|
#[inline]
|
||||||
pub(crate) fn iter_imports_raw(
|
pub(crate) fn iter_imports_raw(
|
||||||
&self,
|
&self,
|
||||||
) -> impl Iterator<Item = (&ImmutableString, &crate::Shared<crate::Module>)> {
|
) -> impl Iterator<Item = (&ImmutableString, &crate::SharedModule)> {
|
||||||
self.imports.iter().zip(self.modules.iter()).rev()
|
self.imports.iter().zip(self.modules.iter()).rev()
|
||||||
}
|
}
|
||||||
/// Get an iterator to the stack of globally-imported [modules][crate::Module] in forward order.
|
/// Get an iterator to the stack of globally-imported [modules][crate::Module] in forward order.
|
||||||
@ -212,7 +211,7 @@ impl GlobalRuntimeState<'_> {
|
|||||||
#[inline]
|
#[inline]
|
||||||
pub fn scan_imports_raw(
|
pub fn scan_imports_raw(
|
||||||
&self,
|
&self,
|
||||||
) -> impl Iterator<Item = (&ImmutableString, &crate::Shared<crate::Module>)> {
|
) -> impl Iterator<Item = (&ImmutableString, &crate::SharedModule)> {
|
||||||
self.imports.iter().zip(self.modules.iter())
|
self.imports.iter().zip(self.modules.iter())
|
||||||
}
|
}
|
||||||
/// Can the particular function with [`Dynamic`] parameter(s) exist in the stack of
|
/// Can the particular function with [`Dynamic`] parameter(s) exist in the stack of
|
||||||
@ -319,12 +318,12 @@ impl GlobalRuntimeState<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
impl IntoIterator for GlobalRuntimeState<'_> {
|
impl IntoIterator for GlobalRuntimeState {
|
||||||
type Item = (ImmutableString, crate::Shared<crate::Module>);
|
type Item = (ImmutableString, crate::SharedModule);
|
||||||
type IntoIter = std::iter::Rev<
|
type IntoIter = std::iter::Rev<
|
||||||
std::iter::Zip<
|
std::iter::Zip<
|
||||||
smallvec::IntoIter<[ImmutableString; crate::STATIC_VEC_INLINE_SIZE]>,
|
smallvec::IntoIter<[ImmutableString; crate::STATIC_VEC_INLINE_SIZE]>,
|
||||||
smallvec::IntoIter<[crate::Shared<crate::Module>; crate::STATIC_VEC_INLINE_SIZE]>,
|
smallvec::IntoIter<[crate::SharedModule; crate::STATIC_VEC_INLINE_SIZE]>,
|
||||||
>,
|
>,
|
||||||
>;
|
>;
|
||||||
|
|
||||||
@ -334,12 +333,12 @@ impl IntoIterator for GlobalRuntimeState<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
impl<'a> IntoIterator for &'a GlobalRuntimeState<'_> {
|
impl<'a> IntoIterator for &'a GlobalRuntimeState {
|
||||||
type Item = (&'a ImmutableString, &'a crate::Shared<crate::Module>);
|
type Item = (&'a ImmutableString, &'a crate::SharedModule);
|
||||||
type IntoIter = std::iter::Rev<
|
type IntoIter = std::iter::Rev<
|
||||||
std::iter::Zip<
|
std::iter::Zip<
|
||||||
std::slice::Iter<'a, ImmutableString>,
|
std::slice::Iter<'a, ImmutableString>,
|
||||||
std::slice::Iter<'a, crate::Shared<crate::Module>>,
|
std::slice::Iter<'a, crate::SharedModule>,
|
||||||
>,
|
>,
|
||||||
>;
|
>;
|
||||||
|
|
||||||
@ -349,9 +348,7 @@ impl<'a> IntoIterator for &'a GlobalRuntimeState<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
impl<K: Into<ImmutableString>, M: Into<crate::Shared<crate::Module>>> Extend<(K, M)>
|
impl<K: Into<ImmutableString>, M: Into<crate::SharedModule>> Extend<(K, M)> for GlobalRuntimeState {
|
||||||
for GlobalRuntimeState<'_>
|
|
||||||
{
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn extend<T: IntoIterator<Item = (K, M)>>(&mut self, iter: T) {
|
fn extend<T: IntoIterator<Item = (K, M)>>(&mut self, iter: T) {
|
||||||
for (k, m) in iter {
|
for (k, m) in iter {
|
||||||
@ -361,7 +358,7 @@ impl<K: Into<ImmutableString>, M: Into<crate::Shared<crate::Module>>> Extend<(K,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Debug for GlobalRuntimeState<'_> {
|
impl fmt::Debug for GlobalRuntimeState {
|
||||||
#[cold]
|
#[cold]
|
||||||
#[inline(never)]
|
#[inline(never)]
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
564
src/eval/stmt.rs
564
src/eval/stmt.rs
@ -7,9 +7,8 @@ use crate::ast::{
|
|||||||
};
|
};
|
||||||
use crate::func::{get_builtin_op_assignment_fn, get_hasher};
|
use crate::func::{get_builtin_op_assignment_fn, get_hasher};
|
||||||
use crate::types::dynamic::{AccessMode, Union};
|
use crate::types::dynamic::{AccessMode, Union};
|
||||||
use crate::{
|
use crate::types::RestoreOnDrop;
|
||||||
Dynamic, Engine, ImmutableString, Module, Position, RhaiResult, RhaiResultOf, Scope, ERR, INT,
|
use crate::{Dynamic, Engine, Position, RhaiResult, RhaiResultOf, Scope, SharedModule, ERR, INT};
|
||||||
};
|
|
||||||
use std::hash::{Hash, Hasher};
|
use std::hash::{Hash, Hasher};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
@ -27,10 +26,9 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
this_ptr: &mut Dynamic,
|
||||||
statements: &[Stmt],
|
statements: &[Stmt],
|
||||||
restore_orig_state: bool,
|
restore_orig_state: bool,
|
||||||
) -> RhaiResult {
|
) -> RhaiResult {
|
||||||
@ -38,17 +36,40 @@ impl Engine {
|
|||||||
return Ok(Dynamic::UNIT);
|
return Ok(Dynamic::UNIT);
|
||||||
}
|
}
|
||||||
|
|
||||||
let orig_always_search_scope = global.always_search_scope;
|
// Restore scope at end of block if necessary
|
||||||
let orig_scope_len = scope.len();
|
let orig_scope_len = scope.len();
|
||||||
|
let scope = &mut *RestoreOnDrop::lock_if(restore_orig_state, scope, move |s| {
|
||||||
|
s.rewind(orig_scope_len);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Restore global state at end of block if necessary
|
||||||
|
let orig_always_search_scope = global.always_search_scope;
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
let orig_imports_len = global.num_imports();
|
let orig_imports_len = global.num_imports();
|
||||||
let orig_fn_resolution_caches_len = caches.fn_resolution_caches_len();
|
|
||||||
|
|
||||||
if restore_orig_state {
|
if restore_orig_state {
|
||||||
global.scope_level += 1;
|
global.scope_level += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
let result = statements.iter().try_fold(Dynamic::UNIT, |_, stmt| {
|
let global = &mut *RestoreOnDrop::lock_if(restore_orig_state, global, move |g| {
|
||||||
|
g.scope_level -= 1;
|
||||||
|
|
||||||
|
#[cfg(not(feature = "no_module"))]
|
||||||
|
g.truncate_imports(orig_imports_len);
|
||||||
|
|
||||||
|
// The impact of new local variables goes away at the end of a block
|
||||||
|
// because any new variables introduced will go out of scope
|
||||||
|
g.always_search_scope = orig_always_search_scope;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Pop new function resolution caches at end of block
|
||||||
|
let orig_fn_resolution_caches_len = caches.fn_resolution_caches_len();
|
||||||
|
let caches = &mut *RestoreOnDrop::lock(caches, move |c| {
|
||||||
|
c.rewind_fn_resolution_caches(orig_fn_resolution_caches_len)
|
||||||
|
});
|
||||||
|
|
||||||
|
// Run the statements
|
||||||
|
statements.iter().try_fold(Dynamic::UNIT, |_, stmt| {
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
let imports_len = global.num_imports();
|
let imports_len = global.num_imports();
|
||||||
|
|
||||||
@ -56,7 +77,6 @@ impl Engine {
|
|||||||
global,
|
global,
|
||||||
caches,
|
caches,
|
||||||
lib,
|
lib,
|
||||||
level,
|
|
||||||
scope,
|
scope,
|
||||||
this_ptr,
|
this_ptr,
|
||||||
stmt,
|
stmt,
|
||||||
@ -72,10 +92,11 @@ impl Engine {
|
|||||||
.skip(imports_len)
|
.skip(imports_len)
|
||||||
.any(|(.., m)| m.contains_indexed_global_functions())
|
.any(|(.., m)| m.contains_indexed_global_functions())
|
||||||
{
|
{
|
||||||
|
// Different scenarios where the cache must be cleared - notice that this is
|
||||||
|
// expensive as all function resolutions must start again
|
||||||
if caches.fn_resolution_caches_len() > orig_fn_resolution_caches_len {
|
if caches.fn_resolution_caches_len() > orig_fn_resolution_caches_len {
|
||||||
// When new module is imported with global functions and there is already
|
// When new module is imported with global functions and there is already
|
||||||
// a new cache, clear it - notice that this is expensive as all function
|
// a new cache, just clear it
|
||||||
// resolutions must start again
|
|
||||||
caches.fn_resolution_cache_mut().clear();
|
caches.fn_resolution_cache_mut().clear();
|
||||||
} else if restore_orig_state {
|
} else if restore_orig_state {
|
||||||
// When new module is imported with global functions, push a new cache
|
// When new module is imported with global functions, push a new cache
|
||||||
@ -88,23 +109,7 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Ok(result)
|
Ok(result)
|
||||||
});
|
})
|
||||||
|
|
||||||
// If imports list is modified, pop the functions lookup cache
|
|
||||||
caches.rewind_fn_resolution_caches(orig_fn_resolution_caches_len);
|
|
||||||
|
|
||||||
if restore_orig_state {
|
|
||||||
scope.rewind(orig_scope_len);
|
|
||||||
global.scope_level -= 1;
|
|
||||||
#[cfg(not(feature = "no_module"))]
|
|
||||||
global.truncate_imports(orig_imports_len);
|
|
||||||
|
|
||||||
// The impact of new local variables goes away at the end of a block
|
|
||||||
// because any new variables introduced will go out of scope
|
|
||||||
global.always_search_scope = orig_always_search_scope;
|
|
||||||
}
|
|
||||||
|
|
||||||
result
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluate an op-assignment statement.
|
/// Evaluate an op-assignment statement.
|
||||||
@ -112,20 +117,17 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
op_info: &OpAssignment,
|
op_info: &OpAssignment,
|
||||||
target: &mut Target,
|
target: &mut Target,
|
||||||
root: (&str, Position),
|
root: (&str, Position),
|
||||||
new_val: Dynamic,
|
mut new_val: Dynamic,
|
||||||
) -> RhaiResultOf<()> {
|
) -> RhaiResultOf<()> {
|
||||||
|
// Assignment to constant variable?
|
||||||
if target.is_read_only() {
|
if target.is_read_only() {
|
||||||
// Assignment to constant variable
|
|
||||||
return Err(ERR::ErrorAssignmentToConstant(root.0.to_string(), root.1).into());
|
return Err(ERR::ErrorAssignmentToConstant(root.0.to_string(), root.1).into());
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut new_val = new_val;
|
|
||||||
|
|
||||||
if op_info.is_op_assignment() {
|
if op_info.is_op_assignment() {
|
||||||
let OpAssignment {
|
let OpAssignment {
|
||||||
hash_op_assign,
|
hash_op_assign,
|
||||||
@ -139,14 +141,17 @@ impl Engine {
|
|||||||
|
|
||||||
let hash = *hash_op_assign;
|
let hash = *hash_op_assign;
|
||||||
let args = &mut [&mut *lock_guard, &mut new_val];
|
let args = &mut [&mut *lock_guard, &mut new_val];
|
||||||
let level = level + 1;
|
|
||||||
|
|
||||||
if self.fast_operators() {
|
if self.fast_operators() {
|
||||||
if let Some(func) = get_builtin_op_assignment_fn(op_assign_token, args[0], args[1])
|
if let Some(func) = get_builtin_op_assignment_fn(op_assign_token, args[0], args[1])
|
||||||
{
|
{
|
||||||
// Built-in found
|
// Built-in found
|
||||||
let op = op_assign_token.literal_syntax();
|
let op = op_assign_token.literal_syntax();
|
||||||
let context = (self, op, None, &*global, lib, *op_pos, level).into();
|
|
||||||
|
global.level += 1;
|
||||||
|
let global = &*RestoreOnDrop::lock(global, move |g| g.level -= 1);
|
||||||
|
|
||||||
|
let context = (self, op, None, global, lib, *op_pos).into();
|
||||||
return func(context, args).map(|_| ());
|
return func(context, args).map(|_| ());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -156,7 +161,7 @@ impl Engine {
|
|||||||
let token = Some(op_assign_token);
|
let token = Some(op_assign_token);
|
||||||
|
|
||||||
match self.exec_native_fn_call(
|
match self.exec_native_fn_call(
|
||||||
global, caches, lib, level, op_assign, token, hash, args, true, *op_pos,
|
global, caches, lib, op_assign, token, hash, args, true, *op_pos,
|
||||||
) {
|
) {
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(err) if matches!(*err, ERR::ErrorFunctionNotFound(ref f, ..) if f.starts_with(op_assign)) =>
|
Err(err) if matches!(*err, ERR::ErrorFunctionNotFound(ref f, ..) if f.starts_with(op_assign)) =>
|
||||||
@ -166,7 +171,7 @@ impl Engine {
|
|||||||
|
|
||||||
*args[0] = self
|
*args[0] = self
|
||||||
.exec_native_fn_call(
|
.exec_native_fn_call(
|
||||||
global, caches, lib, level, op, token, *hash_op, args, true, *op_pos,
|
global, caches, lib, op, token, *hash_op, args, true, *op_pos,
|
||||||
)
|
)
|
||||||
.map_err(|err| err.fill_position(op_info.pos))?
|
.map_err(|err| err.fill_position(op_info.pos))?
|
||||||
.0
|
.0
|
||||||
@ -196,16 +201,16 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
this_ptr: &mut Dynamic,
|
||||||
stmt: &Stmt,
|
stmt: &Stmt,
|
||||||
rewind_scope: bool,
|
rewind_scope: bool,
|
||||||
) -> RhaiResult {
|
) -> RhaiResult {
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
let reset_debugger =
|
let reset = self.run_debugger_with_reset(global, caches, lib, scope, this_ptr, stmt)?;
|
||||||
self.run_debugger_with_reset(global, caches, lib, level, scope, this_ptr, stmt)?;
|
#[cfg(feature = "debugging")]
|
||||||
|
let global = &mut *RestoreOnDrop::lock(global, move |g| g.debugger.reset_status(reset));
|
||||||
|
|
||||||
// Coded this way for better branch prediction.
|
// Coded this way for better branch prediction.
|
||||||
// Popular branches are lifted out of the `match` statement into their own branches.
|
// Popular branches are lifted out of the `match` statement into their own branches.
|
||||||
@ -214,13 +219,7 @@ impl Engine {
|
|||||||
if let Stmt::FnCall(x, pos) = stmt {
|
if let Stmt::FnCall(x, pos) = stmt {
|
||||||
self.track_operation(global, stmt.position())?;
|
self.track_operation(global, stmt.position())?;
|
||||||
|
|
||||||
let result =
|
return self.eval_fn_call_expr(global, caches, lib, scope, this_ptr, x, *pos);
|
||||||
self.eval_fn_call_expr(global, caches, lib, level, scope, this_ptr, x, *pos);
|
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
|
||||||
global.debugger.reset_status(reset_debugger);
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Then assignments.
|
// Then assignments.
|
||||||
@ -231,17 +230,13 @@ impl Engine {
|
|||||||
|
|
||||||
self.track_operation(global, stmt.position())?;
|
self.track_operation(global, stmt.position())?;
|
||||||
|
|
||||||
let result = if let Expr::Variable(x, ..) = lhs {
|
if let Expr::Variable(x, ..) = lhs {
|
||||||
let rhs_result = self
|
let rhs_val = self
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, rhs)
|
.eval_expr(global, caches, lib, scope, this_ptr, rhs)?
|
||||||
.map(Dynamic::flatten);
|
.flatten();
|
||||||
|
|
||||||
if let Ok(rhs_val) = rhs_result {
|
let (mut lhs_ptr, pos) =
|
||||||
let search_result =
|
self.search_namespace(global, caches, lib, scope, this_ptr, lhs)?;
|
||||||
self.search_namespace(global, caches, lib, level, scope, this_ptr, lhs);
|
|
||||||
|
|
||||||
if let Ok(search_val) = search_result {
|
|
||||||
let (mut lhs_ptr, pos) = search_val;
|
|
||||||
|
|
||||||
let var_name = x.3.as_str();
|
let var_name = x.3.as_str();
|
||||||
|
|
||||||
@ -254,9 +249,7 @@ impl Engine {
|
|||||||
|
|
||||||
// Cannot assign to temp result from expression
|
// Cannot assign to temp result from expression
|
||||||
if is_temp_result {
|
if is_temp_result {
|
||||||
return Err(
|
return Err(ERR::ErrorAssignmentToConstant(var_name.to_string(), pos).into());
|
||||||
ERR::ErrorAssignmentToConstant(var_name.to_string(), pos).into()
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.track_operation(global, pos)?;
|
self.track_operation(global, pos)?;
|
||||||
@ -264,27 +257,20 @@ impl Engine {
|
|||||||
let root = (var_name, pos);
|
let root = (var_name, pos);
|
||||||
let lhs_ptr = &mut lhs_ptr;
|
let lhs_ptr = &mut lhs_ptr;
|
||||||
|
|
||||||
self.eval_op_assignment(
|
return self
|
||||||
global, caches, lib, level, op_info, lhs_ptr, root, rhs_val,
|
.eval_op_assignment(global, caches, lib, op_info, lhs_ptr, root, rhs_val)
|
||||||
)
|
.map(|_| Dynamic::UNIT);
|
||||||
.map(|_| Dynamic::UNIT)
|
|
||||||
} else {
|
|
||||||
search_result.map(|_| Dynamic::UNIT)
|
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
rhs_result
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let (op_info, BinaryExpr { lhs, rhs }) = &**x;
|
|
||||||
|
|
||||||
let rhs_result = self.eval_expr(global, caches, lib, level, scope, this_ptr, rhs);
|
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
||||||
|
{
|
||||||
|
let rhs_val = self.eval_expr(global, caches, lib, scope, this_ptr, rhs)?;
|
||||||
|
|
||||||
if let Ok(rhs_val) = rhs_result {
|
|
||||||
// Check if the result is a string. If so, intern it.
|
// Check if the result is a string. If so, intern it.
|
||||||
#[cfg(not(feature = "no_closure"))]
|
#[cfg(not(feature = "no_closure"))]
|
||||||
let is_string = !rhs_val.is_shared() && rhs_val.is::<ImmutableString>();
|
let is_string = !rhs_val.is_shared() && rhs_val.is::<crate::ImmutableString>();
|
||||||
#[cfg(feature = "no_closure")]
|
#[cfg(feature = "no_closure")]
|
||||||
let is_string = rhs_val.is::<ImmutableString>();
|
let is_string = rhs_val.is::<crate::ImmutableString>();
|
||||||
|
|
||||||
let rhs_val = if is_string {
|
let rhs_val = if is_string {
|
||||||
self.get_interned_string(
|
self.get_interned_string(
|
||||||
@ -298,7 +284,7 @@ impl Engine {
|
|||||||
let _new_val = &mut Some((rhs_val, op_info));
|
let _new_val = &mut Some((rhs_val, op_info));
|
||||||
|
|
||||||
// Must be either `var[index] op= val` or `var.prop op= val`
|
// Must be either `var[index] op= val` or `var.prop op= val`
|
||||||
match lhs {
|
return match lhs {
|
||||||
// name op= rhs (handled above)
|
// name op= rhs (handled above)
|
||||||
Expr::Variable(..) => {
|
Expr::Variable(..) => {
|
||||||
unreachable!("Expr::Variable case is already handled")
|
unreachable!("Expr::Variable case is already handled")
|
||||||
@ -306,69 +292,49 @@ impl Engine {
|
|||||||
// idx_lhs[idx_expr] op= rhs
|
// idx_lhs[idx_expr] op= rhs
|
||||||
#[cfg(not(feature = "no_index"))]
|
#[cfg(not(feature = "no_index"))]
|
||||||
Expr::Index(..) => self
|
Expr::Index(..) => self
|
||||||
.eval_dot_index_chain(
|
.eval_dot_index_chain(global, caches, lib, scope, this_ptr, lhs, _new_val),
|
||||||
global, caches, lib, level, scope, this_ptr, lhs, _new_val,
|
|
||||||
)
|
|
||||||
.map(|_| Dynamic::UNIT),
|
|
||||||
// dot_lhs.dot_rhs op= rhs
|
// dot_lhs.dot_rhs op= rhs
|
||||||
#[cfg(not(feature = "no_object"))]
|
#[cfg(not(feature = "no_object"))]
|
||||||
Expr::Dot(..) => self
|
Expr::Dot(..) => self
|
||||||
.eval_dot_index_chain(
|
.eval_dot_index_chain(global, caches, lib, scope, this_ptr, lhs, _new_val),
|
||||||
global, caches, lib, level, scope, this_ptr, lhs, _new_val,
|
|
||||||
)
|
|
||||||
.map(|_| Dynamic::UNIT),
|
|
||||||
_ => unreachable!("cannot assign to expression: {:?}", lhs),
|
_ => unreachable!("cannot assign to expression: {:?}", lhs),
|
||||||
}
|
}
|
||||||
} else {
|
.map(|_| Dynamic::UNIT);
|
||||||
rhs_result
|
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
|
||||||
global.debugger.reset_status(reset_debugger);
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.track_operation(global, stmt.position())?;
|
self.track_operation(global, stmt.position())?;
|
||||||
|
|
||||||
let result = match stmt {
|
match stmt {
|
||||||
// No-op
|
// No-op
|
||||||
Stmt::Noop(..) => Ok(Dynamic::UNIT),
|
Stmt::Noop(..) => Ok(Dynamic::UNIT),
|
||||||
|
|
||||||
// Expression as statement
|
// Expression as statement
|
||||||
Stmt::Expr(expr) => self
|
Stmt::Expr(expr) => self
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, expr)
|
.eval_expr(global, caches, lib, scope, this_ptr, expr)
|
||||||
.map(Dynamic::flatten),
|
.map(Dynamic::flatten),
|
||||||
|
|
||||||
// Block scope
|
// Block scope
|
||||||
Stmt::Block(statements, ..) if statements.is_empty() => Ok(Dynamic::UNIT),
|
Stmt::Block(statements, ..) if statements.is_empty() => Ok(Dynamic::UNIT),
|
||||||
Stmt::Block(statements, ..) => self.eval_stmt_block(
|
Stmt::Block(statements, ..) => {
|
||||||
global, caches, lib, level, scope, this_ptr, statements, true,
|
self.eval_stmt_block(global, caches, lib, scope, this_ptr, statements, true)
|
||||||
),
|
}
|
||||||
|
|
||||||
// If statement
|
// If statement
|
||||||
Stmt::If(x, ..) => {
|
Stmt::If(x, ..) => {
|
||||||
let (expr, if_block, else_block) = &**x;
|
let (expr, if_block, else_block) = &**x;
|
||||||
|
|
||||||
let guard_val = self
|
let guard_val = self
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, expr)
|
.eval_expr(global, caches, lib, scope, this_ptr, expr)?
|
||||||
.and_then(|v| {
|
.as_bool()
|
||||||
v.as_bool().map_err(|typ| {
|
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, expr.position()))?;
|
||||||
self.make_type_mismatch_err::<bool>(typ, expr.position())
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
match guard_val {
|
if guard_val && !if_block.is_empty() {
|
||||||
Ok(true) if if_block.is_empty() => Ok(Dynamic::UNIT),
|
self.eval_stmt_block(global, caches, lib, scope, this_ptr, if_block, true)
|
||||||
Ok(true) => self.eval_stmt_block(
|
} else if !guard_val && !else_block.is_empty() {
|
||||||
global, caches, lib, level, scope, this_ptr, if_block, true,
|
self.eval_stmt_block(global, caches, lib, scope, this_ptr, else_block, true)
|
||||||
),
|
} else {
|
||||||
Ok(false) if else_block.is_empty() => Ok(Dynamic::UNIT),
|
Ok(Dynamic::UNIT)
|
||||||
Ok(false) => self.eval_stmt_block(
|
|
||||||
global, caches, lib, level, scope, this_ptr, else_block, true,
|
|
||||||
),
|
|
||||||
err => err.map(Into::into),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -384,11 +350,11 @@ impl Engine {
|
|||||||
},
|
},
|
||||||
) = &**x;
|
) = &**x;
|
||||||
|
|
||||||
let value_result =
|
let mut result = None;
|
||||||
self.eval_expr(global, caches, lib, level, scope, this_ptr, expr);
|
|
||||||
|
|
||||||
if let Ok(value) = value_result {
|
let value = self.eval_expr(global, caches, lib, scope, this_ptr, expr)?;
|
||||||
let expr_result = if value.is_hashable() {
|
|
||||||
|
if value.is_hashable() {
|
||||||
let hasher = &mut get_hasher();
|
let hasher = &mut get_hasher();
|
||||||
value.hash(hasher);
|
value.hash(hasher);
|
||||||
let hash = hasher.finish();
|
let hash = hasher.finish();
|
||||||
@ -397,88 +363,54 @@ impl Engine {
|
|||||||
if let Some(case_blocks_list) = cases.get(&hash) {
|
if let Some(case_blocks_list) = cases.get(&hash) {
|
||||||
assert!(!case_blocks_list.is_empty());
|
assert!(!case_blocks_list.is_empty());
|
||||||
|
|
||||||
let mut result = Ok(None);
|
|
||||||
|
|
||||||
for &index in case_blocks_list {
|
for &index in case_blocks_list {
|
||||||
let block = &expressions[index];
|
let block = &expressions[index];
|
||||||
|
|
||||||
let cond_result = match block.condition {
|
let cond_result = match block.condition {
|
||||||
Expr::BoolConstant(b, ..) => Ok(b),
|
Expr::BoolConstant(b, ..) => b,
|
||||||
ref c => self
|
ref c => self
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, c)
|
.eval_expr(global, caches, lib, scope, this_ptr, c)?
|
||||||
.and_then(|v| {
|
.as_bool()
|
||||||
v.as_bool().map_err(|typ| {
|
.map_err(|typ| {
|
||||||
self.make_type_mismatch_err::<bool>(
|
self.make_type_mismatch_err::<bool>(typ, c.position())
|
||||||
typ,
|
})?,
|
||||||
c.position(),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
match cond_result {
|
if cond_result {
|
||||||
Ok(true) => result = Ok(Some(&block.expr)),
|
result = Some(&block.expr);
|
||||||
Ok(false) => continue,
|
|
||||||
_ => result = cond_result.map(|_| None),
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
result
|
|
||||||
} else if value.is::<INT>() && !ranges.is_empty() {
|
} else if value.is::<INT>() && !ranges.is_empty() {
|
||||||
// Then check integer ranges
|
// Then check integer ranges
|
||||||
let value = value.as_int().expect("`INT`");
|
let value = value.as_int().expect("`INT`");
|
||||||
let mut result = Ok(None);
|
|
||||||
|
|
||||||
for r in ranges.iter().filter(|r| r.contains(value)) {
|
for r in ranges.iter().filter(|r| r.contains(value)) {
|
||||||
let block = &expressions[r.index()];
|
let block = &expressions[r.index()];
|
||||||
|
|
||||||
let cond_result = match block.condition {
|
let cond_result = match block.condition {
|
||||||
Expr::BoolConstant(b, ..) => Ok(b),
|
Expr::BoolConstant(b, ..) => b,
|
||||||
ref c => self
|
ref c => self
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, c)
|
.eval_expr(global, caches, lib, scope, this_ptr, c)?
|
||||||
.and_then(|v| {
|
.as_bool()
|
||||||
v.as_bool().map_err(|typ| {
|
.map_err(|typ| {
|
||||||
self.make_type_mismatch_err::<bool>(
|
self.make_type_mismatch_err::<bool>(typ, c.position())
|
||||||
typ,
|
})?,
|
||||||
c.position(),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
match cond_result {
|
if cond_result {
|
||||||
Ok(true) => result = Ok(Some(&block.expr)),
|
result = Some(&block.expr);
|
||||||
Ok(false) => continue,
|
|
||||||
_ => result = cond_result.map(|_| None),
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
result
|
result
|
||||||
} else {
|
.or_else(|| def_case.as_ref().map(|&index| &expressions[index].expr))
|
||||||
// Nothing matches
|
.map_or(Ok(Dynamic::UNIT), |expr| {
|
||||||
Ok(None)
|
self.eval_expr(global, caches, lib, scope, this_ptr, expr)
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Non-hashable
|
|
||||||
Ok(None)
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Ok(Some(expr)) = expr_result {
|
|
||||||
self.eval_expr(global, caches, lib, level, scope, this_ptr, expr)
|
|
||||||
} else if let Ok(None) = expr_result {
|
|
||||||
// Default match clause
|
|
||||||
def_case.as_ref().map_or(Ok(Dynamic::UNIT), |&index| {
|
|
||||||
let def_expr = &expressions[index].expr;
|
|
||||||
self.eval_expr(global, caches, lib, level, scope, this_ptr, def_expr)
|
|
||||||
})
|
})
|
||||||
} else {
|
|
||||||
expr_result.map(|_| Dynamic::UNIT)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
value_result
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Loop
|
// Loop
|
||||||
@ -489,17 +421,16 @@ impl Engine {
|
|||||||
loop {
|
loop {
|
||||||
self.track_operation(global, body.position())?;
|
self.track_operation(global, body.position())?;
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
match self.eval_stmt_block(
|
if let Err(err) =
|
||||||
global, caches, lib, level, scope, this_ptr, body, true,
|
self.eval_stmt_block(global, caches, lib, scope, this_ptr, body, true)
|
||||||
) {
|
{
|
||||||
Ok(_) => (),
|
match *err {
|
||||||
Err(err) => match *err {
|
|
||||||
ERR::LoopBreak(false, ..) => (),
|
ERR::LoopBreak(false, ..) => (),
|
||||||
ERR::LoopBreak(true, value, ..) => break Ok(value),
|
ERR::LoopBreak(true, value, ..) => break Ok(value),
|
||||||
_ => break Err(err),
|
_ => break Err(err),
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -511,30 +442,27 @@ impl Engine {
|
|||||||
|
|
||||||
loop {
|
loop {
|
||||||
let condition = self
|
let condition = self
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, expr)
|
.eval_expr(global, caches, lib, scope, this_ptr, expr)?
|
||||||
.and_then(|v| {
|
.as_bool()
|
||||||
v.as_bool().map_err(|typ| {
|
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, expr.position()))?;
|
||||||
self.make_type_mismatch_err::<bool>(typ, expr.position())
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
match condition {
|
if !condition {
|
||||||
Ok(false) => break Ok(Dynamic::UNIT),
|
break Ok(Dynamic::UNIT);
|
||||||
Ok(true) if body.is_empty() => (),
|
}
|
||||||
Ok(true) => {
|
|
||||||
match self.eval_stmt_block(
|
if body.is_empty() {
|
||||||
global, caches, lib, level, scope, this_ptr, body, true,
|
continue;
|
||||||
) {
|
}
|
||||||
Ok(_) => (),
|
|
||||||
Err(err) => match *err {
|
if let Err(err) =
|
||||||
|
self.eval_stmt_block(global, caches, lib, scope, this_ptr, body, true)
|
||||||
|
{
|
||||||
|
match *err {
|
||||||
ERR::LoopBreak(false, ..) => (),
|
ERR::LoopBreak(false, ..) => (),
|
||||||
ERR::LoopBreak(true, value, ..) => break Ok(value),
|
ERR::LoopBreak(true, value, ..) => break Ok(value),
|
||||||
_ => break Err(err),
|
_ => break Err(err),
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
err => break err.map(|_| Dynamic::UNIT),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -545,30 +473,24 @@ impl Engine {
|
|||||||
|
|
||||||
loop {
|
loop {
|
||||||
if !body.is_empty() {
|
if !body.is_empty() {
|
||||||
match self.eval_stmt_block(
|
if let Err(err) =
|
||||||
global, caches, lib, level, scope, this_ptr, body, true,
|
self.eval_stmt_block(global, caches, lib, scope, this_ptr, body, true)
|
||||||
) {
|
{
|
||||||
Ok(_) => (),
|
match *err {
|
||||||
Err(err) => match *err {
|
|
||||||
ERR::LoopBreak(false, ..) => continue,
|
ERR::LoopBreak(false, ..) => continue,
|
||||||
ERR::LoopBreak(true, value, ..) => break Ok(value),
|
ERR::LoopBreak(true, value, ..) => break Ok(value),
|
||||||
_ => break Err(err),
|
_ => break Err(err),
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let condition = self
|
let condition = self
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, expr)
|
.eval_expr(global, caches, lib, scope, this_ptr, expr)?
|
||||||
.and_then(|v| {
|
.as_bool()
|
||||||
v.as_bool().map_err(|typ| {
|
.map_err(|typ| self.make_type_mismatch_err::<bool>(typ, expr.position()))?;
|
||||||
self.make_type_mismatch_err::<bool>(typ, expr.position())
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
match condition {
|
if condition ^ is_while {
|
||||||
Ok(condition) if condition ^ is_while => break Ok(Dynamic::UNIT),
|
break Ok(Dynamic::UNIT);
|
||||||
Ok(_) => (),
|
|
||||||
err => break err.map(|_| Dynamic::UNIT),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -577,11 +499,10 @@ impl Engine {
|
|||||||
Stmt::For(x, ..) => {
|
Stmt::For(x, ..) => {
|
||||||
let (var_name, counter, expr, statements) = &**x;
|
let (var_name, counter, expr, statements) = &**x;
|
||||||
|
|
||||||
let iter_result = self
|
let iter_obj = self
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, expr)
|
.eval_expr(global, caches, lib, scope, this_ptr, expr)?
|
||||||
.map(Dynamic::flatten);
|
.flatten();
|
||||||
|
|
||||||
if let Ok(iter_obj) = iter_result {
|
|
||||||
let iter_type = iter_obj.type_id();
|
let iter_type = iter_obj.type_id();
|
||||||
|
|
||||||
// lib should only contain scripts, so technically they cannot have iterators
|
// lib should only contain scripts, so technically they cannot have iterators
|
||||||
@ -603,9 +524,15 @@ impl Engine {
|
|||||||
.find_map(|m| m.get_qualified_iter(iter_type))
|
.find_map(|m| m.get_qualified_iter(iter_type))
|
||||||
});
|
});
|
||||||
|
|
||||||
if let Some(func) = func {
|
let func = func.ok_or_else(|| ERR::ErrorFor(expr.start_position()))?;
|
||||||
// Add the loop variables
|
|
||||||
|
// Restore scope at end of statement
|
||||||
let orig_scope_len = scope.len();
|
let orig_scope_len = scope.len();
|
||||||
|
let scope = &mut *RestoreOnDrop::lock(scope, move |s| {
|
||||||
|
s.rewind(orig_scope_len);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add the loop variables
|
||||||
let counter_index = if counter.is_empty() {
|
let counter_index = if counter.is_empty() {
|
||||||
usize::MAX
|
usize::MAX
|
||||||
} else {
|
} else {
|
||||||
@ -616,9 +543,9 @@ impl Engine {
|
|||||||
scope.push(var_name.name.clone(), ());
|
scope.push(var_name.name.clone(), ());
|
||||||
let index = scope.len() - 1;
|
let index = scope.len() - 1;
|
||||||
|
|
||||||
let loop_result = func(iter_obj)
|
let mut result = Dynamic::UNIT;
|
||||||
.enumerate()
|
|
||||||
.try_fold(Dynamic::UNIT, |_, (x, iter_value)| {
|
for (x, iter_value) in func(iter_obj).enumerate() {
|
||||||
// Increment counter
|
// Increment counter
|
||||||
if counter_index < usize::MAX {
|
if counter_index < usize::MAX {
|
||||||
// As the variable increments from 0, this should always work
|
// As the variable increments from 0, this should always work
|
||||||
@ -638,54 +565,49 @@ impl Engine {
|
|||||||
Dynamic::from_int(index_value);
|
Dynamic::from_int(index_value);
|
||||||
}
|
}
|
||||||
|
|
||||||
let value = match iter_value {
|
// Set loop value
|
||||||
Ok(v) => v.flatten(),
|
let value = iter_value
|
||||||
Err(err) => return Err(err.fill_position(expr.position())),
|
.map_err(|err| err.fill_position(expr.position()))?
|
||||||
};
|
.flatten();
|
||||||
|
|
||||||
*scope.get_mut_by_index(index).write_lock().unwrap() = value;
|
*scope.get_mut_by_index(index).write_lock().unwrap() = value;
|
||||||
|
|
||||||
|
// Run block
|
||||||
self.track_operation(global, statements.position())?;
|
self.track_operation(global, statements.position())?;
|
||||||
|
|
||||||
if statements.is_empty() {
|
if statements.is_empty() {
|
||||||
return Ok(Dynamic::UNIT);
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.eval_stmt_block(
|
match self
|
||||||
global, caches, lib, level, scope, this_ptr, statements, true,
|
.eval_stmt_block(global, caches, lib, scope, this_ptr, statements, true)
|
||||||
)
|
{
|
||||||
.map(|_| Dynamic::UNIT)
|
Ok(_) => (),
|
||||||
.or_else(|err| match *err {
|
Err(err) => match *err {
|
||||||
ERR::LoopBreak(false, ..) => Ok(Dynamic::UNIT),
|
ERR::LoopBreak(false, ..) => (),
|
||||||
_ => Err(err),
|
ERR::LoopBreak(true, value, ..) => {
|
||||||
})
|
result = value;
|
||||||
})
|
break;
|
||||||
.or_else(|err| match *err {
|
|
||||||
ERR::LoopBreak(true, value, ..) => Ok(value),
|
|
||||||
_ => Err(err),
|
|
||||||
});
|
|
||||||
|
|
||||||
scope.rewind(orig_scope_len);
|
|
||||||
|
|
||||||
loop_result
|
|
||||||
} else {
|
|
||||||
Err(ERR::ErrorFor(expr.start_position()).into())
|
|
||||||
}
|
}
|
||||||
} else {
|
_ => return Err(err),
|
||||||
iter_result
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
// Continue/Break statement
|
// Continue/Break statement
|
||||||
Stmt::BreakLoop(expr, options, pos) => {
|
Stmt::BreakLoop(expr, options, pos) => {
|
||||||
let is_break = options.contains(ASTFlags::BREAK);
|
let is_break = options.contains(ASTFlags::BREAK);
|
||||||
|
|
||||||
if let Some(ref expr) = expr {
|
let value = if let Some(ref expr) = expr {
|
||||||
self.eval_expr(global, caches, lib, level, scope, this_ptr, expr)
|
self.eval_expr(global, caches, lib, scope, this_ptr, expr)?
|
||||||
.and_then(|v| ERR::LoopBreak(is_break, v, *pos).into())
|
|
||||||
} else {
|
} else {
|
||||||
Err(ERR::LoopBreak(is_break, Dynamic::UNIT, *pos).into())
|
Dynamic::UNIT
|
||||||
}
|
};
|
||||||
|
|
||||||
|
Err(ERR::LoopBreak(is_break, value, *pos).into())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try/Catch statement
|
// Try/Catch statement
|
||||||
@ -699,12 +621,8 @@ impl Engine {
|
|||||||
catch_block,
|
catch_block,
|
||||||
} = &**x;
|
} = &**x;
|
||||||
|
|
||||||
let result = self
|
match self.eval_stmt_block(global, caches, lib, scope, this_ptr, try_block, true) {
|
||||||
.eval_stmt_block(global, caches, lib, level, scope, this_ptr, try_block, true)
|
r @ Ok(_) => r,
|
||||||
.map(|_| Dynamic::UNIT);
|
|
||||||
|
|
||||||
match result {
|
|
||||||
Ok(_) => result,
|
|
||||||
Err(err) if err.is_pseudo_error() => Err(err),
|
Err(err) if err.is_pseudo_error() => Err(err),
|
||||||
Err(err) if !err.is_catchable() => Err(err),
|
Err(err) if !err.is_catchable() => Err(err),
|
||||||
Err(mut err) => {
|
Err(mut err) => {
|
||||||
@ -743,43 +661,42 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Restore scope at end of block
|
||||||
let orig_scope_len = scope.len();
|
let orig_scope_len = scope.len();
|
||||||
|
let scope =
|
||||||
|
&mut *RestoreOnDrop::lock_if(!catch_var.is_empty(), scope, move |s| {
|
||||||
|
s.rewind(orig_scope_len);
|
||||||
|
});
|
||||||
|
|
||||||
if !catch_var.is_empty() {
|
if !catch_var.is_empty() {
|
||||||
scope.push(catch_var.clone(), err_value);
|
scope.push(catch_var.clone(), err_value);
|
||||||
}
|
}
|
||||||
|
|
||||||
let result = self.eval_stmt_block(
|
self.eval_stmt_block(
|
||||||
global,
|
global,
|
||||||
caches,
|
caches,
|
||||||
lib,
|
lib,
|
||||||
level,
|
|
||||||
scope,
|
scope,
|
||||||
this_ptr,
|
this_ptr,
|
||||||
catch_block,
|
catch_block,
|
||||||
true,
|
true,
|
||||||
);
|
)
|
||||||
|
.map(|_| Dynamic::UNIT)
|
||||||
scope.rewind(orig_scope_len);
|
.map_err(|result_err| match *result_err {
|
||||||
|
|
||||||
match result {
|
|
||||||
Ok(_) => Ok(Dynamic::UNIT),
|
|
||||||
Err(result_err) => match *result_err {
|
|
||||||
// Re-throw exception
|
// Re-throw exception
|
||||||
ERR::ErrorRuntime(Dynamic(Union::Unit(..)), pos) => {
|
ERR::ErrorRuntime(Dynamic(Union::Unit(..)), pos) => {
|
||||||
err.set_position(pos);
|
err.set_position(pos);
|
||||||
Err(err)
|
err
|
||||||
}
|
|
||||||
_ => Err(result_err),
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
_ => result_err,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Throw value
|
// Throw value
|
||||||
Stmt::Return(Some(expr), options, pos) if options.contains(ASTFlags::BREAK) => self
|
Stmt::Return(Some(expr), options, pos) if options.contains(ASTFlags::BREAK) => self
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, expr)
|
.eval_expr(global, caches, lib, scope, this_ptr, expr)
|
||||||
.and_then(|v| Err(ERR::ErrorRuntime(v.flatten(), *pos).into())),
|
.and_then(|v| Err(ERR::ErrorRuntime(v.flatten(), *pos).into())),
|
||||||
|
|
||||||
// Empty throw
|
// Empty throw
|
||||||
@ -789,7 +706,7 @@ impl Engine {
|
|||||||
|
|
||||||
// Return value
|
// Return value
|
||||||
Stmt::Return(Some(expr), .., pos) => self
|
Stmt::Return(Some(expr), .., pos) => self
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, expr)
|
.eval_expr(global, caches, lib, scope, this_ptr, expr)
|
||||||
.and_then(|v| Err(ERR::Return(v.flatten(), *pos).into())),
|
.and_then(|v| Err(ERR::Return(v.flatten(), *pos).into())),
|
||||||
|
|
||||||
// Empty return
|
// Empty return
|
||||||
@ -811,40 +728,27 @@ impl Engine {
|
|||||||
let export = options.contains(ASTFlags::EXPORTED);
|
let export = options.contains(ASTFlags::EXPORTED);
|
||||||
|
|
||||||
// Check variable definition filter
|
// Check variable definition filter
|
||||||
let result = if let Some(ref filter) = self.def_var_filter {
|
if let Some(ref filter) = self.def_var_filter {
|
||||||
let will_shadow = scope.contains(var_name);
|
let will_shadow = scope.contains(var_name);
|
||||||
let nesting_level = global.scope_level;
|
|
||||||
let is_const = access == AccessMode::ReadOnly;
|
let is_const = access == AccessMode::ReadOnly;
|
||||||
let info = VarDefInfo {
|
let info = VarDefInfo {
|
||||||
name: var_name,
|
name: var_name,
|
||||||
is_const,
|
is_const,
|
||||||
nesting_level,
|
nesting_level: global.scope_level,
|
||||||
will_shadow,
|
will_shadow,
|
||||||
};
|
};
|
||||||
let context = EvalContext::new(self, global, None, lib, level, scope, this_ptr);
|
let context = EvalContext::new(self, global, caches, lib, scope, this_ptr);
|
||||||
|
|
||||||
match filter(true, info, context) {
|
if !filter(true, info, context)? {
|
||||||
Ok(true) => None,
|
return Err(ERR::ErrorForbiddenVariable(var_name.to_string(), *pos).into());
|
||||||
Ok(false) => {
|
|
||||||
Some(Err(
|
|
||||||
ERR::ErrorForbiddenVariable(var_name.to_string(), *pos).into()
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
err @ Err(_) => Some(err),
|
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Some(result) = result {
|
|
||||||
result.map(|_| Dynamic::UNIT)
|
|
||||||
} else {
|
|
||||||
// Evaluate initial value
|
// Evaluate initial value
|
||||||
let value_result = self
|
let mut value = self
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, expr)
|
.eval_expr(global, caches, lib, scope, this_ptr, expr)?
|
||||||
.map(Dynamic::flatten);
|
.flatten();
|
||||||
|
|
||||||
if let Ok(mut value) = value_result {
|
|
||||||
let _alias = if !rewind_scope {
|
let _alias = if !rewind_scope {
|
||||||
// Put global constants into global module
|
// Put global constants into global module
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
@ -853,13 +757,11 @@ impl Engine {
|
|||||||
&& access == AccessMode::ReadOnly
|
&& access == AccessMode::ReadOnly
|
||||||
&& lib.iter().any(|m| !m.is_empty())
|
&& lib.iter().any(|m| !m.is_empty())
|
||||||
{
|
{
|
||||||
crate::func::locked_write(global.constants.get_or_insert_with(
|
crate::func::locked_write(global.constants.get_or_insert_with(|| {
|
||||||
|| {
|
crate::Shared::new(
|
||||||
crate::Shared::new(crate::Locked::new(
|
crate::Locked::new(std::collections::BTreeMap::new()),
|
||||||
std::collections::BTreeMap::new(),
|
)
|
||||||
))
|
}))
|
||||||
},
|
|
||||||
))
|
|
||||||
.insert(var_name.name.clone(), value.clone());
|
.insert(var_name.name.clone(), value.clone());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -887,10 +789,6 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Ok(Dynamic::UNIT)
|
Ok(Dynamic::UNIT)
|
||||||
} else {
|
|
||||||
value_result
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Import statement
|
// Import statement
|
||||||
@ -903,26 +801,19 @@ impl Engine {
|
|||||||
return Err(ERR::ErrorTooManyModules(*_pos).into());
|
return Err(ERR::ErrorTooManyModules(*_pos).into());
|
||||||
}
|
}
|
||||||
|
|
||||||
let path_result = self
|
let v = self.eval_expr(global, caches, lib, scope, this_ptr, expr)?;
|
||||||
.eval_expr(global, caches, lib, level, scope, this_ptr, expr)
|
|
||||||
.and_then(|v| {
|
|
||||||
let typ = v.type_name();
|
let typ = v.type_name();
|
||||||
v.try_cast::<crate::ImmutableString>().ok_or_else(|| {
|
let path = v.try_cast::<crate::ImmutableString>().ok_or_else(|| {
|
||||||
self.make_type_mismatch_err::<crate::ImmutableString>(
|
self.make_type_mismatch_err::<crate::ImmutableString>(typ, expr.position())
|
||||||
typ,
|
})?;
|
||||||
expr.position(),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
if let Ok(path) = path_result {
|
|
||||||
use crate::ModuleResolver;
|
use crate::ModuleResolver;
|
||||||
|
|
||||||
let path_pos = expr.start_position();
|
let path_pos = expr.start_position();
|
||||||
|
|
||||||
let resolver = global.embedded_module_resolver.clone();
|
let resolver = global.embedded_module_resolver.clone();
|
||||||
|
|
||||||
let module_result = resolver
|
let module = resolver
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|r| match r.resolve_raw(self, global, &path, path_pos) {
|
.and_then(|r| match r.resolve_raw(self, global, &path, path_pos) {
|
||||||
Err(err) if matches!(*err, ERR::ErrorModuleNotFound(..)) => None,
|
Err(err) if matches!(*err, ERR::ErrorModuleNotFound(..)) => None,
|
||||||
@ -936,9 +827,8 @@ impl Engine {
|
|||||||
})
|
})
|
||||||
.unwrap_or_else(|| {
|
.unwrap_or_else(|| {
|
||||||
Err(ERR::ErrorModuleNotFound(path.to_string(), path_pos).into())
|
Err(ERR::ErrorModuleNotFound(path.to_string(), path_pos).into())
|
||||||
});
|
})?;
|
||||||
|
|
||||||
if let Ok(module) = module_result {
|
|
||||||
let (export, must_be_indexed) = if !export.is_empty() {
|
let (export, must_be_indexed) = if !export.is_empty() {
|
||||||
(export.name.clone(), true)
|
(export.name.clone(), true)
|
||||||
} else {
|
} else {
|
||||||
@ -957,12 +847,6 @@ impl Engine {
|
|||||||
global.num_modules_loaded += 1;
|
global.num_modules_loaded += 1;
|
||||||
|
|
||||||
Ok(Dynamic::UNIT)
|
Ok(Dynamic::UNIT)
|
||||||
} else {
|
|
||||||
module_result.map(|_| Dynamic::UNIT)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
path_result.map(|_| Dynamic::UNIT)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Export statement
|
// Export statement
|
||||||
@ -1003,12 +887,7 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_ => unreachable!("statement cannot be evaluated: {:?}", stmt),
|
_ => unreachable!("statement cannot be evaluated: {:?}", stmt),
|
||||||
};
|
}
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
|
||||||
global.debugger.reset_status(reset_debugger);
|
|
||||||
|
|
||||||
result
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluate a list of statements with no `this` pointer.
|
/// Evaluate a list of statements with no `this` pointer.
|
||||||
@ -1018,14 +897,13 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
statements: &[Stmt],
|
statements: &[Stmt],
|
||||||
) -> RhaiResult {
|
) -> RhaiResult {
|
||||||
self.eval_stmt_block(
|
let mut this = Dynamic::NULL;
|
||||||
global, caches, lib, level, scope, &mut None, statements, false,
|
|
||||||
)
|
self.eval_stmt_block(global, caches, lib, scope, &mut this, statements, false)
|
||||||
.or_else(|err| match *err {
|
.or_else(|err| match *err {
|
||||||
ERR::Return(out, ..) => Ok(out),
|
ERR::Return(out, ..) => Ok(out),
|
||||||
ERR::LoopBreak(..) => {
|
ERR::LoopBreak(..) => {
|
||||||
|
250
src/func/call.rs
250
src/func/call.rs
@ -9,9 +9,10 @@ use crate::engine::{
|
|||||||
};
|
};
|
||||||
use crate::eval::{Caches, FnResolutionCacheEntry, GlobalRuntimeState};
|
use crate::eval::{Caches, FnResolutionCacheEntry, GlobalRuntimeState};
|
||||||
use crate::tokenizer::{is_valid_function_name, Token};
|
use crate::tokenizer::{is_valid_function_name, Token};
|
||||||
|
use crate::types::RestoreOnDrop;
|
||||||
use crate::{
|
use crate::{
|
||||||
calc_fn_hash, calc_fn_hash_full, Dynamic, Engine, FnArgsVec, FnPtr, ImmutableString, Module,
|
calc_fn_hash, calc_fn_hash_full, Dynamic, Engine, FnArgsVec, FnPtr, ImmutableString,
|
||||||
OptimizationLevel, Position, RhaiError, RhaiResult, RhaiResultOf, Scope, ERR,
|
OptimizationLevel, Position, RhaiError, RhaiResult, RhaiResultOf, Scope, SharedModule, ERR,
|
||||||
};
|
};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use hashbrown::hash_map::Entry;
|
use hashbrown::hash_map::Entry;
|
||||||
@ -88,9 +89,11 @@ impl<'a> ArgBackup<'a> {
|
|||||||
/// If `change_first_arg_to_copy` has been called, this function **MUST** be called _BEFORE_
|
/// If `change_first_arg_to_copy` has been called, this function **MUST** be called _BEFORE_
|
||||||
/// exiting the current scope. Otherwise it is undefined behavior as the shorter lifetime will leak.
|
/// exiting the current scope. Otherwise it is undefined behavior as the shorter lifetime will leak.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn restore_first_arg(mut self, args: &mut FnCallArgs<'a>) {
|
pub fn restore_first_arg(&mut self, args: &mut FnCallArgs<'a>) {
|
||||||
if let Some(p) = self.orig_mut.take() {
|
if let Some(p) = self.orig_mut.take() {
|
||||||
args[0] = p;
|
args[0] = p;
|
||||||
|
} else {
|
||||||
|
unreachable!("`Some`");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -166,7 +169,7 @@ impl Engine {
|
|||||||
_global: &GlobalRuntimeState,
|
_global: &GlobalRuntimeState,
|
||||||
caches: &'s mut Caches,
|
caches: &'s mut Caches,
|
||||||
local_entry: &'s mut Option<FnResolutionCacheEntry>,
|
local_entry: &'s mut Option<FnResolutionCacheEntry>,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
op_token: Option<&Token>,
|
op_token: Option<&Token>,
|
||||||
hash_base: u64,
|
hash_base: u64,
|
||||||
args: Option<&mut FnCallArgs>,
|
args: Option<&mut FnCallArgs>,
|
||||||
@ -193,8 +196,7 @@ impl Engine {
|
|||||||
loop {
|
loop {
|
||||||
let func = lib
|
let func = lib
|
||||||
.iter()
|
.iter()
|
||||||
.copied()
|
.chain(self.global_modules.iter())
|
||||||
.chain(self.global_modules.iter().map(|m| m.as_ref()))
|
|
||||||
.find_map(|m| m.get_fn(hash).map(|f| (f, m.id_raw())));
|
.find_map(|m| m.get_fn(hash).map(|f| (f, m.id_raw())));
|
||||||
|
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
@ -323,12 +325,11 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
name: &str,
|
name: &str,
|
||||||
op_token: Option<&Token>,
|
op_token: Option<&Token>,
|
||||||
hash: u64,
|
hash: u64,
|
||||||
args: &mut FnCallArgs,
|
mut args: &mut FnCallArgs,
|
||||||
is_ref_mut: bool,
|
is_ref_mut: bool,
|
||||||
pos: Position,
|
pos: Position,
|
||||||
) -> RhaiResultOf<(Dynamic, bool)> {
|
) -> RhaiResultOf<(Dynamic, bool)> {
|
||||||
@ -355,17 +356,22 @@ impl Engine {
|
|||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
let orig_call_stack_len = global.debugger.call_stack().len();
|
let orig_call_stack_len = global.debugger.call_stack().len();
|
||||||
|
|
||||||
let mut _result = if let Some(FnResolutionCacheEntry { func, source }) = func {
|
let FnResolutionCacheEntry { func, source } = func.unwrap();
|
||||||
assert!(func.is_native());
|
assert!(func.is_native());
|
||||||
|
|
||||||
let mut backup = ArgBackup::new();
|
let backup = &mut ArgBackup::new();
|
||||||
|
|
||||||
// Calling pure function but the first argument is a reference?
|
// Calling pure function but the first argument is a reference?
|
||||||
if is_ref_mut && func.is_pure() && !args.is_empty() {
|
let swap = is_ref_mut && func.is_pure() && !args.is_empty();
|
||||||
|
|
||||||
|
if swap {
|
||||||
// Clone the first argument
|
// Clone the first argument
|
||||||
backup.change_first_arg_to_copy(args);
|
backup.change_first_arg_to_copy(args);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let args =
|
||||||
|
&mut *RestoreOnDrop::lock_if(swap, &mut args, move |a| backup.restore_first_arg(a));
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
if self.debugger.is_some() {
|
if self.debugger.is_some() {
|
||||||
global.debugger.push_call_stack_frame(
|
global.debugger.push_call_stack_frame(
|
||||||
@ -378,9 +384,9 @@ impl Engine {
|
|||||||
|
|
||||||
// Run external function
|
// Run external function
|
||||||
let src = source.as_ref().map(|s| s.as_str());
|
let src = source.as_ref().map(|s| s.as_str());
|
||||||
let context = (self, name, src, &*global, lib, pos, level).into();
|
let context = (self, name, src, &*global, lib, pos).into();
|
||||||
|
|
||||||
let result = if func.is_plugin_fn() {
|
let mut _result = if func.is_plugin_fn() {
|
||||||
let f = func.get_plugin_fn().unwrap();
|
let f = func.get_plugin_fn().unwrap();
|
||||||
if !f.is_pure() && !args.is_empty() && args[0].is_read_only() {
|
if !f.is_pure() && !args.is_empty() && args[0].is_read_only() {
|
||||||
Err(ERR::ErrorNonPureMethodCallOnConstant(name.to_string(), pos).into())
|
Err(ERR::ErrorNonPureMethodCallOnConstant(name.to_string(), pos).into())
|
||||||
@ -391,34 +397,27 @@ impl Engine {
|
|||||||
func.get_native_fn().unwrap()(context, args)
|
func.get_native_fn().unwrap()(context, args)
|
||||||
};
|
};
|
||||||
|
|
||||||
// Restore the original reference
|
|
||||||
backup.restore_first_arg(args);
|
|
||||||
|
|
||||||
result
|
|
||||||
} else {
|
|
||||||
unreachable!("`Some`");
|
|
||||||
};
|
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
{
|
{
|
||||||
let trigger = match global.debugger.status {
|
let trigger = match global.debugger.status {
|
||||||
crate::eval::DebuggerStatus::FunctionExit(n) => n >= level,
|
crate::eval::DebuggerStatus::FunctionExit(n) => n >= global.level,
|
||||||
crate::eval::DebuggerStatus::Next(.., true) => true,
|
crate::eval::DebuggerStatus::Next(.., true) => true,
|
||||||
_ => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
if trigger {
|
if trigger {
|
||||||
let scope = &mut &mut Scope::new();
|
let scope = &mut &mut Scope::new();
|
||||||
|
let mut this = Dynamic::NULL;
|
||||||
let node = crate::ast::Stmt::Noop(pos);
|
let node = crate::ast::Stmt::Noop(pos);
|
||||||
let node = (&node).into();
|
let node = (&node).into();
|
||||||
let event = match _result {
|
let event = match _result {
|
||||||
Ok(ref r) => crate::eval::DebuggerEvent::FunctionExitWithValue(r),
|
Ok(ref r) => crate::eval::DebuggerEvent::FunctionExitWithValue(r),
|
||||||
Err(ref err) => crate::eval::DebuggerEvent::FunctionExitWithError(err),
|
Err(ref err) => crate::eval::DebuggerEvent::FunctionExitWithError(err),
|
||||||
};
|
};
|
||||||
match self
|
|
||||||
.run_debugger_raw(global, caches, lib, level, scope, &mut None, node, event)
|
if let Err(err) =
|
||||||
|
self.run_debugger_raw(global, caches, lib, scope, &mut this, node, event)
|
||||||
{
|
{
|
||||||
Ok(_) => (),
|
_result = Err(err);
|
||||||
Err(err) => _result = Err(err),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -538,13 +537,12 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
_scope: Option<&mut Scope>,
|
_scope: Option<&mut Scope>,
|
||||||
fn_name: &str,
|
fn_name: &str,
|
||||||
op_token: Option<&Token>,
|
op_token: Option<&Token>,
|
||||||
hashes: FnCallHashes,
|
hashes: FnCallHashes,
|
||||||
args: &mut FnCallArgs,
|
mut args: &mut FnCallArgs,
|
||||||
is_ref_mut: bool,
|
is_ref_mut: bool,
|
||||||
_is_method_call: bool,
|
_is_method_call: bool,
|
||||||
pos: Position,
|
pos: Position,
|
||||||
@ -561,7 +559,8 @@ impl Engine {
|
|||||||
#[cfg(not(feature = "no_closure"))]
|
#[cfg(not(feature = "no_closure"))]
|
||||||
ensure_no_data_race(fn_name, args, is_ref_mut)?;
|
ensure_no_data_race(fn_name, args, is_ref_mut)?;
|
||||||
|
|
||||||
let level = level + 1;
|
global.level += 1;
|
||||||
|
let global = &mut *RestoreOnDrop::lock(global, move |g| g.level -= 1);
|
||||||
|
|
||||||
// These may be redirected from method style calls.
|
// These may be redirected from method style calls.
|
||||||
if hashes.is_native_only() {
|
if hashes.is_native_only() {
|
||||||
@ -586,7 +585,7 @@ impl Engine {
|
|||||||
} else {
|
} else {
|
||||||
let hash_script =
|
let hash_script =
|
||||||
calc_fn_hash(None, fn_name.as_str(), num_params as usize);
|
calc_fn_hash(None, fn_name.as_str(), num_params as usize);
|
||||||
self.has_script_fn(Some(global), caches, lib, hash_script)
|
self.has_script_fn(global, caches, lib, hash_script)
|
||||||
}
|
}
|
||||||
.into(),
|
.into(),
|
||||||
false,
|
false,
|
||||||
@ -614,19 +613,11 @@ impl Engine {
|
|||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
if !hashes.is_native_only() {
|
if !hashes.is_native_only() {
|
||||||
// Script-defined function call?
|
// Script-defined function call?
|
||||||
|
let hash = hashes.script();
|
||||||
let local_entry = &mut None;
|
let local_entry = &mut None;
|
||||||
|
|
||||||
if let Some(FnResolutionCacheEntry { func, ref source }) = self
|
if let Some(FnResolutionCacheEntry { func, ref source }) = self
|
||||||
.resolve_fn(
|
.resolve_fn(global, caches, local_entry, lib, None, hash, None, false)
|
||||||
global,
|
|
||||||
caches,
|
|
||||||
local_entry,
|
|
||||||
lib,
|
|
||||||
None,
|
|
||||||
hashes.script(),
|
|
||||||
None,
|
|
||||||
false,
|
|
||||||
)
|
|
||||||
.cloned()
|
.cloned()
|
||||||
{
|
{
|
||||||
// Script function call
|
// Script function call
|
||||||
@ -648,46 +639,37 @@ impl Engine {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let orig_source = mem::replace(&mut global.source, source.clone());
|
let orig_source = mem::replace(&mut global.source, source.clone());
|
||||||
|
let global = &mut *RestoreOnDrop::lock(global, move |g| g.source = orig_source);
|
||||||
|
|
||||||
let result = if _is_method_call {
|
return if _is_method_call {
|
||||||
// Method call of script function - map first argument to `this`
|
// Method call of script function - map first argument to `this`
|
||||||
let (first_arg, rest_args) = args.split_first_mut().unwrap();
|
let (first_arg, rest_args) = args.split_first_mut().unwrap();
|
||||||
|
|
||||||
self.call_script_fn(
|
self.call_script_fn(
|
||||||
global,
|
global, caches, lib, scope, first_arg, func, rest_args, true, pos,
|
||||||
caches,
|
|
||||||
lib,
|
|
||||||
level,
|
|
||||||
scope,
|
|
||||||
&mut Some(*first_arg),
|
|
||||||
func,
|
|
||||||
rest_args,
|
|
||||||
true,
|
|
||||||
pos,
|
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
// Normal call of script function
|
// Normal call of script function
|
||||||
let mut backup = ArgBackup::new();
|
let backup = &mut ArgBackup::new();
|
||||||
|
|
||||||
// The first argument is a reference?
|
// The first argument is a reference?
|
||||||
if is_ref_mut && !args.is_empty() {
|
let swap = is_ref_mut && !args.is_empty();
|
||||||
|
|
||||||
|
if swap {
|
||||||
backup.change_first_arg_to_copy(args);
|
backup.change_first_arg_to_copy(args);
|
||||||
}
|
}
|
||||||
|
|
||||||
let result = self.call_script_fn(
|
let args = &mut *RestoreOnDrop::lock_if(swap, &mut args, move |a| {
|
||||||
global, caches, lib, level, scope, &mut None, func, args, true, pos,
|
backup.restore_first_arg(a)
|
||||||
);
|
});
|
||||||
|
|
||||||
// Restore the original reference
|
let mut this = Dynamic::NULL;
|
||||||
backup.restore_first_arg(args);
|
|
||||||
|
|
||||||
result
|
self.call_script_fn(
|
||||||
};
|
global, caches, lib, scope, &mut this, func, args, true, pos,
|
||||||
|
)
|
||||||
// Restore the original source
|
}
|
||||||
global.source = orig_source;
|
.map(|r| (r, false));
|
||||||
|
|
||||||
return result.map(|r| (r, false));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -695,7 +677,7 @@ impl Engine {
|
|||||||
let hash = hashes.native();
|
let hash = hashes.native();
|
||||||
|
|
||||||
self.exec_native_fn_call(
|
self.exec_native_fn_call(
|
||||||
global, caches, lib, level, fn_name, op_token, hash, args, is_ref_mut, pos,
|
global, caches, lib, fn_name, op_token, hash, args, is_ref_mut, pos,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -705,10 +687,9 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
this_ptr: &mut Dynamic,
|
||||||
arg_expr: &Expr,
|
arg_expr: &Expr,
|
||||||
) -> RhaiResultOf<(Dynamic, Position)> {
|
) -> RhaiResultOf<(Dynamic, Position)> {
|
||||||
// Literal values
|
// Literal values
|
||||||
@ -716,24 +697,21 @@ impl Engine {
|
|||||||
self.track_operation(global, arg_expr.start_position())?;
|
self.track_operation(global, arg_expr.start_position())?;
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
self.run_debugger(global, caches, lib, level, scope, this_ptr, arg_expr)?;
|
self.run_debugger(global, caches, lib, scope, this_ptr, arg_expr)?;
|
||||||
|
|
||||||
return Ok((value, arg_expr.start_position()));
|
return Ok((value, arg_expr.start_position()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Do not match function exit for arguments
|
// Do not match function exit for arguments
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
let reset_debugger = global.debugger.clear_status_if(|status| {
|
let reset = global.debugger.clear_status_if(|status| {
|
||||||
matches!(status, crate::eval::DebuggerStatus::FunctionExit(..))
|
matches!(status, crate::eval::DebuggerStatus::FunctionExit(..))
|
||||||
});
|
});
|
||||||
|
|
||||||
let result = self.eval_expr(global, caches, lib, level, scope, this_ptr, arg_expr);
|
|
||||||
|
|
||||||
// Restore function exit status
|
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
global.debugger.reset_status(reset_debugger);
|
let global = &mut *RestoreOnDrop::lock(global, move |g| g.debugger.reset_status(reset));
|
||||||
|
|
||||||
result.map(|r| (r, arg_expr.start_position()))
|
self.eval_expr(global, caches, lib, scope, this_ptr, arg_expr)
|
||||||
|
.map(|r| (r, arg_expr.start_position()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Call a dot method.
|
/// Call a dot method.
|
||||||
@ -742,8 +720,7 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
fn_name: &str,
|
fn_name: &str,
|
||||||
mut hash: FnCallHashes,
|
mut hash: FnCallHashes,
|
||||||
target: &mut crate::eval::Target,
|
target: &mut crate::eval::Target,
|
||||||
@ -784,7 +761,6 @@ impl Engine {
|
|||||||
global,
|
global,
|
||||||
caches,
|
caches,
|
||||||
lib,
|
lib,
|
||||||
level,
|
|
||||||
None,
|
None,
|
||||||
fn_name,
|
fn_name,
|
||||||
None,
|
None,
|
||||||
@ -840,7 +816,6 @@ impl Engine {
|
|||||||
global,
|
global,
|
||||||
caches,
|
caches,
|
||||||
lib,
|
lib,
|
||||||
level,
|
|
||||||
None,
|
None,
|
||||||
&fn_name,
|
&fn_name,
|
||||||
None,
|
None,
|
||||||
@ -941,7 +916,6 @@ impl Engine {
|
|||||||
global,
|
global,
|
||||||
caches,
|
caches,
|
||||||
lib,
|
lib,
|
||||||
level,
|
|
||||||
None,
|
None,
|
||||||
fn_name,
|
fn_name,
|
||||||
None,
|
None,
|
||||||
@ -967,10 +941,9 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
this_ptr: &mut Dynamic,
|
||||||
fn_name: &str,
|
fn_name: &str,
|
||||||
op_token: Option<&Token>,
|
op_token: Option<&Token>,
|
||||||
first_arg: Option<&Expr>,
|
first_arg: Option<&Expr>,
|
||||||
@ -994,7 +967,7 @@ impl Engine {
|
|||||||
KEYWORD_FN_PTR_CALL if total_args >= 1 => {
|
KEYWORD_FN_PTR_CALL if total_args >= 1 => {
|
||||||
let arg = first_arg.unwrap();
|
let arg = first_arg.unwrap();
|
||||||
let (arg_value, arg_pos) =
|
let (arg_value, arg_pos) =
|
||||||
self.get_arg_value(global, caches, lib, level, scope, this_ptr, arg)?;
|
self.get_arg_value(global, caches, lib, scope, this_ptr, arg)?;
|
||||||
|
|
||||||
if !arg_value.is::<FnPtr>() {
|
if !arg_value.is::<FnPtr>() {
|
||||||
let typ = self.map_type_name(arg_value.type_name());
|
let typ = self.map_type_name(arg_value.type_name());
|
||||||
@ -1035,7 +1008,7 @@ impl Engine {
|
|||||||
KEYWORD_FN_PTR if total_args == 1 => {
|
KEYWORD_FN_PTR if total_args == 1 => {
|
||||||
let arg = first_arg.unwrap();
|
let arg = first_arg.unwrap();
|
||||||
let (arg_value, arg_pos) =
|
let (arg_value, arg_pos) =
|
||||||
self.get_arg_value(global, caches, lib, level, scope, this_ptr, arg)?;
|
self.get_arg_value(global, caches, lib, scope, this_ptr, arg)?;
|
||||||
|
|
||||||
// Fn - only in function call style
|
// Fn - only in function call style
|
||||||
return arg_value
|
return arg_value
|
||||||
@ -1050,7 +1023,7 @@ impl Engine {
|
|||||||
KEYWORD_FN_PTR_CURRY if total_args > 1 => {
|
KEYWORD_FN_PTR_CURRY if total_args > 1 => {
|
||||||
let first = first_arg.unwrap();
|
let first = first_arg.unwrap();
|
||||||
let (arg_value, arg_pos) =
|
let (arg_value, arg_pos) =
|
||||||
self.get_arg_value(global, caches, lib, level, scope, this_ptr, first)?;
|
self.get_arg_value(global, caches, lib, scope, this_ptr, first)?;
|
||||||
|
|
||||||
if !arg_value.is::<FnPtr>() {
|
if !arg_value.is::<FnPtr>() {
|
||||||
let typ = self.map_type_name(arg_value.type_name());
|
let typ = self.map_type_name(arg_value.type_name());
|
||||||
@ -1062,7 +1035,7 @@ impl Engine {
|
|||||||
// Append the new curried arguments to the existing list.
|
// Append the new curried arguments to the existing list.
|
||||||
let fn_curry = a_expr.iter().try_fold(fn_curry, |mut curried, expr| {
|
let fn_curry = a_expr.iter().try_fold(fn_curry, |mut curried, expr| {
|
||||||
let (value, ..) =
|
let (value, ..) =
|
||||||
self.get_arg_value(global, caches, lib, level, scope, this_ptr, expr)?;
|
self.get_arg_value(global, caches, lib, scope, this_ptr, expr)?;
|
||||||
curried.push(value);
|
curried.push(value);
|
||||||
Ok::<_, RhaiError>(curried)
|
Ok::<_, RhaiError>(curried)
|
||||||
})?;
|
})?;
|
||||||
@ -1075,7 +1048,7 @@ impl Engine {
|
|||||||
crate::engine::KEYWORD_IS_SHARED if total_args == 1 => {
|
crate::engine::KEYWORD_IS_SHARED if total_args == 1 => {
|
||||||
let arg = first_arg.unwrap();
|
let arg = first_arg.unwrap();
|
||||||
let (arg_value, ..) =
|
let (arg_value, ..) =
|
||||||
self.get_arg_value(global, caches, lib, level, scope, this_ptr, arg)?;
|
self.get_arg_value(global, caches, lib, scope, this_ptr, arg)?;
|
||||||
return Ok(arg_value.is_shared().into());
|
return Ok(arg_value.is_shared().into());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1084,14 +1057,14 @@ impl Engine {
|
|||||||
crate::engine::KEYWORD_IS_DEF_FN if total_args == 2 => {
|
crate::engine::KEYWORD_IS_DEF_FN if total_args == 2 => {
|
||||||
let first = first_arg.unwrap();
|
let first = first_arg.unwrap();
|
||||||
let (arg_value, arg_pos) =
|
let (arg_value, arg_pos) =
|
||||||
self.get_arg_value(global, caches, lib, level, scope, this_ptr, first)?;
|
self.get_arg_value(global, caches, lib, scope, this_ptr, first)?;
|
||||||
|
|
||||||
let fn_name = arg_value
|
let fn_name = arg_value
|
||||||
.into_immutable_string()
|
.into_immutable_string()
|
||||||
.map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, arg_pos))?;
|
.map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, arg_pos))?;
|
||||||
|
|
||||||
let (arg_value, arg_pos) =
|
let (arg_value, arg_pos) =
|
||||||
self.get_arg_value(global, caches, lib, level, scope, this_ptr, &a_expr[0])?;
|
self.get_arg_value(global, caches, lib, scope, this_ptr, &a_expr[0])?;
|
||||||
|
|
||||||
let num_params = arg_value
|
let num_params = arg_value
|
||||||
.as_int()
|
.as_int()
|
||||||
@ -1101,7 +1074,7 @@ impl Engine {
|
|||||||
false
|
false
|
||||||
} else {
|
} else {
|
||||||
let hash_script = calc_fn_hash(None, &fn_name, num_params as usize);
|
let hash_script = calc_fn_hash(None, &fn_name, num_params as usize);
|
||||||
self.has_script_fn(Some(global), caches, lib, hash_script)
|
self.has_script_fn(global, caches, lib, hash_script)
|
||||||
}
|
}
|
||||||
.into());
|
.into());
|
||||||
}
|
}
|
||||||
@ -1110,7 +1083,7 @@ impl Engine {
|
|||||||
KEYWORD_IS_DEF_VAR if total_args == 1 => {
|
KEYWORD_IS_DEF_VAR if total_args == 1 => {
|
||||||
let arg = first_arg.unwrap();
|
let arg = first_arg.unwrap();
|
||||||
let (arg_value, arg_pos) =
|
let (arg_value, arg_pos) =
|
||||||
self.get_arg_value(global, caches, lib, level, scope, this_ptr, arg)?;
|
self.get_arg_value(global, caches, lib, scope, this_ptr, arg)?;
|
||||||
let var_name = arg_value
|
let var_name = arg_value
|
||||||
.into_immutable_string()
|
.into_immutable_string()
|
||||||
.map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, arg_pos))?;
|
.map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, arg_pos))?;
|
||||||
@ -1125,12 +1098,15 @@ impl Engine {
|
|||||||
let orig_imports_len = global.num_imports();
|
let orig_imports_len = global.num_imports();
|
||||||
let arg = first_arg.unwrap();
|
let arg = first_arg.unwrap();
|
||||||
let (arg_value, pos) =
|
let (arg_value, pos) =
|
||||||
self.get_arg_value(global, caches, lib, level, scope, this_ptr, arg)?;
|
self.get_arg_value(global, caches, lib, scope, this_ptr, arg)?;
|
||||||
let s = &arg_value
|
let s = &arg_value
|
||||||
.into_immutable_string()
|
.into_immutable_string()
|
||||||
.map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, pos))?;
|
.map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, pos))?;
|
||||||
let result =
|
|
||||||
self.eval_script_expr_in_place(global, caches, lib, level + 1, scope, s, pos);
|
global.level += 1;
|
||||||
|
let global = &mut *RestoreOnDrop::lock(global, move |g| g.level -= 1);
|
||||||
|
|
||||||
|
let result = self.eval_script_expr_in_place(global, caches, lib, scope, s, pos);
|
||||||
|
|
||||||
// IMPORTANT! If the eval defines new variables in the current scope,
|
// IMPORTANT! If the eval defines new variables in the current scope,
|
||||||
// all variable offsets from this point on will be mis-aligned.
|
// all variable offsets from this point on will be mis-aligned.
|
||||||
@ -1172,7 +1148,7 @@ impl Engine {
|
|||||||
.copied()
|
.copied()
|
||||||
.chain(a_expr.iter())
|
.chain(a_expr.iter())
|
||||||
.try_for_each(|expr| {
|
.try_for_each(|expr| {
|
||||||
self.get_arg_value(global, caches, lib, level, scope, this_ptr, expr)
|
self.get_arg_value(global, caches, lib, scope, this_ptr, expr)
|
||||||
.map(|(value, ..)| arg_values.push(value.flatten()))
|
.map(|(value, ..)| arg_values.push(value.flatten()))
|
||||||
})?;
|
})?;
|
||||||
args.extend(curry.iter_mut());
|
args.extend(curry.iter_mut());
|
||||||
@ -1183,8 +1159,8 @@ impl Engine {
|
|||||||
|
|
||||||
return self
|
return self
|
||||||
.exec_fn_call(
|
.exec_fn_call(
|
||||||
global, caches, lib, level, scope, name, op_token, hashes, &mut args,
|
global, caches, lib, scope, name, op_token, hashes, &mut args, is_ref_mut,
|
||||||
is_ref_mut, false, pos,
|
false, pos,
|
||||||
)
|
)
|
||||||
.map(|(v, ..)| v);
|
.map(|(v, ..)| v);
|
||||||
}
|
}
|
||||||
@ -1200,16 +1176,16 @@ impl Engine {
|
|||||||
let first_expr = first_arg.unwrap();
|
let first_expr = first_arg.unwrap();
|
||||||
|
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
self.run_debugger(global, caches, lib, level, scope, this_ptr, first_expr)?;
|
self.run_debugger(global, caches, lib, scope, this_ptr, first_expr)?;
|
||||||
|
|
||||||
// func(x, ...) -> x.func(...)
|
// func(x, ...) -> x.func(...)
|
||||||
a_expr.iter().try_for_each(|expr| {
|
a_expr.iter().try_for_each(|expr| {
|
||||||
self.get_arg_value(global, caches, lib, level, scope, this_ptr, expr)
|
self.get_arg_value(global, caches, lib, scope, this_ptr, expr)
|
||||||
.map(|(value, ..)| arg_values.push(value.flatten()))
|
.map(|(value, ..)| arg_values.push(value.flatten()))
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let (mut target, _pos) =
|
let (mut target, _pos) =
|
||||||
self.search_namespace(global, caches, lib, level, scope, this_ptr, first_expr)?;
|
self.search_namespace(global, caches, lib, scope, this_ptr, first_expr)?;
|
||||||
|
|
||||||
if target.is_read_only() {
|
if target.is_read_only() {
|
||||||
target = target.into_owned();
|
target = target.into_owned();
|
||||||
@ -1236,7 +1212,7 @@ impl Engine {
|
|||||||
.into_iter()
|
.into_iter()
|
||||||
.chain(a_expr.iter())
|
.chain(a_expr.iter())
|
||||||
.try_for_each(|expr| {
|
.try_for_each(|expr| {
|
||||||
self.get_arg_value(global, caches, lib, level, scope, this_ptr, expr)
|
self.get_arg_value(global, caches, lib, scope, this_ptr, expr)
|
||||||
.map(|(value, ..)| arg_values.push(value.flatten()))
|
.map(|(value, ..)| arg_values.push(value.flatten()))
|
||||||
})?;
|
})?;
|
||||||
args.extend(curry.iter_mut());
|
args.extend(curry.iter_mut());
|
||||||
@ -1246,8 +1222,7 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.exec_fn_call(
|
self.exec_fn_call(
|
||||||
global, caches, lib, level, None, name, op_token, hashes, &mut args, is_ref_mut, false,
|
global, caches, lib, None, name, op_token, hashes, &mut args, is_ref_mut, false, pos,
|
||||||
pos,
|
|
||||||
)
|
)
|
||||||
.map(|(v, ..)| v)
|
.map(|(v, ..)| v)
|
||||||
}
|
}
|
||||||
@ -1258,10 +1233,9 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
this_ptr: &mut Dynamic,
|
||||||
namespace: &crate::ast::Namespace,
|
namespace: &crate::ast::Namespace,
|
||||||
fn_name: &str,
|
fn_name: &str,
|
||||||
args_expr: &[Expr],
|
args_expr: &[Expr],
|
||||||
@ -1280,20 +1254,20 @@ impl Engine {
|
|||||||
// and avoid cloning the value
|
// and avoid cloning the value
|
||||||
if !args_expr.is_empty() && args_expr[0].is_variable_access(true) {
|
if !args_expr.is_empty() && args_expr[0].is_variable_access(true) {
|
||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
self.run_debugger(global, caches, lib, level, scope, this_ptr, &args_expr[0])?;
|
self.run_debugger(global, caches, lib, scope, this_ptr, &args_expr[0])?;
|
||||||
|
|
||||||
// func(x, ...) -> x.func(...)
|
// func(x, ...) -> x.func(...)
|
||||||
arg_values.push(Dynamic::UNIT);
|
arg_values.push(Dynamic::UNIT);
|
||||||
|
|
||||||
args_expr.iter().skip(1).try_for_each(|expr| {
|
args_expr.iter().skip(1).try_for_each(|expr| {
|
||||||
self.get_arg_value(global, caches, lib, level, scope, this_ptr, expr)
|
self.get_arg_value(global, caches, lib, scope, this_ptr, expr)
|
||||||
.map(|(value, ..)| arg_values.push(value.flatten()))
|
.map(|(value, ..)| arg_values.push(value.flatten()))
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
// Get target reference to first argument
|
// Get target reference to first argument
|
||||||
let first_arg = &args_expr[0];
|
let first_arg = &args_expr[0];
|
||||||
let (target, _pos) =
|
let (target, _pos) =
|
||||||
self.search_scope_only(global, caches, lib, level, scope, this_ptr, first_arg)?;
|
self.search_scope_only(global, caches, lib, scope, this_ptr, first_arg)?;
|
||||||
|
|
||||||
self.track_operation(global, _pos)?;
|
self.track_operation(global, _pos)?;
|
||||||
|
|
||||||
@ -1316,7 +1290,7 @@ impl Engine {
|
|||||||
} else {
|
} else {
|
||||||
// func(..., ...) or func(mod::x, ...)
|
// func(..., ...) or func(mod::x, ...)
|
||||||
args_expr.iter().try_for_each(|expr| {
|
args_expr.iter().try_for_each(|expr| {
|
||||||
self.get_arg_value(global, caches, lib, level, scope, this_ptr, expr)
|
self.get_arg_value(global, caches, lib, scope, this_ptr, expr)
|
||||||
.map(|(value, ..)| arg_values.push(value.flatten()))
|
.map(|(value, ..)| arg_values.push(value.flatten()))
|
||||||
})?;
|
})?;
|
||||||
args.extend(arg_values.iter_mut());
|
args.extend(arg_values.iter_mut());
|
||||||
@ -1383,26 +1357,26 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let level = level + 1;
|
global.level += 1;
|
||||||
|
let global = &mut *RestoreOnDrop::lock(global, move |g| g.level -= 1);
|
||||||
|
|
||||||
match func {
|
match func {
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
Some(f) if f.is_script() => {
|
Some(f) if f.is_script() => {
|
||||||
let fn_def = f.get_script_fn_def().expect("script-defined function");
|
let fn_def = f.get_script_fn_def().expect("script-defined function");
|
||||||
let new_scope = &mut Scope::new();
|
let new_scope = &mut Scope::new();
|
||||||
|
let mut this = Dynamic::NULL;
|
||||||
|
|
||||||
let orig_source = mem::replace(&mut global.source, module.id_raw().cloned());
|
let orig_source = mem::replace(&mut global.source, module.id_raw().cloned());
|
||||||
|
let global = &mut *RestoreOnDrop::lock(global, move |g| g.source = orig_source);
|
||||||
|
|
||||||
let result = self.call_script_fn(
|
self.call_script_fn(
|
||||||
global, caches, lib, level, new_scope, &mut None, fn_def, &mut args, true, pos,
|
global, caches, lib, new_scope, &mut this, fn_def, &mut args, true, pos,
|
||||||
);
|
)
|
||||||
|
|
||||||
global.source = orig_source;
|
|
||||||
|
|
||||||
result
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Some(f) if f.is_plugin_fn() => {
|
Some(f) if f.is_plugin_fn() => {
|
||||||
let context = (self, fn_name, module.id(), &*global, lib, pos, level).into();
|
let context = (self, fn_name, module.id(), &*global, lib, pos).into();
|
||||||
let f = f.get_plugin_fn().expect("plugin function");
|
let f = f.get_plugin_fn().expect("plugin function");
|
||||||
let result = if !f.is_pure() && !args.is_empty() && args[0].is_read_only() {
|
let result = if !f.is_pure() && !args.is_empty() && args[0].is_read_only() {
|
||||||
Err(ERR::ErrorNonPureMethodCallOnConstant(fn_name.to_string(), pos).into())
|
Err(ERR::ErrorNonPureMethodCallOnConstant(fn_name.to_string(), pos).into())
|
||||||
@ -1414,7 +1388,7 @@ impl Engine {
|
|||||||
|
|
||||||
Some(f) if f.is_native() => {
|
Some(f) if f.is_native() => {
|
||||||
let func = f.get_native_fn().expect("native function");
|
let func = f.get_native_fn().expect("native function");
|
||||||
let context = (self, fn_name, module.id(), &*global, lib, pos, level).into();
|
let context = (self, fn_name, module.id(), &*global, lib, pos).into();
|
||||||
let result = func(context, &mut args);
|
let result = func(context, &mut args);
|
||||||
self.check_return_value(result, pos)
|
self.check_return_value(result, pos)
|
||||||
}
|
}
|
||||||
@ -1442,8 +1416,7 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
script: &str,
|
script: &str,
|
||||||
_pos: Position,
|
_pos: Position,
|
||||||
@ -1479,7 +1452,7 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Evaluate the AST
|
// Evaluate the AST
|
||||||
self.eval_global_statements(global, caches, lib, level, scope, statements)
|
self.eval_global_statements(global, caches, lib, scope, statements)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluate a function call expression.
|
/// Evaluate a function call expression.
|
||||||
@ -1487,10 +1460,9 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
this_ptr: &mut Dynamic,
|
||||||
expr: &FnCallExpr,
|
expr: &FnCallExpr,
|
||||||
pos: Position,
|
pos: Position,
|
||||||
) -> RhaiResult {
|
) -> RhaiResult {
|
||||||
@ -1510,12 +1482,12 @@ impl Engine {
|
|||||||
// Short-circuit native binary operator call if under Fast Operators mode
|
// Short-circuit native binary operator call if under Fast Operators mode
|
||||||
if op_token.is_some() && self.fast_operators() && args.len() == 2 {
|
if op_token.is_some() && self.fast_operators() && args.len() == 2 {
|
||||||
let mut lhs = self
|
let mut lhs = self
|
||||||
.get_arg_value(global, caches, lib, level, scope, this_ptr, &args[0])?
|
.get_arg_value(global, caches, lib, scope, this_ptr, &args[0])?
|
||||||
.0
|
.0
|
||||||
.flatten();
|
.flatten();
|
||||||
|
|
||||||
let mut rhs = self
|
let mut rhs = self
|
||||||
.get_arg_value(global, caches, lib, level, scope, this_ptr, &args[1])?
|
.get_arg_value(global, caches, lib, scope, this_ptr, &args[1])?
|
||||||
.0
|
.0
|
||||||
.flatten();
|
.flatten();
|
||||||
|
|
||||||
@ -1525,14 +1497,16 @@ impl Engine {
|
|||||||
get_builtin_binary_op_fn(op_token.as_ref().unwrap(), operands[0], operands[1])
|
get_builtin_binary_op_fn(op_token.as_ref().unwrap(), operands[0], operands[1])
|
||||||
{
|
{
|
||||||
// Built-in found
|
// Built-in found
|
||||||
let context = (self, name.as_str(), None, &*global, lib, pos, level + 1).into();
|
global.level += 1;
|
||||||
|
let global = &*RestoreOnDrop::lock(global, move |g| g.level -= 1);
|
||||||
|
|
||||||
|
let context = (self, name.as_str(), None, global, lib, pos).into();
|
||||||
return func(context, operands);
|
return func(context, operands);
|
||||||
}
|
}
|
||||||
|
|
||||||
return self
|
return self
|
||||||
.exec_fn_call(
|
.exec_fn_call(
|
||||||
global, caches, lib, level, None, name, op_token, *hashes, operands, false,
|
global, caches, lib, None, name, op_token, *hashes, operands, false, false, pos,
|
||||||
false, pos,
|
|
||||||
)
|
)
|
||||||
.map(|(v, ..)| v);
|
.map(|(v, ..)| v);
|
||||||
}
|
}
|
||||||
@ -1543,7 +1517,7 @@ impl Engine {
|
|||||||
let hash = hashes.native();
|
let hash = hashes.native();
|
||||||
|
|
||||||
return self.make_qualified_function_call(
|
return self.make_qualified_function_call(
|
||||||
global, caches, lib, level, scope, this_ptr, namespace, name, args, hash, pos,
|
global, caches, lib, scope, this_ptr, namespace, name, args, hash, pos,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1554,7 +1528,7 @@ impl Engine {
|
|||||||
);
|
);
|
||||||
|
|
||||||
self.make_function_call(
|
self.make_function_call(
|
||||||
global, caches, lib, level, scope, this_ptr, name, op_token, first_arg, args, *hashes,
|
global, caches, lib, scope, this_ptr, name, op_token, first_arg, args, *hashes,
|
||||||
*capture, pos,
|
*capture, pos,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
@ -22,6 +22,8 @@ pub use callable_function::CallableFunction;
|
|||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
pub use func::Func;
|
pub use func::Func;
|
||||||
pub use hashing::{calc_fn_hash, calc_fn_hash_full, calc_var_hash, get_hasher, StraightHashMap};
|
pub use hashing::{calc_fn_hash, calc_fn_hash_full, calc_var_hash, get_hasher, StraightHashMap};
|
||||||
|
#[cfg(feature = "internals")]
|
||||||
|
pub use native::NativeCallContextStore;
|
||||||
pub use native::{
|
pub use native::{
|
||||||
locked_read, locked_write, shared_get_mut, shared_make_mut, shared_take, shared_take_or_clone,
|
locked_read, locked_write, shared_get_mut, shared_make_mut, shared_take, shared_take_or_clone,
|
||||||
shared_try_take, FnAny, FnPlugin, IteratorFn, Locked, NativeCallContext, SendSync, Shared,
|
shared_try_take, FnAny, FnPlugin, IteratorFn, Locked, NativeCallContext, SendSync, Shared,
|
||||||
|
@ -8,7 +8,7 @@ use crate::tokenizer::{is_valid_function_name, Token, TokenizeState};
|
|||||||
use crate::types::dynamic::Variant;
|
use crate::types::dynamic::Variant;
|
||||||
use crate::{
|
use crate::{
|
||||||
calc_fn_hash, Dynamic, Engine, EvalContext, FuncArgs, Module, Position, RhaiResult,
|
calc_fn_hash, Dynamic, Engine, EvalContext, FuncArgs, Module, Position, RhaiResult,
|
||||||
RhaiResultOf, StaticVec, VarDefInfo, ERR,
|
RhaiResultOf, SharedModule, StaticVec, VarDefInfo, ERR,
|
||||||
};
|
};
|
||||||
use std::any::type_name;
|
use std::any::type_name;
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
@ -72,13 +72,38 @@ pub struct NativeCallContext<'a> {
|
|||||||
/// Function source, if any.
|
/// Function source, if any.
|
||||||
source: Option<&'a str>,
|
source: Option<&'a str>,
|
||||||
/// The current [`GlobalRuntimeState`], if any.
|
/// The current [`GlobalRuntimeState`], if any.
|
||||||
global: Option<&'a GlobalRuntimeState<'a>>,
|
global: &'a GlobalRuntimeState,
|
||||||
/// The current stack of loaded [modules][Module].
|
/// The current stack of loaded [modules][Module].
|
||||||
lib: &'a [&'a Module],
|
lib: &'a [SharedModule],
|
||||||
/// [Position] of the function call.
|
/// [Position] of the function call.
|
||||||
pos: Position,
|
pos: Position,
|
||||||
/// The current nesting level of function calls.
|
}
|
||||||
level: usize,
|
|
||||||
|
/// _(internals)_ Context of a native Rust function call.
|
||||||
|
/// Exported under the `internals` feature only.
|
||||||
|
#[cfg(feature = "internals")]
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct NativeCallContextStore {
|
||||||
|
/// Name of function called.
|
||||||
|
pub fn_name: String,
|
||||||
|
/// Function source, if any.
|
||||||
|
pub source: Option<String>,
|
||||||
|
/// The current [`GlobalRuntimeState`], if any.
|
||||||
|
pub global: GlobalRuntimeState,
|
||||||
|
/// The current stack of loaded [modules][Module].
|
||||||
|
pub lib: StaticVec<SharedModule>,
|
||||||
|
/// [Position] of the function call.
|
||||||
|
pub pos: Position,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "internals")]
|
||||||
|
impl NativeCallContextStore {
|
||||||
|
/// Create a [`NativeCallContext`] from a [`NativeCallContextClone`].
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub fn create_context<'a>(&'a self, engine: &'a Engine) -> NativeCallContext<'a> {
|
||||||
|
NativeCallContext::from_stored_data(engine, self)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a>
|
impl<'a>
|
||||||
@ -86,10 +111,9 @@ impl<'a>
|
|||||||
&'a Engine,
|
&'a Engine,
|
||||||
&'a str,
|
&'a str,
|
||||||
Option<&'a str>,
|
Option<&'a str>,
|
||||||
&'a GlobalRuntimeState<'a>,
|
&'a GlobalRuntimeState,
|
||||||
&'a [&Module],
|
&'a [SharedModule],
|
||||||
Position,
|
Position,
|
||||||
usize,
|
|
||||||
)> for NativeCallContext<'a>
|
)> for NativeCallContext<'a>
|
||||||
{
|
{
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
@ -99,58 +123,22 @@ impl<'a>
|
|||||||
&'a str,
|
&'a str,
|
||||||
Option<&'a str>,
|
Option<&'a str>,
|
||||||
&'a GlobalRuntimeState,
|
&'a GlobalRuntimeState,
|
||||||
&'a [&Module],
|
&'a [SharedModule],
|
||||||
Position,
|
Position,
|
||||||
usize,
|
|
||||||
),
|
),
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
engine: value.0,
|
engine: value.0,
|
||||||
fn_name: value.1,
|
fn_name: value.1,
|
||||||
source: value.2,
|
source: value.2,
|
||||||
global: Some(value.3),
|
global: value.3,
|
||||||
lib: value.4,
|
lib: value.4,
|
||||||
pos: value.5,
|
pos: value.5,
|
||||||
level: value.6,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> From<(&'a Engine, &'a str, &'a [&'a Module])> for NativeCallContext<'a> {
|
|
||||||
#[inline(always)]
|
|
||||||
fn from(value: (&'a Engine, &'a str, &'a [&Module])) -> Self {
|
|
||||||
Self {
|
|
||||||
engine: value.0,
|
|
||||||
fn_name: value.1,
|
|
||||||
source: None,
|
|
||||||
global: None,
|
|
||||||
lib: value.2,
|
|
||||||
pos: Position::NONE,
|
|
||||||
level: 0,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> NativeCallContext<'a> {
|
impl<'a> NativeCallContext<'a> {
|
||||||
/// _(internals)_ Create a new [`NativeCallContext`].
|
|
||||||
/// Exported under the `internals` feature only.
|
|
||||||
#[deprecated(
|
|
||||||
since = "1.3.0",
|
|
||||||
note = "`NativeCallContext::new` will be moved under `internals`. Use `FnPtr::call` to call a function pointer directly."
|
|
||||||
)]
|
|
||||||
#[inline(always)]
|
|
||||||
#[must_use]
|
|
||||||
pub fn new(engine: &'a Engine, fn_name: &'a str, lib: &'a [&Module]) -> Self {
|
|
||||||
Self {
|
|
||||||
engine,
|
|
||||||
fn_name,
|
|
||||||
source: None,
|
|
||||||
global: None,
|
|
||||||
lib,
|
|
||||||
pos: Position::NONE,
|
|
||||||
level: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/// _(internals)_ Create a new [`NativeCallContext`].
|
/// _(internals)_ Create a new [`NativeCallContext`].
|
||||||
/// Exported under the `internals` feature only.
|
/// Exported under the `internals` feature only.
|
||||||
///
|
///
|
||||||
@ -164,20 +152,49 @@ impl<'a> NativeCallContext<'a> {
|
|||||||
fn_name: &'a str,
|
fn_name: &'a str,
|
||||||
source: Option<&'a str>,
|
source: Option<&'a str>,
|
||||||
global: &'a GlobalRuntimeState,
|
global: &'a GlobalRuntimeState,
|
||||||
lib: &'a [&Module],
|
lib: &'a [SharedModule],
|
||||||
pos: Position,
|
pos: Position,
|
||||||
level: usize,
|
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
engine,
|
engine,
|
||||||
fn_name,
|
fn_name,
|
||||||
source,
|
source,
|
||||||
global: Some(global),
|
global,
|
||||||
lib,
|
lib,
|
||||||
pos,
|
pos,
|
||||||
level,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// _(internals)_ Create a [`NativeCallContext`] from a [`NativeCallContextClone`].
|
||||||
|
/// Exported under the `internals` feature only.
|
||||||
|
#[cfg(feature = "internals")]
|
||||||
|
#[inline]
|
||||||
|
#[must_use]
|
||||||
|
pub fn from_stored_data(engine: &'a Engine, context: &'a NativeCallContextStore) -> Self {
|
||||||
|
Self {
|
||||||
|
engine,
|
||||||
|
fn_name: &context.fn_name,
|
||||||
|
source: context.source.as_ref().map(String::as_str),
|
||||||
|
global: &context.global,
|
||||||
|
lib: &context.lib,
|
||||||
|
pos: context.pos,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// _(internals)_ Store this [`NativeCallContext`] into a [`NativeCallContextClone`].
|
||||||
|
/// Exported under the `internals` feature only.
|
||||||
|
#[cfg(feature = "internals")]
|
||||||
|
#[inline]
|
||||||
|
#[must_use]
|
||||||
|
pub fn store_data(&self) -> NativeCallContextStore {
|
||||||
|
NativeCallContextStore {
|
||||||
|
fn_name: self.fn_name.to_string(),
|
||||||
|
source: self.source.map(|s| s.to_string()),
|
||||||
|
global: self.global.clone(),
|
||||||
|
lib: self.lib.iter().cloned().collect(),
|
||||||
|
pos: self.pos,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The current [`Engine`].
|
/// The current [`Engine`].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
@ -200,7 +217,7 @@ impl<'a> NativeCallContext<'a> {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn call_level(&self) -> usize {
|
pub const fn call_level(&self) -> usize {
|
||||||
self.level
|
self.global.level
|
||||||
}
|
}
|
||||||
/// The current source.
|
/// The current source.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
@ -212,7 +229,7 @@ impl<'a> NativeCallContext<'a> {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn tag(&self) -> Option<&Dynamic> {
|
pub fn tag(&self) -> Option<&Dynamic> {
|
||||||
self.global.as_ref().map(|g| &g.tag)
|
Some(&self.global.tag)
|
||||||
}
|
}
|
||||||
/// Get an iterator over the current set of modules imported via `import` statements
|
/// Get an iterator over the current set of modules imported via `import` statements
|
||||||
/// in reverse order.
|
/// in reverse order.
|
||||||
@ -221,7 +238,7 @@ impl<'a> NativeCallContext<'a> {
|
|||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn iter_imports(&self) -> impl Iterator<Item = (&str, &Module)> {
|
pub fn iter_imports(&self) -> impl Iterator<Item = (&str, &Module)> {
|
||||||
self.global.iter().flat_map(|&g| g.iter_imports())
|
self.global.iter_imports()
|
||||||
}
|
}
|
||||||
/// Get an iterator over the current set of modules imported via `import` statements in reverse order.
|
/// Get an iterator over the current set of modules imported via `import` statements in reverse order.
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
@ -229,8 +246,8 @@ impl<'a> NativeCallContext<'a> {
|
|||||||
#[inline]
|
#[inline]
|
||||||
pub(crate) fn iter_imports_raw(
|
pub(crate) fn iter_imports_raw(
|
||||||
&self,
|
&self,
|
||||||
) -> impl Iterator<Item = (&crate::ImmutableString, &Shared<Module>)> {
|
) -> impl Iterator<Item = (&crate::ImmutableString, &SharedModule)> {
|
||||||
self.global.iter().flat_map(|&g| g.iter_imports_raw())
|
self.global.iter_imports_raw()
|
||||||
}
|
}
|
||||||
/// _(internals)_ The current [`GlobalRuntimeState`], if any.
|
/// _(internals)_ The current [`GlobalRuntimeState`], if any.
|
||||||
/// Exported under the `internals` feature only.
|
/// Exported under the `internals` feature only.
|
||||||
@ -239,21 +256,21 @@ impl<'a> NativeCallContext<'a> {
|
|||||||
#[cfg(feature = "internals")]
|
#[cfg(feature = "internals")]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn global_runtime_state(&self) -> Option<&GlobalRuntimeState> {
|
pub const fn global_runtime_state(&self) -> &GlobalRuntimeState {
|
||||||
self.global
|
self.global
|
||||||
}
|
}
|
||||||
/// Get an iterator over the namespaces containing definitions of all script-defined functions
|
/// Get an iterator over the namespaces containing definitions of all script-defined functions
|
||||||
/// in reverse order (i.e. parent namespaces are iterated after child namespaces).
|
/// in reverse order (i.e. parent namespaces are iterated after child namespaces).
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn iter_namespaces(&self) -> impl Iterator<Item = &Module> {
|
pub fn iter_namespaces(&self) -> impl Iterator<Item = &Module> {
|
||||||
self.lib.iter().copied()
|
self.lib.iter().map(|m| m.as_ref())
|
||||||
}
|
}
|
||||||
/// _(internals)_ The current stack of namespaces containing definitions of all script-defined functions.
|
/// _(internals)_ The current stack of namespaces containing definitions of all script-defined functions.
|
||||||
/// Exported under the `internals` feature only.
|
/// Exported under the `internals` feature only.
|
||||||
#[cfg(feature = "internals")]
|
#[cfg(feature = "internals")]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn namespaces(&self) -> &[&Module] {
|
pub const fn namespaces(&self) -> &[SharedModule] {
|
||||||
self.lib
|
self.lib
|
||||||
}
|
}
|
||||||
/// Call a function inside the call context with the provided arguments.
|
/// Call a function inside the call context with the provided arguments.
|
||||||
@ -375,10 +392,7 @@ impl<'a> NativeCallContext<'a> {
|
|||||||
is_method_call: bool,
|
is_method_call: bool,
|
||||||
args: &mut [&mut Dynamic],
|
args: &mut [&mut Dynamic],
|
||||||
) -> RhaiResult {
|
) -> RhaiResult {
|
||||||
let global = &mut self
|
let mut global = &mut self.global.clone();
|
||||||
.global
|
|
||||||
.cloned()
|
|
||||||
.unwrap_or_else(|| GlobalRuntimeState::new(self.engine()));
|
|
||||||
let caches = &mut Caches::new();
|
let caches = &mut Caches::new();
|
||||||
|
|
||||||
let fn_name = fn_name.as_ref();
|
let fn_name = fn_name.as_ref();
|
||||||
@ -386,6 +400,8 @@ impl<'a> NativeCallContext<'a> {
|
|||||||
let op_token = op_token.as_ref();
|
let op_token = op_token.as_ref();
|
||||||
let args_len = args.len();
|
let args_len = args.len();
|
||||||
|
|
||||||
|
global.level += 1;
|
||||||
|
|
||||||
if native_only {
|
if native_only {
|
||||||
return self
|
return self
|
||||||
.engine()
|
.engine()
|
||||||
@ -393,7 +409,6 @@ impl<'a> NativeCallContext<'a> {
|
|||||||
global,
|
global,
|
||||||
caches,
|
caches,
|
||||||
self.lib,
|
self.lib,
|
||||||
self.level + 1,
|
|
||||||
fn_name,
|
fn_name,
|
||||||
op_token,
|
op_token,
|
||||||
calc_fn_hash(None, fn_name, args_len),
|
calc_fn_hash(None, fn_name, args_len),
|
||||||
@ -421,7 +436,6 @@ impl<'a> NativeCallContext<'a> {
|
|||||||
global,
|
global,
|
||||||
caches,
|
caches,
|
||||||
self.lib,
|
self.lib,
|
||||||
self.level + 1,
|
|
||||||
None,
|
None,
|
||||||
fn_name,
|
fn_name,
|
||||||
op_token,
|
op_token,
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
use super::call::FnCallArgs;
|
use super::call::FnCallArgs;
|
||||||
use crate::ast::ScriptFnDef;
|
use crate::ast::ScriptFnDef;
|
||||||
use crate::eval::{Caches, GlobalRuntimeState};
|
use crate::eval::{Caches, GlobalRuntimeState};
|
||||||
use crate::{Dynamic, Engine, Module, Position, RhaiError, RhaiResult, Scope, ERR};
|
use crate::{Dynamic, Engine, Position, RhaiError, RhaiResult, Scope, SharedModule, ERR};
|
||||||
use std::mem;
|
use std::mem;
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
@ -26,10 +26,9 @@ impl Engine {
|
|||||||
&self,
|
&self,
|
||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
level: usize,
|
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
this_ptr: &mut Dynamic,
|
||||||
fn_def: &ScriptFnDef,
|
fn_def: &ScriptFnDef,
|
||||||
args: &mut FnCallArgs,
|
args: &mut FnCallArgs,
|
||||||
rewind_scope: bool,
|
rewind_scope: bool,
|
||||||
@ -66,7 +65,7 @@ impl Engine {
|
|||||||
self.track_operation(global, pos)?;
|
self.track_operation(global, pos)?;
|
||||||
|
|
||||||
// Check for stack overflow
|
// Check for stack overflow
|
||||||
if level > self.max_call_levels() {
|
if global.level > self.max_call_levels() {
|
||||||
return Err(ERR::ErrorStackOverflow(pos).into());
|
return Err(ERR::ErrorStackOverflow(pos).into());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -127,8 +126,8 @@ impl Engine {
|
|||||||
lib
|
lib
|
||||||
} else {
|
} else {
|
||||||
caches.push_fn_resolution_cache();
|
caches.push_fn_resolution_cache();
|
||||||
lib_merged.push(&**fn_lib);
|
lib_merged.push(fn_lib.clone());
|
||||||
lib_merged.extend(lib.iter().copied());
|
lib_merged.extend(lib.iter().cloned());
|
||||||
&lib_merged
|
&lib_merged
|
||||||
},
|
},
|
||||||
Some(mem::replace(&mut global.constants, constants.clone())),
|
Some(mem::replace(&mut global.constants, constants.clone())),
|
||||||
@ -140,7 +139,7 @@ impl Engine {
|
|||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
{
|
{
|
||||||
let node = crate::ast::Stmt::Noop(fn_def.body.position());
|
let node = crate::ast::Stmt::Noop(fn_def.body.position());
|
||||||
self.run_debugger(global, caches, lib, level, scope, this_ptr, &node)?;
|
self.run_debugger(global, caches, lib, scope, this_ptr, &node)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Evaluate the function
|
// Evaluate the function
|
||||||
@ -149,7 +148,6 @@ impl Engine {
|
|||||||
global,
|
global,
|
||||||
caches,
|
caches,
|
||||||
lib,
|
lib,
|
||||||
level,
|
|
||||||
scope,
|
scope,
|
||||||
this_ptr,
|
this_ptr,
|
||||||
&fn_def.body,
|
&fn_def.body,
|
||||||
@ -179,7 +177,7 @@ impl Engine {
|
|||||||
#[cfg(feature = "debugging")]
|
#[cfg(feature = "debugging")]
|
||||||
{
|
{
|
||||||
let trigger = match global.debugger.status {
|
let trigger = match global.debugger.status {
|
||||||
crate::eval::DebuggerStatus::FunctionExit(n) => n >= level,
|
crate::eval::DebuggerStatus::FunctionExit(n) => n >= global.level,
|
||||||
crate::eval::DebuggerStatus::Next(.., true) => true,
|
crate::eval::DebuggerStatus::Next(.., true) => true,
|
||||||
_ => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
@ -190,9 +188,7 @@ impl Engine {
|
|||||||
Ok(ref r) => crate::eval::DebuggerEvent::FunctionExitWithValue(r),
|
Ok(ref r) => crate::eval::DebuggerEvent::FunctionExitWithValue(r),
|
||||||
Err(ref err) => crate::eval::DebuggerEvent::FunctionExitWithError(err),
|
Err(ref err) => crate::eval::DebuggerEvent::FunctionExitWithError(err),
|
||||||
};
|
};
|
||||||
match self
|
match self.run_debugger_raw(global, caches, lib, scope, this_ptr, node, event) {
|
||||||
.run_debugger_raw(global, caches, lib, level, scope, this_ptr, node, event)
|
|
||||||
{
|
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(err) => _result = Err(err),
|
Err(err) => _result = Err(err),
|
||||||
}
|
}
|
||||||
@ -228,9 +224,9 @@ impl Engine {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub(crate) fn has_script_fn(
|
pub(crate) fn has_script_fn(
|
||||||
&self,
|
&self,
|
||||||
_global: Option<&GlobalRuntimeState>,
|
_global: &GlobalRuntimeState,
|
||||||
caches: &mut Caches,
|
caches: &mut Caches,
|
||||||
lib: &[&Module],
|
lib: &[SharedModule],
|
||||||
hash_script: u64,
|
hash_script: u64,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
let cache = caches.fn_resolution_cache_mut();
|
let cache = caches.fn_resolution_cache_mut();
|
||||||
@ -247,7 +243,7 @@ impl Engine {
|
|||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
let result = result ||
|
let result = result ||
|
||||||
// Then check imported modules
|
// Then check imported modules
|
||||||
_global.map_or(false, |m| m.contains_qualified_fn(hash_script))
|
_global.contains_qualified_fn(hash_script)
|
||||||
// Then check sub-modules
|
// Then check sub-modules
|
||||||
|| self.global_sub_modules.values().any(|m| m.contains_qualified_fn(hash_script));
|
|| self.global_sub_modules.values().any(|m| m.contains_qualified_fn(hash_script));
|
||||||
|
|
||||||
|
@ -240,6 +240,9 @@ pub use func::Locked;
|
|||||||
|
|
||||||
use func::{calc_fn_hash, calc_fn_hash_full, calc_var_hash};
|
use func::{calc_fn_hash, calc_fn_hash_full, calc_var_hash};
|
||||||
|
|
||||||
|
/// A shared [`Module`].
|
||||||
|
type SharedModule = Shared<Module>;
|
||||||
|
|
||||||
pub use rhai_codegen::*;
|
pub use rhai_codegen::*;
|
||||||
|
|
||||||
pub use func::{plugin, FuncArgs};
|
pub use func::{plugin, FuncArgs};
|
||||||
|
@ -10,7 +10,7 @@ use crate::func::{
|
|||||||
use crate::types::{dynamic::Variant, BloomFilterU64, CustomTypesCollection};
|
use crate::types::{dynamic::Variant, BloomFilterU64, CustomTypesCollection};
|
||||||
use crate::{
|
use crate::{
|
||||||
calc_fn_hash, calc_fn_hash_full, Dynamic, Identifier, ImmutableString, NativeCallContext,
|
calc_fn_hash, calc_fn_hash_full, Dynamic, Identifier, ImmutableString, NativeCallContext,
|
||||||
RhaiResultOf, Shared, SmartString, StaticVec,
|
RhaiResultOf, Shared, SharedModule, SmartString, StaticVec,
|
||||||
};
|
};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
@ -172,7 +172,7 @@ pub struct Module {
|
|||||||
/// Custom types.
|
/// Custom types.
|
||||||
custom_types: Option<CustomTypesCollection>,
|
custom_types: Option<CustomTypesCollection>,
|
||||||
/// Sub-modules.
|
/// Sub-modules.
|
||||||
modules: Option<BTreeMap<Identifier, Shared<Module>>>,
|
modules: Option<BTreeMap<Identifier, SharedModule>>,
|
||||||
/// [`Module`] variables.
|
/// [`Module`] variables.
|
||||||
variables: Option<BTreeMap<Identifier, Dynamic>>,
|
variables: Option<BTreeMap<Identifier, Dynamic>>,
|
||||||
/// Flattened collection of all [`Module`] variables, including those in sub-modules.
|
/// Flattened collection of all [`Module`] variables, including those in sub-modules.
|
||||||
@ -754,7 +754,7 @@ impl Module {
|
|||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub(crate) fn get_sub_modules_mut(&mut self) -> &mut BTreeMap<Identifier, Shared<Module>> {
|
pub(crate) fn get_sub_modules_mut(&mut self) -> &mut BTreeMap<Identifier, SharedModule> {
|
||||||
// We must assume that the user has changed the sub-modules
|
// We must assume that the user has changed the sub-modules
|
||||||
// (otherwise why take a mutable reference?)
|
// (otherwise why take a mutable reference?)
|
||||||
self.all_functions = None;
|
self.all_functions = None;
|
||||||
@ -822,7 +822,7 @@ impl Module {
|
|||||||
pub fn set_sub_module(
|
pub fn set_sub_module(
|
||||||
&mut self,
|
&mut self,
|
||||||
name: impl Into<Identifier>,
|
name: impl Into<Identifier>,
|
||||||
sub_module: impl Into<Shared<Module>>,
|
sub_module: impl Into<SharedModule>,
|
||||||
) -> &mut Self {
|
) -> &mut Self {
|
||||||
self.modules
|
self.modules
|
||||||
.get_or_insert_with(|| Default::default())
|
.get_or_insert_with(|| Default::default())
|
||||||
@ -1830,7 +1830,7 @@ impl Module {
|
|||||||
|
|
||||||
/// Get an iterator to the sub-modules in the [`Module`].
|
/// Get an iterator to the sub-modules in the [`Module`].
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn iter_sub_modules(&self) -> impl Iterator<Item = (&str, &Shared<Module>)> {
|
pub fn iter_sub_modules(&self) -> impl Iterator<Item = (&str, &SharedModule)> {
|
||||||
self.modules
|
self.modules
|
||||||
.iter()
|
.iter()
|
||||||
.flat_map(|m| m.iter().map(|(k, m)| (k.as_str(), m)))
|
.flat_map(|m| m.iter().map(|(k, m)| (k.as_str(), m)))
|
||||||
@ -1986,7 +1986,7 @@ impl Module {
|
|||||||
// Run the script
|
// Run the script
|
||||||
let caches = &mut crate::eval::Caches::new();
|
let caches = &mut crate::eval::Caches::new();
|
||||||
|
|
||||||
let result = engine.eval_ast_with_scope_raw(global, caches, 0, &mut scope, ast);
|
let result = engine.eval_ast_with_scope_raw(global, caches, &mut scope, ast);
|
||||||
|
|
||||||
// Create new module
|
// Create new module
|
||||||
let mut module = Module::new();
|
let mut module = Module::new();
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
Engine, Module, ModuleResolver, Position, RhaiResultOf, Shared, StaticVec, ERR,
|
Engine, ModuleResolver, Position, RhaiResultOf, SharedModule, StaticVec, ERR,
|
||||||
STATIC_VEC_INLINE_SIZE,
|
STATIC_VEC_INLINE_SIZE,
|
||||||
};
|
};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
@ -138,7 +138,7 @@ impl ModuleResolver for ModuleResolversCollection {
|
|||||||
source_path: Option<&str>,
|
source_path: Option<&str>,
|
||||||
path: &str,
|
path: &str,
|
||||||
pos: Position,
|
pos: Position,
|
||||||
) -> RhaiResultOf<Shared<Module>> {
|
) -> RhaiResultOf<SharedModule> {
|
||||||
for resolver in &self.0 {
|
for resolver in &self.0 {
|
||||||
match resolver.resolve(engine, source_path, path, pos) {
|
match resolver.resolve(engine, source_path, path, pos) {
|
||||||
Ok(module) => return Ok(module),
|
Ok(module) => return Ok(module),
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
use crate::{Engine, Module, ModuleResolver, Position, RhaiResultOf, Shared, ERR};
|
use crate::{Engine, ModuleResolver, Position, RhaiResultOf, SharedModule, ERR};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
|
|
||||||
@ -45,7 +45,7 @@ impl ModuleResolver for DummyModuleResolver {
|
|||||||
_: Option<&str>,
|
_: Option<&str>,
|
||||||
path: &str,
|
path: &str,
|
||||||
pos: Position,
|
pos: Position,
|
||||||
) -> RhaiResultOf<Shared<Module>> {
|
) -> RhaiResultOf<SharedModule> {
|
||||||
Err(ERR::ErrorModuleNotFound(path.into(), pos).into())
|
Err(ERR::ErrorModuleNotFound(path.into(), pos).into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -4,7 +4,8 @@
|
|||||||
use crate::eval::GlobalRuntimeState;
|
use crate::eval::GlobalRuntimeState;
|
||||||
use crate::func::{locked_read, locked_write};
|
use crate::func::{locked_read, locked_write};
|
||||||
use crate::{
|
use crate::{
|
||||||
Engine, Identifier, Locked, Module, ModuleResolver, Position, RhaiResultOf, Scope, Shared, ERR,
|
Engine, Identifier, Locked, Module, ModuleResolver, Position, RhaiResultOf, Scope, Shared,
|
||||||
|
SharedModule, ERR,
|
||||||
};
|
};
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
@ -51,7 +52,7 @@ pub struct FileModuleResolver {
|
|||||||
extension: Identifier,
|
extension: Identifier,
|
||||||
cache_enabled: bool,
|
cache_enabled: bool,
|
||||||
scope: Scope<'static>,
|
scope: Scope<'static>,
|
||||||
cache: Locked<BTreeMap<PathBuf, Shared<Module>>>,
|
cache: Locked<BTreeMap<PathBuf, SharedModule>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for FileModuleResolver {
|
impl Default for FileModuleResolver {
|
||||||
@ -258,7 +259,7 @@ impl FileModuleResolver {
|
|||||||
/// The next time this path is resolved, the script file will be loaded once again.
|
/// The next time this path is resolved, the script file will be loaded once again.
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn clear_cache_for_path(&mut self, path: impl AsRef<Path>) -> Option<Shared<Module>> {
|
pub fn clear_cache_for_path(&mut self, path: impl AsRef<Path>) -> Option<SharedModule> {
|
||||||
locked_write(&self.cache)
|
locked_write(&self.cache)
|
||||||
.remove_entry(path.as_ref())
|
.remove_entry(path.as_ref())
|
||||||
.map(|(.., v)| v)
|
.map(|(.., v)| v)
|
||||||
@ -293,7 +294,7 @@ impl FileModuleResolver {
|
|||||||
source: Option<&str>,
|
source: Option<&str>,
|
||||||
path: &str,
|
path: &str,
|
||||||
pos: Position,
|
pos: Position,
|
||||||
) -> Result<Shared<Module>, Box<crate::EvalAltResult>> {
|
) -> Result<SharedModule, Box<crate::EvalAltResult>> {
|
||||||
// Load relative paths from source if there is no base path specified
|
// Load relative paths from source if there is no base path specified
|
||||||
let source_path = global
|
let source_path = global
|
||||||
.as_ref()
|
.as_ref()
|
||||||
@ -344,7 +345,7 @@ impl ModuleResolver for FileModuleResolver {
|
|||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
path: &str,
|
path: &str,
|
||||||
pos: Position,
|
pos: Position,
|
||||||
) -> RhaiResultOf<Shared<Module>> {
|
) -> RhaiResultOf<SharedModule> {
|
||||||
self.impl_resolve(engine, Some(global), None, path, pos)
|
self.impl_resolve(engine, Some(global), None, path, pos)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -355,7 +356,7 @@ impl ModuleResolver for FileModuleResolver {
|
|||||||
source: Option<&str>,
|
source: Option<&str>,
|
||||||
path: &str,
|
path: &str,
|
||||||
pos: Position,
|
pos: Position,
|
||||||
) -> RhaiResultOf<Shared<Module>> {
|
) -> RhaiResultOf<SharedModule> {
|
||||||
self.impl_resolve(engine, None, source, path, pos)
|
self.impl_resolve(engine, None, source, path, pos)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
use crate::eval::GlobalRuntimeState;
|
use crate::eval::GlobalRuntimeState;
|
||||||
use crate::func::SendSync;
|
use crate::func::SendSync;
|
||||||
use crate::{Engine, Module, Position, RhaiResultOf, Shared, AST};
|
use crate::{Engine, Position, RhaiResultOf, SharedModule, AST};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
|
|
||||||
@ -25,7 +25,7 @@ pub trait ModuleResolver: SendSync {
|
|||||||
source: Option<&str>,
|
source: Option<&str>,
|
||||||
path: &str,
|
path: &str,
|
||||||
pos: Position,
|
pos: Position,
|
||||||
) -> RhaiResultOf<Shared<Module>>;
|
) -> RhaiResultOf<SharedModule>;
|
||||||
|
|
||||||
/// Resolve a module based on a path string, given a [`GlobalRuntimeState`].
|
/// Resolve a module based on a path string, given a [`GlobalRuntimeState`].
|
||||||
///
|
///
|
||||||
@ -38,7 +38,7 @@ pub trait ModuleResolver: SendSync {
|
|||||||
global: &mut GlobalRuntimeState,
|
global: &mut GlobalRuntimeState,
|
||||||
path: &str,
|
path: &str,
|
||||||
pos: Position,
|
pos: Position,
|
||||||
) -> RhaiResultOf<Shared<Module>> {
|
) -> RhaiResultOf<SharedModule> {
|
||||||
self.resolve(engine, global.source(), path, pos)
|
self.resolve(engine, global.source(), path, pos)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
Engine, Identifier, Module, ModuleResolver, Position, RhaiResultOf, Shared, SmartString, ERR,
|
Engine, Identifier, Module, ModuleResolver, Position, RhaiResultOf, SharedModule, SmartString,
|
||||||
|
ERR,
|
||||||
};
|
};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
@ -27,7 +28,7 @@ use std::{
|
|||||||
/// engine.set_module_resolver(resolver);
|
/// engine.set_module_resolver(resolver);
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Debug, Clone, Default)]
|
#[derive(Debug, Clone, Default)]
|
||||||
pub struct StaticModuleResolver(BTreeMap<Identifier, Shared<Module>>);
|
pub struct StaticModuleResolver(BTreeMap<Identifier, SharedModule>);
|
||||||
|
|
||||||
impl StaticModuleResolver {
|
impl StaticModuleResolver {
|
||||||
/// Create a new [`StaticModuleResolver`].
|
/// Create a new [`StaticModuleResolver`].
|
||||||
@ -65,7 +66,7 @@ impl StaticModuleResolver {
|
|||||||
}
|
}
|
||||||
/// Remove a [module][Module] given its path.
|
/// Remove a [module][Module] given its path.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn remove(&mut self, path: &str) -> Option<Shared<Module>> {
|
pub fn remove(&mut self, path: &str) -> Option<SharedModule> {
|
||||||
self.0.remove(path)
|
self.0.remove(path)
|
||||||
}
|
}
|
||||||
/// Does the path exist?
|
/// Does the path exist?
|
||||||
@ -80,12 +81,12 @@ impl StaticModuleResolver {
|
|||||||
}
|
}
|
||||||
/// Get an iterator of all the [modules][Module].
|
/// Get an iterator of all the [modules][Module].
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn iter(&self) -> impl Iterator<Item = (&str, &Shared<Module>)> {
|
pub fn iter(&self) -> impl Iterator<Item = (&str, &SharedModule)> {
|
||||||
self.0.iter().map(|(k, v)| (k.as_str(), v))
|
self.0.iter().map(|(k, v)| (k.as_str(), v))
|
||||||
}
|
}
|
||||||
/// Get a mutable iterator of all the [modules][Module].
|
/// Get a mutable iterator of all the [modules][Module].
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut Shared<Module>)> {
|
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut SharedModule)> {
|
||||||
self.0.iter_mut().map(|(k, v)| (k.as_str(), v))
|
self.0.iter_mut().map(|(k, v)| (k.as_str(), v))
|
||||||
}
|
}
|
||||||
/// Get an iterator of all the [module][Module] paths.
|
/// Get an iterator of all the [module][Module] paths.
|
||||||
@ -95,7 +96,7 @@ impl StaticModuleResolver {
|
|||||||
}
|
}
|
||||||
/// Get an iterator of all the [modules][Module].
|
/// Get an iterator of all the [modules][Module].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn values(&self) -> impl Iterator<Item = &Shared<Module>> {
|
pub fn values(&self) -> impl Iterator<Item = &SharedModule> {
|
||||||
self.0.values()
|
self.0.values()
|
||||||
}
|
}
|
||||||
/// Remove all [modules][Module].
|
/// Remove all [modules][Module].
|
||||||
@ -130,8 +131,8 @@ impl StaticModuleResolver {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl IntoIterator for StaticModuleResolver {
|
impl IntoIterator for StaticModuleResolver {
|
||||||
type Item = (Identifier, Shared<Module>);
|
type Item = (Identifier, SharedModule);
|
||||||
type IntoIter = IntoIter<SmartString, Shared<Module>>;
|
type IntoIter = IntoIter<SmartString, SharedModule>;
|
||||||
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
@ -141,8 +142,8 @@ impl IntoIterator for StaticModuleResolver {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> IntoIterator for &'a StaticModuleResolver {
|
impl<'a> IntoIterator for &'a StaticModuleResolver {
|
||||||
type Item = (&'a Identifier, &'a Shared<Module>);
|
type Item = (&'a Identifier, &'a SharedModule);
|
||||||
type IntoIter = Iter<'a, SmartString, Shared<Module>>;
|
type IntoIter = Iter<'a, SmartString, SharedModule>;
|
||||||
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn into_iter(self) -> Self::IntoIter {
|
fn into_iter(self) -> Self::IntoIter {
|
||||||
@ -158,7 +159,7 @@ impl ModuleResolver for StaticModuleResolver {
|
|||||||
_: Option<&str>,
|
_: Option<&str>,
|
||||||
path: &str,
|
path: &str,
|
||||||
pos: Position,
|
pos: Position,
|
||||||
) -> RhaiResultOf<Shared<Module>> {
|
) -> RhaiResultOf<SharedModule> {
|
||||||
self.0
|
self.0
|
||||||
.get(path)
|
.get(path)
|
||||||
.cloned()
|
.cloned()
|
||||||
|
@ -50,18 +50,18 @@ struct OptimizerState<'a> {
|
|||||||
/// Has the [`AST`] been changed during this pass?
|
/// Has the [`AST`] been changed during this pass?
|
||||||
changed: bool,
|
changed: bool,
|
||||||
/// Collection of constants to use for eager function evaluations.
|
/// Collection of constants to use for eager function evaluations.
|
||||||
variables: StaticVec<(Identifier, AccessMode, Option<Dynamic>)>,
|
variables: StaticVec<(Identifier, AccessMode, Dynamic)>,
|
||||||
/// Activate constants propagation?
|
/// Activate constants propagation?
|
||||||
propagate_constants: bool,
|
propagate_constants: bool,
|
||||||
/// An [`Engine`] instance for eager function evaluation.
|
/// An [`Engine`] instance for eager function evaluation.
|
||||||
engine: &'a Engine,
|
engine: &'a Engine,
|
||||||
/// The global runtime state.
|
/// The global runtime state.
|
||||||
global: GlobalRuntimeState<'a>,
|
global: GlobalRuntimeState,
|
||||||
/// Function resolution caches.
|
/// Function resolution caches.
|
||||||
caches: Caches<'a>,
|
caches: Caches,
|
||||||
/// [Module][crate::Module] containing script-defined functions.
|
/// [Module][crate::Module] containing script-defined functions.
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
lib: &'a [&'a crate::Module],
|
lib: &'a [crate::SharedModule],
|
||||||
/// Optimization level.
|
/// Optimization level.
|
||||||
optimization_level: OptimizationLevel,
|
optimization_level: OptimizationLevel,
|
||||||
}
|
}
|
||||||
@ -71,7 +71,7 @@ impl<'a> OptimizerState<'a> {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn new(
|
pub fn new(
|
||||||
engine: &'a Engine,
|
engine: &'a Engine,
|
||||||
#[cfg(not(feature = "no_function"))] lib: &'a [&'a crate::Module],
|
#[cfg(not(feature = "no_function"))] lib: &'a [crate::SharedModule],
|
||||||
optimization_level: OptimizationLevel,
|
optimization_level: OptimizationLevel,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
@ -108,12 +108,7 @@ impl<'a> OptimizerState<'a> {
|
|||||||
}
|
}
|
||||||
/// Add a new variable to the list.
|
/// Add a new variable to the list.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn push_var(
|
pub fn push_var(&mut self, name: impl Into<Identifier>, access: AccessMode, value: Dynamic) {
|
||||||
&mut self,
|
|
||||||
name: impl Into<Identifier>,
|
|
||||||
access: AccessMode,
|
|
||||||
value: Option<Dynamic>,
|
|
||||||
) {
|
|
||||||
self.variables.push((name.into(), access, value));
|
self.variables.push((name.into(), access, value));
|
||||||
}
|
}
|
||||||
/// Look up a constant from the list.
|
/// Look up a constant from the list.
|
||||||
@ -127,7 +122,8 @@ impl<'a> OptimizerState<'a> {
|
|||||||
if n == name {
|
if n == name {
|
||||||
return match access {
|
return match access {
|
||||||
AccessMode::ReadWrite => None,
|
AccessMode::ReadWrite => None,
|
||||||
AccessMode::ReadOnly => value.as_ref(),
|
AccessMode::ReadOnly if value.is_null() => None,
|
||||||
|
AccessMode::ReadOnly => Some(value),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -141,7 +137,7 @@ impl<'a> OptimizerState<'a> {
|
|||||||
fn_name: &str,
|
fn_name: &str,
|
||||||
op_token: Option<&Token>,
|
op_token: Option<&Token>,
|
||||||
arg_values: &mut [Dynamic],
|
arg_values: &mut [Dynamic],
|
||||||
) -> Option<Dynamic> {
|
) -> Dynamic {
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
let lib = self.lib;
|
let lib = self.lib;
|
||||||
#[cfg(feature = "no_function")]
|
#[cfg(feature = "no_function")]
|
||||||
@ -152,7 +148,6 @@ impl<'a> OptimizerState<'a> {
|
|||||||
&mut self.global,
|
&mut self.global,
|
||||||
&mut self.caches,
|
&mut self.caches,
|
||||||
lib,
|
lib,
|
||||||
0,
|
|
||||||
fn_name,
|
fn_name,
|
||||||
op_token,
|
op_token,
|
||||||
calc_fn_hash(None, fn_name, arg_values.len()),
|
calc_fn_hash(None, fn_name, arg_values.len()),
|
||||||
@ -160,8 +155,7 @@ impl<'a> OptimizerState<'a> {
|
|||||||
false,
|
false,
|
||||||
Position::NONE,
|
Position::NONE,
|
||||||
)
|
)
|
||||||
.ok()
|
.map_or(Dynamic::NULL, |(v, ..)| v)
|
||||||
.map(|(v, ..)| v)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -271,13 +265,13 @@ fn optimize_stmt_block(
|
|||||||
state.push_var(
|
state.push_var(
|
||||||
x.0.as_str(),
|
x.0.as_str(),
|
||||||
AccessMode::ReadOnly,
|
AccessMode::ReadOnly,
|
||||||
x.1.get_literal_value(),
|
x.1.get_literal_value().unwrap_or(Dynamic::NULL),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Add variables into the state
|
// Add variables into the state
|
||||||
optimize_expr(&mut x.1, state, false);
|
optimize_expr(&mut x.1, state, false);
|
||||||
state.push_var(x.0.as_str(), AccessMode::ReadWrite, None);
|
state.push_var(x.0.as_str(), AccessMode::ReadWrite, Dynamic::NULL);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Optimize the statement
|
// Optimize the statement
|
||||||
@ -1149,7 +1143,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut OptimizerState, _chaining: bool) {
|
|||||||
#[cfg(feature = "no_function")]
|
#[cfg(feature = "no_function")]
|
||||||
let lib = &[][..];
|
let lib = &[][..];
|
||||||
|
|
||||||
let context = (state.engine, x.name.as_str(), lib).into();
|
let context = (state.engine, x.name.as_str(),None, &state.global, lib, *pos).into();
|
||||||
let (first, second) = arg_values.split_first_mut().unwrap();
|
let (first, second) = arg_values.split_first_mut().unwrap();
|
||||||
(f)(context, &mut [ first, &mut second[0] ]).ok()
|
(f)(context, &mut [ first, &mut second[0] ]).ok()
|
||||||
}) {
|
}) {
|
||||||
@ -1189,7 +1183,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut OptimizerState, _chaining: bool) {
|
|||||||
=> {
|
=> {
|
||||||
// First search for script-defined functions (can override built-in)
|
// First search for script-defined functions (can override built-in)
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
let has_script_fn = !x.hashes.is_native_only() && state.lib.iter().find_map(|&m| m.get_script_fn(&x.name, x.args.len())).is_some();
|
let has_script_fn = !x.hashes.is_native_only() && state.lib.iter().find_map(|m| m.get_script_fn(&x.name, x.args.len())).is_some();
|
||||||
#[cfg(feature = "no_function")]
|
#[cfg(feature = "no_function")]
|
||||||
let has_script_fn = false;
|
let has_script_fn = false;
|
||||||
|
|
||||||
@ -1197,13 +1191,13 @@ fn optimize_expr(expr: &mut Expr, state: &mut OptimizerState, _chaining: bool) {
|
|||||||
let arg_values = &mut x.args.iter().map(Expr::get_literal_value).collect::<Option<StaticVec<_>>>().unwrap();
|
let arg_values = &mut x.args.iter().map(Expr::get_literal_value).collect::<Option<StaticVec<_>>>().unwrap();
|
||||||
|
|
||||||
let result = match x.name.as_str() {
|
let result = match x.name.as_str() {
|
||||||
KEYWORD_TYPE_OF if arg_values.len() == 1 => Some(state.engine.map_type_name(arg_values[0].type_name()).into()),
|
KEYWORD_TYPE_OF if arg_values.len() == 1 => state.engine.map_type_name(arg_values[0].type_name()).into(),
|
||||||
#[cfg(not(feature = "no_closure"))]
|
#[cfg(not(feature = "no_closure"))]
|
||||||
crate::engine::KEYWORD_IS_SHARED if arg_values.len() == 1 => Some(Dynamic::FALSE),
|
crate::engine::KEYWORD_IS_SHARED if arg_values.len() == 1 => Dynamic::FALSE,
|
||||||
_ => state.call_fn_with_constant_arguments(&x.name, x.op_token.as_ref(), arg_values)
|
_ => state.call_fn_with_constant_arguments(&x.name, x.op_token.as_ref(), arg_values)
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Some(result) = result {
|
if !result.is_null() {
|
||||||
state.set_dirty();
|
state.set_dirty();
|
||||||
*expr = Expr::from_dynamic(result, *pos);
|
*expr = Expr::from_dynamic(result, *pos);
|
||||||
return;
|
return;
|
||||||
@ -1263,7 +1257,7 @@ fn optimize_top_level(
|
|||||||
statements: StmtBlockContainer,
|
statements: StmtBlockContainer,
|
||||||
engine: &Engine,
|
engine: &Engine,
|
||||||
scope: &Scope,
|
scope: &Scope,
|
||||||
#[cfg(not(feature = "no_function"))] lib: &[&crate::Module],
|
#[cfg(not(feature = "no_function"))] lib: &[crate::SharedModule],
|
||||||
optimization_level: OptimizationLevel,
|
optimization_level: OptimizationLevel,
|
||||||
) -> StmtBlockContainer {
|
) -> StmtBlockContainer {
|
||||||
let mut statements = statements;
|
let mut statements = statements;
|
||||||
@ -1289,15 +1283,15 @@ fn optimize_top_level(
|
|||||||
.rev()
|
.rev()
|
||||||
.flat_map(|m| m.iter_var())
|
.flat_map(|m| m.iter_var())
|
||||||
{
|
{
|
||||||
state.push_var(name, AccessMode::ReadOnly, Some(value.clone()));
|
state.push_var(name, AccessMode::ReadOnly, value.clone());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add constants and variables from the scope
|
// Add constants and variables from the scope
|
||||||
for (name, constant, value) in scope.iter() {
|
for (name, constant, value) in scope.iter() {
|
||||||
if constant {
|
if constant {
|
||||||
state.push_var(name, AccessMode::ReadOnly, Some(value));
|
state.push_var(name, AccessMode::ReadOnly, value);
|
||||||
} else {
|
} else {
|
||||||
state.push_var(name, AccessMode::ReadWrite, None);
|
state.push_var(name, AccessMode::ReadWrite, Dynamic::NULL);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1317,7 +1311,7 @@ pub fn optimize_into_ast(
|
|||||||
let mut statements = statements;
|
let mut statements = statements;
|
||||||
|
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
let lib = {
|
let lib: crate::Shared<_> = {
|
||||||
let mut module = crate::Module::new();
|
let mut module = crate::Module::new();
|
||||||
|
|
||||||
if optimization_level != OptimizationLevel::None {
|
if optimization_level != OptimizationLevel::None {
|
||||||
@ -1338,7 +1332,7 @@ pub fn optimize_into_ast(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let lib2 = &[&lib2];
|
let lib2 = &[lib2.into()];
|
||||||
|
|
||||||
for fn_def in functions {
|
for fn_def in functions {
|
||||||
let mut fn_def = crate::func::shared_take_or_clone(fn_def);
|
let mut fn_def = crate::func::shared_take_or_clone(fn_def);
|
||||||
@ -1356,7 +1350,7 @@ pub fn optimize_into_ast(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module
|
module.into()
|
||||||
};
|
};
|
||||||
|
|
||||||
statements.shrink_to_fit();
|
statements.shrink_to_fit();
|
||||||
@ -1369,7 +1363,7 @@ pub fn optimize_into_ast(
|
|||||||
engine,
|
engine,
|
||||||
scope,
|
scope,
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
&[&lib],
|
&[lib.clone()],
|
||||||
optimization_level,
|
optimization_level,
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
@ -33,8 +33,7 @@ mod debugging_functions {
|
|||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
#[cfg(not(feature = "no_index"))]
|
#[cfg(not(feature = "no_index"))]
|
||||||
pub fn back_trace(ctx: NativeCallContext) -> Array {
|
pub fn back_trace(ctx: NativeCallContext) -> Array {
|
||||||
if let Some(global) = ctx.global_runtime_state() {
|
ctx.global_runtime_state()
|
||||||
global
|
|
||||||
.debugger
|
.debugger
|
||||||
.call_stack()
|
.call_stack()
|
||||||
.iter()
|
.iter()
|
||||||
@ -57,19 +56,13 @@ mod debugging_functions {
|
|||||||
map.insert("display".into(), display.into());
|
map.insert("display".into(), display.into());
|
||||||
map.insert("fn_name".into(), _fn_name.into());
|
map.insert("fn_name".into(), _fn_name.into());
|
||||||
if !_args.is_empty() {
|
if !_args.is_empty() {
|
||||||
map.insert(
|
map.insert("args".into(), Dynamic::from_array(_args.clone().to_vec()));
|
||||||
"args".into(),
|
|
||||||
Dynamic::from_array(_args.clone().to_vec()),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if let Some(source) = _source {
|
if let Some(source) = _source {
|
||||||
map.insert("source".into(), source.into());
|
map.insert("source".into(), source.into());
|
||||||
}
|
}
|
||||||
if !_pos.is_none() {
|
if !_pos.is_none() {
|
||||||
map.insert(
|
map.insert("line".into(), (_pos.line().unwrap() as crate::INT).into());
|
||||||
"line".into(),
|
|
||||||
(_pos.line().unwrap() as crate::INT).into(),
|
|
||||||
);
|
|
||||||
map.insert(
|
map.insert(
|
||||||
"position".into(),
|
"position".into(),
|
||||||
(_pos.position().unwrap_or(0) as crate::INT).into(),
|
(_pos.position().unwrap_or(0) as crate::INT).into(),
|
||||||
@ -82,8 +75,5 @@ mod debugging_functions {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
.collect()
|
.collect()
|
||||||
} else {
|
|
||||||
Array::new()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
//! Module containing all built-in _packages_ available to Rhai, plus facilities to define custom packages.
|
//! Module containing all built-in _packages_ available to Rhai, plus facilities to define custom packages.
|
||||||
|
|
||||||
use crate::{Engine, Module, Shared};
|
use crate::{Engine, Module, SharedModule};
|
||||||
|
|
||||||
pub(crate) mod arithmetic;
|
pub(crate) mod arithmetic;
|
||||||
pub(crate) mod array_basic;
|
pub(crate) mod array_basic;
|
||||||
@ -99,7 +99,7 @@ pub trait Package {
|
|||||||
|
|
||||||
/// Get a reference to a shared module from this package.
|
/// Get a reference to a shared module from this package.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
fn as_shared_module(&self) -> Shared<Module>;
|
fn as_shared_module(&self) -> SharedModule;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Macro that makes it easy to define a _package_ (which is basically a shared [module][Module])
|
/// Macro that makes it easy to define a _package_ (which is basically a shared [module][Module])
|
||||||
|
@ -8,7 +8,7 @@ use crate::ast::{
|
|||||||
SwitchCasesCollection, TryCatchBlock,
|
SwitchCasesCollection, TryCatchBlock,
|
||||||
};
|
};
|
||||||
use crate::engine::{Precedence, KEYWORD_THIS, OP_CONTAINS};
|
use crate::engine::{Precedence, KEYWORD_THIS, OP_CONTAINS};
|
||||||
use crate::eval::GlobalRuntimeState;
|
use crate::eval::{Caches, GlobalRuntimeState};
|
||||||
use crate::func::{hashing::get_hasher, StraightHashMap};
|
use crate::func::{hashing::get_hasher, StraightHashMap};
|
||||||
use crate::tokenizer::{
|
use crate::tokenizer::{
|
||||||
is_keyword_function, is_valid_function_name, is_valid_identifier, Token, TokenStream,
|
is_keyword_function, is_valid_function_name, is_valid_identifier, Token, TokenStream,
|
||||||
@ -55,7 +55,7 @@ pub struct ParseState<'e> {
|
|||||||
/// External [scope][Scope] with constants.
|
/// External [scope][Scope] with constants.
|
||||||
pub scope: &'e Scope<'e>,
|
pub scope: &'e Scope<'e>,
|
||||||
/// Global runtime state.
|
/// Global runtime state.
|
||||||
pub global: GlobalRuntimeState<'e>,
|
pub global: GlobalRuntimeState,
|
||||||
/// Encapsulates a local stack with variable names to simulate an actual runtime scope.
|
/// Encapsulates a local stack with variable names to simulate an actual runtime scope.
|
||||||
pub stack: Scope<'e>,
|
pub stack: Scope<'e>,
|
||||||
/// Size of the local variables stack upon entry of the current block scope.
|
/// Size of the local variables stack upon entry of the current block scope.
|
||||||
@ -2898,23 +2898,24 @@ impl Engine {
|
|||||||
|
|
||||||
if let Some(ref filter) = self.def_var_filter {
|
if let Some(ref filter) = self.def_var_filter {
|
||||||
let will_shadow = state.stack.iter().any(|(v, ..)| v == name);
|
let will_shadow = state.stack.iter().any(|(v, ..)| v == name);
|
||||||
let level = settings.level;
|
state.global.level = settings.level;
|
||||||
let is_const = access == AccessMode::ReadOnly;
|
let is_const = access == AccessMode::ReadOnly;
|
||||||
let info = VarDefInfo {
|
let info = VarDefInfo {
|
||||||
name: &name,
|
name: &name,
|
||||||
is_const,
|
is_const,
|
||||||
nesting_level: level,
|
nesting_level: state.global.level,
|
||||||
will_shadow,
|
will_shadow,
|
||||||
};
|
};
|
||||||
let mut this_ptr = None;
|
let caches = &mut Caches::new();
|
||||||
|
let mut this = Dynamic::NULL;
|
||||||
|
|
||||||
let context = EvalContext::new(
|
let context = EvalContext::new(
|
||||||
self,
|
self,
|
||||||
&mut state.global,
|
&mut state.global,
|
||||||
None,
|
caches,
|
||||||
&[],
|
&[],
|
||||||
level,
|
|
||||||
&mut state.stack,
|
&mut state.stack,
|
||||||
&mut this_ptr,
|
&mut this,
|
||||||
);
|
);
|
||||||
|
|
||||||
match filter(false, info, context) {
|
match filter(false, info, context) {
|
||||||
|
@ -125,6 +125,8 @@ impl<'de> Deserializer<'de> for DynamicDeserializer<'de> {
|
|||||||
|
|
||||||
fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
|
fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
|
||||||
match self.0 .0 {
|
match self.0 .0 {
|
||||||
|
Union::Null => unreachable!(),
|
||||||
|
|
||||||
Union::Unit(..) => self.deserialize_unit(visitor),
|
Union::Unit(..) => self.deserialize_unit(visitor),
|
||||||
Union::Bool(..) => self.deserialize_bool(visitor),
|
Union::Bool(..) => self.deserialize_bool(visitor),
|
||||||
Union::Str(..) => self.deserialize_str(visitor),
|
Union::Str(..) => self.deserialize_str(visitor),
|
||||||
|
@ -15,6 +15,8 @@ use crate::types::dynamic::Variant;
|
|||||||
impl Serialize for Dynamic {
|
impl Serialize for Dynamic {
|
||||||
fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
|
fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
|
Union::Null => unreachable!(),
|
||||||
|
|
||||||
Union::Unit(..) => ser.serialize_unit(),
|
Union::Unit(..) => ser.serialize_unit(),
|
||||||
Union::Bool(x, ..) => ser.serialize_bool(x),
|
Union::Bool(x, ..) => ser.serialize_bool(x),
|
||||||
Union::Str(ref s, ..) => ser.serialize_str(s.as_str()),
|
Union::Str(ref s, ..) => ser.serialize_str(s.as_str()),
|
||||||
|
@ -45,9 +45,9 @@ fn check_struct_sizes() {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
size_of::<NativeCallContext>(),
|
size_of::<NativeCallContext>(),
|
||||||
if cfg!(feature = "no_position") {
|
if cfg!(feature = "no_position") {
|
||||||
72
|
64
|
||||||
} else {
|
} else {
|
||||||
80
|
72
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -55,6 +55,9 @@ pub struct Dynamic(pub(crate) Union);
|
|||||||
///
|
///
|
||||||
/// Most variants are boxed to reduce the size.
|
/// Most variants are boxed to reduce the size.
|
||||||
pub enum Union {
|
pub enum Union {
|
||||||
|
/// An error value which should not exist.
|
||||||
|
Null,
|
||||||
|
|
||||||
/// The Unit value - ().
|
/// The Unit value - ().
|
||||||
Unit((), Tag, AccessMode),
|
Unit((), Tag, AccessMode),
|
||||||
/// A boolean value.
|
/// A boolean value.
|
||||||
@ -178,6 +181,8 @@ impl Dynamic {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn tag(&self) -> Tag {
|
pub const fn tag(&self) -> Tag {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
|
Union::Null => unreachable!(),
|
||||||
|
|
||||||
Union::Unit(_, tag, _)
|
Union::Unit(_, tag, _)
|
||||||
| Union::Bool(_, tag, _)
|
| Union::Bool(_, tag, _)
|
||||||
| Union::Str(_, tag, _)
|
| Union::Str(_, tag, _)
|
||||||
@ -203,6 +208,8 @@ impl Dynamic {
|
|||||||
/// Attach arbitrary data to this [`Dynamic`].
|
/// Attach arbitrary data to this [`Dynamic`].
|
||||||
pub fn set_tag(&mut self, value: Tag) -> &mut Self {
|
pub fn set_tag(&mut self, value: Tag) -> &mut Self {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
|
Union::Null => unreachable!(),
|
||||||
|
|
||||||
Union::Unit(_, ref mut tag, _)
|
Union::Unit(_, ref mut tag, _)
|
||||||
| Union::Bool(_, ref mut tag, _)
|
| Union::Bool(_, ref mut tag, _)
|
||||||
| Union::Str(_, ref mut tag, _)
|
| Union::Str(_, ref mut tag, _)
|
||||||
@ -226,6 +233,12 @@ impl Dynamic {
|
|||||||
}
|
}
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
/// Is this [`Dynamic`] null?
|
||||||
|
#[inline(always)]
|
||||||
|
#[must_use]
|
||||||
|
pub(crate) const fn is_null(&self) -> bool {
|
||||||
|
matches!(self.0, Union::Null)
|
||||||
|
}
|
||||||
/// Does this [`Dynamic`] hold a variant data type instead of one of the supported system
|
/// Does this [`Dynamic`] hold a variant data type instead of one of the supported system
|
||||||
/// primitive types?
|
/// primitive types?
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
@ -307,6 +320,8 @@ impl Dynamic {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn type_id(&self) -> TypeId {
|
pub fn type_id(&self) -> TypeId {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
|
Union::Null => unreachable!(),
|
||||||
|
|
||||||
Union::Unit(..) => TypeId::of::<()>(),
|
Union::Unit(..) => TypeId::of::<()>(),
|
||||||
Union::Bool(..) => TypeId::of::<bool>(),
|
Union::Bool(..) => TypeId::of::<bool>(),
|
||||||
Union::Str(..) => TypeId::of::<ImmutableString>(),
|
Union::Str(..) => TypeId::of::<ImmutableString>(),
|
||||||
@ -341,6 +356,8 @@ impl Dynamic {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn type_name(&self) -> &'static str {
|
pub fn type_name(&self) -> &'static str {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
|
Union::Null => unreachable!(),
|
||||||
|
|
||||||
Union::Unit(..) => "()",
|
Union::Unit(..) => "()",
|
||||||
Union::Bool(..) => "bool",
|
Union::Bool(..) => "bool",
|
||||||
Union::Str(..) => "string",
|
Union::Str(..) => "string",
|
||||||
@ -385,6 +402,8 @@ impl Hash for Dynamic {
|
|||||||
mem::discriminant(&self.0).hash(state);
|
mem::discriminant(&self.0).hash(state);
|
||||||
|
|
||||||
match self.0 {
|
match self.0 {
|
||||||
|
Union::Null => unreachable!(),
|
||||||
|
|
||||||
Union::Unit(..) => (),
|
Union::Unit(..) => (),
|
||||||
Union::Bool(ref b, ..) => b.hash(state),
|
Union::Bool(ref b, ..) => b.hash(state),
|
||||||
Union::Str(ref s, ..) => s.hash(state),
|
Union::Str(ref s, ..) => s.hash(state),
|
||||||
@ -416,6 +435,8 @@ impl Hash for Dynamic {
|
|||||||
impl fmt::Display for Dynamic {
|
impl fmt::Display for Dynamic {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
|
Union::Null => unreachable!(),
|
||||||
|
|
||||||
Union::Unit(..) => Ok(()),
|
Union::Unit(..) => Ok(()),
|
||||||
Union::Bool(ref v, ..) => fmt::Display::fmt(v, f),
|
Union::Bool(ref v, ..) => fmt::Display::fmt(v, f),
|
||||||
Union::Str(ref v, ..) => fmt::Display::fmt(v, f),
|
Union::Str(ref v, ..) => fmt::Display::fmt(v, f),
|
||||||
@ -509,6 +530,8 @@ impl fmt::Debug for Dynamic {
|
|||||||
#[inline(never)]
|
#[inline(never)]
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
|
Union::Null => unreachable!(),
|
||||||
|
|
||||||
Union::Unit(ref v, ..) => fmt::Debug::fmt(v, f),
|
Union::Unit(ref v, ..) => fmt::Debug::fmt(v, f),
|
||||||
Union::Bool(ref v, ..) => fmt::Debug::fmt(v, f),
|
Union::Bool(ref v, ..) => fmt::Debug::fmt(v, f),
|
||||||
Union::Str(ref v, ..) => fmt::Debug::fmt(v, f),
|
Union::Str(ref v, ..) => fmt::Debug::fmt(v, f),
|
||||||
@ -619,6 +642,8 @@ impl Clone for Dynamic {
|
|||||||
/// The cloned copy is marked read-write even if the original is read-only.
|
/// The cloned copy is marked read-write even if the original is read-only.
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
|
Union::Null => unreachable!(),
|
||||||
|
|
||||||
Union::Unit(v, tag, ..) => Self(Union::Unit(v, tag, ReadWrite)),
|
Union::Unit(v, tag, ..) => Self(Union::Unit(v, tag, ReadWrite)),
|
||||||
Union::Bool(v, tag, ..) => Self(Union::Bool(v, tag, ReadWrite)),
|
Union::Bool(v, tag, ..) => Self(Union::Bool(v, tag, ReadWrite)),
|
||||||
Union::Str(ref v, tag, ..) => Self(Union::Str(v.clone(), tag, ReadWrite)),
|
Union::Str(ref v, tag, ..) => Self(Union::Str(v.clone(), tag, ReadWrite)),
|
||||||
@ -666,6 +691,9 @@ use std::f32::consts as FloatConstants;
|
|||||||
use std::f64::consts as FloatConstants;
|
use std::f64::consts as FloatConstants;
|
||||||
|
|
||||||
impl Dynamic {
|
impl Dynamic {
|
||||||
|
/// A [`Dynamic`] containing a `null`.
|
||||||
|
pub(crate) const NULL: Self = Self(Union::Null);
|
||||||
|
|
||||||
/// A [`Dynamic`] containing a `()`.
|
/// A [`Dynamic`] containing a `()`.
|
||||||
pub const UNIT: Self = Self(Union::Unit((), DEFAULT_TAG_VALUE, ReadWrite));
|
pub const UNIT: Self = Self(Union::Unit((), DEFAULT_TAG_VALUE, ReadWrite));
|
||||||
/// A [`Dynamic`] containing a `true`.
|
/// A [`Dynamic`] containing a `true`.
|
||||||
@ -888,6 +916,8 @@ impl Dynamic {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub(crate) const fn access_mode(&self) -> AccessMode {
|
pub(crate) const fn access_mode(&self) -> AccessMode {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
|
Union::Null => unreachable!(),
|
||||||
|
|
||||||
Union::Unit(.., access)
|
Union::Unit(.., access)
|
||||||
| Union::Bool(.., access)
|
| Union::Bool(.., access)
|
||||||
| Union::Str(.., access)
|
| Union::Str(.., access)
|
||||||
@ -913,6 +943,8 @@ impl Dynamic {
|
|||||||
/// Set the [`AccessMode`] for this [`Dynamic`].
|
/// Set the [`AccessMode`] for this [`Dynamic`].
|
||||||
pub(crate) fn set_access_mode(&mut self, typ: AccessMode) -> &mut Self {
|
pub(crate) fn set_access_mode(&mut self, typ: AccessMode) -> &mut Self {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
|
Union::Null => unreachable!(),
|
||||||
|
|
||||||
Union::Unit(.., ref mut access)
|
Union::Unit(.., ref mut access)
|
||||||
| Union::Bool(.., ref mut access)
|
| Union::Bool(.., ref mut access)
|
||||||
| Union::Str(.., ref mut access)
|
| Union::Str(.., ref mut access)
|
||||||
@ -1107,6 +1139,7 @@ impl Dynamic {
|
|||||||
let _access = self.access_mode();
|
let _access = self.access_mode();
|
||||||
|
|
||||||
match self.0 {
|
match self.0 {
|
||||||
|
Union::Null => unreachable!(),
|
||||||
Union::Shared(..) => self,
|
Union::Shared(..) => self,
|
||||||
_ => Self(Union::Shared(
|
_ => Self(Union::Shared(
|
||||||
crate::Locked::new(self).into(),
|
crate::Locked::new(self).into(),
|
||||||
@ -1151,6 +1184,8 @@ impl Dynamic {
|
|||||||
reify!(self, |v: T| return Some(v));
|
reify!(self, |v: T| return Some(v));
|
||||||
|
|
||||||
match self.0 {
|
match self.0 {
|
||||||
|
Union::Null => unreachable!(),
|
||||||
|
|
||||||
Union::Int(v, ..) => reify!(v => Option<T>),
|
Union::Int(v, ..) => reify!(v => Option<T>),
|
||||||
#[cfg(not(feature = "no_float"))]
|
#[cfg(not(feature = "no_float"))]
|
||||||
Union::Float(v, ..) => reify!(*v => Option<T>),
|
Union::Float(v, ..) => reify!(*v => Option<T>),
|
||||||
@ -1485,6 +1520,7 @@ impl Dynamic {
|
|||||||
}
|
}
|
||||||
|
|
||||||
match self.0 {
|
match self.0 {
|
||||||
|
Union::Null => unreachable!(),
|
||||||
Union::Variant(ref v, ..) => (***v).as_any().downcast_ref::<T>(),
|
Union::Variant(ref v, ..) => (***v).as_any().downcast_ref::<T>(),
|
||||||
#[cfg(not(feature = "no_closure"))]
|
#[cfg(not(feature = "no_closure"))]
|
||||||
Union::Shared(..) => None,
|
Union::Shared(..) => None,
|
||||||
@ -1583,6 +1619,7 @@ impl Dynamic {
|
|||||||
}
|
}
|
||||||
|
|
||||||
match self.0 {
|
match self.0 {
|
||||||
|
Union::Null => unreachable!(),
|
||||||
Union::Variant(ref mut v, ..) => (***v).as_any_mut().downcast_mut::<T>(),
|
Union::Variant(ref mut v, ..) => (***v).as_any_mut().downcast_mut::<T>(),
|
||||||
#[cfg(not(feature = "no_closure"))]
|
#[cfg(not(feature = "no_closure"))]
|
||||||
Union::Shared(..) => None,
|
Union::Shared(..) => None,
|
||||||
|
@ -1,10 +1,11 @@
|
|||||||
//! The `FnPtr` type.
|
//! The `FnPtr` type.
|
||||||
|
|
||||||
|
use crate::eval::GlobalRuntimeState;
|
||||||
use crate::tokenizer::is_valid_function_name;
|
use crate::tokenizer::is_valid_function_name;
|
||||||
use crate::types::dynamic::Variant;
|
use crate::types::dynamic::Variant;
|
||||||
use crate::{
|
use crate::{
|
||||||
Dynamic, Engine, FuncArgs, ImmutableString, Module, NativeCallContext, Position, RhaiError,
|
Dynamic, Engine, FuncArgs, ImmutableString, NativeCallContext, Position, RhaiError, RhaiResult,
|
||||||
RhaiResult, RhaiResultOf, StaticVec, AST, ERR,
|
RhaiResultOf, SharedModule, StaticVec, AST, ERR,
|
||||||
};
|
};
|
||||||
#[cfg(feature = "no_std")]
|
#[cfg(feature = "no_std")]
|
||||||
use std::prelude::v1::*;
|
use std::prelude::v1::*;
|
||||||
@ -150,17 +151,19 @@ impl FnPtr {
|
|||||||
let mut arg_values = crate::StaticVec::new_const();
|
let mut arg_values = crate::StaticVec::new_const();
|
||||||
args.parse(&mut arg_values);
|
args.parse(&mut arg_values);
|
||||||
|
|
||||||
let lib = [
|
let lib: &[SharedModule] = &[
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
_ast.as_ref(),
|
AsRef::<SharedModule>::as_ref(ast).clone(),
|
||||||
];
|
];
|
||||||
let lib = if lib.first().map_or(true, |m: &&Module| m.is_empty()) {
|
let lib = if lib.first().map_or(true, |m| m.is_empty()) {
|
||||||
&lib[0..0]
|
&[][..]
|
||||||
} else {
|
} else {
|
||||||
&lib
|
&lib
|
||||||
};
|
};
|
||||||
#[allow(deprecated)]
|
|
||||||
let ctx = NativeCallContext::new(engine, self.fn_name(), lib);
|
let global = &GlobalRuntimeState::new(engine);
|
||||||
|
|
||||||
|
let ctx = (engine, self.fn_name(), None, global, lib, Position::NONE).into();
|
||||||
|
|
||||||
let result = self.call_raw(&ctx, None, arg_values)?;
|
let result = self.call_raw(&ctx, None, arg_values)?;
|
||||||
|
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
|
//! A strings interner type.
|
||||||
|
|
||||||
use super::BloomFilterU64;
|
use super::BloomFilterU64;
|
||||||
use crate::func::{hashing::get_hasher, StraightHashMap};
|
use crate::func::{hashing::get_hasher, StraightHashMap};
|
||||||
use crate::ImmutableString;
|
use crate::ImmutableString;
|
||||||
@ -20,10 +22,8 @@ pub const MAX_INTERNED_STRINGS: usize = 1024;
|
|||||||
/// Maximum length of strings interned.
|
/// Maximum length of strings interned.
|
||||||
pub const MAX_STRING_LEN: usize = 24;
|
pub const MAX_STRING_LEN: usize = 24;
|
||||||
|
|
||||||
/// _(internals)_ A factory of identifiers from text strings.
|
/// _(internals)_ A cache for interned strings.
|
||||||
/// Exported under the `internals` feature only.
|
/// Exported under the `internals` feature only.
|
||||||
///
|
|
||||||
/// Normal identifiers, property getters and setters are interned separately.
|
|
||||||
pub struct StringsInterner<'a> {
|
pub struct StringsInterner<'a> {
|
||||||
/// Maximum number of strings interned.
|
/// Maximum number of strings interned.
|
||||||
pub capacity: usize,
|
pub capacity: usize,
|
||||||
@ -103,14 +103,23 @@ impl StringsInterner<'_> {
|
|||||||
if value.strong_count() > 1 {
|
if value.strong_count() > 1 {
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
e.insert(value).clone()
|
e.insert(value).clone()
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// If the interner is over capacity, remove the longest entry that has the lowest count
|
// Throttle the cache upon exit
|
||||||
if self.cache.len() > self.capacity {
|
self.throttle_cache(hash);
|
||||||
// Throttle: leave some buffer to grow when shrinking the cache.
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// If the interner is over capacity, remove the longest entry that has the lowest count
|
||||||
|
fn throttle_cache(&mut self, hash: u64) {
|
||||||
|
if self.cache.len() <= self.capacity {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Leave some buffer to grow when shrinking the cache.
|
||||||
// We leave at least two entries, one for the empty string, and one for the string
|
// We leave at least two entries, one for the empty string, and one for the string
|
||||||
// that has just been inserted.
|
// that has just been inserted.
|
||||||
let max = if self.capacity < 5 {
|
let max = if self.capacity < 5 {
|
||||||
@ -124,8 +133,7 @@ impl StringsInterner<'_> {
|
|||||||
.cache
|
.cache
|
||||||
.iter()
|
.iter()
|
||||||
.fold((0, usize::MAX, 0), |(x, c, n), (&k, v)| {
|
.fold((0, usize::MAX, 0), |(x, c, n), (&k, v)| {
|
||||||
if k != hash
|
if k != hash && (v.strong_count() < c || (v.strong_count() == c && v.len() > x))
|
||||||
&& (v.strong_count() < c || (v.strong_count() == c && v.len() > x))
|
|
||||||
{
|
{
|
||||||
(v.len(), v.strong_count(), k)
|
(v.len(), v.strong_count(), k)
|
||||||
} else {
|
} else {
|
||||||
@ -137,9 +145,6 @@ impl StringsInterner<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Number of strings interned.
|
/// Number of strings interned.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
|
@ -8,6 +8,7 @@ pub mod fn_ptr;
|
|||||||
pub mod immutable_string;
|
pub mod immutable_string;
|
||||||
pub mod interner;
|
pub mod interner;
|
||||||
pub mod parse_error;
|
pub mod parse_error;
|
||||||
|
pub mod restore;
|
||||||
pub mod scope;
|
pub mod scope;
|
||||||
pub mod variant;
|
pub mod variant;
|
||||||
|
|
||||||
@ -21,5 +22,6 @@ pub use fn_ptr::FnPtr;
|
|||||||
pub use immutable_string::ImmutableString;
|
pub use immutable_string::ImmutableString;
|
||||||
pub use interner::StringsInterner;
|
pub use interner::StringsInterner;
|
||||||
pub use parse_error::{LexError, ParseError, ParseErrorType};
|
pub use parse_error::{LexError, ParseError, ParseErrorType};
|
||||||
|
pub use restore::RestoreOnDrop;
|
||||||
pub use scope::Scope;
|
pub use scope::Scope;
|
||||||
pub use variant::Variant;
|
pub use variant::Variant;
|
||||||
|
65
src/types/restore.rs
Normal file
65
src/types/restore.rs
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
//! Facility to run state restoration logic at the end of scope.
|
||||||
|
|
||||||
|
use std::ops::{Deref, DerefMut};
|
||||||
|
#[cfg(feature = "no_std")]
|
||||||
|
use std::prelude::v1::*;
|
||||||
|
|
||||||
|
/// Run custom restoration logic upon the end of scope.
|
||||||
|
#[must_use]
|
||||||
|
pub struct RestoreOnDrop<'a, T, R: FnOnce(&mut T)> {
|
||||||
|
value: &'a mut T,
|
||||||
|
restore: Option<R>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T, R: FnOnce(&mut T)> RestoreOnDrop<'a, T, R> {
|
||||||
|
/// Create a new [`RestoreOnDrop`] that locks a mutable reference and runs restoration logic at
|
||||||
|
/// the end of scope only when `need_restore` is `true`.
|
||||||
|
///
|
||||||
|
/// Beware that the end of scope means the end of its lifetime, not necessarily waiting until
|
||||||
|
/// the current block scope is exited.
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn lock_if(need_restore: bool, value: &'a mut T, restore: R) -> Self {
|
||||||
|
Self {
|
||||||
|
value,
|
||||||
|
restore: if need_restore { Some(restore) } else { None },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a new [`RestoreOnDrop`] that locks a mutable reference and runs restoration logic at
|
||||||
|
/// the end of scope.
|
||||||
|
///
|
||||||
|
/// Beware that the end of scope means the end of its lifetime, not necessarily waiting until
|
||||||
|
/// the current block scope is exited.
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn lock(value: &'a mut T, restore: R) -> Self {
|
||||||
|
Self {
|
||||||
|
value,
|
||||||
|
restore: Some(restore),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T, R: FnOnce(&mut T)> Drop for RestoreOnDrop<'a, T, R> {
|
||||||
|
#[inline(always)]
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(restore) = self.restore.take() {
|
||||||
|
restore(self.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T, R: FnOnce(&mut T)> Deref for RestoreOnDrop<'a, T, R> {
|
||||||
|
type Target = T;
|
||||||
|
|
||||||
|
#[inline(always)]
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
self.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T, R: FnOnce(&mut T)> DerefMut for RestoreOnDrop<'a, T, R> {
|
||||||
|
#[inline(always)]
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
|
self.value
|
||||||
|
}
|
||||||
|
}
|
@ -2,7 +2,7 @@
|
|||||||
use rhai::{
|
use rhai::{
|
||||||
module_resolvers::{DummyModuleResolver, StaticModuleResolver},
|
module_resolvers::{DummyModuleResolver, StaticModuleResolver},
|
||||||
Dynamic, Engine, EvalAltResult, FnNamespace, FnPtr, ImmutableString, Module, NativeCallContext,
|
Dynamic, Engine, EvalAltResult, FnNamespace, FnPtr, ImmutableString, Module, NativeCallContext,
|
||||||
ParseError, ParseErrorType, Scope, Shared, INT,
|
ParseError, ParseErrorType, Scope, INT,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -546,44 +546,13 @@ fn test_module_context() -> Result<(), Box<EvalAltResult>> {
|
|||||||
engine.register_fn(
|
engine.register_fn(
|
||||||
"calc",
|
"calc",
|
||||||
|context: NativeCallContext, fp: FnPtr| -> Result<INT, Box<EvalAltResult>> {
|
|context: NativeCallContext, fp: FnPtr| -> Result<INT, Box<EvalAltResult>> {
|
||||||
// Store fields for later use
|
|
||||||
let engine = context.engine();
|
let engine = context.engine();
|
||||||
let fn_name = context.fn_name().to_string();
|
|
||||||
let source = context.source().map(|s| s.to_string());
|
|
||||||
let global = context.global_runtime_state().unwrap().clone();
|
|
||||||
let pos = context.position();
|
|
||||||
let call_level = context.call_level();
|
|
||||||
|
|
||||||
// Store the paths of the stack of call modules up to this point
|
// Store context for later use - requires the 'internals' feature
|
||||||
let modules_list: Vec<String> = context
|
let context_data = context.store_data();
|
||||||
.iter_namespaces()
|
|
||||||
.map(|m| m.id().unwrap_or("testing"))
|
|
||||||
.filter(|id| !id.is_empty())
|
|
||||||
.map(|id| id.to_string())
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
// Recreate the 'NativeCallContext' - requires the 'internals' feature
|
// Recreate the 'NativeCallContext'
|
||||||
let mut libraries = Vec::<Shared<Module>>::new();
|
let new_context = context_data.create_context(engine);
|
||||||
|
|
||||||
for path in modules_list {
|
|
||||||
// Recreate the stack of call modules by resolving each path with
|
|
||||||
// the module resolver.
|
|
||||||
let module = engine.module_resolver().resolve(engine, None, &path, pos)?;
|
|
||||||
|
|
||||||
libraries.push(module);
|
|
||||||
}
|
|
||||||
|
|
||||||
let lib: Vec<&Module> = libraries.iter().map(|m| m.as_ref()).collect();
|
|
||||||
|
|
||||||
let new_context = NativeCallContext::new_with_all_fields(
|
|
||||||
engine,
|
|
||||||
&fn_name,
|
|
||||||
source.as_ref().map(String::as_str),
|
|
||||||
&global,
|
|
||||||
&lib,
|
|
||||||
pos,
|
|
||||||
call_level,
|
|
||||||
);
|
|
||||||
|
|
||||||
fp.call_within_context(&new_context, (41 as INT,))
|
fp.call_within_context(&new_context, (41 as INT,))
|
||||||
},
|
},
|
||||||
|
Loading…
Reference in New Issue
Block a user