5 use std::path::PathBuf;
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 HELP_TEXT : [&str ; 4] =
12 ["Type a postfix expression to evaluate.",
13 "Example: 4 5 + 12 -",
14 "Supported operators: +, -, *, /",
18 const HOMEDIR_NOT_FOUND : &'static str = "User home directory not found \
19 (missing environment?).";
21 const HISTORY_FILE_NOT_FOUND : &'static str = "History file not found.";
23 const SAVE_HISTORY_ERROR : &'static str = "Unable to save command history!";
25 const ERROR : &'static str = "Error";
26 const ERROR_HELP : &'static str = "Type ? or h or H for help";
28 // Describe an operator - one of add, subtract, multiply or divide
36 // structure to hold an expression in the stack
41 // function to compute a result by popping the stack and
42 // pushing back the result
43 fn get_result (t : &mut Vec<Expression>, op : Operator) -> Result<f32,String> {
44 // pop the stack for last operand
45 // if nothing - panic with error
48 return Err (ILLEGAL_EXP.to_string());
50 // pop the stack for the first operand
51 // if nothing - panic with error
54 return Err (ILLEGAL_EXP.to_string());
57 let num1 = n1.unwrap().value;
58 let num2 = n2.unwrap().value;
60 // depending on the operation, set the result
63 t.push (Expression{value: num2 + num1});
67 t.push (Expression{value: num2 - num1});
71 t.push (Expression{value: num2 * num1});
75 t.push (Expression{value: num2 / num1});
81 // evaluation function
82 fn evaluate (expr : &str, match_num : ®ex::Regex) -> Result<f32,String> {
83 let mut ops = Vec::<Expression>::new ();
84 // tokenize the individual words by splitting at whitespace
85 let words = expr.split_whitespace ();
87 // iterate over the words
90 // if the word matches one of +, -, *, / then push it on the stack
91 // and immediately evaluate the expression by popping the operator
92 // and the last two operands and push the result back on to the stack
94 let m = get_result (&mut ops, Operator::ADD);
96 return Err (m.unwrap_err().to_string());
100 let m = get_result (&mut ops, Operator::SUB);
102 return Err (m.unwrap_err().to_string());
106 let m = get_result (&mut ops, Operator::MUL);
108 return Err (m.unwrap_err().to_string());
112 let m = get_result (&mut ops, Operator::DIV);
114 return Err (m.unwrap_err().to_string());
117 // if word matches a number, push it on to the stack
118 _ => if match_num.is_match (word) {
119 let num = word.parse ().unwrap ();
120 ops.push (Expression { value: num });
122 // if word doesn't match either operator or number then panic.
124 return Err (ERR_PARSING_NOT_MATCH.to_string());
130 // if the stack has more than one value, it means that the postfix
131 // expression is not complete - so display the stack status
132 return Err (ERR_POSTFIX_INCOMPLETE.to_string());
134 // stack has only one item which is the result so display it
135 let res = ops[0].value;
140 // Single command mode - command line arguments mode - evaluate the expression
141 // given in the command line and quit
142 fn run_command_line (args : &Vec<String>, match_num : ®ex::Regex) {
143 let mut expr = String::new ();
145 // create the expression string to evaluate
146 for arg in args.iter() {
148 expr.push_str (&arg);
153 // evaluate the result
154 let res = evaluate (&expr, &match_num);
155 // if Result is OK then print the result in green
157 let restxt = format! ("{}", res.unwrap());
158 println! ("{}", restxt.green ());
160 // print the error in purple
161 let errtxt = format! ("{}: {}", ERROR,
163 eprintln! ("{}", errtxt.purple ());
167 // get the history file name as string - home dir + .evpfhistory
168 fn get_history_file () -> Result<String,String> {
169 // get the environment variable HOME
170 let home_path = env::var ("HOME");
171 // if not found, return an error
172 if home_path.is_err () {
173 return Err (HOMEDIR_NOT_FOUND.to_string());
175 // build the path for the history file i.e. homedir + .evpfhistory in
176 // platform independent way
177 let mut hist_file = PathBuf::new ();
178 hist_file.push (home_path.unwrap());
179 hist_file.push (".evpfhistory");
181 // if cannot convert to string return error
182 if hist_file.to_str ().is_none () {
183 return Err (HOMEDIR_NOT_FOUND.to_string());
186 // return the history file path as a string
187 let hist_file_path = String::from (hist_file.to_str().unwrap());
188 return Ok (hist_file_path);
191 // Interactive mode - display the prompt and evaluate expressions entered into
192 // the prompt - until user quits
193 fn run_interactive_mode (match_num : ®ex::Regex) {
194 // get a line from input and evaluate it
195 let mut expr = String::new ();
197 let mut rl = Editor::<()>::new ();
199 // load the history file
200 let hist_file = get_history_file ();
201 // if unable to load the history file, display the appropriate error
202 if hist_file.is_err () {
203 eprintln! ("{}", &hist_file.unwrap_err());
205 if rl.load_history (&hist_file.unwrap ()).is_err () {
206 eprintln! ("{}", HISTORY_FILE_NOT_FOUND.purple());
209 // loop until a blank line is received
213 let line = rl.readline ("evpf> ");
217 let hist = line.unwrap ();
218 rl.add_history_entry (&hist);
219 expr.push_str (&hist);
221 if expr == "q" || expr == "Q" {
222 // quit if the expression is q or Qs
224 } else if expr == "?" || expr == "h" || expr == "H" {
226 for text in HELP_TEXT.iter() {
227 println! ("{}", text.cyan() );
231 } else if expr == "" {
232 // continue without proceeding
237 let res = evaluate (&expr, &match_num);
239 // if Result is OK then print the result in green
241 let restxt = format! ("{}", res.unwrap());
242 println! ("{}", restxt.green ());
244 // print the error in purple
245 let errtxt = format! ("{}: {}", ERROR,
247 eprintln! ("{}", errtxt.purple());
248 eprintln! ("{}", ERROR_HELP.purple());
252 let hist_file = get_history_file ();
253 if ! hist_file.is_err () {
254 if rl.save_history (&hist_file.unwrap()).is_err () {
255 eprintln! ("{}", SAVE_HISTORY_ERROR);
261 // collect the command line arguments - if any
262 let args : Vec<String> = env::args().collect ();
263 // regular expression to match a number
264 let match_num = Regex::new (r"^\-?\d+?\.*?\d*?$").unwrap ();
267 // if arguments are provided run in command line mode - i.e. print the
269 run_command_line (&args, &match_num);
272 // if arguments are not provided run in interactive mode -
273 // display a prompt and get the expression
274 // repeat until the user quits
275 run_interactive_mode (&match_num);