-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
115 lines (95 loc) · 2.88 KB
/
main.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
#define MEMORY_SIZE 30000
void print_memory(vector<char> const &memory) {
for (auto &t : memory) cout << (int) t << " ";
cout << endl;
}
vector<char> compile(vector<char> const &program, vector<pair<int, int>> const &loopPointers) {
vector<char> memory(MEMORY_SIZE, 0);
unsigned int ptr{};
char c{};
for (int ip{0}; ip < program.size(); ++ip) {
char instruction{program[ip]};
switch (instruction) {
case '+':
++memory[ptr];
break;
case '-':
--memory[ptr];
break;
case '>':
++ptr;
break;
case '<':
--ptr;
break;
case '.':
cout << memory[ptr];
break;
case ',':
cin >> c;
memory[ptr] = c;
break;
case '[':
if (memory[ptr] == 0) {
auto it = std::find_if(loopPointers.begin(), loopPointers.end(),
[&ip](const pair<int, int> &element) {
return element.first == ip || element.second == ip;
});
ip = it->second;
}
break;
case ']':
if (memory[ptr] != 0) {
auto it = std::find_if(loopPointers.begin(), loopPointers.end(),
[&ip](const pair<int, int> &element) {
return element.first == ip || element.second == ip;
});
ip = it->first;
}
break;
default:
break;
}
}
return memory;
}
void print_pair(vector<pair<int, int>> const &v) {
for (auto &e: v) {
cout << "(" << e.first << ", " << e.second << ")" << endl;
}
}
int main(int argc, char *argv[]) {
if (argc < 2) {
cerr << "Illegal number of parameters" << endl;
return 1;
}
string filename{argv[1]};
ifstream file{"../" + filename};
if (!file) {
cerr << "No such file" << endl;
return 1;
}
char c{};
vector<char> tokens{};
vector<pair<int, int>> loopStack{};
vector<int> openLoop{};
int index{};
while (file.get(c)) {
if (c == '[') {
openLoop.push_back(index);
} else if (c == ']') {
loopStack.emplace_back(pair(openLoop.back(), index));
openLoop.pop_back();
}
tokens.push_back(c);
++index;
}
vector<char> output = compile(tokens, loopStack);
//print_memory(output);
return 0;
}