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
use crate::ast::Ast;
use crate::lexer::Lexer;
use crate::Error;
use hashbrown::HashMap;

/// Evaluate a single expression from `input`.
///
/// Returns `Ok(result)` if the evaluation is successful, or `Err(cause)` if
/// parsing or evaluating the expression failed.
///
/// # Example
///
/// ```
/// # use hashbrown::HashMap;
/// use cruncher::{eval};
///
/// assert_eq!(eval("45 - 2^3", None), Ok(37.0));
///
/// let mut context :HashMap<String,f64> = HashMap::new();
/// context.insert("a".into(), -5.0);
/// assert_eq!(eval("3 * a", &context), Ok(-15.0));
/// ```
pub fn eval<'a, C>(input: &str, context: C) -> Result<f64, Error>
where
    C: Into<Option<&'a HashMap<String, f64>>>,
{
    Expr::parse(input).and_then(|expr| expr.eval(context))
}

/// A parsed and optimized mathematical expression.
///
/// # Examples
/// ```
/// # use cruncher::{Expr};
/// # use hashbrown::HashMap;
/// let expr = Expr::parse("3 + 5 * 2").unwrap();
/// assert_eq!(expr.eval(None), Ok(13.0));
///
/// let mut context :HashMap<String,f64> = HashMap::new();
/// context.insert("a".into(), 42.0);
/// let expr = Expr::parse("-2 * a").unwrap();
/// assert_eq!(expr.eval(&context), Ok(-84.0));
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Expr {
    ast: Ast,
}

impl Expr {
    /// Parse the given mathematical `expression` into an `Expr`.
    ///
    /// # Examples
    /// ```
    /// # use cruncher::Expr;
    /// // A valid expression
    /// assert!(Expr::parse("3 + 5 * 2").is_ok());
    /// // an invalid expression
    /// assert!(Expr::parse("3eff + 5 * 2").is_err());
    /// ```
    pub fn parse(expression: &str) -> Result<Self, Error> {
        let mut lexer = Lexer::new(expression);

        match Ast::from_tokens(&mut lexer.parse()?, "") {
            Ok(ast) => Ok(Self { ast }),
            Err(err) => Err(err),
        }
    }

    /// Evaluate the expression in a given optional `context`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use cruncher::{Expr};
    /// # use hashbrown::HashMap;
    /// let expr = Expr::parse("3 + 5 * 2").unwrap();
    /// assert_eq!(expr.eval(None), Ok(13.0));
    ///
    /// let expr = Expr::parse("3 + a").unwrap();
    ///
    /// let mut context :HashMap<String,f64> = HashMap::new();
    /// context.insert("a".into(), -5.0);
    /// assert_eq!(expr.eval(&context), Ok(-2.0));
    /// context.insert("a".into(), 2.0);
    /// assert_eq!(expr.eval(&context), Ok(5.0));
    /// ```
    pub fn eval<'a, C>(&self, context: C) -> Result<f64, Error>
    where
        C: Into<Option<&'a HashMap<String, f64>>>,
    {
        Self::inner_eval(&self.ast, context.into())
    }

    fn inner_eval(ast: &Ast, context: Option<&HashMap<String, f64>>) -> Result<f64, Error> {
        match *ast {
            Ast::Variable(ref name) => context
                // If we have a context
                .and_then(|c|
                    // and the context has a value for the variable name, use the value
                    c.get(name).and_then(|v| Some(v.to_owned())))
                // Otherwise, we return an error
                .ok_or_else(|| Error::NameError(format!("name '{}' is not defined", name))),
            Ast::Value(number) => Ok(number),
            Ast::Add(ref left, ref right) => {
                Ok(Self::inner_eval(left, context)? + Self::inner_eval(right, context)?)
            }
            Ast::Sub(ref left, ref right) => {
                Ok(Self::inner_eval(left, context)? - Self::inner_eval(right, context)?)
            }
            Ast::Mul(ref left, ref right) => {
                Ok(Self::inner_eval(left, context)? * Self::inner_eval(right, context)?)
            }
            Ast::Div(ref left, ref right) => {
                Ok(Self::inner_eval(left, context)? / Self::inner_eval(right, context)?)
            }
            Ast::Exp(ref left, ref right) => {
                Ok(Self::inner_eval(left, context)?.powf(Self::inner_eval(right, context)?))
            }
            Ast::Function(ref func, ref arg) => Ok(func(Self::inner_eval(arg, context)?)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::error::Error;

    #[test]
    fn parse() {
        let valid_expressions = [
            "3 + +5e67",
            "(3 + -5)*45",
            "(3. + 5.0)*\t\n45",
            "(3 + 5^5e-6)*45",
            "sin(34.0) ^ sqrt(28.0)",
            "abc[ty8789]",
        ];
        for expr in &valid_expressions {
            assert!(Expr::parse(expr).is_ok());
        }
    }

    #[test]
    fn eval() {
        let mut context: HashMap<String, f64> = HashMap::new();
        context.insert("a".into(), 1.0);
        context.insert("b".into(), 2.0);

        let eval_pairs = [
            ("3 + 5", None, 8.0),
            ("2 - 5", None, -3.0),
            ("2 * 5", None, 10.0),
            ("10 / 5", None, 2.0),
            ("2 ^ 3", None, 8.0),
            ("-3", None, -3.0),
            ("25 + -3", None, 22.0),
            ("25 - -3", None, 28.0),
            ("25 - -3", None, 28.0),
            ("3 + 5 * 2", None, 13.0),
            ("sqrt(9)", None, 3.0),
            ("sin(18.0) * 3", None, 3.0 * f64::sin(18.0)),
            ("2 * a", Some(&context), 2.0),
            ("(a + b)^2", Some(&context), 9.0),
        ];
        for eval_pair in &eval_pairs {
            assert_eq!(super::eval(eval_pair.0, eval_pair.1), Ok(eval_pair.2));
        }

        let result = super::eval("2 * z", &context);
        assert_eq!(
            result.err().unwrap().description(),
            "name 'z' is not defined"
        );
        let result = super::eval("2 * a", None);
        assert_eq!(
            result.err().unwrap().description(),
            "name 'a' is not defined"
        );
    }

    // use std::time::Instant;
    //
    // #[test]
    // fn bench() {
    //     let watch = Instant::now();
    //     let t = Expr::parse("(var1 + var2 * 3) / (2 + 3) - something").unwrap();
    //     let capacity = 5_000_000;
    //     let iterations = 5_000_000;
    //     let mut dicts = Vec::with_capacity(capacity);
    //     for i in 1..=iterations {
    //         let mut dict: HashMap<String, f64> = HashMap::with_capacity(3);
    //         dict.insert("var1".to_owned(), 10.0 + f64::from(i));
    //         dict.insert("var2".to_owned(), 20.0 + f64::from(i));
    //         dict.insert("something".to_owned(), 30.0 + f64::from(i));
    //         dicts.push(dict);
    //     }
    //     let watch = watch.elapsed();

    //     let mut results: Vec<f64> = Vec::with_capacity(capacity);

    //     let watch2 = Instant::now();
    //     for dict in &dicts {
    //         results.push(t.eval(dict).unwrap());
    //     }
    //     let watch2 = watch2.elapsed();

    //     println!("{}", results[0]);
    //     println!("{}", watch.as_millis());
    //     println!("{}", watch2.as_millis());
    // }
}