-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbf_simple2_yk.c
More file actions
133 lines (121 loc) · 3.23 KB
/
bf_simple2_yk.c
File metadata and controls
133 lines (121 loc) · 3.23 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#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
char *jmp_back(char *);
char *jmp_fwd(char *);
void interp(char *prog, char *prog_end, char *cells, char *cells_end,
YkMT *mt, YkLocation *yklocs)
{
// FIXME: need to call yktrace_const on `prog` (or otherwise inform yk that
// prog is immutable for the duration of a trace).
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) {
instr = jmp_fwd(instr);
}
break;
}
case ']': {
if (*cell != 0) {
instr = jmp_back(instr);
}
break;
}
default: break;
}
instr++;
}
}
// FIXME: needs to be given the yktrace_idempotent attribute
char *jmp_back(char *instr) {
int count = 0;
while (true) {
instr--;
if (*instr == '[') {
if (count == 0)
return instr;
count--;
} else if (*instr == ']')
count++;
}
}
// FIXME: needs to be given the yktrace_idempotent attribute
char *jmp_fwd(char *instr) {
int count = 0;
while (true) {
instr++;
if (*instr == ']') {
if (count == 0)
return instr;
count--;
} else if (*instr == '[')
count++;
}
}
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);
}