73 lines
1.8 KiB
Rust
73 lines
1.8 KiB
Rust
use std::fs;
|
|
use std::env;
|
|
use std::fmt;
|
|
use std::usize;
|
|
|
|
mod eval;
|
|
|
|
struct Program {
|
|
data: Vec<String>,
|
|
pc: usize
|
|
}
|
|
|
|
impl Program {
|
|
fn from_string(program: String) -> Program {
|
|
let mut op_list: Vec<String> = Vec::new();
|
|
|
|
for opcode in program.split(" ").collect::<Vec<&str>>() {
|
|
let mut new_op = opcode.to_owned();
|
|
new_op = new_op.replace("\n", "");
|
|
|
|
if new_op.len() != 0 {
|
|
op_list.push(new_op.to_owned());
|
|
}
|
|
}
|
|
return Program{ data: op_list, pc: 0 };
|
|
}
|
|
|
|
fn eval(&self, instruction: &String) {
|
|
let opcode = instruction.chars().collect::<Vec<char>>()[0];
|
|
let arguments = &instruction[1..];
|
|
|
|
match opcode {
|
|
'p' => println!("{}", arguments),
|
|
'a' => println!("{}", eval::do_math(arguments, '+')),
|
|
's' => println!("{}", eval::do_math(arguments, '-')),
|
|
'm' => println!("{}", eval::do_math(arguments, '*')),
|
|
'd' => println!("{}", eval::do_math(arguments, '/')),
|
|
_ => panic!("SyntaxError at opcode {}!", self.pc)
|
|
}
|
|
}
|
|
|
|
fn run(&mut self) {
|
|
println!("{}", self);
|
|
while self.pc < self.data.len() {
|
|
let instruction = &self.data[self.pc];
|
|
|
|
self.eval(instruction);
|
|
|
|
self.pc = self.pc + 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for Program {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
write!(f, "Program ({:?})", self.data)
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
|
|
let args: Vec<String> = env::args().collect();
|
|
if args.len() == 1 {
|
|
panic!("You must provide an argument!");
|
|
}
|
|
|
|
let filename = &args[1];
|
|
|
|
let contents = fs::read_to_string(filename).expect("Something went wrong reading the file");
|
|
let mut prog = Program::from_string(contents);
|
|
prog.run();
|
|
}
|