summaryrefslogtreecommitdiff
path: root/qexpr/src/lib.rs
blob: fa59c5c962e86d032ce432831756ff556c051aeb (plain)
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
extern crate exprparser;
extern crate qvalues;

use exprparser::*;
use qvalues::*;

use std::collections::HashMap;

fn evaluate_factor(f: &Factor, symbols: &HashMap<String, QValue>) -> Option<QValue> {
    match f {
        Factor::Value(v) => Some(QValue::new(*v)),
        Factor::Symbol(s) => symbols.get(s).map(|v| v.clone()),
        Factor::Expression(e) => evaluate(e, symbols),
    }
}

fn evaluate_term(t: &Term, symbols: &HashMap<String, QValue>) -> Option<QValue> {
    match t {
        Term::Mul(bf, bt) => Some(evaluate_factor(bf, symbols)? * evaluate_term(bt, symbols)?),
        Term::Div(bf, bt) => Some(evaluate_factor(bf, symbols)? / evaluate_term(bt, symbols)?),
        Term::Factor(bf) => evaluate_factor(bf, symbols),
    }
}

pub fn evaluate(e: &Expression, symbols: &HashMap<String, QValue>) -> Option<QValue> {
    match e {
        Expression::Add(bt, be) => evaluate_term(bt, symbols)? + evaluate(be, symbols)?,
        Expression::Sub(bt, be) => evaluate_term(bt, symbols)? + evaluate(be, symbols)?,
        Expression::Term(bt) => evaluate_term(bt, symbols),
    }
}