First commitFirst commit..

This commit is contained in:
giomba 2023-03-10 08:19:15 +01:00
commit dab4ac069d
5 changed files with 157 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

7
Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "brainfuck-interpreter"
version = "0.1.0"

8
Cargo.toml Normal file
View File

@ -0,0 +1,8 @@
[package]
name = "brainfuck-interpreter"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

2
program.bf Normal file
View File

@ -0,0 +1,2 @@
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.

139
src/main.rs Normal file
View File

@ -0,0 +1,139 @@
use std::fs;
struct Machine {
ip: usize,
program: Vec<u8>,
mem: Vec<i8>,
ptr: usize,
}
impl Machine {
fn next(&mut self) {
self.ptr += 1;
}
fn prev(&mut self) {
self.ptr -= 1;
}
fn inc(&mut self) {
self.mem[self.ptr] += 1;
}
fn dec(&mut self) {
/*
if self.mem[self.ip] == 0 {
self.mem[self.ip] = 255;
return;
} else {*/
self.mem[self.ptr] -= 1;
}
fn out(&self) {
println!("OUT: {}", self.mem[self.ptr]);
}
fn load(&mut self, filename: &str) {
self.program = fs::read(filename).unwrap();
}
fn end_loop(&mut self) {
let mut nest = 1;
self.ip -= 2;
loop {
println!("] : {}", nest);
match self.program[self.ip] {
b']' => {
nest += 1;
}
b'[' => {
nest -= 1;
if nest == 0 {
self.ip += 1;
return;
}
}
_ => {}
}
self.ip -= 1;
}
}
fn begin_loop(&mut self) {
println!("BEGIN LOOP");
if self.mem[self.ptr] != 0 {
return;
}
println!("SKIP LOOP");
let mut nest = 1;
loop {
println!("[ : {}", nest);
match self.program[self.ip] {
b'[' => {
nest += 1;
}
b']' => {
nest -= 1;
if nest == 0 {
self.end_loop();
return;
}
}
_ => {}
}
self.ip += 1;
}
}
fn step(&mut self) {
let opcode = self.program[self.ip];
self.ip += 1;
println!(
"ip: {:02x}, opcode: {:02x}, ptr: {:02x}, memory: {:02x} {:02x} {:02x} {:02x}, ",
self.ip, opcode, self.ptr, self.mem[0], self.mem[1], self.mem[2], self.mem[3]
);
match opcode {
b'>' => {
self.next();
}
b'<' => {
self.prev();
}
b'+' => {
self.inc();
}
b'-' => {
self.dec();
}
b'.' => {
self.out();
}
b'[' => {
self.begin_loop();
}
b']' => {
self.end_loop();
}
_ => {
panic!("invalid opcode: {:02x}", opcode);
}
}
}
}
fn main() {
let mut machine = Machine {
ip: 0,
ptr: 0,
mem: Vec::new(),
program: Vec::new(),
};
machine.mem.resize(1024, 0);
machine.load("program.bf");
loop {
machine.step();
}
}