-
Notifications
You must be signed in to change notification settings - Fork 259
Expand file tree
/
Copy pathbf.cpp
More file actions
109 lines (91 loc) · 2.29 KB
/
bf.cpp
File metadata and controls
109 lines (91 loc) · 2.29 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <vector>
#include <string>
#include <map>
#include <fstream>
#include <libnotify.hpp>
#include <sstream>
#include <unistd.h>
using namespace std;
enum op_type { INC, MOVE, LOOP, PRINT };
struct Op;
typedef vector<Op> Ops;
struct Op {
op_type op;
int val;
Ops loop;
Op(Ops v) : op(LOOP), loop(v) {}
Op(op_type _op, int v = 0) : op(_op), val(v) {}
};
class Tape {
int pos;
vector<int> tape;
public:
Tape() {
pos = 0;
tape.push_back(0);
}
int get() { return tape[pos]; }
void inc(int x) { tape[pos] += x; }
void move(int x) { pos += x; while (pos >= tape.size()) tape.resize(2 * tape.size()); }
};
class Program {
Ops ops;
public:
Program(string code) {
string::iterator iterator = code.begin();
ops = parse(&iterator, code.end());
}
void run() {
Tape tape;
_run(ops, tape);
}
private:
Ops parse(string::iterator *iterator, string::iterator end) {
Ops res;
while (*iterator != end) {
char c = **iterator;
*iterator += 1;
switch (c) {
case '+': res.push_back(Op(INC, 1)); break;
case '-': res.push_back(Op(INC, -1)); break;
case '>': res.push_back(Op(MOVE, 1)); break;
case '<': res.push_back(Op(MOVE, -1)); break;
case '.': res.push_back(Op(PRINT)); break;
case '[': res.push_back(Op(parse(iterator, end))); break;
case ']': return res;
}
}
return res;
}
void _run(Ops &program, Tape &tape) {
for (Ops::iterator it = program.begin(); it != program.end(); it++) {
Op &op = *it;
switch (op.op) {
case INC: tape.inc(op.val); break;
case MOVE: tape.move(op.val); break;
case LOOP: while (tape.get() > 0) _run(op.loop, tape); break;
case PRINT: printf("%c", tape.get()); fflush(stdout); break;
}
}
}
};
string read_file(string filename){
ifstream textstream(filename.c_str());
textstream.seekg(0, ios_base::end);
const int lenght = textstream.tellg();
textstream.seekg(0);
string text(lenght, ' ');
textstream.read(&text[0], lenght);
textstream.close();
return text;
}
int main(int argc, char** argv) {
string text = read_file(string(argv[1]));
stringstream ostr;
ostr << "C++\t" << getpid();
notify(ostr.str());
Program p(text);
p.run();
notify("stop");
return 0;
}