Split core and standard libraries into packages.
This commit is contained in:
442
src/packages/arithmetic.rs
Normal file
442
src/packages/arithmetic.rs
Normal file
@@ -0,0 +1,442 @@
|
||||
use super::{
|
||||
create_new_package, reg_binary, reg_unary, Package, PackageLibrary, PackageLibraryStore,
|
||||
};
|
||||
|
||||
use crate::fn_register::{map_dynamic as map, map_result as result};
|
||||
use crate::parser::INT;
|
||||
use crate::result::EvalAltResult;
|
||||
use crate::token::Position;
|
||||
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
use crate::parser::FLOAT;
|
||||
|
||||
use num_traits::{
|
||||
identities::Zero, CheckedAdd, CheckedDiv, CheckedMul, CheckedNeg, CheckedRem, CheckedShl,
|
||||
CheckedShr, CheckedSub,
|
||||
};
|
||||
|
||||
use crate::stdlib::{
|
||||
fmt::Display,
|
||||
format,
|
||||
ops::{Add, BitAnd, BitOr, BitXor, Deref, Div, Mul, Neg, Rem, Shl, Shr, Sub},
|
||||
{i32, i64, u32},
|
||||
};
|
||||
|
||||
// Checked add
|
||||
fn add<T: Display + CheckedAdd>(x: T, y: T) -> Result<T, EvalAltResult> {
|
||||
x.checked_add(&y).ok_or_else(|| {
|
||||
EvalAltResult::ErrorArithmetic(
|
||||
format!("Addition overflow: {} + {}", x, y),
|
||||
Position::none(),
|
||||
)
|
||||
})
|
||||
}
|
||||
// Checked subtract
|
||||
fn sub<T: Display + CheckedSub>(x: T, y: T) -> Result<T, EvalAltResult> {
|
||||
x.checked_sub(&y).ok_or_else(|| {
|
||||
EvalAltResult::ErrorArithmetic(
|
||||
format!("Subtraction underflow: {} - {}", x, y),
|
||||
Position::none(),
|
||||
)
|
||||
})
|
||||
}
|
||||
// Checked multiply
|
||||
fn mul<T: Display + CheckedMul>(x: T, y: T) -> Result<T, EvalAltResult> {
|
||||
x.checked_mul(&y).ok_or_else(|| {
|
||||
EvalAltResult::ErrorArithmetic(
|
||||
format!("Multiplication overflow: {} * {}", x, y),
|
||||
Position::none(),
|
||||
)
|
||||
})
|
||||
}
|
||||
// Checked divide
|
||||
fn div<T>(x: T, y: T) -> Result<T, EvalAltResult>
|
||||
where
|
||||
T: Display + CheckedDiv + PartialEq + Zero,
|
||||
{
|
||||
// Detect division by zero
|
||||
if y == T::zero() {
|
||||
return Err(EvalAltResult::ErrorArithmetic(
|
||||
format!("Division by zero: {} / {}", x, y),
|
||||
Position::none(),
|
||||
));
|
||||
}
|
||||
|
||||
x.checked_div(&y).ok_or_else(|| {
|
||||
EvalAltResult::ErrorArithmetic(
|
||||
format!("Division overflow: {} / {}", x, y),
|
||||
Position::none(),
|
||||
)
|
||||
})
|
||||
}
|
||||
// Checked negative - e.g. -(i32::MIN) will overflow i32::MAX
|
||||
fn neg<T: Display + CheckedNeg>(x: T) -> Result<T, EvalAltResult> {
|
||||
x.checked_neg().ok_or_else(|| {
|
||||
EvalAltResult::ErrorArithmetic(format!("Negation overflow: -{}", x), Position::none())
|
||||
})
|
||||
}
|
||||
// Checked absolute
|
||||
fn abs<T: Display + CheckedNeg + PartialOrd + Zero>(x: T) -> Result<T, EvalAltResult> {
|
||||
// FIX - We don't use Signed::abs() here because, contrary to documentation, it panics
|
||||
// when the number is ::MIN instead of returning ::MIN itself.
|
||||
if x >= <T as Zero>::zero() {
|
||||
Ok(x)
|
||||
} else {
|
||||
x.checked_neg().ok_or_else(|| {
|
||||
EvalAltResult::ErrorArithmetic(format!("Negation overflow: -{}", x), Position::none())
|
||||
})
|
||||
}
|
||||
}
|
||||
// Unchecked add - may panic on overflow
|
||||
fn add_u<T: Add>(x: T, y: T) -> <T as Add>::Output {
|
||||
x + y
|
||||
}
|
||||
// Unchecked subtract - may panic on underflow
|
||||
fn sub_u<T: Sub>(x: T, y: T) -> <T as Sub>::Output {
|
||||
x - y
|
||||
}
|
||||
// Unchecked multiply - may panic on overflow
|
||||
fn mul_u<T: Mul>(x: T, y: T) -> <T as Mul>::Output {
|
||||
x * y
|
||||
}
|
||||
// Unchecked divide - may panic when dividing by zero
|
||||
fn div_u<T: Div>(x: T, y: T) -> <T as Div>::Output {
|
||||
x / y
|
||||
}
|
||||
// Unchecked negative - may panic on overflow
|
||||
fn neg_u<T: Neg>(x: T) -> <T as Neg>::Output {
|
||||
-x
|
||||
}
|
||||
// Unchecked absolute - may panic on overflow
|
||||
fn abs_u<T>(x: T) -> <T as Neg>::Output
|
||||
where
|
||||
T: Neg + PartialOrd + Default + Into<<T as Neg>::Output>,
|
||||
{
|
||||
// Numbers should default to zero
|
||||
if x < Default::default() {
|
||||
-x
|
||||
} else {
|
||||
x.into()
|
||||
}
|
||||
}
|
||||
// Bit operators
|
||||
fn binary_and<T: BitAnd>(x: T, y: T) -> <T as BitAnd>::Output {
|
||||
x & y
|
||||
}
|
||||
fn binary_or<T: BitOr>(x: T, y: T) -> <T as BitOr>::Output {
|
||||
x | y
|
||||
}
|
||||
fn binary_xor<T: BitXor>(x: T, y: T) -> <T as BitXor>::Output {
|
||||
x ^ y
|
||||
}
|
||||
// Checked left-shift
|
||||
fn shl<T: Display + CheckedShl>(x: T, y: INT) -> Result<T, EvalAltResult> {
|
||||
// Cannot shift by a negative number of bits
|
||||
if y < 0 {
|
||||
return Err(EvalAltResult::ErrorArithmetic(
|
||||
format!("Left-shift by a negative number: {} << {}", x, y),
|
||||
Position::none(),
|
||||
));
|
||||
}
|
||||
|
||||
CheckedShl::checked_shl(&x, y as u32).ok_or_else(|| {
|
||||
EvalAltResult::ErrorArithmetic(
|
||||
format!("Left-shift by too many bits: {} << {}", x, y),
|
||||
Position::none(),
|
||||
)
|
||||
})
|
||||
}
|
||||
// Checked right-shift
|
||||
fn shr<T: Display + CheckedShr>(x: T, y: INT) -> Result<T, EvalAltResult> {
|
||||
// Cannot shift by a negative number of bits
|
||||
if y < 0 {
|
||||
return Err(EvalAltResult::ErrorArithmetic(
|
||||
format!("Right-shift by a negative number: {} >> {}", x, y),
|
||||
Position::none(),
|
||||
));
|
||||
}
|
||||
|
||||
CheckedShr::checked_shr(&x, y as u32).ok_or_else(|| {
|
||||
EvalAltResult::ErrorArithmetic(
|
||||
format!("Right-shift by too many bits: {} % {}", x, y),
|
||||
Position::none(),
|
||||
)
|
||||
})
|
||||
}
|
||||
// Unchecked left-shift - may panic if shifting by a negative number of bits
|
||||
fn shl_u<T: Shl<T>>(x: T, y: T) -> <T as Shl<T>>::Output {
|
||||
x.shl(y)
|
||||
}
|
||||
// Unchecked right-shift - may panic if shifting by a negative number of bits
|
||||
fn shr_u<T: Shr<T>>(x: T, y: T) -> <T as Shr<T>>::Output {
|
||||
x.shr(y)
|
||||
}
|
||||
// Checked modulo
|
||||
fn modulo<T: Display + CheckedRem>(x: T, y: T) -> Result<T, EvalAltResult> {
|
||||
x.checked_rem(&y).ok_or_else(|| {
|
||||
EvalAltResult::ErrorArithmetic(
|
||||
format!("Modulo division by zero or overflow: {} % {}", x, y),
|
||||
Position::none(),
|
||||
)
|
||||
})
|
||||
}
|
||||
// Unchecked modulo - may panic if dividing by zero
|
||||
fn modulo_u<T: Rem>(x: T, y: T) -> <T as Rem>::Output {
|
||||
x % y
|
||||
}
|
||||
// Checked power
|
||||
fn pow_i_i(x: INT, y: INT) -> Result<INT, EvalAltResult> {
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
{
|
||||
if y > (u32::MAX as INT) {
|
||||
Err(EvalAltResult::ErrorArithmetic(
|
||||
format!("Integer raised to too large an index: {} ~ {}", x, y),
|
||||
Position::none(),
|
||||
))
|
||||
} else if y < 0 {
|
||||
Err(EvalAltResult::ErrorArithmetic(
|
||||
format!("Integer raised to a negative index: {} ~ {}", x, y),
|
||||
Position::none(),
|
||||
))
|
||||
} else {
|
||||
x.checked_pow(y as u32).ok_or_else(|| {
|
||||
EvalAltResult::ErrorArithmetic(
|
||||
format!("Power overflow: {} ~ {}", x, y),
|
||||
Position::none(),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "only_i32")]
|
||||
{
|
||||
if y < 0 {
|
||||
Err(EvalAltResult::ErrorArithmetic(
|
||||
format!("Integer raised to a negative index: {} ~ {}", x, y),
|
||||
Position::none(),
|
||||
))
|
||||
} else {
|
||||
x.checked_pow(y as u32).ok_or_else(|| {
|
||||
EvalAltResult::ErrorArithmetic(
|
||||
format!("Power overflow: {} ~ {}", x, y),
|
||||
Position::none(),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
// Unchecked integer power - may panic on overflow or if the power index is too high (> u32::MAX)
|
||||
fn pow_i_i_u(x: INT, y: INT) -> INT {
|
||||
x.pow(y as u32)
|
||||
}
|
||||
// Floating-point power - always well-defined
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
fn pow_f_f(x: FLOAT, y: FLOAT) -> FLOAT {
|
||||
x.powf(y)
|
||||
}
|
||||
// Checked power
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
fn pow_f_i(x: FLOAT, y: INT) -> Result<FLOAT, EvalAltResult> {
|
||||
// Raise to power that is larger than an i32
|
||||
if y > (i32::MAX as INT) {
|
||||
return Err(EvalAltResult::ErrorArithmetic(
|
||||
format!("Number raised to too large an index: {} ~ {}", x, y),
|
||||
Position::none(),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(x.powi(y as i32))
|
||||
}
|
||||
// Unchecked power - may be incorrect if the power index is too high (> i32::MAX)
|
||||
#[cfg(feature = "unchecked")]
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
fn pow_f_i_u(x: FLOAT, y: INT) -> FLOAT {
|
||||
x.powi(y as i32)
|
||||
}
|
||||
|
||||
pub struct ArithmeticPackage(PackageLibrary);
|
||||
|
||||
impl Deref for ArithmeticPackage {
|
||||
type Target = PackageLibrary;
|
||||
|
||||
fn deref(&self) -> &PackageLibrary {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! reg_unary_x { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => {
|
||||
$(reg_unary($lib, $op, $func::<$par>, result);)* };
|
||||
}
|
||||
macro_rules! reg_unary { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => {
|
||||
$(reg_unary($lib, $op, $func::<$par>, map);)* };
|
||||
}
|
||||
macro_rules! reg_op_x { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => {
|
||||
$(reg_binary($lib, $op, $func::<$par>, result);)* };
|
||||
}
|
||||
macro_rules! reg_op { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => {
|
||||
$(reg_binary($lib, $op, $func::<$par>, map);)* };
|
||||
}
|
||||
|
||||
impl Package for ArithmeticPackage {
|
||||
fn new() -> Self {
|
||||
let mut pkg = create_new_package();
|
||||
Self::init(&mut pkg);
|
||||
Self(pkg.into())
|
||||
}
|
||||
|
||||
fn get(&self) -> PackageLibrary {
|
||||
self.0.clone()
|
||||
}
|
||||
|
||||
fn init(lib: &mut PackageLibraryStore) {
|
||||
// Checked basic arithmetic
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
{
|
||||
reg_op_x!(lib, "+", add, INT);
|
||||
reg_op_x!(lib, "-", sub, INT);
|
||||
reg_op_x!(lib, "*", mul, INT);
|
||||
reg_op_x!(lib, "/", div, INT);
|
||||
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
#[cfg(not(feature = "only_i64"))]
|
||||
{
|
||||
reg_op_x!(lib, "+", add, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op_x!(lib, "-", sub, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op_x!(lib, "*", mul, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op_x!(lib, "/", div, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
}
|
||||
}
|
||||
|
||||
// Unchecked basic arithmetic
|
||||
#[cfg(feature = "unchecked")]
|
||||
{
|
||||
reg_op!(lib, "+", add_u, INT);
|
||||
reg_op!(lib, "-", sub_u, INT);
|
||||
reg_op!(lib, "*", mul_u, INT);
|
||||
reg_op!(lib, "/", div_u, INT);
|
||||
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
#[cfg(not(feature = "only_i64"))]
|
||||
{
|
||||
reg_op!(lib, "+", add_u, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op!(lib, "-", sub_u, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op!(lib, "*", mul_u, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op!(lib, "/", div_u, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
}
|
||||
}
|
||||
|
||||
// Basic arithmetic for floating-point - no need to check
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
{
|
||||
reg_op!(lib, "+", add_u, f32, f64);
|
||||
reg_op!(lib, "-", sub_u, f32, f64);
|
||||
reg_op!(lib, "*", mul_u, f32, f64);
|
||||
reg_op!(lib, "/", div_u, f32, f64);
|
||||
}
|
||||
|
||||
// Bit operations
|
||||
reg_op!(lib, "|", binary_or, INT);
|
||||
reg_op!(lib, "&", binary_and, INT);
|
||||
reg_op!(lib, "^", binary_xor, INT);
|
||||
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
#[cfg(not(feature = "only_i64"))]
|
||||
{
|
||||
reg_op!(lib, "|", binary_or, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op!(lib, "&", binary_and, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op!(lib, "^", binary_xor, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
}
|
||||
|
||||
// Checked bit shifts
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
{
|
||||
reg_op_x!(lib, "<<", shl, INT);
|
||||
reg_op_x!(lib, ">>", shr, INT);
|
||||
reg_op_x!(lib, "%", modulo, INT);
|
||||
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
#[cfg(not(feature = "only_i64"))]
|
||||
{
|
||||
reg_op_x!(lib, "<<", shl, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op_x!(lib, ">>", shr, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op_x!(lib, "%", modulo, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
}
|
||||
}
|
||||
|
||||
// Unchecked bit shifts
|
||||
#[cfg(feature = "unchecked")]
|
||||
{
|
||||
reg_op!(lib, "<<", shl_u, INT, INT);
|
||||
reg_op!(lib, ">>", shr_u, INT, INT);
|
||||
reg_op!(lib, "%", modulo_u, INT);
|
||||
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
#[cfg(not(feature = "only_i64"))]
|
||||
{
|
||||
reg_op!(lib, "<<", shl_u, i64, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op!(lib, ">>", shr_u, i64, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op!(lib, "%", modulo_u, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
}
|
||||
}
|
||||
|
||||
// Checked power
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
{
|
||||
reg_binary(lib, "~", pow_i_i, result);
|
||||
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
reg_binary(lib, "~", pow_f_i, result);
|
||||
}
|
||||
|
||||
// Unchecked power
|
||||
#[cfg(feature = "unchecked")]
|
||||
{
|
||||
reg_binary(lib, "~", pow_i_i_u, map);
|
||||
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
reg_binary(lib, "~", pow_f_i_u, map);
|
||||
}
|
||||
|
||||
// Floating-point modulo and power
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
{
|
||||
reg_op!(lib, "%", modulo_u, f32, f64);
|
||||
reg_binary(lib, "~", pow_f_f, map);
|
||||
}
|
||||
|
||||
// Checked unary
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
{
|
||||
reg_unary_x!(lib, "-", neg, INT);
|
||||
reg_unary_x!(lib, "abs", abs, INT);
|
||||
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
#[cfg(not(feature = "only_i64"))]
|
||||
{
|
||||
reg_unary_x!(lib, "-", neg, i8, i16, i32, i64, i128);
|
||||
reg_unary_x!(lib, "abs", abs, i8, i16, i32, i64, i128);
|
||||
}
|
||||
}
|
||||
|
||||
// Unchecked unary
|
||||
#[cfg(feature = "unchecked")]
|
||||
{
|
||||
reg_unary!(lib, "-", neg_u, INT);
|
||||
reg_unary!(lib, "abs", abs_u, INT);
|
||||
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
#[cfg(not(feature = "only_i64"))]
|
||||
{
|
||||
reg_unary!(lib, "-", neg_u, i8, i16, i32, i64, i128);
|
||||
reg_unary!(lib, "abs", abs_u, i8, i16, i32, i64, i128);
|
||||
}
|
||||
}
|
||||
|
||||
// Floating-point unary
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
{
|
||||
reg_unary!(lib, "-", neg_u, f32, f64);
|
||||
reg_unary!(lib, "abs", abs_u, f32, f64);
|
||||
}
|
||||
}
|
||||
}
|
139
src/packages/array_basic.rs
Normal file
139
src/packages/array_basic.rs
Normal file
@@ -0,0 +1,139 @@
|
||||
use super::{
|
||||
create_new_package, reg_binary, reg_binary_mut, reg_trinary_mut, reg_unary_mut, Package,
|
||||
PackageLibrary, PackageLibraryStore,
|
||||
};
|
||||
|
||||
use crate::any::{Dynamic, Variant};
|
||||
use crate::engine::Array;
|
||||
use crate::fn_register::{map_dynamic as map, map_identity as copy};
|
||||
use crate::parser::INT;
|
||||
|
||||
use crate::stdlib::ops::Deref;
|
||||
|
||||
// Register array utility functions
|
||||
fn push<T: Variant + Clone>(list: &mut Array, item: T) {
|
||||
list.push(Dynamic::from(item));
|
||||
}
|
||||
fn ins<T: Variant + Clone>(list: &mut Array, position: INT, item: T) {
|
||||
if position <= 0 {
|
||||
list.insert(0, Dynamic::from(item));
|
||||
} else if (position as usize) >= list.len() - 1 {
|
||||
push(list, item);
|
||||
} else {
|
||||
list.insert(position as usize, Dynamic::from(item));
|
||||
}
|
||||
}
|
||||
fn pad<T: Variant + Clone>(list: &mut Array, len: INT, item: T) {
|
||||
if len >= 0 {
|
||||
while list.len() < len as usize {
|
||||
push(list, item.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BasicArrayPackage(PackageLibrary);
|
||||
|
||||
impl Deref for BasicArrayPackage {
|
||||
type Target = PackageLibrary;
|
||||
|
||||
fn deref(&self) -> &PackageLibrary {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! reg_op { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => {
|
||||
$(reg_binary_mut($lib, $op, $func::<$par>, map);)* };
|
||||
}
|
||||
macro_rules! reg_tri { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => {
|
||||
$(reg_trinary_mut($lib, $op, $func::<$par>, map);)* };
|
||||
}
|
||||
|
||||
impl Package for BasicArrayPackage {
|
||||
fn new() -> Self {
|
||||
let mut pkg = create_new_package();
|
||||
Self::init(&mut pkg);
|
||||
Self(pkg.into())
|
||||
}
|
||||
|
||||
fn get(&self) -> PackageLibrary {
|
||||
self.0.clone()
|
||||
}
|
||||
|
||||
fn init(lib: &mut PackageLibraryStore) {
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
{
|
||||
reg_op!(lib, "push", push, INT, bool, char, String, Array, ());
|
||||
reg_tri!(lib, "pad", pad, INT, bool, char, String, Array, ());
|
||||
reg_tri!(lib, "insert", ins, INT, bool, char, String, Array, ());
|
||||
|
||||
reg_binary_mut(lib, "append", |x: &mut Array, y: Array| x.extend(y), map);
|
||||
reg_binary(
|
||||
lib,
|
||||
"+",
|
||||
|mut x: Array, y: Array| {
|
||||
x.extend(y);
|
||||
x
|
||||
},
|
||||
map,
|
||||
);
|
||||
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
#[cfg(not(feature = "only_i64"))]
|
||||
{
|
||||
reg_op!(lib, "push", push, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_tri!(lib, "pad", pad, i8, u8, i16, u16, i32, u32, i64, u64, i128, u128);
|
||||
reg_tri!(lib, "insert", ins, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
{
|
||||
reg_op!(lib, "push", push, f32, f64);
|
||||
reg_tri!(lib, "pad", pad, f32, f64);
|
||||
reg_tri!(lib, "insert", ins, f32, f64);
|
||||
}
|
||||
|
||||
reg_unary_mut(
|
||||
lib,
|
||||
"pop",
|
||||
|list: &mut Array| list.pop().unwrap_or_else(|| Dynamic::from_unit()),
|
||||
copy,
|
||||
);
|
||||
reg_unary_mut(
|
||||
lib,
|
||||
"shift",
|
||||
|list: &mut Array| {
|
||||
if !list.is_empty() {
|
||||
Dynamic::from_unit()
|
||||
} else {
|
||||
list.remove(0)
|
||||
}
|
||||
},
|
||||
copy,
|
||||
);
|
||||
reg_binary_mut(
|
||||
lib,
|
||||
"remove",
|
||||
|list: &mut Array, len: INT| {
|
||||
if len < 0 || (len as usize) >= list.len() {
|
||||
Dynamic::from_unit()
|
||||
} else {
|
||||
list.remove(len as usize)
|
||||
}
|
||||
},
|
||||
copy,
|
||||
);
|
||||
reg_unary_mut(lib, "len", |list: &mut Array| list.len() as INT, map);
|
||||
reg_unary_mut(lib, "clear", |list: &mut Array| list.clear(), map);
|
||||
reg_binary_mut(
|
||||
lib,
|
||||
"truncate",
|
||||
|list: &mut Array, len: INT| {
|
||||
if len >= 0 {
|
||||
list.truncate(len as usize);
|
||||
}
|
||||
},
|
||||
map,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
33
src/packages/basic.rs
Normal file
33
src/packages/basic.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
use super::{
|
||||
create_new_package, reg_binary, reg_binary_mut, reg_unary, Package, PackageLibrary,
|
||||
PackageLibraryStore,
|
||||
};
|
||||
|
||||
use crate::fn_register::map_dynamic as map;
|
||||
use crate::parser::INT;
|
||||
|
||||
use crate::stdlib::ops::Deref;
|
||||
|
||||
pub struct BasicPackage(PackageLibrary);
|
||||
|
||||
impl Deref for BasicPackage {
|
||||
type Target = PackageLibrary;
|
||||
|
||||
fn deref(&self) -> &PackageLibrary {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Package for BasicPackage {
|
||||
fn new() -> Self {
|
||||
let mut pkg = create_new_package();
|
||||
Self::init(&mut pkg);
|
||||
Self(pkg.into())
|
||||
}
|
||||
|
||||
fn get(&self) -> PackageLibrary {
|
||||
self.0.clone()
|
||||
}
|
||||
|
||||
fn init(lib: &mut PackageLibraryStore) {}
|
||||
}
|
173
src/packages/iter_basic.rs
Normal file
173
src/packages/iter_basic.rs
Normal file
@@ -0,0 +1,173 @@
|
||||
use super::{
|
||||
create_new_package, reg_binary, reg_trinary, reg_unary_mut, Package, PackageLibrary,
|
||||
PackageLibraryStore,
|
||||
};
|
||||
|
||||
use crate::any::{Dynamic, Union, Variant};
|
||||
use crate::engine::{Array, Map};
|
||||
use crate::fn_register::map_dynamic as map;
|
||||
use crate::parser::INT;
|
||||
|
||||
use crate::stdlib::{
|
||||
any::TypeId,
|
||||
ops::{Add, Deref, Range},
|
||||
};
|
||||
|
||||
// Register range function
|
||||
fn reg_range<T: Variant + Clone>(lib: &mut PackageLibraryStore)
|
||||
where
|
||||
Range<T>: Iterator<Item = T>,
|
||||
{
|
||||
lib.1.insert(
|
||||
TypeId::of::<Range<T>>(),
|
||||
Box::new(|source: &Dynamic| {
|
||||
Box::new(
|
||||
source
|
||||
.downcast_ref::<Range<T>>()
|
||||
.cloned()
|
||||
.unwrap()
|
||||
.map(|x| x.into_dynamic()),
|
||||
) as Box<dyn Iterator<Item = Dynamic>>
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Register range function with step
|
||||
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
|
||||
struct StepRange<T>(T, T, T)
|
||||
where
|
||||
for<'a> &'a T: Add<&'a T, Output = T>,
|
||||
T: Variant + Clone + PartialOrd;
|
||||
|
||||
impl<T> Iterator for StepRange<T>
|
||||
where
|
||||
for<'a> &'a T: Add<&'a T, Output = T>,
|
||||
T: Variant + Clone + PartialOrd,
|
||||
{
|
||||
type Item = T;
|
||||
|
||||
fn next(&mut self) -> Option<T> {
|
||||
if self.0 < self.1 {
|
||||
let v = self.0.clone();
|
||||
self.0 = &v + &self.2;
|
||||
Some(v)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reg_step<T>(lib: &mut PackageLibraryStore)
|
||||
where
|
||||
for<'a> &'a T: Add<&'a T, Output = T>,
|
||||
T: Variant + Clone + PartialOrd,
|
||||
StepRange<T>: Iterator<Item = T>,
|
||||
{
|
||||
lib.1.insert(
|
||||
TypeId::of::<StepRange<T>>(),
|
||||
Box::new(|source: &Dynamic| {
|
||||
Box::new(
|
||||
source
|
||||
.downcast_ref::<StepRange<T>>()
|
||||
.cloned()
|
||||
.unwrap()
|
||||
.map(|x| x.into_dynamic()),
|
||||
) as Box<dyn Iterator<Item = Dynamic>>
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
pub struct BasicIteratorPackage(PackageLibrary);
|
||||
|
||||
impl Deref for BasicIteratorPackage {
|
||||
type Target = PackageLibrary;
|
||||
|
||||
fn deref(&self) -> &PackageLibrary {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Package for BasicIteratorPackage {
|
||||
fn new() -> Self {
|
||||
let mut pkg = create_new_package();
|
||||
Self::init(&mut pkg);
|
||||
Self(pkg.into())
|
||||
}
|
||||
|
||||
fn get(&self) -> PackageLibrary {
|
||||
self.0.clone()
|
||||
}
|
||||
|
||||
fn init(lib: &mut PackageLibraryStore) {
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
{
|
||||
// Register array iterator
|
||||
lib.1.insert(
|
||||
TypeId::of::<Array>(),
|
||||
Box::new(|a: &Dynamic| {
|
||||
Box::new(a.downcast_ref::<Array>().unwrap().clone().into_iter())
|
||||
as Box<dyn Iterator<Item = Dynamic>>
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Register map access functions
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
{
|
||||
fn map_get_keys(map: &mut Map) -> Vec<Dynamic> {
|
||||
map.iter()
|
||||
.map(|(k, _)| Dynamic(Union::Str(Box::new(k.to_string()))))
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
fn map_get_values(map: &mut Map) -> Vec<Dynamic> {
|
||||
map.iter().map(|(_, v)| v.clone()).collect::<Vec<_>>()
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
reg_unary_mut(lib, "keys", map_get_keys, map);
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
reg_unary_mut(lib, "values", map_get_values, map);
|
||||
}
|
||||
|
||||
fn get_range<T>(from: T, to: T) -> Range<T> {
|
||||
from..to
|
||||
}
|
||||
|
||||
reg_range::<INT>(lib);
|
||||
reg_binary(lib, "range", get_range::<INT>, map);
|
||||
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
#[cfg(not(feature = "only_i64"))]
|
||||
{
|
||||
macro_rules! reg_range {
|
||||
($self:expr, $x:expr, $( $y:ty ),*) => (
|
||||
$(
|
||||
reg_range::<$y>($self);
|
||||
reg_binary($self, $x, get_range::<$y>, map);
|
||||
)*
|
||||
)
|
||||
}
|
||||
|
||||
reg_range!(lib, "range", i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
}
|
||||
|
||||
reg_step::<INT>(lib);
|
||||
reg_trinary(lib, "range", StepRange::<INT>, map);
|
||||
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
#[cfg(not(feature = "only_i64"))]
|
||||
{
|
||||
macro_rules! reg_step {
|
||||
($self:expr, $x:expr, $( $y:ty ),*) => (
|
||||
$(
|
||||
reg_step::<$y>($self);
|
||||
reg_trinary($self, $x, StepRange::<$y>, map);
|
||||
)*
|
||||
)
|
||||
}
|
||||
|
||||
reg_step!(lib, "range", i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
}
|
||||
}
|
||||
}
|
113
src/packages/logic.rs
Normal file
113
src/packages/logic.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
use super::{
|
||||
create_new_package, reg_binary, reg_binary_mut, reg_unary, Package, PackageLibrary,
|
||||
PackageLibraryStore,
|
||||
};
|
||||
|
||||
use crate::fn_register::map_dynamic as map;
|
||||
use crate::parser::INT;
|
||||
|
||||
use crate::stdlib::ops::Deref;
|
||||
|
||||
// Comparison operators
|
||||
pub fn lt<T: PartialOrd>(x: T, y: T) -> bool {
|
||||
x < y
|
||||
}
|
||||
pub fn lte<T: PartialOrd>(x: T, y: T) -> bool {
|
||||
x <= y
|
||||
}
|
||||
pub fn gt<T: PartialOrd>(x: T, y: T) -> bool {
|
||||
x > y
|
||||
}
|
||||
pub fn gte<T: PartialOrd>(x: T, y: T) -> bool {
|
||||
x >= y
|
||||
}
|
||||
pub fn eq<T: PartialEq>(x: T, y: T) -> bool {
|
||||
x == y
|
||||
}
|
||||
pub fn ne<T: PartialEq>(x: T, y: T) -> bool {
|
||||
x != y
|
||||
}
|
||||
|
||||
// Logic operators
|
||||
fn and(x: bool, y: bool) -> bool {
|
||||
x && y
|
||||
}
|
||||
fn or(x: bool, y: bool) -> bool {
|
||||
x || y
|
||||
}
|
||||
fn not(x: bool) -> bool {
|
||||
!x
|
||||
}
|
||||
|
||||
macro_rules! reg_op { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => {
|
||||
$(reg_binary($lib, $op, $func::<$par>, map);)* };
|
||||
}
|
||||
|
||||
pub struct LogicPackage(PackageLibrary);
|
||||
|
||||
impl Deref for LogicPackage {
|
||||
type Target = PackageLibrary;
|
||||
|
||||
fn deref(&self) -> &PackageLibrary {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Package for LogicPackage {
|
||||
fn new() -> Self {
|
||||
let mut pkg = create_new_package();
|
||||
Self::init(&mut pkg);
|
||||
Self(pkg.into())
|
||||
}
|
||||
|
||||
fn get(&self) -> PackageLibrary {
|
||||
self.0.clone()
|
||||
}
|
||||
|
||||
fn init(lib: &mut PackageLibraryStore) {
|
||||
reg_op!(lib, "<", lt, INT, char);
|
||||
reg_op!(lib, "<=", lte, INT, char);
|
||||
reg_op!(lib, ">", gt, INT, char);
|
||||
reg_op!(lib, ">=", gte, INT, char);
|
||||
reg_op!(lib, "==", eq, INT, char, bool, ());
|
||||
reg_op!(lib, "!=", ne, INT, char, bool, ());
|
||||
|
||||
// Special versions for strings - at least avoid copying the first string
|
||||
reg_binary_mut(lib, "<", |x: &mut String, y: String| *x < y, map);
|
||||
reg_binary_mut(lib, "<=", |x: &mut String, y: String| *x <= y, map);
|
||||
reg_binary_mut(lib, ">", |x: &mut String, y: String| *x > y, map);
|
||||
reg_binary_mut(lib, ">=", |x: &mut String, y: String| *x >= y, map);
|
||||
reg_binary_mut(lib, "==", |x: &mut String, y: String| *x == y, map);
|
||||
reg_binary_mut(lib, "!=", |x: &mut String, y: String| *x != y, map);
|
||||
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
#[cfg(not(feature = "only_i64"))]
|
||||
{
|
||||
reg_op!(lib, "<", lt, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op!(lib, "<=", lte, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op!(lib, ">", gt, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op!(lib, ">=", gte, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op!(lib, "==", eq, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op!(lib, "!=", ne, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
{
|
||||
reg_op!(lib, "<", lt, f32, f64);
|
||||
reg_op!(lib, "<=", lte, f32, f64);
|
||||
reg_op!(lib, ">", gt, f32, f64);
|
||||
reg_op!(lib, ">=", gte, f32, f64);
|
||||
reg_op!(lib, "==", eq, f32, f64);
|
||||
reg_op!(lib, "!=", ne, f32, f64);
|
||||
}
|
||||
|
||||
// `&&` and `||` are treated specially as they short-circuit.
|
||||
// They are implemented as special `Expr` instances, not function calls.
|
||||
//reg_op!(lib, "||", or, bool);
|
||||
//reg_op!(lib, "&&", and, bool);
|
||||
|
||||
reg_binary(lib, "|", or, map);
|
||||
reg_binary(lib, "&", and, map);
|
||||
reg_unary(lib, "!", not, map);
|
||||
}
|
||||
}
|
75
src/packages/map_basic.rs
Normal file
75
src/packages/map_basic.rs
Normal file
@@ -0,0 +1,75 @@
|
||||
use super::{
|
||||
create_new_package, reg_binary, reg_binary_mut, reg_unary_mut, Package, PackageLibrary,
|
||||
PackageLibraryStore,
|
||||
};
|
||||
|
||||
use crate::any::Dynamic;
|
||||
use crate::engine::Map;
|
||||
use crate::fn_register::map_dynamic as map;
|
||||
use crate::parser::INT;
|
||||
|
||||
use crate::stdlib::ops::Deref;
|
||||
|
||||
pub struct BasicMapPackage(PackageLibrary);
|
||||
|
||||
impl Deref for BasicMapPackage {
|
||||
type Target = PackageLibrary;
|
||||
|
||||
fn deref(&self) -> &PackageLibrary {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Package for BasicMapPackage {
|
||||
fn new() -> Self {
|
||||
let mut pkg = create_new_package();
|
||||
Self::init(&mut pkg);
|
||||
Self(pkg.into())
|
||||
}
|
||||
|
||||
fn get(&self) -> PackageLibrary {
|
||||
self.0.clone()
|
||||
}
|
||||
|
||||
fn init(lib: &mut PackageLibraryStore) {
|
||||
// Register map functions
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
{
|
||||
reg_binary_mut(
|
||||
lib,
|
||||
"has",
|
||||
|map: &mut Map, prop: String| map.contains_key(&prop),
|
||||
map,
|
||||
);
|
||||
reg_unary_mut(lib, "len", |map: &mut Map| map.len() as INT, map);
|
||||
reg_unary_mut(lib, "clear", |map: &mut Map| map.clear(), map);
|
||||
reg_binary_mut(
|
||||
lib,
|
||||
"remove",
|
||||
|x: &mut Map, name: String| x.remove(&name).unwrap_or_else(|| Dynamic::from_unit()),
|
||||
map,
|
||||
);
|
||||
reg_binary_mut(
|
||||
lib,
|
||||
"mixin",
|
||||
|map1: &mut Map, map2: Map| {
|
||||
map2.into_iter().for_each(|(key, value)| {
|
||||
map1.insert(key, value);
|
||||
});
|
||||
},
|
||||
map,
|
||||
);
|
||||
reg_binary(
|
||||
lib,
|
||||
"+",
|
||||
|mut map1: Map, map2: Map| {
|
||||
map2.into_iter().for_each(|(key, value)| {
|
||||
map1.insert(key, value);
|
||||
});
|
||||
map1
|
||||
},
|
||||
map,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
154
src/packages/math_basic.rs
Normal file
154
src/packages/math_basic.rs
Normal file
@@ -0,0 +1,154 @@
|
||||
use super::{
|
||||
create_new_package, reg_binary, reg_unary, Package, PackageLibrary, PackageLibraryStore,
|
||||
};
|
||||
|
||||
use crate::fn_register::{map_dynamic as map, map_result as result};
|
||||
use crate::parser::INT;
|
||||
use crate::result::EvalAltResult;
|
||||
use crate::token::Position;
|
||||
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
use crate::parser::FLOAT;
|
||||
|
||||
use crate::stdlib::{i32, i64, ops::Deref};
|
||||
|
||||
#[cfg(feature = "only_i32")]
|
||||
const MAX_INT: INT = i32::MAX;
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
const MAX_INT: INT = i64::MAX;
|
||||
|
||||
pub struct BasicMathPackage(PackageLibrary);
|
||||
|
||||
impl Deref for BasicMathPackage {
|
||||
type Target = PackageLibrary;
|
||||
|
||||
fn deref(&self) -> &PackageLibrary {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Package for BasicMathPackage {
|
||||
fn new() -> Self {
|
||||
let mut pkg = create_new_package();
|
||||
Self::init(&mut pkg);
|
||||
Self(pkg.into())
|
||||
}
|
||||
|
||||
fn get(&self) -> PackageLibrary {
|
||||
self.0.clone()
|
||||
}
|
||||
|
||||
fn init(lib: &mut PackageLibraryStore) {
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
{
|
||||
// Advanced math functions
|
||||
reg_unary(lib, "sin", |x: FLOAT| x.to_radians().sin(), map);
|
||||
reg_unary(lib, "cos", |x: FLOAT| x.to_radians().cos(), map);
|
||||
reg_unary(lib, "tan", |x: FLOAT| x.to_radians().tan(), map);
|
||||
reg_unary(lib, "sinh", |x: FLOAT| x.to_radians().sinh(), map);
|
||||
reg_unary(lib, "cosh", |x: FLOAT| x.to_radians().cosh(), map);
|
||||
reg_unary(lib, "tanh", |x: FLOAT| x.to_radians().tanh(), map);
|
||||
reg_unary(lib, "asin", |x: FLOAT| x.asin().to_degrees(), map);
|
||||
reg_unary(lib, "acos", |x: FLOAT| x.acos().to_degrees(), map);
|
||||
reg_unary(lib, "atan", |x: FLOAT| x.atan().to_degrees(), map);
|
||||
reg_unary(lib, "asinh", |x: FLOAT| x.asinh().to_degrees(), map);
|
||||
reg_unary(lib, "acosh", |x: FLOAT| x.acosh().to_degrees(), map);
|
||||
reg_unary(lib, "atanh", |x: FLOAT| x.atanh().to_degrees(), map);
|
||||
reg_unary(lib, "sqrt", |x: FLOAT| x.sqrt(), map);
|
||||
reg_unary(lib, "exp", |x: FLOAT| x.exp(), map);
|
||||
reg_unary(lib, "ln", |x: FLOAT| x.ln(), map);
|
||||
reg_binary(lib, "log", |x: FLOAT, base: FLOAT| x.log(base), map);
|
||||
reg_unary(lib, "log10", |x: FLOAT| x.log10(), map);
|
||||
reg_unary(lib, "floor", |x: FLOAT| x.floor(), map);
|
||||
reg_unary(lib, "ceiling", |x: FLOAT| x.ceil(), map);
|
||||
reg_unary(lib, "round", |x: FLOAT| x.ceil(), map);
|
||||
reg_unary(lib, "int", |x: FLOAT| x.trunc(), map);
|
||||
reg_unary(lib, "fraction", |x: FLOAT| x.fract(), map);
|
||||
reg_unary(lib, "is_nan", |x: FLOAT| x.is_nan(), map);
|
||||
reg_unary(lib, "is_finite", |x: FLOAT| x.is_finite(), map);
|
||||
reg_unary(lib, "is_infinite", |x: FLOAT| x.is_infinite(), map);
|
||||
|
||||
// Register conversion functions
|
||||
reg_unary(lib, "to_float", |x: INT| x as FLOAT, map);
|
||||
reg_unary(lib, "to_float", |x: f32| x as FLOAT, map);
|
||||
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
#[cfg(not(feature = "only_i64"))]
|
||||
{
|
||||
reg_unary(lib, "to_float", |x: i8| x as FLOAT, map);
|
||||
reg_unary(lib, "to_float", |x: u8| x as FLOAT, map);
|
||||
reg_unary(lib, "to_float", |x: i16| x as FLOAT, map);
|
||||
reg_unary(lib, "to_float", |x: u16| x as FLOAT, map);
|
||||
reg_unary(lib, "to_float", |x: i32| x as FLOAT, map);
|
||||
reg_unary(lib, "to_float", |x: u32| x as FLOAT, map);
|
||||
reg_unary(lib, "to_float", |x: i64| x as FLOAT, map);
|
||||
reg_unary(lib, "to_float", |x: u64| x as FLOAT, map);
|
||||
reg_unary(lib, "to_float", |x: i128| x as FLOAT, map);
|
||||
reg_unary(lib, "to_float", |x: u128| x as FLOAT, map);
|
||||
}
|
||||
}
|
||||
|
||||
reg_unary(lib, "to_int", |ch: char| ch as INT, map);
|
||||
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
#[cfg(not(feature = "only_i64"))]
|
||||
{
|
||||
reg_unary(lib, "to_int", |x: i8| x as INT, map);
|
||||
reg_unary(lib, "to_int", |x: u8| x as INT, map);
|
||||
reg_unary(lib, "to_int", |x: i16| x as INT, map);
|
||||
reg_unary(lib, "to_int", |x: u16| x as INT, map);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
{
|
||||
reg_unary(lib, "to_int", |x: i32| x as INT, map);
|
||||
reg_unary(lib, "to_int", |x: u64| x as INT, map);
|
||||
|
||||
#[cfg(feature = "only_i64")]
|
||||
reg_unary(lib, "to_int", |x: u32| x as INT, map);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
{
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
{
|
||||
reg_unary(
|
||||
lib,
|
||||
"to_int",
|
||||
|x: f32| {
|
||||
if x > (MAX_INT as f32) {
|
||||
return Err(EvalAltResult::ErrorArithmetic(
|
||||
format!("Integer overflow: to_int({})", x),
|
||||
Position::none(),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(x.trunc() as INT)
|
||||
},
|
||||
result,
|
||||
);
|
||||
reg_unary(
|
||||
lib,
|
||||
"to_int",
|
||||
|x: FLOAT| {
|
||||
if x > (MAX_INT as FLOAT) {
|
||||
return Err(EvalAltResult::ErrorArithmetic(
|
||||
format!("Integer overflow: to_int({})", x),
|
||||
Position::none(),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(x.trunc() as INT)
|
||||
},
|
||||
result,
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "unchecked")]
|
||||
{
|
||||
reg_unary(lib, "to_int", |x: f32| x as INT, map);
|
||||
reg_unary(lib, "to_int", |x: f64| x as INT, map);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
307
src/packages/mod.rs
Normal file
307
src/packages/mod.rs
Normal file
@@ -0,0 +1,307 @@
|
||||
use crate::any::{Dynamic, Variant};
|
||||
use crate::engine::{calc_fn_spec, FnAny, FnCallArgs, IteratorFn};
|
||||
use crate::result::EvalAltResult;
|
||||
use crate::token::Position;
|
||||
|
||||
use crate::stdlib::{
|
||||
any::{type_name, TypeId},
|
||||
boxed::Box,
|
||||
collections::HashMap,
|
||||
ops::Deref,
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
mod arithmetic;
|
||||
mod array_basic;
|
||||
mod iter_basic;
|
||||
mod logic;
|
||||
mod map_basic;
|
||||
mod math_basic;
|
||||
mod pkg_core;
|
||||
mod pkg_std;
|
||||
mod string_basic;
|
||||
mod string_more;
|
||||
mod time_basic;
|
||||
|
||||
pub use arithmetic::ArithmeticPackage;
|
||||
pub use array_basic::BasicArrayPackage;
|
||||
pub use iter_basic::BasicIteratorPackage;
|
||||
pub use logic::LogicPackage;
|
||||
pub use map_basic::BasicMapPackage;
|
||||
pub use math_basic::BasicMathPackage;
|
||||
pub use pkg_core::CorePackage;
|
||||
pub use pkg_std::StandardPackage;
|
||||
pub use string_basic::BasicStringPackage;
|
||||
pub use string_more::MoreStringPackage;
|
||||
pub use time_basic::BasicTimePackage;
|
||||
|
||||
pub trait Package: Deref {
|
||||
fn new() -> Self;
|
||||
fn init(lib: &mut PackageLibraryStore);
|
||||
fn get(&self) -> PackageLibrary;
|
||||
}
|
||||
|
||||
pub type PackageLibraryStore = (HashMap<u64, Box<FnAny>>, HashMap<TypeId, Box<IteratorFn>>);
|
||||
|
||||
#[cfg(not(feature = "sync"))]
|
||||
pub type PackageLibrary = Rc<PackageLibraryStore>;
|
||||
|
||||
#[cfg(feature = "sync")]
|
||||
pub type PackageLibrary = Arc<PackageLibraryStore>;
|
||||
|
||||
fn check_num_args(
|
||||
name: &str,
|
||||
num_args: usize,
|
||||
args: &mut FnCallArgs,
|
||||
pos: Position,
|
||||
) -> Result<(), Box<EvalAltResult>> {
|
||||
if args.len() != num_args {
|
||||
Err(Box::new(EvalAltResult::ErrorFunctionArgsMismatch(
|
||||
name.to_string(),
|
||||
num_args,
|
||||
args.len(),
|
||||
pos,
|
||||
)))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn create_new_package() -> PackageLibraryStore {
|
||||
(HashMap::new(), HashMap::new())
|
||||
}
|
||||
|
||||
fn reg_none<R>(
|
||||
lib: &mut PackageLibraryStore,
|
||||
fn_name: &'static str,
|
||||
|
||||
#[cfg(not(feature = "sync"))] func: impl Fn() -> R + 'static,
|
||||
#[cfg(feature = "sync")] func: impl Fn() -> R + Send + Sync + 'static,
|
||||
|
||||
#[cfg(not(feature = "sync"))] map_result: impl Fn(R, Position) -> Result<Dynamic, Box<EvalAltResult>>
|
||||
+ 'static,
|
||||
#[cfg(feature = "sync")] map_result: impl Fn(R, Position) -> Result<Dynamic, Box<EvalAltResult>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
) {
|
||||
let hash = calc_fn_spec(fn_name, ([] as [TypeId; 0]).iter().cloned());
|
||||
|
||||
let f = Box::new(move |args: &mut FnCallArgs, pos: Position| {
|
||||
check_num_args(fn_name, 0, args, pos)?;
|
||||
|
||||
let r = func();
|
||||
map_result(r, pos)
|
||||
});
|
||||
|
||||
lib.0.insert(hash, f);
|
||||
}
|
||||
|
||||
fn reg_unary<T: Variant + Clone, R>(
|
||||
lib: &mut PackageLibraryStore,
|
||||
fn_name: &'static str,
|
||||
|
||||
#[cfg(not(feature = "sync"))] func: impl Fn(T) -> R + 'static,
|
||||
#[cfg(feature = "sync")] func: impl Fn(T) -> R + Send + Sync + 'static,
|
||||
|
||||
#[cfg(not(feature = "sync"))] map_result: impl Fn(R, Position) -> Result<Dynamic, Box<EvalAltResult>>
|
||||
+ 'static,
|
||||
#[cfg(feature = "sync")] map_result: impl Fn(R, Position) -> Result<Dynamic, Box<EvalAltResult>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
) {
|
||||
//println!("register {}({})", fn_name, type_name::<T>());
|
||||
|
||||
let hash = calc_fn_spec(fn_name, [TypeId::of::<T>()].iter().cloned());
|
||||
|
||||
let f = Box::new(move |args: &mut FnCallArgs, pos: Position| {
|
||||
check_num_args(fn_name, 1, args, pos)?;
|
||||
|
||||
let mut drain = args.iter_mut();
|
||||
let x: &mut T = drain.next().unwrap().downcast_mut().unwrap();
|
||||
|
||||
let r = func(x.clone());
|
||||
map_result(r, pos)
|
||||
});
|
||||
|
||||
lib.0.insert(hash, f);
|
||||
}
|
||||
|
||||
fn reg_unary_mut<T: Variant + Clone, R>(
|
||||
lib: &mut PackageLibraryStore,
|
||||
fn_name: &'static str,
|
||||
|
||||
#[cfg(not(feature = "sync"))] func: impl Fn(&mut T) -> R + 'static,
|
||||
#[cfg(feature = "sync")] func: impl Fn(&mut T) -> R + Send + Sync + 'static,
|
||||
|
||||
#[cfg(not(feature = "sync"))] map_result: impl Fn(R, Position) -> Result<Dynamic, Box<EvalAltResult>>
|
||||
+ 'static,
|
||||
#[cfg(feature = "sync")] map_result: impl Fn(R, Position) -> Result<Dynamic, Box<EvalAltResult>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
) {
|
||||
//println!("register {}(&mut {})", fn_name, type_name::<T>());
|
||||
|
||||
let hash = calc_fn_spec(fn_name, [TypeId::of::<T>()].iter().cloned());
|
||||
|
||||
let f = Box::new(move |args: &mut FnCallArgs, pos: Position| {
|
||||
check_num_args(fn_name, 1, args, pos)?;
|
||||
|
||||
let mut drain = args.iter_mut();
|
||||
let x: &mut T = drain.next().unwrap().downcast_mut().unwrap();
|
||||
|
||||
let r = func(x);
|
||||
map_result(r, pos)
|
||||
});
|
||||
|
||||
lib.0.insert(hash, f);
|
||||
}
|
||||
|
||||
fn reg_binary<A: Variant + Clone, B: Variant + Clone, R>(
|
||||
lib: &mut PackageLibraryStore,
|
||||
fn_name: &'static str,
|
||||
|
||||
#[cfg(not(feature = "sync"))] func: impl Fn(A, B) -> R + 'static,
|
||||
#[cfg(feature = "sync")] func: impl Fn(A, B) -> R + Send + Sync + 'static,
|
||||
|
||||
#[cfg(not(feature = "sync"))] map_result: impl Fn(R, Position) -> Result<Dynamic, Box<EvalAltResult>>
|
||||
+ 'static,
|
||||
#[cfg(feature = "sync")] map_result: impl Fn(R, Position) -> Result<Dynamic, Box<EvalAltResult>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
) {
|
||||
//println!("register {}({}, {})", fn_name, type_name::<A>(), type_name::<B>());
|
||||
|
||||
let hash = calc_fn_spec(
|
||||
fn_name,
|
||||
[TypeId::of::<A>(), TypeId::of::<B>()].iter().cloned(),
|
||||
);
|
||||
|
||||
let f = Box::new(move |args: &mut FnCallArgs, pos: Position| {
|
||||
check_num_args(fn_name, 2, args, pos)?;
|
||||
|
||||
let mut drain = args.iter_mut();
|
||||
let x: &mut A = drain.next().unwrap().downcast_mut().unwrap();
|
||||
let y: &mut B = drain.next().unwrap().downcast_mut().unwrap();
|
||||
|
||||
let r = func(x.clone(), y.clone());
|
||||
map_result(r, pos)
|
||||
});
|
||||
|
||||
lib.0.insert(hash, f);
|
||||
}
|
||||
|
||||
fn reg_binary_mut<A: Variant + Clone, B: Variant + Clone, R>(
|
||||
lib: &mut PackageLibraryStore,
|
||||
fn_name: &'static str,
|
||||
|
||||
#[cfg(not(feature = "sync"))] func: impl Fn(&mut A, B) -> R + 'static,
|
||||
#[cfg(feature = "sync")] func: impl Fn(&mut A, B) -> R + Send + Sync + 'static,
|
||||
|
||||
#[cfg(not(feature = "sync"))] map_result: impl Fn(R, Position) -> Result<Dynamic, Box<EvalAltResult>>
|
||||
+ 'static,
|
||||
#[cfg(feature = "sync")] map_result: impl Fn(R, Position) -> Result<Dynamic, Box<EvalAltResult>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
) {
|
||||
//println!("register {}(&mut {}, {})", fn_name, type_name::<A>(), type_name::<B>());
|
||||
|
||||
let hash = calc_fn_spec(
|
||||
fn_name,
|
||||
[TypeId::of::<A>(), TypeId::of::<B>()].iter().cloned(),
|
||||
);
|
||||
|
||||
let f = Box::new(move |args: &mut FnCallArgs, pos: Position| {
|
||||
check_num_args(fn_name, 2, args, pos)?;
|
||||
|
||||
let mut drain = args.iter_mut();
|
||||
let x: &mut A = drain.next().unwrap().downcast_mut().unwrap();
|
||||
let y: &mut B = drain.next().unwrap().downcast_mut().unwrap();
|
||||
|
||||
let r = func(x, y.clone());
|
||||
map_result(r, pos)
|
||||
});
|
||||
|
||||
lib.0.insert(hash, f);
|
||||
}
|
||||
|
||||
fn reg_trinary<A: Variant + Clone, B: Variant + Clone, C: Variant + Clone, R>(
|
||||
lib: &mut PackageLibraryStore,
|
||||
fn_name: &'static str,
|
||||
|
||||
#[cfg(not(feature = "sync"))] func: impl Fn(A, B, C) -> R + 'static,
|
||||
#[cfg(feature = "sync")] func: impl Fn(A, B, C) -> R + Send + Sync + 'static,
|
||||
|
||||
#[cfg(not(feature = "sync"))] map_result: impl Fn(R, Position) -> Result<Dynamic, Box<EvalAltResult>>
|
||||
+ 'static,
|
||||
#[cfg(feature = "sync")] map_result: impl Fn(R, Position) -> Result<Dynamic, Box<EvalAltResult>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
) {
|
||||
//println!("register {}({}, {}, {})", fn_name, type_name::<A>(), type_name::<B>(), type_name::<C>());
|
||||
|
||||
let hash = calc_fn_spec(
|
||||
fn_name,
|
||||
[TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>()]
|
||||
.iter()
|
||||
.cloned(),
|
||||
);
|
||||
|
||||
let f = Box::new(move |args: &mut FnCallArgs, pos: Position| {
|
||||
check_num_args(fn_name, 3, args, pos)?;
|
||||
|
||||
let mut drain = args.iter_mut();
|
||||
let x: &mut A = drain.next().unwrap().downcast_mut().unwrap();
|
||||
let y: &mut B = drain.next().unwrap().downcast_mut().unwrap();
|
||||
let z: &mut C = drain.next().unwrap().downcast_mut().unwrap();
|
||||
|
||||
let r = func(x.clone(), y.clone(), z.clone());
|
||||
map_result(r, pos)
|
||||
});
|
||||
|
||||
lib.0.insert(hash, f);
|
||||
}
|
||||
|
||||
fn reg_trinary_mut<A: Variant + Clone, B: Variant + Clone, C: Variant + Clone, R>(
|
||||
lib: &mut PackageLibraryStore,
|
||||
fn_name: &'static str,
|
||||
|
||||
#[cfg(not(feature = "sync"))] func: impl Fn(&mut A, B, C) -> R + 'static,
|
||||
#[cfg(feature = "sync")] func: impl Fn(&mut A, B, C) -> R + Send + Sync + 'static,
|
||||
|
||||
#[cfg(not(feature = "sync"))] map_result: impl Fn(R, Position) -> Result<Dynamic, Box<EvalAltResult>>
|
||||
+ 'static,
|
||||
#[cfg(feature = "sync")] map_result: impl Fn(R, Position) -> Result<Dynamic, Box<EvalAltResult>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
) {
|
||||
//println!("register {}(&mut {}, {}, {})", fn_name, type_name::<A>(), type_name::<B>(), type_name::<C>());
|
||||
|
||||
let hash = calc_fn_spec(
|
||||
fn_name,
|
||||
[TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>()]
|
||||
.iter()
|
||||
.cloned(),
|
||||
);
|
||||
|
||||
let f = Box::new(move |args: &mut FnCallArgs, pos: Position| {
|
||||
check_num_args(fn_name, 3, args, pos)?;
|
||||
|
||||
let mut drain = args.iter_mut();
|
||||
let x: &mut A = drain.next().unwrap().downcast_mut().unwrap();
|
||||
let y: &mut B = drain.next().unwrap().downcast_mut().unwrap();
|
||||
let z: &mut C = drain.next().unwrap().downcast_mut().unwrap();
|
||||
|
||||
let r = func(x, y.clone(), z.clone());
|
||||
map_result(r, pos)
|
||||
});
|
||||
|
||||
lib.0.insert(hash, f);
|
||||
}
|
37
src/packages/pkg_core.rs
Normal file
37
src/packages/pkg_core.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
use super::arithmetic::ArithmeticPackage;
|
||||
use super::create_new_package;
|
||||
use super::iter_basic::BasicIteratorPackage;
|
||||
use super::logic::LogicPackage;
|
||||
use super::string_basic::BasicStringPackage;
|
||||
use super::{Package, PackageLibrary, PackageLibraryStore};
|
||||
|
||||
use crate::stdlib::ops::Deref;
|
||||
|
||||
pub struct CorePackage(PackageLibrary);
|
||||
|
||||
impl Deref for CorePackage {
|
||||
type Target = PackageLibrary;
|
||||
|
||||
fn deref(&self) -> &PackageLibrary {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Package for CorePackage {
|
||||
fn new() -> Self {
|
||||
let mut pkg = create_new_package();
|
||||
Self::init(&mut pkg);
|
||||
Self(pkg.into())
|
||||
}
|
||||
|
||||
fn init(lib: &mut PackageLibraryStore) {
|
||||
ArithmeticPackage::init(lib);
|
||||
LogicPackage::init(lib);
|
||||
BasicStringPackage::init(lib);
|
||||
BasicIteratorPackage::init(lib);
|
||||
}
|
||||
|
||||
fn get(&self) -> PackageLibrary {
|
||||
self.0.clone()
|
||||
}
|
||||
}
|
40
src/packages/pkg_std.rs
Normal file
40
src/packages/pkg_std.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
use super::array_basic::BasicArrayPackage;
|
||||
use super::map_basic::BasicMapPackage;
|
||||
use super::math_basic::BasicMathPackage;
|
||||
use super::pkg_core::CorePackage;
|
||||
use super::string_more::MoreStringPackage;
|
||||
use super::time_basic::BasicTimePackage;
|
||||
use super::{create_new_package, Package, PackageLibrary, PackageLibraryStore};
|
||||
|
||||
use crate::stdlib::ops::Deref;
|
||||
|
||||
pub struct StandardPackage(PackageLibrary);
|
||||
|
||||
impl Deref for StandardPackage {
|
||||
type Target = PackageLibrary;
|
||||
|
||||
fn deref(&self) -> &PackageLibrary {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Package for StandardPackage {
|
||||
fn new() -> Self {
|
||||
let mut pkg = create_new_package();
|
||||
Self::init(&mut pkg);
|
||||
Self(pkg.into())
|
||||
}
|
||||
|
||||
fn init(lib: &mut PackageLibraryStore) {
|
||||
CorePackage::init(lib);
|
||||
BasicMathPackage::init(lib);
|
||||
BasicArrayPackage::init(lib);
|
||||
BasicMapPackage::init(lib);
|
||||
BasicTimePackage::init(lib);
|
||||
MoreStringPackage::init(lib);
|
||||
}
|
||||
|
||||
fn get(&self) -> PackageLibrary {
|
||||
self.0.clone()
|
||||
}
|
||||
}
|
124
src/packages/string_basic.rs
Normal file
124
src/packages/string_basic.rs
Normal file
@@ -0,0 +1,124 @@
|
||||
use super::{
|
||||
create_new_package, reg_binary, reg_binary_mut, reg_none, reg_unary, reg_unary_mut, Package,
|
||||
PackageLibrary, PackageLibraryStore,
|
||||
};
|
||||
|
||||
use crate::engine::{Array, Map, FUNC_TO_STRING, KEYWORD_DEBUG, KEYWORD_PRINT};
|
||||
use crate::fn_register::map_dynamic as map;
|
||||
use crate::parser::INT;
|
||||
|
||||
use crate::stdlib::{
|
||||
fmt::{Debug, Display},
|
||||
format,
|
||||
ops::Deref,
|
||||
};
|
||||
|
||||
// Register print and debug
|
||||
fn to_debug<T: Debug>(x: &mut T) -> String {
|
||||
format!("{:?}", x)
|
||||
}
|
||||
fn to_string<T: Display>(x: &mut T) -> String {
|
||||
format!("{}", x)
|
||||
}
|
||||
fn format_map(x: &mut Map) -> String {
|
||||
format!("#{:?}", x)
|
||||
}
|
||||
|
||||
macro_rules! reg_op { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => {
|
||||
$(reg_unary_mut($lib, $op, $func::<$par>, map);)* };
|
||||
}
|
||||
|
||||
pub struct BasicStringPackage(PackageLibrary);
|
||||
|
||||
impl Deref for BasicStringPackage {
|
||||
type Target = PackageLibrary;
|
||||
|
||||
fn deref(&self) -> &PackageLibrary {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Package for BasicStringPackage {
|
||||
fn new() -> Self {
|
||||
let mut pkg = create_new_package();
|
||||
Self::init(&mut pkg);
|
||||
Self(pkg.into())
|
||||
}
|
||||
|
||||
fn get(&self) -> PackageLibrary {
|
||||
self.0.clone()
|
||||
}
|
||||
|
||||
fn init(lib: &mut PackageLibraryStore) {
|
||||
reg_op!(lib, KEYWORD_PRINT, to_string, String, INT, bool);
|
||||
reg_op!(lib, FUNC_TO_STRING, to_string, String, INT, bool);
|
||||
reg_op!(lib, KEYWORD_PRINT, to_string, String, char, String);
|
||||
reg_op!(lib, FUNC_TO_STRING, to_string, String, char, String);
|
||||
reg_none(lib, KEYWORD_PRINT, || "".to_string(), map);
|
||||
reg_unary(lib, KEYWORD_PRINT, |_: ()| "".to_string(), map);
|
||||
reg_unary(lib, FUNC_TO_STRING, |_: ()| "".to_string(), map);
|
||||
reg_op!(lib, KEYWORD_DEBUG, to_debug, String, INT, bool, ());
|
||||
reg_op!(lib, KEYWORD_DEBUG, to_debug, String, char, String);
|
||||
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
#[cfg(not(feature = "only_i64"))]
|
||||
{
|
||||
reg_op!(lib, KEYWORD_PRINT, to_string, String, i8, u8, i16, u16);
|
||||
reg_op!(lib, FUNC_TO_STRING, to_string, String, i8, u8, i16, u16);
|
||||
reg_op!(lib, KEYWORD_PRINT, to_string, String, i32, u32, i64, u64);
|
||||
reg_op!(lib, FUNC_TO_STRING, to_string, String, i32, u32, i64, u64);
|
||||
reg_op!(lib, KEYWORD_PRINT, to_string, String, i128, u128);
|
||||
reg_op!(lib, FUNC_TO_STRING, to_string, String, i128, u128);
|
||||
reg_op!(lib, KEYWORD_DEBUG, to_debug, String, i8, u8, i16, u16);
|
||||
reg_op!(lib, KEYWORD_DEBUG, to_debug, String, i32, u32, i64, u64);
|
||||
reg_op!(lib, KEYWORD_DEBUG, to_debug, String, i128, u128);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
{
|
||||
reg_op!(lib, KEYWORD_PRINT, to_string, String, f32, f64);
|
||||
reg_op!(lib, FUNC_TO_STRING, to_string, String, f32, f64);
|
||||
reg_op!(lib, KEYWORD_DEBUG, to_debug, String, f32, f64);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
{
|
||||
reg_op!(lib, KEYWORD_PRINT, to_debug, String, Array);
|
||||
reg_op!(lib, FUNC_TO_STRING, to_debug, String, Array);
|
||||
reg_op!(lib, KEYWORD_DEBUG, to_debug, String, Array);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
{
|
||||
reg_unary_mut(lib, KEYWORD_PRINT, format_map, map);
|
||||
reg_unary_mut(lib, FUNC_TO_STRING, format_map, map);
|
||||
reg_unary_mut(lib, KEYWORD_DEBUG, format_map, map);
|
||||
}
|
||||
|
||||
reg_binary(
|
||||
lib,
|
||||
"+",
|
||||
|mut s: String, ch: char| {
|
||||
s.push(ch);
|
||||
s
|
||||
},
|
||||
map,
|
||||
);
|
||||
reg_binary(
|
||||
lib,
|
||||
"+",
|
||||
|mut s: String, s2: String| {
|
||||
s.push_str(&s2);
|
||||
s
|
||||
},
|
||||
map,
|
||||
);
|
||||
reg_binary_mut(lib, "append", |s: &mut String, ch: char| s.push(ch), map);
|
||||
reg_binary_mut(
|
||||
lib,
|
||||
"append",
|
||||
|s: &mut String, add: String| s.push_str(&add),
|
||||
map,
|
||||
);
|
||||
}
|
||||
}
|
259
src/packages/string_more.rs
Normal file
259
src/packages/string_more.rs
Normal file
@@ -0,0 +1,259 @@
|
||||
use super::{
|
||||
create_new_package, reg_binary, reg_binary_mut, reg_trinary_mut, reg_unary, reg_unary_mut,
|
||||
Package, PackageLibrary, PackageLibraryStore,
|
||||
};
|
||||
|
||||
use crate::engine::Array;
|
||||
use crate::fn_register::map_dynamic as map;
|
||||
use crate::parser::INT;
|
||||
|
||||
use crate::stdlib::{fmt::Display, ops::Deref};
|
||||
|
||||
// Register string concatenate functions
|
||||
fn prepend<T: Display>(x: T, y: String) -> String {
|
||||
format!("{}{}", x, y)
|
||||
}
|
||||
fn append<T: Display>(x: String, y: T) -> String {
|
||||
format!("{}{}", x, y)
|
||||
}
|
||||
fn sub_string(s: &mut String, start: INT, len: INT) -> String {
|
||||
let offset = if s.is_empty() || len <= 0 {
|
||||
return "".to_string();
|
||||
} else if start < 0 {
|
||||
0
|
||||
} else if (start as usize) >= s.chars().count() {
|
||||
return "".to_string();
|
||||
} else {
|
||||
start as usize
|
||||
};
|
||||
|
||||
let chars: Vec<_> = s.chars().collect();
|
||||
|
||||
let len = if offset + (len as usize) > chars.len() {
|
||||
chars.len() - offset
|
||||
} else {
|
||||
len as usize
|
||||
};
|
||||
|
||||
chars[offset..][..len].into_iter().collect::<String>()
|
||||
}
|
||||
fn crop_string(s: &mut String, start: INT, len: INT) {
|
||||
let offset = if s.is_empty() || len <= 0 {
|
||||
s.clear();
|
||||
return;
|
||||
} else if start < 0 {
|
||||
0
|
||||
} else if (start as usize) >= s.chars().count() {
|
||||
s.clear();
|
||||
return;
|
||||
} else {
|
||||
start as usize
|
||||
};
|
||||
|
||||
let chars: Vec<_> = s.chars().collect();
|
||||
|
||||
let len = if offset + (len as usize) > chars.len() {
|
||||
chars.len() - offset
|
||||
} else {
|
||||
len as usize
|
||||
};
|
||||
|
||||
s.clear();
|
||||
|
||||
chars[offset..][..len]
|
||||
.into_iter()
|
||||
.for_each(|&ch| s.push(ch));
|
||||
}
|
||||
|
||||
pub struct MoreStringPackage(PackageLibrary);
|
||||
|
||||
impl Deref for MoreStringPackage {
|
||||
type Target = PackageLibrary;
|
||||
|
||||
fn deref(&self) -> &PackageLibrary {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! reg_op { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => {
|
||||
$(reg_binary($lib, $op, $func::<$par>, map);)* };
|
||||
}
|
||||
|
||||
impl Package for MoreStringPackage {
|
||||
fn new() -> Self {
|
||||
let mut pkg = create_new_package();
|
||||
Self::init(&mut pkg);
|
||||
Self(pkg.into())
|
||||
}
|
||||
|
||||
fn get(&self) -> PackageLibrary {
|
||||
self.0.clone()
|
||||
}
|
||||
|
||||
fn init(lib: &mut PackageLibraryStore) {
|
||||
reg_op!(lib, "+", append, INT, bool, char);
|
||||
reg_binary_mut(lib, "+", |x: &mut String, _: ()| x.clone(), map);
|
||||
|
||||
reg_op!(lib, "+", prepend, INT, bool, char);
|
||||
reg_binary(lib, "+", |_: (), y: String| y, map);
|
||||
|
||||
#[cfg(not(feature = "only_i32"))]
|
||||
#[cfg(not(feature = "only_i64"))]
|
||||
{
|
||||
reg_op!(lib, "+", append, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
reg_op!(lib, "+", prepend, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
{
|
||||
reg_op!(lib, "+", append, f32, f64);
|
||||
reg_op!(lib, "+", prepend, f32, f64);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_index"))]
|
||||
{
|
||||
reg_binary(lib, "+", |x: String, y: Array| format!("{}{:?}", x, y), map);
|
||||
reg_binary(lib, "+", |x: Array, y: String| format!("{:?}{}", x, y), map);
|
||||
}
|
||||
|
||||
reg_unary_mut(lib, "len", |s: &mut String| s.chars().count() as INT, map);
|
||||
reg_binary_mut(
|
||||
lib,
|
||||
"contains",
|
||||
|s: &mut String, ch: char| s.contains(ch),
|
||||
map,
|
||||
);
|
||||
reg_binary_mut(
|
||||
lib,
|
||||
"contains",
|
||||
|s: &mut String, find: String| s.contains(&find),
|
||||
map,
|
||||
);
|
||||
reg_trinary_mut(
|
||||
lib,
|
||||
"index_of",
|
||||
|s: &mut String, ch: char, start: INT| {
|
||||
let start = if start < 0 {
|
||||
0
|
||||
} else if (start as usize) >= s.chars().count() {
|
||||
return -1 as INT;
|
||||
} else {
|
||||
s.chars().take(start as usize).collect::<String>().len()
|
||||
};
|
||||
|
||||
s[start..]
|
||||
.find(ch)
|
||||
.map(|index| s[0..start + index].chars().count() as INT)
|
||||
.unwrap_or(-1 as INT)
|
||||
},
|
||||
map,
|
||||
);
|
||||
reg_binary_mut(
|
||||
lib,
|
||||
"index_of",
|
||||
|s: &mut String, ch: char| {
|
||||
s.find(ch)
|
||||
.map(|index| s[0..index].chars().count() as INT)
|
||||
.unwrap_or(-1 as INT)
|
||||
},
|
||||
map,
|
||||
);
|
||||
reg_trinary_mut(
|
||||
lib,
|
||||
"index_of",
|
||||
|s: &mut String, find: String, start: INT| {
|
||||
let start = if start < 0 {
|
||||
0
|
||||
} else if (start as usize) >= s.chars().count() {
|
||||
return -1 as INT;
|
||||
} else {
|
||||
s.chars().take(start as usize).collect::<String>().len()
|
||||
};
|
||||
|
||||
s[start..]
|
||||
.find(&find)
|
||||
.map(|index| s[0..start + index].chars().count() as INT)
|
||||
.unwrap_or(-1 as INT)
|
||||
},
|
||||
map,
|
||||
);
|
||||
reg_binary_mut(
|
||||
lib,
|
||||
"index_of",
|
||||
|s: &mut String, find: String| {
|
||||
s.find(&find)
|
||||
.map(|index| s[0..index].chars().count() as INT)
|
||||
.unwrap_or(-1 as INT)
|
||||
},
|
||||
map,
|
||||
);
|
||||
reg_unary_mut(lib, "clear", |s: &mut String| s.clear(), map);
|
||||
reg_binary_mut(lib, "append", |s: &mut String, ch: char| s.push(ch), map);
|
||||
reg_binary_mut(
|
||||
lib,
|
||||
"append",
|
||||
|s: &mut String, add: String| s.push_str(&add),
|
||||
map,
|
||||
);
|
||||
reg_trinary_mut(lib, "sub_string", sub_string, map);
|
||||
reg_binary_mut(
|
||||
lib,
|
||||
"sub_string",
|
||||
|s: &mut String, start: INT| sub_string(s, start, s.len() as INT),
|
||||
map,
|
||||
);
|
||||
reg_trinary_mut(lib, "crop", crop_string, map);
|
||||
reg_binary_mut(
|
||||
lib,
|
||||
"crop",
|
||||
|s: &mut String, start: INT| crop_string(s, start, s.len() as INT),
|
||||
map,
|
||||
);
|
||||
reg_binary_mut(
|
||||
lib,
|
||||
"truncate",
|
||||
|s: &mut String, len: INT| {
|
||||
if len >= 0 {
|
||||
let chars: Vec<_> = s.chars().take(len as usize).collect();
|
||||
s.clear();
|
||||
chars.into_iter().for_each(|ch| s.push(ch));
|
||||
} else {
|
||||
s.clear();
|
||||
}
|
||||
},
|
||||
map,
|
||||
);
|
||||
reg_trinary_mut(
|
||||
lib,
|
||||
"pad",
|
||||
|s: &mut String, len: INT, ch: char| {
|
||||
for _ in 0..s.chars().count() - len as usize {
|
||||
s.push(ch);
|
||||
}
|
||||
},
|
||||
map,
|
||||
);
|
||||
reg_trinary_mut(
|
||||
lib,
|
||||
"replace",
|
||||
|s: &mut String, find: String, sub: String| {
|
||||
let new_str = s.replace(&find, &sub);
|
||||
s.clear();
|
||||
s.push_str(&new_str);
|
||||
},
|
||||
map,
|
||||
);
|
||||
reg_unary_mut(
|
||||
lib,
|
||||
"trim",
|
||||
|s: &mut String| {
|
||||
let trimmed = s.trim();
|
||||
|
||||
if trimmed.len() < s.len() {
|
||||
*s = trimmed.to_string();
|
||||
}
|
||||
},
|
||||
map,
|
||||
);
|
||||
}
|
||||
}
|
126
src/packages/time_basic.rs
Normal file
126
src/packages/time_basic.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
use super::logic::{eq, gt, gte, lt, lte, ne};
|
||||
use super::{
|
||||
create_new_package, reg_binary, reg_none, reg_unary, Package, PackageLibrary,
|
||||
PackageLibraryStore,
|
||||
};
|
||||
|
||||
use crate::fn_register::{map_dynamic as map, map_result as result};
|
||||
use crate::parser::INT;
|
||||
|
||||
use crate::stdlib::{ops::Deref, time::Instant};
|
||||
|
||||
pub struct BasicTimePackage(PackageLibrary);
|
||||
|
||||
impl Deref for BasicTimePackage {
|
||||
type Target = PackageLibrary;
|
||||
|
||||
fn deref(&self) -> &PackageLibrary {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Package for BasicTimePackage {
|
||||
fn new() -> Self {
|
||||
let mut pkg = create_new_package();
|
||||
Self::init(&mut pkg);
|
||||
Self(pkg.into())
|
||||
}
|
||||
|
||||
fn get(&self) -> PackageLibrary {
|
||||
self.0.clone()
|
||||
}
|
||||
|
||||
fn init(lib: &mut PackageLibraryStore) {
|
||||
#[cfg(not(feature = "no_std"))]
|
||||
{
|
||||
// Register date/time functions
|
||||
reg_none(lib, "timestamp", || Instant::now(), map);
|
||||
|
||||
reg_binary(
|
||||
lib,
|
||||
"-",
|
||||
|ts1: Instant, ts2: Instant| {
|
||||
if ts2 > ts1 {
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
return Ok(-(ts2 - ts1).as_secs_f64());
|
||||
|
||||
#[cfg(feature = "no_float")]
|
||||
{
|
||||
let seconds = (ts2 - ts1).as_secs();
|
||||
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
{
|
||||
if seconds > (MAX_INT as u64) {
|
||||
return Err(EvalAltResult::ErrorArithmetic(
|
||||
format!(
|
||||
"Integer overflow for timestamp duration: {}",
|
||||
-(seconds as i64)
|
||||
),
|
||||
Position::none(),
|
||||
));
|
||||
}
|
||||
}
|
||||
return Ok(-(seconds as INT));
|
||||
}
|
||||
} else {
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
return Ok((ts1 - ts2).as_secs_f64());
|
||||
|
||||
#[cfg(feature = "no_float")]
|
||||
{
|
||||
let seconds = (ts1 - ts2).as_secs();
|
||||
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
{
|
||||
if seconds > (MAX_INT as u64) {
|
||||
return Err(EvalAltResult::ErrorArithmetic(
|
||||
format!(
|
||||
"Integer overflow for timestamp duration: {}",
|
||||
seconds
|
||||
),
|
||||
Position::none(),
|
||||
));
|
||||
}
|
||||
}
|
||||
return Ok(seconds as INT);
|
||||
}
|
||||
}
|
||||
},
|
||||
result,
|
||||
);
|
||||
}
|
||||
|
||||
reg_binary(lib, "<", lt::<Instant>, map);
|
||||
reg_binary(lib, "<=", lte::<Instant>, map);
|
||||
reg_binary(lib, ">", gt::<Instant>, map);
|
||||
reg_binary(lib, ">=", gte::<Instant>, map);
|
||||
reg_binary(lib, "==", eq::<Instant>, map);
|
||||
reg_binary(lib, "!=", ne::<Instant>, map);
|
||||
|
||||
reg_unary(
|
||||
lib,
|
||||
"elapsed",
|
||||
|timestamp: Instant| {
|
||||
#[cfg(not(feature = "no_float"))]
|
||||
return Ok(timestamp.elapsed().as_secs_f64());
|
||||
|
||||
#[cfg(feature = "no_float")]
|
||||
{
|
||||
let seconds = timestamp.elapsed().as_secs();
|
||||
|
||||
#[cfg(not(feature = "unchecked"))]
|
||||
{
|
||||
if seconds > (MAX_INT as u64) {
|
||||
return Err(EvalAltResult::ErrorArithmetic(
|
||||
format!("Integer overflow for timestamp.elapsed(): {}", seconds),
|
||||
Position::none(),
|
||||
));
|
||||
}
|
||||
}
|
||||
return Ok(seconds as INT);
|
||||
}
|
||||
},
|
||||
result,
|
||||
);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user