commit 88ddc6d810da9efced429b440fb580790d91bb80 Author: Marco Thomas Date: Tue Apr 22 09:14:07 2025 +0900 ft: initial impl diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..d77a0e1 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "brainfuck-rs" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..f9a42b2 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "brainfuck-rs" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..e88cc82 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,69 @@ +use std::io::{self, Read}; + +fn interpret(code: &str) { + let mut memory = [0 as u8; 10_000]; + let mut head = 0 as usize; + let mut pc = 0 as usize; + let mut loop_stack = Vec::new(); + + let code_bytes = code.as_bytes(); + while pc < code.len() { + match code_bytes[pc] as char { + '>' => head += 1, + '<' => head -= 1, + '+' => memory[head] += 1, + '-' => memory[head] -= 1, + '.' => println!("{}", memory[head]), + ',' => { + let mut input_buf = [0u8; 1]; + if io::stdin().read_exact(&mut input_buf).is_ok() { + memory[head] = input_buf[0]; + } + } + '[' => { + // loop start + if memory[pc] == 0 { + let mut count_brackets = 1; + + // find nested brackets + while count_brackets > 0 { + pc += 1; + if pc >= code_bytes.len() { + panic!("Missing closing loop!"); + } + match code_bytes[pc] as char { + // closing current loop + ']' => count_brackets -= 1, + // nested bracket + '[' => count_brackets += 1, + // ignore rest + _ => {} + } + } + } else { + // save pc to jump back to + loop_stack.push(pc); + } + } + ']' => { + // loop terminator + if memory[pc] != 0 { + if let Some(start_pc) = loop_stack.last() { + pc = *start_pc; + } + } else { + // loop done, continue normally + loop_stack.pop(); + } + } + _ => panic!("Invalid instruction"), + } + pc += 1; + } +} + +fn main() { + let code = "+++++++++[>++++++++<-]>."; + let hello_world = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."; + interpret(hello_world); +}