commit
a4292ab0f9
14
CHANGELOG.md
14
CHANGELOG.md
@ -1,6 +1,20 @@
|
||||
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
|
||||
==============
|
||||
|
||||
|
@ -3,7 +3,7 @@ members = [".", "codegen"]
|
||||
|
||||
[package]
|
||||
name = "rhai"
|
||||
version = "0.20.2"
|
||||
version = "0.20.3"
|
||||
edition = "2018"
|
||||
authors = ["Jonathan Turner", "Lukáš Hozda", "Stephen Chung", "jhwgh1968"]
|
||||
description = "Embedded scripting for Rust"
|
||||
@ -20,7 +20,7 @@ smallvec = { version = "1.6", default-features = false, features = ["union"] }
|
||||
ahash = { version = "0.7", default-features = false }
|
||||
num-traits = { version = "0.2", default_features = false }
|
||||
smartstring = { version = "0.2.6", default_features = false }
|
||||
rhai_codegen = { version = "0.3.4", path = "codegen", default_features = false }
|
||||
rhai_codegen = { version = "0.3.7", path = "codegen", default_features = false }
|
||||
|
||||
[features]
|
||||
default = ["smartstring/std", "ahash/std", "num-traits/std"] # remove 'smartstring/std' when smartstring is updated to support no-std
|
||||
|
@ -11,6 +11,7 @@ Rhai - Embedded Scripting for Rust
|
||||
[![VS Code plugin installs](https://img.shields.io/visual-studio-marketplace/i/rhaiscript.vscode-rhai?logo=visual-studio-code&label=vs%20code)](https://marketplace.visualstudio.com/items?itemName=rhaiscript.vscode-rhai)
|
||||
[![Sublime Text package downloads](https://img.shields.io/packagecontrol/dt/Rhai.svg?logo=sublime-text&label=sublime%20text)](https://packagecontrol.io/packages/Rhai)
|
||||
[![Discord Chat](https://img.shields.io/discord/767611025456889857.svg?logo=discord&label=discord)](https://discord.gg/HquqbYFcZ9)
|
||||
[![Zulip Chat](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg?logo=zulip)](https://rhaiscript.zulipchat.com)
|
||||
[![Reddit Channel](https://img.shields.io/reddit/subreddit-subscribers/Rhai?logo=reddit&label=reddit)](https://www.reddit.com/r/Rhai)
|
||||
|
||||
[![Rhai logo](https://rhai.rs/book/images/logo/rhai-banner-transparent-colour.svg)](https://rhai.rs)
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "rhai_codegen"
|
||||
version = "0.3.6"
|
||||
version = "0.3.7"
|
||||
edition = "2018"
|
||||
authors = ["jhwgh1968", "Stephen Chung"]
|
||||
description = "Procedural macros support package for Rhai, a scripting language and engine for Rust"
|
||||
@ -16,7 +16,7 @@ default = []
|
||||
metadata = []
|
||||
|
||||
[dev-dependencies]
|
||||
rhai = { path = "..", version = ">=0.19.15" }
|
||||
rhai = { path = "..", version = ">=0.20.3" }
|
||||
trybuild = "1"
|
||||
|
||||
[dependencies]
|
||||
|
@ -845,7 +845,6 @@ impl ExportedFn {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { #is_method_call }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -286,7 +286,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
#[allow(unused)]
|
||||
#[inline(always)] pub fn dynamic_result_fn() -> RhaiResult {
|
||||
@ -322,7 +321,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
#[allow(unused)]
|
||||
#[inline(always)] pub fn dynamic_result_fn(x: usize) -> RhaiResult {
|
||||
@ -358,7 +356,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
#[allow(unused)]
|
||||
#[inline(always)] pub fn dynamic_result_fn(context: NativeCallContext, x: usize) -> RhaiResult {
|
||||
@ -396,7 +393,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
#[allow(unused)]
|
||||
#[inline(always)] pub fn dynamic_result_fn() -> RhaiResult {
|
||||
@ -428,7 +424,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
};
|
||||
|
||||
@ -460,7 +455,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
#[allow(unused)]
|
||||
#[inline(always)] pub fn dynamic_result_fn(x: usize, y: usize) -> RhaiResult {
|
||||
@ -500,7 +494,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { true }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
#[allow(unused)]
|
||||
#[inline(always)] pub fn dynamic_result_fn(x: &mut usize, y: usize) -> RhaiResult {
|
||||
@ -537,7 +530,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
#[allow(unused)]
|
||||
#[inline(always)] pub fn dynamic_result_fn(message: &str) -> RhaiResult {
|
||||
|
@ -315,7 +315,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -370,7 +369,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -424,7 +422,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -492,7 +489,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
@ -510,7 +506,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -565,7 +560,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -627,7 +621,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -862,7 +855,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -947,7 +939,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -1001,7 +992,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { false }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -1057,7 +1047,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { true }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -1114,7 +1103,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { true }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -1174,7 +1162,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { true }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
#[allow(unused_imports)]
|
||||
@ -1255,7 +1242,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { true }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
#[allow(unused_imports)]
|
||||
@ -1337,7 +1323,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { true }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -1398,7 +1383,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { true }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -1457,7 +1441,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { true }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -1519,7 +1502,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { true }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -1578,7 +1560,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { true }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -1640,7 +1621,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { true }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -1700,7 +1680,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { true }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -1763,7 +1742,6 @@ mod generate_tests {
|
||||
}
|
||||
|
||||
#[inline(always)] fn is_method_call(&self) -> bool { true }
|
||||
#[inline(always)] fn is_variadic(&self) -> bool { false }
|
||||
}
|
||||
}
|
||||
};
|
||||
|
@ -2014,13 +2014,13 @@ impl Expr {
|
||||
|
||||
Self::DynamicConstant(_, _)
|
||||
| Self::BoolConstant(_, _)
|
||||
| Self::IntegerConstant(_, _)
|
||||
| Self::CharConstant(_, _)
|
||||
| Self::And(_, _)
|
||||
| Self::Or(_, _)
|
||||
| Self::Unit(_) => false,
|
||||
|
||||
Self::StringConstant(_, _)
|
||||
Self::IntegerConstant(_, _)
|
||||
| Self::StringConstant(_, _)
|
||||
| Self::InterpolatedString(_)
|
||||
| Self::FnCall(_, _)
|
||||
| Self::Stmt(_)
|
||||
|
@ -83,7 +83,7 @@ fn main() {
|
||||
|
||||
if let Err(err) = engine
|
||||
.compile(contents)
|
||||
.map_err(|err| Box::new(err.into()) as Box<EvalAltResult>)
|
||||
.map_err(|err| err.into())
|
||||
.and_then(|mut ast| {
|
||||
ast.set_source(filename.to_string_lossy().to_string());
|
||||
engine.consume_ast(&ast)
|
||||
|
136
src/dynamic.rs
136
src/dynamic.rs
@ -711,6 +711,8 @@ impl fmt::Debug for Dynamic {
|
||||
}
|
||||
}
|
||||
|
||||
use AccessMode::*;
|
||||
|
||||
impl Clone for Dynamic {
|
||||
/// Clone the [`Dynamic`] value.
|
||||
///
|
||||
@ -719,33 +721,25 @@ impl Clone for Dynamic {
|
||||
/// The cloned copy is marked read-write even if the original is read-only.
|
||||
fn clone(&self) -> Self {
|
||||
match self.0 {
|
||||
Union::Unit(value, tag, _) => Self(Union::Unit(value, tag, AccessMode::ReadWrite)),
|
||||
Union::Bool(value, tag, _) => Self(Union::Bool(value, tag, AccessMode::ReadWrite)),
|
||||
Union::Str(ref value, tag, _) => {
|
||||
Self(Union::Str(value.clone(), tag, AccessMode::ReadWrite))
|
||||
}
|
||||
Union::Char(value, tag, _) => Self(Union::Char(value, tag, AccessMode::ReadWrite)),
|
||||
Union::Int(value, tag, _) => Self(Union::Int(value, tag, AccessMode::ReadWrite)),
|
||||
Union::Unit(value, tag, _) => Self(Union::Unit(value, tag, ReadWrite)),
|
||||
Union::Bool(value, tag, _) => Self(Union::Bool(value, tag, ReadWrite)),
|
||||
Union::Str(ref value, tag, _) => Self(Union::Str(value.clone(), tag, ReadWrite)),
|
||||
Union::Char(value, tag, _) => Self(Union::Char(value, tag, ReadWrite)),
|
||||
Union::Int(value, tag, _) => Self(Union::Int(value, tag, ReadWrite)),
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
Union::Float(value, tag, _) => Self(Union::Float(value, tag, AccessMode::ReadWrite)),
|
||||
Union::Float(value, tag, _) => Self(Union::Float(value, tag, ReadWrite)),
|
||||
#[cfg(feature = "decimal")]
|
||||
Union::Decimal(ref value, tag, _) => {
|
||||
Self(Union::Decimal(value.clone(), tag, AccessMode::ReadWrite))
|
||||
Self(Union::Decimal(value.clone(), tag, ReadWrite))
|
||||
}
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Union::Array(ref value, tag, _) => {
|
||||
Self(Union::Array(value.clone(), tag, AccessMode::ReadWrite))
|
||||
}
|
||||
Union::Array(ref value, tag, _) => Self(Union::Array(value.clone(), tag, ReadWrite)),
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Union::Map(ref value, tag, _) => {
|
||||
Self(Union::Map(value.clone(), tag, AccessMode::ReadWrite))
|
||||
}
|
||||
Union::FnPtr(ref value, tag, _) => {
|
||||
Self(Union::FnPtr(value.clone(), tag, AccessMode::ReadWrite))
|
||||
}
|
||||
Union::Map(ref value, tag, _) => Self(Union::Map(value.clone(), tag, ReadWrite)),
|
||||
Union::FnPtr(ref value, tag, _) => Self(Union::FnPtr(value.clone(), tag, ReadWrite)),
|
||||
#[cfg(not(feature = "no_std"))]
|
||||
Union::TimeStamp(ref value, tag, _) => {
|
||||
Self(Union::TimeStamp(value.clone(), tag, AccessMode::ReadWrite))
|
||||
Self(Union::TimeStamp(value.clone(), tag, ReadWrite))
|
||||
}
|
||||
|
||||
Union::Variant(ref value, tag, _) => {
|
||||
@ -755,9 +749,7 @@ impl Clone for Dynamic {
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
Union::Shared(ref cell, tag, _) => {
|
||||
Self(Union::Shared(cell.clone(), tag, AccessMode::ReadWrite))
|
||||
}
|
||||
Union::Shared(ref cell, tag, _) => Self(Union::Shared(cell.clone(), tag, ReadWrite)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -771,21 +763,21 @@ impl Default for Dynamic {
|
||||
|
||||
impl Dynamic {
|
||||
/// A [`Dynamic`] containing a `()`.
|
||||
pub const UNIT: Dynamic = Self(Union::Unit((), DEFAULT_TAG, AccessMode::ReadWrite));
|
||||
pub const UNIT: Dynamic = Self(Union::Unit((), DEFAULT_TAG, ReadWrite));
|
||||
/// A [`Dynamic`] containing a `true`.
|
||||
pub const TRUE: Dynamic = Self(Union::Bool(true, DEFAULT_TAG, AccessMode::ReadWrite));
|
||||
pub const TRUE: Dynamic = Self(Union::Bool(true, DEFAULT_TAG, ReadWrite));
|
||||
/// A [`Dynamic`] containing a [`false`].
|
||||
pub const FALSE: Dynamic = Self(Union::Bool(false, DEFAULT_TAG, AccessMode::ReadWrite));
|
||||
pub const FALSE: Dynamic = Self(Union::Bool(false, DEFAULT_TAG, ReadWrite));
|
||||
/// A [`Dynamic`] containing the integer zero.
|
||||
pub const ZERO: Dynamic = Self(Union::Int(0, DEFAULT_TAG, AccessMode::ReadWrite));
|
||||
pub const ZERO: Dynamic = Self(Union::Int(0, DEFAULT_TAG, ReadWrite));
|
||||
/// A [`Dynamic`] containing the integer one.
|
||||
pub const ONE: Dynamic = Self(Union::Int(1, DEFAULT_TAG, AccessMode::ReadWrite));
|
||||
pub const ONE: Dynamic = Self(Union::Int(1, DEFAULT_TAG, ReadWrite));
|
||||
/// A [`Dynamic`] containing the integer two.
|
||||
pub const TWO: Dynamic = Self(Union::Int(2, DEFAULT_TAG, AccessMode::ReadWrite));
|
||||
pub const TWO: Dynamic = Self(Union::Int(2, DEFAULT_TAG, ReadWrite));
|
||||
/// A [`Dynamic`] containing the integer ten.
|
||||
pub const TEN: Dynamic = Self(Union::Int(10, DEFAULT_TAG, AccessMode::ReadWrite));
|
||||
pub const TEN: Dynamic = Self(Union::Int(10, DEFAULT_TAG, ReadWrite));
|
||||
/// A [`Dynamic`] containing the integer negative one.
|
||||
pub const NEGATIVE_ONE: Dynamic = Self(Union::Int(-1, DEFAULT_TAG, AccessMode::ReadWrite));
|
||||
pub const NEGATIVE_ONE: Dynamic = Self(Union::Int(-1, DEFAULT_TAG, ReadWrite));
|
||||
/// A [`Dynamic`] containing `0.0`.
|
||||
///
|
||||
/// Not available under `no_float`.
|
||||
@ -793,7 +785,7 @@ impl Dynamic {
|
||||
pub const FLOAT_ZERO: Dynamic = Self(Union::Float(
|
||||
FloatWrapper::const_new(0.0),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
ReadWrite,
|
||||
));
|
||||
/// A [`Dynamic`] containing `1.0`.
|
||||
///
|
||||
@ -802,7 +794,7 @@ impl Dynamic {
|
||||
pub const FLOAT_ONE: Dynamic = Self(Union::Float(
|
||||
FloatWrapper::const_new(1.0),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
ReadWrite,
|
||||
));
|
||||
/// A [`Dynamic`] containing `2.0`.
|
||||
///
|
||||
@ -811,7 +803,7 @@ impl Dynamic {
|
||||
pub const FLOAT_TWO: Dynamic = Self(Union::Float(
|
||||
FloatWrapper::const_new(2.0),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
ReadWrite,
|
||||
));
|
||||
/// A [`Dynamic`] containing `10.0`.
|
||||
///
|
||||
@ -820,7 +812,7 @@ impl Dynamic {
|
||||
pub const FLOAT_TEN: Dynamic = Self(Union::Float(
|
||||
FloatWrapper::const_new(10.0),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
ReadWrite,
|
||||
));
|
||||
/// A [`Dynamic`] containing the `-1.0`.
|
||||
///
|
||||
@ -829,7 +821,7 @@ impl Dynamic {
|
||||
pub const FLOAT_NEGATIVE_ONE: Dynamic = Self(Union::Float(
|
||||
FloatWrapper::const_new(-1.0),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
ReadWrite,
|
||||
));
|
||||
|
||||
/// Get the [`AccessMode`] for this [`Dynamic`].
|
||||
@ -898,7 +890,7 @@ impl Dynamic {
|
||||
pub fn is_read_only(&self) -> bool {
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
match self.0 {
|
||||
Union::Shared(_, _, AccessMode::ReadOnly) => return true,
|
||||
Union::Shared(_, _, ReadOnly) => return true,
|
||||
Union::Shared(ref cell, _, _) => {
|
||||
#[cfg(not(feature = "sync"))]
|
||||
let value = cell.borrow();
|
||||
@ -906,16 +898,16 @@ impl Dynamic {
|
||||
let value = cell.read().unwrap();
|
||||
|
||||
return match value.access_mode() {
|
||||
AccessMode::ReadWrite => false,
|
||||
AccessMode::ReadOnly => true,
|
||||
ReadWrite => false,
|
||||
ReadOnly => true,
|
||||
};
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
|
||||
match self.access_mode() {
|
||||
AccessMode::ReadWrite => false,
|
||||
AccessMode::ReadOnly => true,
|
||||
ReadWrite => false,
|
||||
ReadOnly => true,
|
||||
}
|
||||
}
|
||||
/// Can this [`Dynamic`] be hashed?
|
||||
@ -1066,7 +1058,7 @@ impl Dynamic {
|
||||
Self(Union::Variant(
|
||||
Box::new(Box::new(value)),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
ReadWrite,
|
||||
))
|
||||
}
|
||||
/// Turn the [`Dynamic`] value into a shared [`Dynamic`] value backed by an
|
||||
@ -1788,37 +1780,33 @@ impl Dynamic {
|
||||
impl From<()> for Dynamic {
|
||||
#[inline(always)]
|
||||
fn from(value: ()) -> Self {
|
||||
Self(Union::Unit(value, DEFAULT_TAG, AccessMode::ReadWrite))
|
||||
Self(Union::Unit(value, DEFAULT_TAG, ReadWrite))
|
||||
}
|
||||
}
|
||||
impl From<bool> for Dynamic {
|
||||
#[inline(always)]
|
||||
fn from(value: bool) -> Self {
|
||||
Self(Union::Bool(value, DEFAULT_TAG, AccessMode::ReadWrite))
|
||||
Self(Union::Bool(value, DEFAULT_TAG, ReadWrite))
|
||||
}
|
||||
}
|
||||
impl From<INT> for Dynamic {
|
||||
#[inline(always)]
|
||||
fn from(value: INT) -> Self {
|
||||
Self(Union::Int(value, DEFAULT_TAG, AccessMode::ReadWrite))
|
||||
Self(Union::Int(value, DEFAULT_TAG, ReadWrite))
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
impl From<FLOAT> for Dynamic {
|
||||
#[inline(always)]
|
||||
fn from(value: FLOAT) -> Self {
|
||||
Self(Union::Float(
|
||||
value.into(),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
))
|
||||
Self(Union::Float(value.into(), DEFAULT_TAG, ReadWrite))
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
impl From<FloatWrapper<FLOAT>> for Dynamic {
|
||||
#[inline(always)]
|
||||
fn from(value: FloatWrapper<FLOAT>) -> Self {
|
||||
Self(Union::Float(value, DEFAULT_TAG, AccessMode::ReadWrite))
|
||||
Self(Union::Float(value, DEFAULT_TAG, ReadWrite))
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "decimal")]
|
||||
@ -1828,20 +1816,20 @@ impl From<Decimal> for Dynamic {
|
||||
Self(Union::Decimal(
|
||||
Box::new(value.into()),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
ReadWrite,
|
||||
))
|
||||
}
|
||||
}
|
||||
impl From<char> for Dynamic {
|
||||
#[inline(always)]
|
||||
fn from(value: char) -> Self {
|
||||
Self(Union::Char(value, DEFAULT_TAG, AccessMode::ReadWrite))
|
||||
Self(Union::Char(value, DEFAULT_TAG, ReadWrite))
|
||||
}
|
||||
}
|
||||
impl<S: Into<ImmutableString>> From<S> for Dynamic {
|
||||
#[inline(always)]
|
||||
fn from(value: S) -> Self {
|
||||
Self(Union::Str(value.into(), DEFAULT_TAG, AccessMode::ReadWrite))
|
||||
Self(Union::Str(value.into(), DEFAULT_TAG, ReadWrite))
|
||||
}
|
||||
}
|
||||
impl From<&ImmutableString> for Dynamic {
|
||||
@ -1862,11 +1850,7 @@ impl Dynamic {
|
||||
/// Create a [`Dynamic`] from an [`Array`].
|
||||
#[inline(always)]
|
||||
pub(crate) fn from_array(array: Array) -> Self {
|
||||
Self(Union::Array(
|
||||
Box::new(array),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
))
|
||||
Self(Union::Array(Box::new(array), DEFAULT_TAG, ReadWrite))
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
@ -1876,7 +1860,7 @@ impl<T: Variant + Clone> From<Vec<T>> for Dynamic {
|
||||
Self(Union::Array(
|
||||
Box::new(value.into_iter().map(Dynamic::from).collect()),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
ReadWrite,
|
||||
))
|
||||
}
|
||||
}
|
||||
@ -1887,7 +1871,7 @@ impl<T: Variant + Clone> From<&[T]> for Dynamic {
|
||||
Self(Union::Array(
|
||||
Box::new(value.iter().cloned().map(Dynamic::from).collect()),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
ReadWrite,
|
||||
))
|
||||
}
|
||||
}
|
||||
@ -1898,7 +1882,7 @@ impl<T: Variant + Clone> std::iter::FromIterator<T> for Dynamic {
|
||||
Self(Union::Array(
|
||||
Box::new(iter.into_iter().map(Dynamic::from).collect()),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
ReadWrite,
|
||||
))
|
||||
}
|
||||
}
|
||||
@ -1907,11 +1891,7 @@ impl Dynamic {
|
||||
/// Create a [`Dynamic`] from a [`Map`].
|
||||
#[inline(always)]
|
||||
pub(crate) fn from_map(map: Map) -> Self {
|
||||
Self(Union::Map(
|
||||
Box::new(map),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
))
|
||||
Self(Union::Map(Box::new(map), DEFAULT_TAG, ReadWrite))
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
@ -1929,7 +1909,7 @@ impl<K: Into<crate::Identifier>, T: Variant + Clone> From<std::collections::Hash
|
||||
.collect(),
|
||||
),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
ReadWrite,
|
||||
))
|
||||
}
|
||||
}
|
||||
@ -1947,45 +1927,33 @@ impl<K: Into<crate::Identifier>, T: Variant + Clone> From<std::collections::BTre
|
||||
.collect(),
|
||||
),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
ReadWrite,
|
||||
))
|
||||
}
|
||||
}
|
||||
impl From<FnPtr> for Dynamic {
|
||||
#[inline(always)]
|
||||
fn from(value: FnPtr) -> Self {
|
||||
Self(Union::FnPtr(
|
||||
Box::new(value),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
))
|
||||
Self(Union::FnPtr(Box::new(value), DEFAULT_TAG, ReadWrite))
|
||||
}
|
||||
}
|
||||
impl From<Box<FnPtr>> for Dynamic {
|
||||
#[inline(always)]
|
||||
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"))]
|
||||
impl From<Instant> for Dynamic {
|
||||
#[inline(always)]
|
||||
fn from(value: Instant) -> Self {
|
||||
Self(Union::TimeStamp(
|
||||
Box::new(value),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
))
|
||||
Self(Union::TimeStamp(Box::new(value), DEFAULT_TAG, ReadWrite))
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
impl From<crate::Shared<crate::Locked<Dynamic>>> for Dynamic {
|
||||
#[inline(always)]
|
||||
fn from(value: crate::Shared<crate::Locked<Self>>) -> Self {
|
||||
Self(Union::Shared(
|
||||
value.into(),
|
||||
DEFAULT_TAG,
|
||||
AccessMode::ReadWrite,
|
||||
))
|
||||
Self(Union::Shared(value.into(), DEFAULT_TAG, ReadWrite))
|
||||
}
|
||||
}
|
||||
|
210
src/engine.rs
210
src/engine.rs
@ -263,7 +263,7 @@ enum ChainArgument {
|
||||
Property(Position),
|
||||
/// Arguments to a dot method call.
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
MethodCallArgs(StaticVec<Dynamic>, StaticVec<Position>),
|
||||
MethodCallArgs(StaticVec<Dynamic>, Position),
|
||||
/// Index value.
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
IndexValue(Dynamic, Position),
|
||||
@ -294,7 +294,7 @@ impl ChainArgument {
|
||||
/// Panics if not `ChainArgument::MethodCallArgs`.
|
||||
#[inline(always)]
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
pub fn as_fn_call_args(self) -> (StaticVec<Dynamic>, StaticVec<Position>) {
|
||||
pub fn as_fn_call_args(self) -> (StaticVec<Dynamic>, Position) {
|
||||
match self {
|
||||
Self::Property(_) => {
|
||||
panic!("expecting ChainArgument::MethodCallArgs")
|
||||
@ -303,16 +303,16 @@ impl ChainArgument {
|
||||
Self::IndexValue(_, _) => {
|
||||
panic!("expecting ChainArgument::MethodCallArgs")
|
||||
}
|
||||
Self::MethodCallArgs(values, positions) => (values, positions),
|
||||
Self::MethodCallArgs(values, pos) => (values, pos),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
impl From<(StaticVec<Dynamic>, StaticVec<Position>)> for ChainArgument {
|
||||
impl From<(StaticVec<Dynamic>, Position)> for ChainArgument {
|
||||
#[inline(always)]
|
||||
fn from((values, positions): (StaticVec<Dynamic>, StaticVec<Position>)) -> Self {
|
||||
Self::MethodCallArgs(values, positions)
|
||||
fn from((values, pos): (StaticVec<Dynamic>, Position)) -> Self {
|
||||
Self::MethodCallArgs(values, pos)
|
||||
}
|
||||
}
|
||||
|
||||
@ -332,10 +332,13 @@ pub enum Target<'a> {
|
||||
/// The target is a mutable reference to a Shared `Dynamic` value.
|
||||
/// It holds both the access guard and the original shared value.
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
LockGuard((crate::dynamic::DynamicWriteLock<'a, Dynamic>, Dynamic)),
|
||||
/// The target is a temporary `Dynamic` value (i.e. the mutation can cause no side effects).
|
||||
Value(Dynamic),
|
||||
/// The target is a bit inside an [`INT`][crate::INT].
|
||||
/// This is necessary because directly pointing to a bit inside an [`INT`][crate::INT] is impossible.
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
BitField(&'a mut Dynamic, usize, Dynamic),
|
||||
/// The target is a character inside a String.
|
||||
/// This is necessary because directly pointing to a char inside a String is impossible.
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
@ -350,10 +353,11 @@ impl<'a> Target<'a> {
|
||||
match self {
|
||||
Self::Ref(_) => true,
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Self::LockGuard(_) => true,
|
||||
Self::Value(_) => false,
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Self::BitField(_, _, _) => false,
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Self::StringChar(_, _, _) => false,
|
||||
}
|
||||
}
|
||||
@ -364,10 +368,11 @@ impl<'a> Target<'a> {
|
||||
match self {
|
||||
Self::Ref(_) => false,
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Self::LockGuard(_) => false,
|
||||
Self::Value(_) => true,
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Self::BitField(_, _, _) => false,
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Self::StringChar(_, _, _) => false,
|
||||
}
|
||||
}
|
||||
@ -378,10 +383,11 @@ impl<'a> Target<'a> {
|
||||
match self {
|
||||
Self::Ref(r) => r.is_shared(),
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Self::LockGuard(_) => true,
|
||||
Self::Value(r) => r.is_shared(),
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Self::BitField(_, _, _) => false,
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Self::StringChar(_, _, _) => false,
|
||||
}
|
||||
}
|
||||
@ -392,10 +398,11 @@ impl<'a> Target<'a> {
|
||||
match self {
|
||||
Self::Ref(r) => r.is::<T>(),
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Self::LockGuard((r, _)) => r.is::<T>(),
|
||||
Self::Value(r) => r.is::<T>(),
|
||||
#[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>(),
|
||||
}
|
||||
}
|
||||
@ -405,10 +412,11 @@ impl<'a> Target<'a> {
|
||||
match self {
|
||||
Self::Ref(r) => r.clone(), // Referenced value is cloned
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Self::LockGuard((_, orig)) => orig, // Original value is simply taken
|
||||
Self::Value(v) => v, // Owned value is simply taken
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Self::BitField(_, _, value) => value, // Boolean is taken
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Self::StringChar(_, _, ch) => ch, // Character is taken
|
||||
}
|
||||
}
|
||||
@ -427,7 +435,6 @@ impl<'a> Target<'a> {
|
||||
}
|
||||
/// Propagate a changed value back to the original source.
|
||||
/// This has no effect except for string indexing.
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
#[inline(always)]
|
||||
pub fn propagate_changed_value(&mut self) -> Result<(), Box<EvalAltResult>> {
|
||||
match self {
|
||||
@ -435,9 +442,14 @@ impl<'a> Target<'a> {
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
Self::LockGuard(_) => Ok(()),
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Self::BitField(_, _, value) => {
|
||||
let new_val = value.clone();
|
||||
self.set_value(new_val, Position::NONE)
|
||||
}
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Self::StringChar(_, _, ch) => {
|
||||
let char_value = ch.clone();
|
||||
self.set_value(char_value, Position::NONE)
|
||||
let new_val = ch.clone();
|
||||
self.set_value(new_val, Position::NONE)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -450,10 +462,35 @@ impl<'a> Target<'a> {
|
||||
match self {
|
||||
Self::Ref(r) => **r = new_val,
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Self::LockGuard((r, _)) => **r = new_val,
|
||||
Self::Value(_) => panic!("cannot update a value"),
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
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, _) => {
|
||||
let s = &mut *s
|
||||
.write_lock::<ImmutableString>()
|
||||
@ -486,7 +523,6 @@ impl<'a> From<&'a mut Dynamic> for Target<'a> {
|
||||
#[inline(always)]
|
||||
fn from(value: &'a mut Dynamic) -> Self {
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
if value.is_shared() {
|
||||
// Cloning is cheap for a shared value
|
||||
let container = value.clone();
|
||||
@ -510,10 +546,11 @@ impl Deref for Target<'_> {
|
||||
match self {
|
||||
Self::Ref(r) => *r,
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Self::LockGuard((r, _)) => &**r,
|
||||
Self::Value(ref r) => r,
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Self::BitField(_, _, ref r) => r,
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Self::StringChar(_, _, ref r) => r,
|
||||
}
|
||||
}
|
||||
@ -532,10 +569,11 @@ impl DerefMut for Target<'_> {
|
||||
match self {
|
||||
Self::Ref(r) => *r,
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Self::LockGuard((r, _)) => r.deref_mut(),
|
||||
Self::Value(ref mut r) => r,
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Self::BitField(_, _, ref mut r) => r,
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Self::StringChar(_, _, ref mut r) => r,
|
||||
}
|
||||
}
|
||||
@ -787,7 +825,7 @@ pub struct Engine {
|
||||
|
||||
/// A module resolution service.
|
||||
#[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.
|
||||
pub(crate) type_names: BTreeMap<Identifier, Box<Identifier>>,
|
||||
@ -890,10 +928,10 @@ impl Engine {
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
#[cfg(not(feature = "no_std"))]
|
||||
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
|
||||
module_resolver: Box::new(crate::module::resolvers::FileModuleResolver::new()),
|
||||
module_resolver: Some(Box::new(crate::module::resolvers::FileModuleResolver::new())),
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
#[cfg(any(feature = "no_std", target_arch = "wasm32",))]
|
||||
module_resolver: Box::new(crate::module::resolvers::DummyModuleResolver::new()),
|
||||
module_resolver: None,
|
||||
|
||||
type_names: Default::default(),
|
||||
empty_string: Default::default(),
|
||||
@ -950,7 +988,7 @@ impl Engine {
|
||||
global_sub_modules: Default::default(),
|
||||
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
module_resolver: Box::new(crate::module::resolvers::DummyModuleResolver::new()),
|
||||
module_resolver: None,
|
||||
|
||||
type_names: Default::default(),
|
||||
empty_string: Default::default(),
|
||||
@ -1629,24 +1667,25 @@ impl Engine {
|
||||
match expr {
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Expr::FnCall(x, _) if _parent_chain_type == ChainType::Dot && !x.is_qualified() => {
|
||||
let mut arg_positions: StaticVec<_> = Default::default();
|
||||
|
||||
let mut arg_values = x
|
||||
let arg_values = x
|
||||
.args
|
||||
.iter()
|
||||
.inspect(|arg_expr| arg_positions.push(arg_expr.position()))
|
||||
.map(|arg_expr| {
|
||||
self.eval_expr(scope, mods, state, lib, this_ptr, arg_expr, level)
|
||||
.map(Dynamic::flatten)
|
||||
})
|
||||
.chain(x.literal_args.iter().map(|(v, _)| Ok(v.clone())))
|
||||
.collect::<Result<StaticVec<_>, _>>()?;
|
||||
|
||||
x.literal_args
|
||||
let pos = x
|
||||
.args
|
||||
.iter()
|
||||
.inspect(|(_, pos)| arg_positions.push(*pos))
|
||||
.for_each(|(v, _)| arg_values.push(v.clone()));
|
||||
.map(|arg_expr| arg_expr.position())
|
||||
.chain(x.literal_args.iter().map(|(_, pos)| *pos))
|
||||
.next()
|
||||
.unwrap_or_default();
|
||||
|
||||
idx_values.push((arg_values, arg_positions).into());
|
||||
idx_values.push((arg_values, pos).into());
|
||||
}
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Expr::FnCall(_, _) if _parent_chain_type == ChainType::Dot => {
|
||||
@ -1674,24 +1713,25 @@ impl Engine {
|
||||
Expr::FnCall(x, _)
|
||||
if _parent_chain_type == ChainType::Dot && !x.is_qualified() =>
|
||||
{
|
||||
let mut arg_positions: StaticVec<_> = Default::default();
|
||||
|
||||
let mut arg_values = x
|
||||
let arg_values = x
|
||||
.args
|
||||
.iter()
|
||||
.inspect(|arg_expr| arg_positions.push(arg_expr.position()))
|
||||
.map(|arg_expr| {
|
||||
self.eval_expr(scope, mods, state, lib, this_ptr, arg_expr, level)
|
||||
.map(Dynamic::flatten)
|
||||
})
|
||||
.chain(x.literal_args.iter().map(|(v, _)| Ok(v.clone())))
|
||||
.collect::<Result<StaticVec<_>, _>>()?;
|
||||
|
||||
x.literal_args
|
||||
let pos = x
|
||||
.args
|
||||
.iter()
|
||||
.inspect(|(_, pos)| arg_positions.push(*pos))
|
||||
.for_each(|(v, _)| arg_values.push(v.clone()));
|
||||
.map(|arg_expr| arg_expr.position())
|
||||
.chain(x.literal_args.iter().map(|(_, pos)| *pos))
|
||||
.next()
|
||||
.unwrap_or_default();
|
||||
|
||||
(arg_values, arg_positions).into()
|
||||
(arg_values, pos).into()
|
||||
}
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Expr::FnCall(_, _) if _parent_chain_type == ChainType::Dot => {
|
||||
@ -1816,6 +1856,43 @@ impl Engine {
|
||||
.unwrap_or_else(|| Target::from(Dynamic::UNIT)))
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Dynamic(Union::Int(value, _, _)) => {
|
||||
// val_int[idx]
|
||||
let index = idx
|
||||
.as_int()
|
||||
.map_err(|err| self.make_type_mismatch_err::<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"))]
|
||||
Dynamic(Union::Str(s, _, _)) => {
|
||||
// val_string[idx]
|
||||
@ -1824,7 +1901,6 @@ impl Engine {
|
||||
.map_err(|err| self.make_type_mismatch_err::<crate::INT>(err, idx_pos))?;
|
||||
|
||||
let (ch, offset) = if index >= 0 {
|
||||
// Count from end if negative
|
||||
let offset = index as usize;
|
||||
(
|
||||
s.chars().nth(offset).ok_or_else(|| {
|
||||
@ -1833,9 +1909,10 @@ impl Engine {
|
||||
})?,
|
||||
offset,
|
||||
)
|
||||
} else if let Some(index) = index.checked_abs() {
|
||||
let offset = index as usize;
|
||||
} else if let Some(abs_index) = index.checked_abs() {
|
||||
let offset = abs_index as usize;
|
||||
(
|
||||
// Count from end if negative
|
||||
s.chars().rev().nth(offset - 1).ok_or_else(|| {
|
||||
let chars_len = s.chars().count();
|
||||
EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos)
|
||||
@ -2037,11 +2114,7 @@ impl Engine {
|
||||
Expr::Unit(_) => Ok(Dynamic::UNIT),
|
||||
|
||||
Expr::Custom(custom, _) => {
|
||||
let expressions = custom
|
||||
.keywords
|
||||
.iter()
|
||||
.map(Into::into)
|
||||
.collect::<StaticVec<_>>();
|
||||
let expressions: StaticVec<_> = custom.keywords.iter().map(Into::into).collect();
|
||||
let key_token = custom.tokens.first().expect(
|
||||
"never fails because a custom syntax stream must contain at least one token",
|
||||
);
|
||||
@ -2155,8 +2228,8 @@ impl Engine {
|
||||
op_pos: Position,
|
||||
mut target: Target,
|
||||
root: (&str, Position),
|
||||
mut new_value: Dynamic,
|
||||
new_value_pos: Position,
|
||||
mut new_val: Dynamic,
|
||||
new_val_pos: Position,
|
||||
) -> Result<(), Box<EvalAltResult>> {
|
||||
if target.is_read_only() {
|
||||
// Assignment to constant variable
|
||||
@ -2168,6 +2241,7 @@ impl Engine {
|
||||
hash_op,
|
||||
op,
|
||||
}) = op_info
|
||||
{
|
||||
{
|
||||
let mut lock_guard;
|
||||
let lhs_ptr_inner;
|
||||
@ -2187,30 +2261,32 @@ impl Engine {
|
||||
}
|
||||
|
||||
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) {
|
||||
Ok(_) => (),
|
||||
Err(err) if matches!(err.as_ref(), EvalAltResult::ErrorFunctionNotFound(f, _) if f.starts_with(op)) =>
|
||||
{
|
||||
// Expand to `var = var op rhs`
|
||||
let op = &op[..op.len() - 1]; // extract operator without =
|
||||
|
||||
// Run function
|
||||
let (value, _) = self
|
||||
.call_native_fn(mods, state, lib, op, hash_op, args, true, false, op_pos)?;
|
||||
let (value, _) = self.call_native_fn(
|
||||
mods, state, lib, op, hash_op, args, true, false, op_pos,
|
||||
)?;
|
||||
|
||||
*args[0] = value.flatten();
|
||||
}
|
||||
err => return err.map(|_| ()),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
target.propagate_changed_value()?;
|
||||
} else {
|
||||
// Normal assignment
|
||||
target.set_value(new_value, new_value_pos)?;
|
||||
Ok(())
|
||||
target.set_value(new_val, new_val_pos)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Evaluate a statement.
|
||||
@ -2757,20 +2833,26 @@ impl Engine {
|
||||
use crate::ModuleResolver;
|
||||
|
||||
let source = state.source.as_ref().map(|s| s.as_str());
|
||||
let expr_pos = expr.position();
|
||||
let path_pos = expr.position();
|
||||
|
||||
let module = state
|
||||
.resolver
|
||||
.as_ref()
|
||||
.and_then(|r| match r.resolve(self, source, &path, expr_pos) {
|
||||
Ok(m) => return Some(Ok(m)),
|
||||
Err(err) => match *err {
|
||||
EvalAltResult::ErrorModuleNotFound(_, _) => None,
|
||||
_ => return Some(Err(err)),
|
||||
},
|
||||
.and_then(|r| match r.resolve(self, source, &path, path_pos) {
|
||||
Err(err)
|
||||
if matches!(*err, EvalAltResult::ErrorModuleNotFound(_, _)) =>
|
||||
{
|
||||
None
|
||||
}
|
||||
result => Some(result),
|
||||
})
|
||||
.or_else(|| {
|
||||
self.module_resolver
|
||||
.as_ref()
|
||||
.map(|r| r.resolve(self, source, &path, path_pos))
|
||||
})
|
||||
.unwrap_or_else(|| {
|
||||
self.module_resolver.resolve(self, source, &path, expr_pos)
|
||||
EvalAltResult::ErrorModuleNotFound(path.to_string(), path_pos).into()
|
||||
})?;
|
||||
|
||||
export.as_ref().map(|x| x.name.clone()).map(|name| {
|
||||
|
@ -1101,8 +1101,10 @@ impl Engine {
|
||||
});
|
||||
}
|
||||
|
||||
let mut resolver = StaticModuleResolver::new();
|
||||
let mut ast = self.compile_scripts_with_scope(scope, &[script])?;
|
||||
|
||||
if let Some(ref module_resolver) = self.module_resolver {
|
||||
let mut resolver = StaticModuleResolver::new();
|
||||
let mut imports = Default::default();
|
||||
|
||||
collect_imports(&ast, &mut resolver, &mut imports);
|
||||
@ -1111,10 +1113,7 @@ impl Engine {
|
||||
while let Some(path) = imports.iter().next() {
|
||||
let path = path.clone();
|
||||
|
||||
match self
|
||||
.module_resolver
|
||||
.resolve_ast(self, None, &path, Position::NONE)
|
||||
{
|
||||
match module_resolver.resolve_ast(self, None, &path, Position::NONE) {
|
||||
Some(Ok(module_ast)) => {
|
||||
collect_imports(&module_ast, &mut resolver, &mut imports)
|
||||
}
|
||||
@ -1122,18 +1121,15 @@ impl Engine {
|
||||
None => (),
|
||||
}
|
||||
|
||||
let module = shared_take_or_clone(self.module_resolver.resolve(
|
||||
self,
|
||||
None,
|
||||
&path,
|
||||
Position::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);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(ast)
|
||||
}
|
||||
|
@ -188,7 +188,7 @@ impl Engine {
|
||||
&mut self,
|
||||
resolver: impl crate::ModuleResolver + 'static,
|
||||
) -> &mut Self {
|
||||
self.module_resolver = Box::new(resolver);
|
||||
self.module_resolver = Some(Box::new(resolver));
|
||||
self
|
||||
}
|
||||
/// Disable a particular keyword or operator in the language.
|
||||
|
@ -515,13 +515,11 @@ impl Engine {
|
||||
);
|
||||
|
||||
// Merge in encapsulated environment, if any
|
||||
let lib_merged;
|
||||
let lib_merged: StaticVec<_>;
|
||||
|
||||
let (unified_lib, unified) = if let Some(ref env_lib) = fn_def.lib {
|
||||
state.push_fn_resolution_cache();
|
||||
lib_merged = once(env_lib.as_ref())
|
||||
.chain(lib.iter().cloned())
|
||||
.collect::<StaticVec<_>>();
|
||||
lib_merged = once(env_lib.as_ref()).chain(lib.iter().cloned()).collect();
|
||||
(lib_merged.as_ref(), true)
|
||||
} else {
|
||||
(lib, false)
|
||||
@ -895,20 +893,16 @@ impl Engine {
|
||||
fn_name: &str,
|
||||
mut hash: FnCallHashes,
|
||||
target: &mut crate::engine::Target,
|
||||
(call_args, call_arg_positions): &mut (StaticVec<Dynamic>, StaticVec<Position>),
|
||||
(call_args, call_arg_pos): &mut (StaticVec<Dynamic>, Position),
|
||||
pos: Position,
|
||||
level: usize,
|
||||
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
|
||||
let is_ref = target.is_ref();
|
||||
|
||||
// Get a reference to the mutation target Dynamic
|
||||
let obj = target.as_mut();
|
||||
let mut fn_name = fn_name;
|
||||
|
||||
let (result, updated) = match fn_name {
|
||||
KEYWORD_FN_PTR_CALL if obj.is::<FnPtr>() => {
|
||||
KEYWORD_FN_PTR_CALL if target.is::<FnPtr>() => {
|
||||
// FnPtr call
|
||||
let fn_ptr = obj
|
||||
let fn_ptr = target
|
||||
.read_lock::<FnPtr>()
|
||||
.expect("never fails because `obj` is `FnPtr`");
|
||||
// Redirect function name
|
||||
@ -917,11 +911,8 @@ impl Engine {
|
||||
// Recalculate hashes
|
||||
let new_hash = FnCallHashes::from_script(calc_fn_hash(fn_name, args_len));
|
||||
// Arguments are passed as-is, adding the curried arguments
|
||||
let mut curry = fn_ptr.curry().iter().cloned().collect::<StaticVec<_>>();
|
||||
let mut args = curry
|
||||
.iter_mut()
|
||||
.chain(call_args.iter_mut())
|
||||
.collect::<StaticVec<_>>();
|
||||
let mut curry: StaticVec<_> = fn_ptr.curry().iter().cloned().collect();
|
||||
let mut args: StaticVec<_> = curry.iter_mut().chain(call_args.iter_mut()).collect();
|
||||
|
||||
// Map it to name(args) in function-call style
|
||||
self.exec_fn_call(
|
||||
@ -932,20 +923,19 @@ impl Engine {
|
||||
if call_args.len() > 0 {
|
||||
if !call_args[0].is::<FnPtr>() {
|
||||
return Err(self.make_type_mismatch_err::<FnPtr>(
|
||||
self.map_type_name(obj.type_name()),
|
||||
call_arg_positions[0],
|
||||
self.map_type_name(target.type_name()),
|
||||
*call_arg_pos,
|
||||
));
|
||||
}
|
||||
} else {
|
||||
return Err(self.make_type_mismatch_err::<FnPtr>(
|
||||
self.map_type_name(obj.type_name()),
|
||||
self.map_type_name(target.type_name()),
|
||||
pos,
|
||||
));
|
||||
}
|
||||
|
||||
// FnPtr call on object
|
||||
let fn_ptr = call_args.remove(0).cast::<FnPtr>();
|
||||
call_arg_positions.remove(0);
|
||||
// Redirect function name
|
||||
let fn_name = fn_ptr.fn_name();
|
||||
let args_len = call_args.len() + fn_ptr.curry().len();
|
||||
@ -955,11 +945,11 @@ impl Engine {
|
||||
calc_fn_hash(fn_name, args_len + 1),
|
||||
);
|
||||
// Replace the first argument with the object pointer, adding the curried arguments
|
||||
let mut curry = fn_ptr.curry().iter().cloned().collect::<StaticVec<_>>();
|
||||
let mut args = once(obj)
|
||||
let mut curry: StaticVec<_> = fn_ptr.curry().iter().cloned().collect();
|
||||
let mut args: StaticVec<_> = once(target.as_mut())
|
||||
.chain(curry.iter_mut())
|
||||
.chain(call_args.iter_mut())
|
||||
.collect::<StaticVec<_>>();
|
||||
.collect();
|
||||
|
||||
// Map it to name(args) in function-call style
|
||||
self.exec_fn_call(
|
||||
@ -967,14 +957,14 @@ impl Engine {
|
||||
)
|
||||
}
|
||||
KEYWORD_FN_PTR_CURRY => {
|
||||
if !obj.is::<FnPtr>() {
|
||||
if !target.is::<FnPtr>() {
|
||||
return Err(self.make_type_mismatch_err::<FnPtr>(
|
||||
self.map_type_name(obj.type_name()),
|
||||
self.map_type_name(target.type_name()),
|
||||
pos,
|
||||
));
|
||||
}
|
||||
|
||||
let fn_ptr = obj
|
||||
let fn_ptr = target
|
||||
.read_lock::<FnPtr>()
|
||||
.expect("never fails because `obj` is `FnPtr`");
|
||||
|
||||
@ -1005,26 +995,21 @@ impl Engine {
|
||||
}
|
||||
|
||||
_ => {
|
||||
let mut fn_name = fn_name;
|
||||
let _redirected;
|
||||
|
||||
// Check if it is a map method call in OOP style
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
if let Some(map) = obj.read_lock::<Map>() {
|
||||
if let Some(map) = target.read_lock::<Map>() {
|
||||
if let Some(val) = map.get(fn_name) {
|
||||
if let Some(fn_ptr) = val.read_lock::<FnPtr>() {
|
||||
// Remap the function name
|
||||
_redirected = fn_ptr.get_fn_name().clone();
|
||||
fn_name = &_redirected;
|
||||
// Add curried arguments
|
||||
fn_ptr
|
||||
.curry()
|
||||
.iter()
|
||||
.cloned()
|
||||
.enumerate()
|
||||
.for_each(|(i, v)| {
|
||||
call_args.insert(i, v);
|
||||
call_arg_positions.insert(i, Position::NONE);
|
||||
});
|
||||
if fn_ptr.is_curried() {
|
||||
call_args.insert_many(0, fn_ptr.curry().iter().cloned());
|
||||
}
|
||||
// Recalculate the hash based on the new function name and new arguments
|
||||
hash = FnCallHashes::from_script_and_native(
|
||||
calc_fn_hash(fn_name, call_args.len()),
|
||||
@ -1035,9 +1020,8 @@ impl Engine {
|
||||
};
|
||||
|
||||
// Attached object pointer in front of the arguments
|
||||
let mut args = once(obj)
|
||||
.chain(call_args.iter_mut())
|
||||
.collect::<StaticVec<_>>();
|
||||
let mut args: StaticVec<_> =
|
||||
once(target.as_mut()).chain(call_args.iter_mut()).collect();
|
||||
|
||||
self.exec_fn_call(
|
||||
mods, state, lib, fn_name, hash, &mut args, is_ref, true, pos, None, level,
|
||||
@ -1416,6 +1400,7 @@ impl Engine {
|
||||
arg_values[0] = target.take_or_clone().flatten();
|
||||
args = arg_values.iter_mut().collect();
|
||||
} else {
|
||||
// Turn it into a method call only if the object is not shared and not a simple value
|
||||
let (first, rest) = arg_values
|
||||
.split_first_mut()
|
||||
.expect("never fails because the arguments list is not empty");
|
||||
|
@ -4,7 +4,7 @@
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use crate::dynamic::Variant;
|
||||
use crate::{Engine, EvalAltResult, ParseError, Scope, AST};
|
||||
use crate::{Engine, EvalAltResult, ParseError, Scope, SmartString, AST};
|
||||
#[cfg(feature = "no_std")]
|
||||
use std::prelude::v1::*;
|
||||
|
||||
@ -98,7 +98,7 @@ macro_rules! def_anonymous_fn {
|
||||
|
||||
#[inline(always)]
|
||||
fn create_from_ast(self, ast: AST, entry_point: &str) -> Self::Output {
|
||||
let fn_name = entry_point.to_string();
|
||||
let fn_name: SmartString = entry_point.into();
|
||||
Box::new(move |$($par),*| self.call_fn(&mut Scope::new(), &ast, &fn_name, ($($par,)*)))
|
||||
}
|
||||
|
||||
|
@ -314,6 +314,11 @@ impl FnPtr {
|
||||
pub fn is_curried(&self) -> bool {
|
||||
!self.1.is_empty()
|
||||
}
|
||||
/// Get the number of curried arguments.
|
||||
#[inline(always)]
|
||||
pub fn num_curried(&self) -> usize {
|
||||
self.1.len()
|
||||
}
|
||||
/// Does the function pointer refer to an anonymous function?
|
||||
///
|
||||
/// Not available under `no_function`.
|
||||
@ -339,7 +344,7 @@ impl FnPtr {
|
||||
this_ptr: Option<&mut Dynamic>,
|
||||
mut arg_values: impl AsMut<[Dynamic]>,
|
||||
) -> RhaiResult {
|
||||
let mut args_data;
|
||||
let mut args_data: StaticVec<_>;
|
||||
|
||||
let arg_values = if self.curry().is_empty() {
|
||||
arg_values.as_mut()
|
||||
@ -349,7 +354,7 @@ impl FnPtr {
|
||||
.iter()
|
||||
.cloned()
|
||||
.chain(arg_values.as_mut().iter_mut().map(mem::take))
|
||||
.collect::<StaticVec<_>>();
|
||||
.collect();
|
||||
|
||||
args_data.as_mut()
|
||||
};
|
||||
|
@ -147,7 +147,7 @@ fn call_fn_with_constant_arguments(
|
||||
state.lib,
|
||||
fn_name,
|
||||
calc_fn_hash(fn_name, arg_values.len()),
|
||||
arg_values.iter_mut().collect::<StaticVec<_>>().as_mut(),
|
||||
&mut arg_values.iter_mut().collect::<StaticVec<_>>(),
|
||||
false,
|
||||
false,
|
||||
Position::NONE,
|
||||
@ -202,7 +202,7 @@ fn optimize_stmt_block(
|
||||
match stmt {
|
||||
// Add constant literals into the state
|
||||
Stmt::Const(value_expr, x, _, _) => {
|
||||
optimize_expr(value_expr, state);
|
||||
optimize_expr(value_expr, state, false);
|
||||
|
||||
if value_expr.is_constant() {
|
||||
state.push_var(
|
||||
@ -214,7 +214,7 @@ fn optimize_stmt_block(
|
||||
}
|
||||
// Add variables into the state
|
||||
Stmt::Let(value_expr, x, _, _) => {
|
||||
optimize_expr(value_expr, state);
|
||||
optimize_expr(value_expr, state, false);
|
||||
state.push_var(&x.name, AccessMode::ReadWrite, None);
|
||||
}
|
||||
// Optimize the statement
|
||||
@ -392,10 +392,10 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) {
|
||||
|
||||
// expr op= expr
|
||||
Stmt::Assignment(x, _) => match x.0 {
|
||||
Expr::Variable(_, _, _) => optimize_expr(&mut x.2, state),
|
||||
Expr::Variable(_, _, _) => optimize_expr(&mut x.2, state, false),
|
||||
_ => {
|
||||
optimize_expr(&mut x.0, state);
|
||||
optimize_expr(&mut x.2, state);
|
||||
optimize_expr(&mut x.0, state, false);
|
||||
optimize_expr(&mut x.2, state, false);
|
||||
}
|
||||
},
|
||||
|
||||
@ -405,7 +405,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) {
|
||||
|
||||
let pos = condition.position();
|
||||
let mut expr = mem::take(condition);
|
||||
optimize_expr(&mut expr, state);
|
||||
optimize_expr(&mut expr, state, false);
|
||||
|
||||
*stmt = if preserve_result {
|
||||
// -> { expr, Noop }
|
||||
@ -440,7 +440,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) {
|
||||
}
|
||||
// if expr { if_block } else { else_block }
|
||||
Stmt::If(condition, x, _) => {
|
||||
optimize_expr(condition, state);
|
||||
optimize_expr(condition, state, false);
|
||||
let if_block = mem::take(x.0.statements()).into_vec();
|
||||
*x.0.statements() =
|
||||
optimize_stmt_block(if_block, state, preserve_result, true, false).into();
|
||||
@ -462,7 +462,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) {
|
||||
if let Some(block) = table.get_mut(&hash) {
|
||||
if let Some(mut condition) = mem::take(&mut block.0) {
|
||||
// switch const { case if condition => stmt, _ => def } => if condition { stmt } else { def }
|
||||
optimize_expr(&mut condition, state);
|
||||
optimize_expr(&mut condition, state, false);
|
||||
|
||||
let def_block = mem::take(&mut *x.1).into_vec();
|
||||
let def_stmt = optimize_stmt_block(def_block, state, true, true, false);
|
||||
@ -502,12 +502,12 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) {
|
||||
}
|
||||
// switch
|
||||
Stmt::Switch(match_expr, x, _) => {
|
||||
optimize_expr(match_expr, state);
|
||||
optimize_expr(match_expr, state, false);
|
||||
x.0.values_mut().for_each(|block| {
|
||||
let condition = mem::take(&mut block.0).map_or_else(
|
||||
|| Expr::Unit(Position::NONE),
|
||||
|mut condition| {
|
||||
optimize_expr(&mut condition, state);
|
||||
optimize_expr(&mut condition, state, false);
|
||||
condition
|
||||
},
|
||||
);
|
||||
@ -550,7 +550,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) {
|
||||
}
|
||||
// while expr { block }
|
||||
Stmt::While(condition, body, _) => {
|
||||
optimize_expr(condition, state);
|
||||
optimize_expr(condition, state, false);
|
||||
let block = mem::take(body.statements()).into_vec();
|
||||
*body.statements() = optimize_stmt_block(block, state, false, true, false).into();
|
||||
|
||||
@ -587,21 +587,21 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) {
|
||||
}
|
||||
// do { block } while|until expr
|
||||
Stmt::Do(body, condition, _, _) => {
|
||||
optimize_expr(condition, state);
|
||||
optimize_expr(condition, state, false);
|
||||
let block = mem::take(body.statements()).into_vec();
|
||||
*body.statements() = optimize_stmt_block(block, state, false, true, false).into();
|
||||
}
|
||||
// for id in expr { block }
|
||||
Stmt::For(iterable, x, _) => {
|
||||
optimize_expr(iterable, state);
|
||||
optimize_expr(iterable, state, false);
|
||||
let body = mem::take(x.1.statements()).into_vec();
|
||||
*x.1.statements() = optimize_stmt_block(body, state, false, true, false).into();
|
||||
}
|
||||
// let id = expr;
|
||||
Stmt::Let(expr, _, _, _) => optimize_expr(expr, state),
|
||||
Stmt::Let(expr, _, _, _) => optimize_expr(expr, state, false),
|
||||
// import expr as var;
|
||||
#[cfg(not(feature = "no_module"))]
|
||||
Stmt::Import(expr, _, _) => optimize_expr(expr, state),
|
||||
Stmt::Import(expr, _, _) => optimize_expr(expr, state, false),
|
||||
// { block }
|
||||
Stmt::Block(statements, pos) => {
|
||||
let statements = mem::take(statements).into_vec();
|
||||
@ -640,7 +640,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) {
|
||||
}
|
||||
// func(...)
|
||||
Stmt::Expr(expr @ Expr::FnCall(_, _)) => {
|
||||
optimize_expr(expr, state);
|
||||
optimize_expr(expr, state, false);
|
||||
match expr {
|
||||
Expr::FnCall(x, pos) => {
|
||||
state.set_dirty();
|
||||
@ -660,9 +660,9 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) {
|
||||
*stmt = mem::take(x.as_mut()).into();
|
||||
}
|
||||
// expr;
|
||||
Stmt::Expr(expr) => optimize_expr(expr, state),
|
||||
Stmt::Expr(expr) => optimize_expr(expr, state, false),
|
||||
// return expr;
|
||||
Stmt::Return(_, Some(ref mut expr), _) => optimize_expr(expr, state),
|
||||
Stmt::Return(_, Some(ref mut expr), _) => optimize_expr(expr, state, false),
|
||||
|
||||
// All other statements - skip
|
||||
_ => (),
|
||||
@ -670,7 +670,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) {
|
||||
}
|
||||
|
||||
/// Optimize an [expression][Expr].
|
||||
fn optimize_expr(expr: &mut Expr, state: &mut State) {
|
||||
fn optimize_expr(expr: &mut Expr, state: &mut State, _chaining: bool) {
|
||||
// These keywords are handled specially
|
||||
const DONT_EVAL_KEYWORDS: &[&str] = &[
|
||||
KEYWORD_PRINT, // side effects
|
||||
@ -693,7 +693,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
|
||||
}
|
||||
// lhs.rhs
|
||||
#[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
|
||||
(Expr::Map(m, pos), Expr::Property(p)) if m.0.iter().all(|(_, x)| x.is_pure()) => {
|
||||
let prop = p.2.0.as_str();
|
||||
@ -705,14 +705,17 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
|
||||
.unwrap_or_else(|| Expr::Unit(*pos));
|
||||
}
|
||||
// var.rhs
|
||||
(Expr::Variable(_, _, _), rhs) => optimize_expr(rhs, state),
|
||||
(Expr::Variable(_, _, _), rhs) => optimize_expr(rhs, state, true),
|
||||
// lhs.rhs
|
||||
(lhs, rhs) => { optimize_expr(lhs, state); optimize_expr(rhs, state); }
|
||||
(lhs, rhs) => { optimize_expr(lhs, state, false); optimize_expr(rhs, state, true); }
|
||||
}
|
||||
// ....lhs.rhs
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Expr::Dot(x, _) => { optimize_expr(&mut x.lhs, state, false); optimize_expr(&mut x.rhs, state, _chaining); }
|
||||
|
||||
// lhs[rhs]
|
||||
#[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]
|
||||
(Expr::Array(a, pos), Expr::IntegerConstant(i, _))
|
||||
if *i >= 0 && (*i as usize) < a.len() && a.iter().all(Expr::is_pure) =>
|
||||
@ -744,6 +747,18 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
|
||||
.map(|(_, mut expr)| { expr.set_position(*pos); expr })
|
||||
.unwrap_or_else(|| Expr::Unit(*pos));
|
||||
}
|
||||
// int[int]
|
||||
(Expr::IntegerConstant(n, pos), Expr::IntegerConstant(i, _)) if *i >= 0 && (*i as usize) < (std::mem::size_of_val(n) * 8) => {
|
||||
// Bit-field literal indexing - get the bit
|
||||
state.set_dirty();
|
||||
*expr = Expr::BoolConstant((*n & (1 << (*i as usize))) != 0, *pos);
|
||||
}
|
||||
// int[-int]
|
||||
(Expr::IntegerConstant(n, pos), Expr::IntegerConstant(i, _)) if *i < 0 && i.checked_abs().map(|i| i as usize <= (std::mem::size_of_val(n) * 8)).unwrap_or(false) => {
|
||||
// Bit-field literal indexing - get the bit
|
||||
state.set_dirty();
|
||||
*expr = Expr::BoolConstant((*n & (1 << (std::mem::size_of_val(n) * 8 - i.abs() as usize))) != 0, *pos);
|
||||
}
|
||||
// string[int]
|
||||
(Expr::StringConstant(s, pos), Expr::IntegerConstant(i, _)) if *i >= 0 && (*i as usize) < s.chars().count() => {
|
||||
// String literal indexing - get the character
|
||||
@ -757,10 +772,13 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
|
||||
*expr = Expr::CharConstant(s.chars().rev().nth(i.abs() as usize - 1).unwrap(), *pos);
|
||||
}
|
||||
// var[rhs]
|
||||
(Expr::Variable(_, _, _), rhs) => optimize_expr(rhs, state),
|
||||
(Expr::Variable(_, _, _), rhs) => optimize_expr(rhs, state, true),
|
||||
// lhs[rhs]
|
||||
(lhs, rhs) => { optimize_expr(lhs, state); optimize_expr(rhs, state); }
|
||||
(lhs, rhs) => { optimize_expr(lhs, state, false); optimize_expr(rhs, state, true); }
|
||||
},
|
||||
// ...[lhs][rhs]
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Expr::Index(x, _) => { optimize_expr(&mut x.lhs, state, false); optimize_expr(&mut x.rhs, state, _chaining); }
|
||||
// ``
|
||||
Expr::InterpolatedString(x) if x.is_empty() => {
|
||||
state.set_dirty();
|
||||
@ -773,7 +791,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
|
||||
}
|
||||
// `... ${ ... } ...`
|
||||
Expr::InterpolatedString(x) => {
|
||||
x.iter_mut().for_each(|expr| optimize_expr(expr, state));
|
||||
x.iter_mut().for_each(|expr| optimize_expr(expr, state, false));
|
||||
|
||||
let mut n= 0;
|
||||
|
||||
@ -824,7 +842,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
|
||||
}
|
||||
// [ items .. ]
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
Expr::Array(x, _) => x.iter_mut().for_each(|expr| optimize_expr(expr, state)),
|
||||
Expr::Array(x, _) => x.iter_mut().for_each(|expr| optimize_expr(expr, state, false)),
|
||||
// #{ key:constant, .. }
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Expr::Map(_, _) if expr.is_constant() => {
|
||||
@ -833,13 +851,13 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
|
||||
}
|
||||
// #{ key:value, .. }
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
Expr::Map(x, _) => x.0.iter_mut().for_each(|(_, expr)| optimize_expr(expr, state)),
|
||||
Expr::Map(x, _) => x.0.iter_mut().for_each(|(_, expr)| optimize_expr(expr, state, false)),
|
||||
// lhs && rhs
|
||||
Expr::And(x, _) => match (&mut x.lhs, &mut x.rhs) {
|
||||
// true && rhs -> rhs
|
||||
(Expr::BoolConstant(true, _), rhs) => {
|
||||
state.set_dirty();
|
||||
optimize_expr(rhs, state);
|
||||
optimize_expr(rhs, state, false);
|
||||
*expr = mem::take(rhs);
|
||||
}
|
||||
// false && rhs -> false
|
||||
@ -850,18 +868,18 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
|
||||
// lhs && true -> lhs
|
||||
(lhs, Expr::BoolConstant(true, _)) => {
|
||||
state.set_dirty();
|
||||
optimize_expr(lhs, state);
|
||||
optimize_expr(lhs, state, false);
|
||||
*expr = mem::take(lhs);
|
||||
}
|
||||
// lhs && rhs
|
||||
(lhs, rhs) => { optimize_expr(lhs, state); optimize_expr(rhs, state); }
|
||||
(lhs, rhs) => { optimize_expr(lhs, state, false); optimize_expr(rhs, state, false); }
|
||||
},
|
||||
// lhs || rhs
|
||||
Expr::Or(ref mut x, _) => match (&mut x.lhs, &mut x.rhs) {
|
||||
// false || rhs -> rhs
|
||||
(Expr::BoolConstant(false, _), rhs) => {
|
||||
state.set_dirty();
|
||||
optimize_expr(rhs, state);
|
||||
optimize_expr(rhs, state, false);
|
||||
*expr = mem::take(rhs);
|
||||
}
|
||||
// true || rhs -> true
|
||||
@ -872,11 +890,11 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
|
||||
// lhs || false
|
||||
(lhs, Expr::BoolConstant(false, _)) => {
|
||||
state.set_dirty();
|
||||
optimize_expr(lhs, state);
|
||||
optimize_expr(lhs, state, false);
|
||||
*expr = mem::take(lhs);
|
||||
}
|
||||
// lhs || rhs
|
||||
(lhs, rhs) => { optimize_expr(lhs, state); optimize_expr(rhs, state); }
|
||||
(lhs, rhs) => { optimize_expr(lhs, state, false); optimize_expr(rhs, state, false); }
|
||||
},
|
||||
|
||||
// eval!
|
||||
@ -899,7 +917,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
|
||||
|
||||
// Do not call some special keywords
|
||||
Expr::FnCall(x, _) if DONT_EVAL_KEYWORDS.contains(&x.name.as_ref()) => {
|
||||
x.args.iter_mut().for_each(|a| optimize_expr(a, state));
|
||||
x.args.iter_mut().for_each(|a| optimize_expr(a, state, false));
|
||||
}
|
||||
|
||||
// Call built-in operators
|
||||
@ -933,7 +951,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
|
||||
}
|
||||
}
|
||||
|
||||
x.args.iter_mut().for_each(|a| optimize_expr(a, state));
|
||||
x.args.iter_mut().for_each(|a| optimize_expr(a, state, false));
|
||||
|
||||
// Move constant arguments to the right
|
||||
while x.args.last().map(Expr::is_constant).unwrap_or(false) {
|
||||
@ -989,12 +1007,12 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
|
||||
}
|
||||
}
|
||||
|
||||
x.args.iter_mut().for_each(|a| optimize_expr(a, state));
|
||||
x.args.iter_mut().for_each(|a| optimize_expr(a, state, false));
|
||||
}
|
||||
|
||||
// id(args ..) -> optimize function call arguments
|
||||
Expr::FnCall(x, _) => {
|
||||
x.args.iter_mut().for_each(|a| optimize_expr(a, state));
|
||||
x.args.iter_mut().for_each(|a| optimize_expr(a, state, false));
|
||||
|
||||
// Move constant arguments to the right
|
||||
while x.args.last().map(Expr::is_constant).unwrap_or(false) {
|
||||
@ -1021,7 +1039,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) {
|
||||
if x.scope_changed {
|
||||
state.propagate_constants = false;
|
||||
}
|
||||
x.keywords.iter_mut().for_each(|expr| optimize_expr(expr, state));
|
||||
x.keywords.iter_mut().for_each(|expr| optimize_expr(expr, state, false));
|
||||
}
|
||||
|
||||
// All other expressions - skip
|
||||
|
@ -745,7 +745,7 @@ mod array_functions {
|
||||
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
|
||||
|
@ -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 {
|
||||
($lib:ident | $x:expr => $( $y:ty ),*) => {
|
||||
$(
|
||||
@ -304,4 +369,18 @@ def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, {
|
||||
#[cfg(feature = "metadata")]
|
||||
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>"]);
|
||||
});
|
||||
|
@ -1,7 +1,7 @@
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use crate::def_package;
|
||||
use crate::plugin::*;
|
||||
use crate::{def_package, EvalAltResult, INT};
|
||||
#[cfg(feature = "no_std")]
|
||||
use std::prelude::v1::*;
|
||||
|
||||
@ -59,6 +59,8 @@ def_package!(crate:LogicPackage:"Logical operators.", lib, {
|
||||
}
|
||||
|
||||
set_exported_fn!(lib, "!", not);
|
||||
|
||||
combine_with_exported_module!(lib, "bit_field", bit_field_functions);
|
||||
});
|
||||
|
||||
// Logic operators
|
||||
@ -87,8 +89,6 @@ gen_cmp_functions!(float => f64);
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
#[export_module]
|
||||
mod f32_functions {
|
||||
use crate::INT;
|
||||
|
||||
#[rhai_fn(name = "==")]
|
||||
pub fn eq_if(x: INT, y: f32) -> bool {
|
||||
(x as f32) == (y as f32)
|
||||
@ -142,8 +142,6 @@ mod f32_functions {
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
#[export_module]
|
||||
mod f64_functions {
|
||||
use crate::INT;
|
||||
|
||||
#[rhai_fn(name = "==")]
|
||||
pub fn eq_if(x: INT, y: f64) -> bool {
|
||||
(x as f64) == (y as f64)
|
||||
@ -193,3 +191,159 @@ mod f64_functions {
|
||||
(x as f64) <= (y as f64)
|
||||
}
|
||||
}
|
||||
|
||||
#[export_module]
|
||||
mod bit_field_functions {
|
||||
const BITS: usize = std::mem::size_of::<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(())
|
||||
}
|
||||
}
|
||||
|
@ -110,7 +110,7 @@ mod string_functions {
|
||||
pub fn index_of_char_starting_from(string: &str, character: char, start: INT) -> INT {
|
||||
let start = if start < 0 {
|
||||
if let Some(n) = start.checked_abs() {
|
||||
let chars = string.chars().collect::<Vec<_>>();
|
||||
let chars: Vec<_> = string.chars().collect();
|
||||
let num_chars = chars.len();
|
||||
if n as usize > num_chars {
|
||||
0
|
||||
|
@ -15,7 +15,7 @@ use crate::token::{
|
||||
};
|
||||
use crate::utils::{get_hasher, IdentifierBuilder};
|
||||
use crate::{
|
||||
calc_fn_hash, calc_qualified_fn_hash, Dynamic, Engine, FnPtr, Identifier, LexError, ParseError,
|
||||
calc_fn_hash, calc_qualified_fn_hash, Dynamic, Engine, Identifier, LexError, ParseError,
|
||||
ParseErrorType, Position, Scope, Shared, StaticVec, AST,
|
||||
};
|
||||
#[cfg(feature = "no_std")]
|
||||
@ -455,7 +455,10 @@ fn parse_index_chain(
|
||||
// Check type of indexing - must be integer or string
|
||||
match &idx_expr {
|
||||
Expr::IntegerConstant(_, pos) => match lhs {
|
||||
Expr::Array(_, _) | Expr::StringConstant(_, _) | Expr::InterpolatedString(_) => (),
|
||||
Expr::IntegerConstant(_, _)
|
||||
| Expr::Array(_, _)
|
||||
| Expr::StringConstant(_, _)
|
||||
| Expr::InterpolatedString(_) => (),
|
||||
|
||||
Expr::Map(_, _) => {
|
||||
return Err(PERR::MalformedIndexExpr(
|
||||
@ -1864,7 +1867,7 @@ fn parse_custom_syntax(
|
||||
state.stack.push((empty, AccessMode::ReadWrite));
|
||||
}
|
||||
|
||||
let parse_func = &syntax.parse;
|
||||
let parse_func = syntax.parse.as_ref();
|
||||
|
||||
segments.push(key.into());
|
||||
tokens.push(key.into());
|
||||
@ -3014,7 +3017,7 @@ fn parse_anon_fn(
|
||||
comments: Default::default(),
|
||||
};
|
||||
|
||||
let fn_ptr = FnPtr::new_unchecked(fn_name.into(), Default::default());
|
||||
let fn_ptr = crate::FnPtr::new_unchecked(fn_name.into(), Default::default());
|
||||
let expr = Expr::DynamicConstant(Box::new(fn_ptr.into()), settings.pos);
|
||||
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
|
@ -25,7 +25,4 @@ pub trait PluginFunction {
|
||||
|
||||
/// Is this plugin function a method?
|
||||
fn is_method_call(&self) -> bool;
|
||||
|
||||
/// Is this plugin function variadic?
|
||||
fn is_variadic(&self) -> bool;
|
||||
}
|
||||
|
@ -56,6 +56,9 @@ pub enum EvalAltResult {
|
||||
/// String indexing out-of-bounds.
|
||||
/// Wrapped values are the current number of characters in the string and the index number.
|
||||
ErrorStringBounds(usize, INT, Position),
|
||||
/// Bit-field indexing out-of-bounds.
|
||||
/// Wrapped values are the current number of bits in the bit-field and the index number.
|
||||
ErrorBitFieldBounds(usize, INT, Position),
|
||||
/// Trying to index into a type that is not an array, an object map, or a string, and has no
|
||||
/// indexer function defined. Wrapped value is the type name.
|
||||
ErrorIndexingType(String, Position),
|
||||
@ -109,6 +112,7 @@ impl EvalAltResult {
|
||||
Self::ErrorArrayBounds(_, _, _) => "Array index out of bounds",
|
||||
Self::ErrorStringBounds(0, _, _) => "Empty string has nothing to index",
|
||||
Self::ErrorStringBounds(_, _, _) => "String index out of bounds",
|
||||
Self::ErrorBitFieldBounds(_, _, _) => "Bit-field index out of bounds",
|
||||
Self::ErrorFor(_) => "For loop expects an array, object map, or range",
|
||||
Self::ErrorVariableNotFound(_, _) => "Variable not found",
|
||||
Self::ErrorModuleNotFound(_, _) => "Module not found",
|
||||
@ -233,6 +237,11 @@ impl fmt::Display for EvalAltResult {
|
||||
"String index {} out of bounds: only {} characters in the string",
|
||||
index, max
|
||||
)?,
|
||||
Self::ErrorBitFieldBounds(max, index, _) => write!(
|
||||
f,
|
||||
"Bit-field index {} out of bounds: only {} bits in the bit-field",
|
||||
index, max
|
||||
)?,
|
||||
Self::ErrorDataTooLarge(typ, _) => write!(f, "{} exceeds maximum limit", typ)?,
|
||||
}
|
||||
|
||||
@ -289,6 +298,7 @@ impl EvalAltResult {
|
||||
| Self::ErrorMismatchDataType(_, _, _)
|
||||
| Self::ErrorArrayBounds(_, _, _)
|
||||
| Self::ErrorStringBounds(_, _, _)
|
||||
| Self::ErrorBitFieldBounds(_, _, _)
|
||||
| Self::ErrorIndexingType(_, _)
|
||||
| Self::ErrorFor(_)
|
||||
| Self::ErrorVariableNotFound(_, _)
|
||||
@ -372,7 +382,9 @@ impl EvalAltResult {
|
||||
map.insert("requested".into(), r.into());
|
||||
map.insert("actual".into(), a.into());
|
||||
}
|
||||
Self::ErrorArrayBounds(n, i, _) | Self::ErrorStringBounds(n, i, _) => {
|
||||
Self::ErrorArrayBounds(n, i, _)
|
||||
| Self::ErrorStringBounds(n, i, _)
|
||||
| Self::ErrorBitFieldBounds(n, i, _) => {
|
||||
map.insert("length".into(), (*n as INT).into());
|
||||
map.insert("index".into(), (*i as INT).into());
|
||||
}
|
||||
@ -412,6 +424,7 @@ impl EvalAltResult {
|
||||
| Self::ErrorMismatchDataType(_, _, pos)
|
||||
| Self::ErrorArrayBounds(_, _, pos)
|
||||
| Self::ErrorStringBounds(_, _, pos)
|
||||
| Self::ErrorBitFieldBounds(_, _, pos)
|
||||
| Self::ErrorIndexingType(_, pos)
|
||||
| Self::ErrorFor(pos)
|
||||
| Self::ErrorVariableNotFound(_, pos)
|
||||
@ -452,6 +465,7 @@ impl EvalAltResult {
|
||||
| Self::ErrorMismatchDataType(_, _, pos)
|
||||
| Self::ErrorArrayBounds(_, _, pos)
|
||||
| Self::ErrorStringBounds(_, _, pos)
|
||||
| Self::ErrorBitFieldBounds(_, _, pos)
|
||||
| Self::ErrorIndexingType(_, pos)
|
||||
| Self::ErrorFor(pos)
|
||||
| Self::ErrorVariableNotFound(_, pos)
|
||||
|
@ -13,3 +13,38 @@ fn test_right_shift() -> Result<(), Box<EvalAltResult>> {
|
||||
assert_eq!(engine.eval::<INT>("9 >> 1")?, 4);
|
||||
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(())
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user