This commit is contained in:
nora 2022-04-12 20:50:31 +02:00
parent 539d0e0502
commit 7b88c99039
7 changed files with 576 additions and 29 deletions

View file

@ -1,4 +1,4 @@
use crate::opts::IrInstr;
use crate::opts::Stmt;
use std::io::{Read, Write};
use std::num::Wrapping;
@ -6,29 +6,29 @@ const MEM_SIZE: usize = 32_000;
type Memory = [Wrapping<u8>; MEM_SIZE];
pub fn run(instrs: &[IrInstr<'_>]) {
pub fn run(instrs: &[Stmt<'_>]) {
let mut mem = [Wrapping(0u8); MEM_SIZE];
let mut ptr = 0;
execute(&mut mem, &mut ptr, instrs);
}
fn execute(mem: &mut Memory, ptr: &mut usize, instrs: &[IrInstr<'_>]) {
fn execute(mem: &mut Memory, ptr: &mut usize, instrs: &[Stmt<'_>]) {
for instr in instrs {
match instr {
IrInstr::Add(n) => {
Stmt::Add(n) => {
mem[*ptr] += n;
}
IrInstr::Sub(n) => {
Stmt::Sub(n) => {
mem[*ptr] -= n;
}
IrInstr::Right(n) => {
Stmt::Right(n) => {
*ptr += n;
if *ptr >= MEM_SIZE {
*ptr = 0;
}
}
IrInstr::Left(n) => {
Stmt::Left(n) => {
if *ptr < *n {
let diff = *n - *ptr;
*ptr = MEM_SIZE - 1 - diff;
@ -36,22 +36,22 @@ fn execute(mem: &mut Memory, ptr: &mut usize, instrs: &[IrInstr<'_>]) {
*ptr -= n;
}
}
IrInstr::Out => {
Stmt::Out => {
let char = mem[*ptr].0 as char;
print!("{char}");
std::io::stdout().flush().unwrap();
}
IrInstr::In => {
Stmt::In => {
let mut buf = [0; 1];
std::io::stdin().read_exact(&mut buf).unwrap();
mem[*ptr] = Wrapping(buf[0]);
}
IrInstr::Loop(body) => {
Stmt::Loop(body) => {
while mem[*ptr] != Wrapping(0) {
execute(mem, ptr, body);
}
}
IrInstr::SetNull => {
Stmt::SetNull => {
mem[*ptr] = Wrapping(0);
}
}