-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfvm.cpp
More file actions
84 lines (77 loc) · 2.01 KB
/
Copy pathbfvm.cpp
File metadata and controls
84 lines (77 loc) · 2.01 KB
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
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "Usage: bfvm <filename.bfp>" << std::endl;
return 1;
}
std::string filename = argv[1];
std::ifstream in(filename, std::ios::binary);
if (!in) {
std::cerr << "Error opening file: " << filename << std::endl;
return 1;
}
std::vector<char> code;
char ch;
while (in.get(ch)) {
code.push_back(ch);
}
in.close();
// Precompute matching brackets
std::vector<int> matching(code.size(), -1);
std::stack<int> stk;
for (size_t i = 0; i < code.size(); ++i) {
if (code[i] == 6) { // [
stk.push(i);
} else if (code[i] == 7) { // ]
if (!stk.empty()) {
int start = stk.top();
stk.pop();
matching[start] = i;
matching[i] = start;
}
}
}
// VM
const int DATA_SIZE = 30000;
std::vector<char> data(DATA_SIZE, 0);
size_t dp = 0;
size_t ip = 0;
while (ip < code.size()) {
char instr = code[ip];
switch (instr) {
case 0: // >
dp = (dp + 1) % DATA_SIZE;
break;
case 1: // <
dp = (dp - 1 + DATA_SIZE) % DATA_SIZE;
break;
case 2: // +
data[dp]++;
break;
case 3: // -
data[dp]--;
break;
case 4: // .
std::cout << data[dp];
break;
case 5: // ,
data[dp] = std::cin.get();
break;
case 6: // [
if (data[dp] == 0) {
ip = matching[ip];
}
break;
case 7: // ]
if (data[dp] != 0) {
ip = matching[ip];
}
break;
}
ip++;
}
return 0;
}