blob: ebca77b3759749b7684a24d1495bbd346301775b (
plain) (
blame)
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
|
//
// Created by bmestanov on 15.11.18.
//
#define TAPE_SIZE 65536
#define STACK_SIZE 8192
#include <fstream>
#include <iostream>
void failIf(bool condition, const char *message) {
if (condition) {
std::cerr << message;
exit(1);
}
}
int main(int argc, char **argv) {
argc--;
argv++;
char memory[TAPE_SIZE] = {0};
char *pp = memory; // program pointer
long stack[STACK_SIZE];
int sp = 0; // stack pointer
failIf(!argv[0], "No file provided");
std::ifstream file;
file.open(argv[0]);
failIf(!file, "Error opening file");
while (!file.eof()) {
auto symbol = static_cast<char>(file.get());
switch (symbol) {
case '>': {
// Allow memory wrap
pp = memory + (pp - memory + 1) % TAPE_SIZE;
break;
}
case '<': {
pp = memory + (pp - memory - 1) % TAPE_SIZE;
break;
}
case '+': {
(*pp)++;
break;
}
case '-': {
(*pp)--;
break;
}
case '.': {
std::putchar(*pp);
break;
}
case ',': {
*pp = static_cast<char>(std::getchar());
break;
}
case '[': {
if (*pp) {
failIf(sp == STACK_SIZE, "Stack overflow");
stack[sp++] = file.tellg();
} else {
long move = 1;
while (move > 0) {
auto next = static_cast<char>(file.get());
if (next == '[') move++;
if (next == ']') move--;
if (file.eof()) failIf(true, "Invalid syntax");
}
}
break;
}
case ']': {
failIf(sp == 0, "Invalid syntax");
if (*pp) {
long top = stack[sp - 1];
file.seekg(top);
} else {
sp--;
}
}
default:;
}
}
return 0;
}
|