try to implement parser

This commit is contained in:
2021-09-20 14:04:07 +02:00
parent 48d90e6a2a
commit 3923b278fc
2 changed files with 22 additions and 8 deletions

View File

@@ -29,18 +29,22 @@ pub struct Machine<'a> {
} }
impl<'a> Machine<'a> { impl<'a> Machine<'a> {
pub fn new(code: Vec<Instruction>, input: &'a mut BufReader<Box<dyn Read>>, output: &'a mut BufWriter<Box<dyn Write>>) -> Self { pub fn new(code: &str, input: &'a mut BufReader<Box<dyn Read>>, output: &'a mut BufWriter<Box<dyn Write>>) -> Self {
Machine { Machine {
ip: 0, ip: 0,
mp: 0, mp: 0,
buf: [0;1], buf: [0; 1],
memory: [0; 50000], memory: [0; 50000],
code, code: parse(code),
input, input,
output, output,
} }
} }
pub fn parse(code: &str){
return;
}
pub fn execute(&mut self){ pub fn execute(&mut self){
// prevent ip from getting out of bounds // prevent ip from getting out of bounds
while self.ip < self.code.len() { while self.ip < self.code.len() {

View File

@@ -1,10 +1,11 @@
use std::env; use std::env;
use std::fs; use std::fs;
use std::io::{stdin, stdout, BufReader, Read}; use std::io::{stdin, stdout, BufReader, BufWriter, Read, Write};
use rbfckr::machine::Machine; use rbfckr::machine::Machine;
fn main() { fn main() {
// try to read from file
let file_name = match env::args().nth(1){ let file_name = match env::args().nth(1){
None => { None => {
println!("Usage: rbfckr <filename>"); println!("Usage: rbfckr <filename>");
@@ -12,14 +13,23 @@ fn main() {
} }
Some(file_name) => file_name, Some(file_name) => file_name,
}; };
let bf_code = match fs::read_to_string(file_name) { // try to copy brainfuck code to string
Ok(bf_code) => bf_code, let code = match fs::read_to_string(file_name) {
Ok(code) => code,
Err(e) => { Err(e) => {
println!("Error reading file: {}", e); println!("Error reading file: {}", e);
return; return;
} }
}; };
// 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);
println!("{}", bf_code); // execute code
machine.execute();
} }