Move definition of Array and Map to lib.rs.

This commit is contained in:
Stephen Chung 2020-11-16 21:14:32 +08:00
parent adb902326e
commit d50d48f26f
12 changed files with 50 additions and 65 deletions

View File

@ -3,7 +3,7 @@
///! Test evaluating with scope ///! Test evaluating with scope
extern crate test; extern crate test;
use rhai::{module_resolvers::StaticModuleResolver, Engine, Module, OptimizationLevel}; use rhai::{Engine, Module, OptimizationLevel};
use test::Bencher; use test::Bencher;
#[bench] #[bench]
@ -20,9 +20,7 @@ fn bench_eval_module(bench: &mut Bencher) {
let module = Module::eval_ast_as_new(Default::default(), &ast, &engine).unwrap(); let module = Module::eval_ast_as_new(Default::default(), &ast, &engine).unwrap();
let mut resolver = StaticModuleResolver::new(); engine.register_module("testing", module);
resolver.insert("testing", module);
engine.set_module_resolver(Some(resolver));
let ast = engine let ast = engine
.compile( .compile(

View File

@ -31,12 +31,6 @@ use crate::stdlib::{
vec::Vec, vec::Vec,
}; };
#[cfg(not(feature = "no_closure"))]
use crate::stdlib::collections::HashSet;
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
use crate::stdlib::cmp::max;
/// A type representing the access mode of a scripted function. /// A type representing the access mode of a scripted function.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum FnAccess { pub enum FnAccess {
@ -98,7 +92,7 @@ pub struct ScriptFnDef {
pub params: StaticVec<ImmutableString>, pub params: StaticVec<ImmutableString>,
/// Access to external variables. /// Access to external variables.
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
pub externals: HashSet<ImmutableString>, pub externals: crate::stdlib::collections::HashSet<ImmutableString>,
} }
impl fmt::Display for ScriptFnDef { impl fmt::Display for ScriptFnDef {
@ -940,14 +934,20 @@ impl Expr {
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Self::Array(x, _) if self.is_constant() => { Self::Array(x, _) if self.is_constant() => {
let mut arr = Array::with_capacity(max(crate::engine::TYPICAL_ARRAY_SIZE, x.len())); let mut arr = Array::with_capacity(crate::stdlib::cmp::max(
crate::engine::TYPICAL_ARRAY_SIZE,
x.len(),
));
arr.extend(x.iter().map(|v| v.get_constant_value().unwrap())); arr.extend(x.iter().map(|v| v.get_constant_value().unwrap()));
Dynamic(Union::Array(Box::new(arr))) Dynamic(Union::Array(Box::new(arr)))
} }
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Self::Map(x, _) if self.is_constant() => { Self::Map(x, _) if self.is_constant() => {
let mut map = Map::with_capacity(max(crate::engine::TYPICAL_MAP_SIZE, x.len())); let mut map = Map::with_capacity(crate::stdlib::cmp::max(
crate::engine::TYPICAL_MAP_SIZE,
x.len(),
));
map.extend( map.extend(
x.iter() x.iter()
.map(|(k, v)| (k.name.clone(), v.get_constant_value().unwrap())), .map(|(k, v)| (k.name.clone(), v.get_constant_value().unwrap())),

View File

@ -28,20 +28,14 @@ use crate::stdlib::{
string::{String, ToString}, string::{String, ToString},
}; };
/// Variable-sized array of `Dynamic` values.
///
/// Not available under the `no_index` feature.
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
pub type Array = crate::stdlib::vec::Vec<Dynamic>; use crate::Array;
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
pub const TYPICAL_ARRAY_SIZE: usize = 8; // Small arrays are typical pub const TYPICAL_ARRAY_SIZE: usize = 8; // Small arrays are typical
/// Hash map of `Dynamic` values with `ImmutableString` keys.
///
/// Not available under the `no_object` feature.
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
pub type Map = HashMap<ImmutableString, Dynamic>; use crate::Map;
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
pub const TYPICAL_MAP_SIZE: usize = 8; // Small maps are typical pub const TYPICAL_MAP_SIZE: usize = 8; // Small maps are typical

View File

@ -761,7 +761,7 @@ impl Engine {
self.register_indexer_get(getter) self.register_indexer_get(getter)
.register_indexer_set(setter) .register_indexer_set(setter)
} }
/// Register a `Module` as a sub-module with the `Engine`. /// Register a `Module` as a fixed module namespace with the `Engine`.
/// ///
/// # Example /// # Example
/// ///
@ -775,7 +775,7 @@ impl Engine {
/// let mut module = Module::new(); /// let mut module = Module::new();
/// module.set_fn_1("calc", |x: i64| Ok(x + 1)); /// module.set_fn_1("calc", |x: i64| Ok(x + 1));
/// ///
/// // Register the module as a sub-module /// // Register the module as a fixed sub-module
/// engine.register_module("CalcService", module); /// engine.register_module("CalcService", module);
/// ///
/// assert_eq!(engine.eval::<i64>("CalcService::calc(41)")?, 42); /// assert_eq!(engine.eval::<i64>("CalcService::calc(41)")?, 42);

View File

@ -40,25 +40,25 @@ use crate::stdlib::{
use num_traits::float::Float; use num_traits::float::Float;
/// Extract the property name from a getter function name. /// Extract the property name from a getter function name.
#[cfg(not(feature = "no_object"))]
#[inline(always)] #[inline(always)]
fn extract_prop_from_getter(_fn_name: &str) -> Option<&str> { fn extract_prop_from_getter(_fn_name: &str) -> Option<&str> {
#[cfg(not(feature = "no_object"))]
if _fn_name.starts_with(crate::engine::FN_GET) { if _fn_name.starts_with(crate::engine::FN_GET) {
return Some(&_fn_name[crate::engine::FN_GET.len()..]); Some(&_fn_name[crate::engine::FN_GET.len()..])
} else {
None
} }
None
} }
/// Extract the property name from a setter function name. /// Extract the property name from a setter function name.
#[cfg(not(feature = "no_object"))]
#[inline(always)] #[inline(always)]
fn extract_prop_from_setter(_fn_name: &str) -> Option<&str> { fn extract_prop_from_setter(_fn_name: &str) -> Option<&str> {
#[cfg(not(feature = "no_object"))]
if _fn_name.starts_with(crate::engine::FN_SET) { if _fn_name.starts_with(crate::engine::FN_SET) {
return Some(&_fn_name[crate::engine::FN_SET.len()..]); Some(&_fn_name[crate::engine::FN_SET.len()..])
} else {
None
} }
None
} }
/// A type that temporarily stores a mutable reference to a `Dynamic`, /// A type that temporarily stores a mutable reference to a `Dynamic`,
@ -244,6 +244,7 @@ impl Engine {
} }
// Getter function not found? // Getter function not found?
#[cfg(not(feature = "no_object"))]
if let Some(prop) = extract_prop_from_getter(fn_name) { if let Some(prop) = extract_prop_from_getter(fn_name) {
return EvalAltResult::ErrorDotExpr( return EvalAltResult::ErrorDotExpr(
format!( format!(
@ -257,6 +258,7 @@ impl Engine {
} }
// Setter function not found? // Setter function not found?
#[cfg(not(feature = "no_object"))]
if let Some(prop) = extract_prop_from_setter(fn_name) { if let Some(prop) = extract_prop_from_setter(fn_name) {
return EvalAltResult::ErrorDotExpr( return EvalAltResult::ErrorDotExpr(
format!( format!(

View File

@ -17,13 +17,6 @@ use crate::stdlib::rc::Rc;
#[cfg(feature = "sync")] #[cfg(feature = "sync")]
use crate::stdlib::sync::Arc; 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. /// Trait that maps to `Send + Sync` only under the `sync` feature.
#[cfg(feature = "sync")] #[cfg(feature = "sync")]
pub trait SendSync: Send + Sync {} pub trait SendSync: Send + Sync {}
@ -48,11 +41,11 @@ pub type Shared<T> = Arc<T>;
/// Synchronized shared object. /// Synchronized shared object.
#[cfg(any(not(feature = "no_closure"), not(feature = "no_module")))] #[cfg(any(not(feature = "no_closure"), not(feature = "no_module")))]
#[cfg(not(feature = "sync"))] #[cfg(not(feature = "sync"))]
pub type Locked<T> = RefCell<T>; pub type Locked<T> = crate::stdlib::cell::RefCell<T>;
/// Synchronized shared object. /// Synchronized shared object.
#[cfg(any(not(feature = "no_closure"), not(feature = "no_module")))] #[cfg(any(not(feature = "no_closure"), not(feature = "no_module")))]
#[cfg(feature = "sync")] #[cfg(feature = "sync")]
pub type Locked<T> = RwLock<T>; pub type Locked<T> = crate::stdlib::sync::RwLock<T>;
/// Context of native Rust function call. /// Context of native Rust function call.
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]

View File

@ -141,11 +141,17 @@ pub use ast::FnAccess;
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
pub use fn_func::Func; pub use fn_func::Func;
/// Variable-sized array of `Dynamic` values.
///
/// Not available under the `no_index` feature.
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
pub use engine::Array; pub type Array = stdlib::vec::Vec<Dynamic>;
/// Hash map of `Dynamic` values with `ImmutableString` keys.
///
/// Not available under the `no_object` feature.
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
pub use engine::Map; pub type Map = stdlib::collections::HashMap<ImmutableString, Dynamic>;
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
pub use module::ModuleResolver; pub use module::ModuleResolver;

View File

@ -3,13 +3,13 @@
use crate::def_package; use crate::def_package;
use crate::dynamic::Dynamic; use crate::dynamic::Dynamic;
use crate::engine::{Array, OP_EQUALS, TYPICAL_ARRAY_SIZE}; use crate::engine::{OP_EQUALS, TYPICAL_ARRAY_SIZE};
use crate::fn_native::{FnPtr, NativeCallContext}; use crate::fn_native::{FnPtr, NativeCallContext};
use crate::plugin::*; use crate::plugin::*;
use crate::result::EvalAltResult; use crate::result::EvalAltResult;
use crate::token::NO_POS; use crate::token::NO_POS;
use crate::utils::ImmutableString; use crate::utils::ImmutableString;
use crate::INT; use crate::{Array, INT};
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
use crate::Map; use crate::Map;

View File

@ -2,10 +2,10 @@
use crate::def_package; use crate::def_package;
use crate::dynamic::Dynamic; use crate::dynamic::Dynamic;
use crate::engine::{Map, OP_EQUALS}; use crate::engine::OP_EQUALS;
use crate::plugin::*; use crate::plugin::*;
use crate::utils::ImmutableString; use crate::utils::ImmutableString;
use crate::INT; use crate::{Map, INT};
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
use crate::Array; use crate::Array;

View File

@ -1418,7 +1418,9 @@ fn make_dot_expr(
} }
// lhs.Fn() or lhs.eval() // lhs.Fn() or lhs.eval()
(_, Expr::FnCall(x, pos)) (_, Expr::FnCall(x, pos))
if x.args.len() == 0 && [crate::engine::KEYWORD_FN_PTR, crate::engine::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!( return Err(PERR::BadInput(LexError::ImproperSymbol(format!(
"'{}' should not be called in method style. Try {}(...);", "'{}' should not be called in method style. Try {}(...);",
@ -2664,11 +2666,13 @@ 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())))); args.push(Expr::Variable(Box::new((None, None, 0, x.clone().into()))));
}); });
let hash = calc_script_fn_hash(empty(), crate::engine::KEYWORD_FN_PTR_CURRY, num_externals + 1); let curry_func = crate::engine::KEYWORD_FN_PTR_CURRY;
let hash = calc_script_fn_hash(empty(), curry_func, num_externals + 1);
let expr = Expr::FnCall( let expr = Expr::FnCall(
Box::new(FnCallExpr { Box::new(FnCallExpr {
name: crate::engine::KEYWORD_FN_PTR_CURRY.into(), name: curry_func.into(),
hash, hash,
args, args,
..Default::default() ..Default::default()

View File

@ -15,12 +15,6 @@ use crate::stdlib::{
string::{String, ToString}, string::{String, ToString},
}; };
#[cfg(not(feature = "no_std"))]
use crate::stdlib::collections::hash_map::DefaultHasher;
#[cfg(feature = "no_std")]
use ahash::AHasher;
/// A hasher that only takes one single `u64` and returns it as a hash key. /// A hasher that only takes one single `u64` and returns it as a hash key.
/// ///
/// # Panics /// # Panics
@ -95,9 +89,9 @@ pub fn calc_script_fn_hash<'a>(
/// Create an instance of the default hasher. /// Create an instance of the default hasher.
pub fn get_hasher() -> impl Hasher { pub fn get_hasher() -> impl Hasher {
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
let s: AHasher = Default::default(); let s: ahash::AHasher = Default::default();
#[cfg(not(feature = "no_std"))] #[cfg(not(feature = "no_std"))]
let s = DefaultHasher::new(); let s = crate::stdlib::collections::hash_map::DefaultHasher::new();
s s
} }

View File

@ -1,6 +1,5 @@
#![cfg(not(any(feature = "no_index", feature = "no_module")))] #![cfg(not(any(feature = "no_index", feature = "no_module")))]
use rhai::module_resolvers::StaticModuleResolver;
use rhai::plugin::*; use rhai::plugin::*;
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
@ -96,14 +95,9 @@ fn test_plugins_package() -> Result<(), Box<EvalAltResult>> {
"6 kitties" "6 kitties"
); );
let mut resolver = StaticModuleResolver::new(); engine.register_module("test", exported_module!(test::special_array_package));
resolver.insert("test", exported_module!(test::special_array_package));
engine.set_module_resolver(Some(resolver)); assert_eq!(engine.eval::<INT>("test::MYSTIC_NUMBER")?, 42);
assert_eq!(
engine.eval::<INT>(r#"import "test" as test; test::MYSTIC_NUMBER"#)?,
42
);
Ok(()) Ok(())
} }