aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: f3f9d2da68e5a2f89ad16c65c7f47808695893f6 (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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use std::io::{ stdin };
use std::f64;

mod lex;
use crate::lex::*;

mod parse;
use crate::parse::*;

fn main() {
    loop {
        let mut input = String::new();
        stdin().read_line(&mut input).unwrap();

        let input = input.trim();
        let input = input.replace(" ", "");
        let input = autobalance_parens(&input[..]).unwrap();

        if input == "exit" {
            return
        }

        let lexed = lexer(&input[..]);
        let postfixed = to_postfix(lexed.unwrap());
        let evaled = eval_postfix(postfixed.unwrap());
        println!("ans: {}", evaled.unwrap());
        println!();
    }
}

fn autobalance_parens(input: &str) -> Result<String, String> {
    let mut balanced = String::from(input);
    let mut left_parens = 0;
    let mut right_parens = 0;
    for letter in input.chars() {
        if letter == '(' {
            left_parens += 1;
        } else if letter == ')' {
            right_parens += 1;
        }
    }

    if left_parens > right_parens {
        let extras = ")".repeat(left_parens - right_parens);
        balanced.push_str(&extras[..]);
        Ok(balanced)
    } else if left_parens < right_parens {
        return Err(format!("Mismatched parentheses"))
    } else {
        Ok(balanced)
    }
}