Merge pull request #416 from schungx/master

Implement bit-fields.
This commit is contained in:
Stephen Chung 2021-06-02 16:45:50 +08:00 committed by GitHub
commit a4292ab0f9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
25 changed files with 657 additions and 337 deletions

View File

@ -1,6 +1,20 @@
Rhai Release Notes 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 Version 0.20.2
============== ==============

View File

@ -3,7 +3,7 @@ members = [".", "codegen"]
[package] [package]
name = "rhai" name = "rhai"
version = "0.20.2" version = "0.20.3"
edition = "2018" edition = "2018"
authors = ["Jonathan Turner", "Lukáš Hozda", "Stephen Chung", "jhwgh1968"] authors = ["Jonathan Turner", "Lukáš Hozda", "Stephen Chung", "jhwgh1968"]
description = "Embedded scripting for Rust" description = "Embedded scripting for Rust"
@ -20,7 +20,7 @@ smallvec = { version = "1.6", default-features = false, features = ["union"] }
ahash = { version = "0.7", default-features = false } ahash = { version = "0.7", default-features = false }
num-traits = { version = "0.2", default_features = false } num-traits = { version = "0.2", default_features = false }
smartstring = { version = "0.2.6", 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] [features]
default = ["smartstring/std", "ahash/std", "num-traits/std"] # remove 'smartstring/std' when smartstring is updated to support no-std default = ["smartstring/std", "ahash/std", "num-traits/std"] # remove 'smartstring/std' when smartstring is updated to support no-std

View File

@ -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) [![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) [![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) [![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) [![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) [![Rhai logo](https://rhai.rs/book/images/logo/rhai-banner-transparent-colour.svg)](https://rhai.rs)

View File

@ -1,6 +1,6 @@
[package] [package]
name = "rhai_codegen" name = "rhai_codegen"
version = "0.3.6" version = "0.3.7"
edition = "2018" edition = "2018"
authors = ["jhwgh1968", "Stephen Chung"] authors = ["jhwgh1968", "Stephen Chung"]
description = "Procedural macros support package for Rhai, a scripting language and engine for Rust" description = "Procedural macros support package for Rhai, a scripting language and engine for Rust"
@ -16,7 +16,7 @@ default = []
metadata = [] metadata = []
[dev-dependencies] [dev-dependencies]
rhai = { path = "..", version = ">=0.19.15" } rhai = { path = "..", version = ">=0.20.3" }
trybuild = "1" trybuild = "1"
[dependencies] [dependencies]

View File

@ -845,7 +845,6 @@ impl ExportedFn {
} }
#[inline(always)] fn is_method_call(&self) -> bool { #is_method_call } #[inline(always)] fn is_method_call(&self) -> bool { #is_method_call }
#[inline(always)] fn is_variadic(&self) -> bool { false }
} }
} }
} }

View File

@ -286,7 +286,6 @@ mod generate_tests {
} }
#[inline(always)] fn is_method_call(&self) -> bool { false } #[inline(always)] fn is_method_call(&self) -> bool { false }
#[inline(always)] fn is_variadic(&self) -> bool { false }
} }
#[allow(unused)] #[allow(unused)]
#[inline(always)] pub fn dynamic_result_fn() -> RhaiResult { #[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_method_call(&self) -> bool { false }
#[inline(always)] fn is_variadic(&self) -> bool { false }
} }
#[allow(unused)] #[allow(unused)]
#[inline(always)] pub fn dynamic_result_fn(x: usize) -> RhaiResult { #[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_method_call(&self) -> bool { false }
#[inline(always)] fn is_variadic(&self) -> bool { false }
} }
#[allow(unused)] #[allow(unused)]
#[inline(always)] pub fn dynamic_result_fn(context: NativeCallContext, x: usize) -> RhaiResult { #[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_method_call(&self) -> bool { false }
#[inline(always)] fn is_variadic(&self) -> bool { false }
} }
#[allow(unused)] #[allow(unused)]
#[inline(always)] pub fn dynamic_result_fn() -> RhaiResult { #[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_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_method_call(&self) -> bool { false }
#[inline(always)] fn is_variadic(&self) -> bool { false }
} }
#[allow(unused)] #[allow(unused)]
#[inline(always)] pub fn dynamic_result_fn(x: usize, y: usize) -> RhaiResult { #[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_method_call(&self) -> bool { true }
#[inline(always)] fn is_variadic(&self) -> bool { false }
} }
#[allow(unused)] #[allow(unused)]
#[inline(always)] pub fn dynamic_result_fn(x: &mut usize, y: usize) -> RhaiResult { #[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_method_call(&self) -> bool { false }
#[inline(always)] fn is_variadic(&self) -> bool { false }
} }
#[allow(unused)] #[allow(unused)]
#[inline(always)] pub fn dynamic_result_fn(message: &str) -> RhaiResult { #[inline(always)] pub fn dynamic_result_fn(message: &str) -> RhaiResult {

View File

@ -315,7 +315,6 @@ mod generate_tests {
} }
#[inline(always)] fn is_method_call(&self) -> bool { false } #[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_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_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_method_call(&self) -> bool { false }
#[inline(always)] fn is_variadic(&self) -> bool { false }
} }
#[allow(non_camel_case_types)] #[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_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_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_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_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_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_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_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_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_method_call(&self) -> bool { true }
#[inline(always)] fn is_variadic(&self) -> bool { false }
} }
} }
#[allow(unused_imports)] #[allow(unused_imports)]
@ -1255,7 +1242,6 @@ mod generate_tests {
} }
#[inline(always)] fn is_method_call(&self) -> bool { true } #[inline(always)] fn is_method_call(&self) -> bool { true }
#[inline(always)] fn is_variadic(&self) -> bool { false }
} }
} }
#[allow(unused_imports)] #[allow(unused_imports)]
@ -1337,7 +1323,6 @@ mod generate_tests {
} }
#[inline(always)] fn is_method_call(&self) -> bool { true } #[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_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_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_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_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_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_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_method_call(&self) -> bool { true }
#[inline(always)] fn is_variadic(&self) -> bool { false }
} }
} }
}; };

View File

@ -2014,13 +2014,13 @@ impl Expr {
Self::DynamicConstant(_, _) Self::DynamicConstant(_, _)
| Self::BoolConstant(_, _) | Self::BoolConstant(_, _)
| Self::IntegerConstant(_, _)
| Self::CharConstant(_, _) | Self::CharConstant(_, _)
| Self::And(_, _) | Self::And(_, _)
| Self::Or(_, _) | Self::Or(_, _)
| Self::Unit(_) => false, | Self::Unit(_) => false,
Self::StringConstant(_, _) Self::IntegerConstant(_, _)
| Self::StringConstant(_, _)
| Self::InterpolatedString(_) | Self::InterpolatedString(_)
| Self::FnCall(_, _) | Self::FnCall(_, _)
| Self::Stmt(_) | Self::Stmt(_)

View File

@ -83,7 +83,7 @@ fn main() {
if let Err(err) = engine if let Err(err) = engine
.compile(contents) .compile(contents)
.map_err(|err| Box::new(err.into()) as Box<EvalAltResult>) .map_err(|err| err.into())
.and_then(|mut ast| { .and_then(|mut ast| {
ast.set_source(filename.to_string_lossy().to_string()); ast.set_source(filename.to_string_lossy().to_string());
engine.consume_ast(&ast) engine.consume_ast(&ast)

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)
} }
} }
@ -332,10 +332,13 @@ pub enum Target<'a> {
/// The target is a mutable reference to a Shared `Dynamic` value. /// The target is a mutable reference to a Shared `Dynamic` value.
/// It holds both the access guard and the original shared value. /// It holds both the access guard and the original shared value.
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "no_object"))]
LockGuard((crate::dynamic::DynamicWriteLock<'a, Dynamic>, Dynamic)), LockGuard((crate::dynamic::DynamicWriteLock<'a, Dynamic>, Dynamic)),
/// The target is a temporary `Dynamic` value (i.e. the mutation can cause no side effects). /// The target is a temporary `Dynamic` value (i.e. the mutation can cause no side effects).
Value(Dynamic), 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. /// The target is a character inside a String.
/// This is necessary because directly pointing to a char inside a String is impossible. /// This is necessary because directly pointing to a char inside a String is impossible.
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
@ -350,10 +353,11 @@ impl<'a> Target<'a> {
match self { match self {
Self::Ref(_) => true, Self::Ref(_) => true,
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "no_object"))]
Self::LockGuard(_) => true, Self::LockGuard(_) => true,
Self::Value(_) => false, Self::Value(_) => false,
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Self::BitField(_, _, _) => false,
#[cfg(not(feature = "no_index"))]
Self::StringChar(_, _, _) => false, Self::StringChar(_, _, _) => false,
} }
} }
@ -364,10 +368,11 @@ impl<'a> Target<'a> {
match self { match self {
Self::Ref(_) => false, Self::Ref(_) => false,
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "no_object"))]
Self::LockGuard(_) => false, Self::LockGuard(_) => false,
Self::Value(_) => true, Self::Value(_) => true,
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Self::BitField(_, _, _) => false,
#[cfg(not(feature = "no_index"))]
Self::StringChar(_, _, _) => false, Self::StringChar(_, _, _) => false,
} }
} }
@ -378,10 +383,11 @@ impl<'a> Target<'a> {
match self { match self {
Self::Ref(r) => r.is_shared(), Self::Ref(r) => r.is_shared(),
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "no_object"))]
Self::LockGuard(_) => true, Self::LockGuard(_) => true,
Self::Value(r) => r.is_shared(), Self::Value(r) => r.is_shared(),
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Self::BitField(_, _, _) => false,
#[cfg(not(feature = "no_index"))]
Self::StringChar(_, _, _) => false, Self::StringChar(_, _, _) => false,
} }
} }
@ -392,10 +398,11 @@ impl<'a> Target<'a> {
match self { match self {
Self::Ref(r) => r.is::<T>(), Self::Ref(r) => r.is::<T>(),
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "no_object"))]
Self::LockGuard((r, _)) => r.is::<T>(), Self::LockGuard((r, _)) => r.is::<T>(),
Self::Value(r) => r.is::<T>(), Self::Value(r) => r.is::<T>(),
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Self::BitField(_, _, _) => TypeId::of::<T>() == TypeId::of::<bool>(),
#[cfg(not(feature = "no_index"))]
Self::StringChar(_, _, _) => TypeId::of::<T>() == TypeId::of::<char>(), Self::StringChar(_, _, _) => TypeId::of::<T>() == TypeId::of::<char>(),
} }
} }
@ -405,10 +412,11 @@ impl<'a> Target<'a> {
match self { match self {
Self::Ref(r) => r.clone(), // Referenced value is cloned Self::Ref(r) => r.clone(), // Referenced value is cloned
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "no_object"))]
Self::LockGuard((_, orig)) => orig, // Original value is simply taken Self::LockGuard((_, orig)) => orig, // Original value is simply taken
Self::Value(v) => v, // Owned value is simply taken Self::Value(v) => v, // Owned value is simply taken
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Self::BitField(_, _, value) => value, // Boolean is taken
#[cfg(not(feature = "no_index"))]
Self::StringChar(_, _, ch) => ch, // Character is taken Self::StringChar(_, _, ch) => ch, // Character is taken
} }
} }
@ -427,7 +435,6 @@ impl<'a> Target<'a> {
} }
/// Propagate a changed value back to the original source. /// Propagate a changed value back to the original source.
/// This has no effect except for string indexing. /// This has no effect except for string indexing.
#[cfg(not(feature = "no_object"))]
#[inline(always)] #[inline(always)]
pub fn propagate_changed_value(&mut self) -> Result<(), Box<EvalAltResult>> { pub fn propagate_changed_value(&mut self) -> Result<(), Box<EvalAltResult>> {
match self { match self {
@ -435,9 +442,14 @@ impl<'a> Target<'a> {
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
Self::LockGuard(_) => Ok(()), Self::LockGuard(_) => Ok(()),
#[cfg(not(feature = "no_index"))] #[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) => { Self::StringChar(_, _, ch) => {
let char_value = ch.clone(); let new_val = ch.clone();
self.set_value(char_value, Position::NONE) self.set_value(new_val, Position::NONE)
} }
} }
} }
@ -450,10 +462,35 @@ impl<'a> Target<'a> {
match self { match self {
Self::Ref(r) => **r = new_val, Self::Ref(r) => **r = new_val,
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "no_object"))]
Self::LockGuard((r, _)) => **r = new_val, Self::LockGuard((r, _)) => **r = new_val,
Self::Value(_) => panic!("cannot update a value"), Self::Value(_) => panic!("cannot update a value"),
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Self::BitField(value, index, _) => {
let value = &mut *value
.write_lock::<crate::INT>()
.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, _) => { Self::StringChar(s, index, _) => {
let s = &mut *s let s = &mut *s
.write_lock::<ImmutableString>() .write_lock::<ImmutableString>()
@ -486,7 +523,6 @@ impl<'a> From<&'a mut Dynamic> for Target<'a> {
#[inline(always)] #[inline(always)]
fn from(value: &'a mut Dynamic) -> Self { fn from(value: &'a mut Dynamic) -> Self {
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "no_object"))]
if value.is_shared() { if value.is_shared() {
// Cloning is cheap for a shared value // Cloning is cheap for a shared value
let container = value.clone(); let container = value.clone();
@ -510,10 +546,11 @@ impl Deref for Target<'_> {
match self { match self {
Self::Ref(r) => *r, Self::Ref(r) => *r,
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "no_object"))]
Self::LockGuard((r, _)) => &**r, Self::LockGuard((r, _)) => &**r,
Self::Value(ref r) => r, Self::Value(ref r) => r,
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Self::BitField(_, _, ref r) => r,
#[cfg(not(feature = "no_index"))]
Self::StringChar(_, _, ref r) => r, Self::StringChar(_, _, ref r) => r,
} }
} }
@ -532,10 +569,11 @@ impl DerefMut for Target<'_> {
match self { match self {
Self::Ref(r) => *r, Self::Ref(r) => *r,
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "no_object"))]
Self::LockGuard((r, _)) => r.deref_mut(), Self::LockGuard((r, _)) => r.deref_mut(),
Self::Value(ref mut r) => r, Self::Value(ref mut r) => r,
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Self::BitField(_, _, ref mut r) => r,
#[cfg(not(feature = "no_index"))]
Self::StringChar(_, _, ref mut r) => r, Self::StringChar(_, _, ref mut r) => r,
} }
} }
@ -787,7 +825,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 +928,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 +988,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 +1667,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 +1713,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 => {
@ -1816,6 +1856,43 @@ impl Engine {
.unwrap_or_else(|| Target::from(Dynamic::UNIT))) .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::<crate::INT>(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"))] #[cfg(not(feature = "no_index"))]
Dynamic(Union::Str(s, _, _)) => { Dynamic(Union::Str(s, _, _)) => {
// val_string[idx] // val_string[idx]
@ -1824,7 +1901,6 @@ impl Engine {
.map_err(|err| self.make_type_mismatch_err::<crate::INT>(err, idx_pos))?; .map_err(|err| self.make_type_mismatch_err::<crate::INT>(err, idx_pos))?;
let (ch, offset) = if index >= 0 { let (ch, offset) = if index >= 0 {
// Count from end if negative
let offset = index as usize; let offset = index as usize;
( (
s.chars().nth(offset).ok_or_else(|| { s.chars().nth(offset).ok_or_else(|| {
@ -1833,9 +1909,10 @@ impl Engine {
})?, })?,
offset, offset,
) )
} else if let Some(index) = index.checked_abs() { } else if let Some(abs_index) = index.checked_abs() {
let offset = index as usize; let offset = abs_index as usize;
( (
// Count from end if negative
s.chars().rev().nth(offset - 1).ok_or_else(|| { s.chars().rev().nth(offset - 1).ok_or_else(|| {
let chars_len = s.chars().count(); let chars_len = s.chars().count();
EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos) EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos)
@ -2037,11 +2114,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",
); );
@ -2155,8 +2228,8 @@ impl Engine {
op_pos: Position, op_pos: Position,
mut target: Target, mut target: Target,
root: (&str, Position), root: (&str, Position),
mut new_value: Dynamic, mut new_val: Dynamic,
new_value_pos: Position, new_val_pos: Position,
) -> Result<(), Box<EvalAltResult>> { ) -> Result<(), Box<EvalAltResult>> {
if target.is_read_only() { if target.is_read_only() {
// Assignment to constant variable // Assignment to constant variable
@ -2169,48 +2242,51 @@ impl Engine {
op, op,
}) = op_info }) = op_info
{ {
let mut lock_guard; {
let lhs_ptr_inner; let mut lock_guard;
let lhs_ptr_inner;
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
let target_is_shared = target.is_shared(); let target_is_shared = target.is_shared();
#[cfg(feature = "no_closure")] #[cfg(feature = "no_closure")]
let target_is_shared = false; let target_is_shared = false;
if target_is_shared { if target_is_shared {
lock_guard = target lock_guard = target
.write_lock::<Dynamic>() .write_lock::<Dynamic>()
.expect("never fails when casting to `Dynamic`"); .expect("never fails when casting to `Dynamic`");
lhs_ptr_inner = &mut *lock_guard; lhs_ptr_inner = &mut *lock_guard;
} else { } else {
lhs_ptr_inner = &mut *target; lhs_ptr_inner = &mut *target;
} }
let hash = hash_op_assign; let hash = hash_op_assign;
let args = &mut [lhs_ptr_inner, &mut new_value]; let args = &mut [lhs_ptr_inner, &mut new_val];
match self.call_native_fn(mods, state, lib, op, hash, args, true, true, op_pos) { 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)) =>
Err(err) if matches!(err.as_ref(), EvalAltResult::ErrorFunctionNotFound(f, _) if f.starts_with(op)) => {
{ // Expand to `var = var op rhs`
// Expand to `var = var op rhs` let op = &op[..op.len() - 1]; // extract operator without =
let op = &op[..op.len() - 1]; // extract operator without =
// Run function
// Run function let (value, _) = self.call_native_fn(
let (value, _) = self mods, state, lib, op, hash_op, args, true, false, op_pos,
.call_native_fn(mods, state, lib, op, hash_op, args, true, false, op_pos)?; )?;
*args[0] = value.flatten(); *args[0] = value.flatten();
}
err => return err.map(|_| ()),
} }
err => return err.map(|_| ()),
} }
Ok(()) target.propagate_changed_value()?;
} else { } else {
// Normal assignment // Normal assignment
target.set_value(new_value, new_value_pos)?; target.set_value(new_val, new_val_pos)?;
Ok(())
} }
Ok(())
} }
/// Evaluate a statement. /// Evaluate a statement.
@ -2757,20 +2833,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,38 +1101,34 @@ 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])?;
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() { collect_imports(&ast, &mut resolver, &mut imports);
while let Some(path) = imports.iter().next() {
let path = path.clone();
match self if !imports.is_empty() {
.module_resolver while let Some(path) = imports.iter().next() {
.resolve_ast(self, None, &path, Position::NONE) let path = path.clone();
{
Some(Ok(module_ast)) => { match module_resolver.resolve_ast(self, None, &path, Position::NONE) {
collect_imports(&module_ast, &mut resolver, &mut imports) 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);
} }
ast.set_resolver(resolver);
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);
} }
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,
@ -1416,6 +1400,7 @@ impl Engine {
arg_values[0] = target.take_or_clone().flatten(); arg_values[0] = target.take_or_clone().flatten();
args = arg_values.iter_mut().collect(); args = arg_values.iter_mut().collect();
} else { } else {
// Turn it into a method call only if the object is not shared and not a simple value
let (first, rest) = arg_values let (first, rest) = arg_values
.split_first_mut() .split_first_mut()
.expect("never fails because the arguments list is not empty"); .expect("never fails because the arguments list is not empty");

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,
@ -202,7 +202,7 @@ fn optimize_stmt_block(
match stmt { match stmt {
// Add constant literals into the state // Add constant literals into the state
Stmt::Const(value_expr, x, _, _) => { Stmt::Const(value_expr, x, _, _) => {
optimize_expr(value_expr, state); optimize_expr(value_expr, state, false);
if value_expr.is_constant() { if value_expr.is_constant() {
state.push_var( state.push_var(
@ -214,7 +214,7 @@ fn optimize_stmt_block(
} }
// Add variables into the state // Add variables into the state
Stmt::Let(value_expr, x, _, _) => { Stmt::Let(value_expr, x, _, _) => {
optimize_expr(value_expr, state); optimize_expr(value_expr, state, false);
state.push_var(&x.name, AccessMode::ReadWrite, None); state.push_var(&x.name, AccessMode::ReadWrite, None);
} }
// Optimize the statement // Optimize the statement
@ -392,10 +392,10 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) {
// expr op= expr // expr op= expr
Stmt::Assignment(x, _) => match x.0 { 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.0, state, false);
optimize_expr(&mut x.2, state); 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 pos = condition.position();
let mut expr = mem::take(condition); let mut expr = mem::take(condition);
optimize_expr(&mut expr, state); optimize_expr(&mut expr, state, false);
*stmt = if preserve_result { *stmt = if preserve_result {
// -> { expr, Noop } // -> { 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 } // if expr { if_block } else { else_block }
Stmt::If(condition, x, _) => { Stmt::If(condition, x, _) => {
optimize_expr(condition, state); optimize_expr(condition, state, false);
let if_block = mem::take(x.0.statements()).into_vec(); let if_block = mem::take(x.0.statements()).into_vec();
*x.0.statements() = *x.0.statements() =
optimize_stmt_block(if_block, state, preserve_result, true, false).into(); 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(block) = table.get_mut(&hash) {
if let Some(mut condition) = mem::take(&mut block.0) { if let Some(mut condition) = mem::take(&mut block.0) {
// switch const { case if condition => stmt, _ => def } => if condition { stmt } else { def } // 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_block = mem::take(&mut *x.1).into_vec();
let def_stmt = optimize_stmt_block(def_block, state, true, true, false); 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 // switch
Stmt::Switch(match_expr, x, _) => { Stmt::Switch(match_expr, x, _) => {
optimize_expr(match_expr, state); optimize_expr(match_expr, state, false);
x.0.values_mut().for_each(|block| { x.0.values_mut().for_each(|block| {
let condition = mem::take(&mut block.0).map_or_else( let condition = mem::take(&mut block.0).map_or_else(
|| Expr::Unit(Position::NONE), || Expr::Unit(Position::NONE),
|mut condition| { |mut condition| {
optimize_expr(&mut condition, state); optimize_expr(&mut condition, state, false);
condition condition
}, },
); );
@ -550,7 +550,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) {
} }
// while expr { block } // while expr { block }
Stmt::While(condition, body, _) => { Stmt::While(condition, body, _) => {
optimize_expr(condition, state); optimize_expr(condition, state, false);
let block = mem::take(body.statements()).into_vec(); let block = mem::take(body.statements()).into_vec();
*body.statements() = optimize_stmt_block(block, state, false, true, false).into(); *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 // do { block } while|until expr
Stmt::Do(body, condition, _, _) => { Stmt::Do(body, condition, _, _) => {
optimize_expr(condition, state); optimize_expr(condition, state, false);
let block = mem::take(body.statements()).into_vec(); let block = mem::take(body.statements()).into_vec();
*body.statements() = optimize_stmt_block(block, state, false, true, false).into(); *body.statements() = optimize_stmt_block(block, state, false, true, false).into();
} }
// for id in expr { block } // for id in expr { block }
Stmt::For(iterable, x, _) => { Stmt::For(iterable, x, _) => {
optimize_expr(iterable, state); optimize_expr(iterable, state, false);
let body = mem::take(x.1.statements()).into_vec(); let body = mem::take(x.1.statements()).into_vec();
*x.1.statements() = optimize_stmt_block(body, state, false, true, false).into(); *x.1.statements() = optimize_stmt_block(body, state, false, true, false).into();
} }
// let id = expr; // let id = expr;
Stmt::Let(expr, _, _, _) => optimize_expr(expr, state), Stmt::Let(expr, _, _, _) => optimize_expr(expr, state, false),
// import expr as var; // import expr as var;
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
Stmt::Import(expr, _, _) => optimize_expr(expr, state), Stmt::Import(expr, _, _) => optimize_expr(expr, state, false),
// { block } // { block }
Stmt::Block(statements, pos) => { Stmt::Block(statements, pos) => {
let statements = mem::take(statements).into_vec(); let statements = mem::take(statements).into_vec();
@ -640,7 +640,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) {
} }
// func(...) // func(...)
Stmt::Expr(expr @ Expr::FnCall(_, _)) => { Stmt::Expr(expr @ Expr::FnCall(_, _)) => {
optimize_expr(expr, state); optimize_expr(expr, state, false);
match expr { match expr {
Expr::FnCall(x, pos) => { Expr::FnCall(x, pos) => {
state.set_dirty(); 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(); *stmt = mem::take(x.as_mut()).into();
} }
// expr; // expr;
Stmt::Expr(expr) => optimize_expr(expr, state), Stmt::Expr(expr) => optimize_expr(expr, state, false),
// return expr; // 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 // All other statements - skip
_ => (), _ => (),
@ -670,7 +670,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) {
} }
/// Optimize an [expression][Expr]. /// Optimize an [expression][Expr].
fn optimize_expr(expr: &mut Expr, state: &mut State) { fn optimize_expr(expr: &mut Expr, state: &mut State, _chaining: bool) {
// These keywords are handled specially // These keywords are handled specially
const DONT_EVAL_KEYWORDS: &[&str] = &[ const DONT_EVAL_KEYWORDS: &[&str] = &[
KEYWORD_PRINT, // side effects KEYWORD_PRINT, // side effects
@ -693,7 +693,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
} }
// lhs.rhs // lhs.rhs
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Expr::Dot(x, _) => match (&mut x.lhs, &mut x.rhs) { Expr::Dot(x, _) if !_chaining => match (&mut x.lhs, &mut x.rhs) {
// map.string // map.string
(Expr::Map(m, pos), Expr::Property(p)) if m.0.iter().all(|(_, x)| x.is_pure()) => { (Expr::Map(m, pos), Expr::Property(p)) if m.0.iter().all(|(_, x)| x.is_pure()) => {
let prop = p.2.0.as_str(); 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)); .unwrap_or_else(|| Expr::Unit(*pos));
} }
// var.rhs // var.rhs
(Expr::Variable(_, _, _), rhs) => optimize_expr(rhs, state), (Expr::Variable(_, _, _), rhs) => optimize_expr(rhs, state, true),
// lhs.rhs // 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, _chaining); }
// lhs[rhs] // lhs[rhs]
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Expr::Index(x, _) => match (&mut x.lhs, &mut x.rhs) { Expr::Index(x, _) if !_chaining => match (&mut x.lhs, &mut x.rhs) {
// array[int] // array[int]
(Expr::Array(a, pos), Expr::IntegerConstant(i, _)) (Expr::Array(a, pos), Expr::IntegerConstant(i, _))
if *i >= 0 && (*i as usize) < a.len() && a.iter().all(Expr::is_pure) => 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 }) .map(|(_, mut expr)| { expr.set_position(*pos); expr })
.unwrap_or_else(|| Expr::Unit(*pos)); .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] // string[int]
(Expr::StringConstant(s, pos), Expr::IntegerConstant(i, _)) if *i >= 0 && (*i as usize) < s.chars().count() => { (Expr::StringConstant(s, pos), Expr::IntegerConstant(i, _)) if *i >= 0 && (*i as usize) < s.chars().count() => {
// String literal indexing - get the character // 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); *expr = Expr::CharConstant(s.chars().rev().nth(i.abs() as usize - 1).unwrap(), *pos);
} }
// var[rhs] // var[rhs]
(Expr::Variable(_, _, _), rhs) => optimize_expr(rhs, state), (Expr::Variable(_, _, _), rhs) => optimize_expr(rhs, state, true),
// lhs[rhs] // 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, _chaining); }
// `` // ``
Expr::InterpolatedString(x) if x.is_empty() => { Expr::InterpolatedString(x) if x.is_empty() => {
state.set_dirty(); state.set_dirty();
@ -773,7 +791,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
} }
// `... ${ ... } ...` // `... ${ ... } ...`
Expr::InterpolatedString(x) => { 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; let mut n= 0;
@ -824,7 +842,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
} }
// [ items .. ] // [ items .. ]
#[cfg(not(feature = "no_index"))] #[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, .. } // #{ key:constant, .. }
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Expr::Map(_, _) if expr.is_constant() => { Expr::Map(_, _) if expr.is_constant() => {
@ -833,13 +851,13 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
} }
// #{ key:value, .. } // #{ key:value, .. }
#[cfg(not(feature = "no_object"))] #[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 // lhs && rhs
Expr::And(x, _) => match (&mut x.lhs, &mut x.rhs) { Expr::And(x, _) => match (&mut x.lhs, &mut x.rhs) {
// true && rhs -> rhs // true && rhs -> rhs
(Expr::BoolConstant(true, _), rhs) => { (Expr::BoolConstant(true, _), rhs) => {
state.set_dirty(); state.set_dirty();
optimize_expr(rhs, state); optimize_expr(rhs, state, false);
*expr = mem::take(rhs); *expr = mem::take(rhs);
} }
// false && rhs -> false // false && rhs -> false
@ -850,18 +868,18 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
// lhs && true -> lhs // lhs && true -> lhs
(lhs, Expr::BoolConstant(true, _)) => { (lhs, Expr::BoolConstant(true, _)) => {
state.set_dirty(); state.set_dirty();
optimize_expr(lhs, state); optimize_expr(lhs, state, false);
*expr = mem::take(lhs); *expr = mem::take(lhs);
} }
// lhs && rhs // 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 // lhs || rhs
Expr::Or(ref mut x, _) => match (&mut x.lhs, &mut x.rhs) { Expr::Or(ref mut x, _) => match (&mut x.lhs, &mut x.rhs) {
// false || rhs -> rhs // false || rhs -> rhs
(Expr::BoolConstant(false, _), rhs) => { (Expr::BoolConstant(false, _), rhs) => {
state.set_dirty(); state.set_dirty();
optimize_expr(rhs, state); optimize_expr(rhs, state, false);
*expr = mem::take(rhs); *expr = mem::take(rhs);
} }
// true || rhs -> true // true || rhs -> true
@ -872,11 +890,11 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
// lhs || false // lhs || false
(lhs, Expr::BoolConstant(false, _)) => { (lhs, Expr::BoolConstant(false, _)) => {
state.set_dirty(); state.set_dirty();
optimize_expr(lhs, state); optimize_expr(lhs, state, false);
*expr = mem::take(lhs); *expr = mem::take(lhs);
} }
// lhs || rhs // 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! // eval!
@ -899,7 +917,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
// Do not call some special keywords // Do not call some special keywords
Expr::FnCall(x, _) if DONT_EVAL_KEYWORDS.contains(&x.name.as_ref()) => { 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 // 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 // Move constant arguments to the right
while x.args.last().map(Expr::is_constant).unwrap_or(false) { 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 // id(args ..) -> optimize function call arguments
Expr::FnCall(x, _) => { 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 // Move constant arguments to the right
while x.args.last().map(Expr::is_constant).unwrap_or(false) { 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 { if x.scope_changed {
state.propagate_constants = false; 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 // All other expressions - skip

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

@ -126,6 +126,71 @@ 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::<INT>() * 8;
impl BitRange {
pub fn new(value: INT, from: INT, len: INT) -> Result<Self, Box<EvalAltResult>> {
let from = if from >= 0 {
let offset = from as usize;
#[cfg(not(feature = "unchecked"))]
if offset >= BITS {
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, crate::Position::NONE)
.into();
}
BITS - (abs_from as usize)
} else {
return EvalAltResult::ErrorBitFieldBounds(BITS, from, crate::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<Self::Item> {
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 { macro_rules! reg_range {
($lib:ident | $x:expr => $( $y:ty ),*) => { ($lib:ident | $x:expr => $( $y:ty ),*) => {
$( $(
@ -304,4 +369,18 @@ def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, {
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
lib.update_fn_metadata(_hash, &["from: Decimal", "to: Decimal", "step: Decimal", "Iterator<Item=Decimal>"]); lib.update_fn_metadata(_hash, &["from: Decimal", "to: Decimal", "step: Decimal", "Iterator<Item=Decimal>"]);
} }
lib.set_iterator::<BitRange>();
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<Item=bool>"]);
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<Item=bool>"]);
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<Item=bool>"]);
}); });

View File

@ -1,7 +1,7 @@
#![allow(non_snake_case)] #![allow(non_snake_case)]
use crate::def_package;
use crate::plugin::*; use crate::plugin::*;
use crate::{def_package, EvalAltResult, INT};
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
use std::prelude::v1::*; use std::prelude::v1::*;
@ -59,6 +59,8 @@ def_package!(crate:LogicPackage:"Logical operators.", lib, {
} }
set_exported_fn!(lib, "!", not); set_exported_fn!(lib, "!", not);
combine_with_exported_module!(lib, "bit_field", bit_field_functions);
}); });
// Logic operators // Logic operators
@ -87,8 +89,6 @@ gen_cmp_functions!(float => f64);
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
#[export_module] #[export_module]
mod f32_functions { mod f32_functions {
use crate::INT;
#[rhai_fn(name = "==")] #[rhai_fn(name = "==")]
pub fn eq_if(x: INT, y: f32) -> bool { pub fn eq_if(x: INT, y: f32) -> bool {
(x as f32) == (y as f32) (x as f32) == (y as f32)
@ -142,8 +142,6 @@ mod f32_functions {
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
#[export_module] #[export_module]
mod f64_functions { mod f64_functions {
use crate::INT;
#[rhai_fn(name = "==")] #[rhai_fn(name = "==")]
pub fn eq_if(x: INT, y: f64) -> bool { pub fn eq_if(x: INT, y: f64) -> bool {
(x as f64) == (y as f64) (x as f64) == (y as f64)
@ -193,3 +191,159 @@ mod f64_functions {
(x as f64) <= (y as f64) (x as f64) <= (y as f64)
} }
} }
#[export_module]
mod bit_field_functions {
const BITS: usize = std::mem::size_of::<INT>() * 8;
#[rhai_fn(return_raw)]
pub fn get_bit(value: INT, index: INT) -> Result<bool, Box<EvalAltResult>> {
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<EvalAltResult>> {
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<INT, Box<EvalAltResult>> {
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<EvalAltResult>> {
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(())
}
}

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

@ -15,7 +15,7 @@ use crate::token::{
}; };
use crate::utils::{get_hasher, IdentifierBuilder}; use crate::utils::{get_hasher, IdentifierBuilder};
use crate::{ 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, ParseErrorType, Position, Scope, Shared, StaticVec, AST,
}; };
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
@ -455,7 +455,10 @@ fn parse_index_chain(
// Check type of indexing - must be integer or string // Check type of indexing - must be integer or string
match &idx_expr { match &idx_expr {
Expr::IntegerConstant(_, pos) => match lhs { Expr::IntegerConstant(_, pos) => match lhs {
Expr::Array(_, _) | Expr::StringConstant(_, _) | Expr::InterpolatedString(_) => (), Expr::IntegerConstant(_, _)
| Expr::Array(_, _)
| Expr::StringConstant(_, _)
| Expr::InterpolatedString(_) => (),
Expr::Map(_, _) => { Expr::Map(_, _) => {
return Err(PERR::MalformedIndexExpr( return Err(PERR::MalformedIndexExpr(
@ -1864,7 +1867,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());
@ -3014,7 +3017,7 @@ fn parse_anon_fn(
comments: Default::default(), 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); let expr = Expr::DynamicConstant(Box::new(fn_ptr.into()), settings.pos);
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]

View File

@ -25,7 +25,4 @@ pub trait PluginFunction {
/// Is this plugin function a method? /// Is this plugin function a method?
fn is_method_call(&self) -> bool; fn is_method_call(&self) -> bool;
/// Is this plugin function variadic?
fn is_variadic(&self) -> bool;
} }

View File

@ -56,6 +56,9 @@ pub enum EvalAltResult {
/// String indexing out-of-bounds. /// String indexing out-of-bounds.
/// Wrapped values are the current number of characters in the string and the index number. /// Wrapped values are the current number of characters in the string and the index number.
ErrorStringBounds(usize, INT, Position), 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 /// 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. /// indexer function defined. Wrapped value is the type name.
ErrorIndexingType(String, Position), ErrorIndexingType(String, Position),
@ -109,6 +112,7 @@ impl EvalAltResult {
Self::ErrorArrayBounds(_, _, _) => "Array index out of bounds", Self::ErrorArrayBounds(_, _, _) => "Array index out of bounds",
Self::ErrorStringBounds(0, _, _) => "Empty string has nothing to index", Self::ErrorStringBounds(0, _, _) => "Empty string has nothing to index",
Self::ErrorStringBounds(_, _, _) => "String index out of bounds", 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::ErrorFor(_) => "For loop expects an array, object map, or range",
Self::ErrorVariableNotFound(_, _) => "Variable not found", Self::ErrorVariableNotFound(_, _) => "Variable not found",
Self::ErrorModuleNotFound(_, _) => "Module 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", "String index {} out of bounds: only {} characters in the string",
index, max 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)?, Self::ErrorDataTooLarge(typ, _) => write!(f, "{} exceeds maximum limit", typ)?,
} }
@ -289,6 +298,7 @@ impl EvalAltResult {
| Self::ErrorMismatchDataType(_, _, _) | Self::ErrorMismatchDataType(_, _, _)
| Self::ErrorArrayBounds(_, _, _) | Self::ErrorArrayBounds(_, _, _)
| Self::ErrorStringBounds(_, _, _) | Self::ErrorStringBounds(_, _, _)
| Self::ErrorBitFieldBounds(_, _, _)
| Self::ErrorIndexingType(_, _) | Self::ErrorIndexingType(_, _)
| Self::ErrorFor(_) | Self::ErrorFor(_)
| Self::ErrorVariableNotFound(_, _) | Self::ErrorVariableNotFound(_, _)
@ -372,7 +382,9 @@ impl EvalAltResult {
map.insert("requested".into(), r.into()); map.insert("requested".into(), r.into());
map.insert("actual".into(), a.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("length".into(), (*n as INT).into());
map.insert("index".into(), (*i as INT).into()); map.insert("index".into(), (*i as INT).into());
} }
@ -412,6 +424,7 @@ impl EvalAltResult {
| Self::ErrorMismatchDataType(_, _, pos) | Self::ErrorMismatchDataType(_, _, pos)
| Self::ErrorArrayBounds(_, _, pos) | Self::ErrorArrayBounds(_, _, pos)
| Self::ErrorStringBounds(_, _, pos) | Self::ErrorStringBounds(_, _, pos)
| Self::ErrorBitFieldBounds(_, _, pos)
| Self::ErrorIndexingType(_, pos) | Self::ErrorIndexingType(_, pos)
| Self::ErrorFor(pos) | Self::ErrorFor(pos)
| Self::ErrorVariableNotFound(_, pos) | Self::ErrorVariableNotFound(_, pos)
@ -452,6 +465,7 @@ impl EvalAltResult {
| Self::ErrorMismatchDataType(_, _, pos) | Self::ErrorMismatchDataType(_, _, pos)
| Self::ErrorArrayBounds(_, _, pos) | Self::ErrorArrayBounds(_, _, pos)
| Self::ErrorStringBounds(_, _, pos) | Self::ErrorStringBounds(_, _, pos)
| Self::ErrorBitFieldBounds(_, _, pos)
| Self::ErrorIndexingType(_, pos) | Self::ErrorIndexingType(_, pos)
| Self::ErrorFor(pos) | Self::ErrorFor(pos)
| Self::ErrorVariableNotFound(_, pos) | Self::ErrorVariableNotFound(_, pos)

View File

@ -13,3 +13,38 @@ fn test_right_shift() -> Result<(), Box<EvalAltResult>> {
assert_eq!(engine.eval::<INT>("9 >> 1")?, 4); assert_eq!(engine.eval::<INT>("9 >> 1")?, 4);
Ok(()) Ok(())
} }
#[cfg(not(feature = "no_index"))]
#[test]
fn test_bit_fields() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert!(!engine.eval::<bool>("let x = 10; x[0]")?);
assert!(engine.eval::<bool>("let x = 10; x[1]")?);
assert!(!engine.eval::<bool>("let x = 10; x[-1]")?);
assert_eq!(
engine.eval::<INT>("let x = 10; x[0] = true; x[1] = false; x")?,
9
);
assert_eq!(engine.eval::<INT>("let x = 10; get_bits(x, 1, 3)")?, 5);
assert_eq!(
engine.eval::<INT>("let x = 10; set_bits(x, 1, 3, 7); x")?,
14
);
assert_eq!(
engine.eval::<INT>(
"
let x = 0b001101101010001;
let count = 0;
for b in bits(x, 2, 10) {
if b { count += 1; }
}
count
"
)?,
5
);
Ok(())
}