Code style refinements.

This commit is contained in:
Stephen Chung 2021-05-29 18:33:29 +08:00
parent 5f36f1a28c
commit 76bd48d0a6
12 changed files with 157 additions and 196 deletions

View File

@ -1,6 +1,10 @@
Rhai Release Notes Rhai Release Notes
================== ==================
Version 0.20.3
==============
Version 0.20.2 Version 0.20.2
============== ==============

View File

@ -711,6 +711,8 @@ impl fmt::Debug for Dynamic {
} }
} }
use AccessMode::*;
impl Clone for Dynamic { impl Clone for Dynamic {
/// Clone the [`Dynamic`] value. /// Clone the [`Dynamic`] value.
/// ///
@ -719,33 +721,25 @@ impl Clone for Dynamic {
/// The cloned copy is marked read-write even if the original is read-only. /// The cloned copy is marked read-write even if the original is read-only.
fn clone(&self) -> Self { fn clone(&self) -> Self {
match self.0 { match self.0 {
Union::Unit(value, tag, _) => Self(Union::Unit(value, tag, AccessMode::ReadWrite)), Union::Unit(value, tag, _) => Self(Union::Unit(value, tag, ReadWrite)),
Union::Bool(value, tag, _) => Self(Union::Bool(value, tag, AccessMode::ReadWrite)), Union::Bool(value, tag, _) => Self(Union::Bool(value, tag, ReadWrite)),
Union::Str(ref value, tag, _) => { Union::Str(ref value, tag, _) => Self(Union::Str(value.clone(), tag, ReadWrite)),
Self(Union::Str(value.clone(), tag, AccessMode::ReadWrite)) Union::Char(value, tag, _) => Self(Union::Char(value, tag, ReadWrite)),
} Union::Int(value, tag, _) => Self(Union::Int(value, tag, ReadWrite)),
Union::Char(value, tag, _) => Self(Union::Char(value, tag, AccessMode::ReadWrite)),
Union::Int(value, tag, _) => Self(Union::Int(value, tag, AccessMode::ReadWrite)),
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
Union::Float(value, tag, _) => Self(Union::Float(value, tag, AccessMode::ReadWrite)), Union::Float(value, tag, _) => Self(Union::Float(value, tag, ReadWrite)),
#[cfg(feature = "decimal")] #[cfg(feature = "decimal")]
Union::Decimal(ref value, tag, _) => { Union::Decimal(ref value, tag, _) => {
Self(Union::Decimal(value.clone(), tag, AccessMode::ReadWrite)) Self(Union::Decimal(value.clone(), tag, ReadWrite))
} }
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Union::Array(ref value, tag, _) => { Union::Array(ref value, tag, _) => Self(Union::Array(value.clone(), tag, ReadWrite)),
Self(Union::Array(value.clone(), tag, AccessMode::ReadWrite))
}
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Union::Map(ref value, tag, _) => { Union::Map(ref value, tag, _) => Self(Union::Map(value.clone(), tag, ReadWrite)),
Self(Union::Map(value.clone(), tag, AccessMode::ReadWrite)) Union::FnPtr(ref value, tag, _) => Self(Union::FnPtr(value.clone(), tag, ReadWrite)),
}
Union::FnPtr(ref value, tag, _) => {
Self(Union::FnPtr(value.clone(), tag, AccessMode::ReadWrite))
}
#[cfg(not(feature = "no_std"))] #[cfg(not(feature = "no_std"))]
Union::TimeStamp(ref value, tag, _) => { Union::TimeStamp(ref value, tag, _) => {
Self(Union::TimeStamp(value.clone(), tag, AccessMode::ReadWrite)) Self(Union::TimeStamp(value.clone(), tag, ReadWrite))
} }
Union::Variant(ref value, tag, _) => { Union::Variant(ref value, tag, _) => {
@ -755,9 +749,7 @@ impl Clone for Dynamic {
} }
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
Union::Shared(ref cell, tag, _) => { Union::Shared(ref cell, tag, _) => Self(Union::Shared(cell.clone(), tag, ReadWrite)),
Self(Union::Shared(cell.clone(), tag, AccessMode::ReadWrite))
}
} }
} }
} }
@ -771,21 +763,21 @@ impl Default for Dynamic {
impl Dynamic { impl Dynamic {
/// A [`Dynamic`] containing a `()`. /// A [`Dynamic`] containing a `()`.
pub const UNIT: Dynamic = Self(Union::Unit((), DEFAULT_TAG, AccessMode::ReadWrite)); pub const UNIT: Dynamic = Self(Union::Unit((), DEFAULT_TAG, ReadWrite));
/// A [`Dynamic`] containing a `true`. /// A [`Dynamic`] containing a `true`.
pub const TRUE: Dynamic = Self(Union::Bool(true, DEFAULT_TAG, AccessMode::ReadWrite)); pub const TRUE: Dynamic = Self(Union::Bool(true, DEFAULT_TAG, ReadWrite));
/// A [`Dynamic`] containing a [`false`]. /// A [`Dynamic`] containing a [`false`].
pub const FALSE: Dynamic = Self(Union::Bool(false, DEFAULT_TAG, AccessMode::ReadWrite)); pub const FALSE: Dynamic = Self(Union::Bool(false, DEFAULT_TAG, ReadWrite));
/// A [`Dynamic`] containing the integer zero. /// A [`Dynamic`] containing the integer zero.
pub const ZERO: Dynamic = Self(Union::Int(0, DEFAULT_TAG, AccessMode::ReadWrite)); pub const ZERO: Dynamic = Self(Union::Int(0, DEFAULT_TAG, ReadWrite));
/// A [`Dynamic`] containing the integer one. /// A [`Dynamic`] containing the integer one.
pub const ONE: Dynamic = Self(Union::Int(1, DEFAULT_TAG, AccessMode::ReadWrite)); pub const ONE: Dynamic = Self(Union::Int(1, DEFAULT_TAG, ReadWrite));
/// A [`Dynamic`] containing the integer two. /// A [`Dynamic`] containing the integer two.
pub const TWO: Dynamic = Self(Union::Int(2, DEFAULT_TAG, AccessMode::ReadWrite)); pub const TWO: Dynamic = Self(Union::Int(2, DEFAULT_TAG, ReadWrite));
/// A [`Dynamic`] containing the integer ten. /// A [`Dynamic`] containing the integer ten.
pub const TEN: Dynamic = Self(Union::Int(10, DEFAULT_TAG, AccessMode::ReadWrite)); pub const TEN: Dynamic = Self(Union::Int(10, DEFAULT_TAG, ReadWrite));
/// A [`Dynamic`] containing the integer negative one. /// A [`Dynamic`] containing the integer negative one.
pub const NEGATIVE_ONE: Dynamic = Self(Union::Int(-1, DEFAULT_TAG, AccessMode::ReadWrite)); pub const NEGATIVE_ONE: Dynamic = Self(Union::Int(-1, DEFAULT_TAG, ReadWrite));
/// A [`Dynamic`] containing `0.0`. /// A [`Dynamic`] containing `0.0`.
/// ///
/// Not available under `no_float`. /// Not available under `no_float`.
@ -793,7 +785,7 @@ impl Dynamic {
pub const FLOAT_ZERO: Dynamic = Self(Union::Float( pub const FLOAT_ZERO: Dynamic = Self(Union::Float(
FloatWrapper::const_new(0.0), FloatWrapper::const_new(0.0),
DEFAULT_TAG, DEFAULT_TAG,
AccessMode::ReadWrite, ReadWrite,
)); ));
/// A [`Dynamic`] containing `1.0`. /// A [`Dynamic`] containing `1.0`.
/// ///
@ -802,7 +794,7 @@ impl Dynamic {
pub const FLOAT_ONE: Dynamic = Self(Union::Float( pub const FLOAT_ONE: Dynamic = Self(Union::Float(
FloatWrapper::const_new(1.0), FloatWrapper::const_new(1.0),
DEFAULT_TAG, DEFAULT_TAG,
AccessMode::ReadWrite, ReadWrite,
)); ));
/// A [`Dynamic`] containing `2.0`. /// A [`Dynamic`] containing `2.0`.
/// ///
@ -811,7 +803,7 @@ impl Dynamic {
pub const FLOAT_TWO: Dynamic = Self(Union::Float( pub const FLOAT_TWO: Dynamic = Self(Union::Float(
FloatWrapper::const_new(2.0), FloatWrapper::const_new(2.0),
DEFAULT_TAG, DEFAULT_TAG,
AccessMode::ReadWrite, ReadWrite,
)); ));
/// A [`Dynamic`] containing `10.0`. /// A [`Dynamic`] containing `10.0`.
/// ///
@ -820,7 +812,7 @@ impl Dynamic {
pub const FLOAT_TEN: Dynamic = Self(Union::Float( pub const FLOAT_TEN: Dynamic = Self(Union::Float(
FloatWrapper::const_new(10.0), FloatWrapper::const_new(10.0),
DEFAULT_TAG, DEFAULT_TAG,
AccessMode::ReadWrite, ReadWrite,
)); ));
/// A [`Dynamic`] containing the `-1.0`. /// A [`Dynamic`] containing the `-1.0`.
/// ///
@ -829,7 +821,7 @@ impl Dynamic {
pub const FLOAT_NEGATIVE_ONE: Dynamic = Self(Union::Float( pub const FLOAT_NEGATIVE_ONE: Dynamic = Self(Union::Float(
FloatWrapper::const_new(-1.0), FloatWrapper::const_new(-1.0),
DEFAULT_TAG, DEFAULT_TAG,
AccessMode::ReadWrite, ReadWrite,
)); ));
/// Get the [`AccessMode`] for this [`Dynamic`]. /// Get the [`AccessMode`] for this [`Dynamic`].
@ -898,7 +890,7 @@ impl Dynamic {
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(_, _, AccessMode::ReadOnly) => return true, Union::Shared(_, _, ReadOnly) => return true,
Union::Shared(ref cell, _, _) => { Union::Shared(ref cell, _, _) => {
#[cfg(not(feature = "sync"))] #[cfg(not(feature = "sync"))]
let value = cell.borrow(); let value = cell.borrow();
@ -906,16 +898,16 @@ impl Dynamic {
let value = cell.read().unwrap(); let value = cell.read().unwrap();
return match value.access_mode() { return match value.access_mode() {
AccessMode::ReadWrite => false, ReadWrite => false,
AccessMode::ReadOnly => true, ReadOnly => true,
}; };
} }
_ => (), _ => (),
} }
match self.access_mode() { match self.access_mode() {
AccessMode::ReadWrite => false, ReadWrite => false,
AccessMode::ReadOnly => true, ReadOnly => true,
} }
} }
/// Can this [`Dynamic`] be hashed? /// Can this [`Dynamic`] be hashed?
@ -1066,7 +1058,7 @@ impl Dynamic {
Self(Union::Variant( Self(Union::Variant(
Box::new(Box::new(value)), Box::new(Box::new(value)),
DEFAULT_TAG, DEFAULT_TAG,
AccessMode::ReadWrite, ReadWrite,
)) ))
} }
/// Turn the [`Dynamic`] value into a shared [`Dynamic`] value backed by an /// Turn the [`Dynamic`] value into a shared [`Dynamic`] value backed by an
@ -1788,37 +1780,33 @@ impl Dynamic {
impl From<()> for Dynamic { impl From<()> for Dynamic {
#[inline(always)] #[inline(always)]
fn from(value: ()) -> Self { fn from(value: ()) -> Self {
Self(Union::Unit(value, DEFAULT_TAG, AccessMode::ReadWrite)) Self(Union::Unit(value, DEFAULT_TAG, ReadWrite))
} }
} }
impl From<bool> for Dynamic { impl From<bool> for Dynamic {
#[inline(always)] #[inline(always)]
fn from(value: bool) -> Self { fn from(value: bool) -> Self {
Self(Union::Bool(value, DEFAULT_TAG, AccessMode::ReadWrite)) Self(Union::Bool(value, DEFAULT_TAG, ReadWrite))
} }
} }
impl From<INT> for Dynamic { impl From<INT> for Dynamic {
#[inline(always)] #[inline(always)]
fn from(value: INT) -> Self { fn from(value: INT) -> Self {
Self(Union::Int(value, DEFAULT_TAG, AccessMode::ReadWrite)) Self(Union::Int(value, DEFAULT_TAG, ReadWrite))
} }
} }
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
impl From<FLOAT> for Dynamic { impl From<FLOAT> for Dynamic {
#[inline(always)] #[inline(always)]
fn from(value: FLOAT) -> Self { fn from(value: FLOAT) -> Self {
Self(Union::Float( Self(Union::Float(value.into(), DEFAULT_TAG, ReadWrite))
value.into(),
DEFAULT_TAG,
AccessMode::ReadWrite,
))
} }
} }
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
impl From<FloatWrapper<FLOAT>> for Dynamic { impl From<FloatWrapper<FLOAT>> for Dynamic {
#[inline(always)] #[inline(always)]
fn from(value: FloatWrapper<FLOAT>) -> Self { fn from(value: FloatWrapper<FLOAT>) -> Self {
Self(Union::Float(value, DEFAULT_TAG, AccessMode::ReadWrite)) Self(Union::Float(value, DEFAULT_TAG, ReadWrite))
} }
} }
#[cfg(feature = "decimal")] #[cfg(feature = "decimal")]
@ -1828,20 +1816,20 @@ impl From<Decimal> for Dynamic {
Self(Union::Decimal( Self(Union::Decimal(
Box::new(value.into()), Box::new(value.into()),
DEFAULT_TAG, DEFAULT_TAG,
AccessMode::ReadWrite, ReadWrite,
)) ))
} }
} }
impl From<char> for Dynamic { impl From<char> for Dynamic {
#[inline(always)] #[inline(always)]
fn from(value: char) -> Self { fn from(value: char) -> Self {
Self(Union::Char(value, DEFAULT_TAG, AccessMode::ReadWrite)) Self(Union::Char(value, DEFAULT_TAG, ReadWrite))
} }
} }
impl<S: Into<ImmutableString>> From<S> for Dynamic { impl<S: Into<ImmutableString>> From<S> for Dynamic {
#[inline(always)] #[inline(always)]
fn from(value: S) -> Self { fn from(value: S) -> Self {
Self(Union::Str(value.into(), DEFAULT_TAG, AccessMode::ReadWrite)) Self(Union::Str(value.into(), DEFAULT_TAG, ReadWrite))
} }
} }
impl From<&ImmutableString> for Dynamic { impl From<&ImmutableString> for Dynamic {
@ -1862,11 +1850,7 @@ impl Dynamic {
/// Create a [`Dynamic`] from an [`Array`]. /// Create a [`Dynamic`] from an [`Array`].
#[inline(always)] #[inline(always)]
pub(crate) fn from_array(array: Array) -> Self { pub(crate) fn from_array(array: Array) -> Self {
Self(Union::Array( Self(Union::Array(Box::new(array), DEFAULT_TAG, ReadWrite))
Box::new(array),
DEFAULT_TAG,
AccessMode::ReadWrite,
))
} }
} }
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
@ -1876,7 +1860,7 @@ impl<T: Variant + Clone> From<Vec<T>> for Dynamic {
Self(Union::Array( Self(Union::Array(
Box::new(value.into_iter().map(Dynamic::from).collect()), Box::new(value.into_iter().map(Dynamic::from).collect()),
DEFAULT_TAG, DEFAULT_TAG,
AccessMode::ReadWrite, ReadWrite,
)) ))
} }
} }
@ -1887,7 +1871,7 @@ impl<T: Variant + Clone> From<&[T]> for Dynamic {
Self(Union::Array( Self(Union::Array(
Box::new(value.iter().cloned().map(Dynamic::from).collect()), Box::new(value.iter().cloned().map(Dynamic::from).collect()),
DEFAULT_TAG, DEFAULT_TAG,
AccessMode::ReadWrite, ReadWrite,
)) ))
} }
} }
@ -1898,7 +1882,7 @@ impl<T: Variant + Clone> std::iter::FromIterator<T> for Dynamic {
Self(Union::Array( Self(Union::Array(
Box::new(iter.into_iter().map(Dynamic::from).collect()), Box::new(iter.into_iter().map(Dynamic::from).collect()),
DEFAULT_TAG, DEFAULT_TAG,
AccessMode::ReadWrite, ReadWrite,
)) ))
} }
} }
@ -1907,11 +1891,7 @@ impl Dynamic {
/// Create a [`Dynamic`] from a [`Map`]. /// Create a [`Dynamic`] from a [`Map`].
#[inline(always)] #[inline(always)]
pub(crate) fn from_map(map: Map) -> Self { pub(crate) fn from_map(map: Map) -> Self {
Self(Union::Map( Self(Union::Map(Box::new(map), DEFAULT_TAG, ReadWrite))
Box::new(map),
DEFAULT_TAG,
AccessMode::ReadWrite,
))
} }
} }
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
@ -1929,7 +1909,7 @@ impl<K: Into<crate::Identifier>, T: Variant + Clone> From<std::collections::Hash
.collect(), .collect(),
), ),
DEFAULT_TAG, DEFAULT_TAG,
AccessMode::ReadWrite, ReadWrite,
)) ))
} }
} }
@ -1947,45 +1927,33 @@ impl<K: Into<crate::Identifier>, T: Variant + Clone> From<std::collections::BTre
.collect(), .collect(),
), ),
DEFAULT_TAG, DEFAULT_TAG,
AccessMode::ReadWrite, ReadWrite,
)) ))
} }
} }
impl From<FnPtr> for Dynamic { impl From<FnPtr> for Dynamic {
#[inline(always)] #[inline(always)]
fn from(value: FnPtr) -> Self { fn from(value: FnPtr) -> Self {
Self(Union::FnPtr( Self(Union::FnPtr(Box::new(value), DEFAULT_TAG, ReadWrite))
Box::new(value),
DEFAULT_TAG,
AccessMode::ReadWrite,
))
} }
} }
impl From<Box<FnPtr>> for Dynamic { impl From<Box<FnPtr>> for Dynamic {
#[inline(always)] #[inline(always)]
fn from(value: Box<FnPtr>) -> Self { fn from(value: Box<FnPtr>) -> Self {
Self(Union::FnPtr(value, DEFAULT_TAG, AccessMode::ReadWrite)) Self(Union::FnPtr(value, DEFAULT_TAG, ReadWrite))
} }
} }
#[cfg(not(feature = "no_std"))] #[cfg(not(feature = "no_std"))]
impl From<Instant> for Dynamic { impl From<Instant> for Dynamic {
#[inline(always)] #[inline(always)]
fn from(value: Instant) -> Self { fn from(value: Instant) -> Self {
Self(Union::TimeStamp( Self(Union::TimeStamp(Box::new(value), DEFAULT_TAG, ReadWrite))
Box::new(value),
DEFAULT_TAG,
AccessMode::ReadWrite,
))
} }
} }
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
impl From<crate::Shared<crate::Locked<Dynamic>>> for Dynamic { impl From<crate::Shared<crate::Locked<Dynamic>>> for Dynamic {
#[inline(always)] #[inline(always)]
fn from(value: crate::Shared<crate::Locked<Self>>) -> Self { fn from(value: crate::Shared<crate::Locked<Self>>) -> Self {
Self(Union::Shared( Self(Union::Shared(value.into(), DEFAULT_TAG, ReadWrite))
value.into(),
DEFAULT_TAG,
AccessMode::ReadWrite,
))
} }
} }

View File

@ -263,7 +263,7 @@ enum ChainArgument {
Property(Position), Property(Position),
/// Arguments to a dot method call. /// Arguments to a dot method call.
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
MethodCallArgs(StaticVec<Dynamic>, StaticVec<Position>), MethodCallArgs(StaticVec<Dynamic>, Position),
/// Index value. /// Index value.
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
IndexValue(Dynamic, Position), IndexValue(Dynamic, Position),
@ -294,7 +294,7 @@ impl ChainArgument {
/// Panics if not `ChainArgument::MethodCallArgs`. /// Panics if not `ChainArgument::MethodCallArgs`.
#[inline(always)] #[inline(always)]
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
pub fn as_fn_call_args(self) -> (StaticVec<Dynamic>, StaticVec<Position>) { pub fn as_fn_call_args(self) -> (StaticVec<Dynamic>, Position) {
match self { match self {
Self::Property(_) => { Self::Property(_) => {
panic!("expecting ChainArgument::MethodCallArgs") panic!("expecting ChainArgument::MethodCallArgs")
@ -303,16 +303,16 @@ impl ChainArgument {
Self::IndexValue(_, _) => { Self::IndexValue(_, _) => {
panic!("expecting ChainArgument::MethodCallArgs") panic!("expecting ChainArgument::MethodCallArgs")
} }
Self::MethodCallArgs(values, positions) => (values, positions), Self::MethodCallArgs(values, pos) => (values, pos),
} }
} }
} }
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
impl From<(StaticVec<Dynamic>, StaticVec<Position>)> for ChainArgument { impl From<(StaticVec<Dynamic>, Position)> for ChainArgument {
#[inline(always)] #[inline(always)]
fn from((values, positions): (StaticVec<Dynamic>, StaticVec<Position>)) -> Self { fn from((values, pos): (StaticVec<Dynamic>, Position)) -> Self {
Self::MethodCallArgs(values, positions) Self::MethodCallArgs(values, pos)
} }
} }
@ -787,7 +787,7 @@ pub struct Engine {
/// A module resolution service. /// A module resolution service.
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
pub(crate) module_resolver: Box<dyn crate::ModuleResolver>, pub(crate) module_resolver: Option<Box<dyn crate::ModuleResolver>>,
/// A map mapping type names to pretty-print names. /// A map mapping type names to pretty-print names.
pub(crate) type_names: BTreeMap<Identifier, Box<Identifier>>, pub(crate) type_names: BTreeMap<Identifier, Box<Identifier>>,
@ -890,10 +890,10 @@ impl Engine {
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_std"))] #[cfg(not(feature = "no_std"))]
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))] #[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
module_resolver: Box::new(crate::module::resolvers::FileModuleResolver::new()), module_resolver: Some(Box::new(crate::module::resolvers::FileModuleResolver::new())),
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
#[cfg(any(feature = "no_std", target_arch = "wasm32",))] #[cfg(any(feature = "no_std", target_arch = "wasm32",))]
module_resolver: Box::new(crate::module::resolvers::DummyModuleResolver::new()), module_resolver: None,
type_names: Default::default(), type_names: Default::default(),
empty_string: Default::default(), empty_string: Default::default(),
@ -950,7 +950,7 @@ impl Engine {
global_sub_modules: Default::default(), global_sub_modules: Default::default(),
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
module_resolver: Box::new(crate::module::resolvers::DummyModuleResolver::new()), module_resolver: None,
type_names: Default::default(), type_names: Default::default(),
empty_string: Default::default(), empty_string: Default::default(),
@ -1629,24 +1629,25 @@ impl Engine {
match expr { match expr {
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Expr::FnCall(x, _) if _parent_chain_type == ChainType::Dot && !x.is_qualified() => { Expr::FnCall(x, _) if _parent_chain_type == ChainType::Dot && !x.is_qualified() => {
let mut arg_positions: StaticVec<_> = Default::default(); let arg_values = x
let mut arg_values = x
.args .args
.iter() .iter()
.inspect(|arg_expr| arg_positions.push(arg_expr.position()))
.map(|arg_expr| { .map(|arg_expr| {
self.eval_expr(scope, mods, state, lib, this_ptr, arg_expr, level) self.eval_expr(scope, mods, state, lib, this_ptr, arg_expr, level)
.map(Dynamic::flatten) .map(Dynamic::flatten)
}) })
.chain(x.literal_args.iter().map(|(v, _)| Ok(v.clone())))
.collect::<Result<StaticVec<_>, _>>()?; .collect::<Result<StaticVec<_>, _>>()?;
x.literal_args let pos = x
.args
.iter() .iter()
.inspect(|(_, pos)| arg_positions.push(*pos)) .map(|arg_expr| arg_expr.position())
.for_each(|(v, _)| arg_values.push(v.clone())); .chain(x.literal_args.iter().map(|(_, pos)| *pos))
.next()
.unwrap_or_default();
idx_values.push((arg_values, arg_positions).into()); idx_values.push((arg_values, pos).into());
} }
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Expr::FnCall(_, _) if _parent_chain_type == ChainType::Dot => { Expr::FnCall(_, _) if _parent_chain_type == ChainType::Dot => {
@ -1674,24 +1675,25 @@ impl Engine {
Expr::FnCall(x, _) Expr::FnCall(x, _)
if _parent_chain_type == ChainType::Dot && !x.is_qualified() => if _parent_chain_type == ChainType::Dot && !x.is_qualified() =>
{ {
let mut arg_positions: StaticVec<_> = Default::default(); let arg_values = x
let mut arg_values = x
.args .args
.iter() .iter()
.inspect(|arg_expr| arg_positions.push(arg_expr.position()))
.map(|arg_expr| { .map(|arg_expr| {
self.eval_expr(scope, mods, state, lib, this_ptr, arg_expr, level) self.eval_expr(scope, mods, state, lib, this_ptr, arg_expr, level)
.map(Dynamic::flatten) .map(Dynamic::flatten)
}) })
.chain(x.literal_args.iter().map(|(v, _)| Ok(v.clone())))
.collect::<Result<StaticVec<_>, _>>()?; .collect::<Result<StaticVec<_>, _>>()?;
x.literal_args let pos = x
.args
.iter() .iter()
.inspect(|(_, pos)| arg_positions.push(*pos)) .map(|arg_expr| arg_expr.position())
.for_each(|(v, _)| arg_values.push(v.clone())); .chain(x.literal_args.iter().map(|(_, pos)| *pos))
.next()
.unwrap_or_default();
(arg_values, arg_positions).into() (arg_values, pos).into()
} }
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Expr::FnCall(_, _) if _parent_chain_type == ChainType::Dot => { Expr::FnCall(_, _) if _parent_chain_type == ChainType::Dot => {
@ -2037,11 +2039,7 @@ impl Engine {
Expr::Unit(_) => Ok(Dynamic::UNIT), Expr::Unit(_) => Ok(Dynamic::UNIT),
Expr::Custom(custom, _) => { Expr::Custom(custom, _) => {
let expressions = custom let expressions: StaticVec<_> = custom.keywords.iter().map(Into::into).collect();
.keywords
.iter()
.map(Into::into)
.collect::<StaticVec<_>>();
let key_token = custom.tokens.first().expect( let key_token = custom.tokens.first().expect(
"never fails because a custom syntax stream must contain at least one token", "never fails because a custom syntax stream must contain at least one token",
); );
@ -2757,20 +2755,26 @@ impl Engine {
use crate::ModuleResolver; use crate::ModuleResolver;
let source = state.source.as_ref().map(|s| s.as_str()); let source = state.source.as_ref().map(|s| s.as_str());
let expr_pos = expr.position(); let path_pos = expr.position();
let module = state let module = state
.resolver .resolver
.as_ref() .as_ref()
.and_then(|r| match r.resolve(self, source, &path, expr_pos) { .and_then(|r| match r.resolve(self, source, &path, path_pos) {
Ok(m) => return Some(Ok(m)), Err(err)
Err(err) => match *err { if matches!(*err, EvalAltResult::ErrorModuleNotFound(_, _)) =>
EvalAltResult::ErrorModuleNotFound(_, _) => None, {
_ => return Some(Err(err)), None
}, }
result => Some(result),
})
.or_else(|| {
self.module_resolver
.as_ref()
.map(|r| r.resolve(self, source, &path, path_pos))
}) })
.unwrap_or_else(|| { .unwrap_or_else(|| {
self.module_resolver.resolve(self, source, &path, expr_pos) EvalAltResult::ErrorModuleNotFound(path.to_string(), path_pos).into()
})?; })?;
export.as_ref().map(|x| x.name.clone()).map(|name| { export.as_ref().map(|x| x.name.clone()).map(|name| {

View File

@ -1101,8 +1101,10 @@ impl Engine {
}); });
} }
let mut resolver = StaticModuleResolver::new();
let mut ast = self.compile_scripts_with_scope(scope, &[script])?; let mut ast = self.compile_scripts_with_scope(scope, &[script])?;
if let Some(ref module_resolver) = self.module_resolver {
let mut resolver = StaticModuleResolver::new();
let mut imports = Default::default(); let mut imports = Default::default();
collect_imports(&ast, &mut resolver, &mut imports); collect_imports(&ast, &mut resolver, &mut imports);
@ -1111,10 +1113,7 @@ impl Engine {
while let Some(path) = imports.iter().next() { while let Some(path) = imports.iter().next() {
let path = path.clone(); let path = path.clone();
match self match module_resolver.resolve_ast(self, None, &path, Position::NONE) {
.module_resolver
.resolve_ast(self, None, &path, Position::NONE)
{
Some(Ok(module_ast)) => { Some(Ok(module_ast)) => {
collect_imports(&module_ast, &mut resolver, &mut imports) collect_imports(&module_ast, &mut resolver, &mut imports)
} }
@ -1122,18 +1121,15 @@ impl Engine {
None => (), None => (),
} }
let module = shared_take_or_clone(self.module_resolver.resolve( let module = module_resolver.resolve(self, None, &path, Position::NONE)?;
self, let module = shared_take_or_clone(module);
None,
&path,
Position::NONE,
)?);
imports.remove(&path); imports.remove(&path);
resolver.insert(path, module); resolver.insert(path, module);
} }
ast.set_resolver(resolver); ast.set_resolver(resolver);
} }
}
Ok(ast) Ok(ast)
} }

View File

@ -188,7 +188,7 @@ impl Engine {
&mut self, &mut self,
resolver: impl crate::ModuleResolver + 'static, resolver: impl crate::ModuleResolver + 'static,
) -> &mut Self { ) -> &mut Self {
self.module_resolver = Box::new(resolver); self.module_resolver = Some(Box::new(resolver));
self self
} }
/// Disable a particular keyword or operator in the language. /// Disable a particular keyword or operator in the language.

View File

@ -515,13 +515,11 @@ impl Engine {
); );
// Merge in encapsulated environment, if any // Merge in encapsulated environment, if any
let lib_merged; let lib_merged: StaticVec<_>;
let (unified_lib, unified) = if let Some(ref env_lib) = fn_def.lib { let (unified_lib, unified) = if let Some(ref env_lib) = fn_def.lib {
state.push_fn_resolution_cache(); state.push_fn_resolution_cache();
lib_merged = once(env_lib.as_ref()) lib_merged = once(env_lib.as_ref()).chain(lib.iter().cloned()).collect();
.chain(lib.iter().cloned())
.collect::<StaticVec<_>>();
(lib_merged.as_ref(), true) (lib_merged.as_ref(), true)
} else { } else {
(lib, false) (lib, false)
@ -895,20 +893,16 @@ impl Engine {
fn_name: &str, fn_name: &str,
mut hash: FnCallHashes, mut hash: FnCallHashes,
target: &mut crate::engine::Target, target: &mut crate::engine::Target,
(call_args, call_arg_positions): &mut (StaticVec<Dynamic>, StaticVec<Position>), (call_args, call_arg_pos): &mut (StaticVec<Dynamic>, Position),
pos: Position, pos: Position,
level: usize, level: usize,
) -> Result<(Dynamic, bool), Box<EvalAltResult>> { ) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
let is_ref = target.is_ref(); let is_ref = target.is_ref();
// Get a reference to the mutation target Dynamic
let obj = target.as_mut();
let mut fn_name = fn_name;
let (result, updated) = match fn_name { let (result, updated) = match fn_name {
KEYWORD_FN_PTR_CALL if obj.is::<FnPtr>() => { KEYWORD_FN_PTR_CALL if target.is::<FnPtr>() => {
// FnPtr call // FnPtr call
let fn_ptr = obj let fn_ptr = target
.read_lock::<FnPtr>() .read_lock::<FnPtr>()
.expect("never fails because `obj` is `FnPtr`"); .expect("never fails because `obj` is `FnPtr`");
// Redirect function name // Redirect function name
@ -917,11 +911,8 @@ impl Engine {
// Recalculate hashes // Recalculate hashes
let new_hash = FnCallHashes::from_script(calc_fn_hash(fn_name, args_len)); let new_hash = FnCallHashes::from_script(calc_fn_hash(fn_name, args_len));
// Arguments are passed as-is, adding the curried arguments // Arguments are passed as-is, adding the curried arguments
let mut curry = fn_ptr.curry().iter().cloned().collect::<StaticVec<_>>(); let mut curry: StaticVec<_> = fn_ptr.curry().iter().cloned().collect();
let mut args = curry let mut args: StaticVec<_> = curry.iter_mut().chain(call_args.iter_mut()).collect();
.iter_mut()
.chain(call_args.iter_mut())
.collect::<StaticVec<_>>();
// Map it to name(args) in function-call style // Map it to name(args) in function-call style
self.exec_fn_call( self.exec_fn_call(
@ -932,20 +923,19 @@ impl Engine {
if call_args.len() > 0 { if call_args.len() > 0 {
if !call_args[0].is::<FnPtr>() { if !call_args[0].is::<FnPtr>() {
return Err(self.make_type_mismatch_err::<FnPtr>( return Err(self.make_type_mismatch_err::<FnPtr>(
self.map_type_name(obj.type_name()), self.map_type_name(target.type_name()),
call_arg_positions[0], *call_arg_pos,
)); ));
} }
} else { } else {
return Err(self.make_type_mismatch_err::<FnPtr>( return Err(self.make_type_mismatch_err::<FnPtr>(
self.map_type_name(obj.type_name()), self.map_type_name(target.type_name()),
pos, pos,
)); ));
} }
// FnPtr call on object // FnPtr call on object
let fn_ptr = call_args.remove(0).cast::<FnPtr>(); let fn_ptr = call_args.remove(0).cast::<FnPtr>();
call_arg_positions.remove(0);
// Redirect function name // Redirect function name
let fn_name = fn_ptr.fn_name(); let fn_name = fn_ptr.fn_name();
let args_len = call_args.len() + fn_ptr.curry().len(); let args_len = call_args.len() + fn_ptr.curry().len();
@ -955,11 +945,11 @@ impl Engine {
calc_fn_hash(fn_name, args_len + 1), calc_fn_hash(fn_name, args_len + 1),
); );
// Replace the first argument with the object pointer, adding the curried arguments // Replace the first argument with the object pointer, adding the curried arguments
let mut curry = fn_ptr.curry().iter().cloned().collect::<StaticVec<_>>(); let mut curry: StaticVec<_> = fn_ptr.curry().iter().cloned().collect();
let mut args = once(obj) let mut args: StaticVec<_> = once(target.as_mut())
.chain(curry.iter_mut()) .chain(curry.iter_mut())
.chain(call_args.iter_mut()) .chain(call_args.iter_mut())
.collect::<StaticVec<_>>(); .collect();
// Map it to name(args) in function-call style // Map it to name(args) in function-call style
self.exec_fn_call( self.exec_fn_call(
@ -967,14 +957,14 @@ impl Engine {
) )
} }
KEYWORD_FN_PTR_CURRY => { KEYWORD_FN_PTR_CURRY => {
if !obj.is::<FnPtr>() { if !target.is::<FnPtr>() {
return Err(self.make_type_mismatch_err::<FnPtr>( return Err(self.make_type_mismatch_err::<FnPtr>(
self.map_type_name(obj.type_name()), self.map_type_name(target.type_name()),
pos, pos,
)); ));
} }
let fn_ptr = obj let fn_ptr = target
.read_lock::<FnPtr>() .read_lock::<FnPtr>()
.expect("never fails because `obj` is `FnPtr`"); .expect("never fails because `obj` is `FnPtr`");
@ -1005,26 +995,21 @@ impl Engine {
} }
_ => { _ => {
let mut fn_name = fn_name;
let _redirected; let _redirected;
// Check if it is a map method call in OOP style // Check if it is a map method call in OOP style
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
if let Some(map) = obj.read_lock::<Map>() { if let Some(map) = target.read_lock::<Map>() {
if let Some(val) = map.get(fn_name) { if let Some(val) = map.get(fn_name) {
if let Some(fn_ptr) = val.read_lock::<FnPtr>() { if let Some(fn_ptr) = val.read_lock::<FnPtr>() {
// Remap the function name // Remap the function name
_redirected = fn_ptr.get_fn_name().clone(); _redirected = fn_ptr.get_fn_name().clone();
fn_name = &_redirected; fn_name = &_redirected;
// Add curried arguments // Add curried arguments
fn_ptr if fn_ptr.is_curried() {
.curry() call_args.insert_many(0, fn_ptr.curry().iter().cloned());
.iter() }
.cloned()
.enumerate()
.for_each(|(i, v)| {
call_args.insert(i, v);
call_arg_positions.insert(i, Position::NONE);
});
// Recalculate the hash based on the new function name and new arguments // Recalculate the hash based on the new function name and new arguments
hash = FnCallHashes::from_script_and_native( hash = FnCallHashes::from_script_and_native(
calc_fn_hash(fn_name, call_args.len()), calc_fn_hash(fn_name, call_args.len()),
@ -1035,9 +1020,8 @@ impl Engine {
}; };
// Attached object pointer in front of the arguments // Attached object pointer in front of the arguments
let mut args = once(obj) let mut args: StaticVec<_> =
.chain(call_args.iter_mut()) once(target.as_mut()).chain(call_args.iter_mut()).collect();
.collect::<StaticVec<_>>();
self.exec_fn_call( self.exec_fn_call(
mods, state, lib, fn_name, hash, &mut args, is_ref, true, pos, None, level, mods, state, lib, fn_name, hash, &mut args, is_ref, true, pos, None, level,

View File

@ -4,7 +4,7 @@
#![allow(non_snake_case)] #![allow(non_snake_case)]
use crate::dynamic::Variant; use crate::dynamic::Variant;
use crate::{Engine, EvalAltResult, ParseError, Scope, AST}; use crate::{Engine, EvalAltResult, ParseError, Scope, SmartString, AST};
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
use std::prelude::v1::*; use std::prelude::v1::*;
@ -98,7 +98,7 @@ macro_rules! def_anonymous_fn {
#[inline(always)] #[inline(always)]
fn create_from_ast(self, ast: AST, entry_point: &str) -> Self::Output { fn create_from_ast(self, ast: AST, entry_point: &str) -> Self::Output {
let fn_name = entry_point.to_string(); let fn_name: SmartString = entry_point.into();
Box::new(move |$($par),*| self.call_fn(&mut Scope::new(), &ast, &fn_name, ($($par,)*))) Box::new(move |$($par),*| self.call_fn(&mut Scope::new(), &ast, &fn_name, ($($par,)*)))
} }

View File

@ -314,6 +314,11 @@ impl FnPtr {
pub fn is_curried(&self) -> bool { pub fn is_curried(&self) -> bool {
!self.1.is_empty() !self.1.is_empty()
} }
/// Get the number of curried arguments.
#[inline(always)]
pub fn num_curried(&self) -> usize {
self.1.len()
}
/// Does the function pointer refer to an anonymous function? /// Does the function pointer refer to an anonymous function?
/// ///
/// Not available under `no_function`. /// Not available under `no_function`.
@ -339,7 +344,7 @@ impl FnPtr {
this_ptr: Option<&mut Dynamic>, this_ptr: Option<&mut Dynamic>,
mut arg_values: impl AsMut<[Dynamic]>, mut arg_values: impl AsMut<[Dynamic]>,
) -> RhaiResult { ) -> RhaiResult {
let mut args_data; let mut args_data: StaticVec<_>;
let arg_values = if self.curry().is_empty() { let arg_values = if self.curry().is_empty() {
arg_values.as_mut() arg_values.as_mut()
@ -349,7 +354,7 @@ impl FnPtr {
.iter() .iter()
.cloned() .cloned()
.chain(arg_values.as_mut().iter_mut().map(mem::take)) .chain(arg_values.as_mut().iter_mut().map(mem::take))
.collect::<StaticVec<_>>(); .collect();
args_data.as_mut() args_data.as_mut()
}; };

View File

@ -147,7 +147,7 @@ fn call_fn_with_constant_arguments(
state.lib, state.lib,
fn_name, fn_name,
calc_fn_hash(fn_name, arg_values.len()), calc_fn_hash(fn_name, arg_values.len()),
arg_values.iter_mut().collect::<StaticVec<_>>().as_mut(), &mut arg_values.iter_mut().collect::<StaticVec<_>>(),
false, false,
false, false,
Position::NONE, Position::NONE,

View File

@ -745,7 +745,7 @@ mod array_functions {
len as usize len as usize
}; };
let mut drained = array.drain(..start).collect::<Array>(); let mut drained: Array = array.drain(..start).collect();
drained.extend(array.drain(len..)); drained.extend(array.drain(len..));
drained drained

View File

@ -110,7 +110,7 @@ mod string_functions {
pub fn index_of_char_starting_from(string: &str, character: char, start: INT) -> INT { pub fn index_of_char_starting_from(string: &str, character: char, start: INT) -> INT {
let start = if start < 0 { let start = if start < 0 {
if let Some(n) = start.checked_abs() { if let Some(n) = start.checked_abs() {
let chars = string.chars().collect::<Vec<_>>(); let chars: Vec<_> = string.chars().collect();
let num_chars = chars.len(); let num_chars = chars.len();
if n as usize > num_chars { if n as usize > num_chars {
0 0

View File

@ -1864,7 +1864,7 @@ fn parse_custom_syntax(
state.stack.push((empty, AccessMode::ReadWrite)); state.stack.push((empty, AccessMode::ReadWrite));
} }
let parse_func = &syntax.parse; let parse_func = syntax.parse.as_ref();
segments.push(key.into()); segments.push(key.into());
tokens.push(key.into()); tokens.push(key.into());