add parser, but machine still stuck in a loop

This commit is contained in:
2021-09-20 23:43:05 +02:00
parent 9f705f8389
commit da99c5b4d1
2 changed files with 58 additions and 2 deletions

View File

@@ -3,6 +3,7 @@ use std::fs;
use std::io::{stdin, stdout, BufReader, BufWriter, Read, Write};
use rbfckr::machine::Machine;
use rbfckr::parser::Parser;
fn main() {
// try to read from file
@@ -22,13 +23,17 @@ fn main() {
return;
}
};
// create brainfuck parser and turn the code into instructions
let mut parser = Parser::new(code);
parser.parse();
// create reader and writer objects
let mut reader: BufReader<Box<dyn Read>> = BufReader::new(Box::new(stdin()));
let mut writer: BufWriter<Box<dyn Write>> = BufWriter::new(Box::new(stdout()));
// create machine
let mut machine = Machine::new(code, &mut reader, &mut writer);
// create machine and load instructions
let mut machine = Machine::new(parser.instructions, &mut reader, &mut writer);
// execute code
machine.execute();

View File

@@ -0,0 +1,51 @@
use crate::instruction::InstructionType::{ Increment, Decrement, Leftshift, Rightshift, PutChar, GetChar, JumpIfZero, JumpIfNotZero};
use crate::instruction::{Instruction, InstructionType};
pub struct Parser {
code: Box<Vec<char>>,
code_length: usize,
position: usize,
pub instructions: Vec<Instruction>,
}
impl Parser {
pub fn new(code: String) -> Parser {
let code_filtered: Vec<char> = code.chars().filter(|c| !c.is_whitespace()).collect();
let code_length = &code_filtered.len();
Parser {
code: Box::new(code_filtered),
code_length: *code_length,
position: 0,
instructions: vec![],
}
}
pub fn parse(&mut self) {
while self.position < self.code_length {
let current = self.code[self.position];
match current {
'+' => self.load_instruction(Increment),
'-' => self.load_instruction(Decrement),
'<' => self.load_instruction(Leftshift),
'>' => self.load_instruction(Rightshift),
'.' => self.load_instruction(PutChar),
',' => self.load_instruction(GetChar),
'[' => self.load_instruction(JumpIfZero),
']' => self.load_instruction(JumpIfNotZero),
_ => (),
}
self.position += 1;
}
}
fn load_instruction(&mut self, itype: InstructionType) {
let instruction = Instruction {
itype,
argument: 0,
};
self.instructions.push(instruction);
}
}