-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqf.c
More file actions
153 lines (137 loc) · 2.34 KB
/
qf.c
File metadata and controls
153 lines (137 loc) · 2.34 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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#include "qf.h"
int qf_run(const char *prog, FILE *in, FILE *out)
{
char *a, imm=0;
unsigned short p = 0;
int c, ch, psize, i=-1, lcount=0;
const unsigned char *uprog = prog;
a = malloc(1<<16);
bzero(a, 1<<16);
psize = strlen(prog);
/* Implement an indirect threaded BF variant: QF
* 0x1i: + add imm
* 0x2i: - sub imm
* 0x3i: > seek next imm
* 0x4i: < seek prev imm
* 0x50: . output
* 0x60: , input
* 0x70: [ begin loop
* 0x80: ] end loop
* 0x90: nop
*/
static void *itbl[] = {&&qf_fin, &&qf_inc, &&qf_dec, \
&&qf_nxt, &&qf_prv, &&qf_out, &&qf_inp, \
&&qf_beg, &&qf_end, &&qf_nop};
#define NEXT if(i < psize) { \
unsigned char instr = uprog[++i]; \
imm = instr & 0xf; \
goto *itbl[instr >> 4]; \
} else { goto qf_fin; }
/* Start the program */
qf_nop:
NEXT;
qf_inc:
a[p] += imm;
NEXT;
qf_dec:
a[p] -= imm;
NEXT;
qf_nxt:
p += imm;
NEXT;
qf_prv:
p -= imm;
NEXT;
qf_out:
fputc(a[p], out);
NEXT;
qf_inp:
c = fgetc(in);
a[p] = (c != EOF) ? c : 0;
NEXT;
qf_beg:
if(a[p] == 0) {
c = 1;
while(c) {
if(i == psize-1)
goto QF_ERR;
ch = uprog[++i];
if(ch == 0x70)
c++;
else if(ch == 0x80)
c--;
}
}
NEXT;
qf_end:
if(a[p] != 0) {
if(++lcount > MAXLOOPS)
goto QF_ERR;
c = -1;
while(c) {
if(i == 0)
goto QF_ERR;
ch = uprog[--i];
if(ch == 0x70)
c++;
else if(ch == 0x80)
c--;
}
}
NEXT;
qf_fin:
free(a);
return 1;
QF_ERR:
fprintf(out, "\nERR: problems.\n");
free(a);
return -1;
}
/* Convert bf to qf */
char *bf_to_qf(const char *bfp)
{
int i=0, j=0, k=0, maxlen=128, plen;
char *qfp;
plen = strlen(bfp);
qfp = malloc(maxlen);
#define CONSUME(ch) \
for (k = 1; bfp[i] == ch && k < 15 && i < plen; k++) ++i
while(i < plen) {
switch(bfp[i++]) {
case '+':
CONSUME('+');
qfp[j++] = 0x10 + k;
break;
case '-':
CONSUME('-');
qfp[j++] = 0x20 + k;
break;
case '>':
CONSUME('>');
qfp[j++] = 0x30 + k;
break;
case '<':
CONSUME('<');
qfp[j++] = 0x40 + k;
break;
case '.':
qfp[j++] = 0x50;
break;
case ',':
qfp[j++] = 0x60;
break;
case '[':
qfp[j++] = 0x70;
break;
case ']':
qfp[j++] = 0x80;
break;
}
if(j == maxlen) {
maxlen *= 2;
qfp = realloc(qfp, maxlen);
}
}
qfp[j] = '\0';
return qfp;
}