Rename Imports to GlobalRuntimeState.

This commit is contained in:
Stephen Chung 2021-12-27 23:03:30 +08:00
parent e8b070cbf8
commit a78488d935
13 changed files with 373 additions and 342 deletions

View File

@ -1,7 +1,7 @@
//! Module that defines the `call_fn` API of [`Engine`].
#![cfg(not(feature = "no_function"))]
use crate::engine::{EvalState, Imports};
use crate::engine::{EvalState, GlobalRuntimeState};
use crate::types::dynamic::Variant;
use crate::{
Dynamic, Engine, FuncArgs, Position, RhaiResult, RhaiResultOf, Scope, StaticVec, AST, ERR,
@ -154,13 +154,13 @@ impl Engine {
arg_values: impl AsMut<[Dynamic]>,
) -> RhaiResult {
let state = &mut EvalState::new();
let mods = &mut Imports::new();
let global = &mut GlobalRuntimeState::new();
let statements = ast.statements();
let orig_scope_len = scope.len();
if eval_ast && !statements.is_empty() {
self.eval_global_statements(scope, mods, state, statements, &[ast.as_ref()], 0)?;
self.eval_global_statements(scope, global, state, statements, &[ast.as_ref()], 0)?;
if rewind_scope {
scope.rewind(orig_scope_len);
@ -183,7 +183,7 @@ impl Engine {
let result = self.call_script_fn(
scope,
mods,
global,
state,
&[ast.as_ref()],
&mut this_ptr,

View File

@ -163,7 +163,7 @@ impl EvalContext<'_, '_, '_, '_, '_, '_, '_, '_> {
pub fn eval_expression_tree(&mut self, expr: &Expression) -> RhaiResult {
self.engine.eval_expr(
self.scope,
self.mods,
self.global,
self.state,
self.lib,
self.this_ptr,

View File

@ -1,6 +1,6 @@
//! Module that defines the public evaluation API of [`Engine`].
use crate::engine::{EvalState, Imports};
use crate::engine::{EvalState, GlobalRuntimeState};
use crate::parser::ParseState;
use crate::types::dynamic::Variant;
use crate::{Dynamic, Engine, Module, Position, RhaiResult, RhaiResultOf, Scope, AST, ERR};
@ -184,9 +184,9 @@ impl Engine {
scope: &mut Scope,
ast: &AST,
) -> RhaiResultOf<T> {
let mods = &mut Imports::new();
let global = &mut GlobalRuntimeState::new();
let result = self.eval_ast_with_scope_raw(scope, mods, ast, 0)?;
let result = self.eval_ast_with_scope_raw(scope, global, ast, 0)?;
let typ = self.map_type_name(result.type_name());
@ -204,17 +204,17 @@ impl Engine {
pub(crate) fn eval_ast_with_scope_raw<'a>(
&self,
scope: &mut Scope,
mods: &mut Imports,
global: &mut GlobalRuntimeState,
ast: &'a AST,
level: usize,
) -> RhaiResult {
let mut state = EvalState::new();
if ast.source_raw().is_some() {
mods.source = ast.source_raw().cloned();
global.source = ast.source_raw().cloned();
}
#[cfg(not(feature = "no_module"))]
{
mods.embedded_module_resolver = ast.resolver().cloned();
global.embedded_module_resolver = ast.resolver().cloned();
}
let statements = ast.statements();
@ -232,6 +232,6 @@ impl Engine {
} else {
&lib
};
self.eval_global_statements(scope, mods, &mut state, statements, lib, level)
self.eval_global_statements(scope, global, &mut state, statements, lib, level)
}
}

View File

@ -1,6 +1,6 @@
//! Module that defines the public evaluation API of [`Engine`].
use crate::engine::{EvalState, Imports};
use crate::engine::{EvalState, GlobalRuntimeState};
use crate::parser::ParseState;
use crate::{Engine, Module, RhaiResultOf, Scope, AST};
#[cfg(feature = "no_std")]
@ -44,14 +44,14 @@ impl Engine {
/// Evaluate an [`AST`] with own scope, returning any error (if any).
#[inline]
pub fn run_ast_with_scope(&self, scope: &mut Scope, ast: &AST) -> RhaiResultOf<()> {
let mods = &mut Imports::new();
let global = &mut GlobalRuntimeState::new();
let mut state = EvalState::new();
if ast.source_raw().is_some() {
mods.source = ast.source_raw().cloned();
global.source = ast.source_raw().cloned();
}
#[cfg(not(feature = "no_module"))]
{
mods.embedded_module_resolver = ast.resolver().cloned();
global.embedded_module_resolver = ast.resolver().cloned();
}
let statements = ast.statements();
@ -65,7 +65,7 @@ impl Engine {
} else {
&lib
};
self.eval_global_statements(scope, mods, &mut state, statements, lib, 0)?;
self.eval_global_statements(scope, global, &mut state, statements, lib, 0)?;
}
Ok(())
}

View File

@ -15,11 +15,11 @@ pub struct ScriptFnDef {
pub body: StmtBlock,
/// Encapsulated running environment, if any.
pub lib: Option<Shared<Module>>,
/// Encapsulated imported modules.
/// Encapsulated [`GlobalRuntimeState`][crate::GlobalRuntimeState].
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
pub mods: crate::engine::Imports,
pub global: crate::engine::GlobalRuntimeState,
/// Function name.
pub name: Identifier,
/// Function access mode.

File diff suppressed because it is too large Load Diff

View File

@ -6,8 +6,9 @@ use super::{get_builtin_binary_op_fn, get_builtin_op_assignment_fn};
use crate::api::default_limits::MAX_DYNAMIC_PARAMETERS;
use crate::ast::{Expr, FnCallHashes, Stmt};
use crate::engine::{
EvalState, FnResolutionCacheEntry, Imports, KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR,
KEYWORD_FN_PTR_CALL, KEYWORD_FN_PTR_CURRY, KEYWORD_IS_DEF_VAR, KEYWORD_PRINT, KEYWORD_TYPE_OF,
EvalState, FnResolutionCacheEntry, GlobalRuntimeState, KEYWORD_DEBUG, KEYWORD_EVAL,
KEYWORD_FN_PTR, KEYWORD_FN_PTR_CALL, KEYWORD_FN_PTR_CURRY, KEYWORD_IS_DEF_VAR, KEYWORD_PRINT,
KEYWORD_TYPE_OF,
};
use crate::module::Namespace;
use crate::tokenizer::Token;
@ -165,7 +166,7 @@ impl Engine {
#[must_use]
fn resolve_fn<'s>(
&self,
mods: &Imports,
global: &GlobalRuntimeState,
state: &'s mut EvalState,
lib: &[&Module],
fn_name: impl AsRef<str>,
@ -217,7 +218,8 @@ impl Engine {
})
})
.or_else(|| {
mods.get_fn(hash)
global
.get_fn(hash)
.map(|(func, source)| FnResolutionCacheEntry {
func: func.clone(),
source: source.cloned(),
@ -308,7 +310,7 @@ impl Engine {
/// **DO NOT** reuse the argument values unless for the first `&mut` argument - all others are silently replaced by `()`!
pub(crate) fn call_native_fn(
&self,
mods: &mut Imports,
global: &mut GlobalRuntimeState,
state: &mut EvalState,
lib: &[&Module],
name: impl AsRef<str>,
@ -319,13 +321,22 @@ impl Engine {
pos: Position,
) -> RhaiResultOf<(Dynamic, bool)> {
#[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut mods.num_operations, pos)?;
self.inc_operations(&mut global.num_operations, pos)?;
let name = name.as_ref();
let parent_source = mods.source.clone();
let parent_source = global.source.clone();
// Check if function access already in the cache
let func = self.resolve_fn(mods, state, lib, name, hash, Some(args), true, is_op_assign);
let func = self.resolve_fn(
global,
state,
lib,
name,
hash,
Some(args),
true,
is_op_assign,
);
if let Some(FnResolutionCacheEntry { func, source }) = func {
assert!(func.is_native());
@ -347,7 +358,7 @@ impl Engine {
.or_else(|| parent_source.as_ref())
.map(|s| s.as_str());
let context = (self, name, source, &*mods, lib, pos).into();
let context = (self, name, source, &*global, lib, pos).into();
let result = if func.is_plugin_fn() {
func.get_plugin_fn()
@ -389,7 +400,7 @@ impl Engine {
pos,
)
})?;
let source = mods.source.as_ref().map(|s| s.as_str());
let source = global.source.as_ref().map(|s| s.as_str());
(debug(&text, source, pos).into(), false)
} else {
(Dynamic::UNIT, false)
@ -485,7 +496,7 @@ impl Engine {
/// **DO NOT** reuse the argument values unless for the first `&mut` argument - all others are silently replaced by `()`!
pub(crate) fn exec_fn_call(
&self,
mods: &mut Imports,
global: &mut GlobalRuntimeState,
state: &mut EvalState,
lib: &[&Module],
fn_name: impl AsRef<str>,
@ -535,7 +546,7 @@ impl Engine {
false
} else {
let hash_script = calc_fn_hash(fn_name.as_str(), num_params as usize);
self.has_script_fn(Some(mods), state, lib, hash_script)
self.has_script_fn(Some(global), state, lib, hash_script)
}
.into(),
false,
@ -562,7 +573,16 @@ impl Engine {
// Script-defined function call?
#[cfg(not(feature = "no_function"))]
if let Some(FnResolutionCacheEntry { func, source }) = self
.resolve_fn(mods, state, lib, fn_name, hashes.script, None, false, false)
.resolve_fn(
global,
state,
lib,
fn_name,
hashes.script,
None,
false,
false,
)
.cloned()
{
// Script function call
@ -587,14 +607,14 @@ impl Engine {
// Method call of script function - map first argument to `this`
let (first_arg, rest_args) = args.split_first_mut().expect("not empty");
let orig_source = mods.source.take();
mods.source = source;
let orig_source = global.source.take();
global.source = source;
let level = _level + 1;
let result = self.call_script_fn(
scope,
mods,
global,
state,
lib,
&mut Some(*first_arg),
@ -606,7 +626,7 @@ impl Engine {
);
// Restore the original source
mods.source = orig_source;
global.source = orig_source;
result?
} else {
@ -621,17 +641,17 @@ impl Engine {
.change_first_arg_to_copy(args);
}
let orig_source = mods.source.take();
mods.source = source;
let orig_source = global.source.take();
global.source = source;
let level = _level + 1;
let result = self.call_script_fn(
scope, mods, state, lib, &mut None, func, args, pos, true, level,
scope, global, state, lib, &mut None, func, args, pos, true, level,
);
// Restore the original source
mods.source = orig_source;
global.source = orig_source;
// Restore the original reference
if let Some(bk) = backup {
@ -647,7 +667,7 @@ impl Engine {
// Native function call
let hash = hashes.native;
self.call_native_fn(
mods, state, lib, fn_name, hash, args, is_ref_mut, false, pos,
global, state, lib, fn_name, hash, args, is_ref_mut, false, pos,
)
}
@ -657,14 +677,14 @@ impl Engine {
pub(crate) fn eval_global_statements(
&self,
scope: &mut Scope,
mods: &mut Imports,
global: &mut GlobalRuntimeState,
state: &mut EvalState,
statements: &[Stmt],
lib: &[&Module],
level: usize,
) -> RhaiResult {
self.eval_stmt_block(
scope, mods, state, lib, &mut None, statements, false, false, level,
scope, global, state, lib, &mut None, statements, false, false, level,
)
.or_else(|err| match *err {
ERR::Return(out, _) => Ok(out),
@ -679,14 +699,14 @@ impl Engine {
fn eval_script_expr_in_place(
&self,
scope: &mut Scope,
mods: &mut Imports,
global: &mut GlobalRuntimeState,
lib: &[&Module],
script: impl AsRef<str>,
_pos: Position,
level: usize,
) -> RhaiResult {
#[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut mods.num_operations, _pos)?;
self.inc_operations(&mut global.num_operations, _pos)?;
let script = script.as_ref().trim();
if script.is_empty() {
@ -714,14 +734,14 @@ impl Engine {
}
// Evaluate the AST
self.eval_global_statements(scope, mods, &mut EvalState::new(), statements, lib, level)
self.eval_global_statements(scope, global, &mut EvalState::new(), statements, lib, level)
}
/// Call a dot method.
#[cfg(not(feature = "no_object"))]
pub(crate) fn make_method_call(
&self,
mods: &mut Imports,
global: &mut GlobalRuntimeState,
state: &mut EvalState,
lib: &[&Module],
fn_name: impl AsRef<str>,
@ -752,7 +772,8 @@ impl Engine {
// Map it to name(args) in function-call style
self.exec_fn_call(
mods, state, lib, fn_name, new_hash, &mut args, false, false, pos, None, level,
global, state, lib, fn_name, new_hash, &mut args, false, false, pos, None,
level,
)
}
KEYWORD_FN_PTR_CALL => {
@ -791,7 +812,7 @@ impl Engine {
// Map it to name(args) in function-call style
self.exec_fn_call(
mods, state, lib, fn_name, new_hash, &mut args, is_ref_mut, true, pos, None,
global, state, lib, fn_name, new_hash, &mut args, is_ref_mut, true, pos, None,
level,
)
}
@ -863,7 +884,8 @@ impl Engine {
args.extend(call_args.iter_mut());
self.exec_fn_call(
mods, state, lib, fn_name, hash, &mut args, is_ref_mut, true, pos, None, level,
global, state, lib, fn_name, hash, &mut args, is_ref_mut, true, pos, None,
level,
)
}
}?;
@ -883,7 +905,7 @@ impl Engine {
pub(crate) fn get_arg_value(
&self,
scope: &mut Scope,
mods: &mut Imports,
global: &mut GlobalRuntimeState,
state: &mut EvalState,
lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>,
@ -894,7 +916,7 @@ impl Engine {
match arg_expr {
Expr::Stack(slot, pos) => Ok((constants[*slot].clone(), *pos)),
ref arg => self
.eval_expr(scope, mods, state, lib, this_ptr, arg, level)
.eval_expr(scope, global, state, lib, this_ptr, arg, level)
.map(|v| (v, arg.position())),
}
}
@ -903,7 +925,7 @@ impl Engine {
pub(crate) fn make_function_call(
&self,
scope: &mut Scope,
mods: &mut Imports,
global: &mut GlobalRuntimeState,
state: &mut EvalState,
lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>,
@ -927,7 +949,7 @@ impl Engine {
// Handle call()
KEYWORD_FN_PTR_CALL if total_args >= 1 => {
let (arg, arg_pos) = self.get_arg_value(
scope, mods, state, lib, this_ptr, level, &a_expr[0], constants,
scope, global, state, lib, this_ptr, level, &a_expr[0], constants,
)?;
if !arg.is::<FnPtr>() {
@ -959,7 +981,7 @@ impl Engine {
// Handle Fn()
KEYWORD_FN_PTR if total_args == 1 => {
let (arg, arg_pos) = self.get_arg_value(
scope, mods, state, lib, this_ptr, level, &a_expr[0], constants,
scope, global, state, lib, this_ptr, level, &a_expr[0], constants,
)?;
// Fn - only in function call style
@ -974,7 +996,7 @@ impl Engine {
// Handle curry()
KEYWORD_FN_PTR_CURRY if total_args > 1 => {
let (arg, arg_pos) = self.get_arg_value(
scope, mods, state, lib, this_ptr, level, &a_expr[0], constants,
scope, global, state, lib, this_ptr, level, &a_expr[0], constants,
)?;
if !arg.is::<FnPtr>() {
@ -991,7 +1013,7 @@ impl Engine {
fn_curry,
|mut curried, expr| -> RhaiResultOf<_> {
let (value, _) = self.get_arg_value(
scope, mods, state, lib, this_ptr, level, expr, constants,
scope, global, state, lib, this_ptr, level, expr, constants,
)?;
curried.push(value);
Ok(curried)
@ -1005,7 +1027,7 @@ impl Engine {
#[cfg(not(feature = "no_closure"))]
crate::engine::KEYWORD_IS_SHARED if total_args == 1 => {
let (arg, _) = self.get_arg_value(
scope, mods, state, lib, this_ptr, level, &a_expr[0], constants,
scope, global, state, lib, this_ptr, level, &a_expr[0], constants,
)?;
return Ok(arg.is_shared().into());
}
@ -1014,7 +1036,7 @@ impl Engine {
#[cfg(not(feature = "no_function"))]
crate::engine::KEYWORD_IS_DEF_FN if total_args == 2 => {
let (arg, arg_pos) = self.get_arg_value(
scope, mods, state, lib, this_ptr, level, &a_expr[0], constants,
scope, global, state, lib, this_ptr, level, &a_expr[0], constants,
)?;
let fn_name = arg
@ -1022,7 +1044,7 @@ impl Engine {
.map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, arg_pos))?;
let (arg, arg_pos) = self.get_arg_value(
scope, mods, state, lib, this_ptr, level, &a_expr[1], constants,
scope, global, state, lib, this_ptr, level, &a_expr[1], constants,
)?;
let num_params = arg
@ -1033,7 +1055,7 @@ impl Engine {
false
} else {
let hash_script = calc_fn_hash(&fn_name, num_params as usize);
self.has_script_fn(Some(mods), state, lib, hash_script)
self.has_script_fn(Some(global), state, lib, hash_script)
}
.into());
}
@ -1041,7 +1063,7 @@ impl Engine {
// Handle is_def_var()
KEYWORD_IS_DEF_VAR if total_args == 1 => {
let (arg, arg_pos) = self.get_arg_value(
scope, mods, state, lib, this_ptr, level, &a_expr[0], constants,
scope, global, state, lib, this_ptr, level, &a_expr[0], constants,
)?;
let var_name = arg
.into_immutable_string()
@ -1054,13 +1076,13 @@ impl Engine {
// eval - only in function call style
let orig_scope_len = scope.len();
let (value, pos) = self.get_arg_value(
scope, mods, state, lib, this_ptr, level, &a_expr[0], constants,
scope, global, state, lib, this_ptr, level, &a_expr[0], constants,
)?;
let script = &value
.into_immutable_string()
.map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, pos))?;
let result =
self.eval_script_expr_in_place(scope, mods, lib, script, pos, level + 1);
self.eval_script_expr_in_place(scope, global, lib, script, pos, level + 1);
// IMPORTANT! If the eval defines new variables in the current scope,
// all variable offsets from this point on will be mis-aligned.
@ -1071,7 +1093,8 @@ impl Engine {
return result.map_err(|err| {
ERR::ErrorInFunctionCall(
KEYWORD_EVAL.to_string(),
mods.source
global
.source
.as_ref()
.map(Identifier::to_string)
.unwrap_or_default(),
@ -1096,7 +1119,7 @@ impl Engine {
// variable access) to &mut because `scope` is needed.
if capture_scope && !scope.is_empty() {
a_expr.iter().try_for_each(|expr| {
self.get_arg_value(scope, mods, state, lib, this_ptr, level, expr, constants)
self.get_arg_value(scope, global, state, lib, this_ptr, level, expr, constants)
.map(|(value, _)| arg_values.push(value.flatten()))
})?;
args.extend(curry.iter_mut());
@ -1107,7 +1130,8 @@ impl Engine {
return self
.exec_fn_call(
mods, state, lib, name, hashes, &mut args, is_ref_mut, false, pos, scope, level,
global, state, lib, name, hashes, &mut args, is_ref_mut, false, pos, scope,
level,
)
.map(|(v, _)| v);
}
@ -1124,19 +1148,19 @@ impl Engine {
let (first_expr, rest_expr) = a_expr.split_first().expect("not empty");
rest_expr.iter().try_for_each(|expr| {
self.get_arg_value(scope, mods, state, lib, this_ptr, level, expr, constants)
self.get_arg_value(scope, global, state, lib, this_ptr, level, expr, constants)
.map(|(value, _)| arg_values.push(value.flatten()))
})?;
let (mut target, _pos) =
self.search_namespace(scope, mods, state, lib, this_ptr, first_expr)?;
self.search_namespace(scope, global, state, lib, this_ptr, first_expr)?;
if target.as_ref().is_read_only() {
target = target.into_owned();
}
#[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut mods.num_operations, _pos)?;
self.inc_operations(&mut global.num_operations, _pos)?;
#[cfg(not(feature = "no_closure"))]
let target_is_shared = target.is_shared();
@ -1156,7 +1180,7 @@ impl Engine {
} else {
// func(..., ...)
a_expr.iter().try_for_each(|expr| {
self.get_arg_value(scope, mods, state, lib, this_ptr, level, expr, constants)
self.get_arg_value(scope, global, state, lib, this_ptr, level, expr, constants)
.map(|(value, _)| arg_values.push(value.flatten()))
})?;
args.extend(curry.iter_mut());
@ -1165,7 +1189,7 @@ impl Engine {
}
self.exec_fn_call(
mods, state, lib, name, hashes, &mut args, is_ref_mut, false, pos, None, level,
global, state, lib, name, hashes, &mut args, is_ref_mut, false, pos, None, level,
)
.map(|(v, _)| v)
}
@ -1174,7 +1198,7 @@ impl Engine {
pub(crate) fn make_qualified_function_call(
&self,
scope: &mut Scope,
mods: &mut Imports,
global: &mut GlobalRuntimeState,
state: &mut EvalState,
lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>,
@ -1202,16 +1226,16 @@ impl Engine {
arg_values.push(Dynamic::UNIT);
args_expr.iter().skip(1).try_for_each(|expr| {
self.get_arg_value(scope, mods, state, lib, this_ptr, level, expr, constants)
self.get_arg_value(scope, global, state, lib, this_ptr, level, expr, constants)
.map(|(value, _)| arg_values.push(value.flatten()))
})?;
// Get target reference to first argument
let (target, _pos) =
self.search_scope_only(scope, mods, state, lib, this_ptr, &args_expr[0])?;
self.search_scope_only(scope, global, state, lib, this_ptr, &args_expr[0])?;
#[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut mods.num_operations, _pos)?;
self.inc_operations(&mut global.num_operations, _pos)?;
#[cfg(not(feature = "no_closure"))]
let target_is_shared = target.is_shared();
@ -1232,7 +1256,7 @@ impl Engine {
} else {
// func(..., ...) or func(mod::x, ...)
args_expr.iter().try_for_each(|expr| {
self.get_arg_value(scope, mods, state, lib, this_ptr, level, expr, constants)
self.get_arg_value(scope, global, state, lib, this_ptr, level, expr, constants)
.map(|(value, _)| arg_values.push(value.flatten()))
})?;
args.extend(arg_values.iter_mut());
@ -1240,7 +1264,7 @@ impl Engine {
}
let module = self
.search_imports(mods, state, namespace)
.search_imports(global, state, namespace)
.ok_or_else(|| ERR::ErrorModuleNotFound(namespace.to_string(), namespace[0].pos))?;
// First search in script-defined functions (can override built-in)
@ -1248,7 +1272,7 @@ impl Engine {
// Then search in Rust functions
None => {
#[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut mods.num_operations, pos)?;
self.inc_operations(&mut global.num_operations, pos)?;
let hash_params = calc_fn_params_hash(args.iter().map(|a| a.type_id()));
let hash_qualified_fn = combine_hashes(hash, hash_params);
@ -1277,22 +1301,23 @@ impl Engine {
let new_scope = &mut Scope::new();
let mut source = module.id_raw().cloned();
mem::swap(&mut mods.source, &mut source);
mem::swap(&mut global.source, &mut source);
let level = level + 1;
let result = self.call_script_fn(
new_scope, mods, state, lib, &mut None, fn_def, &mut args, pos, true, level,
new_scope, global, state, lib, &mut None, fn_def, &mut args, pos, true,
level,
);
mods.source = source;
global.source = source;
result
}
}
Some(f) if f.is_plugin_fn() => {
let context = (self, fn_name, module.id(), &*mods, lib, pos).into();
let context = (self, fn_name, module.id(), &*global, lib, pos).into();
f.get_plugin_fn()
.expect("plugin function")
.clone()
@ -1302,7 +1327,7 @@ impl Engine {
Some(f) if f.is_native() => {
let func = f.get_native_fn().expect("native function");
let context = (self, fn_name, module.id(), &*mods, lib, pos).into();
let context = (self, fn_name, module.id(), &*global, lib, pos).into();
func(context, &mut args).map_err(|err| err.fill_position(pos))
}

View File

@ -2,7 +2,7 @@
use super::call::FnCallArgs;
use crate::ast::FnCallHashes;
use crate::engine::{EvalState, Imports};
use crate::engine::{EvalState, GlobalRuntimeState};
use crate::plugin::PluginFunction;
use crate::tokenizer::{Token, TokenizeState};
use crate::types::dynamic::Variant;
@ -61,7 +61,7 @@ pub struct NativeCallContext<'a> {
engine: &'a Engine,
fn_name: &'a str,
source: Option<&'a str>,
mods: Option<&'a Imports>,
global: Option<&'a GlobalRuntimeState>,
lib: &'a [&'a Module],
pos: Position,
}
@ -71,7 +71,7 @@ impl<'a, M: AsRef<[&'a Module]> + ?Sized, S: AsRef<str> + 'a + ?Sized>
&'a Engine,
&'a S,
Option<&'a S>,
&'a Imports,
&'a GlobalRuntimeState,
&'a M,
Position,
)> for NativeCallContext<'a>
@ -82,7 +82,7 @@ impl<'a, M: AsRef<[&'a Module]> + ?Sized, S: AsRef<str> + 'a + ?Sized>
&'a Engine,
&'a S,
Option<&'a S>,
&'a Imports,
&'a GlobalRuntimeState,
&'a M,
Position,
),
@ -91,7 +91,7 @@ impl<'a, M: AsRef<[&'a Module]> + ?Sized, S: AsRef<str> + 'a + ?Sized>
engine: value.0,
fn_name: value.1.as_ref(),
source: value.2.map(|v| v.as_ref()),
mods: Some(value.3),
global: Some(value.3),
lib: value.4.as_ref(),
pos: value.5,
}
@ -107,7 +107,7 @@ impl<'a, M: AsRef<[&'a Module]> + ?Sized, S: AsRef<str> + 'a + ?Sized>
engine: value.0,
fn_name: value.1.as_ref(),
source: None,
mods: None,
global: None,
lib: value.2.as_ref(),
pos: Position::NONE,
}
@ -132,7 +132,7 @@ impl<'a> NativeCallContext<'a> {
engine,
fn_name: fn_name.as_ref(),
source: None,
mods: None,
global: None,
lib,
pos: Position::NONE,
}
@ -149,7 +149,7 @@ impl<'a> NativeCallContext<'a> {
engine: &'a Engine,
fn_name: &'a (impl AsRef<str> + 'a + ?Sized),
source: Option<&'a (impl AsRef<str> + 'a + ?Sized)>,
imports: &'a Imports,
global: &'a GlobalRuntimeState,
lib: &'a [&Module],
pos: Position,
) -> Self {
@ -157,7 +157,7 @@ impl<'a> NativeCallContext<'a> {
engine,
fn_name: fn_name.as_ref(),
source: source.map(|v| v.as_ref()),
mods: Some(imports),
global: Some(global),
lib,
pos,
}
@ -192,7 +192,7 @@ impl<'a> NativeCallContext<'a> {
#[cfg(not(feature = "no_module"))]
#[inline]
pub fn iter_imports(&self) -> impl Iterator<Item = (&str, &Module)> {
self.mods.iter().flat_map(|&m| m.iter())
self.global.iter().flat_map(|&m| m.iter_modules())
}
/// Get an iterator over the current set of modules imported via `import` statements.
#[cfg(not(feature = "no_module"))]
@ -201,9 +201,9 @@ impl<'a> NativeCallContext<'a> {
pub(crate) fn iter_imports_raw(
&self,
) -> impl Iterator<Item = (&crate::Identifier, &Shared<Module>)> {
self.mods.iter().flat_map(|&m| m.iter_raw())
self.global.iter().flat_map(|&m| m.iter_modules_raw())
}
/// _(internals)_ The current set of modules imported via `import` statements.
/// _(internals)_ The current [`GlobalRuntimeState`].
/// Exported under the `internals` feature only.
///
/// Not available under `no_module`.
@ -211,8 +211,8 @@ impl<'a> NativeCallContext<'a> {
#[cfg(not(feature = "no_module"))]
#[inline(always)]
#[must_use]
pub const fn imports(&self) -> Option<&Imports> {
self.mods
pub const fn global_runtime_state(&self) -> Option<&GlobalRuntimeState> {
self.global
}
/// Get an iterator over the namespaces containing definitions of all script-defined functions.
#[inline]
@ -292,7 +292,10 @@ impl<'a> NativeCallContext<'a> {
self.engine()
.exec_fn_call(
&mut self.mods.cloned().unwrap_or_else(|| Imports::new()),
&mut self
.global
.cloned()
.unwrap_or_else(|| GlobalRuntimeState::new()),
&mut EvalState::new(),
self.lib,
fn_name,

View File

@ -3,7 +3,7 @@
use super::call::FnCallArgs;
use crate::ast::ScriptFnDef;
use crate::engine::{EvalState, Imports};
use crate::engine::{EvalState, GlobalRuntimeState};
use crate::r#unsafe::unsafe_cast_var_name_to_lifetime;
use crate::{Dynamic, Engine, Module, Position, RhaiError, RhaiResult, Scope, StaticVec, ERR};
use std::mem;
@ -24,7 +24,7 @@ impl Engine {
pub(crate) fn call_script_fn(
&self,
scope: &mut Scope,
mods: &mut Imports,
global: &mut GlobalRuntimeState,
state: &mut EvalState,
lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>,
@ -38,7 +38,7 @@ impl Engine {
fn make_error(
name: String,
fn_def: &ScriptFnDef,
mods: &Imports,
global: &GlobalRuntimeState,
err: RhaiError,
pos: Position,
) -> RhaiResult {
@ -48,7 +48,7 @@ impl Engine {
.lib
.as_ref()
.and_then(|m| m.id().map(|id| id.to_string()))
.or_else(|| mods.source.as_ref().map(|s| s.to_string()))
.or_else(|| global.source.as_ref().map(|s| s.to_string()))
.unwrap_or_default(),
err,
pos,
@ -59,7 +59,7 @@ impl Engine {
assert!(fn_def.params.len() == args.len());
#[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut mods.num_operations, pos)?;
self.inc_operations(&mut global.num_operations, pos)?;
if fn_def.body.is_empty() {
return Ok(Dynamic::UNIT);
@ -72,7 +72,7 @@ impl Engine {
}
let orig_scope_len = scope.len();
let orig_mods_len = mods.len();
let orig_mods_len = global.num_imported_modules();
// Put arguments into scope as variables
// Actually consume the arguments instead of cloning them
@ -106,11 +106,11 @@ impl Engine {
};
#[cfg(not(feature = "no_module"))]
if !fn_def.mods.is_empty() {
if fn_def.global.num_imported_modules() > 0 {
fn_def
.mods
.iter_raw()
.for_each(|(n, m)| mods.push(n.clone(), m.clone()));
.global
.iter_modules_raw()
.for_each(|(n, m)| global.push_module(n.clone(), m.clone()));
}
// Evaluate the function
@ -118,7 +118,7 @@ impl Engine {
let result = self
.eval_stmt_block(
scope,
mods,
global,
state,
lib,
this_ptr,
@ -138,7 +138,7 @@ impl Engine {
format!("{} @ '{}' < {}", name, src, fn_def.name)
};
make_error(fn_name, fn_def, mods, err, pos)
make_error(fn_name, fn_def, global, err, pos)
}
// System errors are passed straight-through
mut err if err.is_system_exception() => {
@ -146,7 +146,7 @@ impl Engine {
Err(err.into())
}
// Other errors are wrapped in `ErrorInFunctionCall`
_ => make_error(fn_def.name.to_string(), fn_def, mods, err, pos),
_ => make_error(fn_def.name.to_string(), fn_def, global, err, pos),
});
// Remove all local variables
@ -157,7 +157,7 @@ impl Engine {
scope.remove_range(orig_scope_len, args.len())
}
mods.truncate(orig_mods_len);
global.truncate_modules(orig_mods_len);
state.rewind_fn_resolution_caches(orig_fn_resolution_caches_len);
result
@ -167,7 +167,7 @@ impl Engine {
#[must_use]
pub(crate) fn has_script_fn(
&self,
mods: Option<&Imports>,
global: Option<&GlobalRuntimeState>,
state: &mut EvalState,
lib: &[&Module],
hash_script: u64,
@ -183,7 +183,7 @@ impl Engine {
// Then check the global namespace and packages
|| self.global_modules.iter().any(|m| m.contains_fn(hash_script))
// Then check imported modules
|| mods.map_or(false, |m| m.contains_fn(hash_script))
|| global.map_or(false, |m| m.contains_fn(hash_script))
// Then check sub-modules
|| self.global_sub_modules.values().any(|m| m.contains_qualified_fn(hash_script));

View File

@ -241,7 +241,7 @@ pub use ast::{
pub use ast::FloatWrapper;
#[cfg(feature = "internals")]
pub use engine::{EvalState, FnResolutionCache, FnResolutionCacheEntry, Imports};
pub use engine::{EvalState, FnResolutionCache, FnResolutionCacheEntry, GlobalRuntimeState};
#[cfg(feature = "internals")]
pub use module::Namespace;

View File

@ -1549,11 +1549,11 @@ impl Module {
engine: &crate::Engine,
) -> RhaiResultOf<Self> {
let mut scope = scope;
let mut mods = crate::engine::Imports::new();
let orig_mods_len = mods.len();
let mut global = crate::engine::GlobalRuntimeState::new();
let orig_mods_len = global.num_imported_modules();
// Run the script
engine.eval_ast_with_scope_raw(&mut scope, &mut mods, &ast, 0)?;
engine.eval_ast_with_scope_raw(&mut scope, &mut global, &ast, 0)?;
// Create new module
let mut module =
@ -1580,12 +1580,15 @@ impl Module {
});
// Extra modules left in the scope become sub-modules
let mut func_mods = crate::engine::Imports::new();
let mut func_global = crate::engine::GlobalRuntimeState::new();
mods.into_iter().skip(orig_mods_len).for_each(|(alias, m)| {
func_mods.push(alias.clone(), m.clone());
module.set_sub_module(alias, m);
});
global
.into_iter()
.skip(orig_mods_len)
.for_each(|(alias, m)| {
func_global.push_module(alias.clone(), m.clone());
module.set_sub_module(alias, m);
});
// Non-private functions defined become module functions
#[cfg(not(feature = "no_function"))]
@ -1606,7 +1609,7 @@ impl Module {
.as_ref()
.clone();
func.lib = Some(ast.shared_lib().clone());
func.mods = func_mods.clone();
func.global = func_global.clone();
module.set_script_fn(func);
});
}
@ -1790,13 +1793,14 @@ impl Module {
}
}
/// _(internals)_ A chain of [module][Module] names to namespace-qualify a variable or function call.
/// Exported under the `internals` feature only.
/// _(internals)_ A chain of [module][Module] names to namespace-qualify a variable or function
/// call. Exported under the `internals` feature only.
///
/// A [`u64`] offset to the current [`Scope`][crate::Scope] is cached for quick search purposes.
/// A [`u64`] offset to the current [stack of imported modules][crate::GlobalRuntimeState] is
/// cached for quick search purposes.
///
/// A [`StaticVec`] is used because most namespace-qualified access contains only one level,
/// and it is wasteful to always allocate a [`Vec`] with one element.
/// A [`StaticVec`] is used because the vast majority of namespace-qualified access contains only
/// one level, and it is wasteful to always allocate a [`Vec`] with one element.
#[derive(Clone, Eq, PartialEq, Default, Hash)]
pub struct Namespace {
index: Option<NonZeroUsize>,

View File

@ -3,7 +3,8 @@
use crate::ast::{Expr, OpAssignment, Stmt, AST_OPTION_FLAGS::*};
use crate::engine::{
EvalState, Imports, KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, KEYWORD_PRINT, KEYWORD_TYPE_OF,
EvalState, GlobalRuntimeState, KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, KEYWORD_PRINT,
KEYWORD_TYPE_OF,
};
use crate::func::builtin::get_builtin_binary_op_fn;
use crate::func::hashing::get_hasher;
@ -141,7 +142,7 @@ impl<'a> OptimizerState<'a> {
self.engine
.call_native_fn(
&mut Imports::new(),
&mut GlobalRuntimeState::new(),
&mut EvalState::new(),
lib,
&fn_name,
@ -1154,7 +1155,7 @@ pub fn optimize_into_ast(
params: fn_def.params.clone(),
lib: None,
#[cfg(not(feature = "no_module"))]
mods: Imports::new(),
global: GlobalRuntimeState::new(),
#[cfg(not(feature = "no_function"))]
#[cfg(feature = "metadata")]
comments: None,

View File

@ -3129,7 +3129,7 @@ fn parse_fn(
body,
lib: None,
#[cfg(not(feature = "no_module"))]
mods: crate::engine::Imports::new(),
global: crate::engine::GlobalRuntimeState::new(),
#[cfg(not(feature = "no_function"))]
#[cfg(feature = "metadata")]
comments: if comments.is_empty() {
@ -3280,7 +3280,7 @@ fn parse_anon_fn(
body: body.into(),
lib: None,
#[cfg(not(feature = "no_module"))]
mods: crate::engine::Imports::new(),
global: crate::engine::GlobalRuntimeState::new(),
#[cfg(not(feature = "no_function"))]
#[cfg(feature = "metadata")]
comments: None,