Parsodus/examples/brainfuck/generator.cpp

63 lines
1.3 KiB
C++

#include "generator.h"
#include "instruction.h"
#include <iostream>
#include <cstring>
namespace bf {
void Generator::run() {
counter = 0;
std::memset(array, 0, sizeof(array));
while (!lbrackets.empty())
lbrackets.pop();
for(int instruct = 0; instruct < program.size(); instruct++) {
switch(program[instruct]) {
case Instruction::EMPTY: break;
case Instruction::PLUS:
array[counter]++;
break;
case Instruction::MINUS:
array[counter]--;
break;
case Instruction::GREATER:
if (++counter == 30000) {
std::cout << "Tried to access unavailable memory" << std::endl;
return;
} break;
case Instruction::LESS:
if (--counter == -1) {
std::cout << "Tried to access unavailable memory" << std::endl;
return;
} break;
case Instruction::POINT:
std::cout << (char)array[counter];
break;
case Instruction::COMMA:
char c;
std::cin >> c;
array[counter] = (int)c;
break;
case Instruction::LBRACKET:
lbrackets.push(instruct);
if (array[counter] == 0)
while (program[++instruct] != Instruction::RBRACKET) {}
break;
case Instruction::RBRACKET:
if (array[counter] != 0)
instruct = lbrackets.top();
else
lbrackets.pop();
break;
default: // Won't happen
break;
}
}
}
} // namespace bf