From b5ed841ee7e06a97be906a5e88af4906dee04d26 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Thu, 27 May 2021 13:39:48 +0800 Subject: [PATCH 1/7] Bump version. --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index f2236a0b..17c2861d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ members = [".", "codegen"] [package] name = "rhai" -version = "0.20.2" +version = "0.20.3" edition = "2018" authors = ["Jonathan Turner", "Lukáš Hozda", "Stephen Chung", "jhwgh1968"] description = "Embedded scripting for Rust" From 5f36f1a28cd59d7d15b7fc84f5cfb1d495c8a7c5 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Sat, 29 May 2021 18:32:34 +0800 Subject: [PATCH 2/7] Remove PluginFunction::is_variadic. --- Cargo.toml | 2 +- codegen/Cargo.toml | 4 ++-- codegen/src/function.rs | 1 - codegen/src/test/function.rs | 8 -------- codegen/src/test/module.rs | 22 ---------------------- src/plugin.rs | 3 --- 6 files changed, 3 insertions(+), 37 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 17c2861d..6151739d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,7 @@ smallvec = { version = "1.6", default-features = false, features = ["union"] } ahash = { version = "0.7", default-features = false } num-traits = { version = "0.2", default_features = false } smartstring = { version = "0.2.6", default_features = false } -rhai_codegen = { version = "0.3.4", path = "codegen", default_features = false } +rhai_codegen = { version = "0.3.7", path = "codegen", default_features = false } [features] default = ["smartstring/std", "ahash/std", "num-traits/std"] # remove 'smartstring/std' when smartstring is updated to support no-std diff --git a/codegen/Cargo.toml b/codegen/Cargo.toml index 284644a8..cfb9d004 100644 --- a/codegen/Cargo.toml +++ b/codegen/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rhai_codegen" -version = "0.3.6" +version = "0.3.7" edition = "2018" authors = ["jhwgh1968", "Stephen Chung"] description = "Procedural macros support package for Rhai, a scripting language and engine for Rust" @@ -16,7 +16,7 @@ default = [] metadata = [] [dev-dependencies] -rhai = { path = "..", version = ">=0.19.15" } +rhai = { path = "..", version = ">=0.20.3" } trybuild = "1" [dependencies] diff --git a/codegen/src/function.rs b/codegen/src/function.rs index ccc97afa..178f3645 100644 --- a/codegen/src/function.rs +++ b/codegen/src/function.rs @@ -845,7 +845,6 @@ impl ExportedFn { } #[inline(always)] fn is_method_call(&self) -> bool { #is_method_call } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } } diff --git a/codegen/src/test/function.rs b/codegen/src/test/function.rs index 2013a120..7fb6dc3a 100644 --- a/codegen/src/test/function.rs +++ b/codegen/src/test/function.rs @@ -286,7 +286,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } #[allow(unused)] #[inline(always)] pub fn dynamic_result_fn() -> RhaiResult { @@ -322,7 +321,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } #[allow(unused)] #[inline(always)] pub fn dynamic_result_fn(x: usize) -> RhaiResult { @@ -358,7 +356,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } #[allow(unused)] #[inline(always)] pub fn dynamic_result_fn(context: NativeCallContext, x: usize) -> RhaiResult { @@ -396,7 +393,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } #[allow(unused)] #[inline(always)] pub fn dynamic_result_fn() -> RhaiResult { @@ -428,7 +424,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } }; @@ -460,7 +455,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } #[allow(unused)] #[inline(always)] pub fn dynamic_result_fn(x: usize, y: usize) -> RhaiResult { @@ -500,7 +494,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { true } - #[inline(always)] fn is_variadic(&self) -> bool { false } } #[allow(unused)] #[inline(always)] pub fn dynamic_result_fn(x: &mut usize, y: usize) -> RhaiResult { @@ -537,7 +530,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } #[allow(unused)] #[inline(always)] pub fn dynamic_result_fn(message: &str) -> RhaiResult { diff --git a/codegen/src/test/module.rs b/codegen/src/test/module.rs index 959d2700..6e62c4a6 100644 --- a/codegen/src/test/module.rs +++ b/codegen/src/test/module.rs @@ -315,7 +315,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -370,7 +369,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -424,7 +422,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -492,7 +489,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } #[allow(non_camel_case_types)] @@ -510,7 +506,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -565,7 +560,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -627,7 +621,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -862,7 +855,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -947,7 +939,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -1001,7 +992,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { false } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -1057,7 +1047,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { true } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -1114,7 +1103,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { true } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -1174,7 +1162,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { true } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } #[allow(unused_imports)] @@ -1255,7 +1242,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { true } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } #[allow(unused_imports)] @@ -1337,7 +1323,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { true } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -1398,7 +1383,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { true } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -1457,7 +1441,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { true } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -1519,7 +1502,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { true } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -1578,7 +1560,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { true } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -1640,7 +1621,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { true } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -1700,7 +1680,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { true } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; @@ -1763,7 +1742,6 @@ mod generate_tests { } #[inline(always)] fn is_method_call(&self) -> bool { true } - #[inline(always)] fn is_variadic(&self) -> bool { false } } } }; diff --git a/src/plugin.rs b/src/plugin.rs index c183d736..73c2bb1d 100644 --- a/src/plugin.rs +++ b/src/plugin.rs @@ -25,7 +25,4 @@ pub trait PluginFunction { /// Is this plugin function a method? fn is_method_call(&self) -> bool; - - /// Is this plugin function variadic? - fn is_variadic(&self) -> bool; } From 76bd48d0a6705e3d257360563ca0f4559c651c39 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Sat, 29 May 2021 18:33:29 +0800 Subject: [PATCH 3/7] Code style refinements. --- CHANGELOG.md | 4 ++ src/dynamic.rs | 136 ++++++++++++++---------------------- src/engine.rs | 82 +++++++++++----------- src/engine_api.rs | 46 ++++++------ src/engine_settings.rs | 2 +- src/fn_call.rs | 62 ++++++---------- src/fn_func.rs | 4 +- src/fn_native.rs | 9 ++- src/optimize.rs | 2 +- src/packages/array_basic.rs | 2 +- src/packages/string_more.rs | 2 +- src/parser.rs | 2 +- 12 files changed, 157 insertions(+), 196 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40c5ae31..d2dafe5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,10 @@ Rhai Release Notes ================== +Version 0.20.3 +============== + + Version 0.20.2 ============== diff --git a/src/dynamic.rs b/src/dynamic.rs index 005252f5..a9eea0f0 100644 --- a/src/dynamic.rs +++ b/src/dynamic.rs @@ -711,6 +711,8 @@ impl fmt::Debug for Dynamic { } } +use AccessMode::*; + impl Clone for Dynamic { /// 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. fn clone(&self) -> Self { match self.0 { - Union::Unit(value, tag, _) => Self(Union::Unit(value, tag, AccessMode::ReadWrite)), - Union::Bool(value, tag, _) => Self(Union::Bool(value, tag, AccessMode::ReadWrite)), - Union::Str(ref value, tag, _) => { - Self(Union::Str(value.clone(), tag, AccessMode::ReadWrite)) - } - Union::Char(value, tag, _) => Self(Union::Char(value, tag, AccessMode::ReadWrite)), - Union::Int(value, tag, _) => Self(Union::Int(value, tag, AccessMode::ReadWrite)), + Union::Unit(value, tag, _) => Self(Union::Unit(value, tag, ReadWrite)), + Union::Bool(value, tag, _) => Self(Union::Bool(value, tag, ReadWrite)), + Union::Str(ref value, tag, _) => Self(Union::Str(value.clone(), tag, ReadWrite)), + Union::Char(value, tag, _) => Self(Union::Char(value, tag, ReadWrite)), + Union::Int(value, tag, _) => Self(Union::Int(value, tag, ReadWrite)), #[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")] 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"))] - Union::Array(ref value, tag, _) => { - Self(Union::Array(value.clone(), tag, AccessMode::ReadWrite)) - } + Union::Array(ref value, tag, _) => Self(Union::Array(value.clone(), tag, ReadWrite)), #[cfg(not(feature = "no_object"))] - Union::Map(ref value, tag, _) => { - Self(Union::Map(value.clone(), tag, AccessMode::ReadWrite)) - } - Union::FnPtr(ref value, tag, _) => { - Self(Union::FnPtr(value.clone(), tag, AccessMode::ReadWrite)) - } + Union::Map(ref value, tag, _) => Self(Union::Map(value.clone(), tag, ReadWrite)), + Union::FnPtr(ref value, tag, _) => Self(Union::FnPtr(value.clone(), tag, ReadWrite)), #[cfg(not(feature = "no_std"))] 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, _) => { @@ -755,9 +749,7 @@ impl Clone for Dynamic { } #[cfg(not(feature = "no_closure"))] - Union::Shared(ref cell, tag, _) => { - Self(Union::Shared(cell.clone(), tag, AccessMode::ReadWrite)) - } + Union::Shared(ref cell, tag, _) => Self(Union::Shared(cell.clone(), tag, ReadWrite)), } } } @@ -771,21 +763,21 @@ impl Default for Dynamic { impl Dynamic { /// 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`. - 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`]. - 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. - 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. - 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. - 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. - 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. - 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`. /// /// Not available under `no_float`. @@ -793,7 +785,7 @@ impl Dynamic { pub const FLOAT_ZERO: Dynamic = Self(Union::Float( FloatWrapper::const_new(0.0), DEFAULT_TAG, - AccessMode::ReadWrite, + ReadWrite, )); /// A [`Dynamic`] containing `1.0`. /// @@ -802,7 +794,7 @@ impl Dynamic { pub const FLOAT_ONE: Dynamic = Self(Union::Float( FloatWrapper::const_new(1.0), DEFAULT_TAG, - AccessMode::ReadWrite, + ReadWrite, )); /// A [`Dynamic`] containing `2.0`. /// @@ -811,7 +803,7 @@ impl Dynamic { pub const FLOAT_TWO: Dynamic = Self(Union::Float( FloatWrapper::const_new(2.0), DEFAULT_TAG, - AccessMode::ReadWrite, + ReadWrite, )); /// A [`Dynamic`] containing `10.0`. /// @@ -820,7 +812,7 @@ impl Dynamic { pub const FLOAT_TEN: Dynamic = Self(Union::Float( FloatWrapper::const_new(10.0), DEFAULT_TAG, - AccessMode::ReadWrite, + ReadWrite, )); /// A [`Dynamic`] containing the `-1.0`. /// @@ -829,7 +821,7 @@ impl Dynamic { pub const FLOAT_NEGATIVE_ONE: Dynamic = Self(Union::Float( FloatWrapper::const_new(-1.0), DEFAULT_TAG, - AccessMode::ReadWrite, + ReadWrite, )); /// Get the [`AccessMode`] for this [`Dynamic`]. @@ -898,7 +890,7 @@ impl Dynamic { pub fn is_read_only(&self) -> bool { #[cfg(not(feature = "no_closure"))] match self.0 { - Union::Shared(_, _, AccessMode::ReadOnly) => return true, + Union::Shared(_, _, ReadOnly) => return true, Union::Shared(ref cell, _, _) => { #[cfg(not(feature = "sync"))] let value = cell.borrow(); @@ -906,16 +898,16 @@ impl Dynamic { let value = cell.read().unwrap(); return match value.access_mode() { - AccessMode::ReadWrite => false, - AccessMode::ReadOnly => true, + ReadWrite => false, + ReadOnly => true, }; } _ => (), } match self.access_mode() { - AccessMode::ReadWrite => false, - AccessMode::ReadOnly => true, + ReadWrite => false, + ReadOnly => true, } } /// Can this [`Dynamic`] be hashed? @@ -1066,7 +1058,7 @@ impl Dynamic { Self(Union::Variant( Box::new(Box::new(value)), DEFAULT_TAG, - AccessMode::ReadWrite, + ReadWrite, )) } /// Turn the [`Dynamic`] value into a shared [`Dynamic`] value backed by an @@ -1788,37 +1780,33 @@ impl Dynamic { impl From<()> for Dynamic { #[inline(always)] fn from(value: ()) -> Self { - Self(Union::Unit(value, DEFAULT_TAG, AccessMode::ReadWrite)) + Self(Union::Unit(value, DEFAULT_TAG, ReadWrite)) } } impl From for Dynamic { #[inline(always)] fn from(value: bool) -> Self { - Self(Union::Bool(value, DEFAULT_TAG, AccessMode::ReadWrite)) + Self(Union::Bool(value, DEFAULT_TAG, ReadWrite)) } } impl From for Dynamic { #[inline(always)] 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"))] impl From for Dynamic { #[inline(always)] fn from(value: FLOAT) -> Self { - Self(Union::Float( - value.into(), - DEFAULT_TAG, - AccessMode::ReadWrite, - )) + Self(Union::Float(value.into(), DEFAULT_TAG, ReadWrite)) } } #[cfg(not(feature = "no_float"))] impl From> for Dynamic { #[inline(always)] fn from(value: FloatWrapper) -> Self { - Self(Union::Float(value, DEFAULT_TAG, AccessMode::ReadWrite)) + Self(Union::Float(value, DEFAULT_TAG, ReadWrite)) } } #[cfg(feature = "decimal")] @@ -1828,20 +1816,20 @@ impl From for Dynamic { Self(Union::Decimal( Box::new(value.into()), DEFAULT_TAG, - AccessMode::ReadWrite, + ReadWrite, )) } } impl From for Dynamic { #[inline(always)] fn from(value: char) -> Self { - Self(Union::Char(value, DEFAULT_TAG, AccessMode::ReadWrite)) + Self(Union::Char(value, DEFAULT_TAG, ReadWrite)) } } impl> From for Dynamic { #[inline(always)] 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 { @@ -1862,11 +1850,7 @@ impl Dynamic { /// Create a [`Dynamic`] from an [`Array`]. #[inline(always)] pub(crate) fn from_array(array: Array) -> Self { - Self(Union::Array( - Box::new(array), - DEFAULT_TAG, - AccessMode::ReadWrite, - )) + Self(Union::Array(Box::new(array), DEFAULT_TAG, ReadWrite)) } } #[cfg(not(feature = "no_index"))] @@ -1876,7 +1860,7 @@ impl From> for Dynamic { Self(Union::Array( Box::new(value.into_iter().map(Dynamic::from).collect()), DEFAULT_TAG, - AccessMode::ReadWrite, + ReadWrite, )) } } @@ -1887,7 +1871,7 @@ impl From<&[T]> for Dynamic { Self(Union::Array( Box::new(value.iter().cloned().map(Dynamic::from).collect()), DEFAULT_TAG, - AccessMode::ReadWrite, + ReadWrite, )) } } @@ -1898,7 +1882,7 @@ impl std::iter::FromIterator for Dynamic { Self(Union::Array( Box::new(iter.into_iter().map(Dynamic::from).collect()), DEFAULT_TAG, - AccessMode::ReadWrite, + ReadWrite, )) } } @@ -1907,11 +1891,7 @@ impl Dynamic { /// Create a [`Dynamic`] from a [`Map`]. #[inline(always)] pub(crate) fn from_map(map: Map) -> Self { - Self(Union::Map( - Box::new(map), - DEFAULT_TAG, - AccessMode::ReadWrite, - )) + Self(Union::Map(Box::new(map), DEFAULT_TAG, ReadWrite)) } } #[cfg(not(feature = "no_object"))] @@ -1929,7 +1909,7 @@ impl, T: Variant + Clone> From, T: Variant + Clone> From for Dynamic { #[inline(always)] fn from(value: FnPtr) -> Self { - Self(Union::FnPtr( - Box::new(value), - DEFAULT_TAG, - AccessMode::ReadWrite, - )) + Self(Union::FnPtr(Box::new(value), DEFAULT_TAG, ReadWrite)) } } impl From> for Dynamic { #[inline(always)] fn from(value: Box) -> Self { - Self(Union::FnPtr(value, DEFAULT_TAG, AccessMode::ReadWrite)) + Self(Union::FnPtr(value, DEFAULT_TAG, ReadWrite)) } } #[cfg(not(feature = "no_std"))] impl From for Dynamic { #[inline(always)] fn from(value: Instant) -> Self { - Self(Union::TimeStamp( - Box::new(value), - DEFAULT_TAG, - AccessMode::ReadWrite, - )) + Self(Union::TimeStamp(Box::new(value), DEFAULT_TAG, ReadWrite)) } } #[cfg(not(feature = "no_closure"))] impl From>> for Dynamic { #[inline(always)] fn from(value: crate::Shared>) -> Self { - Self(Union::Shared( - value.into(), - DEFAULT_TAG, - AccessMode::ReadWrite, - )) + Self(Union::Shared(value.into(), DEFAULT_TAG, ReadWrite)) } } diff --git a/src/engine.rs b/src/engine.rs index 63f9ed23..7e73572c 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -263,7 +263,7 @@ enum ChainArgument { Property(Position), /// Arguments to a dot method call. #[cfg(not(feature = "no_object"))] - MethodCallArgs(StaticVec, StaticVec), + MethodCallArgs(StaticVec, Position), /// Index value. #[cfg(not(feature = "no_index"))] IndexValue(Dynamic, Position), @@ -294,7 +294,7 @@ impl ChainArgument { /// Panics if not `ChainArgument::MethodCallArgs`. #[inline(always)] #[cfg(not(feature = "no_object"))] - pub fn as_fn_call_args(self) -> (StaticVec, StaticVec) { + pub fn as_fn_call_args(self) -> (StaticVec, Position) { match self { Self::Property(_) => { panic!("expecting ChainArgument::MethodCallArgs") @@ -303,16 +303,16 @@ impl ChainArgument { Self::IndexValue(_, _) => { panic!("expecting ChainArgument::MethodCallArgs") } - Self::MethodCallArgs(values, positions) => (values, positions), + Self::MethodCallArgs(values, pos) => (values, pos), } } } #[cfg(not(feature = "no_object"))] -impl From<(StaticVec, StaticVec)> for ChainArgument { +impl From<(StaticVec, Position)> for ChainArgument { #[inline(always)] - fn from((values, positions): (StaticVec, StaticVec)) -> Self { - Self::MethodCallArgs(values, positions) + fn from((values, pos): (StaticVec, Position)) -> Self { + Self::MethodCallArgs(values, pos) } } @@ -787,7 +787,7 @@ pub struct Engine { /// A module resolution service. #[cfg(not(feature = "no_module"))] - pub(crate) module_resolver: Box, + pub(crate) module_resolver: Option>, /// A map mapping type names to pretty-print names. pub(crate) type_names: BTreeMap>, @@ -890,10 +890,10 @@ impl Engine { #[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_std"))] #[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(any(feature = "no_std", target_arch = "wasm32",))] - module_resolver: Box::new(crate::module::resolvers::DummyModuleResolver::new()), + module_resolver: None, type_names: Default::default(), empty_string: Default::default(), @@ -950,7 +950,7 @@ impl Engine { global_sub_modules: Default::default(), #[cfg(not(feature = "no_module"))] - module_resolver: Box::new(crate::module::resolvers::DummyModuleResolver::new()), + module_resolver: None, type_names: Default::default(), empty_string: Default::default(), @@ -1629,24 +1629,25 @@ impl Engine { match expr { #[cfg(not(feature = "no_object"))] Expr::FnCall(x, _) if _parent_chain_type == ChainType::Dot && !x.is_qualified() => { - let mut arg_positions: StaticVec<_> = Default::default(); - - let mut arg_values = x + let arg_values = x .args .iter() - .inspect(|arg_expr| arg_positions.push(arg_expr.position())) .map(|arg_expr| { self.eval_expr(scope, mods, state, lib, this_ptr, arg_expr, level) .map(Dynamic::flatten) }) + .chain(x.literal_args.iter().map(|(v, _)| Ok(v.clone()))) .collect::, _>>()?; - x.literal_args + let pos = x + .args .iter() - .inspect(|(_, pos)| arg_positions.push(*pos)) - .for_each(|(v, _)| arg_values.push(v.clone())); + .map(|arg_expr| arg_expr.position()) + .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"))] Expr::FnCall(_, _) if _parent_chain_type == ChainType::Dot => { @@ -1674,24 +1675,25 @@ impl Engine { Expr::FnCall(x, _) if _parent_chain_type == ChainType::Dot && !x.is_qualified() => { - let mut arg_positions: StaticVec<_> = Default::default(); - - let mut arg_values = x + let arg_values = x .args .iter() - .inspect(|arg_expr| arg_positions.push(arg_expr.position())) .map(|arg_expr| { self.eval_expr(scope, mods, state, lib, this_ptr, arg_expr, level) .map(Dynamic::flatten) }) + .chain(x.literal_args.iter().map(|(v, _)| Ok(v.clone()))) .collect::, _>>()?; - x.literal_args + let pos = x + .args .iter() - .inspect(|(_, pos)| arg_positions.push(*pos)) - .for_each(|(v, _)| arg_values.push(v.clone())); + .map(|arg_expr| arg_expr.position()) + .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"))] Expr::FnCall(_, _) if _parent_chain_type == ChainType::Dot => { @@ -2037,11 +2039,7 @@ impl Engine { Expr::Unit(_) => Ok(Dynamic::UNIT), Expr::Custom(custom, _) => { - let expressions = custom - .keywords - .iter() - .map(Into::into) - .collect::>(); + let expressions: StaticVec<_> = custom.keywords.iter().map(Into::into).collect(); let key_token = custom.tokens.first().expect( "never fails because a custom syntax stream must contain at least one token", ); @@ -2757,20 +2755,26 @@ impl Engine { use crate::ModuleResolver; let source = state.source.as_ref().map(|s| s.as_str()); - let expr_pos = expr.position(); + let path_pos = expr.position(); let module = state .resolver .as_ref() - .and_then(|r| match r.resolve(self, source, &path, expr_pos) { - Ok(m) => return Some(Ok(m)), - Err(err) => match *err { - EvalAltResult::ErrorModuleNotFound(_, _) => None, - _ => return Some(Err(err)), - }, + .and_then(|r| match r.resolve(self, source, &path, path_pos) { + Err(err) + if matches!(*err, EvalAltResult::ErrorModuleNotFound(_, _)) => + { + None + } + result => Some(result), + }) + .or_else(|| { + self.module_resolver + .as_ref() + .map(|r| r.resolve(self, source, &path, path_pos)) }) .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| { diff --git a/src/engine_api.rs b/src/engine_api.rs index 6a847647..b9d41ee1 100644 --- a/src/engine_api.rs +++ b/src/engine_api.rs @@ -1101,38 +1101,34 @@ impl Engine { }); } - let mut resolver = StaticModuleResolver::new(); let mut ast = self.compile_scripts_with_scope(scope, &[script])?; - let mut imports = Default::default(); - collect_imports(&ast, &mut resolver, &mut imports); + if let Some(ref module_resolver) = self.module_resolver { + let mut resolver = StaticModuleResolver::new(); + let mut imports = Default::default(); - if !imports.is_empty() { - while let Some(path) = imports.iter().next() { - let path = path.clone(); + collect_imports(&ast, &mut resolver, &mut imports); - match self - .module_resolver - .resolve_ast(self, None, &path, Position::NONE) - { - Some(Ok(module_ast)) => { - collect_imports(&module_ast, &mut resolver, &mut imports) + if !imports.is_empty() { + while let Some(path) = imports.iter().next() { + let path = path.clone(); + + match module_resolver.resolve_ast(self, None, &path, Position::NONE) { + Some(Ok(module_ast)) => { + collect_imports(&module_ast, &mut resolver, &mut imports) + } + Some(err) => return err, + None => (), } - Some(err) => return err, - None => (), + + let module = module_resolver.resolve(self, None, &path, Position::NONE)?; + let module = shared_take_or_clone(module); + + imports.remove(&path); + resolver.insert(path, module); } - - let module = shared_take_or_clone(self.module_resolver.resolve( - self, - None, - &path, - Position::NONE, - )?); - - imports.remove(&path); - resolver.insert(path, module); + ast.set_resolver(resolver); } - ast.set_resolver(resolver); } Ok(ast) diff --git a/src/engine_settings.rs b/src/engine_settings.rs index a995c71b..abce7e33 100644 --- a/src/engine_settings.rs +++ b/src/engine_settings.rs @@ -188,7 +188,7 @@ impl Engine { &mut self, resolver: impl crate::ModuleResolver + 'static, ) -> &mut Self { - self.module_resolver = Box::new(resolver); + self.module_resolver = Some(Box::new(resolver)); self } /// Disable a particular keyword or operator in the language. diff --git a/src/fn_call.rs b/src/fn_call.rs index 666add57..88e42578 100644 --- a/src/fn_call.rs +++ b/src/fn_call.rs @@ -515,13 +515,11 @@ impl Engine { ); // 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 { state.push_fn_resolution_cache(); - lib_merged = once(env_lib.as_ref()) - .chain(lib.iter().cloned()) - .collect::>(); + lib_merged = once(env_lib.as_ref()).chain(lib.iter().cloned()).collect(); (lib_merged.as_ref(), true) } else { (lib, false) @@ -895,20 +893,16 @@ impl Engine { fn_name: &str, mut hash: FnCallHashes, target: &mut crate::engine::Target, - (call_args, call_arg_positions): &mut (StaticVec, StaticVec), + (call_args, call_arg_pos): &mut (StaticVec, Position), pos: Position, level: usize, ) -> Result<(Dynamic, bool), Box> { 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 { - KEYWORD_FN_PTR_CALL if obj.is::() => { + KEYWORD_FN_PTR_CALL if target.is::() => { // FnPtr call - let fn_ptr = obj + let fn_ptr = target .read_lock::() .expect("never fails because `obj` is `FnPtr`"); // Redirect function name @@ -917,11 +911,8 @@ impl Engine { // Recalculate hashes let new_hash = FnCallHashes::from_script(calc_fn_hash(fn_name, args_len)); // Arguments are passed as-is, adding the curried arguments - let mut curry = fn_ptr.curry().iter().cloned().collect::>(); - let mut args = curry - .iter_mut() - .chain(call_args.iter_mut()) - .collect::>(); + let mut curry: StaticVec<_> = fn_ptr.curry().iter().cloned().collect(); + let mut args: StaticVec<_> = curry.iter_mut().chain(call_args.iter_mut()).collect(); // Map it to name(args) in function-call style self.exec_fn_call( @@ -932,20 +923,19 @@ impl Engine { if call_args.len() > 0 { if !call_args[0].is::() { return Err(self.make_type_mismatch_err::( - self.map_type_name(obj.type_name()), - call_arg_positions[0], + self.map_type_name(target.type_name()), + *call_arg_pos, )); } } else { return Err(self.make_type_mismatch_err::( - self.map_type_name(obj.type_name()), + self.map_type_name(target.type_name()), pos, )); } // FnPtr call on object let fn_ptr = call_args.remove(0).cast::(); - call_arg_positions.remove(0); // Redirect function name let fn_name = fn_ptr.fn_name(); let args_len = call_args.len() + fn_ptr.curry().len(); @@ -955,11 +945,11 @@ impl Engine { calc_fn_hash(fn_name, args_len + 1), ); // Replace the first argument with the object pointer, adding the curried arguments - let mut curry = fn_ptr.curry().iter().cloned().collect::>(); - let mut args = once(obj) + let mut curry: StaticVec<_> = fn_ptr.curry().iter().cloned().collect(); + let mut args: StaticVec<_> = once(target.as_mut()) .chain(curry.iter_mut()) .chain(call_args.iter_mut()) - .collect::>(); + .collect(); // Map it to name(args) in function-call style self.exec_fn_call( @@ -967,14 +957,14 @@ impl Engine { ) } KEYWORD_FN_PTR_CURRY => { - if !obj.is::() { + if !target.is::() { return Err(self.make_type_mismatch_err::( - self.map_type_name(obj.type_name()), + self.map_type_name(target.type_name()), pos, )); } - let fn_ptr = obj + let fn_ptr = target .read_lock::() .expect("never fails because `obj` is `FnPtr`"); @@ -1005,26 +995,21 @@ impl Engine { } _ => { + let mut fn_name = fn_name; let _redirected; // Check if it is a map method call in OOP style #[cfg(not(feature = "no_object"))] - if let Some(map) = obj.read_lock::() { + if let Some(map) = target.read_lock::() { if let Some(val) = map.get(fn_name) { if let Some(fn_ptr) = val.read_lock::() { // Remap the function name _redirected = fn_ptr.get_fn_name().clone(); fn_name = &_redirected; // Add curried arguments - fn_ptr - .curry() - .iter() - .cloned() - .enumerate() - .for_each(|(i, v)| { - call_args.insert(i, v); - call_arg_positions.insert(i, Position::NONE); - }); + if fn_ptr.is_curried() { + call_args.insert_many(0, fn_ptr.curry().iter().cloned()); + } // Recalculate the hash based on the new function name and new arguments hash = FnCallHashes::from_script_and_native( calc_fn_hash(fn_name, call_args.len()), @@ -1035,9 +1020,8 @@ impl Engine { }; // Attached object pointer in front of the arguments - let mut args = once(obj) - .chain(call_args.iter_mut()) - .collect::>(); + let mut args: StaticVec<_> = + once(target.as_mut()).chain(call_args.iter_mut()).collect(); self.exec_fn_call( mods, state, lib, fn_name, hash, &mut args, is_ref, true, pos, None, level, diff --git a/src/fn_func.rs b/src/fn_func.rs index 3c51911a..c465dab6 100644 --- a/src/fn_func.rs +++ b/src/fn_func.rs @@ -4,7 +4,7 @@ #![allow(non_snake_case)] use crate::dynamic::Variant; -use crate::{Engine, EvalAltResult, ParseError, Scope, AST}; +use crate::{Engine, EvalAltResult, ParseError, Scope, SmartString, AST}; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -98,7 +98,7 @@ macro_rules! def_anonymous_fn { #[inline(always)] 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,)*))) } diff --git a/src/fn_native.rs b/src/fn_native.rs index 0b22fe9b..964488d0 100644 --- a/src/fn_native.rs +++ b/src/fn_native.rs @@ -314,6 +314,11 @@ impl FnPtr { pub fn is_curried(&self) -> bool { !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? /// /// Not available under `no_function`. @@ -339,7 +344,7 @@ impl FnPtr { this_ptr: Option<&mut Dynamic>, mut arg_values: impl AsMut<[Dynamic]>, ) -> RhaiResult { - let mut args_data; + let mut args_data: StaticVec<_>; let arg_values = if self.curry().is_empty() { arg_values.as_mut() @@ -349,7 +354,7 @@ impl FnPtr { .iter() .cloned() .chain(arg_values.as_mut().iter_mut().map(mem::take)) - .collect::>(); + .collect(); args_data.as_mut() }; diff --git a/src/optimize.rs b/src/optimize.rs index 52c4926e..90fae768 100644 --- a/src/optimize.rs +++ b/src/optimize.rs @@ -147,7 +147,7 @@ fn call_fn_with_constant_arguments( state.lib, fn_name, calc_fn_hash(fn_name, arg_values.len()), - arg_values.iter_mut().collect::>().as_mut(), + &mut arg_values.iter_mut().collect::>(), false, false, Position::NONE, diff --git a/src/packages/array_basic.rs b/src/packages/array_basic.rs index 13cbcb19..599a7540 100644 --- a/src/packages/array_basic.rs +++ b/src/packages/array_basic.rs @@ -745,7 +745,7 @@ mod array_functions { len as usize }; - let mut drained = array.drain(..start).collect::(); + let mut drained: Array = array.drain(..start).collect(); drained.extend(array.drain(len..)); drained diff --git a/src/packages/string_more.rs b/src/packages/string_more.rs index 97700e86..a88ddf84 100644 --- a/src/packages/string_more.rs +++ b/src/packages/string_more.rs @@ -110,7 +110,7 @@ mod string_functions { pub fn index_of_char_starting_from(string: &str, character: char, start: INT) -> INT { let start = if start < 0 { if let Some(n) = start.checked_abs() { - let chars = string.chars().collect::>(); + let chars: Vec<_> = string.chars().collect(); let num_chars = chars.len(); if n as usize > num_chars { 0 diff --git a/src/parser.rs b/src/parser.rs index d087f518..6ea22399 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1864,7 +1864,7 @@ fn parse_custom_syntax( state.stack.push((empty, AccessMode::ReadWrite)); } - let parse_func = &syntax.parse; + let parse_func = syntax.parse.as_ref(); segments.push(key.into()); tokens.push(key.into()); From 25e99af07e72485337ee2e777022d783dd5883a2 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Tue, 1 Jun 2021 11:13:56 +0800 Subject: [PATCH 4/7] Add Zulip. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 568b8982..f56d179b 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ Rhai - Embedded Scripting for Rust [![VS Code plugin installs](https://img.shields.io/visual-studio-marketplace/i/rhaiscript.vscode-rhai?logo=visual-studio-code&label=vs%20code)](https://marketplace.visualstudio.com/items?itemName=rhaiscript.vscode-rhai) [![Sublime Text package downloads](https://img.shields.io/packagecontrol/dt/Rhai.svg?logo=sublime-text&label=sublime%20text)](https://packagecontrol.io/packages/Rhai) [![Discord Chat](https://img.shields.io/discord/767611025456889857.svg?logo=discord&label=discord)](https://discord.gg/HquqbYFcZ9) +[![Zulip Chat](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg?logo=zulip)](https://rhaiscript.zulipchat.com) [![Reddit Channel](https://img.shields.io/reddit/subreddit-subscribers/Rhai?logo=reddit&label=reddit)](https://www.reddit.com/r/Rhai) [![Rhai logo](https://rhai.rs/book/images/logo/rhai-banner-transparent-colour.svg)](https://rhai.rs) From 71684f5e2ab405ba00ae574c2e8c015059d345f3 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Wed, 2 Jun 2021 14:29:18 +0800 Subject: [PATCH 5/7] Implement bit-fields. --- CHANGELOG.md | 10 +++ src/ast.rs | 4 +- src/bin/rhai-run.rs | 2 +- src/engine.rs | 171 ++++++++++++++++++++++++++++--------- src/fn_call.rs | 1 + src/optimize.rs | 96 ++++++++++++--------- src/packages/iter_basic.rs | 90 +++++++++++++++++-- src/packages/logic.rs | 164 +++++++++++++++++++++++++++++++++-- src/parser.rs | 5 +- src/result.rs | 16 +++- tests/bit_shift.rs | 35 ++++++++ 11 files changed, 497 insertions(+), 97 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d2dafe5b..990ceab6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ Rhai Release Notes Version 0.20.3 ============== +Bug fixes +--------- + +* Fixed incorrect optimization regarding chain-indexing with non-numeric index. + +New features +------------ + +* An integer value can now be indexed to get/set a single bit. + Version 0.20.2 ============== diff --git a/src/ast.rs b/src/ast.rs index 3fd9f6fd..7a0dfd73 100644 --- a/src/ast.rs +++ b/src/ast.rs @@ -2014,13 +2014,13 @@ impl Expr { Self::DynamicConstant(_, _) | Self::BoolConstant(_, _) - | Self::IntegerConstant(_, _) | Self::CharConstant(_, _) | Self::And(_, _) | Self::Or(_, _) | Self::Unit(_) => false, - Self::StringConstant(_, _) + Self::IntegerConstant(_, _) + | Self::StringConstant(_, _) | Self::InterpolatedString(_) | Self::FnCall(_, _) | Self::Stmt(_) diff --git a/src/bin/rhai-run.rs b/src/bin/rhai-run.rs index 887cffc4..e2867515 100644 --- a/src/bin/rhai-run.rs +++ b/src/bin/rhai-run.rs @@ -83,7 +83,7 @@ fn main() { if let Err(err) = engine .compile(contents) - .map_err(|err| Box::new(err.into()) as Box) + .map_err(|err| err.into()) .and_then(|mut ast| { ast.set_source(filename.to_string_lossy().to_string()); engine.consume_ast(&ast) diff --git a/src/engine.rs b/src/engine.rs index 7e73572c..023729b7 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -336,6 +336,10 @@ pub enum Target<'a> { LockGuard((crate::dynamic::DynamicWriteLock<'a, Dynamic>, Dynamic)), /// The target is a temporary `Dynamic` value (i.e. the mutation can cause no side effects). Value(Dynamic), + /// The target is a bit inside an [`INT`][crate::INT]. + /// This is necessary because directly pointing to a bit inside an [`INT`][crate::INT] is impossible. + #[cfg(not(feature = "no_index"))] + BitField(&'a mut Dynamic, usize, Dynamic), /// The target is a character inside a String. /// This is necessary because directly pointing to a char inside a String is impossible. #[cfg(not(feature = "no_index"))] @@ -354,6 +358,8 @@ impl<'a> Target<'a> { Self::LockGuard(_) => true, Self::Value(_) => false, #[cfg(not(feature = "no_index"))] + Self::BitField(_, _, _) => false, + #[cfg(not(feature = "no_index"))] Self::StringChar(_, _, _) => false, } } @@ -368,6 +374,8 @@ impl<'a> Target<'a> { Self::LockGuard(_) => false, Self::Value(_) => true, #[cfg(not(feature = "no_index"))] + Self::BitField(_, _, _) => false, + #[cfg(not(feature = "no_index"))] Self::StringChar(_, _, _) => false, } } @@ -382,6 +390,8 @@ impl<'a> Target<'a> { Self::LockGuard(_) => true, Self::Value(r) => r.is_shared(), #[cfg(not(feature = "no_index"))] + Self::BitField(_, _, _) => false, + #[cfg(not(feature = "no_index"))] Self::StringChar(_, _, _) => false, } } @@ -396,6 +406,8 @@ impl<'a> Target<'a> { Self::LockGuard((r, _)) => r.is::(), Self::Value(r) => r.is::(), #[cfg(not(feature = "no_index"))] + Self::BitField(_, _, _) => TypeId::of::() == TypeId::of::(), + #[cfg(not(feature = "no_index"))] Self::StringChar(_, _, _) => TypeId::of::() == TypeId::of::(), } } @@ -409,6 +421,8 @@ impl<'a> Target<'a> { Self::LockGuard((_, orig)) => orig, // Original value is simply taken Self::Value(v) => v, // Owned value is simply taken #[cfg(not(feature = "no_index"))] + Self::BitField(_, _, value) => value, // Boolean is taken + #[cfg(not(feature = "no_index"))] Self::StringChar(_, _, ch) => ch, // Character is taken } } @@ -435,9 +449,14 @@ impl<'a> Target<'a> { #[cfg(not(feature = "no_closure"))] Self::LockGuard(_) => Ok(()), #[cfg(not(feature = "no_index"))] + Self::BitField(_, _, value) => { + let new_val = value.clone(); + self.set_value(new_val, Position::NONE) + } + #[cfg(not(feature = "no_index"))] Self::StringChar(_, _, ch) => { - let char_value = ch.clone(); - self.set_value(char_value, Position::NONE) + let new_val = ch.clone(); + self.set_value(new_val, Position::NONE) } } } @@ -454,6 +473,32 @@ impl<'a> Target<'a> { Self::LockGuard((r, _)) => **r = new_val, Self::Value(_) => panic!("cannot update a value"), #[cfg(not(feature = "no_index"))] + Self::BitField(value, index, _) => { + let value = &mut *value + .write_lock::() + .expect("never fails because `BitField` always holds an `INT`"); + + // Replace the bit at the specified index position + let new_bit = new_val.as_bool().map_err(|err| { + Box::new(EvalAltResult::ErrorMismatchDataType( + "bool".to_string(), + err.to_string(), + _pos, + )) + })?; + + let index = *index; + + if index < std::mem::size_of_val(value) * 8 { + let mask = 1 << index; + if new_bit { + *value |= mask; + } else { + *value &= !mask; + } + } + } + #[cfg(not(feature = "no_index"))] Self::StringChar(s, index, _) => { let s = &mut *s .write_lock::() @@ -514,6 +559,8 @@ impl Deref for Target<'_> { Self::LockGuard((r, _)) => &**r, Self::Value(ref r) => r, #[cfg(not(feature = "no_index"))] + Self::BitField(_, _, ref r) => r, + #[cfg(not(feature = "no_index"))] Self::StringChar(_, _, ref r) => r, } } @@ -536,6 +583,8 @@ impl DerefMut for Target<'_> { Self::LockGuard((r, _)) => r.deref_mut(), Self::Value(ref mut r) => r, #[cfg(not(feature = "no_index"))] + Self::BitField(_, _, ref mut r) => r, + #[cfg(not(feature = "no_index"))] Self::StringChar(_, _, ref mut r) => r, } } @@ -1818,6 +1867,43 @@ impl Engine { .unwrap_or_else(|| Target::from(Dynamic::UNIT))) } + #[cfg(not(feature = "no_index"))] + Dynamic(Union::Int(value, _, _)) => { + // val_int[idx] + let index = idx + .as_int() + .map_err(|err| self.make_type_mismatch_err::(err, idx_pos))?; + + let bits = std::mem::size_of_val(value) * 8; + + let (bit_value, offset) = if index >= 0 { + let offset = index as usize; + ( + if offset >= bits { + return EvalAltResult::ErrorBitFieldBounds(bits, index, idx_pos).into(); + } else { + (*value & (1 << offset)) != 0 + }, + offset, + ) + } else if let Some(abs_index) = index.checked_abs() { + let offset = abs_index as usize; + ( + // Count from end if negative + if offset > bits { + return EvalAltResult::ErrorBitFieldBounds(bits, index, idx_pos).into(); + } else { + (*value & (1 << (bits - offset))) != 0 + }, + offset, + ) + } else { + return EvalAltResult::ErrorBitFieldBounds(bits, index, idx_pos).into(); + }; + + Ok(Target::BitField(target, offset, bit_value.into())) + } + #[cfg(not(feature = "no_index"))] Dynamic(Union::Str(s, _, _)) => { // val_string[idx] @@ -1826,7 +1912,6 @@ impl Engine { .map_err(|err| self.make_type_mismatch_err::(err, idx_pos))?; let (ch, offset) = if index >= 0 { - // Count from end if negative let offset = index as usize; ( s.chars().nth(offset).ok_or_else(|| { @@ -1835,9 +1920,10 @@ impl Engine { })?, offset, ) - } else if let Some(index) = index.checked_abs() { - let offset = index as usize; + } else if let Some(abs_index) = index.checked_abs() { + let offset = abs_index as usize; ( + // Count from end if negative s.chars().rev().nth(offset - 1).ok_or_else(|| { let chars_len = s.chars().count(); EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos) @@ -2153,8 +2239,8 @@ impl Engine { op_pos: Position, mut target: Target, root: (&str, Position), - mut new_value: Dynamic, - new_value_pos: Position, + mut new_val: Dynamic, + new_val_pos: Position, ) -> Result<(), Box> { if target.is_read_only() { // Assignment to constant variable @@ -2167,48 +2253,51 @@ impl Engine { op, }) = op_info { - let mut lock_guard; - let lhs_ptr_inner; + { + let mut lock_guard; + let lhs_ptr_inner; - #[cfg(not(feature = "no_closure"))] - let target_is_shared = target.is_shared(); - #[cfg(feature = "no_closure")] - let target_is_shared = false; + #[cfg(not(feature = "no_closure"))] + let target_is_shared = target.is_shared(); + #[cfg(feature = "no_closure")] + let target_is_shared = false; - if target_is_shared { - lock_guard = target - .write_lock::() - .expect("never fails when casting to `Dynamic`"); - lhs_ptr_inner = &mut *lock_guard; - } else { - lhs_ptr_inner = &mut *target; - } - - let hash = hash_op_assign; - let args = &mut [lhs_ptr_inner, &mut new_value]; - - match self.call_native_fn(mods, state, lib, op, hash, args, true, true, op_pos) { - Ok(_) => (), - Err(err) if matches!(err.as_ref(), EvalAltResult::ErrorFunctionNotFound(f, _) if f.starts_with(op)) => - { - // Expand to `var = var op rhs` - let op = &op[..op.len() - 1]; // extract operator without = - - // Run function - let (value, _) = self - .call_native_fn(mods, state, lib, op, hash_op, args, true, false, op_pos)?; - - *args[0] = value.flatten(); + if target_is_shared { + lock_guard = target + .write_lock::() + .expect("never fails when casting to `Dynamic`"); + lhs_ptr_inner = &mut *lock_guard; + } else { + lhs_ptr_inner = &mut *target; + } + + let hash = hash_op_assign; + let args = &mut [lhs_ptr_inner, &mut new_val]; + + match self.call_native_fn(mods, state, lib, op, hash, args, true, true, op_pos) { + Err(err) if matches!(err.as_ref(), EvalAltResult::ErrorFunctionNotFound(f, _) if f.starts_with(op)) => + { + // Expand to `var = var op rhs` + let op = &op[..op.len() - 1]; // extract operator without = + + // Run function + let (value, _) = self.call_native_fn( + mods, state, lib, op, hash_op, args, true, false, op_pos, + )?; + + *args[0] = value.flatten(); + } + err => return err.map(|_| ()), } - err => return err.map(|_| ()), } - Ok(()) + target.propagate_changed_value()?; } else { // Normal assignment - target.set_value(new_value, new_value_pos)?; - Ok(()) + target.set_value(new_val, new_val_pos)?; } + + Ok(()) } /// Evaluate a statement. diff --git a/src/fn_call.rs b/src/fn_call.rs index 88e42578..27cc2116 100644 --- a/src/fn_call.rs +++ b/src/fn_call.rs @@ -1400,6 +1400,7 @@ impl Engine { arg_values[0] = target.take_or_clone().flatten(); args = arg_values.iter_mut().collect(); } else { + // Turn it into a method call only if the object is not shared and not a simple value let (first, rest) = arg_values .split_first_mut() .expect("never fails because the arguments list is not empty"); diff --git a/src/optimize.rs b/src/optimize.rs index 90fae768..d78f5ca4 100644 --- a/src/optimize.rs +++ b/src/optimize.rs @@ -202,7 +202,7 @@ fn optimize_stmt_block( match stmt { // Add constant literals into the state Stmt::Const(value_expr, x, _, _) => { - optimize_expr(value_expr, state); + optimize_expr(value_expr, state, false); if value_expr.is_constant() { state.push_var( @@ -214,7 +214,7 @@ fn optimize_stmt_block( } // Add variables into the state Stmt::Let(value_expr, x, _, _) => { - optimize_expr(value_expr, state); + optimize_expr(value_expr, state, false); state.push_var(&x.name, AccessMode::ReadWrite, None); } // Optimize the statement @@ -392,10 +392,10 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) { // expr op= expr Stmt::Assignment(x, _) => match x.0 { - Expr::Variable(_, _, _) => optimize_expr(&mut x.2, state), + Expr::Variable(_, _, _) => optimize_expr(&mut x.2, state, false), _ => { - optimize_expr(&mut x.0, state); - optimize_expr(&mut x.2, state); + optimize_expr(&mut x.0, state, false); + optimize_expr(&mut x.2, state, false); } }, @@ -405,7 +405,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) { let pos = condition.position(); let mut expr = mem::take(condition); - optimize_expr(&mut expr, state); + optimize_expr(&mut expr, state, false); *stmt = if preserve_result { // -> { expr, Noop } @@ -440,7 +440,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) { } // if expr { if_block } else { else_block } Stmt::If(condition, x, _) => { - optimize_expr(condition, state); + optimize_expr(condition, state, false); let if_block = mem::take(x.0.statements()).into_vec(); *x.0.statements() = optimize_stmt_block(if_block, state, preserve_result, true, false).into(); @@ -462,7 +462,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) { if let Some(block) = table.get_mut(&hash) { if let Some(mut condition) = mem::take(&mut block.0) { // switch const { case if condition => stmt, _ => def } => if condition { stmt } else { def } - optimize_expr(&mut condition, state); + optimize_expr(&mut condition, state, false); let def_block = mem::take(&mut *x.1).into_vec(); let def_stmt = optimize_stmt_block(def_block, state, true, true, false); @@ -502,12 +502,12 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) { } // switch Stmt::Switch(match_expr, x, _) => { - optimize_expr(match_expr, state); + optimize_expr(match_expr, state, false); x.0.values_mut().for_each(|block| { let condition = mem::take(&mut block.0).map_or_else( || Expr::Unit(Position::NONE), |mut condition| { - optimize_expr(&mut condition, state); + optimize_expr(&mut condition, state, false); condition }, ); @@ -550,7 +550,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) { } // while expr { block } Stmt::While(condition, body, _) => { - optimize_expr(condition, state); + optimize_expr(condition, state, false); let block = mem::take(body.statements()).into_vec(); *body.statements() = optimize_stmt_block(block, state, false, true, false).into(); @@ -587,21 +587,21 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) { } // do { block } while|until expr Stmt::Do(body, condition, _, _) => { - optimize_expr(condition, state); + optimize_expr(condition, state, false); let block = mem::take(body.statements()).into_vec(); *body.statements() = optimize_stmt_block(block, state, false, true, false).into(); } // for id in expr { block } Stmt::For(iterable, x, _) => { - optimize_expr(iterable, state); + optimize_expr(iterable, state, false); let body = mem::take(x.1.statements()).into_vec(); *x.1.statements() = optimize_stmt_block(body, state, false, true, false).into(); } // let id = expr; - Stmt::Let(expr, _, _, _) => optimize_expr(expr, state), + Stmt::Let(expr, _, _, _) => optimize_expr(expr, state, false), // import expr as var; #[cfg(not(feature = "no_module"))] - Stmt::Import(expr, _, _) => optimize_expr(expr, state), + Stmt::Import(expr, _, _) => optimize_expr(expr, state, false), // { block } Stmt::Block(statements, pos) => { let statements = mem::take(statements).into_vec(); @@ -640,7 +640,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) { } // func(...) Stmt::Expr(expr @ Expr::FnCall(_, _)) => { - optimize_expr(expr, state); + optimize_expr(expr, state, false); match expr { Expr::FnCall(x, pos) => { state.set_dirty(); @@ -660,9 +660,9 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) { *stmt = mem::take(x.as_mut()).into(); } // expr; - Stmt::Expr(expr) => optimize_expr(expr, state), + Stmt::Expr(expr) => optimize_expr(expr, state, false), // return expr; - Stmt::Return(_, Some(ref mut expr), _) => optimize_expr(expr, state), + Stmt::Return(_, Some(ref mut expr), _) => optimize_expr(expr, state, false), // All other statements - skip _ => (), @@ -670,7 +670,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) { } /// Optimize an [expression][Expr]. -fn optimize_expr(expr: &mut Expr, state: &mut State) { +fn optimize_expr(expr: &mut Expr, state: &mut State, indexing: bool) { // These keywords are handled specially const DONT_EVAL_KEYWORDS: &[&str] = &[ KEYWORD_PRINT, // side effects @@ -693,7 +693,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) { } // lhs.rhs #[cfg(not(feature = "no_object"))] - Expr::Dot(x, _) => match (&mut x.lhs, &mut x.rhs) { + Expr::Dot(x, _) if !indexing => match (&mut x.lhs, &mut x.rhs) { // map.string (Expr::Map(m, pos), Expr::Property(p)) if m.0.iter().all(|(_, x)| x.is_pure()) => { let prop = p.2.0.as_str(); @@ -705,14 +705,17 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) { .unwrap_or_else(|| Expr::Unit(*pos)); } // var.rhs - (Expr::Variable(_, _, _), rhs) => optimize_expr(rhs, state), + (Expr::Variable(_, _, _), rhs) => optimize_expr(rhs, state, true), // lhs.rhs - (lhs, rhs) => { optimize_expr(lhs, state); optimize_expr(rhs, state); } + (lhs, rhs) => { optimize_expr(lhs, state, false); optimize_expr(rhs, state, true); } } + // ....lhs.rhs + #[cfg(not(feature = "no_object"))] + Expr::Dot(x, _) => { optimize_expr(&mut x.lhs, state, false); optimize_expr(&mut x.rhs, state, indexing); } // lhs[rhs] #[cfg(not(feature = "no_index"))] - Expr::Index(x, _) => match (&mut x.lhs, &mut x.rhs) { + Expr::Index(x, _) if !indexing => match (&mut x.lhs, &mut x.rhs) { // array[int] (Expr::Array(a, pos), Expr::IntegerConstant(i, _)) if *i >= 0 && (*i as usize) < a.len() && a.iter().all(Expr::is_pure) => @@ -744,6 +747,18 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) { .map(|(_, mut expr)| { expr.set_position(*pos); expr }) .unwrap_or_else(|| Expr::Unit(*pos)); } + // int[int] + (Expr::IntegerConstant(n, pos), Expr::IntegerConstant(i, _)) if *i >= 0 && (*i as usize) < (std::mem::size_of_val(n) * 8) => { + // Bit-field literal indexing - get the bit + state.set_dirty(); + *expr = Expr::BoolConstant((*n & (1 << (*i as usize))) != 0, *pos); + } + // int[-int] + (Expr::IntegerConstant(n, pos), Expr::IntegerConstant(i, _)) if *i < 0 && i.checked_abs().map(|i| i as usize <= (std::mem::size_of_val(n) * 8)).unwrap_or(false) => { + // Bit-field literal indexing - get the bit + state.set_dirty(); + *expr = Expr::BoolConstant((*n & (1 << (std::mem::size_of_val(n) * 8 - i.abs() as usize))) != 0, *pos); + } // string[int] (Expr::StringConstant(s, pos), Expr::IntegerConstant(i, _)) if *i >= 0 && (*i as usize) < s.chars().count() => { // String literal indexing - get the character @@ -757,10 +772,13 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) { *expr = Expr::CharConstant(s.chars().rev().nth(i.abs() as usize - 1).unwrap(), *pos); } // var[rhs] - (Expr::Variable(_, _, _), rhs) => optimize_expr(rhs, state), + (Expr::Variable(_, _, _), rhs) => optimize_expr(rhs, state, true), // lhs[rhs] - (lhs, rhs) => { optimize_expr(lhs, state); optimize_expr(rhs, state); } + (lhs, rhs) => { optimize_expr(lhs, state, false); optimize_expr(rhs, state, true); } }, + // ...[lhs][rhs] + #[cfg(not(feature = "no_index"))] + Expr::Index(x, _) => { optimize_expr(&mut x.lhs, state, false); optimize_expr(&mut x.rhs, state, indexing); } // `` Expr::InterpolatedString(x) if x.is_empty() => { state.set_dirty(); @@ -773,7 +791,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) { } // `... ${ ... } ...` Expr::InterpolatedString(x) => { - x.iter_mut().for_each(|expr| optimize_expr(expr, state)); + x.iter_mut().for_each(|expr| optimize_expr(expr, state, false)); let mut n= 0; @@ -824,7 +842,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) { } // [ items .. ] #[cfg(not(feature = "no_index"))] - Expr::Array(x, _) => x.iter_mut().for_each(|expr| optimize_expr(expr, state)), + Expr::Array(x, _) => x.iter_mut().for_each(|expr| optimize_expr(expr, state, false)), // #{ key:constant, .. } #[cfg(not(feature = "no_object"))] Expr::Map(_, _) if expr.is_constant() => { @@ -833,13 +851,13 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) { } // #{ key:value, .. } #[cfg(not(feature = "no_object"))] - Expr::Map(x, _) => x.0.iter_mut().for_each(|(_, expr)| optimize_expr(expr, state)), + Expr::Map(x, _) => x.0.iter_mut().for_each(|(_, expr)| optimize_expr(expr, state, false)), // lhs && rhs Expr::And(x, _) => match (&mut x.lhs, &mut x.rhs) { // true && rhs -> rhs (Expr::BoolConstant(true, _), rhs) => { state.set_dirty(); - optimize_expr(rhs, state); + optimize_expr(rhs, state, false); *expr = mem::take(rhs); } // false && rhs -> false @@ -850,18 +868,18 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) { // lhs && true -> lhs (lhs, Expr::BoolConstant(true, _)) => { state.set_dirty(); - optimize_expr(lhs, state); + optimize_expr(lhs, state, false); *expr = mem::take(lhs); } // lhs && rhs - (lhs, rhs) => { optimize_expr(lhs, state); optimize_expr(rhs, state); } + (lhs, rhs) => { optimize_expr(lhs, state, false); optimize_expr(rhs, state, false); } }, // lhs || rhs Expr::Or(ref mut x, _) => match (&mut x.lhs, &mut x.rhs) { // false || rhs -> rhs (Expr::BoolConstant(false, _), rhs) => { state.set_dirty(); - optimize_expr(rhs, state); + optimize_expr(rhs, state, false); *expr = mem::take(rhs); } // true || rhs -> true @@ -872,11 +890,11 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) { // lhs || false (lhs, Expr::BoolConstant(false, _)) => { state.set_dirty(); - optimize_expr(lhs, state); + optimize_expr(lhs, state, false); *expr = mem::take(lhs); } // lhs || rhs - (lhs, rhs) => { optimize_expr(lhs, state); optimize_expr(rhs, state); } + (lhs, rhs) => { optimize_expr(lhs, state, false); optimize_expr(rhs, state, false); } }, // eval! @@ -899,7 +917,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) { // Do not call some special keywords Expr::FnCall(x, _) if DONT_EVAL_KEYWORDS.contains(&x.name.as_ref()) => { - x.args.iter_mut().for_each(|a| optimize_expr(a, state)); + x.args.iter_mut().for_each(|a| optimize_expr(a, state, false)); } // Call built-in operators @@ -933,7 +951,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) { } } - x.args.iter_mut().for_each(|a| optimize_expr(a, state)); + x.args.iter_mut().for_each(|a| optimize_expr(a, state, false)); // Move constant arguments to the right while x.args.last().map(Expr::is_constant).unwrap_or(false) { @@ -989,12 +1007,12 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) { } } - x.args.iter_mut().for_each(|a| optimize_expr(a, state)); + x.args.iter_mut().for_each(|a| optimize_expr(a, state, false)); } // id(args ..) -> optimize function call arguments Expr::FnCall(x, _) => { - x.args.iter_mut().for_each(|a| optimize_expr(a, state)); + x.args.iter_mut().for_each(|a| optimize_expr(a, state, false)); // Move constant arguments to the right while x.args.last().map(Expr::is_constant).unwrap_or(false) { @@ -1021,7 +1039,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) { if x.scope_changed { state.propagate_constants = false; } - x.keywords.iter_mut().for_each(|expr| optimize_expr(expr, state)); + x.keywords.iter_mut().for_each(|expr| optimize_expr(expr, state, false)); } // All other expressions - skip diff --git a/src/packages/iter_basic.rs b/src/packages/iter_basic.rs index 30280c42..9dd26425 100644 --- a/src/packages/iter_basic.rs +++ b/src/packages/iter_basic.rs @@ -1,5 +1,5 @@ use crate::dynamic::Variant; -use crate::{def_package, EvalAltResult, INT}; +use crate::{def_package, EvalAltResult, Position, INT}; use std::ops::Range; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -29,9 +29,9 @@ where Default::default(), Box::new(EvalAltResult::ErrorArithmetic( "step value cannot be zero".to_string(), - crate::Position::NONE, + Position::NONE, )), - crate::Position::NONE, + Position::NONE, ) .into(); } @@ -126,6 +126,68 @@ where } } +// Register range function with step +#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] +struct BitRange(INT, INT, usize); + +const BITS: usize = std::mem::size_of::() * 8; + +impl BitRange { + pub fn new(value: INT, from: INT, len: INT) -> Result> { + let from = if from >= 0 { + let offset = from as usize; + + #[cfg(not(feature = "unchecked"))] + if offset >= BITS { + return EvalAltResult::ErrorBitFieldBounds(BITS, from, Position::NONE).into(); + } + offset + } else { + #[cfg(not(feature = "unchecked"))] + if let Some(abs_from) = from.checked_abs() { + if (abs_from as usize) > BITS { + return EvalAltResult::ErrorBitFieldBounds(BITS, from, Position::NONE).into(); + } + BITS - (abs_from as usize) + } else { + return EvalAltResult::ErrorBitFieldBounds(BITS, from, Position::NONE).into(); + } + + #[cfg(feature = "unchecked")] + { + BITS - (from.abs() as usize) + } + }; + + let len = if len < 0 { + 0 + } else if from + (len as usize) > BITS { + BITS - from + } else { + len as usize + }; + + Ok(Self(value, 1 << from, len)) + } +} + +impl Iterator for BitRange { + type Item = bool; + + fn next(&mut self) -> Option { + let Self(value, mask, len) = *self; + + if len == 0 { + None + } else { + let r = (value & mask) != 0; + self.1 <<= 1; + self.2 -= 1; + Some(r) + } + } +} + macro_rules! reg_range { ($lib:ident | $x:expr => $( $y:ty ),*) => { $( @@ -193,8 +255,8 @@ def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, { #[cfg(not(feature = "unchecked"))] if step == 0.0 { return EvalAltResult::ErrorInFunctionCall("range".to_string(), "".to_string(), - Box::new(EvalAltResult::ErrorArithmetic("step value cannot be zero".to_string(), crate::Position::NONE)), - crate::Position::NONE, + Box::new(EvalAltResult::ErrorArithmetic("step value cannot be zero".to_string(), Position::NONE)), + Position::NONE, ).into(); } @@ -255,8 +317,8 @@ def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, { #[cfg(not(feature = "unchecked"))] if step.is_zero() { return EvalAltResult::ErrorInFunctionCall("range".to_string(), "".to_string(), - Box::new(EvalAltResult::ErrorArithmetic("step value cannot be zero".to_string(), crate::Position::NONE)), - crate::Position::NONE, + Box::new(EvalAltResult::ErrorArithmetic("step value cannot be zero".to_string(), Position::NONE)), + Position::NONE, ).into(); } @@ -304,4 +366,18 @@ def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, { #[cfg(feature = "metadata")] lib.update_fn_metadata(_hash, &["from: Decimal", "to: Decimal", "step: Decimal", "Iterator"]); } + + lib.set_iterator::(); + + let _hash = lib.set_native_fn("bits", |value, from, len| BitRange::new(value, from, len)); + #[cfg(feature = "metadata")] + lib.update_fn_metadata(_hash, &["value: INT", "from: Decimal", "len: Decimal", "Iterator"]); + + let _hash = lib.set_native_fn("bits", |value, from| BitRange::new(value, from, INT::MAX)); + #[cfg(feature = "metadata")] + lib.update_fn_metadata(_hash, &["value: INT", "from: Decimal", "Iterator"]); + + let _hash = lib.set_native_fn("bits", |value| BitRange::new(value, 0, INT::MAX)); + #[cfg(feature = "metadata")] + lib.update_fn_metadata(_hash, &["value: INT", "Iterator"]); }); diff --git a/src/packages/logic.rs b/src/packages/logic.rs index 56339aa4..a1fd8d8f 100644 --- a/src/packages/logic.rs +++ b/src/packages/logic.rs @@ -1,7 +1,7 @@ #![allow(non_snake_case)] -use crate::def_package; use crate::plugin::*; +use crate::{def_package, EvalAltResult, INT}; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -59,6 +59,8 @@ def_package!(crate:LogicPackage:"Logical operators.", lib, { } set_exported_fn!(lib, "!", not); + + combine_with_exported_module!(lib, "bit_field", bit_field_functions); }); // Logic operators @@ -87,8 +89,6 @@ gen_cmp_functions!(float => f64); #[cfg(not(feature = "no_float"))] #[export_module] mod f32_functions { - use crate::INT; - #[rhai_fn(name = "==")] pub fn eq_if(x: INT, y: f32) -> bool { (x as f32) == (y as f32) @@ -142,8 +142,6 @@ mod f32_functions { #[cfg(not(feature = "no_float"))] #[export_module] mod f64_functions { - use crate::INT; - #[rhai_fn(name = "==")] pub fn eq_if(x: INT, y: f64) -> bool { (x as f64) == (y as f64) @@ -193,3 +191,159 @@ mod f64_functions { (x as f64) <= (y as f64) } } + +#[export_module] +mod bit_field_functions { + const BITS: usize = std::mem::size_of::() * 8; + + #[rhai_fn(return_raw)] + pub fn get_bit(value: INT, index: INT) -> Result> { + if index >= 0 { + let offset = index as usize; + + if offset >= BITS { + EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into() + } else { + Ok((value & (1 << offset)) != 0) + } + } else if let Some(abs_index) = index.checked_abs() { + let offset = abs_index as usize; + + // Count from end if negative + if offset > BITS { + EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into() + } else { + Ok((value & (1 << (BITS - offset))) != 0) + } + } else { + EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into() + } + } + #[rhai_fn(return_raw)] + pub fn set_bit(value: &mut INT, index: INT, new_value: bool) -> Result<(), Box> { + if index >= 0 { + let offset = index as usize; + + if offset >= BITS { + EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into() + } else { + let mask = 1 << offset; + if new_value { + *value |= mask; + } else { + *value &= !mask; + } + Ok(()) + } + } else if let Some(abs_index) = index.checked_abs() { + let offset = abs_index as usize; + + // Count from end if negative + if offset > BITS { + EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into() + } else { + let mask = 1 << offset; + if new_value { + *value |= mask; + } else { + *value &= !mask; + } + Ok(()) + } + } else { + EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into() + } + } + #[rhai_fn(return_raw)] + pub fn get_bits(value: INT, index: INT, bits: INT) -> Result> { + if bits < 1 { + return Ok(0); + } + + let offset = if index >= 0 { + let offset = index as usize; + + if offset >= BITS { + return EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into(); + } + + offset + } else if let Some(abs_index) = index.checked_abs() { + let offset = abs_index as usize; + + // Count from end if negative + if offset > BITS { + return EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into(); + } + BITS - offset + } else { + return EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into(); + }; + + let bits = if offset + bits as usize > BITS { + BITS - offset + } else { + bits as usize + }; + + let mut base = 1; + let mut mask = 0; + + for _ in 0..bits { + mask |= base; + base <<= 1; + } + + Ok(((value & (mask << index)) >> index) & mask) + } + #[rhai_fn(return_raw)] + pub fn set_bits( + value: &mut INT, + index: INT, + bits: INT, + new_value: INT, + ) -> Result<(), Box> { + if bits < 1 { + return Ok(()); + } + + let offset = if index >= 0 { + let offset = index as usize; + + if offset >= BITS { + return EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into(); + } + + offset + } else if let Some(abs_index) = index.checked_abs() { + let offset = abs_index as usize; + + // Count from end if negative + if offset > BITS { + return EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into(); + } + BITS - offset + } else { + return EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into(); + }; + + let bits = if offset + bits as usize > BITS { + BITS - offset + } else { + bits as usize + }; + + let mut base = 1; + let mut mask = 0; + + for _ in 0..bits { + mask |= base; + base <<= 1; + } + + *value &= !(mask << index); + *value |= (new_value & mask) << index; + + Ok(()) + } +} diff --git a/src/parser.rs b/src/parser.rs index 6ea22399..69084efd 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -455,7 +455,10 @@ fn parse_index_chain( // Check type of indexing - must be integer or string match &idx_expr { Expr::IntegerConstant(_, pos) => match lhs { - Expr::Array(_, _) | Expr::StringConstant(_, _) | Expr::InterpolatedString(_) => (), + Expr::IntegerConstant(_, _) + | Expr::Array(_, _) + | Expr::StringConstant(_, _) + | Expr::InterpolatedString(_) => (), Expr::Map(_, _) => { return Err(PERR::MalformedIndexExpr( diff --git a/src/result.rs b/src/result.rs index 172e9834..51d692fc 100644 --- a/src/result.rs +++ b/src/result.rs @@ -56,6 +56,9 @@ pub enum EvalAltResult { /// String indexing out-of-bounds. /// Wrapped values are the current number of characters in the string and the index number. ErrorStringBounds(usize, INT, Position), + /// Bit-field indexing out-of-bounds. + /// Wrapped values are the current number of bits in the bit-field and the index number. + ErrorBitFieldBounds(usize, INT, Position), /// Trying to index into a type that is not an array, an object map, or a string, and has no /// indexer function defined. Wrapped value is the type name. ErrorIndexingType(String, Position), @@ -109,6 +112,7 @@ impl EvalAltResult { Self::ErrorArrayBounds(_, _, _) => "Array index out of bounds", Self::ErrorStringBounds(0, _, _) => "Empty string has nothing to index", Self::ErrorStringBounds(_, _, _) => "String index out of bounds", + Self::ErrorBitFieldBounds(_, _, _) => "Bit-field index out of bounds", Self::ErrorFor(_) => "For loop expects an array, object map, or range", Self::ErrorVariableNotFound(_, _) => "Variable not found", Self::ErrorModuleNotFound(_, _) => "Module not found", @@ -233,6 +237,11 @@ impl fmt::Display for EvalAltResult { "String index {} out of bounds: only {} characters in the string", index, max )?, + Self::ErrorBitFieldBounds(max, index, _) => write!( + f, + "Bit-field index {} out of bounds: only {} bits in the bit-field", + index, max + )?, Self::ErrorDataTooLarge(typ, _) => write!(f, "{} exceeds maximum limit", typ)?, } @@ -289,6 +298,7 @@ impl EvalAltResult { | Self::ErrorMismatchDataType(_, _, _) | Self::ErrorArrayBounds(_, _, _) | Self::ErrorStringBounds(_, _, _) + | Self::ErrorBitFieldBounds(_, _, _) | Self::ErrorIndexingType(_, _) | Self::ErrorFor(_) | Self::ErrorVariableNotFound(_, _) @@ -372,7 +382,9 @@ impl EvalAltResult { map.insert("requested".into(), r.into()); map.insert("actual".into(), a.into()); } - Self::ErrorArrayBounds(n, i, _) | Self::ErrorStringBounds(n, i, _) => { + Self::ErrorArrayBounds(n, i, _) + | Self::ErrorStringBounds(n, i, _) + | Self::ErrorBitFieldBounds(n, i, _) => { map.insert("length".into(), (*n as INT).into()); map.insert("index".into(), (*i as INT).into()); } @@ -412,6 +424,7 @@ impl EvalAltResult { | Self::ErrorMismatchDataType(_, _, pos) | Self::ErrorArrayBounds(_, _, pos) | Self::ErrorStringBounds(_, _, pos) + | Self::ErrorBitFieldBounds(_, _, pos) | Self::ErrorIndexingType(_, pos) | Self::ErrorFor(pos) | Self::ErrorVariableNotFound(_, pos) @@ -452,6 +465,7 @@ impl EvalAltResult { | Self::ErrorMismatchDataType(_, _, pos) | Self::ErrorArrayBounds(_, _, pos) | Self::ErrorStringBounds(_, _, pos) + | Self::ErrorBitFieldBounds(_, _, pos) | Self::ErrorIndexingType(_, pos) | Self::ErrorFor(pos) | Self::ErrorVariableNotFound(_, pos) diff --git a/tests/bit_shift.rs b/tests/bit_shift.rs index 0b888e32..c35b33d5 100644 --- a/tests/bit_shift.rs +++ b/tests/bit_shift.rs @@ -13,3 +13,38 @@ fn test_right_shift() -> Result<(), Box> { assert_eq!(engine.eval::("9 >> 1")?, 4); Ok(()) } + +#[cfg(not(feature = "no_index"))] +#[test] +fn test_bit_fields() -> Result<(), Box> { + let engine = Engine::new(); + assert!(!engine.eval::("let x = 10; x[0]")?); + assert!(engine.eval::("let x = 10; x[1]")?); + assert!(!engine.eval::("let x = 10; x[-1]")?); + assert_eq!( + engine.eval::("let x = 10; x[0] = true; x[1] = false; x")?, + 9 + ); + assert_eq!(engine.eval::("let x = 10; get_bits(x, 1, 3)")?, 5); + assert_eq!( + engine.eval::("let x = 10; set_bits(x, 1, 3, 7); x")?, + 14 + ); + assert_eq!( + engine.eval::( + " + let x = 0b001101101010001; + let count = 0; + + for b in bits(x, 2, 10) { + if b { count += 1; } + } + + count + " + )?, + 5 + ); + + Ok(()) +} From 4cf6550fc618bc8fd64996c4806768bb2f96dcb5 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Wed, 2 Jun 2021 15:05:33 +0800 Subject: [PATCH 6/7] Fix tests. --- src/engine.rs | 1 - src/optimize.rs | 10 +++++----- src/packages/iter_basic.rs | 23 +++++++++++++---------- src/parser.rs | 4 ++-- 4 files changed, 20 insertions(+), 18 deletions(-) diff --git a/src/engine.rs b/src/engine.rs index 023729b7..d6ad284f 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -441,7 +441,6 @@ impl<'a> Target<'a> { } /// Propagate a changed value back to the original source. /// This has no effect except for string indexing. - #[cfg(not(feature = "no_object"))] #[inline(always)] pub fn propagate_changed_value(&mut self) -> Result<(), Box> { match self { diff --git a/src/optimize.rs b/src/optimize.rs index d78f5ca4..b28124b5 100644 --- a/src/optimize.rs +++ b/src/optimize.rs @@ -670,7 +670,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) { } /// Optimize an [expression][Expr]. -fn optimize_expr(expr: &mut Expr, state: &mut State, indexing: bool) { +fn optimize_expr(expr: &mut Expr, state: &mut State, _chaining: bool) { // These keywords are handled specially const DONT_EVAL_KEYWORDS: &[&str] = &[ KEYWORD_PRINT, // side effects @@ -693,7 +693,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State, indexing: bool) { } // lhs.rhs #[cfg(not(feature = "no_object"))] - Expr::Dot(x, _) if !indexing => match (&mut x.lhs, &mut x.rhs) { + Expr::Dot(x, _) if !_chaining => match (&mut x.lhs, &mut x.rhs) { // map.string (Expr::Map(m, pos), Expr::Property(p)) if m.0.iter().all(|(_, x)| x.is_pure()) => { let prop = p.2.0.as_str(); @@ -711,11 +711,11 @@ fn optimize_expr(expr: &mut Expr, state: &mut State, indexing: bool) { } // ....lhs.rhs #[cfg(not(feature = "no_object"))] - Expr::Dot(x, _) => { optimize_expr(&mut x.lhs, state, false); optimize_expr(&mut x.rhs, state, indexing); } + Expr::Dot(x, _) => { optimize_expr(&mut x.lhs, state, false); optimize_expr(&mut x.rhs, state, _chaining); } // lhs[rhs] #[cfg(not(feature = "no_index"))] - Expr::Index(x, _) if !indexing => match (&mut x.lhs, &mut x.rhs) { + Expr::Index(x, _) if !_chaining => match (&mut x.lhs, &mut x.rhs) { // array[int] (Expr::Array(a, pos), Expr::IntegerConstant(i, _)) if *i >= 0 && (*i as usize) < a.len() && a.iter().all(Expr::is_pure) => @@ -778,7 +778,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State, indexing: bool) { }, // ...[lhs][rhs] #[cfg(not(feature = "no_index"))] - Expr::Index(x, _) => { optimize_expr(&mut x.lhs, state, false); optimize_expr(&mut x.rhs, state, indexing); } + Expr::Index(x, _) => { optimize_expr(&mut x.lhs, state, false); optimize_expr(&mut x.rhs, state, _chaining); } // `` Expr::InterpolatedString(x) if x.is_empty() => { state.set_dirty(); diff --git a/src/packages/iter_basic.rs b/src/packages/iter_basic.rs index 9dd26425..f5e7cc27 100644 --- a/src/packages/iter_basic.rs +++ b/src/packages/iter_basic.rs @@ -1,5 +1,5 @@ use crate::dynamic::Variant; -use crate::{def_package, EvalAltResult, Position, INT}; +use crate::{def_package, EvalAltResult, INT}; use std::ops::Range; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -29,9 +29,9 @@ where Default::default(), Box::new(EvalAltResult::ErrorArithmetic( "step value cannot be zero".to_string(), - Position::NONE, + crate::Position::NONE, )), - Position::NONE, + crate::Position::NONE, ) .into(); } @@ -139,18 +139,21 @@ impl BitRange { #[cfg(not(feature = "unchecked"))] if offset >= BITS { - return EvalAltResult::ErrorBitFieldBounds(BITS, from, Position::NONE).into(); + return EvalAltResult::ErrorBitFieldBounds(BITS, from, crate::Position::NONE) + .into(); } offset } else { #[cfg(not(feature = "unchecked"))] if let Some(abs_from) = from.checked_abs() { if (abs_from as usize) > BITS { - return EvalAltResult::ErrorBitFieldBounds(BITS, from, Position::NONE).into(); + return EvalAltResult::ErrorBitFieldBounds(BITS, from, crate::Position::NONE) + .into(); } BITS - (abs_from as usize) } else { - return EvalAltResult::ErrorBitFieldBounds(BITS, from, Position::NONE).into(); + return EvalAltResult::ErrorBitFieldBounds(BITS, from, crate::Position::NONE) + .into(); } #[cfg(feature = "unchecked")] @@ -255,8 +258,8 @@ def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, { #[cfg(not(feature = "unchecked"))] if step == 0.0 { return EvalAltResult::ErrorInFunctionCall("range".to_string(), "".to_string(), - Box::new(EvalAltResult::ErrorArithmetic("step value cannot be zero".to_string(), Position::NONE)), - Position::NONE, + Box::new(EvalAltResult::ErrorArithmetic("step value cannot be zero".to_string(), crate::Position::NONE)), + crate::Position::NONE, ).into(); } @@ -317,8 +320,8 @@ def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, { #[cfg(not(feature = "unchecked"))] if step.is_zero() { return EvalAltResult::ErrorInFunctionCall("range".to_string(), "".to_string(), - Box::new(EvalAltResult::ErrorArithmetic("step value cannot be zero".to_string(), Position::NONE)), - Position::NONE, + Box::new(EvalAltResult::ErrorArithmetic("step value cannot be zero".to_string(), crate::Position::NONE)), + crate::Position::NONE, ).into(); } diff --git a/src/parser.rs b/src/parser.rs index 69084efd..9897b613 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -15,7 +15,7 @@ use crate::token::{ }; use crate::utils::{get_hasher, IdentifierBuilder}; use crate::{ - calc_fn_hash, calc_qualified_fn_hash, Dynamic, Engine, FnPtr, Identifier, LexError, ParseError, + calc_fn_hash, calc_qualified_fn_hash, Dynamic, Engine, Identifier, LexError, ParseError, ParseErrorType, Position, Scope, Shared, StaticVec, AST, }; #[cfg(feature = "no_std")] @@ -3017,7 +3017,7 @@ fn parse_anon_fn( comments: Default::default(), }; - let fn_ptr = FnPtr::new_unchecked(fn_name.into(), Default::default()); + let fn_ptr = crate::FnPtr::new_unchecked(fn_name.into(), Default::default()); let expr = Expr::DynamicConstant(Box::new(fn_ptr.into()), settings.pos); #[cfg(not(feature = "no_closure"))] From 99e06abd94f06b0ae9540bc833942539f52896e2 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Wed, 2 Jun 2021 15:18:09 +0800 Subject: [PATCH 7/7] Fix test. --- src/engine.rs | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/engine.rs b/src/engine.rs index d6ad284f..f50656b3 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -332,7 +332,6 @@ pub enum Target<'a> { /// The target is a mutable reference to a Shared `Dynamic` value. /// It holds both the access guard and the original shared value. #[cfg(not(feature = "no_closure"))] - #[cfg(not(feature = "no_object"))] LockGuard((crate::dynamic::DynamicWriteLock<'a, Dynamic>, Dynamic)), /// The target is a temporary `Dynamic` value (i.e. the mutation can cause no side effects). Value(Dynamic), @@ -354,7 +353,6 @@ impl<'a> Target<'a> { match self { Self::Ref(_) => true, #[cfg(not(feature = "no_closure"))] - #[cfg(not(feature = "no_object"))] Self::LockGuard(_) => true, Self::Value(_) => false, #[cfg(not(feature = "no_index"))] @@ -370,7 +368,6 @@ impl<'a> Target<'a> { match self { Self::Ref(_) => false, #[cfg(not(feature = "no_closure"))] - #[cfg(not(feature = "no_object"))] Self::LockGuard(_) => false, Self::Value(_) => true, #[cfg(not(feature = "no_index"))] @@ -386,7 +383,6 @@ impl<'a> Target<'a> { match self { Self::Ref(r) => r.is_shared(), #[cfg(not(feature = "no_closure"))] - #[cfg(not(feature = "no_object"))] Self::LockGuard(_) => true, Self::Value(r) => r.is_shared(), #[cfg(not(feature = "no_index"))] @@ -402,7 +398,6 @@ impl<'a> Target<'a> { match self { Self::Ref(r) => r.is::(), #[cfg(not(feature = "no_closure"))] - #[cfg(not(feature = "no_object"))] Self::LockGuard((r, _)) => r.is::(), Self::Value(r) => r.is::(), #[cfg(not(feature = "no_index"))] @@ -417,7 +412,6 @@ impl<'a> Target<'a> { match self { Self::Ref(r) => r.clone(), // Referenced value is cloned #[cfg(not(feature = "no_closure"))] - #[cfg(not(feature = "no_object"))] Self::LockGuard((_, orig)) => orig, // Original value is simply taken Self::Value(v) => v, // Owned value is simply taken #[cfg(not(feature = "no_index"))] @@ -468,7 +462,6 @@ impl<'a> Target<'a> { match self { Self::Ref(r) => **r = new_val, #[cfg(not(feature = "no_closure"))] - #[cfg(not(feature = "no_object"))] Self::LockGuard((r, _)) => **r = new_val, Self::Value(_) => panic!("cannot update a value"), #[cfg(not(feature = "no_index"))] @@ -530,7 +523,6 @@ impl<'a> From<&'a mut Dynamic> for Target<'a> { #[inline(always)] fn from(value: &'a mut Dynamic) -> Self { #[cfg(not(feature = "no_closure"))] - #[cfg(not(feature = "no_object"))] if value.is_shared() { // Cloning is cheap for a shared value let container = value.clone(); @@ -554,7 +546,6 @@ impl Deref for Target<'_> { match self { Self::Ref(r) => *r, #[cfg(not(feature = "no_closure"))] - #[cfg(not(feature = "no_object"))] Self::LockGuard((r, _)) => &**r, Self::Value(ref r) => r, #[cfg(not(feature = "no_index"))] @@ -578,7 +569,6 @@ impl DerefMut for Target<'_> { match self { Self::Ref(r) => *r, #[cfg(not(feature = "no_closure"))] - #[cfg(not(feature = "no_object"))] Self::LockGuard((r, _)) => r.deref_mut(), Self::Value(ref mut r) => r, #[cfg(not(feature = "no_index"))]