forked from toastedcornflakes/JIT_brainfuck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpreter.c
executable file
·89 lines (79 loc) · 1.9 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
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <interpreter.h>
#include <dbg.h>
// will fetch one brainfuck instruction at a time and execute it
void interpreter_main_loop(unsigned char *command_begin, unsigned char *command_end) {
unsigned char *begin_cells = calloc(1, PLAYGROUND_CELLS);
check_mem(begin_cells);
unsigned char *cell_pointer = begin_cells;
unsigned char *instruction_pointer = command_begin;
/* safe loop version:
while(instruction_pointer >= command_begin && instruction_pointer < command_end &&
cell_pointer >= begin_cells && cell_pointer < begin_cells + PLAYGROUND_CELLS)
*/
// the loop has NO safety checks whatsoever
while(instruction_pointer < command_end) {
unsigned char command = *instruction_pointer;
switch (command) {
case '>':
cell_pointer++;
break;
case '<':
cell_pointer--;
break;
case '+':
(*cell_pointer)++;
break;
case '-':
(*cell_pointer)--;
break;
case '.':
putchar(*cell_pointer);
break;
case',':
// getchar returns an int
*cell_pointer = (unsigned char)getchar();
break;
// control flow stuff
case'[':
// if *cell_pointer == 0, jump to CORRESPONDING (not next!) ]
if (*cell_pointer == 0) {
int count = 0;
while (1) {
if (*instruction_pointer == '[') {
count++;
} else if (*instruction_pointer == ']') {
if(--count == 0) {
break;
}
}
instruction_pointer++;
}
}
break;
case ']':
if (*cell_pointer != 0) {
// jump to CORRESPONDING (not prev!) `[`
int count = 0;
while (1) {
if (*instruction_pointer == ']') {
count++;
} else if (*instruction_pointer == '[') {
if(--count == 0) {
break;
}
}
instruction_pointer--;
}
}
break;
}
instruction_pointer++;
}
error:
if(begin_cells) {
free(begin_cells);
}
}