-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterpreter.cpp
More file actions
128 lines (110 loc) · 3.23 KB
/
interpreter.cpp
File metadata and controls
128 lines (110 loc) · 3.23 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <stdexcept>
using namespace std;
const size_t TAPE_SIZE = 10000;
void runBrainfuck(const string& input) {
vector<char> tape(TAPE_SIZE, 0);
size_t pointer = 0;
size_t unmatchedBrackets = 0;
for (size_t i = 0; i < input.length(); i++) {
char command = input[i];
switch (command) {
case '>':
if (pointer >= TAPE_SIZE - 1) {
throw out_of_range("Pointer moved out of tape bounds.");
}
pointer++;
break;
case '<':
if (pointer == 0) {
throw out_of_range("Pointer moved out of tape bounds.");
}
pointer--;
break;
case '+':
tape[pointer]++;
break;
case '-':
tape[pointer]--;
break;
case '.':
cout << tape[pointer];
break;
case ',':
char inputChar;
cin.get(inputChar);
tape[pointer] = inputChar;
break;
case '[':
if (tape[pointer] == 0) {
size_t unmatched = 1;
while (unmatched > 0) {
i++;
if (i >= input.length()) {
throw runtime_error("Unmatched '[' encountered.");
}
if (input[i] == '[') unmatched++;
if (input[i] == ']') unmatched--;
}
}
break;
case ']':
if (tape[pointer] != 0) {
size_t unmatched = 1;
while (unmatched > 0) {
i--;
if (i >= input.length()) {
throw runtime_error("Unmatched ']' encountered.");
}
if (input[i] == '[') unmatched--;
if (input[i] == ']') unmatched++;
}
}
break;
default:
throw runtime_error("Invalid character!");
}
}
unmatchedBrackets = 0;
for (char command : input) {
if (command == '[') unmatchedBrackets++;
if (command == ']') unmatchedBrackets--;
}
if (unmatchedBrackets != 0) {
throw runtime_error("Unmatched brackets");
}
}
std::string filterBrainfuckCode(const std::string& input) {
std::string filtered;
for (char c : input) {
if (std::string("><+-.,[]").find(c) != std::string::npos) {
filtered += c;
}
}
return filtered;
}
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <brainfuck_file>" << std::endl;
return 1;
}
std::ifstream inputFile(argv[1]);
if (!inputFile) {
std::cerr << "Error: Unable to open file " << argv[1] << std::endl;
return 1;
}
std::string code((std::istreambuf_iterator<char>(inputFile)), std::istreambuf_iterator<char>());
code = filterBrainfuckCode(code);
try {
runBrainfuck(code);
std::cout << std::endl;
}
catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}