bfy/src/interpreter.rs

156 lines
4.7 KiB
Rust
Raw Normal View History

use std::io::{Write};
2022-10-07 19:54:49 +00:00
use std::usize;
use crate::arguments;
2022-10-07 18:17:21 +00:00
2022-10-07 19:54:49 +00:00
pub struct Interpreter {
pub cells: Vec<u8>,
2022-10-07 19:54:49 +00:00
pub pointer: usize,
pub array_size: usize,
pub bf_code: String,
brackets: Vec<BfCommand>,
2022-10-07 19:54:49 +00:00
pub features: Vec<arguments::Feature>,
}
2022-10-07 19:54:49 +00:00
impl Interpreter {
pub fn new(array_size: usize,
bf_code: Option<String>,
features: Vec<arguments::Feature>) -> Self {
Self {
cells: vec![0; array_size],
2022-10-07 19:54:49 +00:00
pointer: 0,
array_size,
bf_code: bf_code.unwrap_or_else(|| String::new()),
brackets: Vec::new(),
features,
}
}
pub fn run(&mut self, bf_code: Option<String>) -> Result<u32, (String, u32)> {
let bf_code = match bf_code {
Some(bf_code) => {
self.bf_code.push_str(&*bf_code);
bf_code
}
None => self.bf_code.clone()
};
2022-10-07 19:54:49 +00:00
match self.run_brainfuck_code(&bf_code) {
Ok(_) => Ok(0),
Err(e) => Err((e, 1)),
}
}
2022-10-07 19:54:49 +00:00
// +[>++<-]
fn iterate(&mut self, code: String) -> Result<(), String> {
while self.cells[self.pointer] != 0 {
self.run_brainfuck_code(&code)?;
}
Ok(())
}
fn run_brainfuck_code(&mut self, bf_code: &str) -> Result<(), String> {
for (i, ch) in bf_code.chars().enumerate() {
2022-10-07 19:54:49 +00:00
match BfCommand::from_char(ch, i) {
Some(cmd) => {
trace!("Executing command: {:?}", cmd);
self.execute(cmd)?
}
None => {
trace!("Skipping character: {}", ch);
}
}
}
Ok(())
}
fn execute(&mut self, cmd: BfCommand) -> Result<(), String> {
match cmd {
BfCommand::IncPtr => {
self.pointer += 1;
if self.pointer >= self.array_size {
if self.features.contains(&arguments::Feature::ReversePointer) {
self.pointer = 0;
} else {
return Err(format!("Pointer out of bounds: {}", self.pointer));
}
}
}
BfCommand::DecPtr => {
if self.pointer == 0 {
if self.features.contains(&arguments::Feature::ReversePointer) {
self.pointer = self.array_size - 1;
} else {
return Err(format!("Pointer out of bounds: {}", self.pointer));
}
} else {
self.pointer -= 1;
}
},
BfCommand::IncVal => {
self.cells[self.pointer] = self.cells[self.pointer].wrapping_add(1);
},
BfCommand::DecVal => {
self.cells[self.pointer] = self.cells[self.pointer].wrapping_sub(1);
},
BfCommand::Print => {
print!("{}", self.cells[self.pointer] as char);
std::io::stdout().flush().unwrap();
},
BfCommand::Read => {
let mut input = String::new();
// TODO: Handle errors, and read only one byte
std::io::stdin().read_line(&mut input).unwrap();
self.cells[self.pointer] = input.chars().next().unwrap() as u8;
},
BfCommand::LoopStart(i) => {
self.brackets.push(BfCommand::LoopStart(i));
},
BfCommand::LoopEnd(i) => {
let open_bracket = self.brackets.pop();
match open_bracket {
Some(BfCommand::LoopStart(j)) => {
if self.cells[self.pointer] != 0 {
let code = self.bf_code[j..i].to_string();
self.iterate(code)?;
2022-10-07 19:54:49 +00:00
}
},
_ => {
return Err(format!("Unmatched closing bracket at position: {}", i));
2022-10-07 19:54:49 +00:00
}
}
2022-10-07 19:54:49 +00:00
}
}
Ok(())
2022-10-07 19:54:49 +00:00
}
}
2022-10-07 19:54:49 +00:00
#[derive(Debug, PartialEq)]
enum BfCommand {
IncPtr,
DecPtr,
IncVal,
DecVal,
Print,
Read,
LoopStart(usize),
LoopEnd(usize),
2022-10-07 19:54:49 +00:00
}
impl BfCommand {
fn from_char(c: char, index: usize) -> Option<BfCommand> {
match c {
'>' => Some(BfCommand::IncPtr),
'<' => Some(BfCommand::DecPtr),
'+' => Some(BfCommand::IncVal),
'-' => Some(BfCommand::DecVal),
'.' => Some(BfCommand::Print),
',' => Some(BfCommand::Read),
'[' => Some(BfCommand::LoopStart(index)),
']' => Some(BfCommand::LoopEnd(index)),
2022-10-07 19:54:49 +00:00
_ => None,
}
}
}