Add FnNamespace for module functions.

This commit is contained in:
Stephen Chung
2020-11-17 12:23:53 +08:00
parent a19865d811
commit 038e3c2554
20 changed files with 264 additions and 171 deletions

View File

@@ -17,7 +17,9 @@ use crate::stdlib::{
use crate::syntax::FnCustomSyntaxEval;
use crate::token::Token;
use crate::utils::StraightHasherBuilder;
use crate::{Dynamic, FnPtr, ImmutableString, Module, Position, Shared, StaticVec, INT, NO_POS};
use crate::{
Dynamic, FnNamespace, FnPtr, ImmutableString, Module, Position, Shared, StaticVec, INT, NO_POS,
};
#[cfg(not(feature = "no_float"))]
use crate::FLOAT;
@@ -28,7 +30,7 @@ use crate::Array;
#[cfg(not(feature = "no_object"))]
use crate::Map;
/// A type representing the access mode of a scripted function.
/// A type representing the access mode of a function.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum FnAccess {
/// Public function.
@@ -37,16 +39,6 @@ pub enum FnAccess {
Private,
}
impl fmt::Display for FnAccess {
#[inline(always)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Private => write!(f, "private"),
Self::Public => write!(f, "public"),
}
}
}
impl FnAccess {
/// Is this access mode private?
#[inline(always)]
@@ -178,7 +170,7 @@ impl AST {
#[cfg(not(feature = "no_function"))]
#[inline(always)]
pub fn clone_functions_only(&self) -> Self {
self.clone_functions_only_filtered(|_, _, _| true)
self.clone_functions_only_filtered(|_, _, _, _, _| true)
}
/// Clone the `AST`'s functions into a new `AST` based on a filter predicate.
/// No statements are cloned.
@@ -188,7 +180,7 @@ impl AST {
#[inline(always)]
pub fn clone_functions_only_filtered(
&self,
mut filter: impl FnMut(FnAccess, &str, usize) -> bool,
mut filter: impl FnMut(FnNamespace, FnAccess, bool, &str, usize) -> bool,
) -> Self {
let mut functions: Module = Default::default();
functions.merge_filtered(&self.1, &mut filter);
@@ -251,7 +243,7 @@ impl AST {
/// ```
#[inline(always)]
pub fn merge(&self, other: &Self) -> Self {
self.merge_filtered(other, |_, _, _| true)
self.merge_filtered(other, |_, _, _, _, _| true)
}
/// Combine one `AST` with another. The second `AST` is consumed.
///
@@ -303,7 +295,7 @@ impl AST {
/// ```
#[inline(always)]
pub fn combine(&mut self, other: Self) -> &mut Self {
self.combine_filtered(other, |_, _, _| true)
self.combine_filtered(other, |_, _, _, _, _| true)
}
/// Merge two `AST` into one. Both `AST`'s are untouched and a new, merged, version
/// is returned.
@@ -339,7 +331,8 @@ impl AST {
/// "#)?;
///
/// // Merge 'ast2', picking only 'error()' but not 'foo(_)', into 'ast1'
/// let ast = ast1.merge_filtered(&ast2, |_, name, params| name == "error" && params == 0);
/// let ast = ast1.merge_filtered(&ast2, |_, _, script, name, params|
/// script && name == "error" && params == 0);
///
/// // 'ast' is essentially:
/// //
@@ -360,7 +353,7 @@ impl AST {
pub fn merge_filtered(
&self,
other: &Self,
mut filter: impl FnMut(FnAccess, &str, usize) -> bool,
mut filter: impl FnMut(FnNamespace, FnAccess, bool, &str, usize) -> bool,
) -> Self {
let Self(statements, functions) = self;
@@ -413,7 +406,8 @@ impl AST {
/// "#)?;
///
/// // Combine 'ast2', picking only 'error()' but not 'foo(_)', into 'ast1'
/// ast1.combine_filtered(ast2, |_, name, params| name == "error" && params == 0);
/// ast1.combine_filtered(ast2, |_, _, script, name, params|
/// script && name == "error" && params == 0);
///
/// // 'ast1' is essentially:
/// //
@@ -434,7 +428,7 @@ impl AST {
pub fn combine_filtered(
&mut self,
other: Self,
mut filter: impl FnMut(FnAccess, &str, usize) -> bool,
mut filter: impl FnMut(FnNamespace, FnAccess, bool, &str, usize) -> bool,
) -> &mut Self {
let Self(ref mut statements, ref mut functions) = self;
statements.extend(other.0.into_iter());
@@ -459,22 +453,25 @@ impl AST {
/// "#)?;
///
/// // Remove all functions except 'foo(_)'
/// ast.retain_functions(|_, name, params| name == "foo" && params == 1);
/// ast.retain_functions(|_, _, name, params| name == "foo" && params == 1);
/// # }
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_function"))]
#[inline(always)]
pub fn retain_functions(&mut self, filter: impl FnMut(FnAccess, &str, usize) -> bool) {
self.1.retain_functions(filter);
pub fn retain_functions(
&mut self,
filter: impl FnMut(FnNamespace, FnAccess, &str, usize) -> bool,
) {
self.1.retain_script_functions(filter);
}
/// Iterate through all functions
#[cfg(not(feature = "no_function"))]
#[inline(always)]
pub fn iter_functions<'a>(
&'a self,
) -> impl Iterator<Item = (FnAccess, &str, usize, Shared<ScriptFnDef>)> + 'a {
) -> impl Iterator<Item = (FnNamespace, FnAccess, &str, usize, Shared<ScriptFnDef>)> + 'a {
self.1.iter_script_fn()
}
/// Clear all function definitions in the `AST`.

View File

@@ -52,7 +52,7 @@ pub const TYPICAL_MAP_SIZE: usize = 8; // Small maps are typical
// We cannot use &str or Cow<str> here because `eval` may load a module and the module name will live beyond
// the AST of the eval script text. The best we can do is a shared reference.
#[derive(Debug, Clone, Default)]
pub struct Imports(StaticVec<(ImmutableString, bool, Shared<Module>)>);
pub struct Imports(StaticVec<(ImmutableString, Shared<Module>)>);
impl Imports {
/// Get the length of this stack of imported modules.
@@ -65,7 +65,7 @@ impl Imports {
}
/// Get the imported module at a particular index.
pub fn get(&self, index: usize) -> Option<Shared<Module>> {
self.0.get(index).map(|(_, _, m)| m).cloned()
self.0.get(index).map(|(_, m)| m).cloned()
}
/// Get the index of an imported module by name.
pub fn find(&self, name: &str) -> Option<usize> {
@@ -73,21 +73,12 @@ impl Imports {
.iter()
.enumerate()
.rev()
.find(|(_, (key, _, _))| key.as_str() == name)
.find(|(_, (key, _))| key.as_str() == name)
.map(|(index, _)| index)
}
/// Push an imported module onto the stack.
pub fn push(&mut self, name: impl Into<ImmutableString>, module: impl Into<Shared<Module>>) {
self.0.push((name.into(), false, module.into()));
}
/// Push a fixed module onto the stack.
#[cfg(not(feature = "no_module"))]
pub(crate) fn push_fixed(
&mut self,
name: impl Into<ImmutableString>,
module: impl Into<Shared<Module>>,
) {
self.0.push((name.into(), true, module.into()));
self.0.push((name.into(), module.into()));
}
/// Truncate the stack of imported modules to a particular length.
pub fn truncate(&mut self, size: usize) {
@@ -95,58 +86,49 @@ impl Imports {
}
/// Get an iterator to this stack of imported modules.
#[allow(dead_code)]
pub fn iter(&self) -> impl Iterator<Item = (&str, bool, Shared<Module>)> {
pub fn iter(&self) -> impl Iterator<Item = (&str, Shared<Module>)> {
self.0
.iter()
.map(|(name, fixed, module)| (name.as_str(), *fixed, module.clone()))
.map(|(name, module)| (name.as_str(), module.clone()))
}
/// Get an iterator to this stack of imported modules.
#[allow(dead_code)]
pub(crate) fn iter_raw<'a>(
&'a self,
) -> impl Iterator<Item = (ImmutableString, bool, Shared<Module>)> + 'a {
) -> impl Iterator<Item = (ImmutableString, Shared<Module>)> + 'a {
self.0.iter().cloned()
}
/// Get a consuming iterator to this stack of imported modules.
pub fn into_iter(self) -> impl Iterator<Item = (ImmutableString, bool, Shared<Module>)> {
pub fn into_iter(self) -> impl Iterator<Item = (ImmutableString, Shared<Module>)> {
self.0.into_iter()
}
/// Add a stream of imported modules.
pub fn extend(
&mut self,
stream: impl Iterator<Item = (ImmutableString, bool, Shared<Module>)>,
) {
pub fn extend(&mut self, stream: impl Iterator<Item = (ImmutableString, Shared<Module>)>) {
self.0.extend(stream)
}
/// Does the specified function hash key exist in this stack of imported modules?
#[allow(dead_code)]
pub fn contains_fn(&self, hash: u64) -> bool {
self.0
.iter()
.any(|(_, fixed, m)| *fixed && m.contains_qualified_fn(hash))
self.0.iter().any(|(_, m)| m.contains_qualified_fn(hash))
}
/// Get specified function via its hash key.
pub fn get_fn(&self, hash: u64) -> Option<&CallableFunction> {
self.0
.iter()
.rev()
.filter(|&&(_, fixed, _)| fixed)
.find_map(|(_, _, m)| m.get_qualified_fn(hash))
.find_map(|(_, m)| m.get_qualified_fn(hash))
}
/// Does the specified TypeId iterator exist in this stack of imported modules?
#[allow(dead_code)]
pub fn contains_iter(&self, id: TypeId) -> bool {
self.0
.iter()
.any(|(_, fixed, m)| *fixed && m.contains_qualified_iter(id))
self.0.iter().any(|(_, m)| m.contains_qualified_iter(id))
}
/// Get the specified TypeId iterator.
pub fn get_iter(&self, id: TypeId) -> Option<IteratorFn> {
self.0
.iter()
.rev()
.filter(|&&(_, fixed, _)| fixed)
.find_map(|(_, _, m)| m.get_qualified_iter(id))
.find_map(|(_, m)| m.get_qualified_iter(id))
}
}

View File

@@ -12,7 +12,8 @@ use crate::stdlib::{
};
use crate::utils::get_hasher;
use crate::{
scope::Scope, Dynamic, Engine, EvalAltResult, NativeCallContext, ParseError, AST, NO_POS,
scope::Scope, Dynamic, Engine, EvalAltResult, FnAccess, FnNamespace, NativeCallContext,
ParseError, AST, NO_POS,
};
#[cfg(not(feature = "no_index"))]
@@ -55,7 +56,8 @@ impl Engine {
+ SendSync
+ 'static,
) -> &mut Self {
self.global_module.set_raw_fn(name, arg_types, func);
self.global_module
.set_raw_fn(name, FnNamespace::Global, FnAccess::Public, arg_types, func);
self
}
/// Register a custom type for use with the `Engine`.
@@ -751,9 +753,9 @@ impl Engine {
// Index the module (making a clone copy if necessary) if it is not indexed
let mut module = crate::fn_native::shared_take_or_clone(module);
module.build_index();
self.global_sub_modules.push_fixed(name, module);
self.global_sub_modules.push(name, module);
} else {
self.global_sub_modules.push_fixed(name, module);
self.global_sub_modules.push(name, module);
}
self
}

View File

@@ -2,12 +2,13 @@
#![allow(non_snake_case)]
use crate::ast::FnAccess;
use crate::dynamic::{DynamicWriteLock, Variant};
use crate::fn_native::{CallableFunction, FnAny, FnCallArgs, SendSync};
use crate::r#unsafe::unsafe_cast_box;
use crate::stdlib::{any::TypeId, boxed::Box, mem, string::String};
use crate::{Dynamic, Engine, EvalAltResult, ImmutableString, NativeCallContext};
use crate::{
Dynamic, Engine, EvalAltResult, FnAccess, FnNamespace, ImmutableString, NativeCallContext,
};
/// Trait to register custom functions with the `Engine`.
pub trait RegisterFn<FN, ARGS, RET> {
@@ -186,7 +187,7 @@ macro_rules! def_register {
{
#[inline]
fn register_fn(&mut self, name: &str, f: FN) -> &mut Self {
self.global_module.set_fn(name, FnAccess::Public,
self.global_module.set_fn(name, FnNamespace::Global, FnAccess::Public,
&[$(map_type_id::<$par>()),*],
CallableFunction::$abi(make_func!(f : map_dynamic ; $($par => $let => $clone => $arg),*))
);
@@ -201,7 +202,7 @@ macro_rules! def_register {
{
#[inline]
fn register_result_fn(&mut self, name: &str, f: FN) -> &mut Self {
self.global_module.set_fn(name, FnAccess::Public,
self.global_module.set_fn(name, FnNamespace::Global, FnAccess::Public,
&[$(map_type_id::<$par>()),*],
CallableFunction::$abi(make_func!(f : map_result ; $($par => $let => $clone => $arg),*))
);

View File

@@ -111,12 +111,12 @@ pub type FLOAT = f64;
#[cfg(feature = "f32_float")]
pub type FLOAT = f32;
pub use ast::AST;
pub use ast::{FnAccess, AST};
pub use dynamic::Dynamic;
pub use engine::{Engine, EvalContext};
pub use fn_native::{FnPtr, NativeCallContext};
pub use fn_register::{RegisterFn, RegisterResultFn};
pub use module::Module;
pub use module::{FnNamespace, Module};
pub use parse_error::{LexError, ParseError, ParseErrorType};
pub use result::EvalAltResult;
pub use scope::Scope;
@@ -135,9 +135,6 @@ pub(crate) use utils::{calc_native_fn_hash, calc_script_fn_hash};
pub use rhai_codegen::*;
#[cfg(not(feature = "no_function"))]
pub use ast::FnAccess;
#[cfg(not(feature = "no_function"))]
pub use fn_func::Func;

View File

@@ -30,11 +30,44 @@ use crate::Array;
#[cfg(not(feature = "no_object"))]
use crate::Map;
#[cfg(not(feature = "no_function"))]
pub type SharedScriptFnDef = Shared<crate::ast::ScriptFnDef>;
/// A type representing the namespace of a function.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum FnNamespace {
/// Global namespace.
Global,
/// Internal only.
Internal,
}
impl FnNamespace {
/// Is this namespace global?
#[inline(always)]
pub fn is_global(self) -> bool {
match self {
Self::Global => true,
Self::Internal => false,
}
}
/// Is this namespace internal?
#[inline(always)]
pub fn is_internal(self) -> bool {
match self {
Self::Global => false,
Self::Internal => true,
}
}
}
/// Data structure containing a single registered function.
#[derive(Debug, Clone)]
pub struct FuncInfo {
/// Function instance.
pub func: CallableFunction,
/// Function namespace.
pub namespace: FnNamespace,
/// Function access mode.
pub access: FnAccess,
/// Function name.
@@ -281,7 +314,7 @@ 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<crate::ast::ScriptFnDef>) -> u64 {
pub(crate) fn set_script_fn(&mut self, fn_def: SharedScriptFnDef) -> u64 {
// None + function name + number of arguments.
let num_params = fn_def.params.len();
let hash_script = crate::calc_script_fn_hash(empty(), &fn_def.name, num_params);
@@ -289,6 +322,7 @@ impl Module {
hash_script,
FuncInfo {
name: fn_def.name.to_string(),
namespace: FnNamespace::Internal,
access: fn_def.access,
params: num_params,
types: None,
@@ -307,7 +341,7 @@ impl Module {
name: &str,
num_params: usize,
public_only: bool,
) -> Option<&Shared<crate::ast::ScriptFnDef>> {
) -> Option<&SharedScriptFnDef> {
self.functions
.values()
.find(
@@ -439,6 +473,7 @@ impl Module {
pub fn set_fn(
&mut self,
name: impl Into<String>,
namespace: FnNamespace,
access: FnAccess,
arg_types: &[TypeId],
func: CallableFunction,
@@ -463,6 +498,7 @@ impl Module {
hash_fn,
FuncInfo {
name,
namespace,
access,
params: params.len(),
types: Some(params),
@@ -506,10 +542,11 @@ impl Module {
/// # Example
///
/// ```
/// use rhai::Module;
/// use rhai::{Module, FnNamespace, FnAccess};
///
/// let mut module = Module::new();
/// let hash = module.set_raw_fn("double_or_not",
/// FnNamespace::Internal, FnAccess::Public,
/// // Pass parameter types via a slice with TypeId's
/// &[std::any::TypeId::of::<i64>(), std::any::TypeId::of::<bool>()],
/// // Fixed closure signature
@@ -538,6 +575,8 @@ impl Module {
pub fn set_raw_fn<T: Variant + Clone>(
&mut self,
name: impl Into<String>,
namespace: FnNamespace,
access: FnAccess,
arg_types: &[TypeId],
func: impl Fn(NativeCallContext, &mut FnCallArgs) -> Result<T, Box<EvalAltResult>>
+ SendSync
@@ -545,14 +584,40 @@ impl Module {
) -> u64 {
let f =
move |ctx: NativeCallContext, args: &mut FnCallArgs| func(ctx, args).map(Dynamic::from);
self.set_fn(
name,
FnAccess::Public,
namespace,
access,
arg_types,
CallableFunction::from_method(Box::new(f)),
)
}
/// Get the namespace of a registered function.
/// Returns `None` if a function with the hash does not exist.
///
/// The `u64` hash is calculated by the function `crate::calc_native_fn_hash`.
#[inline(always)]
pub fn get_fn_namespace(&self, hash: u64) -> Option<FnNamespace> {
self.functions.get(&hash).map(|f| f.namespace)
}
/// Set the namespace of a registered function.
/// Returns the original namespace or `None` if a function with the hash does not exist.
///
/// The `u64` hash is calculated by the function `crate::calc_native_fn_hash`.
#[inline]
pub fn set_fn_namespace(&mut self, hash: u64, namespace: FnNamespace) -> Option<FnNamespace> {
if let Some(f) = self.functions.get_mut(&hash) {
let old_ns = f.namespace;
f.namespace = namespace;
Some(old_ns)
} else {
None
}
}
/// Set a Rust function taking no parameters into the module, returning a hash key.
///
/// If there is a similar existing Rust function, it is replaced.
@@ -576,6 +641,7 @@ impl Module {
let arg_types = [];
self.set_fn(
name,
FnNamespace::Internal,
FnAccess::Public,
&arg_types,
CallableFunction::from_pure(Box::new(f)),
@@ -607,6 +673,7 @@ impl Module {
let arg_types = [TypeId::of::<A>()];
self.set_fn(
name,
FnNamespace::Internal,
FnAccess::Public,
&arg_types,
CallableFunction::from_pure(Box::new(f)),
@@ -638,6 +705,7 @@ impl Module {
let arg_types = [TypeId::of::<A>()];
self.set_fn(
name,
FnNamespace::Internal,
FnAccess::Public,
&arg_types,
CallableFunction::from_method(Box::new(f)),
@@ -697,6 +765,7 @@ impl Module {
let arg_types = [TypeId::of::<A>(), TypeId::of::<B>()];
self.set_fn(
name,
FnNamespace::Internal,
FnAccess::Public,
&arg_types,
CallableFunction::from_pure(Box::new(f)),
@@ -734,6 +803,7 @@ impl Module {
let arg_types = [TypeId::of::<A>(), TypeId::of::<B>()];
self.set_fn(
name,
FnNamespace::Internal,
FnAccess::Public,
&arg_types,
CallableFunction::from_method(Box::new(f)),
@@ -847,6 +917,7 @@ impl Module {
let arg_types = [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>()];
self.set_fn(
name,
FnNamespace::Internal,
FnAccess::Public,
&arg_types,
CallableFunction::from_pure(Box::new(f)),
@@ -890,6 +961,7 @@ impl Module {
let arg_types = [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>()];
self.set_fn(
name,
FnNamespace::Internal,
FnAccess::Public,
&arg_types,
CallableFunction::from_method(Box::new(f)),
@@ -948,6 +1020,7 @@ impl Module {
let arg_types = [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>()];
self.set_fn(
crate::engine::FN_IDX_SET,
FnNamespace::Internal,
FnAccess::Public,
&arg_types,
CallableFunction::from_method(Box::new(f)),
@@ -1038,6 +1111,7 @@ impl Module {
];
self.set_fn(
name,
FnNamespace::Internal,
FnAccess::Public,
&arg_types,
CallableFunction::from_pure(Box::new(f)),
@@ -1088,6 +1162,7 @@ impl Module {
];
self.set_fn(
name,
FnNamespace::Internal,
FnAccess::Public,
&arg_types,
CallableFunction::from_method(Box::new(f)),
@@ -1195,14 +1270,14 @@ impl Module {
/// Merge another module into this module.
#[inline(always)]
pub fn merge(&mut self, other: &Self) -> &mut Self {
self.merge_filtered(other, &mut |_, _, _| true)
self.merge_filtered(other, &mut |_, _, _, _, _| true)
}
/// Merge another module into this module, with only selected script-defined functions based on a filter predicate.
/// Merge another module into this module based on a filter predicate.
pub(crate) fn merge_filtered(
&mut self,
other: &Self,
mut _filter: &mut impl FnMut(FnAccess, &str, usize) -> bool,
mut _filter: &mut impl FnMut(FnNamespace, FnAccess, bool, &str, usize) -> bool,
) -> &mut Self {
#[cfg(not(feature = "no_function"))]
other.modules.iter().for_each(|(k, v)| {
@@ -1220,13 +1295,27 @@ impl Module {
other
.functions
.iter()
.filter(|(_, FuncInfo { func, .. })| match func {
#[cfg(not(feature = "no_function"))]
CallableFunction::Script(f) => {
_filter(f.access, f.name.as_str(), f.params.len())
}
_ => true,
})
.filter(
|(
_,
FuncInfo {
namespace,
access,
name,
params,
func,
..
},
)| {
_filter(
*namespace,
*access,
func.is_script(),
name.as_str(),
*params,
)
},
)
.map(|(&k, v)| (k, v.clone())),
);
@@ -1238,18 +1327,30 @@ impl Module {
self
}
/// Filter out the functions, retaining only some based on a filter predicate.
/// Filter out the functions, retaining only some script-defined functions based on a filter predicate.
#[cfg(not(feature = "no_function"))]
#[inline]
pub(crate) fn retain_functions(
pub(crate) fn retain_script_functions(
&mut self,
mut filter: impl FnMut(FnAccess, &str, usize) -> bool,
mut filter: impl FnMut(FnNamespace, FnAccess, &str, usize) -> bool,
) -> &mut Self {
self.functions
.retain(|_, FuncInfo { func, .. }| match func {
CallableFunction::Script(f) => filter(f.access, f.name.as_str(), f.params.len()),
_ => true,
});
self.functions.retain(
|_,
FuncInfo {
namespace,
access,
name,
params,
func,
..
}| {
if func.is_script() {
filter(*namespace, *access, name.as_str(), *params)
} else {
false
}
},
);
self.all_functions.clear();
self.all_variables.clear();
@@ -1293,16 +1394,25 @@ impl Module {
#[inline(always)]
pub(crate) fn iter_script_fn<'a>(
&'a self,
) -> impl Iterator<Item = (FnAccess, &str, usize, Shared<crate::ast::ScriptFnDef>)> + 'a {
self.functions
.values()
.map(|f| &f.func)
.filter(|f| f.is_script())
.map(CallableFunction::get_fn_def)
.map(|f| {
let func = f.clone();
(f.access, f.name.as_str(), f.params.len(), func)
})
) -> impl Iterator<Item = (FnNamespace, FnAccess, &str, usize, SharedScriptFnDef)> + 'a {
self.functions.values().filter(|f| f.func.is_script()).map(
|FuncInfo {
namespace,
access,
name,
params,
func,
..
}| {
(
*namespace,
*access,
name.as_str(),
*params,
func.get_fn_def().clone(),
)
},
)
}
/// Get an iterator over all script-defined functions in the module.
@@ -1314,14 +1424,17 @@ impl Module {
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "internals"))]
#[inline(always)]
pub fn iter_script_fn_info(&self) -> impl Iterator<Item = (FnAccess, &str, usize)> {
pub fn iter_script_fn_info(
&self,
) -> impl Iterator<Item = (FnNamespace, FnAccess, &str, usize)> {
self.functions.values().filter(|f| f.func.is_script()).map(
|FuncInfo {
name,
namespace,
access,
params,
..
}| (*access, name.as_str(), *params),
}| (*namespace, *access, name.as_str(), *params),
)
}
@@ -1338,7 +1451,7 @@ impl Module {
#[inline(always)]
pub fn iter_script_fn_info(
&self,
) -> impl Iterator<Item = (FnAccess, &str, usize, Shared<crate::ast::ScriptFnDef>)> {
) -> impl Iterator<Item = (FnNamespace, FnAccess, &str, usize, SharedScriptFnDef)> {
self.iter_script_fn()
}
@@ -1392,13 +1505,10 @@ impl Module {
// Extra modules left in the scope become sub-modules
let mut func_mods: crate::engine::Imports = Default::default();
mods.into_iter()
.skip(orig_mods_len)
.filter(|&(_, fixed, _)| !fixed)
.for_each(|(alias, _, m)| {
func_mods.push(alias.clone(), m.clone());
module.set_sub_module(alias, m);
});
mods.into_iter().skip(orig_mods_len).for_each(|(alias, m)| {
func_mods.push(alias.clone(), m.clone());
module.set_sub_module(alias, m);
});
// Non-private functions defined become module functions
#[cfg(not(feature = "no_function"))]
@@ -1406,8 +1516,8 @@ impl Module {
let ast_lib: Shared<Module> = ast.lib().clone().into();
ast.iter_functions()
.filter(|(access, _, _, _)| !access.is_private())
.for_each(|(_, _, _, func)| {
.filter(|(_, access, _, _, _)| !access.is_private())
.for_each(|(_, _, _, _, func)| {
// Encapsulate AST environment
let mut func = func.as_ref().clone();
func.lib = Some(ast_lib.clone());
@@ -1463,6 +1573,7 @@ impl Module {
&hash,
FuncInfo {
name,
namespace,
params,
types,
func,
@@ -1470,22 +1581,20 @@ impl Module {
},
)| {
// Flatten all methods so they can be available without namespace qualifiers
#[cfg(not(feature = "no_object"))]
if func.is_method() {
if namespace.is_global() {
functions.insert(hash, func.clone());
}
// Qualifiers + function name + number of arguments.
let hash_qualified_script =
crate::calc_script_fn_hash(qualifiers.iter().cloned(), name, *params);
if let Some(param_types) = types {
assert_eq!(*params, param_types.len());
// 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 = 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 = crate::calc_native_fn_hash(
@@ -1498,17 +1607,6 @@ impl Module {
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.
crate::calc_script_fn_hash(
qualifiers.iter().map(|&v| v),
&name,
*params,
)
};
functions.insert(hash_qualified_script, func.clone());
}
},

View File

@@ -25,8 +25,8 @@ use crate::syntax::CustomSyntax;
use crate::token::{is_keyword_function, is_valid_identifier, Token, TokenStream};
use crate::utils::{get_hasher, StraightHasherBuilder};
use crate::{
calc_script_fn_hash, Dynamic, Engine, ImmutableString, LexError, ParseError, ParseErrorType,
Position, Scope, StaticVec, AST, NO_POS,
calc_script_fn_hash, Dynamic, Engine, FnAccess, ImmutableString, LexError, ParseError,
ParseErrorType, Position, Scope, StaticVec, AST, NO_POS,
};
#[cfg(not(feature = "no_float"))]
@@ -2371,9 +2371,9 @@ fn parse_stmt(
Token::Fn | Token::Private => {
let access = if matches!(token, Token::Private) {
eat_token(input, Token::Private);
crate::ast::FnAccess::Private
FnAccess::Private
} else {
crate::ast::FnAccess::Public
FnAccess::Public
};
match input.next().unwrap() {
@@ -2554,7 +2554,7 @@ fn parse_fn(
input: &mut TokenStream,
state: &mut ParseState,
lib: &mut FunctionsLib,
access: crate::ast::FnAccess,
access: FnAccess,
mut settings: ParseSettings,
) -> Result<ScriptFnDef, ParseError> {
#[cfg(not(feature = "unchecked"))]
@@ -2789,7 +2789,7 @@ fn parse_anon_fn(
// Define the function
let script = ScriptFnDef {
name: fn_name.clone(),
access: crate::ast::FnAccess::Public,
access: FnAccess::Public,
params,
#[cfg(not(feature = "no_closure"))]
externals: Default::default(),

View File

@@ -1,11 +1,10 @@
//! Module defining macros for developing _plugins_.
pub use crate::ast::FnAccess;
pub use crate::fn_native::{CallableFunction, FnCallArgs};
pub use crate::stdlib::{any::TypeId, boxed::Box, format, mem, string::ToString, vec as new_vec};
pub use crate::{
Dynamic, Engine, EvalAltResult, ImmutableString, Module, NativeCallContext, RegisterFn,
RegisterResultFn,
Dynamic, Engine, EvalAltResult, FnAccess, FnNamespace, ImmutableString, Module,
NativeCallContext, RegisterFn, RegisterResultFn,
};
#[cfg(not(features = "no_module"))]

View File

@@ -105,15 +105,17 @@ pub fn get_hasher() -> impl Hasher {
///
/// The first module name is skipped. Hashing starts from the _second_ module in the chain.
fn calc_fn_hash<'a>(
modules: impl Iterator<Item = &'a str>,
mut modules: impl Iterator<Item = &'a str>,
fn_name: &str,
num: Option<usize>,
params: impl Iterator<Item = TypeId>,
) -> u64 {
let s = &mut get_hasher();
// Hash a boolean indicating whether the hash is namespace-qualified.
modules.next().is_some().hash(s);
// We always skip the first module
modules.skip(1).for_each(|m| m.hash(s));
modules.for_each(|m| m.hash(s));
s.write(fn_name.as_bytes());
if let Some(num) = num {
s.write_usize(num);