-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpreter.c
145 lines (123 loc) · 2.57 KB
/
interpreter.c
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
// Code used to manage a stack that records loop-starts.
#define MAX_PROGSIZE 30000
#define MAX_DATASIZE 30000
#define MAX_NUMLOOPS 15000
int loop_stack[MAX_NUMLOOPS];
int sp = 0;
bool init_complete = false;
void init ();
void push (int idx);
int peek ();
void pop ();
char program_buffer[MAX_PROGSIZE + 1];
char data_buffer[MAX_DATASIZE];
int main (int argc, char **argv) {
assert(argc == 2);
FILE *input = fopen(argv[1], "r");
// Enter the program into our interpreter's program buffer.
program_buffer[MAX_PROGSIZE] = '\0';
int brackets = 0;
int ch;
int ip = 0;
for (ip = 0; ip < MAX_PROGSIZE; ip++) {
if ((ch = fgetc(input)) == EOF) break;
switch (ch) {
case '[':
brackets++;
break;
case ']':
brackets--;
break;
default:
break;
}
program_buffer[ip] = ch;
}
assert(ch == EOF);
assert(brackets == 0);
// Begin manipulating the the data buffer.
init();
int dp;
for (dp = 0; dp < MAX_DATASIZE; dp++)
data_buffer[dp] = 0;
dp = 0;
ip = 0;
do {
ch = program_buffer[ip];
int brackets; // when skipping a loop, you can't find just any ']'...
switch (ch) {
case '[':
if (data_buffer[dp] == 0) {
brackets = -1;
do {
ip++;
if (program_buffer[ip] == '[') brackets--;
if (program_buffer[ip] == ']') brackets++;
} while (brackets != 0);
ip++;
} else push(++ip);
break;
case ']':
if (data_buffer[dp] == 0) {
pop();
ip++;
} else ip = peek();
break;
case '+':
data_buffer[dp]++;
ip++;
break;
case '-':
data_buffer[dp]--;
ip++;
break;
case '<':
dp--;
assert(dp >= 0);
ip++;
break;
case '>':
dp++;
assert(dp < MAX_DATASIZE);
ip++;
break;
case '.':
putchar(data_buffer[dp]);
ip++;
break;
case ',':
data_buffer[dp] = getchar();
ip++;
break;
default:
ip++;
}
} while (program_buffer[ip] != '\0');
return EXIT_SUCCESS;
}
// The stack-related methods.
void init () {
for (int i = 0; i < MAX_NUMLOOPS; i++)
loop_stack[i] = 0;
init_complete = true;
}
void push (int idx) {
assert(init_complete && "Call 'init' first\n");
assert(sp < MAX_NUMLOOPS);
loop_stack[sp++] = idx;
}
int peek () {
assert(init_complete && "Call 'init' first\n");
assert(sp > 0);
return loop_stack[sp - 1];
}
void pop () {
assert(init_complete && "Call 'init' first\n");
assert(sp > 0);
--sp;
}