a branflakes interpreter i used to play with c++
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

59 lines
1.4 KiB

#include <iostream>
#include <stack>
#include <string>
#include <vector>
#include "brainfuck.hpp"
#include "error.hpp"
void Interpreter::run() {
data_tape = std::vector<char>(30000, 0); // tape size from esolangs
jump = std::stack<int>();
// gamers, let's get this bread
for (std::size_t i = 0; i < prog.size(); i++) {
int j = 0;
j = i;
if ((prog[i] == OpCode::LoopEnd) && (data_tape[ptr] != '\0')) { // we might have to make a jump!
i = jump.top() - 1; // account for i++?
}
processIndex(j);
}
if (!jump.empty()) { // levels of brackets don't match
throw ParseExcept(ErrType::BracketMismatch);
}
}
void Interpreter::processIndex(int index) {
switch(prog[index]) {
case OpCode::IncPtr:
++ptr;
break;
case OpCode::DecPtr:
if (--ptr < 0) ptr = 0; // no negative indices
break;
case OpCode::IncByte:
++data_tape[ptr];
break;
case OpCode::DecByte:
--data_tape[ptr];
break;
case OpCode::Write:
std::cout << data_tape[ptr];
break;
case OpCode::Read:
std::cin >> data_tape[ptr];
break;
case OpCode::LoopBegin:
jump.push(index);
break;
case OpCode::LoopEnd:
jump.pop();
break; // handled in run()
default:
break; // shouldn't be in here...
}
}