Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ rhai_codegen = { version = "3.1.0", path = "codegen" }

no-std-compat = { git = "https://gitlab.com/jD91mZM2/no-std-compat.git", version = "0.4.1", default-features = false, features = ["alloc"], optional = true }
libm = { version = "0.2.0", default-features = false, optional = true }
hashbrown = { version = "0.15.0", optional = true }
hashbrown = { version = "0.15.0" }
core-error = { version = "0.0.0", default-features = false, features = ["alloc"], optional = true }
serde = { version = "1.0.136", default-features = false, features = ["derive", "alloc"], optional = true }
serde_json = { version = "1.0.45", default-features = false, features = ["alloc"], optional = true }
Expand Down Expand Up @@ -113,7 +113,7 @@ no_optimize = []
#! ### Compiling for `no-std`

## Turn on `no-std` compilation (nightly only).
no_std = ["no-std-compat", "num-traits/libm", "core-error", "libm", "hashbrown", "no_time"]
no_std = ["no-std-compat", "num-traits/libm", "core-error", "libm", "no_time"]

#! ### JavaScript Interface for WASM

Expand Down
43 changes: 21 additions & 22 deletions src/api/call_fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ impl Engine {

let orig_tag = options.tag.map(|v| mem::replace(&mut global.tag, v));

let mut this_ptr = options.this_ptr;
let this_ptr = options.this_ptr;

#[cfg(not(feature = "no_module"))]
let orig_embedded_module_resolver =
Expand Down Expand Up @@ -259,28 +259,27 @@ impl Engine {
#[cfg(not(feature = "no_closure"))]
crate::func::ensure_no_data_race(name, args, false)?;

ast.shared_lib()
.get_script_fn(name, args.len())
.map_or_else(
|| Err(ERR::ErrorFunctionNotFound(name.into(), Position::NONE).into()),
|fn_def| {
self.call_script_fn(
global,
caches,
scope,
this_ptr.as_deref_mut(),
None,
fn_def,
args,
rewind_scope,
Position::NONE,
)
if let Some(fn_def) = ast.shared_lib().get_script_fn(name, args.len()) {
match self.call_script_fn(
global,
caches,
scope,
this_ptr,
None,
fn_def,
args,
rewind_scope,
Position::NONE,
) {
Ok(val) => Ok(val),
Err(err) => match *err {
ERR::Exit(out, ..) => Ok(out),
_ => Err(err),
},
)
.or_else(|err| match *err {
ERR::Exit(out, ..) => Ok(out),
_ => Err(err),
})
}
} else {
Err(ERR::ErrorFunctionNotFound(name.into(), Position::NONE).into())
}
});

#[cfg(feature = "debugging")]
Expand Down
26 changes: 13 additions & 13 deletions src/api/formatting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,20 +203,20 @@ impl Engine {
#[inline]
#[must_use]
pub fn map_type_name<'a>(&'a self, name: &'a str) -> &'a str {
self.global_modules
.iter()
.find_map(|m| m.get_custom_type_display_by_name(name))
.or_else(|| {
#[cfg(not(feature = "no_module"))]
return self
.global_sub_modules
.values()
.find_map(|m| m.get_custom_type_display_by_name(name));
for m in &self.global_modules {
if let Some(val) = m.get_custom_type_display_by_name(name) {
return val;
}
}

#[cfg(not(feature = "no_module"))]
for m in self.global_sub_modules.values() {
if let Some(val) = m.get_custom_type_display_by_name(name) {
return val;
}
}

#[cfg(feature = "no_module")]
return None;
})
.unwrap_or_else(|| map_std_type_name(name, true))
map_std_type_name(name, true)
}

/// Format a Rust parameter type.
Expand Down
14 changes: 7 additions & 7 deletions src/eval/data_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,12 +194,12 @@ impl Engine {
return Err(ERR::ErrorTooManyOperations(pos).into());
}

self.progress
.as_ref()
.and_then(|progress| {
progress(global.num_operations)
.map(|token| Err(ERR::ErrorTerminated(token, pos).into()))
})
.unwrap_or(Ok(()))
if let Some(progress) = &self.progress {
if let Some(token) = progress(global.num_operations) {
return Err(ERR::ErrorTerminated(token, pos).into());
}
}

Ok(())
}
}
62 changes: 37 additions & 25 deletions src/func/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ use crate::{
calc_fn_hash, calc_fn_hash_full, Dynamic, Engine, FnArgsVec, FnPtr, ImmutableString, Position,
RhaiResult, RhaiResultOf, Scope, Shared, ERR,
};
#[cfg(feature = "no_std")]
use hashbrown::hash_map::Entry;
#[cfg(not(feature = "no_std"))]
use std::collections::hash_map::Entry;
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{
Expand Down Expand Up @@ -170,9 +167,11 @@ impl Engine {
args: Option<&mut FnCallArgs>,
allow_dynamic: bool,
) -> Option<&'s FnResolutionCacheEntry> {
let mut hash = args.as_deref().map_or(hash_base, |args| {
let mut hash = if let Some(args) = &args {
calc_fn_hash_full(hash_base, args.iter().map(|a| a.type_id()))
});
} else {
hash_base
};

let cache = caches.fn_resolution_cache_mut();

Expand All @@ -185,33 +184,46 @@ impl Engine {
let mut bitmask = 1usize; // Bitmask of which parameter to replace with `Dynamic`

loop {
let mut func = None;
// First check scripted functions in the AST or embedded environments
#[cfg(not(feature = "no_function"))]
let func = _global
.lib
.iter()
.rev()
.find_map(|m| m.get_fn(hash).map(|f| (f, m.id_raw())));
#[cfg(feature = "no_function")]
let func = None;
{
for m in 0.._global.lib.len() {
let m = &_global.lib[_global.lib.len() - m - 1];
if let Some(f) = m.get_fn(hash) {
func = Some((f, m.id_raw()));
break;
}
}
}

// Then check the global namespace
let func = func.or_else(|| {
self.global_modules
.iter()
.find_map(|m| m.get_fn(hash).map(|f| (f, m.id_raw())))
});
if func.is_none() {
for m in 0..self.global_modules.len() {
let m = &self.global_modules[self.global_modules.len() - m - 1];
if let Some(f) = m.get_fn(hash) {
func = Some((f, m.id_raw()));
break;
}
}
}

// Then check imported modules for global functions, then global sub-modules for global functions
#[cfg(not(feature = "no_module"))]
let func = func
.or_else(|| _global.get_qualified_fn(hash, true))
.or_else(|| {
self.global_sub_modules
.values()
.filter(|m| m.contains_indexed_global_functions())
.find_map(|m| m.get_qualified_fn(hash).map(|f| (f, m.id_raw())))
});
if func.is_none() {
if let Some(val) = _global.get_qualified_fn(hash, true) {
func = Some(val);
} else {
for m in self.global_sub_modules.values() {
if m.contains_indexed_global_functions() {
if let Some(f) = m.get_qualified_fn(hash) {
func = Some((f, m.id_raw()));
break;
}
}
}
}
}

if let Some((f, s)) = func {
// Specific version found
Expand Down
2 changes: 1 addition & 1 deletion src/func/func_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

#![allow(non_snake_case)]

use crate::types::dynamic::Variant;
use crate::types::dynamic::{AccessMode, Union, Variant};
use crate::Dynamic;
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
Expand Down
3 changes: 0 additions & 3 deletions src/func/hashing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,8 @@ use std::{
hash::{BuildHasher, Hash, Hasher},
};

#[cfg(feature = "no_std")]
pub type StraightHashMap<V> = hashbrown::HashMap<u64, V, StraightHasherBuilder>;

#[cfg(not(feature = "no_std"))]
pub type StraightHashMap<V> = std::collections::HashMap<u64, V, StraightHasherBuilder>;
/// A hasher that only takes one single [`u64`] and returns it as a hash key.
///
/// # Panics
Expand Down
7 changes: 3 additions & 4 deletions src/func/script.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl Engine {
global: &mut GlobalRuntimeState,
caches: &mut Caches,
scope: &mut Scope,
mut this_ptr: Option<&mut Dynamic>,
this_ptr: Option<&mut Dynamic>,
_env: Option<&EncapsulatedEnviron>,
fn_def: &ScriptFuncDef,
args: &mut FnCallArgs,
Expand Down Expand Up @@ -102,8 +102,7 @@ impl Engine {
}| {
imports
.iter()
.cloned()
.for_each(|(n, m)| global.push_import(n, m));
.for_each(|(n, m)| global.push_import(n, m.clone()));

global.lib.extend(lib.clone());

Expand All @@ -123,7 +122,7 @@ impl Engine {
global,
caches,
scope,
this_ptr.as_deref_mut(),
this_ptr,
fn_def.body.statements(),
rewind_scope,
)
Expand Down
23 changes: 13 additions & 10 deletions src/module/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@ use crate::{
Identifier, ImmutableString, RhaiResultOf, Shared, SharedModule, SmartString,
};
use bitflags::bitflags;
#[cfg(feature = "no_std")]
use hashbrown::hash_map::Entry;
#[cfg(not(feature = "no_std"))]
use std::collections::hash_map::Entry;
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{
Expand Down Expand Up @@ -1028,11 +1025,14 @@ impl Module {
///
/// assert_eq!(module.get_custom_type_display_by_name(name), Some("MyType"));
/// ```
#[inline]
#[inline(always)]
#[must_use]
pub fn get_custom_type_display_by_name(&self, type_name: &str) -> Option<&str> {
self.get_custom_type_by_name_raw(type_name)
.map(|typ| typ.display_name.as_str())
if let Some(typ) = self.get_custom_type_by_name_raw(type_name) {
Some(typ.display_name.as_str())
} else {
None
}
}
/// Get the display name of a registered custom type.
///
Expand Down Expand Up @@ -1912,10 +1912,13 @@ impl Module {
#[inline]
#[must_use]
pub(crate) fn get_fn(&self, hash_native: u64) -> Option<&RhaiFunc> {
self.functions
.as_ref()
.and_then(|m| m.get(&hash_native))
.map(|(f, _)| f)
if let Some(funcs) = &self.functions {
if let Some(func) = funcs.get(&hash_native) {
return Some(&func.0);
}
}

None
}

/// Can the particular function with [`Dynamic`] parameter(s) exist in the [`Module`]?
Expand Down
2 changes: 1 addition & 1 deletion src/packages/time_basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ mod time_functions {
#[inline]
fn subtract_impl(timestamp: Instant, seconds: INT) -> RhaiResultOf<Instant> {
if seconds < 0 {
add_inner(timestamp, u64::try_from(seconds.unsigned_abs()).unwrap())
add_inner(timestamp, seconds.unsigned_abs())
} else {
subtract_inner(timestamp, u64::try_from(seconds).unwrap())
}
Expand Down
28 changes: 11 additions & 17 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3658,23 +3658,17 @@ impl Engine {

args.push(fn_expr);

args.extend(
externals
.as_ref()
.iter()
.cloned()
.map(|Ident { name, pos }| {
let (index, is_func) = self.access_var(state, &name, pos);
let idx = match index {
Some(n) if !is_func => u8::try_from(n.get()).ok().and_then(NonZeroU8::new),
_ => None,
};
#[cfg(not(feature = "no_module"))]
return Expr::Variable((index, name, <_>::default(), 0).into(), idx, pos);
#[cfg(feature = "no_module")]
return Expr::Variable((index, name).into(), idx, pos);
}),
);
args.extend(externals.as_ref().iter().map(|Ident { name, pos }| {
let (index, is_func) = self.access_var(state, name, *pos);
let idx = match index {
Some(n) if !is_func => u8::try_from(n.get()).ok().and_then(NonZeroU8::new),
_ => None,
};
#[cfg(not(feature = "no_module"))]
return Expr::Variable((index, name.clone(), <_>::default(), 0).into(), idx, *pos);
#[cfg(feature = "no_module")]
return Expr::Variable((index, name.clone()).into(), idx, pos);
}));

let expr = FnCallExpr {
#[cfg(not(feature = "no_module"))]
Expand Down
8 changes: 2 additions & 6 deletions src/types/dynamic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1403,11 +1403,7 @@ impl Dynamic {
#[cfg(not(feature = "no_closure"))]
reify! { value => |v: crate::Shared<crate::Locked<Self>>| return v.into() }

Self(Union::Variant(
Box::new(Box::new(value)),
DEFAULT_TAG_VALUE,
ReadWrite,
))
Self(Union::Variant(Box::new(Box::new(value)), 0, ReadWrite))
}
/// Turn the [`Dynamic`] value into a shared [`Dynamic`] value backed by an
/// [`Rc<RefCell<Dynamic>>`][std::rc::Rc] or [`Arc<RwLock<Dynamic>>`][std::sync::Arc]
Expand Down Expand Up @@ -1594,7 +1590,7 @@ impl Dynamic {

match self.0 {
Union::Variant(v, ..) if TypeId::of::<T>() == (**v).type_id() => {
Ok((*v).as_boxed_any().downcast().map(|x| *x).unwrap())
Ok(*(*v).as_boxed_any().downcast().unwrap())
}
_ => Err(self),
}
Expand Down
3 changes: 0 additions & 3 deletions src/types/interner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@
use super::BloomFilterU64;
use crate::func::{hashing::get_hasher, StraightHashMap};
use crate::ImmutableString;
#[cfg(feature = "no_std")]
use hashbrown::hash_map::Entry;
#[cfg(not(feature = "no_std"))]
use std::collections::hash_map::Entry;
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{
Expand Down
Loading