Implement opcode for if-statement
This commit is contained in:
parent
5fee22016c
commit
37d0919655
36
src/main.rs
36
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<num1>\d+)(?P<operator>==|!=|>|<|>=|<=)(?P<num2>\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::<Vec<char>>()[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),
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue