rhai 0.13.0

Embedded scripting for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use super::{reg_binary, reg_unary};

use crate::def_package;
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::{
    boxed::Box,
    fmt::Display,
    format,
    ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Rem, Shl, Shr, Sub},
};

// Checked add
fn add<T: Display + CheckedAdd>(x: T, y: T) -> Result<T, Box<EvalAltResult>> {
    x.checked_add(&y).ok_or_else(|| {
        Box::new(EvalAltResult::ErrorArithmetic(
            format!("Addition overflow: {} + {}", x, y),
            Position::none(),
        ))
    })
}
// Checked subtract
fn sub<T: Display + CheckedSub>(x: T, y: T) -> Result<T, Box<EvalAltResult>> {
    x.checked_sub(&y).ok_or_else(|| {
        Box::new(EvalAltResult::ErrorArithmetic(
            format!("Subtraction underflow: {} - {}", x, y),
            Position::none(),
        ))
    })
}
// Checked multiply
fn mul<T: Display + CheckedMul>(x: T, y: T) -> Result<T, Box<EvalAltResult>> {
    x.checked_mul(&y).ok_or_else(|| {
        Box::new(EvalAltResult::ErrorArithmetic(
            format!("Multiplication overflow: {} * {}", x, y),
            Position::none(),
        ))
    })
}
// Checked divide
fn div<T>(x: T, y: T) -> Result<T, Box<EvalAltResult>>
where
    T: Display + CheckedDiv + PartialEq + Zero,
{
    // Detect division by zero
    if y == T::zero() {
        return Err(Box::new(EvalAltResult::ErrorArithmetic(
            format!("Division by zero: {} / {}", x, y),
            Position::none(),
        )));
    }

    x.checked_div(&y).ok_or_else(|| {
        Box::new(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, Box<EvalAltResult>> {
    x.checked_neg().ok_or_else(|| {
        Box::new(EvalAltResult::ErrorArithmetic(
            format!("Negation overflow: -{}", x),
            Position::none(),
        ))
    })
}
// Checked absolute
fn abs<T: Display + CheckedNeg + PartialOrd + Zero>(x: T) -> Result<T, Box<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(|| {
            Box::new(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, Box<EvalAltResult>> {
    // Cannot shift by a negative number of bits
    if y < 0 {
        return Err(Box::new(EvalAltResult::ErrorArithmetic(
            format!("Left-shift by a negative number: {} << {}", x, y),
            Position::none(),
        )));
    }

    CheckedShl::checked_shl(&x, y as u32).ok_or_else(|| {
        Box::new(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, Box<EvalAltResult>> {
    // Cannot shift by a negative number of bits
    if y < 0 {
        return Err(Box::new(EvalAltResult::ErrorArithmetic(
            format!("Right-shift by a negative number: {} >> {}", x, y),
            Position::none(),
        )));
    }

    CheckedShr::checked_shr(&x, y as u32).ok_or_else(|| {
        Box::new(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, Box<EvalAltResult>> {
    x.checked_rem(&y).ok_or_else(|| {
        Box::new(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, Box<EvalAltResult>> {
    #[cfg(not(feature = "only_i32"))]
    {
        if y > (u32::MAX as INT) {
            Err(Box::new(EvalAltResult::ErrorArithmetic(
                format!("Integer raised to too large an index: {} ~ {}", x, y),
                Position::none(),
            )))
        } else if y < 0 {
            Err(Box::new(EvalAltResult::ErrorArithmetic(
                format!("Integer raised to a negative index: {} ~ {}", x, y),
                Position::none(),
            )))
        } else {
            x.checked_pow(y as u32).ok_or_else(|| {
                Box::new(EvalAltResult::ErrorArithmetic(
                    format!("Power overflow: {} ~ {}", x, y),
                    Position::none(),
                ))
            })
        }
    }

    #[cfg(feature = "only_i32")]
    {
        if y < 0 {
            Err(Box::new(EvalAltResult::ErrorArithmetic(
                format!("Integer raised to a negative index: {} ~ {}", x, y),
                Position::none(),
            )))
        } else {
            x.checked_pow(y as u32).ok_or_else(|| {
                Box::new(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, Box<EvalAltResult>> {
    // Raise to power that is larger than an i32
    if y > (i32::MAX as INT) {
        return Err(Box::new(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)
}

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);)* };
}

def_package!(crate:ArithmeticPackage:"Basic arithmetic", lib, {
    // 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);
    }
});