2019-03-15 15:11:31 +00:00
|
|
|
use configuration::EmptyConfiguration;
|
|
|
|
use error::Error;
|
|
|
|
use value::Value;
|
2016-11-16 16:12:26 +00:00
|
|
|
|
2019-03-15 15:11:31 +00:00
|
|
|
mod configuration;
|
|
|
|
mod error;
|
2016-11-16 16:12:26 +00:00
|
|
|
mod operator;
|
2019-03-15 15:11:31 +00:00
|
|
|
mod token;
|
2016-11-20 08:04:06 +00:00
|
|
|
mod tree;
|
2019-03-15 15:11:31 +00:00
|
|
|
mod value;
|
2019-03-15 11:42:18 +00:00
|
|
|
|
2019-03-15 15:11:31 +00:00
|
|
|
pub fn eval(string: &str) -> Result<Value, Error> {
|
|
|
|
tree::tokens_to_operator_tree(token::tokenize(string))?.eval(&EmptyConfiguration)
|
2017-02-13 00:20:53 +00:00
|
|
|
}
|
2016-11-16 16:12:26 +00:00
|
|
|
|
|
|
|
#[cfg(test)]
|
2019-03-15 15:11:31 +00:00
|
|
|
mod test {
|
|
|
|
use crate::{eval, value::Value};
|
2019-03-15 15:18:20 +00:00
|
|
|
use error::Error;
|
2016-11-16 16:12:26 +00:00
|
|
|
|
|
|
|
#[test]
|
2019-03-15 15:18:20 +00:00
|
|
|
fn test_unary_examples() {
|
2019-03-15 15:11:31 +00:00
|
|
|
assert_eq!(eval("3"), Ok(Value::Number(3.0)));
|
2019-03-15 15:18:20 +00:00
|
|
|
assert_eq!(eval("true"), Ok(Value::Boolean(true)));
|
|
|
|
assert_eq!(eval("false"), Ok(Value::Boolean(false)));
|
|
|
|
assert_eq!(eval("blub"), Err(Error::IdentifierNotFound));
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_binary_examples() {
|
2019-03-15 15:11:31 +00:00
|
|
|
assert_eq!(eval("1+3"), Ok(Value::Number(4.0)));
|
|
|
|
assert_eq!(eval("3+1"), Ok(Value::Number(4.0)));
|
|
|
|
assert_eq!(eval("3-5"), Ok(Value::Number(-2.0)));
|
|
|
|
assert_eq!(eval("5-3"), Ok(Value::Number(2.0)));
|
2019-03-15 15:18:20 +00:00
|
|
|
assert_eq!(eval("5 / 4"), Ok(Value::Number(1.25)));
|
|
|
|
assert_eq!(eval("5 *3"), Ok(Value::Number(15.0)));
|
2016-11-16 16:12:26 +00:00
|
|
|
}
|
2019-03-15 15:24:45 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_arithmetic_precedence_examples() {
|
|
|
|
assert_eq!(eval("1+3-2"), Ok(Value::Number(2.0)));
|
|
|
|
assert_eq!(eval("3+1*5"), Ok(Value::Number(8.0)));
|
|
|
|
assert_eq!(eval("2*3-5"), Ok(Value::Number(1.0)));
|
|
|
|
assert_eq!(eval("5-3/3"), Ok(Value::Number(4.0)));
|
|
|
|
assert_eq!(eval("5 / 4*2"), Ok(Value::Number(2.5)));
|
|
|
|
assert_eq!(eval("1-5 *3/15"), Ok(Value::Number(0.0)));
|
|
|
|
}
|
2016-11-16 16:12:26 +00:00
|
|
|
}
|