-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBrainFuckInterpreter.cpp
86 lines (79 loc) · 1.67 KB
/
BrainFuckInterpreter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include "BrainFuckInterpreter.h"
const std::set<char> BrainFuckInterpreter::legalChars = { '<', '>', ',', '.' ,'+', '-', '[', ']' };
BrainFuckInterpreter::BrainFuckInterpreter(CodeMem* code, Mem* memory, InputAbs* input)
{
this->code = code;
this->memory = memory;
this->input = input;
}
BrainFuckInterpreter::~BrainFuckInterpreter()
{
delete this->code;
delete this->memory;
delete this->input;
}
void BrainFuckInterpreter::readInput(const char* cArr, int size)
{
code->init();
for (size_t i = 0; i < size; i++)
{
char opcode = cArr[i];
if (legalChars.find(opcode) != legalChars.end())
{
this->code->push(opcode);
this->programSize++;
}
}
}
bool BrainFuckInterpreter::execute()
{
char opcode = this->code->get(programCounter);
switch (opcode)
{
case '>':
pointerMem++;
break;
case '<':
pointerMem--;
if (pointerMem < 0)
{
pointerMem = memory->maxPointerValue();
}
break;
case '+':
this->memory->inc(pointerMem);
break;
case '-':
this->memory->dec(pointerMem);
break;
case '[':
this->stack.push(this->programCounter);
break;
case ']':
{
int pointer = this->stack.top();
this->stack.pop();
if (this->memory->get(this->pointerMem) != 0)
{
// it adding one after switch case
this->programCounter = pointer - 1;
}
break;
}
case ',':
this->memory->set(this->pointerMem, this->input->readChar());
break;
case '.':
this->input->writeChar(this->memory->get(this->pointerMem));
break;
default:
throw UnknownOpcode(opcode);
break;
}
programCounter++;
if (programCounter >= this->programSize)
{
return false;
}
return true;
}