diff --git a/src/main.rs b/src/main.rs index 2695dfa..a2b36e1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,8 @@ use std::fmt; use std::fs; use std::usize; +use regex::Regex; + mod eval; struct Program { @@ -198,6 +200,39 @@ impl Program { } } + fn handle_if_statement(&mut self, arguments: String) { + let argument_vec: Vec<&str> = arguments.split(":").collect(); + + let condition = argument_vec[0]; + let success = argument_vec[1]; + let failure = argument_vec[2]; + + + let re = Regex::new(r"(?P\d+)(?P==|!=|>|<|>=|<=)(?P\d+)").unwrap(); + let caps = re.captures(condition).unwrap(); + let num1 = &caps["num1"]; + let operator = &caps["operator"]; + let num2 = &caps["num2"]; + + let meets_condition: bool; + + match operator { + "==" => meets_condition = num1 == num2, + "!=" => meets_condition = num1 != num2, + ">" => meets_condition = num1 > num2, + "<" => meets_condition = num1 < num2, + ">=" => meets_condition = num1 >= num2, + "<=" => meets_condition = num1 <= num2, + _ => panic!("SyntaxError: Unknown operator at opcode {}: {}", self.pc, operator) + }; + + if meets_condition { + self.parse(&(success.to_string())); + } else { + self.parse(&(failure.to_string())); + } + } + fn parse(&mut self, instruction: &String) { // Opcode is the first character, arguments are everything after the first char let opcode = instruction.chars().collect::>()[0]; @@ -213,6 +248,7 @@ impl Program { 'l' => self.add_var(&arguments), 'f' => self.add_func(&arguments), 'i' => self.run_external(arguments), + '?' => self.handle_if_statement(arguments), _ => panic!("SyntaxError at opcode {}: Unknown opcode {}", self.pc, opcode), } }