Browse Source

Add interpreter

master
garritfra 4 years ago
parent
commit
1d578880d9
  1. 25
      src/interpreter.rs
  2. 20
      src/main.rs

25
src/interpreter.rs

@ -0,0 +1,25 @@
use crate::instructions::Instruction;
use std::io::Read;
pub fn run(instructions: &Vec<Instruction>, tape: &mut Vec<u8>, ptr: &mut usize) {
for instruction in instructions {
match instruction {
Instruction::Increment => tape[*ptr] += 1,
Instruction::Decrement => tape[*ptr] -= 1,
Instruction::MoveRight => *ptr += 1,
Instruction::MoveLeft => *ptr -= 1,
Instruction::Print => print!("{}", tape[*ptr] as char),
Instruction::Loop(nested) => {
while tape[*ptr] != 0 {
run(&nested, tape, ptr)
}
}
Instruction::Read => {
let mut input: [u8; 1] = [0; 1];
std::io::stdin()
.read_exact(&mut input)
.expect("failed to read stdin");
}
}
}
}

20
src/main.rs

@ -1,17 +1,21 @@
mod instructions;
mod interpreter;
mod lexer;
mod parser;
use instructions::Instruction;
use instructions::OpCode;
fn main() {
let tokens: Vec<OpCode> = lexer::lex("+[-[.]-].");
let instructions: Vec<Instruction> = parser::parse(tokens);
for instruction in &instructions {
println!("{:?}", instruction);
let mut tape: Vec<u8> = vec![0; 1024];
for _i in 0..1024 {
tape.push(60);
}
let mut ptr = 512;
interpreter::run(
&parser::parse(lexer::lex("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
")),
&mut tape,
&mut ptr,
)
}
#[cfg(test)]

Loading…
Cancel
Save