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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
#![doc(html_root_url = "https://docs.rs/exmex/0.7.1")]
//! Exmex is a fast **ex**tendable **m**athematical **ex**pression evaluator.  
//! ```rust
//! # use std::error::Error;
//! # fn main() -> Result<(), Box<dyn Error>> {
//! #
//! use exmex::eval_str;
//! assert!((eval_str("1.5 * ((cos(0) + 23.0) / 2.0)")? - 18.0).abs() < 1e-12);
//! #
//! #     Ok(())
//! # }
//! ```
//! For floats, we have a list of predifined operators containing
//! `^`, `*`, `/`, `+`, `-`, `sin`, `cos`, `tan`, `exp`, `log`, and `log2`. The full list is
//! defined in [`make_default_operators`](make_default_operators).
//!
//! ## Variables
//! For variables we can use strings that are not in the list of operators as shown in the following expression.
//! Additionally, variables should consist only of letters, numbers, and underscores. More precisely, they need to fit the
//! regular expression `r"^[a-zA-Z_]+[a-zA-Z_0-9]*"`.
//! Variables' values are passed as slices to [`eval`](FlatEx::eval).
//! ```rust
//! # use std::error::Error;
//! # fn main() -> Result<(), Box<dyn Error>> {
//! #
//! use exmex::{make_default_operators, parse};
//! let to_be_parsed = "log(z) + 2* (-z^2 + sin(4*y))";
//! let expr = parse::<f64>(to_be_parsed, &make_default_operators::<f64>())?;
//! assert!((expr.eval(&[2.5, 3.7])? - 14.992794866624788 as f64).abs() < 1e-12);
//! #
//! #     Ok(())
//! # }
//! ```
//! The `n`-th number in the slice corresponds to the `n`-th variable. Thereby only the
//! first occurence of the variables is relevant. In this example, we have `z=2.5` and `y=3.7`.
//! If variables are between curly brackets, they can have arbitrary names, e.g., 
//! `{456/549*(}`, `{x}`, and `{x+y}`  are valid variable names as shown in the following.
//! ```rust
//! # use std::error::Error;
//! # fn main() -> Result<(), Box<dyn Error>> {
//! #
//! use exmex::{make_default_operators, parse};
//! let x = 2.1f64;
//! let y = 0.1f64;
//! let to_be_parsed = "log({x+y})";  // {x+y} is the name of one(!) variable, not the sum of two 😕.
//! let expr = parse::<f64>(to_be_parsed, &make_default_operators::<f64>())?;
//! assert!((expr.eval(&[x+y])? - 2.2f64.ln()).abs() < 1e-12);
//! #
//! #     Ok(())
//! # }
//! ```
//! ## Extendability
//! Library users can also define a different set of operators as shown in the following.
//! ```rust
//! # use std::error::Error;
//! # fn main() -> Result<(), Box<dyn Error>> {
//! #
//! use exmex::{parse, BinOp, Operator};
//! let ops = [
//!     Operator {
//!         repr: "%",
//!         bin_op: Some(BinOp{op: |a: i32, b: i32| a % b, prio: 1}),
//!         unary_op: None,
//!     },
//!     Operator {
//!         repr: "/",
//!         bin_op: Some(BinOp{op: |a: i32, b: i32| a / b, prio: 1}),
//!         unary_op: None,
//!     },
//! ];
//! let to_be_parsed = "19 % 5 / 2 / a";
//! let expr = parse::<i32>(to_be_parsed, &ops)?;
//! assert_eq!(expr.eval(&[1])?, 2);
//! #
//! #     Ok(())
//! # }
//! ```
//!
//! ### Operators
//!
//! Operators are instances of the struct
//! [`Operator`](Operator) that has its representation in the field
//! [`repr`](Operator::repr), a binary and a unary operator of
//! type [`Option<BinOp<T>>`](Operator::bin_op) and
//! [`Option<fn(T) -> T>`](Operator::unary_op), respectively, as
//! members. [`BinOp`](BinOp)
//! contains in addition to the operator [`op`](BinOp::op) of type `fn(T, T) -> T` an
//! integer [`prio`](BinOp::prio). Operators
//! can be both, binary and unary such as `-` as defined in the list of default
//! operators. Note that we expect a unary operator to be always on the left of a
//! number.
//!
//! ### Data Types of Numbers
//!
//! You can use any type that implements [`Copy`](core::marker::Copy) and
//! [`FromStr`](std::str::FromStr). In case the representation of your data type in the
//! string does not match the number regex `r"\.?[0-9]+(\.[0-9]+)?"`, you have to pass a
//! suitable regex and use the function
//! [`parse_with_number_pattern`](parse::parse_with_number_pattern) instead of
//! [`parse`](parse::parse). Here is an example for `bool`.
//! ```rust
//! # use std::error::Error;
//! # fn main() -> Result<(), Box<dyn Error>> {
//! #
//! use exmex::{parse_with_number_pattern, BinOp, Operator};
//! let ops = [
//!     Operator {
//!         repr: "&&",
//!         bin_op: Some(BinOp{op: |a: bool, b: bool| a && b, prio: 1}),
//!         unary_op: None,
//!     },
//!     Operator {
//!         repr: "||",
//!         bin_op: Some(BinOp{op: |a: bool, b: bool| a || b, prio: 1}),
//!         unary_op: None,
//!     },
//!     Operator {
//!         repr: "!",
//!         bin_op: None,
//!         unary_op: Some(|a: bool| !a),
//!     },
//! ];
//! let to_be_parsed = "!(true && false) || (!false || (true && false))";
//! let expr = parse_with_number_pattern::<bool>(to_be_parsed, &ops, "true|false")?;
//! assert_eq!(expr.eval(&[])?, true);
//! #
//! #     Ok(())
//! # }
//! ```
//!
//! ## Priorities and Parentheses
//! In Exmex-land, unary operators always have higher priority than binary operators, e.g.,
//! `-2^2=4` instead of `-2^2=-4`. Moreover, we are not too strict regarding parentheses.
//! For instance `"---1"` will evalute to `-1`.
//! If you want to be on the safe side, we suggest using parentheses.
//!
//! ## Unicode
//! Unicode input strings are currently not supported 😕 but might be added in the 
//! future 😀.
//!

mod expression;
mod operators;
mod parse;
mod util;

pub use expression::FlatEx;

pub use parse::{parse, parse_with_default_ops, parse_with_number_pattern, ExParseError};

pub use operators::{make_default_operators, BinOp, Operator};

/// Parses a string, evaluates a string, and returns the resulting number.
///
/// # Errrors
///
/// In case the parsing went wrong, e.g., due to an invalid input string, an
/// [`ExParseError`](ExParseError) is returned.
///
pub fn eval_str(text: &str) -> Result<f64, ExParseError> {
    let flat_ex = parse_with_default_ops(text)?;
    Ok(flat_ex.eval(&[])?)
}

#[cfg(test)]
mod tests {

    use std::iter::once;

    use crate::{
        eval_str,
        operators::{make_default_operators, BinOp, Operator},
        parse::parse,
        parse_with_default_ops,
        util::{assert_float_eq_f32, assert_float_eq_f64},
        ExParseError,
    };

    #[test]
    fn test_readme() {
        fn readme() -> Result<f64, ExParseError> {
            let result = eval_str("sin(73)")?;
            assert_float_eq_f64(result, 73f64.sin());
            let expr = parse_with_default_ops::<f64>("2*x^3-4/z")?;
            let value = expr.eval(&[5.3, 0.5])?;
            assert_float_eq_f64(value, 289.75399999999996);
            Ok(value)
        }
        fn readme_int() -> Result<u32, ExParseError> {
            let ops = [
                Operator {
                    repr: "|",
                    bin_op: Some(BinOp {
                        op: |a: u32, b: u32| a | b,
                        prio: 0,
                    }),
                    unary_op: None,
                },
                Operator {
                    repr: "!",
                    bin_op: None,
                    unary_op: Some(|a: u32| !a),
                },
            ];
            let expr = parse::<u32>("!(a|b)", &ops)?;
            let result = expr.eval(&[0, 1])?;
            assert_eq!(result, u32::MAX - 1);
            Ok(result)
        }
        assert!(!readme().is_err());
        assert!(!readme_int().is_err());
    }
    #[test]
    fn test_variables_curly() {
        let operators = make_default_operators::<f64>();

        let to_be_parsed = "5*{x} + 4*log2(log(1.5-{gamma}))*({x}*-(tan(cos(sin(652.2-{gamma}))))) + 3*{x}";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[1.0, 0.0]).unwrap(), 11.429314405093656);
        let to_be_parsed = "2*(4*{x} + y^2)";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[2.0, 3.0]).unwrap(), 34.0);

        let to_be_parsed = "sin({myvwmlf4i58eo;w/-😕+sin(a)r_25})";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[1.5707963267948966]).unwrap(), 1.0);

        let to_be_parsed = "((sin({myvar_25})))";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[1.5707963267948966]).unwrap(), 1.0);
    }
    #[test]
    fn test_variables() {
        let operators = make_default_operators::<f64>();
        
        let to_be_parsed = " -(-(1+x))";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[1.0]).unwrap(), 2.0);

        let to_be_parsed = " sin(cos(-3.14159265358979*x))";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[1.0]).unwrap(), -0.841470984807896);

        let to_be_parsed = "5*sin(x * (4-y^(2-x) * 3 * cos(x-2*(y-1/(y-2*1/cos(sin(x*y))))))*x)";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[1.5, 0.2532]).unwrap(), -3.1164569260604176);


        let to_be_parsed = "5*x + 4*y + 3*x";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[1.0, 0.0]).unwrap(), 8.0);

        let to_be_parsed = "5*x + 4*y";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[0.0, 1.0]).unwrap(), 4.0);

        let to_be_parsed = "5*x + 4*y + x^2";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[2.5, 3.7]).unwrap(), 33.55);
        assert_float_eq_f64(expr.eval(&[12.0, 9.3]).unwrap(), 241.2);

        let to_be_parsed = "2*(4*x + y^2)";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[2.0, 3.0]).unwrap(), 34.0);

        let to_be_parsed = "sin(myvar_25)";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[1.5707963267948966]).unwrap(), 1.0);

        let to_be_parsed = "((sin(myvar_25)))";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[1.5707963267948966]).unwrap(), 1.0);

        let to_be_parsed = "(0 * myvar_25 + cos(x))";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(
            expr.eval(&[1.5707963267948966, 3.141592653589793]).unwrap(),
            -1.0,
        );

        let to_be_parsed = "(-x^2)";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[1.0]).unwrap(), 1.0);

        let to_be_parsed = "log(x) + 2* (-x^2 + sin(4*y))";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[2.5, 3.7]).unwrap(), 14.992794866624788);

        let to_be_parsed = "-sqrt(x)/(tanh(5-x)*2) + floor(2.4)* 1/asin(-x^2 + sin(4*sinh(y)))";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(
            expr.eval(&[2.5, 3.7]).unwrap(),
            -2.5f64.sqrt() / (2.5f64.tanh() * 2.0)
                + 2.0 / ((3.7f64.sinh() * 4.0).sin() + 2.5 * 2.5).asin(),
        );

        let to_be_parsed = "asin(sin(x)) + acos(cos(x)) + atan(tan(x))";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[0.5]).unwrap(), 1.5);

        let to_be_parsed = "sqrt(alpha^ceil(centauri))";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[2.0, 3.1]).unwrap(), 4.0);

        let to_be_parsed = "trunc(x) + fract(x)";
        let expr = parse(to_be_parsed, &operators).unwrap();
        assert_float_eq_f64(expr.eval(&[23422.52345]).unwrap(), 23422.52345);

    }

    #[test]
    fn test_custom_ops_invert() {
        let ops = vec![
            Operator {
                repr: "invert",
                bin_op: None,
                unary_op: Some(|a: f32| 1.0 / a),
            },
            Operator {
                repr: "sqrt",
                bin_op: None,
                unary_op: Some(|a: f32| a.sqrt()),
            },
        ];
        let expr = parse("sqrt(invert(a))", &ops).unwrap();
        assert_float_eq_f32(expr.eval(&[0.25]).unwrap(), 2.0);
    }

    #[test]
    fn test_custom_ops() {
        let custom_ops = [
            Operator {
                repr: "**",
                bin_op: Some(BinOp {
                    op: |a: f32, b| a.powf(b),
                    prio: 2,
                }),
                unary_op: None,
            },
            Operator {
                repr: "*",
                bin_op: Some(BinOp {
                    op: |a, b| a * b,
                    prio: 1,
                }),
                unary_op: None,
            },
            Operator {
                repr: "invert",
                bin_op: None,
                unary_op: Some(|a: f32| 1.0 / a),
            },
        ];
        let expr = parse("2**2*invert(3)", &custom_ops).unwrap();
        let val = expr.eval(&vec![]).unwrap();
        assert_float_eq_f32(val, 4.0 / 3.0);

        let zero_mapper = Operator {
            repr: "zer0",
            bin_op: Some(BinOp {
                op: |_: f32, _| 0.0,
                prio: 2,
            }),
            unary_op: Some(|_| 0.0),
        };
        let extended_operators = make_default_operators::<f32>()
            .iter()
            .cloned()
            .chain(once(zero_mapper))
            .collect::<Vec<_>>();
        let expr = parse("2^2*1/(berti) + zer0(4)", &extended_operators).unwrap();
        let val = expr.eval(&[4.0]).unwrap();
        assert_float_eq_f32(val, 1.0);
    }

    #[test]
    fn test_eval() {
        assert_float_eq_f64(eval_str(&"2*3^2").unwrap(), 18.0);
        assert_float_eq_f64(eval_str(&"-3^2").unwrap(), 9.0);
        assert_float_eq_f64(eval_str(&"11.3").unwrap(), 11.3);
        assert_float_eq_f64(eval_str(&"+11.3").unwrap(), 11.3);
        assert_float_eq_f64(eval_str(&"-11.3").unwrap(), -11.3);
        assert_float_eq_f64(eval_str(&"(-11.3)").unwrap(), -11.3);
        assert_float_eq_f64(eval_str(&"11.3+0.7").unwrap(), 12.0);
        assert_float_eq_f64(eval_str(&"31.3+0.7*2").unwrap(), 32.7);
        assert_float_eq_f64(eval_str(&"1.3+0.7*2-1").unwrap(), 1.7);
        assert_float_eq_f64(eval_str(&"1.3+0.7*2-1/10").unwrap(), 2.6);
        assert_float_eq_f64(eval_str(&"(1.3+0.7)*2-1/10").unwrap(), 3.9);
        assert_float_eq_f64(eval_str(&"1.3+(0.7*2)-1/10").unwrap(), 2.6);
        assert_float_eq_f64(eval_str(&"1.3+0.7*(2-1)/10").unwrap(), 1.37);
        assert_float_eq_f64(eval_str(&"1.3+0.7*(2-1/10)").unwrap(), 2.63);
        assert_float_eq_f64(eval_str(&"-1*(1.3+0.7*(2-1/10))").unwrap(), -2.63);
        assert_float_eq_f64(eval_str(&"-1*(1.3+(-0.7)*(2-1/10))").unwrap(), 0.03);
        assert_float_eq_f64(eval_str(&"-1*((1.3+0.7)*(2-1/10))").unwrap(), -3.8);
        assert_float_eq_f64(eval_str(&"sin(3.14159265358979)").unwrap(), 0.0);
        assert_float_eq_f64(eval_str(&"0-sin(3.14159265358979 / 2)").unwrap(), -1.0);
        assert_float_eq_f64(eval_str(&"-sin(3.14159265358979 / 2)").unwrap(), -1.0);
        assert_float_eq_f64(eval_str(&"3-(-1+sin(1.5707963267948966)*2)").unwrap(), 2.0);
        assert_float_eq_f64(
            eval_str(&"3-(-1+sin(cos(-3.14159265358979))*2)").unwrap(),
            5.6829419696157935,
        );
        assert_float_eq_f64(
            eval_str(&"-(-1+((-3.14159265358979)/5)*2)").unwrap(),
            2.256637061435916,
        );
        assert_float_eq_f64(eval_str(&"((2-4)/5)*2").unwrap(), -0.8);
        assert_float_eq_f64(
            eval_str(&"-(-1+(sin(-3.14159265358979)/5)*2)").unwrap(),
            1.0,
        );
        assert_float_eq_f64(
            eval_str(&"-(-1+sin(cos(-3.14159265358979)/5)*2)").unwrap(),
            1.3973386615901224,
        );
        assert_float_eq_f64(eval_str(&"-cos(3.14159265358979)").unwrap(), 1.0);
        assert_float_eq_f64(
            eval_str(&"1+sin(-cos(-3.14159265358979))").unwrap(),
            1.8414709848078965,
        );
        assert_float_eq_f64(
            eval_str(&"-1+sin(-cos(-3.14159265358979))").unwrap(),
            -0.1585290151921035,
        );
        assert_float_eq_f64(
            eval_str(&"-(-1+sin(-cos(-3.14159265358979)/5)*2)").unwrap(),
            0.6026613384098776,
        );
        assert_float_eq_f64(eval_str(&"sin(-(2))*2").unwrap(), -1.8185948536513634);
        assert_float_eq_f64(eval_str(&"sin(sin(2))*2").unwrap(), 1.5781446871457767);
        assert_float_eq_f64(eval_str(&"sin(-(sin(2)))*2").unwrap(), -1.5781446871457767);
        assert_float_eq_f64(eval_str(&"-sin(2)*2").unwrap(), -1.8185948536513634);
        assert_float_eq_f64(eval_str(&"sin(-sin(2))*2").unwrap(), -1.5781446871457767);
        assert_float_eq_f64(eval_str(&"sin(-sin(2)^2)*2").unwrap(), 1.4715655294841483);
        assert_float_eq_f64(
            eval_str(&"sin(-sin(2)*-sin(2))*2").unwrap(),
            1.4715655294841483,
        );
        assert_float_eq_f64(eval_str(&"--(1)").unwrap(), 1.0);
        assert_float_eq_f64(eval_str(&"--1").unwrap(), 1.0);
        assert_float_eq_f64(eval_str(&"----1").unwrap(), 1.0);
        assert_float_eq_f64(eval_str(&"---1").unwrap(), -1.0);
        assert_float_eq_f64(eval_str(&"3-(4-2/3+(1-2*2))").unwrap(), 2.666666666666666);
        assert_float_eq_f64(
            eval_str(&"log(log(2))*tan(2)+exp(1.5)").unwrap(),
            5.2825344122094045,
        );
        assert_float_eq_f64(
            eval_str(&"log(log2(2))*tan(2)+exp(1.5)").unwrap(),
            4.4816890703380645,
        );
        assert_float_eq_f64(eval_str(&"log2(2)").unwrap(), 1.0);
        assert_float_eq_f64(eval_str(&"2^log2(2)").unwrap(), 2.0);
        assert_float_eq_f64(eval_str(&"2^(cos(0)+2)").unwrap(), 8.0);
        assert_float_eq_f64(eval_str(&"2^cos(0)+2").unwrap(), 4.0);
    }

    #[test]
    fn test_error_handling() {
        assert!(eval_str(&"").is_err());
        assert!(eval_str(&"5+5-(").is_err());
        assert!(eval_str(&")2*(5+5)*3-2)*2").is_err());
        assert!(eval_str(&"2*(5+5))").is_err());
    }
}