-
Notifications
You must be signed in to change notification settings - Fork 0
/
Executor.cpp
71 lines (69 loc) · 2.13 KB
/
Executor.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
//
// Created by Don Browne on 14/06/15.
//
#include <iostream>
#include "Executor.h"
void Executor::run() {
size_t length = program->length();
for (size_t pc = 0; pc < length; pc++) {
switch ((*program)[pc]) {
case Instruction::NEXT: {
state->next();
break;
}
case Instruction::PREV: {
state->prev();
break;
}
case Instruction::INC: {
state->incr();
break;
}
case Instruction::DEC: {
state->decr();
break;
}
case Instruction::PRINT: {
std::cout << state->get();
break;
}
case Instruction::READ: {
unsigned char inp;
std::cin >> inp;
state->assign(inp);
break;
}
case Instruction::FWD: {
if (state->get() == 0) {
size_t lookahead = pc;
// scan ahead till eof, or matching ] is found
while (lookahead < length && (*program)[lookahead++] != Instruction::BACK);
if (lookahead >= length) {
std::cout << "Reached end of program looking for matching ]" << std::endl;
exit(1);
} else {
pc = lookahead;
}
} else {
jump_stack->push(pc);
}
break;
}
case Instruction::BACK: {
if (jump_stack->empty()) {
std::cout << "Hit ] without matching [" << std::endl;
exit(1);
} else if (state->get() != 0) {
pc = jump_stack->top();
} else {
// if escaping from this loop, pop start from stack
jump_stack->pop();
}
break;
}
case Instruction::NOOP: {
break;
}
}
}
}