rhai/src/eval/global_state.rs

368 lines
12 KiB
Rust
Raw Normal View History

2022-01-07 04:43:47 +01:00
//! Global runtime state.
2022-05-01 18:03:45 +02:00
use crate::{Dynamic, Engine, Identifier};
2022-01-07 04:43:47 +01:00
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
2022-01-29 04:09:43 +01:00
use std::{fmt, marker::PhantomData};
2022-01-07 04:43:47 +01:00
/// Collection of globally-defined constants.
#[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_function"))]
pub type GlobalConstants =
2022-05-01 18:03:45 +02:00
crate::Shared<crate::Locked<std::collections::BTreeMap<Identifier, Dynamic>>>;
2022-01-29 04:09:43 +01:00
/// _(internals)_ Global runtime states.
2022-01-07 04:43:47 +01:00
/// Exported under the `internals` feature only.
//
// # Implementation Notes
//
2022-01-29 04:09:43 +01:00
// This implementation for imported [modules][crate::Module] splits the module names from the shared
2022-02-24 03:36:20 +01:00
// modules to improve data locality.
//
// Most usage will be looking up a particular key from the list and then getting the module that
// corresponds to that key.
2022-01-07 04:43:47 +01:00
#[derive(Clone)]
pub struct GlobalRuntimeState<'a> {
2022-01-07 04:43:47 +01:00
/// Stack of module names.
2022-01-29 04:09:43 +01:00
#[cfg(not(feature = "no_module"))]
keys: crate::StaticVec<Identifier>,
/// Stack of imported [modules][crate::Module].
#[cfg(not(feature = "no_module"))]
modules: crate::StaticVec<crate::Shared<crate::Module>>,
2022-01-07 04:43:47 +01:00
/// Source of the current context.
2022-04-16 10:36:53 +02:00
///
2022-01-07 04:43:47 +01:00
/// No source if the string is empty.
pub source: Identifier,
/// Number of operations performed.
pub num_operations: u64,
/// Number of modules loaded.
pub num_modules_loaded: usize,
2022-04-16 10:36:53 +02:00
/// Level of the current scope.
///
/// The global (root) level is zero, a new block (or function call) is one level higher, and so on.
pub scope_level: usize,
/// Force a [`Scope`][crate::Scope] search by name.
///
/// Normally, access to variables are parsed with a relative offset into the
/// [`Scope`][crate::Scope] to avoid a lookup.
///
/// In some situation, e.g. after running an `eval` statement, or after a custom syntax
/// statement, subsequent offsets may become mis-aligned.
///
/// When that happens, this flag is turned on.
pub always_search_scope: bool,
2022-01-07 04:43:47 +01:00
/// Function call hashes to index getters and setters.
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
fn_hash_indexing: (u64, u64),
2022-04-16 10:36:53 +02:00
/// Embedded [module][crate::Module] resolver.
2022-01-07 04:43:47 +01:00
#[cfg(not(feature = "no_module"))]
2022-01-29 04:09:43 +01:00
pub embedded_module_resolver:
Option<crate::Shared<crate::module::resolvers::StaticModuleResolver>>,
2022-01-07 04:43:47 +01:00
/// Cache of globally-defined constants.
2022-01-28 15:07:49 +01:00
///
/// Interior mutability is needed because it is shared in order to aid in cloning.
2022-01-07 04:43:47 +01:00
#[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_function"))]
2022-04-16 17:32:14 +02:00
pub constants: Option<GlobalConstants>,
2022-05-01 18:03:45 +02:00
/// Custom state that can be used by the external host.
pub tag: Dynamic,
2022-01-24 10:04:40 +01:00
/// Debugging interface.
#[cfg(feature = "debugging")]
pub debugger: super::Debugger,
/// Take care of the lifetime parameter.
dummy: PhantomData<&'a ()>,
2022-01-07 04:43:47 +01:00
}
impl GlobalRuntimeState<'_> {
2022-01-28 11:59:18 +01:00
/// Create a new [`GlobalRuntimeState`] based on an [`Engine`].
2022-01-07 04:43:47 +01:00
#[inline(always)]
#[must_use]
2022-01-28 11:59:18 +01:00
pub fn new(engine: &Engine) -> Self {
2022-01-07 04:43:47 +01:00
Self {
2022-01-29 04:09:43 +01:00
#[cfg(not(feature = "no_module"))]
keys: crate::StaticVec::new_const(),
#[cfg(not(feature = "no_module"))]
modules: crate::StaticVec::new_const(),
2022-01-07 04:43:47 +01:00
source: Identifier::new_const(),
num_operations: 0,
num_modules_loaded: 0,
2022-04-16 10:36:53 +02:00
scope_level: 0,
always_search_scope: false,
2022-01-07 04:43:47 +01:00
#[cfg(not(feature = "no_module"))]
embedded_module_resolver: None,
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
fn_hash_indexing: (0, 0),
#[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_function"))]
2022-01-28 15:07:49 +01:00
constants: None,
2022-05-03 15:55:01 +02:00
tag: engine.default_tag().clone(),
2022-05-03 15:55:01 +02:00
#[cfg(feature = "debugging")]
debugger: crate::eval::Debugger::new(
if engine.debugger.is_some() {
crate::eval::DebuggerStatus::Init
} else {
crate::eval::DebuggerStatus::CONTINUE
},
if let Some((ref init, ..)) = engine.debugger {
init()
} else {
Dynamic::UNIT
},
),
2022-05-03 15:55:01 +02:00
dummy: PhantomData::default(),
2022-01-07 04:43:47 +01:00
}
}
2022-01-29 04:09:43 +01:00
/// Get the length of the stack of globally-imported [modules][crate::Module].
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
2022-01-07 04:43:47 +01:00
#[inline(always)]
#[must_use]
pub fn num_imports(&self) -> usize {
2022-01-07 04:43:47 +01:00
self.keys.len()
}
2022-04-16 10:36:53 +02:00
/// Get the globally-imported [module][crate::Module] at a particular index.
2022-01-29 04:09:43 +01:00
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
2022-01-07 04:43:47 +01:00
#[inline(always)]
#[must_use]
2022-01-29 04:09:43 +01:00
pub fn get_shared_import(&self, index: usize) -> Option<crate::Shared<crate::Module>> {
2022-01-07 04:43:47 +01:00
self.modules.get(index).cloned()
}
2022-04-16 10:36:53 +02:00
/// Get a mutable reference to the globally-imported [module][crate::Module] at a
2022-02-24 03:36:20 +01:00
/// particular index.
2022-01-29 04:09:43 +01:00
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
2022-01-07 04:43:47 +01:00
#[allow(dead_code)]
#[inline(always)]
#[must_use]
2022-01-29 04:09:43 +01:00
pub(crate) fn get_shared_import_mut(
&mut self,
index: usize,
) -> Option<&mut crate::Shared<crate::Module>> {
2022-01-07 04:43:47 +01:00
self.modules.get_mut(index)
}
2022-04-16 10:36:53 +02:00
/// Get the index of a globally-imported [module][crate::Module] by name.
2022-01-29 04:09:43 +01:00
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
2022-01-07 04:43:47 +01:00
#[inline]
#[must_use]
pub fn find_import(&self, name: &str) -> Option<usize> {
2022-01-07 04:43:47 +01:00
let len = self.keys.len();
self.keys.iter().rev().enumerate().find_map(|(i, key)| {
if key == name {
Some(len - 1 - i)
} else {
None
}
})
}
2022-04-16 10:36:53 +02:00
/// Push an imported [module][crate::Module] onto the stack.
2022-01-29 04:09:43 +01:00
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
2022-01-07 04:43:47 +01:00
#[inline(always)]
2022-01-29 04:09:43 +01:00
pub fn push_import(
&mut self,
name: impl Into<Identifier>,
module: impl Into<crate::Shared<crate::Module>>,
) {
2022-01-07 04:43:47 +01:00
self.keys.push(name.into());
self.modules.push(module.into());
}
2022-01-29 04:09:43 +01:00
/// Truncate the stack of globally-imported [modules][crate::Module] to a particular length.
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
2022-01-07 04:43:47 +01:00
#[inline(always)]
pub fn truncate_imports(&mut self, size: usize) {
2022-01-07 04:43:47 +01:00
self.keys.truncate(size);
self.modules.truncate(size);
}
2022-01-29 04:09:43 +01:00
/// Get an iterator to the stack of globally-imported [modules][crate::Module] in reverse order.
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
2022-01-07 04:43:47 +01:00
#[allow(dead_code)]
#[inline]
2022-01-29 04:09:43 +01:00
pub fn iter_imports(&self) -> impl Iterator<Item = (&str, &crate::Module)> {
2022-01-07 04:43:47 +01:00
self.keys
.iter()
.rev()
.zip(self.modules.iter().rev())
.map(|(name, module)| (name.as_str(), module.as_ref()))
}
2022-01-29 04:09:43 +01:00
/// Get an iterator to the stack of globally-imported [modules][crate::Module] in reverse order.
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
2022-01-07 04:43:47 +01:00
#[allow(dead_code)]
#[inline]
2022-01-29 04:09:43 +01:00
pub(crate) fn iter_imports_raw(
&self,
) -> impl Iterator<Item = (&Identifier, &crate::Shared<crate::Module>)> {
2022-01-07 04:43:47 +01:00
self.keys.iter().rev().zip(self.modules.iter().rev())
}
2022-01-29 04:09:43 +01:00
/// Get an iterator to the stack of globally-imported [modules][crate::Module] in forward order.
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
2022-01-07 04:43:47 +01:00
#[allow(dead_code)]
#[inline]
2022-01-29 04:09:43 +01:00
pub fn scan_imports_raw(
&self,
) -> impl Iterator<Item = (&Identifier, &crate::Shared<crate::Module>)> {
2022-01-07 04:43:47 +01:00
self.keys.iter().zip(self.modules.iter())
}
2022-02-24 03:36:20 +01:00
/// Does the specified function hash key exist in the stack of globally-imported
/// [modules][crate::Module]?
2022-01-29 04:09:43 +01:00
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
2022-01-07 04:43:47 +01:00
#[allow(dead_code)]
#[inline]
#[must_use]
pub fn contains_qualified_fn(&self, hash: u64) -> bool {
2022-01-07 04:43:47 +01:00
self.modules.iter().any(|m| m.contains_qualified_fn(hash))
}
2022-02-24 03:36:20 +01:00
/// Get the specified function via its hash key from the stack of globally-imported
/// [modules][crate::Module].
2022-01-29 04:09:43 +01:00
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
2022-01-07 04:43:47 +01:00
#[inline]
#[must_use]
2022-01-29 04:09:43 +01:00
pub fn get_qualified_fn(
&self,
hash: u64,
) -> Option<(&crate::func::CallableFunction, Option<&str>)> {
2022-01-07 04:43:47 +01:00
self.modules
.iter()
.rev()
.find_map(|m| m.get_qualified_fn(hash).map(|f| (f, m.id())))
}
/// Does the specified [`TypeId`][std::any::TypeId] iterator exist in the stack of
2022-01-29 04:09:43 +01:00
/// globally-imported [modules][crate::Module]?
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
2022-01-07 04:43:47 +01:00
#[allow(dead_code)]
#[inline]
#[must_use]
2022-01-29 04:09:43 +01:00
pub fn contains_iter(&self, id: std::any::TypeId) -> bool {
2022-01-07 04:43:47 +01:00
self.modules.iter().any(|m| m.contains_qualified_iter(id))
}
/// Get the specified [`TypeId`][std::any::TypeId] iterator from the stack of globally-imported
2022-01-29 04:09:43 +01:00
/// [modules][crate::Module].
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
2022-01-07 04:43:47 +01:00
#[inline]
#[must_use]
2022-01-29 04:09:43 +01:00
pub fn get_iter(&self, id: std::any::TypeId) -> Option<&crate::func::IteratorFn> {
2022-01-07 04:43:47 +01:00
self.modules
.iter()
.rev()
.find_map(|m| m.get_qualified_iter(id))
}
2022-01-24 10:04:40 +01:00
/// Get the current source.
#[inline]
#[must_use]
pub fn source(&self) -> Option<&str> {
2022-03-20 14:58:43 +01:00
if self.source.is_empty() {
None
} else {
Some(self.source.as_str())
2022-01-24 10:04:40 +01:00
}
}
2022-01-07 04:43:47 +01:00
/// Get the pre-calculated index getter hash.
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
#[must_use]
pub(crate) fn hash_idx_get(&mut self) -> u64 {
if self.fn_hash_indexing != (0, 0) {
self.fn_hash_indexing.0
} else {
2022-01-07 05:19:01 +01:00
let n1 = crate::calc_fn_hash(crate::engine::FN_IDX_GET, 2);
let n2 = crate::calc_fn_hash(crate::engine::FN_IDX_SET, 3);
2022-01-07 04:43:47 +01:00
self.fn_hash_indexing = (n1, n2);
n1
}
}
/// Get the pre-calculated index setter hash.
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
#[must_use]
pub(crate) fn hash_idx_set(&mut self) -> u64 {
if self.fn_hash_indexing != (0, 0) {
self.fn_hash_indexing.1
} else {
2022-01-07 05:19:01 +01:00
let n1 = crate::calc_fn_hash(crate::engine::FN_IDX_GET, 2);
let n2 = crate::calc_fn_hash(crate::engine::FN_IDX_SET, 3);
2022-01-07 04:43:47 +01:00
self.fn_hash_indexing = (n1, n2);
n2
}
}
}
2022-01-29 04:09:43 +01:00
#[cfg(not(feature = "no_module"))]
impl IntoIterator for GlobalRuntimeState<'_> {
2022-01-29 04:09:43 +01:00
type Item = (Identifier, crate::Shared<crate::Module>);
type IntoIter = std::iter::Zip<
std::iter::Rev<smallvec::IntoIter<[Identifier; 3]>>,
std::iter::Rev<smallvec::IntoIter<[crate::Shared<crate::Module>; 3]>>,
>;
2022-01-07 04:43:47 +01:00
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.keys
.into_iter()
.rev()
.zip(self.modules.into_iter().rev())
}
}
2022-01-29 04:09:43 +01:00
#[cfg(not(feature = "no_module"))]
impl<K: Into<Identifier>, M: Into<crate::Shared<crate::Module>>> Extend<(K, M)>
for GlobalRuntimeState<'_>
{
2022-01-10 15:51:24 +01:00
#[inline]
2022-01-07 04:43:47 +01:00
fn extend<T: IntoIterator<Item = (K, M)>>(&mut self, iter: T) {
2022-01-28 11:59:18 +01:00
for (k, m) in iter {
2022-01-07 04:43:47 +01:00
self.keys.push(k.into());
self.modules.push(m.into());
2022-01-28 11:59:18 +01:00
}
2022-01-07 04:43:47 +01:00
}
}
impl fmt::Debug for GlobalRuntimeState<'_> {
2022-01-10 15:51:24 +01:00
#[inline]
2022-01-07 04:43:47 +01:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2022-01-10 06:43:30 +01:00
let mut f = f.debug_struct("GlobalRuntimeState");
2022-01-29 04:09:43 +01:00
#[cfg(not(feature = "no_module"))]
f.field("imports", &self.keys.iter().zip(self.modules.iter()));
f.field("source", &self.source)
.field("num_operations", &self.num_operations)
2022-01-10 06:43:30 +01:00
.field("num_modules_loaded", &self.num_modules_loaded);
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
f.field("fn_hash_indexing", &self.fn_hash_indexing);
#[cfg(not(feature = "no_module"))]
f.field("embedded_module_resolver", &self.embedded_module_resolver);
#[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_function"))]
f.field("constants", &self.constants);
f.finish()
2022-01-07 04:43:47 +01:00
}
}