7 const ILLEGAL_EXP : &'static str = "Illegal Expression";
8 const ERR_PARSING_NOT_MATCH : &'static str = "Error parsing expression! \
9 Must be a number or operator (+,-,* or /)";
10 const ERR_POSTFIX_INCOMPLETE : &'static str = "Postfix expression incomplete!";
11 const ERR_FLUSHING : &'static str = "Error flushing!";
12 const ERR_READING_LINE : &'static str = "Error reading line!";
13 const HELP_TEXT : [&str ; 4] =
14 ["Type an expression in postfix style to evaluate.",
15 "Example: 4 5 + 12 -",
16 "Supported operators: +, -, *, /",
20 const RESULT : &'static str = "Result";
21 const ERROR : &'static str = "Error";
22 const ERROR_HELP : &'static str = "Type ? or h or H for help";
24 // Describe an operator - one of add, subtract, multiply or divide
32 // structure to hold an expression in the stack
37 // function to compute a result by popping the stack and
38 // pushing back the result
39 fn get_result (t : &mut Vec<Expression>, op : Operator) -> Result<f32,String> {
40 // pop the stack for last operand
41 // if nothing - panic with error
44 return Err (ILLEGAL_EXP.to_string());
46 // pop the stack for the first operand
47 // if nothing - panic with error
50 return Err (ILLEGAL_EXP.to_string());
53 let num1 = n1.unwrap().value;
54 let num2 = n2.unwrap().value;
56 // depending on the operation, set the result
59 t.push (Expression{value: num2 + num1});
63 t.push (Expression{value: num2 - num1});
67 t.push (Expression{value: num2 * num1});
71 t.push (Expression{value: num2 / num1});
77 // evaluation function
78 fn evaluate (expr : &str, match_num : ®ex::Regex) -> Result<f32,String> {
79 let mut ops = Vec::<Expression>::new ();
80 // tokenize the individual words by splitting at whitespace
81 let words = expr.split_whitespace ();
83 // iterate over the words
86 // if the word matches one of +, -, *, / then push it on the stack
87 // and immediately evaluate the expression by popping the operator
88 // and the last two operands and push the result back on to the stack
90 let m = get_result (&mut ops, Operator::ADD);
92 return Err (m.unwrap_err().to_string());
96 let m = get_result (&mut ops, Operator::SUB);
98 return Err (m.unwrap_err().to_string());
102 let m = get_result (&mut ops, Operator::MUL);
104 return Err (m.unwrap_err().to_string());
108 let m = get_result (&mut ops, Operator::DIV);
110 return Err (m.unwrap_err().to_string());
113 // if word matches a number, push it on to the stack
114 _ => if match_num.is_match (word) {
115 let num = word.parse ().unwrap ();
116 ops.push (Expression { value: num });
118 // if word doesn't match either operator or number then panic.
120 return Err (ERR_PARSING_NOT_MATCH.to_string());
126 // if the stack has more than one value, it means that the postfix
127 // expression is not complete - so display the stack status
128 return Err (ERR_POSTFIX_INCOMPLETE.to_string());
130 // stack has only one item which is the result so display it
131 let res = ops[0].value;
138 let args : Vec<String> = env::args().collect ();
139 // regular expression to match a number
140 let match_num = Regex::new (r"^\d+?\.*?\d*?$").unwrap ();
143 // if arguments are provided run in command line mode - i.e. print the
145 let mut expr = String::new ();
147 // create the expression string to evaluate
148 for arg in args.iter() {
150 expr.push_str (&arg);
155 // evaluate the result
156 let res = evaluate (&expr, &match_num);
157 // if Result is OK then print the result in green
159 let restxt = format! ("{}: {}", RESULT,
161 println! ("{}", restxt.green ());
163 // print the error in purple
164 let errtxt = format! ("{}: {}", ERROR,
166 eprintln! ("{}", errtxt.purple ());
170 // if arguments are not provided run in interactive mode -
171 // display a prompt and get the expression
172 // repeat until the user quits
174 // get a line from input and evaluate it
175 let mut expr = String::new ();
177 // loop until a blank line is received
180 print!("{}", "evpf>".bold() );
181 io::stdout().flush ().expect (ERR_FLUSHING);
182 // read a line of text
183 io::stdin().read_line (&mut expr).expect (ERR_READING_LINE);
185 let expr = expr.trim ();
187 if expr == "q" || expr == "Q" {
188 // quit if the expression is q or Qs
190 } else if expr == "?" || expr == "h" || expr == "H" {
192 for text in HELP_TEXT.iter() {
193 println! ("{}", text.cyan() );
197 } else if expr == "" {
198 // continue without proceeding
203 let res = evaluate (&expr, &match_num);
205 // if Result is OK then print the result in green
207 let restxt = format! ("{}: {}", RESULT,
209 println! ("{}", restxt.green ());
211 // print the error in purple
212 let errtxt = format! ("{}: {}", ERROR,
214 eprintln! ("{}", errtxt.purple());
215 eprintln! ("{}", ERROR_HELP.purple());