Merge pull request #579 from schungx/master

Version 1.8.0.
This commit is contained in:
Stephen Chung 2022-07-01 12:50:21 +08:00 committed by GitHub
commit 60e36610bc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
31 changed files with 535 additions and 597 deletions

View File

@ -19,7 +19,7 @@ Bug fixes
Reserved Symbols Reserved Symbols
---------------- ----------------
* `?`, `??`, `?.` and `!.` are now reserved symbols. * `?`, `??`, `?.`, `?[` and `!.` are now reserved symbols.
Deprecated API's Deprecated API's
---------------- ----------------
@ -29,7 +29,7 @@ Deprecated API's
New features New features
------------ ------------
* The _Elvis operator_ (`?.`) is now supported for property access and method calls. * The _Elvis operators_ (`?.` and `?[`) are now supported for property access, method calls and indexing.
* The _null-coalescing operator_ (`??`) is now supported to short-circuit `()` values. * The _null-coalescing operator_ (`??`) is now supported to short-circuit `()` values.
Enhancements Enhancements
@ -41,6 +41,7 @@ Enhancements
* Originally, the debugger's custom state uses the same state as `EvalState::tag()` (which is the same as `NativeCallContext::tag()`). It is now split into its own variable accessible under `Debugger::state()`. * Originally, the debugger's custom state uses the same state as `EvalState::tag()` (which is the same as `NativeCallContext::tag()`). It is now split into its own variable accessible under `Debugger::state()`.
* Non-borrowed string keys can now be deserialized for object maps via `serde`. * Non-borrowed string keys can now be deserialized for object maps via `serde`.
* `Scope::get` is added to get a reference to a variable's value. * `Scope::get` is added to get a reference to a variable's value.
* Variable resolvers can now return a _shared_ value which can be mutated.
Version 1.7.0 Version 1.7.0

View File

@ -3,7 +3,7 @@ members = [".", "codegen"]
[package] [package]
name = "rhai" name = "rhai"
version = "1.7.0" version = "1.8.0"
rust-version = "1.57" rust-version = "1.57"
edition = "2018" edition = "2018"
authors = ["Jonathan Turner", "Lukáš Hozda", "Stephen Chung", "jhwgh1968"] authors = ["Jonathan Turner", "Lukáš Hozda", "Stephen Chung", "jhwgh1968"]

View File

@ -1,7 +1,7 @@
//! Module implementing custom syntax for [`Engine`]. //! Module implementing custom syntax for [`Engine`].
use crate::ast::Expr; use crate::ast::Expr;
use crate::func::native::SendSync; use crate::func::SendSync;
use crate::parser::ParseResult; use crate::parser::ParseResult;
use crate::tokenizer::{is_valid_identifier, Token}; use crate::tokenizer::{is_valid_identifier, Token};
use crate::types::dynamic::Variant; use crate::types::dynamic::Variant;

View File

@ -56,12 +56,7 @@ impl Engine {
.shared_lib() .shared_lib()
.iter_fn() .iter_fn()
.filter(|f| f.func.is_script()) .filter(|f| f.func.is_script())
.map(|f| { .map(|f| f.func.get_script_fn_def().unwrap().clone())
f.func
.get_script_fn_def()
.expect("script-defined function")
.clone()
})
.collect(); .collect();
crate::optimizer::optimize_into_ast( crate::optimizer::optimize_into_ast(

View File

@ -123,9 +123,7 @@ impl Engine {
let param_type_names: crate::StaticVec<_> = F::param_names() let param_type_names: crate::StaticVec<_> = F::param_names()
.iter() .iter()
.map(|ty| format!("_: {}", self.format_type_name(ty))) .map(|ty| format!("_: {}", self.format_type_name(ty)))
.chain(std::iter::once( .chain(Some(self.format_type_name(F::return_type_name()).into()))
self.format_type_name(F::return_type_name()).into(),
))
.collect(); .collect();
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
@ -993,7 +991,7 @@ impl Engine {
if !name.contains(separator.as_ref()) { if !name.contains(separator.as_ref()) {
if !module.is_indexed() { if !module.is_indexed() {
// Index the module (making a clone copy if necessary) if it is not indexed // Index the module (making a clone copy if necessary) if it is not indexed
let mut module = crate::func::native::shared_take_or_clone(module); let mut module = crate::func::shared_take_or_clone(module);
module.build_index(); module.build_index();
root.insert(name.into(), module.into()); root.insert(name.into(), module.into());
} else { } else {
@ -1011,7 +1009,7 @@ impl Engine {
root.insert(sub_module.into(), m.into()); root.insert(sub_module.into(), m.into());
} else { } else {
let m = root.remove(sub_module).expect("contains sub-module"); let m = root.remove(sub_module).expect("contains sub-module");
let mut m = crate::func::native::shared_take_or_clone(m); let mut m = crate::func::shared_take_or_clone(m);
register_static_module_raw(m.sub_modules_mut(), remainder, module); register_static_module_raw(m.sub_modules_mut(), remainder, module);
m.build_index(); m.build_index();
root.insert(sub_module.into(), m.into()); root.insert(sub_module.into(), m.into());

View File

@ -86,7 +86,7 @@ fn map_std_type_name(name: &str, shorthands: bool) -> &str {
} }
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
if name == type_name::<crate::packages::iter_basic::float::StepFloatRange>() { if name == type_name::<crate::packages::iter_basic::StepRange<crate::FLOAT>>() {
return if shorthands { return if shorthands {
"range" "range"
} else { } else {
@ -94,7 +94,7 @@ fn map_std_type_name(name: &str, shorthands: bool) -> &str {
}; };
} }
#[cfg(feature = "decimal")] #[cfg(feature = "decimal")]
if name == type_name::<crate::packages::iter_basic::decimal::StepDecimalRange>() { if name == type_name::<crate::packages::iter_basic::StepRange<rust_decimal::Decimal>>() {
return if shorthands { return if shorthands {
"range" "range"
} else { } else {

View File

@ -615,8 +615,7 @@ impl AST {
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
if !other.lib.is_empty() { if !other.lib.is_empty() {
crate::func::native::shared_make_mut(&mut self.lib) crate::func::shared_make_mut(&mut self.lib).merge_filtered(&other.lib, &_filter);
.merge_filtered(&other.lib, &_filter);
} }
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
@ -629,10 +628,8 @@ impl AST {
self.set_resolver(other.resolver.unwrap()); self.set_resolver(other.resolver.unwrap());
} }
(_, _) => { (_, _) => {
let resolver = let resolver = crate::func::shared_make_mut(self.resolver.as_mut().unwrap());
crate::func::native::shared_make_mut(self.resolver.as_mut().unwrap()); let other_resolver = crate::func::shared_take_or_clone(other.resolver.unwrap());
let other_resolver =
crate::func::native::shared_take_or_clone(other.resolver.unwrap());
for (k, v) in other_resolver { for (k, v) in other_resolver {
resolver.insert(k, crate::func::shared_take_or_clone(v)); resolver.insert(k, crate::func::shared_take_or_clone(v));
} }
@ -673,7 +670,7 @@ impl AST {
filter: impl Fn(FnNamespace, FnAccess, &str, usize) -> bool, filter: impl Fn(FnNamespace, FnAccess, &str, usize) -> bool,
) -> &mut Self { ) -> &mut Self {
if !self.lib.is_empty() { if !self.lib.is_empty() {
crate::func::native::shared_make_mut(&mut self.lib).retain_script_functions(filter); crate::func::shared_make_mut(&mut self.lib).retain_script_functions(filter);
} }
self self
} }

View File

@ -411,6 +411,7 @@ pub enum Expr {
/// ///
/// ### Flags /// ### Flags
/// ///
/// [`NEGATED`][ASTFlags::NEGATED] = `?[` ... `]` (`[` ... `]` if unset)
/// [`BREAK`][ASTFlags::BREAK] = terminate the chain (recurse into the chain if unset) /// [`BREAK`][ASTFlags::BREAK] = terminate the chain (recurse into the chain if unset)
Index(Box<BinaryExpr>, ASTFlags, Position), Index(Box<BinaryExpr>, ASTFlags, Position),
/// lhs `&&` rhs /// lhs `&&` rhs
@ -827,7 +828,7 @@ impl Expr {
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Token::Period | Token::Elvis => return true, Token::Period | Token::Elvis => return true,
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Token::LeftBracket => return true, Token::LeftBracket | Token::QuestionBracket => return true,
_ => (), _ => (),
} }

View File

@ -60,6 +60,11 @@ impl Engine {
match chain_type { match chain_type {
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
ChainType::Indexing => { ChainType::Indexing => {
// Check for existence with the null conditional operator
if _parent_options.contains(ASTFlags::NEGATED) && target.is::<()>() {
return Ok((Dynamic::UNIT, false));
}
let pos = rhs.start_position(); let pos = rhs.start_position();
match rhs { match rhs {

View File

@ -146,7 +146,7 @@ impl Engine {
let target_is_shared = false; let target_is_shared = false;
if target_is_shared { if target_is_shared {
lock_guard = target.write_lock::<Dynamic>().expect("`Dynamic`"); lock_guard = target.write_lock::<Dynamic>().unwrap();
lhs_ptr_inner = &mut *lock_guard; lhs_ptr_inner = &mut *lock_guard;
} else { } else {
lhs_ptr_inner = &mut *target; lhs_ptr_inner = &mut *target;
@ -181,7 +181,20 @@ impl Engine {
} }
} else { } else {
// Normal assignment // Normal assignment
*target.as_mut() = new_val;
#[cfg(not(feature = "no_closure"))]
if target.is_shared() {
// Handle case where target is a `Dynamic` shared value
// (returned by a variable resolver, for example)
*target.write_lock::<Dynamic>().unwrap() = new_val;
} else {
*target.as_mut() = new_val;
}
#[cfg(feature = "no_closure")]
{
*target.as_mut() = new_val;
}
} }
target.propagate_changed_value(op_info.pos) target.propagate_changed_value(op_info.pos)
@ -250,7 +263,15 @@ impl Engine {
let var_name = lhs.get_variable_name(false).expect("`Expr::Variable`"); let var_name = lhs.get_variable_name(false).expect("`Expr::Variable`");
if !lhs_ptr.is_ref() { #[cfg(not(feature = "no_closure"))]
// Also handle case where target is a `Dynamic` shared value
// (returned by a variable resolver, for example)
let is_temp_result = !lhs_ptr.is_ref() && !lhs_ptr.is_shared();
#[cfg(feature = "no_closure")]
let is_temp_result = !lhs_ptr.is_ref();
// Cannot assign to temp result from expression
if is_temp_result {
return Err( return Err(
ERR::ErrorAssignmentToConstant(var_name.to_string(), pos).into() ERR::ErrorAssignmentToConstant(var_name.to_string(), pos).into()
); );
@ -950,7 +971,7 @@ impl Engine {
if !export.is_empty() { if !export.is_empty() {
if !module.is_indexed() { if !module.is_indexed() {
// Index the module (making a clone copy if necessary) if it is not indexed // Index the module (making a clone copy if necessary) if it is not indexed
let mut m = crate::func::native::shared_take_or_clone(module); let mut m = crate::func::shared_take_or_clone(module);
m.build_index(); m.build_index();
global.push_import(export.name.clone(), m); global.push_import(export.name.clone(), m);
} else { } else {

View File

@ -28,9 +28,9 @@ pub trait FuncArgs {
/// ///
/// impl FuncArgs for Options { /// impl FuncArgs for Options {
/// fn parse<ARGS: Extend<Dynamic>>(self, args: &mut ARGS) { /// fn parse<ARGS: Extend<Dynamic>>(self, args: &mut ARGS) {
/// args.extend(std::iter::once(self.foo.into())); /// args.extend(Some(self.foo.into()));
/// args.extend(std::iter::once(self.bar.into())); /// args.extend(Some(self.bar.into()));
/// args.extend(std::iter::once(self.baz.into())); /// args.extend(Some(self.baz.into()));
/// } /// }
/// } /// }
/// ///

View File

@ -165,7 +165,7 @@ impl Engine {
) )
} }
/// Resolve a function call. /// Resolve a normal (non-qualified) function call.
/// ///
/// Search order: /// Search order:
/// 1) AST - script functions in the AST /// 1) AST - script functions in the AST
@ -201,11 +201,8 @@ impl Engine {
.entry(hash) .entry(hash)
.or_insert_with(|| { .or_insert_with(|| {
let num_args = args.as_ref().map_or(0, |a| a.len()); let num_args = args.as_ref().map_or(0, |a| a.len());
let max_bitmask = if !allow_dynamic { let mut max_bitmask = 0; // One above maximum bitmask based on number of parameters.
0 // Set later when a specific matching function is not found.
} else {
1usize << usize::min(num_args, MAX_DYNAMIC_PARAMETERS)
};
let mut bitmask = 1usize; // Bitmask of which parameter to replace with `Dynamic` let mut bitmask = 1usize; // Bitmask of which parameter to replace with `Dynamic`
loop { loop {
@ -247,62 +244,85 @@ impl Engine {
}) })
}); });
match func { // Specific version found
// Specific version found if let Some(f) = func {
Some(f) => return Some(f), return Some(f);
}
// Stop when all permutations are exhausted // Check `Dynamic` parameters for functions with parameters
None if bitmask >= max_bitmask => { if allow_dynamic && max_bitmask == 0 && num_args > 0 {
if num_args != 2 { let is_dynamic = lib.iter().any(|&m| m.contains_dynamic_fn(hash_script))
return None; || self
} .global_modules
.iter()
.any(|m| m.contains_dynamic_fn(hash_script));
return args.and_then(|args| { #[cfg(not(feature = "no_module"))]
if !is_op_assignment { let is_dynamic = is_dynamic
get_builtin_binary_op_fn(fn_name, &args[0], &args[1]).map(|f| { || _global
FnResolutionCacheEntry { .iter_imports_raw()
func: CallableFunction::from_method( .any(|(_, m)| m.contains_dynamic_fn(hash_script))
Box::new(f) as Box<FnAny> || self
), .global_sub_modules
source: None, .values()
} .any(|m| m.contains_dynamic_fn(hash_script));
})
} else {
let (first_arg, rest_args) = args.split_first().unwrap();
get_builtin_op_assignment_fn(fn_name, *first_arg, rest_args[0]) // Set maximum bitmask when there are dynamic versions of the function
.map(|f| FnResolutionCacheEntry { if is_dynamic {
func: CallableFunction::from_method( max_bitmask = 1usize << usize::min(num_args, MAX_DYNAMIC_PARAMETERS);
Box::new(f) as Box<FnAny>
),
source: None,
})
}
});
}
// Try all permutations with `Dynamic` wildcards
None => {
let hash_params = calc_fn_params_hash(
args.as_ref()
.expect("no permutations")
.iter()
.enumerate()
.map(|(i, a)| {
let mask = 1usize << (num_args - i - 1);
if bitmask & mask != 0 {
// Replace with `Dynamic`
TypeId::of::<Dynamic>()
} else {
a.type_id()
}
}),
);
hash = combine_hashes(hash_script, hash_params);
bitmask += 1;
} }
} }
// Stop when all permutations are exhausted
if bitmask >= max_bitmask {
if num_args != 2 {
return None;
}
return args.and_then(|args| {
if !is_op_assignment {
get_builtin_binary_op_fn(fn_name, &args[0], &args[1]).map(|f| {
FnResolutionCacheEntry {
func: CallableFunction::from_method(
Box::new(f) as Box<FnAny>
),
source: None,
}
})
} else {
let (first_arg, rest_args) = args.split_first().unwrap();
get_builtin_op_assignment_fn(fn_name, *first_arg, rest_args[0]).map(
|f| FnResolutionCacheEntry {
func: CallableFunction::from_method(
Box::new(f) as Box<FnAny>
),
source: None,
},
)
}
});
}
// Try all permutations with `Dynamic` wildcards
let hash_params = calc_fn_params_hash(
args.as_ref()
.expect("no permutations")
.iter()
.enumerate()
.map(|(i, a)| {
let mask = 1usize << (num_args - i - 1);
if bitmask & mask != 0 {
// Replace with `Dynamic`
TypeId::of::<Dynamic>()
} else {
a.type_id()
}
}),
);
hash = combine_hashes(hash_script, hash_params);
bitmask += 1;
} }
}); });
@ -1202,7 +1222,7 @@ impl Engine {
let (mut target, _pos) = let (mut target, _pos) =
self.search_namespace(scope, global, lib, this_ptr, first_expr, level)?; self.search_namespace(scope, global, lib, this_ptr, first_expr, level)?;
if target.as_ref().is_read_only() { if target.is_read_only() {
target = target.into_owned(); target = target.into_owned();
} }

View File

@ -5,7 +5,6 @@ use std::prelude::v1::*;
use std::{ use std::{
any::TypeId, any::TypeId,
hash::{BuildHasher, Hash, Hasher}, hash::{BuildHasher, Hash, Hasher},
iter::empty,
}; };
/// Dummy hash value to map zeros to. This value can be anything. /// Dummy hash value to map zeros to. This value can be anything.
@ -87,12 +86,16 @@ pub fn get_hasher() -> ahash::AHasher {
/// The first module name is skipped. Hashing starts from the _second_ module in the chain. /// The first module name is skipped. Hashing starts from the _second_ module in the chain.
#[inline] #[inline]
#[must_use] #[must_use]
pub fn calc_qualified_var_hash<'a>(modules: impl Iterator<Item = &'a str>, var_name: &str) -> u64 { pub fn calc_qualified_var_hash<'a>(
modules: impl IntoIterator<Item = &'a str>,
var_name: &str,
) -> u64 {
let s = &mut get_hasher(); let s = &mut get_hasher();
// We always skip the first module // We always skip the first module
let mut len = 0; let mut len = 0;
modules modules
.into_iter()
.inspect(|_| len += 1) .inspect(|_| len += 1)
.skip(1) .skip(1)
.for_each(|m| m.hash(s)); .for_each(|m| m.hash(s));
@ -121,7 +124,7 @@ pub fn calc_qualified_var_hash<'a>(modules: impl Iterator<Item = &'a str>, var_n
#[inline] #[inline]
#[must_use] #[must_use]
pub fn calc_qualified_fn_hash<'a>( pub fn calc_qualified_fn_hash<'a>(
modules: impl Iterator<Item = &'a str>, modules: impl IntoIterator<Item = &'a str>,
fn_name: &str, fn_name: &str,
num: usize, num: usize,
) -> u64 { ) -> u64 {
@ -130,6 +133,7 @@ pub fn calc_qualified_fn_hash<'a>(
// We always skip the first module // We always skip the first module
let mut len = 0; let mut len = 0;
modules modules
.into_iter()
.inspect(|_| len += 1) .inspect(|_| len += 1)
.skip(1) .skip(1)
.for_each(|m| m.hash(s)); .for_each(|m| m.hash(s));
@ -154,7 +158,7 @@ pub fn calc_qualified_fn_hash<'a>(
#[inline(always)] #[inline(always)]
#[must_use] #[must_use]
pub fn calc_fn_hash(fn_name: &str, num: usize) -> u64 { pub fn calc_fn_hash(fn_name: &str, num: usize) -> u64 {
calc_qualified_fn_hash(empty(), fn_name, num) calc_qualified_fn_hash(None, fn_name, num)
} }
/// Calculate a non-zero [`u64`] hash key from a list of parameter types. /// Calculate a non-zero [`u64`] hash key from a list of parameter types.
@ -166,10 +170,13 @@ pub fn calc_fn_hash(fn_name: &str, num: usize) -> u64 {
/// If the hash happens to be zero, it is mapped to `DEFAULT_HASH`. /// If the hash happens to be zero, it is mapped to `DEFAULT_HASH`.
#[inline] #[inline]
#[must_use] #[must_use]
pub fn calc_fn_params_hash(params: impl Iterator<Item = TypeId>) -> u64 { pub fn calc_fn_params_hash(params: impl IntoIterator<Item = TypeId>) -> u64 {
let s = &mut get_hasher(); let s = &mut get_hasher();
let mut len = 0; let mut len = 0;
params.inspect(|_| len += 1).for_each(|t| t.hash(s)); params
.into_iter()
.inspect(|_| len += 1)
.for_each(|t| t.hash(s));
len.hash(s); len.hash(s);
match s.finish() { match s.finish() {

View File

@ -22,8 +22,8 @@ pub use hashing::{
combine_hashes, get_hasher, combine_hashes, get_hasher,
}; };
pub use native::{ pub use native::{
locked_write, shared_make_mut, shared_take, shared_take_or_clone, shared_try_take, FnAny, locked_read, locked_write, shared_get_mut, shared_make_mut, shared_take, shared_take_or_clone,
FnPlugin, IteratorFn, Locked, NativeCallContext, SendSync, Shared, shared_try_take, FnAny, FnPlugin, IteratorFn, Locked, NativeCallContext, SendSync, Shared,
}; };
pub use plugin::PluginFunction; pub use plugin::PluginFunction;
pub use register::RegisterNativeFunction; pub use register::RegisterNativeFunction;

View File

@ -11,7 +11,7 @@
//! //!
//! ## Contents of `my_script.rhai` //! ## Contents of `my_script.rhai`
//! //!
//! ```ignore //! ```rhai
//! /// Brute force factorial function //! /// Brute force factorial function
//! fn factorial(x) { //! fn factorial(x) {
//! if x == 1 { return 1; } //! if x == 1 { return 1; }

View File

@ -7,7 +7,7 @@ use crate::func::{
}; };
use crate::types::{dynamic::Variant, CustomTypesCollection}; use crate::types::{dynamic::Variant, CustomTypesCollection};
use crate::{ use crate::{
calc_fn_params_hash, calc_qualified_fn_hash, combine_hashes, Dynamic, Identifier, calc_fn_hash, calc_fn_params_hash, calc_qualified_fn_hash, combine_hashes, Dynamic, Identifier,
ImmutableString, NativeCallContext, RhaiResultOf, Shared, StaticVec, ImmutableString, NativeCallContext, RhaiResultOf, Shared, StaticVec,
}; };
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
@ -17,7 +17,6 @@ use std::{
cmp::Ordering, cmp::Ordering,
collections::{BTreeMap, BTreeSet}, collections::{BTreeMap, BTreeSet},
fmt, fmt,
iter::{empty, once},
ops::{Add, AddAssign}, ops::{Add, AddAssign},
}; };
@ -214,7 +213,7 @@ impl FuncInfo {
/// The first module name is skipped. Hashing starts from the _second_ module in the chain. /// The first module name is skipped. Hashing starts from the _second_ module in the chain.
#[inline] #[inline]
pub fn calc_native_fn_hash<'a>( pub fn calc_native_fn_hash<'a>(
modules: impl Iterator<Item = &'a str>, modules: impl IntoIterator<Item = &'a str>,
fn_name: &str, fn_name: &str,
params: &[TypeId], params: &[TypeId],
) -> u64 { ) -> u64 {
@ -242,11 +241,13 @@ pub struct Module {
variables: BTreeMap<Identifier, Dynamic>, variables: BTreeMap<Identifier, Dynamic>,
/// Flattened collection of all [`Module`] variables, including those in sub-modules. /// Flattened collection of all [`Module`] variables, including those in sub-modules.
all_variables: BTreeMap<u64, Dynamic>, all_variables: BTreeMap<u64, Dynamic>,
/// External Rust functions. /// Functions (both native Rust and scripted).
functions: BTreeMap<u64, Box<FuncInfo>>, functions: BTreeMap<u64, Box<FuncInfo>>,
/// Flattened collection of all external Rust functions, native or scripted. /// Flattened collection of all functions, native Rust and scripted.
/// including those in sub-modules. /// including those in sub-modules.
all_functions: BTreeMap<u64, CallableFunction>, all_functions: BTreeMap<u64, CallableFunction>,
/// Native Rust functions (in scripted hash format) that contain [`Dynamic`] parameters.
dynamic_functions: BTreeSet<u64>,
/// Iterator functions, keyed by the type producing the iterator. /// Iterator functions, keyed by the type producing the iterator.
type_iterators: BTreeMap<TypeId, Shared<IteratorFn>>, type_iterators: BTreeMap<TypeId, Shared<IteratorFn>>,
/// Flattened collection of iterator functions, including those in sub-modules. /// Flattened collection of iterator functions, including those in sub-modules.
@ -349,6 +350,7 @@ impl Module {
all_variables: BTreeMap::new(), all_variables: BTreeMap::new(),
functions: BTreeMap::new(), functions: BTreeMap::new(),
all_functions: BTreeMap::new(), all_functions: BTreeMap::new(),
dynamic_functions: BTreeSet::new(),
type_iterators: BTreeMap::new(), type_iterators: BTreeMap::new(),
all_type_iterators: BTreeMap::new(), all_type_iterators: BTreeMap::new(),
indexed: true, indexed: true,
@ -418,6 +420,25 @@ impl Module {
self self
} }
/// Clear the [`Module`].
#[inline(always)]
pub fn clear(&mut self) {
self.id.clear();
self.internal = false;
self.standard = false;
self.custom_types.clear();
self.modules.clear();
self.variables.clear();
self.all_variables.clear();
self.functions.clear();
self.all_functions.clear();
self.dynamic_functions.clear();
self.type_iterators.clear();
self.all_type_iterators.clear();
self.indexed = false;
self.contains_indexed_global_functions = false;
}
/// Map a custom type to a friendly display name. /// Map a custom type to a friendly display name.
/// ///
/// # Example /// # Example
@ -626,7 +647,7 @@ impl Module {
let value = Dynamic::from(value); let value = Dynamic::from(value);
if self.indexed { if self.indexed {
let hash_var = crate::calc_qualified_var_hash(once(""), &ident); let hash_var = crate::calc_qualified_var_hash(Some(""), &ident);
self.all_variables.insert(hash_var, value.clone()); self.all_variables.insert(hash_var, value.clone());
} }
self.variables.insert(ident, value); self.variables.insert(ident, value);
@ -965,6 +986,10 @@ impl Module {
.collect(); .collect();
param_types.shrink_to_fit(); param_types.shrink_to_fit();
let is_dynamic = param_types
.iter()
.any(|&type_id| type_id == TypeId::of::<Dynamic>());
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
let (param_names, return_type_name) = { let (param_names, return_type_name) = {
let mut names = _arg_names let mut names = _arg_names
@ -981,7 +1006,12 @@ impl Module {
(names, return_type) (names, return_type)
}; };
let hash_fn = calc_native_fn_hash(empty::<&str>(), name.as_ref(), &param_types); let hash_fn = calc_native_fn_hash(None, name.as_ref(), &param_types);
if is_dynamic {
self.dynamic_functions
.insert(calc_fn_hash(name.as_ref(), param_types.len()));
}
self.functions.insert( self.functions.insert(
hash_fn, hash_fn,
@ -1445,19 +1475,30 @@ impl Module {
) )
} }
/// Get a Rust function. /// Look up a Rust function by hash.
/// ///
/// The [`u64`] hash is returned by the [`set_native_fn`][Module::set_native_fn] call. /// The [`u64`] hash is returned by the [`set_native_fn`][Module::set_native_fn] call.
#[inline] #[inline]
#[must_use] #[must_use]
pub(crate) fn get_fn(&self, hash_fn: u64) -> Option<&CallableFunction> { pub(crate) fn get_fn(&self, hash_native: u64) -> Option<&CallableFunction> {
if !self.functions.is_empty() { if !self.functions.is_empty() {
self.functions.get(&hash_fn).map(|f| &f.func) self.functions.get(&hash_native).map(|f| &f.func)
} else { } else {
None None
} }
} }
/// Does the particular function with [`Dynamic`] parameter(s) exist in the [`Module`]?
#[inline(always)]
#[must_use]
pub(crate) fn contains_dynamic_fn(&self, hash_script: u64) -> bool {
if !self.dynamic_functions.is_empty() {
self.dynamic_functions.contains(&hash_script)
} else {
false
}
}
/// Does the particular namespace-qualified function exist in the [`Module`]? /// Does the particular namespace-qualified function exist in the [`Module`]?
/// ///
/// The [`u64`] hash is calculated by [`build_index`][Module::build_index]. /// The [`u64`] hash is calculated by [`build_index`][Module::build_index].
@ -1492,6 +1533,8 @@ impl Module {
self.modules.extend(other.modules.into_iter()); self.modules.extend(other.modules.into_iter());
self.variables.extend(other.variables.into_iter()); self.variables.extend(other.variables.into_iter());
self.functions.extend(other.functions.into_iter()); self.functions.extend(other.functions.into_iter());
self.dynamic_functions
.extend(other.dynamic_functions.into_iter());
self.type_iterators.extend(other.type_iterators.into_iter()); self.type_iterators.extend(other.type_iterators.into_iter());
self.all_functions.clear(); self.all_functions.clear();
self.all_variables.clear(); self.all_variables.clear();
@ -1511,6 +1554,8 @@ impl Module {
} }
self.variables.extend(other.variables.into_iter()); self.variables.extend(other.variables.into_iter());
self.functions.extend(other.functions.into_iter()); self.functions.extend(other.functions.into_iter());
self.dynamic_functions
.extend(other.dynamic_functions.into_iter());
self.type_iterators.extend(other.type_iterators.into_iter()); self.type_iterators.extend(other.type_iterators.into_iter());
self.all_functions.clear(); self.all_functions.clear();
self.all_variables.clear(); self.all_variables.clear();
@ -1537,6 +1582,8 @@ impl Module {
for (&k, v) in &other.functions { for (&k, v) in &other.functions {
self.functions.entry(k).or_insert_with(|| v.clone()); self.functions.entry(k).or_insert_with(|| v.clone());
} }
self.dynamic_functions
.extend(other.dynamic_functions.iter().cloned());
for (&k, v) in &other.type_iterators { for (&k, v) in &other.type_iterators {
self.type_iterators.entry(k).or_insert_with(|| v.clone()); self.type_iterators.entry(k).or_insert_with(|| v.clone());
} }
@ -1571,6 +1618,7 @@ impl Module {
self.variables self.variables
.extend(other.variables.iter().map(|(k, v)| (k.clone(), v.clone()))); .extend(other.variables.iter().map(|(k, v)| (k.clone(), v.clone())));
self.functions.extend( self.functions.extend(
other other
.functions .functions
@ -1586,6 +1634,9 @@ impl Module {
}) })
.map(|(&k, v)| (k, v.clone())), .map(|(&k, v)| (k, v.clone())),
); );
// This may introduce entries that are superfluous because the function has been filtered away.
self.dynamic_functions
.extend(other.dynamic_functions.iter().cloned());
self.type_iterators self.type_iterators
.extend(other.type_iterators.iter().map(|(&k, v)| (k, v.clone()))); .extend(other.type_iterators.iter().map(|(&k, v)| (k, v.clone())));
@ -1621,6 +1672,7 @@ impl Module {
.collect(); .collect();
self.all_functions.clear(); self.all_functions.clear();
self.dynamic_functions.clear();
self.all_variables.clear(); self.all_variables.clear();
self.all_type_iterators.clear(); self.all_type_iterators.clear();
self.indexed = false; self.indexed = false;

View File

@ -2,7 +2,7 @@
#![cfg(not(target_family = "wasm"))] #![cfg(not(target_family = "wasm"))]
use crate::eval::GlobalRuntimeState; use crate::eval::GlobalRuntimeState;
use crate::func::native::{locked_read, locked_write}; use crate::func::{locked_read, locked_write};
use crate::{ use crate::{
Engine, Identifier, Module, ModuleResolver, Position, RhaiResultOf, Scope, Shared, ERR, Engine, Identifier, Module, ModuleResolver, Position, RhaiResultOf, Scope, Shared, ERR,
}; };
@ -307,12 +307,7 @@ impl FileModuleResolver {
let file_path = self.get_file_path(path, source_path); let file_path = self.get_file_path(path, source_path);
if self.is_cache_enabled() { if self.is_cache_enabled() {
#[cfg(not(feature = "sync"))] if let Some(module) = locked_read(&self.cache).get(&file_path) {
let c = self.cache.borrow();
#[cfg(feature = "sync")]
let c = self.cache.read().unwrap();
if let Some(module) = c.get(&file_path) {
return Ok(module.clone()); return Ok(module.clone());
} }
} }

View File

@ -1,5 +1,5 @@
use crate::eval::GlobalRuntimeState; use crate::eval::GlobalRuntimeState;
use crate::func::native::SendSync; use crate::func::SendSync;
use crate::{Engine, Module, Position, RhaiResultOf, Shared, AST}; use crate::{Engine, Module, Position, RhaiResultOf, Shared, AST};
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
use std::prelude::v1::*; use std::prelude::v1::*;

View File

@ -578,7 +578,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
// Then check ranges // Then check ranges
if value.is::<INT>() && !ranges.is_empty() { if value.is::<INT>() && !ranges.is_empty() {
let value = value.as_int().expect("`INT`"); let value = value.as_int().unwrap();
// Only one range or all ranges without conditions // Only one range or all ranges without conditions
if ranges.len() == 1 if ranges.len() == 1
@ -940,6 +940,12 @@ fn optimize_expr(expr: &mut Expr, state: &mut OptimizerState, _chaining: bool) {
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Expr::Dot(x,..) => { optimize_expr(&mut x.lhs, state, false); optimize_expr(&mut x.rhs, state, _chaining); } Expr::Dot(x,..) => { optimize_expr(&mut x.lhs, state, false); optimize_expr(&mut x.rhs, state, _chaining); }
// ()?[rhs]
#[cfg(not(feature = "no_index"))]
Expr::Index(x, options, ..) if options.contains(ASTFlags::NEGATED) && matches!(x.lhs, Expr::Unit(..)) => {
state.set_dirty();
*expr = mem::take(&mut x.lhs);
}
// lhs[rhs] // lhs[rhs]
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Expr::Index(x, ..) if !_chaining => match (&mut x.lhs, &mut x.rhs) { Expr::Index(x, ..) if !_chaining => match (&mut x.lhs, &mut x.rhs) {
@ -1337,7 +1343,7 @@ pub fn optimize_into_ast(
let lib2 = &[&lib2]; let lib2 = &[&lib2];
for fn_def in functions { for fn_def in functions {
let mut fn_def = crate::func::native::shared_take_or_clone(fn_def); let mut fn_def = crate::func::shared_take_or_clone(fn_def);
// Optimize the function body // Optimize the function body
let body = mem::take(&mut *fn_def.body); let body = mem::take(&mut *fn_def.body);

View File

@ -1397,11 +1397,11 @@ pub mod array_functions {
/// ```rhai /// ```rhai
/// let x = [1, 2, 3, 4, 5]; /// let x = [1, 2, 3, 4, 5];
/// ///
/// let y = x.reduce(|r, v| v + if r == () { 0 } else { r }); /// let y = x.reduce(|r, v| v + (r ?? 0));
/// ///
/// print(y); // prints 15 /// print(y); // prints 15
/// ///
/// let y = x.reduce(|r, v, i| v + i + if r == () { 0 } else { r }); /// let y = x.reduce(|r, v, i| v + i + (r ?? 0));
/// ///
/// print(y); // prints 25 /// print(y); // prints 25
/// ``` /// ```
@ -1423,10 +1423,10 @@ pub mod array_functions {
/// ///
/// ```rhai /// ```rhai
/// fn process(r, x) { /// fn process(r, x) {
/// x + if r == () { 0 } else { r } /// x + (r ?? 0)
/// } /// }
/// fn process_extra(r, x, i) { /// fn process_extra(r, x, i) {
/// x + i + if r == () { 0 } else { r } /// x + i + (r ?? 0)
/// } /// }
/// ///
/// let x = [1, 2, 3, 4, 5]; /// let x = [1, 2, 3, 4, 5];
@ -1556,11 +1556,11 @@ pub mod array_functions {
/// ```rhai /// ```rhai
/// let x = [1, 2, 3, 4, 5]; /// let x = [1, 2, 3, 4, 5];
/// ///
/// let y = x.reduce_rev(|r, v| v + if r == () { 0 } else { r }); /// let y = x.reduce_rev(|r, v| v + (r ?? 0));
/// ///
/// print(y); // prints 15 /// print(y); // prints 15
/// ///
/// let y = x.reduce_rev(|r, v, i| v + i + if r == () { 0 } else { r }); /// let y = x.reduce_rev(|r, v, i| v + i + (r ?? 0));
/// ///
/// print(y); // prints 25 /// print(y); // prints 25
/// ``` /// ```
@ -1583,10 +1583,10 @@ pub mod array_functions {
/// ///
/// ```rhai /// ```rhai
/// fn process(r, x) { /// fn process(r, x) {
/// x + if r == () { 0 } else { r } /// x + (r ?? 0)
/// } /// }
/// fn process_extra(r, x, i) { /// fn process_extra(r, x, i) {
/// x + i + if r == () { 0 } else { r } /// x + i + (r ?? 0)
/// } /// }
/// ///
/// let x = [1, 2, 3, 4, 5]; /// let x = [1, 2, 3, 4, 5];

View File

@ -953,7 +953,7 @@ mod parse_int_functions {
/// * If number of bytes in `range` < number of bytes for `INT`, zeros are padded. /// * If number of bytes in `range` < number of bytes for `INT`, zeros are padded.
/// * If number of bytes in `range` > number of bytes for `INT`, extra bytes are ignored. /// * If number of bytes in `range` > number of bytes for `INT`, extra bytes are ignored.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(); /// let b = blob();
/// ///
/// b += 1; b += 2; b += 3; b += 4; b += 5; /// b += 1; b += 2; b += 3; b += 4; b += 5;
@ -974,7 +974,7 @@ mod parse_int_functions {
/// * If number of bytes in `range` < number of bytes for `INT`, zeros are padded. /// * If number of bytes in `range` < number of bytes for `INT`, zeros are padded.
/// * If number of bytes in `range` > number of bytes for `INT`, extra bytes are ignored. /// * If number of bytes in `range` > number of bytes for `INT`, extra bytes are ignored.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(); /// let b = blob();
/// ///
/// b += 1; b += 2; b += 3; b += 4; b += 5; /// b += 1; b += 2; b += 3; b += 4; b += 5;
@ -1001,7 +1001,7 @@ mod parse_int_functions {
/// * If number of bytes in range < number of bytes for `INT`, zeros are padded. /// * If number of bytes in range < number of bytes for `INT`, zeros are padded.
/// * If number of bytes in range > number of bytes for `INT`, extra bytes are ignored. /// * If number of bytes in range > number of bytes for `INT`, extra bytes are ignored.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(); /// let b = blob();
/// ///
/// b += 1; b += 2; b += 3; b += 4; b += 5; /// b += 1; b += 2; b += 3; b += 4; b += 5;
@ -1019,7 +1019,7 @@ mod parse_int_functions {
/// * If number of bytes in `range` < number of bytes for `INT`, zeros are padded. /// * If number of bytes in `range` < number of bytes for `INT`, zeros are padded.
/// * If number of bytes in `range` > number of bytes for `INT`, extra bytes are ignored. /// * If number of bytes in `range` > number of bytes for `INT`, extra bytes are ignored.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(); /// let b = blob();
/// ///
/// b += 1; b += 2; b += 3; b += 4; b += 5; /// b += 1; b += 2; b += 3; b += 4; b += 5;
@ -1040,7 +1040,7 @@ mod parse_int_functions {
/// * If number of bytes in `range` < number of bytes for `INT`, zeros are padded. /// * If number of bytes in `range` < number of bytes for `INT`, zeros are padded.
/// * If number of bytes in `range` > number of bytes for `INT`, extra bytes are ignored. /// * If number of bytes in `range` > number of bytes for `INT`, extra bytes are ignored.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(); /// let b = blob();
/// ///
/// b += 1; b += 2; b += 3; b += 4; b += 5; /// b += 1; b += 2; b += 3; b += 4; b += 5;
@ -1067,7 +1067,7 @@ mod parse_int_functions {
/// * If number of bytes in range < number of bytes for `INT`, zeros are padded. /// * If number of bytes in range < number of bytes for `INT`, zeros are padded.
/// * If number of bytes in range > number of bytes for `INT`, extra bytes are ignored. /// * If number of bytes in range > number of bytes for `INT`, extra bytes are ignored.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(); /// let b = blob();
/// ///
/// b += 1; b += 2; b += 3; b += 4; b += 5; /// b += 1; b += 2; b += 3; b += 4; b += 5;
@ -1213,7 +1213,7 @@ mod write_int_functions {
/// * If number of bytes in `range` < number of bytes for `INT`, extra bytes in `INT` are not written. /// * If number of bytes in `range` < number of bytes for `INT`, extra bytes in `INT` are not written.
/// * If number of bytes in `range` > number of bytes for `INT`, extra bytes in `range` are not modified. /// * If number of bytes in `range` > number of bytes for `INT`, extra bytes in `range` are not modified.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(8); /// let b = blob(8);
/// ///
/// b.write_le_int(1..3, 0x12345678); /// b.write_le_int(1..3, 0x12345678);
@ -1232,7 +1232,7 @@ mod write_int_functions {
/// * If number of bytes in `range` < number of bytes for `INT`, extra bytes in `INT` are not written. /// * If number of bytes in `range` < number of bytes for `INT`, extra bytes in `INT` are not written.
/// * If number of bytes in `range` > number of bytes for `INT`, extra bytes in `range` are not modified. /// * If number of bytes in `range` > number of bytes for `INT`, extra bytes in `range` are not modified.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(8); /// let b = blob(8);
/// ///
/// b.write_le_int(1..=3, 0x12345678); /// b.write_le_int(1..=3, 0x12345678);
@ -1257,7 +1257,7 @@ mod write_int_functions {
/// * If number of bytes in `range` < number of bytes for `INT`, extra bytes in `INT` are not written. /// * If number of bytes in `range` < number of bytes for `INT`, extra bytes in `INT` are not written.
/// * If number of bytes in `range` > number of bytes for `INT`, extra bytes in `range` are not modified. /// * If number of bytes in `range` > number of bytes for `INT`, extra bytes in `range` are not modified.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(8); /// let b = blob(8);
/// ///
/// b.write_le_int(1, 3, 0x12345678); /// b.write_le_int(1, 3, 0x12345678);
@ -1274,7 +1274,7 @@ mod write_int_functions {
/// * If number of bytes in `range` < number of bytes for `INT`, extra bytes in `INT` are not written. /// * If number of bytes in `range` < number of bytes for `INT`, extra bytes in `INT` are not written.
/// * If number of bytes in `range` > number of bytes for `INT`, extra bytes in `range` are not modified. /// * If number of bytes in `range` > number of bytes for `INT`, extra bytes in `range` are not modified.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(8, 0x42); /// let b = blob(8, 0x42);
/// ///
/// b.write_be_int(1..3, 0x99); /// b.write_be_int(1..3, 0x99);
@ -1293,7 +1293,7 @@ mod write_int_functions {
/// * If number of bytes in `range` < number of bytes for `INT`, extra bytes in `INT` are not written. /// * If number of bytes in `range` < number of bytes for `INT`, extra bytes in `INT` are not written.
/// * If number of bytes in `range` > number of bytes for `INT`, extra bytes in `range` are not modified. /// * If number of bytes in `range` > number of bytes for `INT`, extra bytes in `range` are not modified.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(8, 0x42); /// let b = blob(8, 0x42);
/// ///
/// b.write_be_int(1..=3, 0x99); /// b.write_be_int(1..=3, 0x99);
@ -1318,7 +1318,7 @@ mod write_int_functions {
/// * If number of bytes in `range` < number of bytes for `INT`, extra bytes in `INT` are not written. /// * If number of bytes in `range` < number of bytes for `INT`, extra bytes in `INT` are not written.
/// * If number of bytes in `range` > number of bytes for `INT`, extra bytes in `range` are not modified. /// * If number of bytes in `range` > number of bytes for `INT`, extra bytes in `range` are not modified.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(8, 0x42); /// let b = blob(8, 0x42);
/// ///
/// b.write_be_int(1, 3, 0x99); /// b.write_be_int(1, 3, 0x99);
@ -1464,7 +1464,7 @@ mod write_string_functions {
/// * If number of bytes in `range` < length of `string`, extra bytes in `string` are not written. /// * If number of bytes in `range` < length of `string`, extra bytes in `string` are not written.
/// * If number of bytes in `range` > length of `string`, extra bytes in `range` are not modified. /// * If number of bytes in `range` > length of `string`, extra bytes in `range` are not modified.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(8); /// let b = blob(8);
/// ///
/// b.write_utf8(1..5, "朝には紅顔ありて夕べには白骨となる"); /// b.write_utf8(1..5, "朝には紅顔ありて夕べには白骨となる");
@ -1482,7 +1482,7 @@ mod write_string_functions {
/// * If number of bytes in `range` < length of `string`, extra bytes in `string` are not written. /// * If number of bytes in `range` < length of `string`, extra bytes in `string` are not written.
/// * If number of bytes in `range` > length of `string`, extra bytes in `range` are not modified. /// * If number of bytes in `range` > length of `string`, extra bytes in `range` are not modified.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(8); /// let b = blob(8);
/// ///
/// b.write_utf8(1..=5, "朝には紅顔ありて夕べには白骨となる"); /// b.write_utf8(1..=5, "朝には紅顔ありて夕べには白骨となる");
@ -1506,7 +1506,7 @@ mod write_string_functions {
/// * If number of bytes in `range` < length of `string`, extra bytes in `string` are not written. /// * If number of bytes in `range` < length of `string`, extra bytes in `string` are not written.
/// * If number of bytes in `range` > length of `string`, extra bytes in `range` are not modified. /// * If number of bytes in `range` > length of `string`, extra bytes in `range` are not modified.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(8); /// let b = blob(8);
/// ///
/// b.write_utf8(1, 5, "朝には紅顔ありて夕べには白骨となる"); /// b.write_utf8(1, 5, "朝には紅顔ありて夕べには白骨となる");
@ -1525,7 +1525,7 @@ mod write_string_functions {
/// * If number of bytes in `range` < length of `string`, extra bytes in `string` are not written. /// * If number of bytes in `range` < length of `string`, extra bytes in `string` are not written.
/// * If number of bytes in `range` > length of `string`, extra bytes in `range` are not modified. /// * If number of bytes in `range` > length of `string`, extra bytes in `range` are not modified.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(8); /// let b = blob(8);
/// ///
/// b.write_ascii(1..5, "hello, world!"); /// b.write_ascii(1..5, "hello, world!");
@ -1546,7 +1546,7 @@ mod write_string_functions {
/// * If number of bytes in `range` < length of `string`, extra bytes in `string` are not written. /// * If number of bytes in `range` < length of `string`, extra bytes in `string` are not written.
/// * If number of bytes in `range` > length of `string`, extra bytes in `range` are not modified. /// * If number of bytes in `range` > length of `string`, extra bytes in `range` are not modified.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(8); /// let b = blob(8);
/// ///
/// b.write_ascii(1..=5, "hello, world!"); /// b.write_ascii(1..=5, "hello, world!");
@ -1574,7 +1574,7 @@ mod write_string_functions {
/// * If number of bytes in `range` < length of `string`, extra bytes in `string` are not written. /// * If number of bytes in `range` < length of `string`, extra bytes in `string` are not written.
/// * If number of bytes in `range` > length of `string`, extra bytes in `range` are not modified. /// * If number of bytes in `range` > length of `string`, extra bytes in `range` are not modified.
/// ///
/// ```ignore /// ```rhai
/// let b = blob(8); /// let b = blob(8);
/// ///
/// b.write_ascii(1, 5, "hello, world!"); /// b.write_ascii(1, 5, "hello, world!");

View File

@ -1,34 +1,59 @@
use crate::eval::calc_index; use crate::eval::calc_index;
use crate::plugin::*; use crate::plugin::*;
use crate::types::dynamic::Variant;
use crate::{def_package, ExclusiveRange, InclusiveRange, RhaiResultOf, INT, INT_BITS}; use crate::{def_package, ExclusiveRange, InclusiveRange, RhaiResultOf, INT, INT_BITS};
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
use std::prelude::v1::*; use std::prelude::v1::*;
use std::{ use std::{
any::type_name,
cmp::Ordering,
fmt::Debug,
iter::{ExactSizeIterator, FusedIterator}, iter::{ExactSizeIterator, FusedIterator},
ops::{Range, RangeInclusive}, ops::{Range, RangeInclusive},
}; };
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
use num_traits::{CheckedAdd as Add, CheckedSub as Sub}; #[inline(always)]
fn std_add<T>(x: T, y: T) -> Option<T>
#[cfg(feature = "unchecked")] where
use std::ops::{Add, Sub}; T: Debug + Copy + PartialOrd + num_traits::CheckedAdd<Output = T>,
{
x.checked_add(&y)
}
#[inline(always)]
fn regular_add<T>(x: T, y: T) -> Option<T>
where
T: Debug + Copy + PartialOrd + std::ops::Add<Output = T>,
{
Some(x + y)
}
// Range iterator with step // Range iterator with step
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] #[derive(Clone, Copy, Hash, Eq, PartialEq)]
pub struct StepRange<T>(T, T, T) pub struct StepRange<T: Debug + Copy + PartialOrd> {
where pub from: T,
T: Variant + Copy + PartialOrd + Add<Output = T> + Sub<Output = T>; pub to: T,
pub step: T,
pub add: fn(T, T) -> Option<T>,
pub dir: i8,
}
impl<T> StepRange<T> impl<T: Debug + Copy + PartialOrd> Debug for StepRange<T> {
where fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
T: Variant + Copy + PartialOrd + Add<Output = T> + Sub<Output = T>, f.debug_tuple(&format!("StepRange<{}>", type_name::<T>()))
{ .field(&self.from)
pub fn new(from: T, to: T, step: T) -> RhaiResultOf<Self> { .field(&self.to)
#[cfg(not(feature = "unchecked"))] .field(&self.step)
if let Some(r) = from.checked_add(&step) { .finish()
if r == from { }
}
impl<T: Debug + Copy + PartialOrd> StepRange<T> {
pub fn new(from: T, to: T, step: T, add: fn(T, T) -> Option<T>) -> RhaiResultOf<Self> {
let mut dir = 0;
if let Some(n) = add(from, step) {
#[cfg(not(feature = "unchecked"))]
if n == from {
return Err(crate::ERR::ErrorInFunctionCall( return Err(crate::ERR::ErrorInFunctionCall(
"range".to_string(), "range".to_string(),
String::new(), String::new(),
@ -41,77 +66,53 @@ where
) )
.into()); .into());
} }
match from.partial_cmp(&to).unwrap_or(Ordering::Equal) {
Ordering::Less if n > from => dir = 1,
Ordering::Greater if n < from => dir = -1,
_ => (),
}
} }
Ok(Self(from, to, step)) Ok(Self {
from,
to,
step,
add,
dir,
})
} }
} }
impl<T> Iterator for StepRange<T> impl<T: Debug + Copy + PartialOrd> Iterator for StepRange<T> {
where
T: Variant + Copy + PartialOrd + Add<Output = T> + Sub<Output = T>,
{
type Item = T; type Item = T;
fn next(&mut self) -> Option<T> { fn next(&mut self) -> Option<T> {
if self.0 == self.1 { if self.dir == 0 {
None return None;
} else if self.0 < self.1 { }
#[cfg(not(feature = "unchecked"))]
let diff1 = self.1.checked_sub(&self.0)?;
#[cfg(feature = "unchecked")]
let diff1 = self.1 - self.0;
let v = self.0; let v = self.from;
#[cfg(not(feature = "unchecked"))] self.from = (self.add)(self.from, self.step)?;
let n = self.0.checked_add(&self.2)?;
#[cfg(feature = "unchecked")]
let n = self.0 + self.2;
#[cfg(not(feature = "unchecked"))] if self.dir > 0 {
let diff2 = self.1.checked_sub(&n)?; if self.from >= self.to {
#[cfg(feature = "unchecked")] self.dir = 0;
let diff2 = self.1 - n; }
} else if self.dir < 0 {
if diff2 >= diff1 { if self.from <= self.to {
None self.dir = 0;
} else {
self.0 = if n >= self.1 { self.1 } else { n };
Some(v)
} }
} else { } else {
#[cfg(not(feature = "unchecked"))] unreachable!();
let diff1 = self.0.checked_sub(&self.1)?;
#[cfg(feature = "unchecked")]
let diff1 = self.0 - self.1;
let v = self.0;
#[cfg(not(feature = "unchecked"))]
let n = self.0.checked_add(&self.2)?;
#[cfg(feature = "unchecked")]
let n = self.0 + self.2;
#[cfg(not(feature = "unchecked"))]
let diff2 = n.checked_sub(&self.1)?;
#[cfg(feature = "unchecked")]
let diff2 = n - self.1;
if diff2 >= diff1 {
None
} else {
self.0 = if n <= self.1 { self.1 } else { n };
Some(v)
}
} }
Some(v)
} }
} }
impl<T> FusedIterator for StepRange<T> where impl<T: Debug + Copy + PartialOrd> FusedIterator for StepRange<T> {}
T: Variant + Copy + PartialOrd + Add<Output = T> + Sub<Output = T>
{
}
// Bit-field iterator with step // Bit-field iterator with step
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
@ -237,134 +238,6 @@ impl ExactSizeIterator for CharsStream {
} }
} }
#[cfg(not(feature = "no_float"))]
pub mod float {
use super::*;
use crate::FLOAT;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StepFloatRange(FLOAT, FLOAT, FLOAT);
impl StepFloatRange {
pub fn new(from: FLOAT, to: FLOAT, step: FLOAT) -> RhaiResultOf<Self> {
#[cfg(not(feature = "unchecked"))]
if step == 0.0 {
return Err(crate::ERR::ErrorInFunctionCall(
"range".to_string(),
"".to_string(),
crate::ERR::ErrorArithmetic(
"step value cannot be zero".to_string(),
Position::NONE,
)
.into(),
Position::NONE,
)
.into());
}
Ok(Self(from, to, step))
}
}
impl Iterator for StepFloatRange {
type Item = FLOAT;
fn next(&mut self) -> Option<FLOAT> {
if self.0 == self.1 {
None
} else if self.0 < self.1 {
#[cfg(not(feature = "unchecked"))]
if self.2 < 0.0 {
return None;
}
let v = self.0;
let n = self.0 + self.2;
self.0 = if n >= self.1 { self.1 } else { n };
Some(v)
} else {
#[cfg(not(feature = "unchecked"))]
if self.2 > 0.0 {
return None;
}
let v = self.0;
let n = self.0 + self.2;
self.0 = if n <= self.1 { self.1 } else { n };
Some(v)
}
}
}
impl FusedIterator for StepFloatRange {}
}
#[cfg(feature = "decimal")]
pub mod decimal {
use super::*;
use rust_decimal::Decimal;
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
pub struct StepDecimalRange(Decimal, Decimal, Decimal);
impl StepDecimalRange {
pub fn new(from: Decimal, to: Decimal, step: Decimal) -> RhaiResultOf<Self> {
#[cfg(not(feature = "unchecked"))]
if step.is_zero() {
return Err(crate::ERR::ErrorInFunctionCall(
"range".to_string(),
"".to_string(),
crate::ERR::ErrorArithmetic(
"step value cannot be zero".to_string(),
Position::NONE,
)
.into(),
Position::NONE,
)
.into());
}
Ok(Self(from, to, step))
}
}
impl Iterator for StepDecimalRange {
type Item = Decimal;
fn next(&mut self) -> Option<Decimal> {
if self.0 == self.1 {
None
} else if self.0 < self.1 {
#[cfg(not(feature = "unchecked"))]
if self.2.is_sign_negative() {
return None;
}
let v = self.0;
let n = self.0 + self.2;
self.0 = if n >= self.1 { self.1 } else { n };
Some(v)
} else {
#[cfg(not(feature = "unchecked"))]
if self.2.is_sign_positive() {
return None;
}
let v = self.0;
let n = self.0 + self.2;
self.0 = if n <= self.1 { self.1 } else { n };
Some(v)
}
}
}
impl FusedIterator for StepDecimalRange {}
}
macro_rules! reg_range { macro_rules! reg_range {
($lib:ident | $x:expr => $( $y:ty ),*) => { ($lib:ident | $x:expr => $( $y:ty ),*) => {
$( $(
@ -377,11 +250,13 @@ macro_rules! reg_range {
concat!("to: ", stringify!($y)), concat!("to: ", stringify!($y)),
concat!("Iterator<Item=", stringify!($y), ">"), concat!("Iterator<Item=", stringify!($y), ">"),
], [ ], [
"/// Return an iterator over the range of `from..to`.", "/// Return an iterator over the exclusive range of `from..to`.",
"/// The value `to` is never included.",
"///", "///",
"/// # Example", "/// # Example",
"///", "///",
"/// ```rhai", "/// ```rhai",
"/// // prints all values from 8 to 17",
"/// for n in range(8, 18) {", "/// for n in range(8, 18) {",
"/// print(n);", "/// print(n);",
"/// }", "/// }",
@ -392,9 +267,15 @@ macro_rules! reg_range {
)* )*
}; };
($lib:ident | step $x:expr => $( $y:ty ),*) => { ($lib:ident | step $x:expr => $( $y:ty ),*) => {
#[cfg(not(feature = "unchecked"))]
reg_range!($lib | step(std_add) $x => $( $y ),*);
#[cfg(feature = "unchecked")]
reg_range!($lib | step(regular_add) $x => $( $y ),*);
};
($lib:ident | step ( $add:ident ) $x:expr => $( $y:ty ),*) => {
$( $(
$lib.set_iterator::<StepRange<$y>>(); $lib.set_iterator::<StepRange<$y>>();
let _hash = $lib.set_native_fn($x, |from: $y, to: $y, step: $y| StepRange::new(from, to, step)); let _hash = $lib.set_native_fn($x, |from: $y, to: $y, step: $y| StepRange::new(from, to, step, $add));
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
$lib.update_fn_metadata_with_comments(_hash, [ $lib.update_fn_metadata_with_comments(_hash, [
@ -403,17 +284,22 @@ macro_rules! reg_range {
concat!("step: ", stringify!($y)), concat!("step: ", stringify!($y)),
concat!("Iterator<Item=", stringify!($y), ">") concat!("Iterator<Item=", stringify!($y), ">")
], [ ], [
"/// Return an iterator over the range of `from..to`, each iterator increasing by `step`.", "/// Return an iterator over the exclusive range of `from..to`, each iteration increasing by `step`.",
"/// The value `to` is never included.",
"///", "///",
"/// If `from` > `to` and `step` < 0, the iteration goes backwards.", "/// If `from` > `to` and `step` < 0, the iteration goes backwards.",
"///", "///",
"/// If `from` > `to` and `step` > 0 or `from` < `to` and `step` < 0, an empty iterator is returned.",
"///",
"/// # Example", "/// # Example",
"///", "///",
"/// ```rhai", "/// ```rhai",
"/// // prints all values from 8 to 17 in steps of 3",
"/// for n in range(8, 18, 3) {", "/// for n in range(8, 18, 3) {",
"/// print(n);", "/// print(n);",
"/// }", "/// }",
"///", "///",
"/// // prints all values down from 18 to 9 in steps of -3",
"/// for n in range(18, 8, -3) {", "/// for n in range(18, 8, -3) {",
"/// print(n);", "/// print(n);",
"/// }", "/// }",
@ -436,7 +322,6 @@ def_package! {
reg_range!(lib | "range" => i8, u8, i16, u16, i32, u32, i64, u64); reg_range!(lib | "range" => i8, u8, i16, u16, i32, u32, i64, u64);
#[cfg(not(target_family = "wasm"))] #[cfg(not(target_family = "wasm"))]
reg_range!(lib | "range" => i128, u128); reg_range!(lib | "range" => i128, u128);
} }
@ -448,63 +333,22 @@ def_package! {
reg_range!(lib | step "range" => i8, u8, i16, u16, i32, u32, i64, u64); reg_range!(lib | step "range" => i8, u8, i16, u16, i32, u32, i64, u64);
#[cfg(not(target_family = "wasm"))] #[cfg(not(target_family = "wasm"))]
reg_range!(lib | step "range" => i128, u128); reg_range!(lib | step "range" => i128, u128);
} }
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
{ reg_range!(lib | step(regular_add) "range" => crate::FLOAT);
lib.set_iterator::<float::StepFloatRange>();
let _hash = lib.set_native_fn("range", float::StepFloatRange::new);
#[cfg(feature = "metadata")]
lib.update_fn_metadata_with_comments(
_hash,
["from: FLOAT", "to: FLOAT", "step: FLOAT", "Iterator<Item=FLOAT>"],
[
"/// Return an iterator over the range of `from..to`, each iterator increasing by `step`.",
"///",
"/// If `from` > `to` and `step` < 0, the iteration goes backwards.",
"///",
"/// # Example",
"///",
"/// ```rhai",
"/// for n in range(8.0, 18.0, 3.0) {",
"/// print(n);",
"/// }",
"///",
"/// for n in range(18.0, 8.0, -3.0) {",
"/// print(n);",
"/// }",
"/// ```"
]
);
}
#[cfg(feature = "decimal")] #[cfg(feature = "decimal")]
{ reg_range!(lib | step "range" => rust_decimal::Decimal);
lib.set_iterator::<decimal::StepDecimalRange>();
let _hash = lib.set_native_fn("range", decimal::StepDecimalRange::new);
#[cfg(feature = "metadata")]
lib.update_fn_metadata_with_comments(
_hash,
["from: Decimal", "to: Decimal", "step: Decimal", "Iterator<Item=Decimal>"],
[
"/// Return an iterator over the range of `from..to`, each iterator increasing by `step`.",
"///",
"/// If `from` > `to` and `step` < 0, the iteration goes backwards.",
]
);
}
// Register string iterator // Register string iterator
lib.set_iterator::<CharsStream>(); lib.set_iterator::<CharsStream>();
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
let (range_type, range_inclusive_type) = ( let (range_type, range_inclusive_type) = (
format!("range: Range<{}>", std::any::type_name::<INT>()), format!("range: Range<{}>", type_name::<INT>()),
format!("range: RangeInclusive<{}>", std::any::type_name::<INT>()), format!("range: RangeInclusive<{}>", type_name::<INT>()),
); );
let _hash = lib.set_native_fn("chars", |string, range: ExclusiveRange| { let _hash = lib.set_native_fn("chars", |string, range: ExclusiveRange| {

View File

@ -641,6 +641,7 @@ impl Engine {
state: &mut ParseState, state: &mut ParseState,
lib: &mut FnLib, lib: &mut FnLib,
lhs: Expr, lhs: Expr,
options: ASTFlags,
check_index_type: bool, check_index_type: bool,
settings: ParseSettings, settings: ParseSettings,
) -> ParseResult<Expr> { ) -> ParseResult<Expr> {
@ -756,29 +757,35 @@ impl Engine {
// Any more indexing following? // Any more indexing following?
match input.peek().expect(NEVER_ENDS) { match input.peek().expect(NEVER_ENDS) {
// If another indexing level, right-bind it // If another indexing level, right-bind it
(Token::LeftBracket, ..) => { (Token::LeftBracket, ..) | (Token::QuestionBracket, ..) => {
let (token, pos) = input.next().expect(NEVER_ENDS);
let prev_pos = settings.pos; let prev_pos = settings.pos;
settings.pos = eat_token(input, Token::LeftBracket); settings.pos = pos;
// Recursively parse the indexing chain, right-binding each // Recursively parse the indexing chain, right-binding each
let idx_expr = self.parse_index_chain( let idx_expr = self.parse_index_chain(
input, input,
state, state,
lib, lib,
idx_expr, idx_expr,
match token {
Token::LeftBracket => ASTFlags::NONE,
Token::QuestionBracket => ASTFlags::NEGATED,
_ => unreachable!(),
},
false, false,
settings.level_up(), settings.level_up(),
)?; )?;
// Indexing binds to right // Indexing binds to right
Ok(Expr::Index( Ok(Expr::Index(
BinaryExpr { lhs, rhs: idx_expr }.into(), BinaryExpr { lhs, rhs: idx_expr }.into(),
ASTFlags::NONE, options,
prev_pos, prev_pos,
)) ))
} }
// Otherwise terminate the indexing chain // Otherwise terminate the indexing chain
_ => Ok(Expr::Index( _ => Ok(Expr::Index(
BinaryExpr { lhs, rhs: idx_expr }.into(), BinaryExpr { lhs, rhs: idx_expr }.into(),
ASTFlags::BREAK, options | ASTFlags::BREAK,
settings.pos, settings.pos,
)), )),
} }
@ -1634,8 +1641,13 @@ impl Engine {
} }
// Indexing // Indexing
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
(expr, Token::LeftBracket) => { (expr, token @ Token::LeftBracket) | (expr, token @ Token::QuestionBracket) => {
self.parse_index_chain(input, state, lib, expr, true, settings.level_up())? let opt = match token {
Token::LeftBracket => ASTFlags::NONE,
Token::QuestionBracket => ASTFlags::NEGATED,
_ => unreachable!(),
};
self.parse_index_chain(input, state, lib, expr, opt, true, settings.level_up())?
} }
// Property access // Property access
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]

View File

@ -7,7 +7,7 @@ use crate::{calc_fn_hash, Engine, AST};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
use std::prelude::v1::*; use std::prelude::v1::*;
use std::{borrow::Cow, cmp::Ordering, collections::BTreeMap, iter::empty}; use std::{borrow::Cow, cmp::Ordering, collections::BTreeMap};
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
@ -106,7 +106,7 @@ impl<'a> From<&'a FuncInfo> for FnMetadata<'a> {
} else { } else {
( (
FnType::Native, FnType::Native,
calc_native_fn_hash(empty::<&str>(), &info.metadata.name, &info.param_types), calc_native_fn_hash(None, &info.metadata.name, &info.param_types),
) )
}; };

View File

@ -421,9 +421,17 @@ pub enum Token {
/// `.` /// `.`
Period, Period,
/// `?.` /// `?.`
///
/// Reserved under the `no_object` feature.
#[cfg(not(feature = "no_object"))]
Elvis, Elvis,
/// `??` /// `??`
DoubleQuestion, DoubleQuestion,
/// `?[`
///
/// Reserved under the `no_object` feature.
#[cfg(not(feature = "no_index"))]
QuestionBracket,
/// `..` /// `..`
ExclusiveRange, ExclusiveRange,
/// `..=` /// `..=`
@ -580,8 +588,11 @@ impl Token {
Underscore => "_", Underscore => "_",
Comma => ",", Comma => ",",
Period => ".", Period => ".",
#[cfg(not(feature = "no_object"))]
Elvis => "?.", Elvis => "?.",
DoubleQuestion => "??", DoubleQuestion => "??",
#[cfg(not(feature = "no_index"))]
QuestionBracket => "?[",
ExclusiveRange => "..", ExclusiveRange => "..",
InclusiveRange => "..=", InclusiveRange => "..=",
MapStart => "#{", MapStart => "#{",
@ -777,8 +788,11 @@ impl Token {
"_" => Underscore, "_" => Underscore,
"," => Comma, "," => Comma,
"." => Period, "." => Period,
#[cfg(not(feature = "no_object"))]
"?." => Elvis, "?." => Elvis,
"??" => DoubleQuestion, "??" => DoubleQuestion,
#[cfg(not(feature = "no_index"))]
"?[" => QuestionBracket,
".." => ExclusiveRange, ".." => ExclusiveRange,
"..=" => InclusiveRange, "..=" => InclusiveRange,
"#{" => MapStart, "#{" => MapStart,
@ -892,6 +906,7 @@ impl Token {
//Period | //Period |
//Elvis | //Elvis |
//DoubleQuestion | //DoubleQuestion |
//QuestionBracket |
ExclusiveRange | // .. - is unary ExclusiveRange | // .. - is unary
InclusiveRange | // ..= - is unary InclusiveRange | // ..= - is unary
LeftBrace | // { -expr } - is unary LeftBrace | // { -expr } - is unary
@ -999,12 +1014,18 @@ impl Token {
match self { match self {
LeftBrace | RightBrace | LeftParen | RightParen | LeftBracket | RightBracket | Plus LeftBrace | RightBrace | LeftParen | RightParen | LeftBracket | RightBracket | Plus
| UnaryPlus | Minus | UnaryMinus | Multiply | Divide | Modulo | PowerOf | LeftShift | UnaryPlus | Minus | UnaryMinus | Multiply | Divide | Modulo | PowerOf | LeftShift
| RightShift | SemiColon | Colon | DoubleColon | Comma | Period | Elvis | RightShift | SemiColon | Colon | DoubleColon | Comma | Period | DoubleQuestion
| DoubleQuestion | ExclusiveRange | InclusiveRange | MapStart | Equals | LessThan | ExclusiveRange | InclusiveRange | MapStart | Equals | LessThan | GreaterThan
| GreaterThan | LessThanEqualsTo | GreaterThanEqualsTo | EqualsTo | NotEqualsTo | LessThanEqualsTo | GreaterThanEqualsTo | EqualsTo | NotEqualsTo | Bang | Pipe
| Bang | Pipe | Or | XOr | Ampersand | And | PlusAssign | MinusAssign | Or | XOr | Ampersand | And | PlusAssign | MinusAssign | MultiplyAssign
| MultiplyAssign | DivideAssign | LeftShiftAssign | RightShiftAssign | AndAssign | DivideAssign | LeftShiftAssign | RightShiftAssign | AndAssign | OrAssign
| OrAssign | XOrAssign | ModuloAssign | PowerOfAssign => true, | XOrAssign | ModuloAssign | PowerOfAssign => true,
#[cfg(not(feature = "no_object"))]
Elvis => true,
#[cfg(not(feature = "no_index"))]
QuestionBracket => true,
_ => false, _ => false,
} }
@ -1499,7 +1520,7 @@ fn get_next_token_inner(
} }
#[cfg(any(not(feature = "no_float"), feature = "decimal"))] #[cfg(any(not(feature = "no_float"), feature = "decimal"))]
'.' => { '.' => {
stream.get_next().expect("`.`"); stream.get_next().unwrap();
// Check if followed by digits or something that cannot start a property name // Check if followed by digits or something that cannot start a property name
match stream.peek_next().unwrap_or('\0') { match stream.peek_next().unwrap_or('\0') {
@ -1546,7 +1567,7 @@ fn get_next_token_inner(
'+' | '-' => { '+' | '-' => {
result.push(next_char); result.push(next_char);
pos.advance(); pos.advance();
result.push(stream.get_next().expect("`+` or `-`")); result.push(stream.get_next().unwrap());
pos.advance(); pos.advance();
} }
// Not a floating-point number // Not a floating-point number
@ -2047,12 +2068,28 @@ fn get_next_token_inner(
('?', '.') => { ('?', '.') => {
eat_next(stream, pos); eat_next(stream, pos);
return Some((Token::Elvis, start_pos)); return Some((
#[cfg(not(feature = "no_object"))]
Token::Elvis,
#[cfg(feature = "no_object")]
Token::Reserved("?.".into()),
start_pos,
));
} }
('?', '?') => { ('?', '?') => {
eat_next(stream, pos); eat_next(stream, pos);
return Some((Token::DoubleQuestion, start_pos)); return Some((Token::DoubleQuestion, start_pos));
} }
('?', '[') => {
eat_next(stream, pos);
return Some((
#[cfg(not(feature = "no_index"))]
Token::QuestionBracket,
#[cfg(feature = "no_index")]
Token::Reserved("?[".into()),
start_pos,
));
}
('?', ..) => return Some((Token::Reserved("?".into()), start_pos)), ('?', ..) => return Some((Token::Reserved("?".into()), start_pos)),
(ch, ..) if ch.is_whitespace() => (), (ch, ..) if ch.is_whitespace() => (),

View File

@ -25,6 +25,11 @@ impl CustomTypesCollection {
pub fn new() -> Self { pub fn new() -> Self {
Self(BTreeMap::new()) Self(BTreeMap::new())
} }
/// Clear the [`CustomTypesCollection`].
#[inline(always)]
pub fn clear(&mut self) {
self.0.clear();
}
/// Register a custom type. /// Register a custom type.
#[inline(always)] #[inline(always)]
pub fn add(&mut self, type_name: impl Into<Identifier>, name: impl Into<Identifier>) { pub fn add(&mut self, type_name: impl Into<Identifier>, name: impl Into<Identifier>) {

View File

@ -1,7 +1,7 @@
//! Helper module which defines the [`Dynamic`] data type and the //! Helper module which defines the [`Dynamic`] data type and the
//! [`Any`] trait to to allow custom type handling. //! [`Any`] trait to to allow custom type handling.
use crate::func::native::SendSync; use crate::func::{locked_read, SendSync};
use crate::{reify, ExclusiveRange, FnPtr, ImmutableString, InclusiveRange, INT}; use crate::{reify, ExclusiveRange, FnPtr, ImmutableString, InclusiveRange, INT};
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
use std::prelude::v1::*; use std::prelude::v1::*;
@ -26,7 +26,7 @@ pub use instant::Instant;
const CHECKED: &str = "data type was checked"; const CHECKED: &str = "data type was checked";
mod private { mod private {
use crate::func::native::SendSync; use crate::func::SendSync;
use std::any::Any; use std::any::Any;
/// A sealed trait that prevents other crates from implementing [`Variant`]. /// A sealed trait that prevents other crates from implementing [`Variant`].
@ -384,12 +384,7 @@ impl Dynamic {
Union::Variant(ref v, ..) => (***v).type_id(), Union::Variant(ref v, ..) => (***v).type_id(),
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "sync"))] Union::Shared(ref cell, ..) => (*locked_read(cell)).type_id(),
Union::Shared(ref cell, ..) => (*cell.borrow()).type_id(),
#[cfg(not(feature = "no_closure"))]
#[cfg(feature = "sync")]
Union::Shared(ref cell, ..) => (*cell.read().unwrap()).type_id(),
} }
} }
/// Get the name of the type of the value held by this [`Dynamic`]. /// Get the name of the type of the value held by this [`Dynamic`].
@ -455,66 +450,17 @@ impl Hash for Dynamic {
#[cfg(feature = "decimal")] #[cfg(feature = "decimal")]
Union::Decimal(ref d, ..) => d.hash(state), Union::Decimal(ref d, ..) => d.hash(state),
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Union::Array(ref a, ..) => a.as_ref().hash(state), Union::Array(ref a, ..) => a.hash(state),
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Union::Blob(ref a, ..) => a.as_ref().hash(state), Union::Blob(ref a, ..) => a.hash(state),
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Union::Map(ref m, ..) => m.as_ref().hash(state), Union::Map(ref m, ..) => m.hash(state),
Union::FnPtr(ref f, ..) => f.hash(state), Union::FnPtr(ref f, ..) => f.hash(state),
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "sync"))] Union::Shared(ref cell, ..) => (*locked_read(cell)).hash(state),
Union::Shared(ref cell, ..) => (*cell.borrow()).hash(state),
#[cfg(not(feature = "no_closure"))] Union::Variant(..) => unimplemented!("{} cannot be hashed", self.type_name()),
#[cfg(feature = "sync")]
Union::Shared(ref cell, ..) => (*cell.read().unwrap()).hash(state),
Union::Variant(ref _v, ..) => {
#[cfg(not(feature = "only_i32"))]
#[cfg(not(feature = "only_i64"))]
{
let value_any = (***_v).as_any();
let type_id = value_any.type_id();
if type_id == TypeId::of::<u8>() {
TypeId::of::<u8>().hash(state);
value_any.downcast_ref::<u8>().expect(CHECKED).hash(state);
} else if type_id == TypeId::of::<u16>() {
TypeId::of::<u16>().hash(state);
value_any.downcast_ref::<u16>().expect(CHECKED).hash(state);
} else if type_id == TypeId::of::<u32>() {
TypeId::of::<u32>().hash(state);
value_any.downcast_ref::<u32>().expect(CHECKED).hash(state);
} else if type_id == TypeId::of::<u64>() {
TypeId::of::<u64>().hash(state);
value_any.downcast_ref::<u64>().expect(CHECKED).hash(state);
} else if type_id == TypeId::of::<i8>() {
TypeId::of::<i8>().hash(state);
value_any.downcast_ref::<i8>().expect(CHECKED).hash(state);
} else if type_id == TypeId::of::<i16>() {
TypeId::of::<i16>().hash(state);
value_any.downcast_ref::<i16>().expect(CHECKED).hash(state);
} else if type_id == TypeId::of::<i32>() {
TypeId::of::<i32>().hash(state);
value_any.downcast_ref::<i32>().expect(CHECKED).hash(state);
} else if type_id == TypeId::of::<i64>() {
TypeId::of::<i64>().hash(state);
value_any.downcast_ref::<i64>().expect(CHECKED).hash(state);
}
#[cfg(not(target_family = "wasm"))]
if type_id == TypeId::of::<u128>() {
TypeId::of::<u128>().hash(state);
value_any.downcast_ref::<u128>().expect(CHECKED).hash(state);
} else if type_id == TypeId::of::<i128>() {
TypeId::of::<i128>().hash(state);
value_any.downcast_ref::<i128>().expect(CHECKED).hash(state);
}
}
unimplemented!("a custom type cannot be hashed")
}
#[cfg(not(feature = "no_std"))] #[cfg(not(feature = "no_std"))]
Union::TimeStamp(..) => unimplemented!("{} cannot be hashed", self.type_name()), Union::TimeStamp(..) => unimplemented!("{} cannot be hashed", self.type_name()),
@ -550,49 +496,47 @@ impl fmt::Display for Dynamic {
#[cfg(not(feature = "only_i32"))] #[cfg(not(feature = "only_i32"))]
#[cfg(not(feature = "only_i64"))] #[cfg(not(feature = "only_i64"))]
if _type_id == TypeId::of::<u8>() { if let Some(value) = _value_any.downcast_ref::<u8>() {
return fmt::Display::fmt(_value_any.downcast_ref::<u8>().expect(CHECKED), f); return fmt::Display::fmt(value, f);
} else if _type_id == TypeId::of::<u16>() { } else if let Some(value) = _value_any.downcast_ref::<u16>() {
return fmt::Display::fmt(_value_any.downcast_ref::<u16>().expect(CHECKED), f); return fmt::Display::fmt(value, f);
} else if _type_id == TypeId::of::<u32>() { } else if let Some(value) = _value_any.downcast_ref::<u32>() {
return fmt::Display::fmt(_value_any.downcast_ref::<u32>().expect(CHECKED), f); return fmt::Display::fmt(value, f);
} else if _type_id == TypeId::of::<u64>() { } else if let Some(value) = _value_any.downcast_ref::<u64>() {
return fmt::Display::fmt(_value_any.downcast_ref::<u64>().expect(CHECKED), f); return fmt::Display::fmt(value, f);
} else if _type_id == TypeId::of::<i8>() { } else if let Some(value) = _value_any.downcast_ref::<i8>() {
return fmt::Display::fmt(_value_any.downcast_ref::<i8>().expect(CHECKED), f); return fmt::Display::fmt(value, f);
} else if _type_id == TypeId::of::<i16>() { } else if let Some(value) = _value_any.downcast_ref::<i16>() {
return fmt::Display::fmt(_value_any.downcast_ref::<i16>().expect(CHECKED), f); return fmt::Display::fmt(value, f);
} else if _type_id == TypeId::of::<i32>() { } else if let Some(value) = _value_any.downcast_ref::<i32>() {
return fmt::Display::fmt(_value_any.downcast_ref::<i32>().expect(CHECKED), f); return fmt::Display::fmt(value, f);
} else if _type_id == TypeId::of::<i64>() { } else if let Some(value) = _value_any.downcast_ref::<i64>() {
return fmt::Display::fmt(_value_any.downcast_ref::<i64>().expect(CHECKED), f); return fmt::Display::fmt(value, f);
} }
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
#[cfg(not(feature = "f32_float"))] #[cfg(not(feature = "f32_float"))]
if _type_id == TypeId::of::<f32>() { if let Some(value) = _value_any.downcast_ref::<f32>() {
return fmt::Display::fmt(_value_any.downcast_ref::<f32>().expect(CHECKED), f); return fmt::Display::fmt(value, f);
} }
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
#[cfg(feature = "f32_float")] #[cfg(feature = "f32_float")]
if _type_id == TypeId::of::<f64>() { if let Some(value) = _value_any.downcast_ref::<f64>() {
return fmt::Display::fmt(_value_any.downcast_ref::<f64>().expect(CHECKED), f); return fmt::Display::fmt(value, f);
} }
#[cfg(not(feature = "only_i32"))] #[cfg(not(feature = "only_i32"))]
#[cfg(not(feature = "only_i64"))] #[cfg(not(feature = "only_i64"))]
#[cfg(not(target_family = "wasm"))] #[cfg(not(target_family = "wasm"))]
if _type_id == TypeId::of::<u128>() { if let Some(value) = _value_any.downcast_ref::<u128>() {
return fmt::Display::fmt(_value_any.downcast_ref::<u128>().expect(CHECKED), f); return fmt::Display::fmt(value, f);
} else if _type_id == TypeId::of::<i128>() { } else if let Some(value) = _value_any.downcast_ref::<i128>() {
return fmt::Display::fmt(_value_any.downcast_ref::<i128>().expect(CHECKED), f); return fmt::Display::fmt(value, f);
} }
if _type_id == TypeId::of::<ExclusiveRange>() { if let Some(range) = _value_any.downcast_ref::<ExclusiveRange>() {
let range = _value_any.downcast_ref::<ExclusiveRange>().expect(CHECKED);
return write!(f, "{}..{}", range.start, range.end); return write!(f, "{}..{}", range.start, range.end);
} else if _type_id == TypeId::of::<InclusiveRange>() { } else if let Some(range) = _value_any.downcast_ref::<InclusiveRange>() {
let range = _value_any.downcast_ref::<InclusiveRange>().expect(CHECKED);
return write!(f, "{}..={}", range.start(), range.end()); return write!(f, "{}..={}", range.start(), range.end());
} }
@ -655,49 +599,47 @@ impl fmt::Debug for Dynamic {
#[cfg(not(feature = "only_i32"))] #[cfg(not(feature = "only_i32"))]
#[cfg(not(feature = "only_i64"))] #[cfg(not(feature = "only_i64"))]
if _type_id == TypeId::of::<u8>() { if let Some(value) = _value_any.downcast_ref::<u8>() {
return fmt::Debug::fmt(_value_any.downcast_ref::<u8>().expect(CHECKED), f); return fmt::Debug::fmt(value, f);
} else if _type_id == TypeId::of::<u16>() { } else if let Some(value) = _value_any.downcast_ref::<u16>() {
return fmt::Debug::fmt(_value_any.downcast_ref::<u16>().expect(CHECKED), f); return fmt::Debug::fmt(value, f);
} else if _type_id == TypeId::of::<u32>() { } else if let Some(value) = _value_any.downcast_ref::<u32>() {
return fmt::Debug::fmt(_value_any.downcast_ref::<u32>().expect(CHECKED), f); return fmt::Debug::fmt(value, f);
} else if _type_id == TypeId::of::<u64>() { } else if let Some(value) = _value_any.downcast_ref::<u64>() {
return fmt::Debug::fmt(_value_any.downcast_ref::<u64>().expect(CHECKED), f); return fmt::Debug::fmt(value, f);
} else if _type_id == TypeId::of::<i8>() { } else if let Some(value) = _value_any.downcast_ref::<i8>() {
return fmt::Debug::fmt(_value_any.downcast_ref::<i8>().expect(CHECKED), f); return fmt::Debug::fmt(value, f);
} else if _type_id == TypeId::of::<i16>() { } else if let Some(value) = _value_any.downcast_ref::<i16>() {
return fmt::Debug::fmt(_value_any.downcast_ref::<i16>().expect(CHECKED), f); return fmt::Debug::fmt(value, f);
} else if _type_id == TypeId::of::<i32>() { } else if let Some(value) = _value_any.downcast_ref::<i32>() {
return fmt::Debug::fmt(_value_any.downcast_ref::<i32>().expect(CHECKED), f); return fmt::Debug::fmt(value, f);
} else if _type_id == TypeId::of::<i64>() { } else if let Some(value) = _value_any.downcast_ref::<i64>() {
return fmt::Debug::fmt(_value_any.downcast_ref::<i64>().expect(CHECKED), f); return fmt::Debug::fmt(value, f);
} }
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
#[cfg(not(feature = "f32_float"))] #[cfg(not(feature = "f32_float"))]
if _type_id == TypeId::of::<f32>() { if let Some(value) = _value_any.downcast_ref::<f32>() {
return fmt::Debug::fmt(_value_any.downcast_ref::<f32>().expect(CHECKED), f); return fmt::Debug::fmt(value, f);
} }
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
#[cfg(feature = "f32_float")] #[cfg(feature = "f32_float")]
if _type_id == TypeId::of::<f64>() { if let Some(value) = _value_any.downcast_ref::<f64>() {
return fmt::Debug::fmt(_value_any.downcast_ref::<f64>().expect(CHECKED), f); return fmt::Debug::fmt(value, f);
} }
#[cfg(not(feature = "only_i32"))] #[cfg(not(feature = "only_i32"))]
#[cfg(not(feature = "only_i64"))] #[cfg(not(feature = "only_i64"))]
#[cfg(not(target_family = "wasm"))] #[cfg(not(target_family = "wasm"))]
if _type_id == TypeId::of::<u128>() { if let Some(value) = _value_any.downcast_ref::<u128>() {
return fmt::Debug::fmt(_value_any.downcast_ref::<u128>().expect(CHECKED), f); return fmt::Debug::fmt(value, f);
} else if _type_id == TypeId::of::<i128>() { } else if let Some(value) = _value_any.downcast_ref::<i128>() {
return fmt::Debug::fmt(_value_any.downcast_ref::<i128>().expect(CHECKED), f); return fmt::Debug::fmt(value, f);
} }
if _type_id == TypeId::of::<ExclusiveRange>() { if let Some(range) = _value_any.downcast_ref::<ExclusiveRange>() {
let range = _value_any.downcast_ref::<ExclusiveRange>().expect(CHECKED);
return write!(f, "{}..{}", range.start, range.end); return write!(f, "{}..{}", range.start, range.end);
} else if _type_id == TypeId::of::<InclusiveRange>() { } else if let Some(range) = _value_any.downcast_ref::<InclusiveRange>() {
let range = _value_any.downcast_ref::<InclusiveRange>().expect(CHECKED);
return write!(f, "{}..={}", range.start(), range.end()); return write!(f, "{}..={}", range.start(), range.end());
} }
@ -1061,28 +1003,27 @@ impl Dynamic {
/// ///
/// Constant [`Dynamic`] values are read-only. /// Constant [`Dynamic`] values are read-only.
/// ///
/// If a [`&mut Dynamic`][Dynamic] to such a constant is passed to a Rust function, the function /// # Usage
/// can use this information to return an error of
/// [`ErrorAssignmentToConstant`][crate::EvalAltResult::ErrorAssignmentToConstant] if its value
/// is going to be modified.
/// ///
/// This safe-guards constant values from being modified from within Rust functions. /// If a [`&mut Dynamic`][Dynamic] to such a constant is passed to a Rust function, the function
/// can use this information to return the error
/// [`ErrorAssignmentToConstant`][crate::EvalAltResult::ErrorAssignmentToConstant] if its value
/// will be modified.
///
/// This safe-guards constant values from being modified within Rust functions.
///
/// # Shared Values
///
/// If a [`Dynamic`] holds a _shared_ value, then it is read-only only if the shared value
/// itself is read-only.
#[must_use] #[must_use]
pub fn is_read_only(&self) -> bool { pub fn is_read_only(&self) -> bool {
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
match self.0 { match self.0 {
Union::Shared(.., ReadOnly) => return true, // Shared values do not consider the current access mode
//Union::Shared(.., ReadOnly) => return true,
#[cfg(not(feature = "sync"))]
Union::Shared(ref cell, ..) => { Union::Shared(ref cell, ..) => {
return match cell.borrow().access_mode() { return match locked_read(cell).access_mode() {
ReadWrite => false,
ReadOnly => true,
}
}
#[cfg(feature = "sync")]
Union::Shared(ref cell, ..) => {
return match cell.read().unwrap().access_mode() {
ReadWrite => false, ReadWrite => false,
ReadOnly => true, ReadOnly => true,
} }
@ -1114,12 +1055,7 @@ impl Dynamic {
Union::Map(..) => true, Union::Map(..) => true,
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "sync"))] Union::Shared(ref cell, ..) => locked_read(cell).is_hashable(),
Union::Shared(ref cell, ..) => cell.borrow().is_hashable(),
#[cfg(not(feature = "no_closure"))]
#[cfg(feature = "sync")]
Union::Shared(ref cell, ..) => cell.read().unwrap().is_hashable(),
_ => false, _ => false,
} }
@ -1370,11 +1306,7 @@ impl Dynamic {
pub fn flatten_clone(&self) -> Self { pub fn flatten_clone(&self) -> Self {
match self.0 { match self.0 {
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "sync"))] Union::Shared(ref cell, ..) => locked_read(cell).clone(),
Union::Shared(ref cell, ..) => cell.borrow().clone(),
#[cfg(not(feature = "no_closure"))]
#[cfg(feature = "sync")]
Union::Shared(ref cell, ..) => cell.read().unwrap().clone(),
_ => self.clone(), _ => self.clone(),
} }
} }
@ -1389,11 +1321,8 @@ impl Dynamic {
pub fn flatten(self) -> Self { pub fn flatten(self) -> Self {
match self.0 { match self.0 {
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
Union::Shared(cell, ..) => crate::func::native::shared_try_take(cell).map_or_else( Union::Shared(cell, ..) => crate::func::shared_try_take(cell).map_or_else(
#[cfg(not(feature = "sync"))] |ref cell| locked_read(cell).clone(),
|cell| cell.borrow().clone(),
#[cfg(feature = "sync")]
|cell| cell.read().unwrap().clone(),
#[cfg(not(feature = "sync"))] #[cfg(not(feature = "sync"))]
|value| value.into_inner(), |value| value.into_inner(),
#[cfg(feature = "sync")] #[cfg(feature = "sync")]
@ -1414,11 +1343,8 @@ impl Dynamic {
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
Union::Shared(ref mut cell, ..) => { Union::Shared(ref mut cell, ..) => {
let cell = mem::take(cell); let cell = mem::take(cell);
*self = crate::func::native::shared_try_take(cell).map_or_else( *self = crate::func::shared_try_take(cell).map_or_else(
#[cfg(not(feature = "sync"))] |ref cell| locked_read(cell).clone(),
|cell| cell.borrow().clone(),
#[cfg(feature = "sync")]
|cell| cell.read().unwrap().clone(),
#[cfg(not(feature = "sync"))] #[cfg(not(feature = "sync"))]
|value| value.into_inner(), |value| value.into_inner(),
#[cfg(feature = "sync")] #[cfg(feature = "sync")]
@ -1470,10 +1396,7 @@ impl Dynamic {
match self.0 { match self.0 {
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
Union::Shared(ref cell, ..) => { Union::Shared(ref cell, ..) => {
#[cfg(not(feature = "sync"))] let value = locked_read(cell);
let value = cell.borrow();
#[cfg(feature = "sync")]
let value = cell.read().unwrap();
if (*value).type_id() != TypeId::of::<T>() if (*value).type_id() != TypeId::of::<T>()
&& TypeId::of::<Dynamic>() != TypeId::of::<T>() && TypeId::of::<Dynamic>() != TypeId::of::<T>()
@ -1505,7 +1428,7 @@ impl Dynamic {
match self.0 { match self.0 {
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
Union::Shared(ref cell, ..) => { Union::Shared(ref cell, ..) => {
let guard = crate::func::native::locked_write(cell); let guard = crate::func::locked_write(cell);
if (*guard).type_id() != TypeId::of::<T>() if (*guard).type_id() != TypeId::of::<T>()
&& TypeId::of::<Dynamic>() != TypeId::of::<T>() && TypeId::of::<Dynamic>() != TypeId::of::<T>()
@ -1820,11 +1743,8 @@ impl Dynamic {
match self.0 { match self.0 {
Union::Str(s, ..) => Ok(s), Union::Str(s, ..) => Ok(s),
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
Union::Shared(cell, ..) => { Union::Shared(ref cell, ..) => {
#[cfg(not(feature = "sync"))] let value = locked_read(cell);
let value = cell.borrow();
#[cfg(feature = "sync")]
let value = cell.read().unwrap();
match value.0 { match value.0 {
Union::Str(ref s, ..) => Ok(s.clone()), Union::Str(ref s, ..) => Ok(s.clone()),
@ -1842,11 +1762,8 @@ impl Dynamic {
match self.0 { match self.0 {
Union::Array(a, ..) => Ok(*a), Union::Array(a, ..) => Ok(*a),
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
Union::Shared(cell, ..) => { Union::Shared(ref cell, ..) => {
#[cfg(not(feature = "sync"))] let value = locked_read(cell);
let value = cell.borrow();
#[cfg(feature = "sync")]
let value = cell.read().unwrap();
match value.0 { match value.0 {
Union::Array(ref a, ..) => Ok(a.as_ref().clone()), Union::Array(ref a, ..) => Ok(a.as_ref().clone()),
@ -1880,11 +1797,8 @@ impl Dynamic {
.collect(), .collect(),
Union::Blob(..) if TypeId::of::<T>() == TypeId::of::<u8>() => Ok(self.cast::<Vec<T>>()), Union::Blob(..) if TypeId::of::<T>() == TypeId::of::<u8>() => Ok(self.cast::<Vec<T>>()),
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
Union::Shared(cell, ..) => { Union::Shared(ref cell, ..) => {
#[cfg(not(feature = "sync"))] let value = locked_read(cell);
let value = cell.borrow();
#[cfg(feature = "sync")]
let value = cell.read().unwrap();
match value.0 { match value.0 {
Union::Array(ref a, ..) => { Union::Array(ref a, ..) => {
@ -1921,11 +1835,8 @@ impl Dynamic {
match self.0 { match self.0 {
Union::Blob(a, ..) => Ok(*a), Union::Blob(a, ..) => Ok(*a),
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
Union::Shared(cell, ..) => { Union::Shared(ref cell, ..) => {
#[cfg(not(feature = "sync"))] let value = locked_read(cell);
let value = cell.borrow();
#[cfg(feature = "sync")]
let value = cell.read().unwrap();
match value.0 { match value.0 {
Union::Blob(ref a, ..) => Ok(a.as_ref().clone()), Union::Blob(ref a, ..) => Ok(a.as_ref().clone()),

View File

@ -1,6 +1,6 @@
//! The `ImmutableString` type. //! The `ImmutableString` type.
use crate::func::native::{shared_get_mut, shared_make_mut, shared_take}; use crate::func::{shared_get_mut, shared_make_mut, shared_take};
use crate::{Shared, SmartString}; use crate::{Shared, SmartString};
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
use std::prelude::v1::*; use std::prelude::v1::*;

View File

@ -405,3 +405,14 @@ fn test_arrays_map_reduce() -> Result<(), Box<EvalAltResult>> {
Ok(()) Ok(())
} }
#[test]
fn test_arrays_elvis() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert_eq!(engine.eval::<()>("let x = (); x?[2]")?, ());
engine.run("let x = (); x?[2] = 42")?;
Ok(())
}

View File

@ -1,6 +1,6 @@
#![cfg(not(feature = "no_function"))] #![cfg(not(feature = "no_function"))]
use rhai::{Dynamic, Engine, EvalAltResult, FnPtr, Func, FuncArgs, Scope, AST, INT}; use rhai::{Dynamic, Engine, EvalAltResult, FnPtr, Func, FuncArgs, Scope, AST, INT};
use std::{any::TypeId, iter::once}; use std::any::TypeId;
#[test] #[test]
fn test_call_fn() -> Result<(), Box<EvalAltResult>> { fn test_call_fn() -> Result<(), Box<EvalAltResult>> {
@ -107,9 +107,9 @@ struct Options {
impl FuncArgs for Options { impl FuncArgs for Options {
fn parse<C: Extend<Dynamic>>(self, container: &mut C) { fn parse<C: Extend<Dynamic>>(self, container: &mut C) {
container.extend(once(self.foo.into())); container.extend(Some(self.foo.into()));
container.extend(once(self.bar.into())); container.extend(Some(self.bar.into()));
container.extend(once(self.baz.into())); container.extend(Some(self.baz.into()));
} }
} }

View File

@ -1,4 +1,4 @@
use rhai::{Engine, EvalAltResult, ParseErrorType, Position, Scope, INT}; use rhai::{Dynamic, Engine, EvalAltResult, ParseErrorType, Position, Scope, INT};
#[test] #[test]
fn test_var_scope() -> Result<(), Box<EvalAltResult>> { fn test_var_scope() -> Result<(), Box<EvalAltResult>> {
@ -162,9 +162,16 @@ fn test_var_resolver() -> Result<(), Box<EvalAltResult>> {
scope.push("chameleon", 123 as INT); scope.push("chameleon", 123 as INT);
scope.push("DO_NOT_USE", 999 as INT); scope.push("DO_NOT_USE", 999 as INT);
engine.on_var(|name, _, context| { #[cfg(not(feature = "no_closure"))]
let mut base = Dynamic::ONE.into_shared();
#[cfg(not(feature = "no_closure"))]
let shared = base.clone();
engine.on_var(move |name, _, context| {
match name { match name {
"MYSTIC_NUMBER" => Ok(Some((42 as INT).into())), "MYSTIC_NUMBER" => Ok(Some((42 as INT).into())),
#[cfg(not(feature = "no_closure"))]
"HELLO" => Ok(Some(shared.clone())),
// Override a variable - make it not found even if it exists! // Override a variable - make it not found even if it exists!
"DO_NOT_USE" => { "DO_NOT_USE" => {
Err(EvalAltResult::ErrorVariableNotFound(name.to_string(), Position::NONE).into()) Err(EvalAltResult::ErrorVariableNotFound(name.to_string(), Position::NONE).into())
@ -186,6 +193,19 @@ fn test_var_resolver() -> Result<(), Box<EvalAltResult>> {
engine.eval_with_scope::<INT>(&mut scope, "MYSTIC_NUMBER")?, engine.eval_with_scope::<INT>(&mut scope, "MYSTIC_NUMBER")?,
42 42
); );
#[cfg(not(feature = "no_closure"))]
{
assert_eq!(engine.eval::<INT>("HELLO")?, 1);
*base.write_lock::<INT>().unwrap() = 42;
assert_eq!(engine.eval::<INT>("HELLO")?, 42);
engine.run("HELLO = 123")?;
assert_eq!(base.as_int().unwrap(), 123);
assert_eq!(engine.eval::<INT>("HELLO = HELLO + 1; HELLO")?, 124);
assert_eq!(engine.eval::<INT>("HELLO = HELLO * 2; HELLO")?, 248);
assert_eq!(base.as_int().unwrap(), 248);
}
assert_eq!(engine.eval_with_scope::<INT>(&mut scope, "chameleon")?, 1); assert_eq!(engine.eval_with_scope::<INT>(&mut scope, "chameleon")?, 1);
assert!( assert!(
matches!(*engine.eval_with_scope::<INT>(&mut scope, "DO_NOT_USE").expect_err("should error"), matches!(*engine.eval_with_scope::<INT>(&mut scope, "DO_NOT_USE").expect_err("should error"),