From da99c5b4d1217564d0475e865babef65690833e7 Mon Sep 17 00:00:00 2001 From: aaron Date: Mon, 20 Sep 2021 23:43:05 +0200 Subject: [PATCH] add parser, but machine still stuck in a loop --- src/main.rs | 9 +++++++-- src/parser.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/src/main.rs b/src/main.rs index 10aa188..31cbadf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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> = BufReader::new(Box::new(stdin())); let mut writer: BufWriter> = 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(); diff --git a/src/parser.rs b/src/parser.rs index e69de29..a32310f 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -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>, + code_length: usize, + position: usize, + pub instructions: Vec, +} + +impl Parser { + pub fn new(code: String) -> Parser { + let code_filtered: Vec = 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); + } +}