Reduce feature gates on imports.
This commit is contained in:
parent
ef02150afd
commit
adb902326e
13
src/ast.rs
13
src/ast.rs
@ -12,14 +12,11 @@ use crate::INT;
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
use crate::FLOAT;
|
||||
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
use crate::engine::Imports;
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
use crate::{engine::TYPICAL_ARRAY_SIZE, Array};
|
||||
use crate::Array;
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
use crate::{engine::TYPICAL_MAP_SIZE, Map};
|
||||
use crate::Map;
|
||||
|
||||
use crate::stdlib::{
|
||||
borrow::Cow,
|
||||
@ -92,7 +89,7 @@ pub struct ScriptFnDef {
|
||||
pub lib: Option<Shared<Module>>,
|
||||
/// Encapsulated imported modules.
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
pub mods: Imports,
|
||||
pub mods: crate::engine::Imports,
|
||||
/// Function name.
|
||||
pub name: ImmutableString,
|
||||
/// Function access mode.
|
||||
@ -943,14 +940,14 @@ impl Expr {
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Self::Array(x, _) if self.is_constant() => {
|
||||
let mut arr = Array::with_capacity(max(TYPICAL_ARRAY_SIZE, x.len()));
|
||||
let mut arr = Array::with_capacity(max(crate::engine::TYPICAL_ARRAY_SIZE, x.len()));
|
||||
arr.extend(x.iter().map(|v| v.get_constant_value().unwrap()));
|
||||
Dynamic(Union::Array(Box::new(arr)))
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Self::Map(x, _) if self.is_constant() => {
|
||||
let mut map = Map::with_capacity(max(TYPICAL_MAP_SIZE, x.len()));
|
||||
let mut map = Map::with_capacity(max(crate::engine::TYPICAL_MAP_SIZE, x.len()));
|
||||
map.extend(
|
||||
x.iter()
|
||||
.map(|(k, v)| (k.name.clone(), v.get_constant_value().unwrap())),
|
||||
|
@ -5,17 +5,14 @@ use crate::r#unsafe::{unsafe_cast_box, unsafe_try_cast};
|
||||
use crate::utils::ImmutableString;
|
||||
use crate::INT;
|
||||
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
use crate::fn_native::{shared_try_take, Locked, Shared};
|
||||
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
use crate::FLOAT;
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
use crate::engine::Array;
|
||||
use crate::Array;
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
use crate::{engine::Map, StaticVec};
|
||||
use crate::Map;
|
||||
|
||||
use crate::stdlib::{
|
||||
any::{type_name, Any, TypeId},
|
||||
@ -27,20 +24,6 @@ use crate::stdlib::{
|
||||
string::{String, ToString},
|
||||
};
|
||||
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(not(feature = "sync"))]
|
||||
use crate::stdlib::cell::{Ref, RefMut};
|
||||
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(feature = "sync")]
|
||||
use crate::stdlib::sync::{RwLockReadGuard, RwLockWriteGuard};
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
use crate::stdlib::collections::HashMap;
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
use crate::stdlib::vec::Vec;
|
||||
|
||||
#[cfg(not(feature = "no_std"))]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use crate::stdlib::time::Instant;
|
||||
@ -165,7 +148,7 @@ pub enum Union {
|
||||
Variant(Box<Box<dyn Variant>>),
|
||||
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
Shared(Shared<Locked<Dynamic>>),
|
||||
Shared(crate::Shared<crate::Locked<Dynamic>>),
|
||||
}
|
||||
|
||||
/// Underlying `Variant` read guard for `Dynamic`.
|
||||
@ -184,11 +167,11 @@ enum DynamicReadLockInner<'d, T: Variant + Clone> {
|
||||
/// A read guard to a shared `RefCell`.
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(not(feature = "sync"))]
|
||||
Guard(Ref<'d, Dynamic>),
|
||||
Guard(crate::stdlib::cell::Ref<'d, Dynamic>),
|
||||
/// A read guard to a shared `RwLock`.
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(feature = "sync")]
|
||||
Guard(RwLockReadGuard<'d, Dynamic>),
|
||||
Guard(crate::stdlib::sync::RwLockReadGuard<'d, Dynamic>),
|
||||
}
|
||||
|
||||
impl<'d, T: Variant + Clone> Deref for DynamicReadLock<'d, T> {
|
||||
@ -221,11 +204,11 @@ enum DynamicWriteLockInner<'d, T: Variant + Clone> {
|
||||
/// A write guard to a shared `RefCell`.
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(not(feature = "sync"))]
|
||||
Guard(RefMut<'d, Dynamic>),
|
||||
Guard(crate::stdlib::cell::RefMut<'d, Dynamic>),
|
||||
/// A write guard to a shared `RwLock`.
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(feature = "sync")]
|
||||
Guard(RwLockWriteGuard<'d, Dynamic>),
|
||||
Guard(crate::stdlib::sync::RwLockWriteGuard<'d, Dynamic>),
|
||||
}
|
||||
|
||||
impl<'d, T: Variant + Clone> Deref for DynamicWriteLock<'d, T> {
|
||||
@ -375,7 +358,7 @@ impl Hash for Dynamic {
|
||||
Union::Array(a) => (**a).hash(state),
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Union::Map(m) => {
|
||||
let mut buf: StaticVec<_> = m.iter().collect();
|
||||
let mut buf: crate::StaticVec<_> = m.iter().collect();
|
||||
buf.sort_by(|(a, _), (b, _)| a.cmp(b));
|
||||
|
||||
buf.into_iter().for_each(|(key, value)| {
|
||||
@ -694,7 +677,7 @@ impl Dynamic {
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
return match self.0 {
|
||||
Union::Shared(..) => self,
|
||||
_ => Self(Union::Shared(Locked::new(self).into())),
|
||||
_ => Self(Union::Shared(crate::Locked::new(self).into())),
|
||||
};
|
||||
|
||||
#[cfg(feature = "no_closure")]
|
||||
@ -902,7 +885,7 @@ impl Dynamic {
|
||||
pub fn flatten(self) -> Self {
|
||||
match self.0 {
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
Union::Shared(cell) => shared_try_take(cell).map_or_else(
|
||||
Union::Shared(cell) => crate::fn_native::shared_try_take(cell).map_or_else(
|
||||
|cell| {
|
||||
#[cfg(not(feature = "sync"))]
|
||||
return cell.borrow().clone();
|
||||
@ -1312,9 +1295,9 @@ impl<S: Into<ImmutableString>> From<S> for Dynamic {
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
impl<T: Variant + Clone> From<Vec<T>> for Dynamic {
|
||||
impl<T: Variant + Clone> From<crate::stdlib::vec::Vec<T>> for Dynamic {
|
||||
#[inline(always)]
|
||||
fn from(value: Vec<T>) -> Self {
|
||||
fn from(value: crate::stdlib::vec::Vec<T>) -> Self {
|
||||
Self(Union::Array(Box::new(
|
||||
value.into_iter().map(Dynamic::from).collect(),
|
||||
)))
|
||||
@ -1330,9 +1313,11 @@ impl<T: Variant + Clone> From<&[T]> for Dynamic {
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
impl<K: Into<ImmutableString>, T: Variant + Clone> From<HashMap<K, T>> for Dynamic {
|
||||
impl<K: Into<ImmutableString>, T: Variant + Clone> From<crate::stdlib::collections::HashMap<K, T>>
|
||||
for Dynamic
|
||||
{
|
||||
#[inline(always)]
|
||||
fn from(value: HashMap<K, T>) -> Self {
|
||||
fn from(value: crate::stdlib::collections::HashMap<K, T>) -> Self {
|
||||
Self(Union::Map(Box::new(
|
||||
value
|
||||
.into_iter()
|
||||
|
@ -1,6 +1,6 @@
|
||||
//! Main module defining the script evaluation `Engine`.
|
||||
|
||||
use crate::ast::{BinaryExpr, Expr, FnCallExpr, Ident, IdentX, ReturnType, Stmt};
|
||||
use crate::ast::{Expr, FnCallExpr, Ident, IdentX, ReturnType, Stmt};
|
||||
use crate::dynamic::{map_std_type_name, Dynamic, Union, Variant};
|
||||
use crate::fn_call::run_builtin_op_assignment;
|
||||
use crate::fn_native::{CallableFunction, Callback, FnPtr, IteratorFn, OnVarCallback, Shared};
|
||||
@ -12,29 +12,11 @@ use crate::result::EvalAltResult;
|
||||
use crate::scope::{EntryType as ScopeEntryType, Scope};
|
||||
use crate::syntax::CustomSyntax;
|
||||
use crate::token::{Position, NO_POS};
|
||||
use crate::utils::get_hasher;
|
||||
use crate::utils::{get_hasher, ImmutableString};
|
||||
use crate::{calc_native_fn_hash, StaticVec};
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
use crate::INT;
|
||||
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
use crate::{fn_native::shared_take_or_clone, module::ModuleResolver};
|
||||
|
||||
#[cfg(not(feature = "no_std"))]
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use crate::module::resolvers;
|
||||
|
||||
#[cfg(any(not(feature = "no_object"), not(feature = "no_module")))]
|
||||
use crate::utils::ImmutableString;
|
||||
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
use crate::dynamic::DynamicWriteLock;
|
||||
|
||||
use crate::stdlib::{
|
||||
any::type_name,
|
||||
any::{type_name, TypeId},
|
||||
borrow::Cow,
|
||||
boxed::Box,
|
||||
collections::{HashMap, HashSet},
|
||||
@ -46,12 +28,6 @@ use crate::stdlib::{
|
||||
string::{String, ToString},
|
||||
};
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
use crate::stdlib::any::TypeId;
|
||||
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
use crate::stdlib::mem;
|
||||
|
||||
/// Variable-sized array of `Dynamic` values.
|
||||
///
|
||||
/// Not available under the `no_index` feature.
|
||||
@ -61,9 +37,6 @@ pub type Array = crate::stdlib::vec::Vec<Dynamic>;
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
pub const TYPICAL_ARRAY_SIZE: usize = 8; // Small arrays are typical
|
||||
|
||||
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
||||
use crate::stdlib::cmp::max;
|
||||
|
||||
/// Hash map of `Dynamic` values with `ImmutableString` keys.
|
||||
///
|
||||
/// Not available under the `no_object` feature.
|
||||
@ -228,6 +201,7 @@ pub const FN_IDX_GET: &str = "index$get$";
|
||||
pub const FN_IDX_SET: &str = "index$set$";
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
pub const FN_ANONYMOUS: &str = "anon$";
|
||||
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
||||
pub const OP_EQUALS: &str = "==";
|
||||
pub const MARKER_EXPR: &str = "$expr$";
|
||||
pub const MARKER_BLOCK: &str = "$block$";
|
||||
@ -301,7 +275,7 @@ pub enum Target<'a> {
|
||||
/// It holds both the access guard and the original shared value.
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
LockGuard((DynamicWriteLock<'a, Dynamic>, Dynamic)),
|
||||
LockGuard((crate::dynamic::DynamicWriteLock<'a, Dynamic>, Dynamic)),
|
||||
/// The target is a temporary `Dynamic` value (i.e. the mutation can cause no side effects).
|
||||
Value(Dynamic),
|
||||
/// The target is a character inside a String.
|
||||
@ -643,7 +617,7 @@ pub struct Engine {
|
||||
|
||||
/// A module resolution service.
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
pub(crate) module_resolver: Option<Box<dyn ModuleResolver>>,
|
||||
pub(crate) module_resolver: Option<Box<dyn crate::ModuleResolver>>,
|
||||
|
||||
/// A hashmap mapping type names to pretty-print names.
|
||||
pub(crate) type_names: HashMap<String, String>,
|
||||
@ -760,7 +734,7 @@ impl Engine {
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
#[cfg(not(feature = "no_std"))]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
module_resolver: Some(Box::new(resolvers::FileModuleResolver::new())),
|
||||
module_resolver: Some(Box::new(crate::module::resolvers::FileModuleResolver::new())),
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
#[cfg(any(feature = "no_std", target_arch = "wasm32",))]
|
||||
module_resolver: None,
|
||||
@ -1291,7 +1265,7 @@ impl Engine {
|
||||
level: usize,
|
||||
new_val: Option<(Dynamic, Position)>,
|
||||
) -> Result<Dynamic, Box<EvalAltResult>> {
|
||||
let (BinaryExpr { lhs, rhs }, chain_type, op_pos) = match expr {
|
||||
let (crate::ast::BinaryExpr { lhs, rhs }, chain_type, op_pos) = match expr {
|
||||
Expr::Index(x, pos) => (x.as_ref(), ChainType::Index, *pos),
|
||||
Expr::Dot(x, pos) => (x.as_ref(), ChainType::Dot, *pos),
|
||||
_ => unreachable!(),
|
||||
@ -1393,7 +1367,7 @@ impl Engine {
|
||||
Expr::FnCall(_, _) => unreachable!(),
|
||||
Expr::Property(_) => idx_values.push(IndexChainValue::None),
|
||||
Expr::Index(x, _) | Expr::Dot(x, _) => {
|
||||
let BinaryExpr { lhs, rhs, .. } = x.as_ref();
|
||||
let crate::ast::BinaryExpr { lhs, rhs, .. } = x.as_ref();
|
||||
|
||||
// Evaluate in left-to-right order
|
||||
let lhs_val = match lhs {
|
||||
@ -1458,7 +1432,7 @@ impl Engine {
|
||||
// val_array[idx]
|
||||
let index = idx
|
||||
.as_int()
|
||||
.map_err(|err| self.make_type_mismatch_err::<INT>(err, idx_pos))?;
|
||||
.map_err(|err| self.make_type_mismatch_err::<crate::INT>(err, idx_pos))?;
|
||||
|
||||
let arr_len = arr.len();
|
||||
|
||||
@ -1499,7 +1473,7 @@ impl Engine {
|
||||
let chars_len = s.chars().count();
|
||||
let index = idx
|
||||
.as_int()
|
||||
.map_err(|err| self.make_type_mismatch_err::<INT>(err, idx_pos))?;
|
||||
.map_err(|err| self.make_type_mismatch_err::<crate::INT>(err, idx_pos))?;
|
||||
|
||||
if index >= 0 {
|
||||
let offset = index as usize;
|
||||
@ -1772,7 +1746,8 @@ impl Engine {
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Expr::Array(x, _) => {
|
||||
let mut arr = Array::with_capacity(max(TYPICAL_ARRAY_SIZE, x.len()));
|
||||
let mut arr =
|
||||
Array::with_capacity(crate::stdlib::cmp::max(TYPICAL_ARRAY_SIZE, x.len()));
|
||||
for item in x.as_ref() {
|
||||
arr.push(self.eval_expr(scope, mods, state, lib, this_ptr, item, level)?);
|
||||
}
|
||||
@ -1781,7 +1756,8 @@ impl Engine {
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Expr::Map(x, _) => {
|
||||
let mut map = Map::with_capacity(max(TYPICAL_MAP_SIZE, x.len()));
|
||||
let mut map =
|
||||
Map::with_capacity(crate::stdlib::cmp::max(TYPICAL_MAP_SIZE, x.len()));
|
||||
for (IdentX { name: key, .. }, expr) in x.as_ref() {
|
||||
map.insert(
|
||||
key.clone(),
|
||||
@ -2372,7 +2348,7 @@ impl Engine {
|
||||
if let Some(name_def) = alias {
|
||||
if !module.is_indexed() {
|
||||
// Index the module (making a clone copy if necessary) if it is not indexed
|
||||
let mut module = shared_take_or_clone(module);
|
||||
let mut module = crate::fn_native::shared_take_or_clone(module);
|
||||
module.build_index();
|
||||
mods.push(name_def.name.clone(), module);
|
||||
} else {
|
||||
@ -2419,7 +2395,7 @@ impl Engine {
|
||||
|
||||
if !val.is_shared() {
|
||||
// Replace the variable with a shared value.
|
||||
*val = mem::take(val).into_shared();
|
||||
*val = crate::stdlib::mem::take(val).into_shared();
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
|
@ -12,32 +12,10 @@ use crate::token::NO_POS;
|
||||
use crate::utils::get_hasher;
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
use crate::{
|
||||
engine::{Array, FN_IDX_GET, FN_IDX_SET},
|
||||
utils::ImmutableString,
|
||||
};
|
||||
use crate::Array;
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
use crate::{
|
||||
engine::{make_getter, make_setter, Map},
|
||||
parse_error::ParseErrorType,
|
||||
token::{Position, Token},
|
||||
};
|
||||
|
||||
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
||||
use crate::fn_register::{RegisterFn, RegisterResultFn};
|
||||
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
use crate::{fn_args::FuncArgs, fn_call::ensure_no_data_race, StaticVec};
|
||||
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
use crate::fn_native::{shared_take_or_clone, Shared};
|
||||
|
||||
#[cfg(any(not(feature = "no_function"), not(feature = "no_module")))]
|
||||
use crate::module::Module;
|
||||
|
||||
#[cfg(not(feature = "no_optimize"))]
|
||||
use crate::optimize::optimize_into_ast;
|
||||
use crate::Map;
|
||||
|
||||
use crate::stdlib::{
|
||||
any::{type_name, TypeId},
|
||||
@ -46,9 +24,6 @@ use crate::stdlib::{
|
||||
string::String,
|
||||
};
|
||||
|
||||
#[cfg(not(feature = "no_optimize"))]
|
||||
use crate::stdlib::mem;
|
||||
|
||||
#[cfg(not(feature = "no_std"))]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use crate::stdlib::{fs::File, io::prelude::*, path::PathBuf};
|
||||
@ -238,7 +213,7 @@ impl Engine {
|
||||
T: Variant + Clone,
|
||||
U: Variant + Clone,
|
||||
{
|
||||
self.register_fn(&make_getter(name), callback)
|
||||
crate::RegisterFn::register_fn(self, &crate::engine::make_getter(name), callback)
|
||||
}
|
||||
/// Register a getter function for a member of a registered type with the `Engine`.
|
||||
/// Returns `Result<Dynamic, Box<EvalAltResult>>`.
|
||||
@ -285,7 +260,11 @@ impl Engine {
|
||||
name: &str,
|
||||
callback: impl Fn(&mut T) -> Result<Dynamic, Box<EvalAltResult>> + SendSync + 'static,
|
||||
) -> &mut Self {
|
||||
self.register_result_fn(&make_getter(name), callback)
|
||||
crate::RegisterResultFn::register_result_fn(
|
||||
self,
|
||||
&crate::engine::make_getter(name),
|
||||
callback,
|
||||
)
|
||||
}
|
||||
/// Register a setter function for a member of a registered type with the `Engine`.
|
||||
///
|
||||
@ -334,7 +313,7 @@ impl Engine {
|
||||
T: Variant + Clone,
|
||||
U: Variant + Clone,
|
||||
{
|
||||
self.register_fn(&make_setter(name), callback)
|
||||
crate::RegisterFn::register_fn(self, &crate::engine::make_setter(name), callback)
|
||||
}
|
||||
/// Register a setter function for a member of a registered type with the `Engine`.
|
||||
/// Returns `Result<(), Box<EvalAltResult>>`.
|
||||
@ -387,9 +366,11 @@ impl Engine {
|
||||
T: Variant + Clone,
|
||||
U: Variant + Clone,
|
||||
{
|
||||
self.register_result_fn(&make_setter(name), move |obj: &mut T, value: U| {
|
||||
callback(obj, value).map(Into::into)
|
||||
})
|
||||
crate::RegisterResultFn::register_result_fn(
|
||||
self,
|
||||
&crate::engine::make_setter(name),
|
||||
move |obj: &mut T, value: U| callback(obj, value).map(Into::into),
|
||||
)
|
||||
}
|
||||
/// Short-hand for registering both getter and setter functions
|
||||
/// of a registered type with the `Engine`.
|
||||
@ -504,12 +485,12 @@ impl Engine {
|
||||
}
|
||||
if TypeId::of::<T>() == TypeId::of::<String>()
|
||||
|| TypeId::of::<T>() == TypeId::of::<&str>()
|
||||
|| TypeId::of::<T>() == TypeId::of::<ImmutableString>()
|
||||
|| TypeId::of::<T>() == TypeId::of::<crate::ImmutableString>()
|
||||
{
|
||||
panic!("Cannot register indexer for strings.");
|
||||
}
|
||||
|
||||
self.register_fn(FN_IDX_GET, callback)
|
||||
crate::RegisterFn::register_fn(self, crate::engine::FN_IDX_GET, callback)
|
||||
}
|
||||
/// Register an index getter for a custom type with the `Engine`.
|
||||
/// Returns `Result<Dynamic, Box<EvalAltResult>>`.
|
||||
@ -574,12 +555,12 @@ impl Engine {
|
||||
}
|
||||
if TypeId::of::<T>() == TypeId::of::<String>()
|
||||
|| TypeId::of::<T>() == TypeId::of::<&str>()
|
||||
|| TypeId::of::<T>() == TypeId::of::<ImmutableString>()
|
||||
|| TypeId::of::<T>() == TypeId::of::<crate::ImmutableString>()
|
||||
{
|
||||
panic!("Cannot register indexer for strings.");
|
||||
}
|
||||
|
||||
self.register_result_fn(FN_IDX_GET, callback)
|
||||
crate::RegisterResultFn::register_result_fn(self, crate::engine::FN_IDX_GET, callback)
|
||||
}
|
||||
/// Register an index setter for a custom type with the `Engine`.
|
||||
///
|
||||
@ -642,12 +623,12 @@ impl Engine {
|
||||
}
|
||||
if TypeId::of::<T>() == TypeId::of::<String>()
|
||||
|| TypeId::of::<T>() == TypeId::of::<&str>()
|
||||
|| TypeId::of::<T>() == TypeId::of::<ImmutableString>()
|
||||
|| TypeId::of::<T>() == TypeId::of::<crate::ImmutableString>()
|
||||
{
|
||||
panic!("Cannot register indexer for strings.");
|
||||
}
|
||||
|
||||
self.register_fn(FN_IDX_SET, callback)
|
||||
crate::RegisterFn::register_fn(self, crate::engine::FN_IDX_SET, callback)
|
||||
}
|
||||
/// Register an index setter for a custom type with the `Engine`.
|
||||
/// Returns `Result<(), Box<EvalAltResult>>`.
|
||||
@ -714,14 +695,16 @@ impl Engine {
|
||||
}
|
||||
if TypeId::of::<T>() == TypeId::of::<String>()
|
||||
|| TypeId::of::<T>() == TypeId::of::<&str>()
|
||||
|| TypeId::of::<T>() == TypeId::of::<ImmutableString>()
|
||||
|| TypeId::of::<T>() == TypeId::of::<crate::ImmutableString>()
|
||||
{
|
||||
panic!("Cannot register indexer for strings.");
|
||||
}
|
||||
|
||||
self.register_result_fn(FN_IDX_SET, move |obj: &mut T, index: X, value: U| {
|
||||
callback(obj, index, value).map(Into::into)
|
||||
})
|
||||
crate::RegisterResultFn::register_result_fn(
|
||||
self,
|
||||
crate::engine::FN_IDX_SET,
|
||||
move |obj: &mut T, index: X, value: U| callback(obj, index, value).map(Into::into),
|
||||
)
|
||||
}
|
||||
/// Short-hand for register both index getter and setter functions for a custom type with the `Engine`.
|
||||
///
|
||||
@ -802,14 +785,14 @@ impl Engine {
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
pub fn register_module(
|
||||
&mut self,
|
||||
name: impl Into<ImmutableString>,
|
||||
module: impl Into<Shared<Module>>,
|
||||
name: impl Into<crate::ImmutableString>,
|
||||
module: impl Into<crate::Shared<crate::Module>>,
|
||||
) -> &mut Self {
|
||||
let module = module.into();
|
||||
|
||||
if !module.is_indexed() {
|
||||
// Index the module (making a clone copy if necessary) if it is not indexed
|
||||
let mut module = shared_take_or_clone(module);
|
||||
let mut module = crate::fn_native::shared_take_or_clone(module);
|
||||
module.build_index();
|
||||
self.global_sub_modules.push_fixed(name, module);
|
||||
} else {
|
||||
@ -1078,6 +1061,8 @@ impl Engine {
|
||||
/// ```
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
pub fn parse_json(&self, json: &str, has_null: bool) -> Result<Map, Box<EvalAltResult>> {
|
||||
use crate::token::{Position, Token};
|
||||
|
||||
let mut scope = Default::default();
|
||||
|
||||
// Trims the JSON string and add a '#' in front
|
||||
@ -1087,7 +1072,7 @@ impl Engine {
|
||||
} else if json_text.starts_with(Token::LeftBrace.syntax().as_ref()) {
|
||||
["#", json_text]
|
||||
} else {
|
||||
return Err(ParseErrorType::MissingToken(
|
||||
return Err(crate::ParseErrorType::MissingToken(
|
||||
Token::LeftBrace.syntax().into(),
|
||||
"to start a JSON object hash".into(),
|
||||
)
|
||||
@ -1535,7 +1520,7 @@ impl Engine {
|
||||
/// ```
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
#[inline]
|
||||
pub fn call_fn<A: FuncArgs, T: Variant + Clone>(
|
||||
pub fn call_fn<A: crate::fn_args::FuncArgs, T: Variant + Clone>(
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
ast: &AST,
|
||||
@ -1543,7 +1528,7 @@ impl Engine {
|
||||
args: A,
|
||||
) -> Result<T, Box<EvalAltResult>> {
|
||||
let mut arg_values = args.into_vec();
|
||||
let mut args: StaticVec<_> = arg_values.as_mut().iter_mut().collect();
|
||||
let mut args: crate::StaticVec<_> = arg_values.as_mut().iter_mut().collect();
|
||||
|
||||
let result =
|
||||
self.call_fn_dynamic_raw(scope, &[ast.lib()], name, &mut None, args.as_mut())?;
|
||||
@ -1613,12 +1598,12 @@ impl Engine {
|
||||
pub fn call_fn_dynamic(
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
lib: impl AsRef<Module>,
|
||||
lib: impl AsRef<crate::Module>,
|
||||
name: &str,
|
||||
mut this_ptr: Option<&mut Dynamic>,
|
||||
mut arg_values: impl AsMut<[Dynamic]>,
|
||||
) -> Result<Dynamic, Box<EvalAltResult>> {
|
||||
let mut args: StaticVec<_> = arg_values.as_mut().iter_mut().collect();
|
||||
let mut args: crate::StaticVec<_> = arg_values.as_mut().iter_mut().collect();
|
||||
|
||||
self.call_fn_dynamic_raw(scope, &[lib.as_ref()], name, &mut this_ptr, args.as_mut())
|
||||
}
|
||||
@ -1635,7 +1620,7 @@ impl Engine {
|
||||
pub(crate) fn call_fn_dynamic_raw(
|
||||
&self,
|
||||
scope: &mut Scope,
|
||||
lib: &[&Module],
|
||||
lib: &[&crate::Module],
|
||||
name: &str,
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
args: &mut FnCallArgs,
|
||||
@ -1650,7 +1635,7 @@ impl Engine {
|
||||
|
||||
// Check for data race.
|
||||
if cfg!(not(feature = "no_closure")) {
|
||||
ensure_no_data_race(name, args, false)?;
|
||||
crate::fn_call::ensure_no_data_race(name, args, false)?;
|
||||
}
|
||||
|
||||
self.call_script_fn(scope, &mut mods, &mut state, lib, this_ptr, fn_def, args, 0)
|
||||
@ -1685,8 +1670,8 @@ impl Engine {
|
||||
#[cfg(feature = "no_function")]
|
||||
let lib = Default::default();
|
||||
|
||||
let stmt = mem::take(ast.statements_mut());
|
||||
optimize_into_ast(self, scope, stmt, lib, optimization_level)
|
||||
let stmt = crate::stdlib::mem::take(ast.statements_mut());
|
||||
crate::optimize::optimize_into_ast(self, scope, stmt, lib, optimization_level)
|
||||
}
|
||||
/// Provide a callback that will be invoked before each variable access.
|
||||
///
|
||||
|
@ -4,12 +4,6 @@ use crate::engine::Engine;
|
||||
use crate::packages::PackageLibrary;
|
||||
use crate::token::{is_valid_identifier, Token};
|
||||
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
use crate::module::ModuleResolver;
|
||||
|
||||
#[cfg(not(feature = "no_optimize"))]
|
||||
use crate::optimize::OptimizationLevel;
|
||||
|
||||
use crate::stdlib::{format, string::String};
|
||||
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
@ -31,7 +25,10 @@ impl Engine {
|
||||
/// Not available under the `no_optimize` feature.
|
||||
#[cfg(not(feature = "no_optimize"))]
|
||||
#[inline(always)]
|
||||
pub fn set_optimization_level(&mut self, optimization_level: OptimizationLevel) -> &mut Self {
|
||||
pub fn set_optimization_level(
|
||||
&mut self,
|
||||
optimization_level: crate::OptimizationLevel,
|
||||
) -> &mut Self {
|
||||
self.optimization_level = optimization_level;
|
||||
self
|
||||
}
|
||||
@ -41,7 +38,7 @@ impl Engine {
|
||||
/// Not available under the `no_optimize` feature.
|
||||
#[cfg(not(feature = "no_optimize"))]
|
||||
#[inline(always)]
|
||||
pub fn optimization_level(&self) -> OptimizationLevel {
|
||||
pub fn optimization_level(&self) -> crate::OptimizationLevel {
|
||||
self.optimization_level
|
||||
}
|
||||
/// Set the maximum levels of function calls allowed for a script in order to avoid
|
||||
@ -177,9 +174,9 @@ impl Engine {
|
||||
#[inline(always)]
|
||||
pub fn set_module_resolver(
|
||||
&mut self,
|
||||
resolver: Option<impl ModuleResolver + 'static>,
|
||||
resolver: Option<impl crate::ModuleResolver + 'static>,
|
||||
) -> &mut Self {
|
||||
self.module_resolver = resolver.map(|f| Box::new(f) as Box<dyn ModuleResolver>);
|
||||
self.module_resolver = resolver.map(|f| Box::new(f) as Box<dyn crate::ModuleResolver>);
|
||||
self
|
||||
}
|
||||
/// Disable a particular keyword or operator in the language.
|
||||
|
@ -18,20 +18,11 @@ use crate::token::NO_POS;
|
||||
use crate::utils::ImmutableString;
|
||||
use crate::{calc_native_fn_hash, calc_script_fn_hash, StaticVec, INT};
|
||||
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
use crate::{ast::ScriptFnDef, r#unsafe::unsafe_cast_var_name_to_lifetime};
|
||||
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
use crate::FLOAT;
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
use crate::engine::{FN_IDX_GET, FN_IDX_SET};
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
use crate::engine::{Map, Target, FN_GET, FN_SET};
|
||||
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
use crate::engine::KEYWORD_IS_SHARED;
|
||||
use crate::Map;
|
||||
|
||||
use crate::stdlib::{
|
||||
any::{type_name, TypeId},
|
||||
@ -44,9 +35,6 @@ use crate::stdlib::{
|
||||
vec::Vec,
|
||||
};
|
||||
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
use crate::stdlib::borrow::Cow;
|
||||
|
||||
#[cfg(feature = "no_std")]
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
use num_traits::float::Float;
|
||||
@ -55,8 +43,8 @@ use num_traits::float::Float;
|
||||
#[inline(always)]
|
||||
fn extract_prop_from_getter(_fn_name: &str) -> Option<&str> {
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
if _fn_name.starts_with(FN_GET) {
|
||||
return Some(&_fn_name[FN_GET.len()..]);
|
||||
if _fn_name.starts_with(crate::engine::FN_GET) {
|
||||
return Some(&_fn_name[crate::engine::FN_GET.len()..]);
|
||||
}
|
||||
|
||||
None
|
||||
@ -66,8 +54,8 @@ fn extract_prop_from_getter(_fn_name: &str) -> Option<&str> {
|
||||
#[inline(always)]
|
||||
fn extract_prop_from_setter(_fn_name: &str) -> Option<&str> {
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
if _fn_name.starts_with(FN_SET) {
|
||||
return Some(&_fn_name[FN_SET.len()..]);
|
||||
if _fn_name.starts_with(crate::engine::FN_SET) {
|
||||
return Some(&_fn_name[crate::engine::FN_SET.len()..]);
|
||||
}
|
||||
|
||||
None
|
||||
@ -284,7 +272,7 @@ impl Engine {
|
||||
|
||||
// index getter function not found?
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
if fn_name == FN_IDX_GET && args.len() == 2 {
|
||||
if fn_name == crate::engine::FN_IDX_GET && args.len() == 2 {
|
||||
return EvalAltResult::ErrorFunctionNotFound(
|
||||
format!(
|
||||
"{} [{}]",
|
||||
@ -298,7 +286,7 @@ impl Engine {
|
||||
|
||||
// index setter function not found?
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
if fn_name == FN_IDX_SET {
|
||||
if fn_name == crate::engine::FN_IDX_SET {
|
||||
return EvalAltResult::ErrorFunctionNotFound(
|
||||
format!(
|
||||
"{} [{}]=",
|
||||
@ -345,7 +333,7 @@ impl Engine {
|
||||
state: &mut State,
|
||||
lib: &[&Module],
|
||||
this_ptr: &mut Option<&mut Dynamic>,
|
||||
fn_def: &ScriptFnDef,
|
||||
fn_def: &crate::ast::ScriptFnDef,
|
||||
args: &mut FnCallArgs,
|
||||
level: usize,
|
||||
) -> Result<Dynamic, Box<EvalAltResult>> {
|
||||
@ -372,7 +360,8 @@ impl Engine {
|
||||
.iter()
|
||||
.zip(args.iter_mut().map(|v| mem::take(*v)))
|
||||
.map(|(name, value)| {
|
||||
let var_name: Cow<'_, str> = unsafe_cast_var_name_to_lifetime(name).into();
|
||||
let var_name: crate::stdlib::borrow::Cow<'_, str> =
|
||||
crate::r#unsafe::unsafe_cast_var_name_to_lifetime(name).into();
|
||||
(var_name, ScopeEntryType::Normal, value)
|
||||
}),
|
||||
);
|
||||
@ -699,7 +688,7 @@ impl Engine {
|
||||
lib: &[&Module],
|
||||
fn_name: &str,
|
||||
hash_script: u64,
|
||||
target: &mut Target,
|
||||
target: &mut crate::engine::Target,
|
||||
mut call_args: StaticVec<Dynamic>,
|
||||
def_val: Option<Dynamic>,
|
||||
native: bool,
|
||||
@ -782,7 +771,7 @@ impl Engine {
|
||||
} else if {
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
{
|
||||
fn_name == KEYWORD_IS_SHARED && call_args.is_empty()
|
||||
fn_name == crate::engine::KEYWORD_IS_SHARED && call_args.is_empty()
|
||||
}
|
||||
#[cfg(feature = "no_closure")]
|
||||
false
|
||||
@ -908,7 +897,7 @@ impl Engine {
|
||||
|
||||
// Handle is_shared()
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
if fn_name == KEYWORD_IS_SHARED && args_expr.len() == 1 {
|
||||
if fn_name == crate::engine::KEYWORD_IS_SHARED && args_expr.len() == 1 {
|
||||
let value = self.eval_expr(scope, mods, state, lib, this_ptr, &args_expr[0], level)?;
|
||||
|
||||
return Ok(value.is_shared().into());
|
||||
|
@ -10,15 +10,19 @@ use crate::token::{is_valid_identifier, NO_POS};
|
||||
use crate::utils::ImmutableString;
|
||||
use crate::{calc_script_fn_hash, StaticVec};
|
||||
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
use crate::engine::FN_ANONYMOUS;
|
||||
|
||||
use crate::stdlib::{boxed::Box, convert::TryFrom, fmt, iter::empty, mem, string::String};
|
||||
|
||||
#[cfg(feature = "sync")]
|
||||
use crate::stdlib::sync::{Arc, RwLock};
|
||||
#[cfg(not(feature = "sync"))]
|
||||
use crate::stdlib::{cell::RefCell, rc::Rc};
|
||||
use crate::stdlib::rc::Rc;
|
||||
#[cfg(feature = "sync")]
|
||||
use crate::stdlib::sync::Arc;
|
||||
|
||||
#[cfg(any(not(feature = "no_closure"), not(feature = "no_module")))]
|
||||
#[cfg(not(feature = "sync"))]
|
||||
use crate::stdlib::cell::RefCell;
|
||||
#[cfg(any(not(feature = "no_closure"), not(feature = "no_module")))]
|
||||
#[cfg(feature = "sync")]
|
||||
use crate::stdlib::sync::RwLock;
|
||||
|
||||
/// Trait that maps to `Send + Sync` only under the `sync` feature.
|
||||
#[cfg(feature = "sync")]
|
||||
@ -42,9 +46,11 @@ pub type Shared<T> = Rc<T>;
|
||||
pub type Shared<T> = Arc<T>;
|
||||
|
||||
/// Synchronized shared object.
|
||||
#[cfg(any(not(feature = "no_closure"), not(feature = "no_module")))]
|
||||
#[cfg(not(feature = "sync"))]
|
||||
pub type Locked<T> = RefCell<T>;
|
||||
/// Synchronized shared object.
|
||||
#[cfg(any(not(feature = "no_closure"), not(feature = "no_module")))]
|
||||
#[cfg(feature = "sync")]
|
||||
pub type Locked<T> = RwLock<T>;
|
||||
|
||||
@ -249,7 +255,7 @@ impl FnPtr {
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
#[inline(always)]
|
||||
pub fn is_anonymous(&self) -> bool {
|
||||
self.0.starts_with(FN_ANONYMOUS)
|
||||
self.0.starts_with(crate::engine::FN_ANONYMOUS)
|
||||
}
|
||||
/// Call the function pointer with curried arguments (if any).
|
||||
///
|
||||
|
@ -124,6 +124,9 @@ pub use syntax::Expression;
|
||||
pub use token::{Position, NO_POS};
|
||||
pub use utils::ImmutableString;
|
||||
|
||||
#[allow(dead_code)]
|
||||
use fn_native::{Locked, Shared};
|
||||
|
||||
#[cfg(feature = "internals")]
|
||||
pub use utils::{calc_native_fn_hash, calc_script_fn_hash};
|
||||
|
||||
|
@ -10,27 +10,14 @@ use crate::fn_register::by_value as cast_arg;
|
||||
use crate::result::EvalAltResult;
|
||||
use crate::token::{Token, NO_POS};
|
||||
use crate::utils::{ImmutableString, StraightHasherBuilder};
|
||||
use crate::{calc_native_fn_hash, calc_script_fn_hash, StaticVec};
|
||||
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
use crate::ast::ScriptFnDef;
|
||||
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
use crate::{
|
||||
ast::AST,
|
||||
engine::{Engine, Imports},
|
||||
scope::Scope,
|
||||
};
|
||||
use crate::StaticVec;
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
use crate::engine::{Array, FN_IDX_GET, FN_IDX_SET};
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
use crate::engine::{make_getter, make_setter};
|
||||
use crate::Array;
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
use crate::engine::Map;
|
||||
use crate::Map;
|
||||
|
||||
use crate::stdlib::{
|
||||
any::TypeId,
|
||||
@ -295,10 +282,10 @@ impl Module {
|
||||
/// If there is an existing function of the same name and number of arguments, it is replaced.
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
#[inline]
|
||||
pub(crate) fn set_script_fn(&mut self, fn_def: Shared<ScriptFnDef>) -> u64 {
|
||||
pub(crate) fn set_script_fn(&mut self, fn_def: Shared<crate::ast::ScriptFnDef>) -> u64 {
|
||||
// None + function name + number of arguments.
|
||||
let num_params = fn_def.params.len();
|
||||
let hash_script = calc_script_fn_hash(empty(), &fn_def.name, num_params);
|
||||
let hash_script = crate::calc_script_fn_hash(empty(), &fn_def.name, num_params);
|
||||
self.functions.insert(
|
||||
hash_script,
|
||||
FuncInfo {
|
||||
@ -321,7 +308,7 @@ impl Module {
|
||||
name: &str,
|
||||
num_params: usize,
|
||||
public_only: bool,
|
||||
) -> Option<&Shared<ScriptFnDef>> {
|
||||
) -> Option<&Shared<crate::ast::ScriptFnDef>> {
|
||||
self.functions
|
||||
.values()
|
||||
.find(
|
||||
@ -459,7 +446,7 @@ impl Module {
|
||||
) -> u64 {
|
||||
let name = name.into();
|
||||
|
||||
let hash_fn = calc_native_fn_hash(empty(), &name, arg_types.iter().cloned());
|
||||
let hash_fn = crate::calc_native_fn_hash(empty(), &name, arg_types.iter().cloned());
|
||||
|
||||
let params = arg_types
|
||||
.into_iter()
|
||||
@ -678,7 +665,7 @@ impl Module {
|
||||
name: impl Into<String>,
|
||||
func: impl Fn(&mut A) -> Result<T, Box<EvalAltResult>> + SendSync + 'static,
|
||||
) -> u64 {
|
||||
self.set_fn_1_mut(make_getter(&name.into()), func)
|
||||
self.set_fn_1_mut(crate::engine::make_getter(&name.into()), func)
|
||||
}
|
||||
|
||||
/// Set a Rust function taking two parameters into the module, returning a hash key.
|
||||
@ -778,7 +765,7 @@ impl Module {
|
||||
name: impl Into<String>,
|
||||
func: impl Fn(&mut A, B) -> Result<(), Box<EvalAltResult>> + SendSync + 'static,
|
||||
) -> u64 {
|
||||
self.set_fn_2_mut(make_setter(&name.into()), func)
|
||||
self.set_fn_2_mut(crate::engine::make_setter(&name.into()), func)
|
||||
}
|
||||
|
||||
/// Set a Rust index getter taking two parameters (the first one mutable) into the module,
|
||||
@ -822,7 +809,7 @@ impl Module {
|
||||
panic!("Cannot register indexer for strings.");
|
||||
}
|
||||
|
||||
self.set_fn_2_mut(FN_IDX_GET, func)
|
||||
self.set_fn_2_mut(crate::engine::FN_IDX_GET, func)
|
||||
}
|
||||
|
||||
/// Set a Rust function taking three parameters into the module, returning a hash key.
|
||||
@ -961,7 +948,7 @@ impl Module {
|
||||
};
|
||||
let arg_types = [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>()];
|
||||
self.set_fn(
|
||||
FN_IDX_SET,
|
||||
crate::engine::FN_IDX_SET,
|
||||
FnAccess::Public,
|
||||
&arg_types,
|
||||
CallableFunction::from_method(Box::new(f)),
|
||||
@ -1307,7 +1294,7 @@ impl Module {
|
||||
#[inline(always)]
|
||||
pub(crate) fn iter_script_fn<'a>(
|
||||
&'a self,
|
||||
) -> impl Iterator<Item = (FnAccess, &str, usize, Shared<ScriptFnDef>)> + 'a {
|
||||
) -> impl Iterator<Item = (FnAccess, &str, usize, Shared<crate::ast::ScriptFnDef>)> + 'a {
|
||||
self.functions
|
||||
.values()
|
||||
.map(|f| &f.func)
|
||||
@ -1352,7 +1339,7 @@ impl Module {
|
||||
#[inline(always)]
|
||||
pub fn iter_script_fn_info(
|
||||
&self,
|
||||
) -> impl Iterator<Item = (FnAccess, &str, usize, Shared<ScriptFnDef>)> {
|
||||
) -> impl Iterator<Item = (FnAccess, &str, usize, Shared<crate::ast::ScriptFnDef>)> {
|
||||
self.iter_script_fn()
|
||||
}
|
||||
|
||||
@ -1379,9 +1366,9 @@ impl Module {
|
||||
/// ```
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
pub fn eval_ast_as_new(
|
||||
mut scope: Scope,
|
||||
ast: &AST,
|
||||
engine: &Engine,
|
||||
mut scope: crate::Scope,
|
||||
ast: &crate::AST,
|
||||
engine: &crate::Engine,
|
||||
) -> Result<Self, Box<EvalAltResult>> {
|
||||
let mut mods = engine.global_sub_modules.clone();
|
||||
let orig_mods_len = mods.len();
|
||||
@ -1404,7 +1391,7 @@ impl Module {
|
||||
});
|
||||
|
||||
// Extra modules left in the scope become sub-modules
|
||||
let mut func_mods: Imports = Default::default();
|
||||
let mut func_mods: crate::engine::Imports = Default::default();
|
||||
|
||||
mods.into_iter()
|
||||
.skip(orig_mods_len)
|
||||
@ -1457,7 +1444,8 @@ impl Module {
|
||||
// Index all variables
|
||||
module.variables.iter().for_each(|(var_name, value)| {
|
||||
// Qualifiers + variable name
|
||||
let hash_var = calc_script_fn_hash(qualifiers.iter().map(|&v| v), var_name, 0);
|
||||
let hash_var =
|
||||
crate::calc_script_fn_hash(qualifiers.iter().map(|&v| v), var_name, 0);
|
||||
variables.insert(hash_var, value.clone());
|
||||
});
|
||||
|
||||
@ -1494,25 +1482,34 @@ impl Module {
|
||||
// Namespace-qualified Rust functions are indexed in two steps:
|
||||
// 1) Calculate a hash in a similar manner to script-defined functions,
|
||||
// i.e. qualifiers + function name + number of arguments.
|
||||
let hash_qualified_script =
|
||||
calc_script_fn_hash(qualifiers.iter().cloned(), name, *params);
|
||||
let hash_qualified_script = crate::calc_script_fn_hash(
|
||||
qualifiers.iter().cloned(),
|
||||
name,
|
||||
*params,
|
||||
);
|
||||
// 2) Calculate a second hash with no qualifiers, empty function name,
|
||||
// and the actual list of argument `TypeId`'.s
|
||||
let hash_fn_args =
|
||||
calc_native_fn_hash(empty(), "", param_types.iter().cloned());
|
||||
let hash_fn_args = crate::calc_native_fn_hash(
|
||||
empty(),
|
||||
"",
|
||||
param_types.iter().cloned(),
|
||||
);
|
||||
// 3) The final hash is the XOR of the two hashes.
|
||||
let hash_qualified_fn = hash_qualified_script ^ hash_fn_args;
|
||||
|
||||
functions.insert(hash_qualified_fn, func.clone());
|
||||
} else if cfg!(not(feature = "no_function")) {
|
||||
let hash_qualified_script = if cfg!(feature = "no_object")
|
||||
&& qualifiers.is_empty()
|
||||
{
|
||||
hash
|
||||
} else {
|
||||
// Qualifiers + function name + number of arguments.
|
||||
calc_script_fn_hash(qualifiers.iter().map(|&v| v), &name, *params)
|
||||
};
|
||||
let hash_qualified_script =
|
||||
if cfg!(feature = "no_object") && qualifiers.is_empty() {
|
||||
hash
|
||||
} else {
|
||||
// Qualifiers + function name + number of arguments.
|
||||
crate::calc_script_fn_hash(
|
||||
qualifiers.iter().map(|&v| v),
|
||||
&name,
|
||||
*params,
|
||||
)
|
||||
};
|
||||
functions.insert(hash_qualified_script, func.clone());
|
||||
}
|
||||
},
|
||||
|
@ -14,9 +14,6 @@ use crate::token::{is_valid_identifier, Position, NO_POS};
|
||||
use crate::utils::get_hasher;
|
||||
use crate::{calc_native_fn_hash, StaticVec};
|
||||
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
use crate::ast::ReturnType;
|
||||
|
||||
use crate::stdlib::{
|
||||
boxed::Box,
|
||||
hash::{Hash, Hasher},
|
||||
@ -897,9 +894,11 @@ pub fn optimize_into_ast(
|
||||
// {} -> Noop
|
||||
fn_def.body = match body.pop().unwrap_or_else(|| Stmt::Noop(pos)) {
|
||||
// { return val; } -> val
|
||||
Stmt::Return((ReturnType::Return, _), Some(expr), _) => Stmt::Expr(expr),
|
||||
Stmt::Return((crate::ast::ReturnType::Return, _), Some(expr), _) => {
|
||||
Stmt::Expr(expr)
|
||||
}
|
||||
// { return; } -> ()
|
||||
Stmt::Return((ReturnType::Return, pos), None, _) => {
|
||||
Stmt::Return((crate::ast::ReturnType::Return, pos), None, _) => {
|
||||
Stmt::Expr(Expr::Unit(pos))
|
||||
}
|
||||
// All others
|
||||
|
@ -12,7 +12,7 @@ use crate::utils::ImmutableString;
|
||||
use crate::INT;
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
use crate::engine::Map;
|
||||
use crate::Map;
|
||||
|
||||
use crate::stdlib::{any::TypeId, boxed::Box, cmp::max, cmp::Ordering, string::ToString};
|
||||
|
||||
|
@ -8,7 +8,7 @@ use crate::utils::ImmutableString;
|
||||
use crate::INT;
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
use crate::engine::Array;
|
||||
use crate::Array;
|
||||
|
||||
def_package!(crate:BasicMapPackage:"Basic object map utilities.", lib, {
|
||||
combine_with_exported_module!(lib, "map", map_functions);
|
||||
|
@ -8,10 +8,10 @@ use crate::utils::ImmutableString;
|
||||
use crate::INT;
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
use crate::engine::Array;
|
||||
use crate::Array;
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
use crate::engine::Map;
|
||||
use crate::Map;
|
||||
|
||||
use crate::stdlib::{
|
||||
fmt::{Debug, Display},
|
||||
|
@ -8,9 +8,6 @@ use crate::utils::ImmutableString;
|
||||
use crate::StaticVec;
|
||||
use crate::INT;
|
||||
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
use crate::{result::EvalAltResult, token::NO_POS};
|
||||
|
||||
use crate::stdlib::{
|
||||
any::TypeId, boxed::Box, format, mem, string::String, string::ToString, vec::Vec,
|
||||
};
|
||||
@ -255,11 +252,15 @@ mod string_functions {
|
||||
s: &mut ImmutableString,
|
||||
len: INT,
|
||||
ch: char,
|
||||
) -> Result<Dynamic, Box<EvalAltResult>> {
|
||||
) -> Result<Dynamic, Box<crate::EvalAltResult>> {
|
||||
// Check if string will be over max size limit
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
if _ctx.engine().max_string_size() > 0 && len as usize > _ctx.engine().max_string_size() {
|
||||
return EvalAltResult::ErrorDataTooLarge("Length of string".to_string(), NO_POS).into();
|
||||
return crate::EvalAltResult::ErrorDataTooLarge(
|
||||
"Length of string".to_string(),
|
||||
crate::NO_POS,
|
||||
)
|
||||
.into();
|
||||
}
|
||||
|
||||
if len > 0 {
|
||||
@ -275,9 +276,9 @@ mod string_functions {
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
if _ctx.engine().max_string_size() > 0 && s.len() > _ctx.engine().max_string_size()
|
||||
{
|
||||
return EvalAltResult::ErrorDataTooLarge(
|
||||
return crate::EvalAltResult::ErrorDataTooLarge(
|
||||
"Length of string".to_string(),
|
||||
NO_POS,
|
||||
crate::NO_POS,
|
||||
)
|
||||
.into();
|
||||
}
|
||||
@ -292,11 +293,15 @@ mod string_functions {
|
||||
s: &mut ImmutableString,
|
||||
len: INT,
|
||||
padding: &str,
|
||||
) -> Result<Dynamic, Box<EvalAltResult>> {
|
||||
) -> Result<Dynamic, Box<crate::EvalAltResult>> {
|
||||
// Check if string will be over max size limit
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
if _ctx.engine().max_string_size() > 0 && len as usize > _ctx.engine().max_string_size() {
|
||||
return EvalAltResult::ErrorDataTooLarge("Length of string".to_string(), NO_POS).into();
|
||||
return crate::EvalAltResult::ErrorDataTooLarge(
|
||||
"Length of string".to_string(),
|
||||
crate::NO_POS,
|
||||
)
|
||||
.into();
|
||||
}
|
||||
|
||||
if len > 0 {
|
||||
@ -319,9 +324,9 @@ mod string_functions {
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
if _ctx.engine().max_string_size() > 0 && s.len() > _ctx.engine().max_string_size()
|
||||
{
|
||||
return EvalAltResult::ErrorDataTooLarge(
|
||||
return crate::EvalAltResult::ErrorDataTooLarge(
|
||||
"Length of string".to_string(),
|
||||
NO_POS,
|
||||
crate::NO_POS,
|
||||
)
|
||||
.into();
|
||||
}
|
||||
@ -333,7 +338,7 @@ mod string_functions {
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
pub mod arrays {
|
||||
use crate::engine::Array;
|
||||
use crate::Array;
|
||||
|
||||
#[rhai_fn(name = "+")]
|
||||
pub fn append(x: &str, y: Array) -> String {
|
||||
@ -356,7 +361,7 @@ mod string_functions {
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
pub mod maps {
|
||||
use crate::engine::Map;
|
||||
use crate::Map;
|
||||
|
||||
#[rhai_fn(name = "+")]
|
||||
pub fn append(x: &str, y: Map) -> String {
|
||||
|
@ -19,15 +19,6 @@ use crate::{calc_script_fn_hash, StaticVec};
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
use crate::FLOAT;
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
use crate::engine::{make_getter, make_setter, KEYWORD_EVAL, KEYWORD_FN_PTR};
|
||||
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
use crate::{
|
||||
ast::FnAccess,
|
||||
engine::{FN_ANONYMOUS, KEYWORD_FN_PTR_CURRY},
|
||||
};
|
||||
|
||||
use crate::stdlib::{
|
||||
borrow::Cow,
|
||||
boxed::Box,
|
||||
@ -228,8 +219,8 @@ impl Expr {
|
||||
match self {
|
||||
Self::Variable(x) if x.1.is_none() => {
|
||||
let ident = x.3;
|
||||
let getter = state.get_interned_string(make_getter(&ident.name));
|
||||
let setter = state.get_interned_string(make_setter(&ident.name));
|
||||
let getter = state.get_interned_string(crate::engine::make_getter(&ident.name));
|
||||
let setter = state.get_interned_string(crate::engine::make_setter(&ident.name));
|
||||
Self::Property(Box::new(((getter, setter), ident.into())))
|
||||
}
|
||||
_ => self,
|
||||
@ -1389,8 +1380,8 @@ fn make_dot_expr(
|
||||
// lhs.id
|
||||
(lhs, Expr::Variable(x)) if x.1.is_none() => {
|
||||
let ident = x.3;
|
||||
let getter = state.get_interned_string(make_getter(&ident.name));
|
||||
let setter = state.get_interned_string(make_setter(&ident.name));
|
||||
let getter = state.get_interned_string(crate::engine::make_getter(&ident.name));
|
||||
let setter = state.get_interned_string(crate::engine::make_setter(&ident.name));
|
||||
let rhs = Expr::Property(Box::new(((getter, setter), ident)));
|
||||
|
||||
Expr::Dot(Box::new(BinaryExpr { lhs, rhs }), op_pos)
|
||||
@ -1427,7 +1418,7 @@ fn make_dot_expr(
|
||||
}
|
||||
// lhs.Fn() or lhs.eval()
|
||||
(_, Expr::FnCall(x, pos))
|
||||
if x.args.len() == 0 && [KEYWORD_FN_PTR, KEYWORD_EVAL].contains(&x.name.as_ref()) =>
|
||||
if x.args.len() == 0 && [crate::engine::KEYWORD_FN_PTR, crate::engine::KEYWORD_EVAL].contains(&x.name.as_ref()) =>
|
||||
{
|
||||
return Err(PERR::BadInput(LexError::ImproperSymbol(format!(
|
||||
"'{}' should not be called in method style. Try {}(...);",
|
||||
@ -2378,9 +2369,9 @@ fn parse_stmt(
|
||||
Token::Fn | Token::Private => {
|
||||
let access = if matches!(token, Token::Private) {
|
||||
eat_token(input, Token::Private);
|
||||
FnAccess::Private
|
||||
crate::FnAccess::Private
|
||||
} else {
|
||||
FnAccess::Public
|
||||
crate::FnAccess::Public
|
||||
};
|
||||
|
||||
match input.next().unwrap() {
|
||||
@ -2561,7 +2552,7 @@ fn parse_fn(
|
||||
input: &mut TokenStream,
|
||||
state: &mut ParseState,
|
||||
lib: &mut FunctionsLib,
|
||||
access: FnAccess,
|
||||
access: crate::FnAccess,
|
||||
mut settings: ParseSettings,
|
||||
) -> Result<ScriptFnDef, ParseError> {
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
@ -2673,11 +2664,11 @@ fn make_curry_from_externals(fn_expr: Expr, externals: StaticVec<IdentX>, pos: P
|
||||
args.push(Expr::Variable(Box::new((None, None, 0, x.clone().into()))));
|
||||
});
|
||||
|
||||
let hash = calc_script_fn_hash(empty(), KEYWORD_FN_PTR_CURRY, num_externals + 1);
|
||||
let hash = calc_script_fn_hash(empty(), crate::engine::KEYWORD_FN_PTR_CURRY, num_externals + 1);
|
||||
|
||||
let expr = Expr::FnCall(
|
||||
Box::new(FnCallExpr {
|
||||
name: KEYWORD_FN_PTR_CURRY.into(),
|
||||
name: crate::engine::KEYWORD_FN_PTR_CURRY.into(),
|
||||
hash,
|
||||
args,
|
||||
..Default::default()
|
||||
@ -2789,12 +2780,12 @@ fn parse_anon_fn(
|
||||
settings.pos.hash(hasher);
|
||||
let hash = hasher.finish();
|
||||
|
||||
let fn_name: ImmutableString = format!("{}{:016x}", FN_ANONYMOUS, hash).into();
|
||||
let fn_name: ImmutableString = format!("{}{:016x}", crate::engine::FN_ANONYMOUS, hash).into();
|
||||
|
||||
// Define the function
|
||||
let script = ScriptFnDef {
|
||||
name: fn_name.clone(),
|
||||
access: FnAccess::Public,
|
||||
access: crate::FnAccess::Public,
|
||||
params,
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
externals: Default::default(),
|
||||
|
@ -6,9 +6,6 @@ use crate::token::{Position, NO_POS};
|
||||
use crate::utils::ImmutableString;
|
||||
use crate::INT;
|
||||
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
use crate::engine::is_anonymous_fn;
|
||||
|
||||
use crate::stdlib::{
|
||||
boxed::Box,
|
||||
error::Error,
|
||||
@ -159,7 +156,7 @@ impl fmt::Display for EvalAltResult {
|
||||
Self::ErrorParsing(p, _) => write!(f, "Syntax error: {}", p)?,
|
||||
|
||||
#[cfg(not(feature = "no_function"))]
|
||||
Self::ErrorInFunctionCall(s, err, _) if is_anonymous_fn(s) => {
|
||||
Self::ErrorInFunctionCall(s, err, _) if crate::engine::is_anonymous_fn(s) => {
|
||||
write!(f, "Error in call to closure: {}", err)?
|
||||
}
|
||||
Self::ErrorInFunctionCall(s, err, _) => {
|
||||
|
@ -427,6 +427,7 @@ impl<'a> Scope<'a> {
|
||||
}
|
||||
/// Get an iterator to entries in the Scope.
|
||||
#[inline(always)]
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn into_iter(
|
||||
self,
|
||||
) -> impl Iterator<Item = (Cow<'a, str>, EntryType, Dynamic, Vec<String>)> {
|
||||
|
@ -13,13 +13,10 @@ use serde::de::{
|
||||
use serde::Deserialize;
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
use crate::engine::Array;
|
||||
use crate::Array;
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
use crate::engine::Map;
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
use serde::de::{EnumAccess, VariantAccess};
|
||||
use crate::Map;
|
||||
|
||||
use crate::stdlib::{any::type_name, boxed::Box, fmt, string::ToString};
|
||||
|
||||
@ -542,7 +539,7 @@ struct EnumDeserializer<'t, 'de: 't> {
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
impl<'t, 'de> EnumAccess<'de> for EnumDeserializer<'t, 'de> {
|
||||
impl<'t, 'de> serde::de::EnumAccess<'de> for EnumDeserializer<'t, 'de> {
|
||||
type Error = Box<EvalAltResult>;
|
||||
type Variant = Self;
|
||||
|
||||
@ -556,7 +553,7 @@ impl<'t, 'de> EnumAccess<'de> for EnumDeserializer<'t, 'de> {
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
impl<'t, 'de> VariantAccess<'de> for EnumDeserializer<'t, 'de> {
|
||||
impl<'t, 'de> serde::de::VariantAccess<'de> for EnumDeserializer<'t, 'de> {
|
||||
type Error = Box<EvalAltResult>;
|
||||
|
||||
fn unit_variant(mut self) -> Result<(), Self::Error> {
|
||||
|
@ -5,9 +5,10 @@ use crate::result::EvalAltResult;
|
||||
use crate::token::NO_POS;
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
use crate::engine::Array;
|
||||
use crate::Array;
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
use crate::engine::Map;
|
||||
use crate::Map;
|
||||
|
||||
use serde::ser::{
|
||||
Error, SerializeMap, SerializeSeq, SerializeStruct, SerializeTuple, SerializeTupleStruct,
|
||||
@ -15,17 +16,8 @@ use serde::ser::{
|
||||
};
|
||||
use serde::Serialize;
|
||||
|
||||
#[cfg(not(any(feature = "no_object", feature = "no_index")))]
|
||||
use serde::ser::SerializeTupleVariant;
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
use serde::ser::SerializeStructVariant;
|
||||
|
||||
use crate::stdlib::{boxed::Box, fmt, string::ToString};
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
use crate::stdlib::mem;
|
||||
|
||||
/// Serializer for `Dynamic` which is kept as a reference.
|
||||
pub struct DynamicSerializer {
|
||||
/// Buffer to hold a temporary key.
|
||||
@ -477,7 +469,7 @@ impl SerializeMap for DynamicSerializer {
|
||||
) -> Result<(), Box<EvalAltResult>> {
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
{
|
||||
let key = mem::take(&mut self._key)
|
||||
let key = crate::stdlib::mem::take(&mut self._key)
|
||||
.take_immutable_string()
|
||||
.map_err(|typ| {
|
||||
EvalAltResult::ErrorMismatchOutputType("string".into(), typ.into(), NO_POS)
|
||||
@ -554,7 +546,7 @@ pub struct TupleVariantSerializer {
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "no_object", feature = "no_index")))]
|
||||
impl SerializeTupleVariant for TupleVariantSerializer {
|
||||
impl serde::ser::SerializeTupleVariant for TupleVariantSerializer {
|
||||
type Ok = Dynamic;
|
||||
type Error = Box<EvalAltResult>;
|
||||
|
||||
@ -579,7 +571,7 @@ pub struct StructVariantSerializer {
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
impl SerializeStructVariant for StructVariantSerializer {
|
||||
impl serde::ser::SerializeStructVariant for StructVariantSerializer {
|
||||
type Ok = Dynamic;
|
||||
type Error = Box<EvalAltResult>;
|
||||
|
||||
|
@ -5,9 +5,6 @@ use crate::engine::{
|
||||
KEYWORD_IS_DEF_FN, KEYWORD_IS_DEF_VAR, KEYWORD_PRINT, KEYWORD_THIS, KEYWORD_TYPE_OF,
|
||||
};
|
||||
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
use crate::engine::KEYWORD_IS_SHARED;
|
||||
|
||||
use crate::parse_error::LexError;
|
||||
use crate::StaticVec;
|
||||
use crate::INT;
|
||||
@ -545,7 +542,7 @@ impl Token {
|
||||
| KEYWORD_IS_DEF_FN | KEYWORD_THIS => Reserved(syntax.into()),
|
||||
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
KEYWORD_IS_SHARED => Reserved(syntax.into()),
|
||||
crate::engine::KEYWORD_IS_SHARED => Reserved(syntax.into()),
|
||||
|
||||
_ => return None,
|
||||
})
|
||||
@ -1515,7 +1512,7 @@ fn get_identifier(
|
||||
pub fn is_keyword_function(name: &str) -> bool {
|
||||
match name {
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
KEYWORD_IS_SHARED => true,
|
||||
crate::engine::KEYWORD_IS_SHARED => true,
|
||||
KEYWORD_PRINT | KEYWORD_DEBUG | KEYWORD_TYPE_OF | KEYWORD_EVAL | KEYWORD_FN_PTR
|
||||
| KEYWORD_FN_PTR_CALL | KEYWORD_FN_PTR_CURRY | KEYWORD_IS_DEF_VAR | KEYWORD_IS_DEF_FN => {
|
||||
true
|
||||
|
Loading…
Reference in New Issue
Block a user