-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathinterpreter.c
70 lines (66 loc) · 1.25 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
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "util.h"
void interpret(const char *const input)
{
// Initialize the tape with 30,000 zeroes.
uint8_t tape[30000] = { 0 };
// Set the pointer to point at the left most cell of the tape.
uint8_t *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: interpreter <inputfile>");
char *file_contents = read_file(argv[1]);
if (file_contents == NULL) err("Couldn't open file");
interpret(file_contents);
free(file_contents);
}