-
Notifications
You must be signed in to change notification settings - Fork 16
/
interpreter.c
58 lines (53 loc) · 1.47 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
#include <stdio.h> // putchar, getchar
#include <stdlib.h> // NULL, free
#include "file_io.h"
void interpret (const char* const input) {
// Initialize the tape with 30,000 zeroes.
unsigned char tape [30000] = { 0 };
// Set the pointer to point at the left most cell of the tape.
unsigned char* ptr = tape;
char current_char;
for (int i = 0; (current_char = input[i]) != '\0'; ++i) {
switch (current_char) {
case '>': ++ptr; break;
case '<': --ptr; break;
case '+': ++(*ptr); break;
case '-': --(*ptr); break;
case '.': putchar(*ptr); break;
case ',': *ptr = getchar(); break;
case '[':
if (!(*ptr)) {
int loop = 1;
while (loop > 0) {
current_char = input[++i];
if (current_char == ']') {
--loop;
} else if (current_char == '[') {
++loop;
}
}
}
break;
case ']':
if (*ptr) {
int loop = 1;
while (loop > 0) {
current_char = input[--i];
if (current_char == '[') {
--loop;
} else if (current_char == ']') {
++loop;
}
}
}
break;
}
}
}
int main (int argc, char* argv []) {
if (argc != 2) err("Usage: interpret inputfile");
char* file_contents = read_file(argv[1]);
if (file_contents == NULL) err("Couldn't open file");
interpret(file_contents);
free(file_contents);
}