-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbf_simple_yk.c
More file actions
118 lines (109 loc) · 3.08 KB
/
bf_simple_yk.c
File metadata and controls
118 lines (109 loc) · 3.08 KB
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
#include <err.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <yk.h>
#define CELLS_LEN 30000
void interp(char *prog, char *prog_end, char *cells, char *cells_end,
YkMT *mt, YkLocation *yklocs)
{
char *instr = prog;
char *cell = cells;
while (instr < prog_end) {
yk_mt_control_point(mt, &yklocs[instr - prog]);
switch (*instr) {
case '>': {
if (cell++ == cells_end)
errx(1, "out of memory");
break;
}
case '<': {
if (cell > cells)
cell--;
break;
}
case '+': {
(*cell)++;
break;
}
case '-': {
(*cell)--;
break;
}
case '.': {
if (putchar(*cell) == EOF)
err(1, "(stdout)");
break;
}
case ',': {
if (read(STDIN_FILENO, cell, 1) == -1)
err(1, "(stdin)");
break;
}
case '[': {
if (*cell == 0) {
int count = 0;
while (true) {
instr++;
if (*instr == ']') {
if (count == 0)
break;
count--;
} else if (*instr == '[')
count++;
}
}
break;
}
case ']': {
if (*cell != 0) {
int count = 0;
while (true) {
instr--;
if (*instr == '[') {
if (count == 0)
break;
count--;
} else if (*instr == ']')
count++;
}
}
break;
}
default: break;
}
instr++;
}
}
int main(int argc, char *argv[]) {
if (argc < 2)
errx(1, "<filename>");
int fd = open(argv[1], O_RDONLY);
struct stat sb;
if (fstat(fd, &sb) != 0)
err(1, "%s", argv[1]);
size_t prog_len = sb.st_size;
char *prog = malloc(prog_len);
if (prog == NULL)
err(1, "out of memory");
if (read(fd, prog, prog_len) != prog_len)
err(1, "%s", argv[1]);
char *cells = calloc(1, CELLS_LEN);
if (cells == NULL)
err(1, "out of memory");
YkMT *mt = yk_mt_new(NULL);
YkLocation *yklocs = calloc(prog_len, sizeof(YkLocation));
if (yklocs == NULL)
err(1, "out of memory");
for (size_t i = 0; i < prog_len; i++) {
if (prog[i] == ']')
yklocs[i] = yk_location_new();
else
yklocs[i] = yk_location_null();
}
interp(prog, prog + prog_len, cells, cells + CELLS_LEN, mt, yklocs);
free(yklocs);
}