-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda.c
More file actions
379 lines (355 loc) · 9.26 KB
/
Copy pathlambda.c
File metadata and controls
379 lines (355 loc) · 9.26 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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2022 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#ifndef __COSMOPOLITAN__
#include <assert.h>
#include <ctype.h>
#include <locale.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>
#include <wchar.h>
#endif
#include "blc.h"
#define USAGE \
" [-?hubBdsarvnNlS] [FILE...] <stdin >expr.txt 2>memory.txt\n\
Binary Lambda Calculus Virtual Machine\n\
\n\
FLAGS\n\
\n\
-h help\n\
-r redex log\n\
-b binary 8-bit i/o\n\
-B debug print binary\n\
-l print lambda notation\n\
-v variable log [implies -r]\n\
-a action log [implies -r]\n\
-s full machine state logging\n\
-n disables name rewriting rules\n\
-N disables most unicode symbolism\n\
-d dump terms on successful exit\n"
#define NIL 23
#define TRUE 27
#define FALSE 23
#define REF(c) (++(c)->refs, c)
static const char kRom[] = {
APP, 0, // 0 (λ 0 λ 0 (λ 0 wr0 wr1) put) (main gro)
ABS, // 2 λ 0 λ 0 (λ 0 wr0 wr1) put
APP, 0, // 3
VAR, 0, // 5
ABS, // 7
APP, // 8
ABS, // 9 λ 0 λ 0 wr0 wr1
APP, 2, // 10
VAR, // 12
IOP, // 13
ABS, // 14 λ 0 wr0 wr1
APP, 4, // 15
APP, 1, // 17
VAR, // 19
IOP, // 20 wr0
IOP, 0, // 21 wr1
ABS, // 23 (λλ 0) a.k.a. nil
ABS, // 24 exit
VAR, // 25
0, // 26 exit[0]
ABS, // 27 (λλ 1) a.k.a. true
ABS, // 28
VAR, 1, // 29
};
static int postdump;
static int kLazy[256];
void Quit(int sig) {
Dump(0, end, stderr);
exit(128 + sig);
}
void PrintUsage(const char *prog, int rc, FILE *f) {
fputs("Usage: ", f);
fputs(prog, f);
fputs(USAGE, f);
exit(rc);
}
int Backref(int x) {
return x - (end + 1);
}
static inline void Expand(int c) {
if (end >= TERMS) Error(5, "OUT OF TERMS");
mem[end++] = c;
}
void Gc(struct Closure *p) {
for (; p && p != &root; p = p->envp) {
if (--p->refs) break;
Gc(p->next);
p->next = frep;
frep = p;
}
}
void Var(void) {
int i, x;
struct Closure *t, *e;
e = t = envp;
x = mem[ip + 1];
for (i = 0; i < x && e != &root; ++i) {
e = e->next;
}
if (e == &root) Error(10 + x, "UNDEFINED VARIABLE %d", x);
ip = e->term;
envp = REF(e->envp);
Gc(t);
}
void Gro(void) {
int c = fgetc(stdin);
if (c != -1) {
Expand(ABS);
Expand(APP);
Expand(4);
Expand(APP);
Expand(Backref(binary ? kLazy[c] : c & 1 ? FALSE : TRUE));
Expand(VAR);
Expand(0);
} else {
Expand(ABS);
Expand(ABS);
Expand(VAR);
Expand(0);
}
}
void Put(void) {
int bit;
long newip;
if (!binary) {
co = '0' + (ip & 1);
fputc(co, stdout);
newip = 2;
} else if (mem[ip + 1] & 1) { // ip ∈ {6,13}
fputc(co, stdout);
newip = 2;
} else { // ip ∈ {20,21}
newip = 9; // (λ 0 (λ 0 wr1 wr0))
bit = ip & 1;
co = (co * 2) | bit;
}
if (ferror(stdout)) {
exit(55);
}
ip = newip;
}
/*
* Called from Abs() when a lambda is reached with no continuation. The
* original code unconditionally treated mem[ip+2] as an exit code:
*
* int rc = mem[ip + 2]; // (λ 0) [exitcode]
* if (rc) Error(rc, "CONTINUATIONS EXHAUSTED");
*
* That assumes ip is at a `λ.N` ABS whose body is exactly `VAR N`, in which
* case mem[ip+1]==VAR and mem[ip+2]==N. The intent was to reach this via the
* exit ABS at ROM position 24 (mem[24]=ABS, mem[25]=VAR, mem[26]=0), giving
* a clean exit(0).
*
* In practice the wrapper allows execution to terminate at other ABS
* positions whose bodies are not `VAR N`. For example, in bit mode, when
* the lazy input list bottoms out via NIL, control commonly returns to
* ip=14 (the inner `λ. 0 wr0 wr1`). There mem[15]=APP and mem[16]=4 (a
* span operand), so the old code reported a spurious "CONTINUATIONS
* EXHAUSTED" error and exited 4. Reproducer:
*
* ( cat /tmp/AIT/bin/take1k.blc; printf 'hello world!' ) | ./lambda
*
* Tromp's `uni` exits 0 with identical output bytes on the same input.
*
* The fix preserves the original intent: only interpret mem[ip+2] as an
* exit code when the body actually looks like `VAR N`. Otherwise exit
* cleanly.
*/
void Bye(void) {
if (mem[ip + 1] == VAR) {
int rc = mem[ip + 2];
if (rc) Error(rc, "CONTINUATIONS EXHAUSTED");
}
if (postdump) Dump(0, end, stderr);
exit(0);
}
// pops continuation and pushes it to environment
void Abs(void) {
if (!contp) Bye();
struct Closure *t = contp;
contp = t->next;
t->next = envp;
envp = t;
++ip;
}
struct Closure *Alloc(void) {
struct Closure *t;
if (!(t = frep)) {
if (!(t = calloc(1, sizeof(struct Closure)))) {
Error(6, "OUT OF HEAP");
}
}
frep = t->next;
t->refs = 1;
++heap;
return t;
}
// pushes continuation for argument
void App(void) {
int x = mem[ip + 1];
struct Closure *t = Alloc();
t->term = ip + 2 + x;
t->envp = t->term > 21 && t->term != end ? REF(envp) : &root;
t->next = contp;
contp = t;
ip += 2;
}
int LoadByte(int c) {
int i, r = end;
for (i = 7; i >= 0; --i) {
Expand(ABS);
Expand(APP);
Expand(i ? +4 : Backref(NIL));
Expand(APP);
Expand(Backref(c & (1 << i) ? FALSE : TRUE));
Expand(VAR);
Expand(0);
}
return r;
}
void LoadRom(void) {
long i;
for (; end < sizeof(kRom) / sizeof(*kRom); ++end) {
mem[end] = kRom[end];
}
mem[4] = binary ? 2 : 9;
if (binary) {
for (i = 0; i < 256; ++i) {
kLazy[i] = LoadByte(i);
}
}
mem[1] = end - 2;
}
void Iop(void) {
if (ip == end) {
Gro();
} else {
Put(); // ip ∈ {6,13,20,21}
}
Gc(envp);
envp = &root;
}
static void Rex(void) {
if (slog) PrintMachineState(stderr);
if (rlog && (alog || mem[ip] != APP)) {
PrintExpressions(stderr, alog, vlog);
}
switch (mem[ip]) {
case VAR:
Var();
break;
case APP:
App();
break;
case ABS:
Abs();
break;
case IOP:
Iop();
break;
default:
Error(7, "CORRUPT TERM");
}
}
void Krivine(void) {
int main;
long gotoget;
LoadRom();
mem[end++] = APP;
gotoget = end++;
main = end;
mem[gotoget] = Parse(1, stdin).n;
if (rlog) {
Print(main, 1, 0, stderr);
fputs("\n", stderr);
if (alog) {
fputs("⟿ wrap[", stderr);
Print(0, 1, 0, stderr);
fputs("]\n", stderr);
}
}
for (;;) Rex();
}
void LoadFlags(int argc, char *argv[]) {
int i;
const char *prog;
prog = argc ? argv[0] : "lambda";
while ((i = getopt(argc, argv, "?hubBdsarvnNlS")) != -1) {
switch (i) {
case 'b':
binary = 1;
break;
case 'S':
safer = 1;
break;
case 'n':
noname = 1;
break;
case 'N':
asciiname = 1;
break;
case 'B':
style = 2;
break;
case 'l':
style = 1;
break;
case 's':
slog = 1;
break;
case 'r':
rlog = 1;
break;
case 'a':
rlog = 1;
alog = 1;
break;
case 'v':
rlog = 1;
vlog = 1;
break;
case 'd':
postdump = 1;
break;
case '?':
case 'h':
PrintUsage(prog, 0, stdout);
default:
PrintUsage(prog, 1, stderr);
}
}
}
int main(int argc, char *argv[]) {
struct rlimit rlim = {512 * 1024 * 1024, 512 * 1024 * 1024};
setrlimit(RLIMIT_AS, &rlim);
signal(SIGQUIT, Quit);
signal(SIGPIPE, Quit);
LoadFlags(argc, argv);
setlocale(LC_ALL, "");
setvbuf(stdout, 0, _IOLBF, 0);
setvbuf(stderr, 0, _IOLBF, 0);
Krivine();
}