Move most packages to modules.

This commit is contained in:
Stephen Chung 2020-08-22 22:26:49 +08:00
parent 5d6fdba24d
commit 211ce54973
6 changed files with 511 additions and 510 deletions

View File

@ -17,7 +17,6 @@ keywords = [ "scripting" ]
categories = [ "no-std", "embedded", "wasm", "parser-implementations" ] categories = [ "no-std", "embedded", "wasm", "parser-implementations" ]
[dependencies] [dependencies]
num-traits = { version = "0.2.11", default-features = false }
smallvec = { version = "1.4.1", default-features = false } smallvec = { version = "1.4.1", default-features = false }
rhai_codegen = { version = "0.1", path = "codegen" } rhai_codegen = { version = "0.1", path = "codegen" }
@ -39,7 +38,7 @@ internals = [] # expose internal data structures
unicode-xid-ident = ["unicode-xid"] # allow Unicode Standard Annex #31 for identifiers. unicode-xid-ident = ["unicode-xid"] # allow Unicode Standard Annex #31 for identifiers.
# compiling for no-std # compiling for no-std
no_std = [ "no_closure", "num-traits/libm", "hashbrown", "core-error", "libm", "ahash" ] no_std = [ "no_closure", "hashbrown", "core-error", "libm", "ahash" ]
[profile.release] [profile.release]
lto = "fat" lto = "fat"

View File

@ -1120,7 +1120,7 @@ pub fn run_builtin_binary_op(
x: &Dynamic, x: &Dynamic,
y: &Dynamic, y: &Dynamic,
) -> Result<Option<Dynamic>, Box<EvalAltResult>> { ) -> Result<Option<Dynamic>, Box<EvalAltResult>> {
use crate::packages::arithmetic::*; use crate::packages::arithmetic::arith_basic::INT::functions::*;
let args_type = x.type_id(); let args_type = x.type_id();
@ -1134,14 +1134,14 @@ pub fn run_builtin_binary_op(
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
match op { match op {
"+" => return add(x, y).map(Into::into).map(Some), "+" => return add(x, y).map(Some),
"-" => return sub(x, y).map(Into::into).map(Some), "-" => return subtract(x, y).map(Some),
"*" => return mul(x, y).map(Into::into).map(Some), "*" => return multiply(x, y).map(Some),
"/" => return div(x, y).map(Into::into).map(Some), "/" => return divide(x, y).map(Some),
"%" => return modulo(x, y).map(Into::into).map(Some), "%" => return modulo(x, y).map(Some),
"~" => return pow_i_i(x, y).map(Into::into).map(Some), "~" => return power(x, y).map(Some),
">>" => return shr(x, y).map(Into::into).map(Some), ">>" => return shift_right(x, y).map(Some),
"<<" => return shl(x, y).map(Into::into).map(Some), "<<" => return shift_left(x, y).map(Some),
_ => (), _ => (),
} }
} else { } else {
@ -1151,9 +1151,9 @@ pub fn run_builtin_binary_op(
"*" => return Ok(Some((x * y).into())), "*" => return Ok(Some((x * y).into())),
"/" => return Ok(Some((x / y).into())), "/" => return Ok(Some((x / y).into())),
"%" => return Ok(Some((x % y).into())), "%" => return Ok(Some((x % y).into())),
"~" => return pow_i_i_u(x, y).map(Into::into).map(Some), "~" => return Ok(Some(x.pow(y as u32).into())),
">>" => return shr_u(x, y).map(Into::into).map(Some), ">>" => return Ok(Some((x >> y).into())),
"<<" => return shl_u(x, y).map(Into::into).map(Some), "<<" => return Ok(Some((x << y).into())),
_ => (), _ => (),
} }
} }
@ -1228,7 +1228,7 @@ pub fn run_builtin_binary_op(
"*" => return Ok(Some((x * y).into())), "*" => return Ok(Some((x * y).into())),
"/" => return Ok(Some((x / y).into())), "/" => return Ok(Some((x / y).into())),
"%" => return Ok(Some((x % y).into())), "%" => return Ok(Some((x % y).into())),
"~" => return pow_f_f(x, y).map(Into::into).map(Some), "~" => return Ok(Some(x.powf(y).into())),
"==" => return Ok(Some((x == y).into())), "==" => return Ok(Some((x == y).into())),
"!=" => return Ok(Some((x != y).into())), "!=" => return Ok(Some((x != y).into())),
">" => return Ok(Some((x > y).into())), ">" => return Ok(Some((x > y).into())),
@ -1248,7 +1248,7 @@ pub fn run_builtin_op_assignment(
x: &mut Dynamic, x: &mut Dynamic,
y: &Dynamic, y: &Dynamic,
) -> Result<Option<()>, Box<EvalAltResult>> { ) -> Result<Option<()>, Box<EvalAltResult>> {
use crate::packages::arithmetic::*; use crate::packages::arithmetic::arith_basic::INT::functions::*;
let args_type = x.type_id(); let args_type = x.type_id();
@ -1262,14 +1262,14 @@ pub fn run_builtin_op_assignment(
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
match op { match op {
"+=" => return Ok(Some(*x = add(*x, y)?)), "+=" => return Ok(Some(*x = add(*x, y)?.as_int().unwrap())),
"-=" => return Ok(Some(*x = sub(*x, y)?)), "-=" => return Ok(Some(*x = subtract(*x, y)?.as_int().unwrap())),
"*=" => return Ok(Some(*x = mul(*x, y)?)), "*=" => return Ok(Some(*x = multiply(*x, y)?.as_int().unwrap())),
"/=" => return Ok(Some(*x = div(*x, y)?)), "/=" => return Ok(Some(*x = divide(*x, y)?.as_int().unwrap())),
"%=" => return Ok(Some(*x = modulo(*x, y)?)), "%=" => return Ok(Some(*x = modulo(*x, y)?.as_int().unwrap())),
"~=" => return Ok(Some(*x = pow_i_i(*x, y)?)), "~=" => return Ok(Some(*x = power(*x, y)?.as_int().unwrap())),
">>=" => return Ok(Some(*x = shr(*x, y)?)), ">>=" => return Ok(Some(*x = shift_right(*x, y)?.as_int().unwrap())),
"<<=" => return Ok(Some(*x = shl(*x, y)?)), "<<=" => return Ok(Some(*x = shift_left(*x, y)?.as_int().unwrap())),
_ => (), _ => (),
} }
} else { } else {
@ -1279,9 +1279,9 @@ pub fn run_builtin_op_assignment(
"*=" => return Ok(Some(*x *= y)), "*=" => return Ok(Some(*x *= y)),
"/=" => return Ok(Some(*x /= y)), "/=" => return Ok(Some(*x /= y)),
"%=" => return Ok(Some(*x %= y)), "%=" => return Ok(Some(*x %= y)),
"~=" => return Ok(Some(*x = pow_i_i_u(*x, y)?)), "~=" => return Ok(Some(*x = x.pow(y as u32))),
">>=" => return Ok(Some(*x = shr_u(*x, y)?)), ">>=" => return Ok(Some(*x = *x << y)),
"<<=" => return Ok(Some(*x = shl_u(*x, y)?)), "<<=" => return Ok(Some(*x = *x << y)),
_ => (), _ => (),
} }
} }
@ -1322,7 +1322,7 @@ pub fn run_builtin_op_assignment(
"*=" => return Ok(Some(*x *= y)), "*=" => return Ok(Some(*x *= y)),
"/=" => return Ok(Some(*x /= y)), "/=" => return Ok(Some(*x /= y)),
"%=" => return Ok(Some(*x %= y)), "%=" => return Ok(Some(*x %= y)),
"~=" => return Ok(Some(*x = pow_f_f(*x, y)?)), "~=" => return Ok(Some(*x = x.powf(y))),
_ => (), _ => (),
} }
} }

View File

@ -1,419 +1,404 @@
#![allow(non_snake_case)]
use crate::def_package; use crate::def_package;
use crate::module::FuncReturn;
use crate::parser::INT; use crate::parser::INT;
use crate::plugin::*;
use crate::{result::EvalAltResult, token::Position}; use crate::{result::EvalAltResult, token::Position};
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
use crate::parser::FLOAT; use crate::parser::FLOAT;
use num_traits::{
identities::Zero, CheckedAdd, CheckedDiv, CheckedMul, CheckedNeg, CheckedRem, CheckedShl,
CheckedShr, CheckedSub,
};
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
use num_traits::float::Float; use num_traits::float::Float;
use crate::stdlib::{ use crate::stdlib::format;
fmt::Display,
format,
ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Rem, Shl, Shr, Sub},
};
// Checked add macro_rules! gen_arithmetic_functions {
pub fn add<T: Display + CheckedAdd>(x: T, y: T) -> FuncReturn<T> { ($root:ident => $($arg_type:ident),+) => {
x.checked_add(&y).ok_or_else(|| { pub mod $root { $(
EvalAltResult::ErrorArithmetic( pub mod $arg_type {
format!("Addition overflow: {} + {}", x, y), use super::super::*;
Position::none(),
)
.into()
})
}
// Checked subtract
pub fn sub<T: Display + CheckedSub>(x: T, y: T) -> FuncReturn<T> {
x.checked_sub(&y).ok_or_else(|| {
EvalAltResult::ErrorArithmetic(
format!("Subtraction underflow: {} - {}", x, y),
Position::none(),
)
.into()
})
}
// Checked multiply
pub fn mul<T: Display + CheckedMul>(x: T, y: T) -> FuncReturn<T> {
x.checked_mul(&y).ok_or_else(|| {
EvalAltResult::ErrorArithmetic(
format!("Multiplication overflow: {} * {}", x, y),
Position::none(),
)
.into()
})
}
// Checked divide
pub fn div<T>(x: T, y: T) -> FuncReturn<T>
where
T: Display + CheckedDiv + PartialEq + Zero,
{
// Detect division by zero
if y == T::zero() {
return EvalAltResult::ErrorArithmetic(
format!("Division by zero: {} / {}", x, y),
Position::none(),
)
.into();
}
x.checked_div(&y).ok_or_else(|| { #[export_module]
EvalAltResult::ErrorArithmetic( pub mod functions {
format!("Division overflow: {} / {}", x, y), #[rhai_fn(name = "+", return_raw)]
Position::none(), #[inline]
) pub fn add(x: $arg_type, y: $arg_type) -> Result<Dynamic, Box<EvalAltResult>> {
.into() if cfg!(not(feature = "unchecked")) {
}) x.checked_add(y).ok_or_else(|| {
} EvalAltResult::ErrorArithmetic(
// Checked negative - e.g. -(i32::MIN) will overflow i32::MAX format!("Addition overflow: {} + {}", x, y),
pub fn neg<T: Display + CheckedNeg>(x: T) -> FuncReturn<T> { Position::none(),
x.checked_neg().ok_or_else(|| { )
EvalAltResult::ErrorArithmetic(format!("Negation overflow: -{}", x), Position::none()) .into()
.into() }).map(Dynamic::from)
}) } else {
} Ok(Dynamic::from(x + y))
// Checked absolute }
pub fn abs<T: Display + CheckedNeg + PartialOrd + Zero>(x: T) -> FuncReturn<T> { }
// FIX - We don't use Signed::abs() here because, contrary to documentation, it panics #[rhai_fn(name = "-", return_raw)]
// when the number is ::MIN instead of returning ::MIN itself. #[inline]
if x >= <T as Zero>::zero() { pub fn subtract(x: $arg_type, y: $arg_type) -> Result<Dynamic, Box<EvalAltResult>> {
Ok(x) if cfg!(not(feature = "unchecked")) {
} else { x.checked_sub(y).ok_or_else(|| {
x.checked_neg().ok_or_else(|| { EvalAltResult::ErrorArithmetic(
EvalAltResult::ErrorArithmetic(format!("Negation overflow: -{}", x), Position::none()) format!("Subtraction overflow: {} - {}", x, y),
.into() Position::none(),
}) )
} .into()
} }).map(Dynamic::from)
// Unchecked add - may panic on overflow } else {
fn add_u<T: Add>(x: T, y: T) -> FuncReturn<<T as Add>::Output> { Ok(Dynamic::from(x - y))
Ok(x + y) }
} }
// Unchecked subtract - may panic on underflow #[rhai_fn(name = "*", return_raw)]
fn sub_u<T: Sub>(x: T, y: T) -> FuncReturn<<T as Sub>::Output> { #[inline]
Ok(x - y) pub fn multiply(x: $arg_type, y: $arg_type) -> Result<Dynamic, Box<EvalAltResult>> {
} if cfg!(not(feature = "unchecked")) {
// Unchecked multiply - may panic on overflow x.checked_mul(y).ok_or_else(|| {
fn mul_u<T: Mul>(x: T, y: T) -> FuncReturn<<T as Mul>::Output> { EvalAltResult::ErrorArithmetic(
Ok(x * y) format!("Multiplication overflow: {} * {}", x, y),
} Position::none(),
// Unchecked divide - may panic when dividing by zero )
fn div_u<T: Div>(x: T, y: T) -> FuncReturn<<T as Div>::Output> { .into()
Ok(x / y) }).map(Dynamic::from)
} } else {
// Unchecked negative - may panic on overflow Ok(Dynamic::from(x * y))
fn neg_u<T: Neg>(x: T) -> FuncReturn<<T as Neg>::Output> { }
Ok(-x) }
} #[rhai_fn(name = "/", return_raw)]
// Unchecked absolute - may panic on overflow #[inline]
fn abs_u<T>(x: T) -> FuncReturn<<T as Neg>::Output> pub fn divide(x: $arg_type, y: $arg_type) -> Result<Dynamic, Box<EvalAltResult>> {
where if cfg!(not(feature = "unchecked")) {
T: Neg + PartialOrd + Default + Into<<T as Neg>::Output>, // Detect division by zero
{ if y == 0 {
// Numbers should default to zero EvalAltResult::ErrorArithmetic(
if x < Default::default() { format!("Division by zero: {} / {}", x, y),
Ok(-x) Position::none(),
} else { )
Ok(x.into()) .into()
} } else {
} x.checked_div(y).ok_or_else(|| {
// Bit operators EvalAltResult::ErrorArithmetic(
fn binary_and<T: BitAnd>(x: T, y: T) -> FuncReturn<<T as BitAnd>::Output> { format!("Division overflow: {} / {}", x, y),
Ok(x & y) Position::none(),
} )
fn binary_or<T: BitOr>(x: T, y: T) -> FuncReturn<<T as BitOr>::Output> { .into()
Ok(x | y) }).map(Dynamic::from)
} }
fn binary_xor<T: BitXor>(x: T, y: T) -> FuncReturn<<T as BitXor>::Output> { } else {
Ok(x ^ y) Ok(Dynamic::from(x / y))
} }
// Checked left-shift }
pub fn shl<T: Display + CheckedShl>(x: T, y: INT) -> FuncReturn<T> { #[rhai_fn(name = "%", return_raw)]
// Cannot shift by a negative number of bits #[inline]
if y < 0 { pub fn modulo(x: $arg_type, y: $arg_type) -> Result<Dynamic, Box<EvalAltResult>> {
return EvalAltResult::ErrorArithmetic( if cfg!(not(feature = "unchecked")) {
format!("Left-shift by a negative number: {} << {}", x, y), x.checked_rem(y).ok_or_else(|| {
Position::none(), EvalAltResult::ErrorArithmetic(
) format!("Modulo division by zero or overflow: {} % {}", x, y),
.into(); Position::none(),
} )
.into()
}).map(Dynamic::from)
} else {
Ok(Dynamic::from(x % y))
}
}
#[rhai_fn(name = "~", return_raw)]
#[inline]
pub fn power(x: INT, y: INT) -> Result<Dynamic, Box<EvalAltResult>> {
if cfg!(not(feature = "unchecked")) {
if cfg!(not(feature = "only_i32")) && y > (u32::MAX as INT) {
EvalAltResult::ErrorArithmetic(
format!("Integer raised to too large an index: {} ~ {}", x, y),
Position::none(),
)
.into()
} else if y < 0 {
EvalAltResult::ErrorArithmetic(
format!("Integer raised to a negative index: {} ~ {}", x, y),
Position::none(),
)
.into()
} else {
x.checked_pow(y as u32).ok_or_else(|| {
EvalAltResult::ErrorArithmetic(
format!("Power overflow: {} ~ {}", x, y),
Position::none(),
)
.into()
}).map(Dynamic::from)
}
} else {
Ok(Dynamic::from(x.pow(y as u32)))
}
}
CheckedShl::checked_shl(&x, y as u32).ok_or_else(|| { #[rhai_fn(name = "<<", return_raw)]
EvalAltResult::ErrorArithmetic( #[inline]
format!("Left-shift by too many bits: {} << {}", x, y), pub fn shift_left(x: $arg_type, y: INT) -> Result<Dynamic, Box<EvalAltResult>> {
Position::none(), if cfg!(not(feature = "unchecked")) {
) if cfg!(not(feature = "only_i32")) && y > (u32::MAX as INT) {
.into() EvalAltResult::ErrorArithmetic(
}) format!("Left-shift by too many bits: {} << {}", x, y),
} Position::none(),
// Checked right-shift )
pub fn shr<T: Display + CheckedShr>(x: T, y: INT) -> FuncReturn<T> { .into()
// Cannot shift by a negative number of bits } else if y < 0 {
if y < 0 { EvalAltResult::ErrorArithmetic(
return EvalAltResult::ErrorArithmetic( format!("Left-shift by a negative number: {} << {}", x, y),
format!("Right-shift by a negative number: {} >> {}", x, y), Position::none(),
Position::none(), )
) .into()
.into(); } else {
x.checked_shl(y as u32).ok_or_else(|| {
EvalAltResult::ErrorArithmetic(
format!("Left-shift by too many bits: {} << {}", x, y),
Position::none(),
)
.into()
}).map(Dynamic::from)
}
} else {
Ok(Dynamic::from(x << y))
}
}
#[rhai_fn(name = ">>", return_raw)]
#[inline]
pub fn shift_right(x: $arg_type, y: INT) -> Result<Dynamic, Box<EvalAltResult>> {
if cfg!(not(feature = "unchecked")) {
if cfg!(not(feature = "only_i32")) && y > (u32::MAX as INT) {
EvalAltResult::ErrorArithmetic(
format!("Right-shift by too many bits: {} >> {}", x, y),
Position::none(),
)
.into()
} else if y < 0 {
EvalAltResult::ErrorArithmetic(
format!("Right-shift by a negative number: {} >> {}", x, y),
Position::none(),
)
.into()
} else {
x.checked_shr(y as u32).ok_or_else(|| {
EvalAltResult::ErrorArithmetic(
format!("Right-shift by too many bits: {} >> {}", x, y),
Position::none(),
)
.into()
}).map(Dynamic::from)
}
} else {
Ok(Dynamic::from(x >> y))
}
}
#[rhai_fn(name = "&")]
#[inline(always)]
fn binary_and(x: $arg_type, y: $arg_type) -> $arg_type {
x & y
}
#[rhai_fn(name = "|")]
#[inline(always)]
fn binary_or(x: $arg_type, y: $arg_type) -> $arg_type {
x | y
}
#[rhai_fn(name = "^")]
#[inline(always)]
fn binary_xor(x: $arg_type, y: $arg_type) -> $arg_type {
x ^ y
}
}
}
)* }
} }
CheckedShr::checked_shr(&x, y as u32).ok_or_else(|| {
EvalAltResult::ErrorArithmetic(
format!("Right-shift by too many bits: {} % {}", x, y),
Position::none(),
)
.into()
})
}
// Unchecked left-shift - may panic if shifting by a negative number of bits
pub fn shl_u<T: Shl<T>>(x: T, y: T) -> FuncReturn<<T as Shl<T>>::Output> {
Ok(x.shl(y))
}
// Unchecked right-shift - may panic if shifting by a negative number of bits
pub fn shr_u<T: Shr<T>>(x: T, y: T) -> FuncReturn<<T as Shr<T>>::Output> {
Ok(x.shr(y))
}
// Checked modulo
pub fn modulo<T: Display + CheckedRem>(x: T, y: T) -> FuncReturn<T> {
x.checked_rem(&y).ok_or_else(|| {
EvalAltResult::ErrorArithmetic(
format!("Modulo division by zero or overflow: {} % {}", x, y),
Position::none(),
)
.into()
})
}
// Unchecked modulo - may panic if dividing by zero
fn modulo_u<T: Rem>(x: T, y: T) -> FuncReturn<<T as Rem>::Output> {
Ok(x % y)
}
// Checked power
pub fn pow_i_i(x: INT, y: INT) -> FuncReturn<INT> {
if cfg!(not(feature = "only_i32")) {
if y > (u32::MAX as INT) {
EvalAltResult::ErrorArithmetic(
format!("Integer raised to too large an index: {} ~ {}", x, y),
Position::none(),
)
.into()
} else if y < 0 {
EvalAltResult::ErrorArithmetic(
format!("Integer raised to a negative index: {} ~ {}", x, y),
Position::none(),
)
.into()
} else {
x.checked_pow(y as u32).ok_or_else(|| {
EvalAltResult::ErrorArithmetic(
format!("Power overflow: {} ~ {}", x, y),
Position::none(),
)
.into()
})
}
} else {
if y < 0 {
EvalAltResult::ErrorArithmetic(
format!("Integer raised to a negative index: {} ~ {}", x, y),
Position::none(),
)
.into()
} else {
x.checked_pow(y as u32).ok_or_else(|| {
EvalAltResult::ErrorArithmetic(
format!("Power overflow: {} ~ {}", x, y),
Position::none(),
)
.into()
})
}
}
}
// Unchecked integer power - may panic on overflow or if the power index is too high (> u32::MAX)
pub fn pow_i_i_u(x: INT, y: INT) -> FuncReturn<INT> {
Ok(x.pow(y as u32))
}
// Floating-point power - always well-defined
#[cfg(not(feature = "no_float"))]
pub fn pow_f_f(x: FLOAT, y: FLOAT) -> FuncReturn<FLOAT> {
Ok(x.powf(y))
}
// Checked power
#[cfg(not(feature = "no_float"))]
pub fn pow_f_i(x: FLOAT, y: INT) -> FuncReturn<FLOAT> {
// Raise to power that is larger than an i32
if y > (i32::MAX as INT) {
return EvalAltResult::ErrorArithmetic(
format!("Number raised to too large an index: {} ~ {}", x, y),
Position::none(),
)
.into();
}
Ok(x.powi(y as i32))
}
// Unchecked power - may be incorrect if the power index is too high (> i32::MAX)
#[cfg(not(feature = "no_float"))]
pub fn pow_f_i_u(x: FLOAT, y: INT) -> FuncReturn<FLOAT> {
Ok(x.powi(y as i32))
} }
macro_rules! reg_unary { macro_rules! gen_signed_functions {
($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { ($root:ident => $($arg_type:ident),+) => {
$( $lib.set_fn_1($op, $func::<$par>); )* pub mod $root { $(
}; pub mod $arg_type {
use super::super::*;
#[export_module]
pub mod functions {
#[rhai_fn(name = "-", return_raw)]
#[inline]
pub fn neg(x: $arg_type) -> Result<Dynamic, Box<EvalAltResult>> {
if cfg!(not(feature = "unchecked")) {
x.checked_neg().ok_or_else(|| {
EvalAltResult::ErrorArithmetic(format!("Negation overflow: -{}", x), Position::none())
.into()
}).map(Dynamic::from)
} else {
Ok(Dynamic::from(-x))
}
}
#[rhai_fn(return_raw)]
#[inline]
pub fn abs(x: $arg_type) -> Result<Dynamic, Box<EvalAltResult>> {
if cfg!(not(feature = "unchecked")) {
x.checked_abs().ok_or_else(|| {
EvalAltResult::ErrorArithmetic(format!("Negation overflow: -{}", x), Position::none())
.into()
}).map(Dynamic::from)
} else {
Ok(Dynamic::from(x.abs()))
}
}
#[inline]
pub fn sign(x: $arg_type) -> INT {
if x == 0 {
0
} else if x < 0 {
-1
} else {
1
}
}
}
}
)* }
}
} }
macro_rules! reg_op {
($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { macro_rules! reg_functions {
$( $lib.set_fn_2($op, $func::<$par>); )* ($mod_name:ident += $root:ident ; $($arg_type:ident),+ ) => {
}; $($mod_name.combine_flatten(exported_module!($root::$arg_type::functions));)*
} }
macro_rules! reg_sign {
($lib:expr, $op:expr, $ret:ty, $($par:ty),*) => {
$( $lib.set_fn_1($op, |value: $par| -> Result<$ret, _> {
Ok(if value == (0 as $par) {
(0 as $ret)
} else if value < (0 as $par) {
(-1 as $ret)
} else {
(1 as $ret)
})
}); )*
};
} }
def_package!(crate:ArithmeticPackage:"Basic arithmetic", lib, { def_package!(crate:ArithmeticPackage:"Basic arithmetic", lib, {
if cfg!(not(feature = "only_i32")) && cfg!(not(feature = "only_i64")) { reg_functions!(lib += signed_basic; INT);
if cfg!(not(feature = "unchecked")) {
// Checked basic arithmetic
reg_op!(lib, "+", add, i8, u8, i16, u16, i32, u32, u64);
reg_op!(lib, "-", sub, i8, u8, i16, u16, i32, u32, u64);
reg_op!(lib, "*", mul, i8, u8, i16, u16, i32, u32, u64);
reg_op!(lib, "/", div, i8, u8, i16, u16, i32, u32, u64);
// Checked bit shifts
reg_op!(lib, "<<", shl, i8, u8, i16, u16, i32, u32, u64);
reg_op!(lib, ">>", shr, i8, u8, i16, u16, i32, u32, u64);
reg_op!(lib, "%", modulo, i8, u8, i16, u16, i32, u32, u64);
if cfg!(not(target_arch = "wasm32")) { #[cfg(not(feature = "only_i32"))]
reg_op!(lib, "+", add, i128, u128); #[cfg(not(feature = "only_i64"))]
reg_op!(lib, "-", sub, i128, u128);
reg_op!(lib, "*", mul, i128, u128);
reg_op!(lib, "/", div, i128, u128);
// Checked bit shifts
reg_op!(lib, "<<", shl, i128, u128);
reg_op!(lib, ">>", shr, i128, u128);
reg_op!(lib, "%", modulo, i128, u128);
}
}
if cfg!(feature = "unchecked") {
// Unchecked basic arithmetic
reg_op!(lib, "+", add_u, i8, u8, i16, u16, i32, u32, u64);
reg_op!(lib, "-", sub_u, i8, u8, i16, u16, i32, u32, u64);
reg_op!(lib, "*", mul_u, i8, u8, i16, u16, i32, u32, u64);
reg_op!(lib, "/", div_u, i8, u8, i16, u16, i32, u32, u64);
// Unchecked bit shifts
reg_op!(lib, "<<", shl_u, i64, i8, u8, i16, u16, i32, u32, u64);
reg_op!(lib, ">>", shr_u, i64, i8, u8, i16, u16, i32, u32, u64);
reg_op!(lib, "%", modulo_u, i8, u8, i16, u16, i32, u32, u64);
if cfg!(not(target_arch = "wasm32")) {
reg_op!(lib, "+", add_u, i128, u128);
reg_op!(lib, "-", sub_u, i128, u128);
reg_op!(lib, "*", mul_u, i128, u128);
reg_op!(lib, "/", div_u, i128, u128);
// Unchecked bit shifts
reg_op!(lib, "<<", shl_u, i128, u128);
reg_op!(lib, ">>", shr_u, i128, u128);
reg_op!(lib, "%", modulo_u, i128, u128);
}
}
reg_sign!(lib, "sign", INT, i8, i16, i32, i64);
if cfg!(not(target_arch = "wasm32")) {
reg_sign!(lib, "sign", INT, i128);
}
}
// Basic arithmetic for floating-point - no need to check
if cfg!(not(feature = "no_float")) {
reg_op!(lib, "+", add_u, f32);
reg_op!(lib, "-", sub_u, f32);
reg_op!(lib, "*", mul_u, f32);
reg_op!(lib, "/", div_u, f32);
reg_sign!(lib, "sign", f32, f32);
reg_sign!(lib, "sign", f64, f64);
}
if cfg!(not(feature = "only_i32")) && cfg!(not(feature = "only_i64")) {
reg_op!(lib, "|", binary_or, i8, u8, i16, u16, i32, u32, u64);
reg_op!(lib, "&", binary_and, i8, u8, i16, u16, i32, u32, u64);
reg_op!(lib, "^", binary_xor, i8, u8, i16, u16, i32, u32, u64);
if cfg!(not(target_arch = "wasm32")) {
reg_op!(lib, "|", binary_or, i128, u128);
reg_op!(lib, "&", binary_and, i128, u128);
reg_op!(lib, "^", binary_xor, i128, u128);
}
}
#[cfg(not(feature = "no_float"))]
{ {
// Checked power reg_functions!(lib += arith_numbers; i8, u8, i16, u16, i32, u32, u64);
if cfg!(not(feature = "unchecked")) { reg_functions!(lib += signed_numbers; i8, i16, i32);
lib.set_fn_2("~", pow_f_i);
} else {
lib.set_fn_2("~", pow_f_i_u);
}
// Floating-point modulo and power #[cfg(not(target_arch = "wasm32"))]
reg_op!(lib, "%", modulo_u, f32); {
reg_functions!(lib += arith_num_128; i128, u128);
// Floating-point unary reg_functions!(lib += signed_num_128; i128);
reg_unary!(lib, "-", neg_u, f32, f64);
reg_unary!(lib, "abs", abs_u, f32, f64);
}
// Checked unary
if cfg!(not(feature = "unchecked")) {
reg_unary!(lib, "-", neg, INT);
reg_unary!(lib, "abs", abs, INT);
if cfg!(not(feature = "only_i32")) && cfg!(not(feature = "only_i64")) {
reg_unary!(lib, "-", neg, i8, i16, i32, i64);
reg_unary!(lib, "abs", abs, i8, i16, i32, i64);
if cfg!(not(target_arch = "wasm32")) {
reg_unary!(lib, "-", neg, i128);
reg_unary!(lib, "abs", abs, i128);
}
} }
} }
// Unchecked unary // Basic arithmetic for floating-point
if cfg!(feature = "unchecked") { #[cfg(not(feature = "no_float"))]
reg_unary!(lib, "-", neg_u, INT); lib.combine_flatten(exported_module!(float_functions));
reg_unary!(lib, "abs", abs_u, INT);
if cfg!(not(feature = "only_i32")) && cfg!(not(feature = "only_i64")) {
reg_unary!(lib, "-", neg_u, i8, i16, i32, i64);
reg_unary!(lib, "abs", abs_u, i8, i16, i32, i64);
if cfg!(not(target_arch = "wasm32")) {
reg_unary!(lib, "-", neg_u, i128);
reg_unary!(lib, "abs", abs_u, i128);
}
}
}
}); });
gen_arithmetic_functions!(arith_basic => INT);
#[cfg(not(feature = "only_i32"))]
#[cfg(not(feature = "only_i64"))]
gen_arithmetic_functions!(arith_numbers => i8, u8, i16, u16, i32, u32, u64);
#[cfg(not(feature = "only_i32"))]
#[cfg(not(feature = "only_i64"))]
#[cfg(not(target_arch = "wasm32"))]
gen_arithmetic_functions!(arith_num_128 => i128, u128);
gen_signed_functions!(signed_basic => INT);
#[cfg(not(feature = "only_i32"))]
#[cfg(not(feature = "only_i64"))]
gen_signed_functions!(signed_numbers => i8, i16, i32);
#[cfg(not(feature = "only_i32"))]
#[cfg(not(feature = "only_i64"))]
#[cfg(not(target_arch = "wasm32"))]
gen_signed_functions!(signed_num_128 => i128);
#[cfg(not(feature = "no_float"))]
#[export_module]
mod float_functions {
#[rhai_fn(name = "+")]
#[inline(always)]
pub fn add(x: f32, y: f32) -> f32 {
x + y
}
#[rhai_fn(name = "-")]
#[inline(always)]
pub fn subtract(x: f32, y: f32) -> f32 {
x - y
}
#[rhai_fn(name = "*")]
#[inline(always)]
pub fn multiply(x: f32, y: f32) -> f32 {
x * y
}
#[rhai_fn(name = "/")]
#[inline(always)]
pub fn divide(x: f32, y: f32) -> f32 {
x / y
}
#[rhai_fn(name = "%")]
#[inline(always)]
pub fn modulo(x: f32, y: f32) -> f32 {
x % y
}
#[rhai_fn(name = "-")]
#[inline(always)]
pub fn neg_f32(x: f32) -> f32 {
-x
}
#[rhai_fn(name = "-")]
#[inline(always)]
pub fn neg_f64(x: f64) -> f64 {
-x
}
#[rhai_fn(name = "abs")]
#[inline(always)]
pub fn abs_f32(x: f32) -> f32 {
x.abs()
}
#[rhai_fn(name = "abs")]
#[inline(always)]
pub fn abs_f64(x: f64) -> f64 {
x.abs()
}
#[rhai_fn(name = "sign")]
#[inline]
pub fn sign_f32(x: f32) -> INT {
if x == 0.0 {
0
} else if x < 0.0 {
-1
} else {
1
}
}
#[rhai_fn(name = "sign")]
#[inline]
pub fn sign_f64(x: f64) -> INT {
if x == 0.0 {
0
} else if x < 0.0 {
-1
} else {
1
}
}
#[rhai_fn(name = "~", return_raw)]
#[inline(always)]
pub fn pow_f_f(x: FLOAT, y: FLOAT) -> Result<Dynamic, Box<EvalAltResult>> {
Ok(x.powf(y).into())
}
#[rhai_fn(name = "~", return_raw)]
#[inline]
pub fn pow_f_i(x: FLOAT, y: INT) -> Result<Dynamic, Box<EvalAltResult>> {
if cfg!(not(feature = "unchecked")) && y > (i32::MAX as INT) {
EvalAltResult::ErrorArithmetic(
format!("Number raised to too large an index: {} ~ {}", x, y),
Position::none(),
)
.into()
} else {
Ok(x.powi(y as i32).into())
}
}
}

View File

@ -10,10 +10,6 @@ use crate::stdlib::vec::Vec;
def_package!(crate:BasicMapPackage:"Basic object map utilities.", lib, { def_package!(crate:BasicMapPackage:"Basic object map utilities.", lib, {
lib.combine_flatten(exported_module!(map_functions)); lib.combine_flatten(exported_module!(map_functions));
// Register map access functions
#[cfg(not(feature = "no_index"))]
lib.combine_flatten(exported_module!(index_functions));
}); });
#[export_module] #[export_module]
@ -63,15 +59,14 @@ mod map_functions {
} }
}); });
} }
}
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
#[export_module] pub mod indexing {
mod index_functions { pub fn keys(map: &mut Map) -> Vec<Dynamic> {
pub fn keys(map: &mut Map) -> Vec<Dynamic> { map.iter().map(|(k, _)| k.clone().into()).collect()
map.iter().map(|(k, _)| k.clone().into()).collect() }
} pub fn values(map: &mut Map) -> Vec<Dynamic> {
pub fn values(map: &mut Map) -> Vec<Dynamic> { map.iter().map(|(_, v)| v.clone()).collect()
map.iter().map(|(_, v)| v.clone()).collect() }
} }
} }

View File

@ -1,3 +1,5 @@
#![allow(non_snake_case)]
use crate::def_package; use crate::def_package;
use crate::parser::INT; use crate::parser::INT;
use crate::plugin::*; use crate::plugin::*;
@ -22,6 +24,28 @@ pub const MAX_INT: INT = i32::MAX;
#[cfg(not(feature = "only_i32"))] #[cfg(not(feature = "only_i32"))]
pub const MAX_INT: INT = i64::MAX; pub const MAX_INT: INT = i64::MAX;
macro_rules! gen_conversion_functions {
($root:ident => $func_name:ident ( $($arg_type:ident),+ ) -> $result_type:ty) => {
pub mod $root { $(
pub mod $arg_type {
use super::super::*;
#[export_fn]
#[inline(always)]
pub fn $func_name(x: $arg_type) -> $result_type {
x as $result_type
}
}
)* }
}
}
macro_rules! reg_functions {
($mod_name:ident += $root:ident :: $func_name:ident ( $($arg_type:ident),+ ) ) => {
$(set_exported_fn!($mod_name, stringify!($func_name), $root::$arg_type::$func_name);)*
}
}
def_package!(crate:BasicMathPackage:"Basic mathematic functions.", lib, { def_package!(crate:BasicMathPackage:"Basic mathematic functions.", lib, {
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
{ {
@ -31,76 +55,27 @@ def_package!(crate:BasicMathPackage:"Basic mathematic functions.", lib, {
// Trig functions // Trig functions
lib.combine_flatten(exported_module!(trig_functions)); lib.combine_flatten(exported_module!(trig_functions));
// Register conversion functions reg_functions!(lib += basic_to_float::to_float(INT));
lib.set_fn_1("to_float", |x: INT| Ok(x as FLOAT));
lib.set_fn_1("to_float", |x: f32| Ok(x as FLOAT));
if cfg!(not(feature = "only_i32")) && cfg!(not(feature = "only_i64")) { #[cfg(not(feature = "only_i32"))]
lib.set_fn_1("to_float", |x: i8| Ok(x as FLOAT)); #[cfg(not(feature = "only_i64"))]
lib.set_fn_1("to_float", |x: u8| Ok(x as FLOAT)); {
lib.set_fn_1("to_float", |x: i16| Ok(x as FLOAT)); reg_functions!(lib += numbers_to_float::to_float(i8, u8, i16, u16, i32, u32, i64, u32));
lib.set_fn_1("to_float", |x: u16| Ok(x as FLOAT));
lib.set_fn_1("to_float", |x: i32| Ok(x as FLOAT));
lib.set_fn_1("to_float", |x: u32| Ok(x as FLOAT));
lib.set_fn_1("to_float", |x: i64| Ok(x as FLOAT));
lib.set_fn_1("to_float", |x: u64| Ok(x as FLOAT));
if cfg!(not(target_arch = "wasm32")) { #[cfg(not(target_arch = "wasm32"))]
lib.set_fn_1("to_float", |x: i128| Ok(x as FLOAT)); reg_functions!(lib += num_128_to_float::to_float(i128, u128));
lib.set_fn_1("to_float", |x: u128| Ok(x as FLOAT));
}
} }
} }
lib.set_fn_1("to_int", |ch: char| Ok(ch as INT)); reg_functions!(lib += basic_to_int::to_int(char));
if cfg!(not(feature = "only_i32")) && cfg!(not(feature = "only_i64")) { #[cfg(not(feature = "only_i32"))]
lib.set_fn_1("to_int", |x: i8| Ok(x as INT)); #[cfg(not(feature = "only_i64"))]
lib.set_fn_1("to_int", |x: u8| Ok(x as INT));
lib.set_fn_1("to_int", |x: i16| Ok(x as INT));
lib.set_fn_1("to_int", |x: u16| Ok(x as INT));
}
if cfg!(not(feature = "only_i32")) {
lib.set_fn_1("to_int", |x: i32| Ok(x as INT));
lib.set_fn_1("to_int", |x: u64| Ok(x as INT));
if cfg!(feature = "only_i64") {
lib.set_fn_1("to_int", |x: u32| Ok(x as INT));
}
}
#[cfg(not(feature = "no_float"))]
{ {
if cfg!(not(feature = "unchecked")) { reg_functions!(lib += numbers_to_int::to_int(i8, u8, i16, u16, i32, u32, i64, u64));
lib.set_fn_1("to_int", |x: f32| {
if x > (MAX_INT as f32) {
return EvalAltResult::ErrorArithmetic(
format!("Integer overflow: to_int({})", x),
Position::none(),
)
.into();
}
Ok(x.trunc() as INT) #[cfg(not(target_arch = "wasm32"))]
}); reg_functions!(lib += num_128_to_int::to_int(i128, u128));
lib.set_fn_1("to_int", |x: FLOAT| {
if x > (MAX_INT as FLOAT) {
return EvalAltResult::ErrorArithmetic(
format!("Integer overflow: to_int({})", x),
Position::none(),
)
.into();
}
Ok(x.trunc() as INT)
});
}
if cfg!(feature = "unchecked") {
lib.set_fn_1("to_int", |x: f32| Ok(x as INT));
lib.set_fn_1("to_int", |x: f64| Ok(x as INT));
}
} }
}); });
@ -256,4 +231,55 @@ mod float_functions {
pub fn is_infinite_prop(x: FLOAT) -> bool { pub fn is_infinite_prop(x: FLOAT) -> bool {
is_infinite(x) is_infinite(x)
} }
#[rhai_fn(name = "to_int", return_raw)]
#[inline]
pub fn f32_to_int(x: f32) -> Result<Dynamic, Box<EvalAltResult>> {
if cfg!(not(feature = "unchecked")) && x > (MAX_INT as f32) {
EvalAltResult::ErrorArithmetic(
format!("Integer overflow: to_int({})", x),
Position::none(),
)
.into()
} else {
Ok((x.trunc() as INT).into())
}
}
#[rhai_fn(name = "to_int", return_raw)]
#[inline]
pub fn f64_to_int(x: f64) -> Result<Dynamic, Box<EvalAltResult>> {
if cfg!(not(feature = "unchecked")) && x > (MAX_INT as f64) {
EvalAltResult::ErrorArithmetic(
format!("Integer overflow: to_int({})", x),
Position::none(),
)
.into()
} else {
Ok((x.trunc() as INT).into())
}
}
} }
#[cfg(not(feature = "no_float"))]
gen_conversion_functions!(basic_to_float => to_float (INT) -> FLOAT);
#[cfg(not(feature = "no_float"))]
#[cfg(not(feature = "only_i32"))]
#[cfg(not(feature = "only_i64"))]
gen_conversion_functions!(numbers_to_float => to_float (i8, u8, i16, u16, i32, u32, i64, u64) -> FLOAT);
#[cfg(not(feature = "no_float"))]
#[cfg(not(feature = "only_i32"))]
#[cfg(not(feature = "only_i64"))]
#[cfg(not(target_arch = "wasm32"))]
gen_conversion_functions!(num_128_to_float => to_float (i128, u128) -> FLOAT);
gen_conversion_functions!(basic_to_int => to_int (char) -> INT);
#[cfg(not(feature = "only_i32"))]
#[cfg(not(feature = "only_i64"))]
gen_conversion_functions!(numbers_to_int => to_int (i8, u8, i16, u16, i32, u32, i64, u64) -> INT);
#[cfg(not(feature = "only_i32"))]
#[cfg(not(feature = "only_i64"))]
#[cfg(not(target_arch = "wasm32"))]
gen_conversion_functions!(num_128_to_int => to_int (i128, u128) -> INT);

View File

@ -59,9 +59,6 @@ def_package!(crate:MoreStringPackage:"Additional string utilities, including str
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
reg_functions!(lib += float; f32, f64); reg_functions!(lib += float; f32, f64);
#[cfg(not(feature = "no_index"))]
lib.combine_flatten(exported_module!(index_functions));
lib.combine_flatten(exported_module!(string_functions)); lib.combine_flatten(exported_module!(string_functions));
lib.set_raw_fn( lib.set_raw_fn(
@ -343,21 +340,20 @@ mod string_functions {
pub fn replace_char(s: &mut ImmutableString, find: char, sub: char) { pub fn replace_char(s: &mut ImmutableString, find: char, sub: char) {
*s = s.replace(&find.to_string(), &sub.to_string()).into(); *s = s.replace(&find.to_string(), &sub.to_string()).into();
} }
}
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
#[export_module] pub mod arrays {
mod index_functions { use crate::engine::Array;
use crate::engine::Array;
#[rhai_fn(name = "+")] #[rhai_fn(name = "+")]
#[inline] #[inline]
pub fn append(x: &mut ImmutableString, y: Array) -> String { pub fn append(x: &mut ImmutableString, y: Array) -> String {
format!("{}{:?}", x, y) format!("{}{:?}", x, y)
} }
#[rhai_fn(name = "+")] #[rhai_fn(name = "+")]
#[inline] #[inline]
pub fn prepend(x: &mut Array, y: ImmutableString) -> String { pub fn prepend(x: &mut Array, y: ImmutableString) -> String {
format!("{:?}{}", x, y) format!("{:?}{}", x, y)
}
} }
} }