~agam/SimpleCalc

f831da4f5a19abde51f5360b588af278c23dc934 — Agam Brahma 3 years ago 8600337
Working version
1 files changed, 25 insertions(+), 5 deletions(-)

M src/main.rs
M src/main.rs => src/main.rs +25 -5
@@ 1,3 1,4 @@
use std::io;

// See `peg` API at https://docs.rs/peg/0.7.0/peg/



@@ 37,29 38,48 @@ peg::parser!(

        rule term() -> i64
        = 
        n:factor() { n }
        /
        n1:factor() whitespace() op:operator() whitespace() n2:factor() {
            eval(&op, n1, n2)
        }
        /
        n:factor() { n }

        pub rule calculate() -> i64
        =
        n:term() { n }
        / 
        n1:term() whitespace() op:operator() whitespace() n2:term() {
            eval(&op, n1, n2)
        }
        / 
        n:term() { n }
    }
    );

fn main() {
 loop {
    println!("Enter an expression, or 'END' to quit: ");
    let mut input = String::new(); 
    io::stdin().read_line(&mut input)
    .expect("Error reading input!");

    let input = input.as_str().trim();

    if input == "END" {
        break;
    }

    let answer = calc_parser::calculate(input);
    match answer {
        Ok(v) => println!("Answer: {:?}", v),
        Err(e) => println!("Calculation error: {:?}", e),
    }
 } 
}

#[test]
fn test_basic_num() {
    assert_eq!(calc_parser::calculate("42"), Ok(42));
    assert_eq!(calc_parser::calculate("(4)"), Ok(4));
    // assert_eq!(calc_parser::calculate("2 + 4"), Ok(6));
    assert_eq!(calc_parser::calculate("2 + 4"), Ok(6));
    assert_eq!(calc_parser::calculate("3 * 8"), Ok(24));
    assert_eq!(calc_parser::calculate("3 - (4 / 2)"), Ok(1));
}