aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/main.rs19
1 files changed, 13 insertions, 6 deletions
diff --git a/src/main.rs b/src/main.rs
index 50e2af8..a92a594 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -6,6 +6,9 @@ use crate::lex::*;
6mod parse; 6mod parse;
7use crate::parse::*; 7use crate::parse::*;
8 8
9mod error;
10use crate::error::{ CalcError, handler };
11
9use rustyline::error::ReadlineError; 12use rustyline::error::ReadlineError;
10use rustyline::Editor; 13use rustyline::Editor;
11 14
@@ -14,13 +17,16 @@ let mut rl = Editor::<()>::new();
14 if rl.load_history("history.txt").is_err() { 17 if rl.load_history("history.txt").is_err() {
15 println!("No previous history."); 18 println!("No previous history.");
16 } 19 }
17 loop { 20 'main: loop {
18 let readline = rl.readline("> "); 21 let readline = rl.readline("> ");
19 match readline { 22 match readline {
20 Ok(line) => { 23 Ok(line) => {
21 rl.add_history_entry(line.as_ref()); 24 rl.add_history_entry(line.as_ref());
22 let evaled = eval_math_expression(&line[..]).unwrap(); 25 let evaled = eval_math_expression(&line[..]);
23 println!("{}", evaled); 26 match evaled {
27 Ok(ans) => println!("{}", ans),
28 Err(e) => handler(e),
29 };
24 }, 30 },
25 Err(ReadlineError::Interrupted) => { 31 Err(ReadlineError::Interrupted) => {
26 println!("CTRL-C"); 32 println!("CTRL-C");
@@ -39,7 +45,7 @@ let mut rl = Editor::<()>::new();
39 rl.save_history("history.txt").unwrap(); 45 rl.save_history("history.txt").unwrap();
40} 46}
41 47
42fn autobalance_parens(input: &str) -> Result<String, String> { 48fn autobalance_parens(input: &str) -> Result<String, CalcError> {
43 let mut balanced = String::from(input); 49 let mut balanced = String::from(input);
44 let mut left_parens = 0; 50 let mut left_parens = 0;
45 let mut right_parens = 0; 51 let mut right_parens = 0;
@@ -56,16 +62,17 @@ fn autobalance_parens(input: &str) -> Result<String, String> {
56 balanced.push_str(&extras[..]); 62 balanced.push_str(&extras[..]);
57 Ok(balanced) 63 Ok(balanced)
58 } else if left_parens < right_parens { 64 } else if left_parens < right_parens {
59 return Err(format!("Mismatched parentheses")) 65 return Err(CalcError::Syntax("Mismatched parentheses!".into()))
60 } else { 66 } else {
61 Ok(balanced) 67 Ok(balanced)
62 } 68 }
63} 69}
64 70
65fn eval_math_expression(input: &str) -> Result<f64, String> { 71fn eval_math_expression(input: &str) -> Result<f64, CalcError> {
66 let input = autobalance_parens(&input[..])?; 72 let input = autobalance_parens(&input[..])?;
67 let lexed = lexer(&input[..])?; 73 let lexed = lexer(&input[..])?;
68 let postfixed = to_postfix(lexed)?; 74 let postfixed = to_postfix(lexed)?;
69 let evaled = eval_postfix(postfixed)?; 75 let evaled = eval_postfix(postfixed)?;
70 Ok(evaled) 76 Ok(evaled)
71} 77}
78