-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathtinylisp-commented.c
460 lines (398 loc) · 11.2 KB
/
tinylisp-commented.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
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/* tinylisp-commented.c with NaN boxing by Robert A. van Engelen 2022 */
/* tinylisp.c but adorned with comments in an (overly) verbose C style */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/* we only need two types to implement a Lisp interpreter:
I unsigned integer (either 16 bit, 32 bit or 64 bit unsigned)
L Lisp expression (double with NaN boxing)
I variables and function parameters are named as follows:
i any unsigned integer, e.g. a NaN-boxed ordinal value
t a NaN-boxing tag
L variables and function parameters are named as follows:
x,y any Lisp expression
n number
t list
f function or Lisp primitive
p pair, a cons of two Lisp expressions
e,d environment, a list of pairs, e.g. created with (define v x)
v the name of a variable (an atom) or a list of variables */
#define I unsigned
#define L double
/* T(x) returns the tag bits of a NaN-boxed Lisp expression x */
#define T(x) *(unsigned long long*)&x >> 48
/* address of the atom heap is at the bottom of the cell stack */
#define A (char*)cell
/* number of cells for the shared stack and atom heap, increase N as desired */
#define N 1024
/* hp: heap pointer, A+hp with hp=0 points to the first atom string in cell[]
sp: stack pointer, the stack starts at the top of cell[] with sp=N
safety invariant: hp <= sp<<3 */
I hp = 0, sp = N;
/* atom, primitive, cons, closure and nil tags for NaN boxing */
I ATOM = 0x7ff8, PRIM = 0x7ff9, CONS = 0x7ffa, CLOS = 0x7ffb, NIL = 0x7ffc;
/* cell[N] array of Lisp expressions, shared by the stack and atom heap */
L cell[N];
/* Lisp constant expressions () (nil), #t, ERR, and the global environment env */
L nil, tru, err, env;
/* NaN-boxing specific functions:
box(t,i): returns a new NaN-boxed double with tag t and ordinal i
ord(x): returns the ordinal of the NaN-boxed double x
num(n): convert or check number n (does nothing, e.g. could check for NaN)
equ(x,y): returns nonzero if x equals y */
L box(I t, I i) {
L x;
*(unsigned long long*)&x = (unsigned long long)t << 48 | i;
return x;
}
I ord(L x) {
return *(unsigned long long*)&x; /* the return value is narrowed to 32 bit unsigned integer to remove the tag */
}
L num(L n) {
return n;
}
I equ(L x, L y) {
return *(unsigned long long*)&x == *(unsigned long long*)&y;
}
/* interning of atom names (Lisp symbols), returns a unique NaN-boxed ATOM */
L atom(const char *s) {
I i = 0;
while (i < hp && strcmp(A+i, s)) /* search for a matching atom name on the heap */
i += strlen(A+i)+1;
if (i == hp) { /* if not found */
hp += strlen(strcpy(A+i, s))+1; /* allocate and add a new atom name to the heap */
if (hp > sp<<3) /* abort when out of memory */
abort();
}
return box(ATOM, i);
}
/* construct pair (x . y) returns a NaN-boxed CONS */
L cons(L x, L y) {
cell[--sp] = x; /* push the car value x */
cell[--sp] = y; /* push the cdr value y */
if (hp > sp<<3) /* abort when out of memory */
abort();
return box(CONS, sp);
}
/* return the car of a pair or ERR if not a pair */
L car(L p) {
return (T(p) & ~(CONS^CLOS)) == CONS ? cell[ord(p)+1] : err;
}
/* return the cdr of a pair or ERR if not a pair */
L cdr(L p) {
return (T(p) & ~(CONS^CLOS)) == CONS ? cell[ord(p)] : err;
}
/* construct a pair to add to environment e, returns the list ((v . x) . e) */
L pair(L v, L x, L e) {
return cons(cons(v, x), e);
}
/* construct a closure, returns a NaN-boxed CLOS */
L closure(L v, L x, L e) {
return box(CLOS, ord(pair(v, x, equ(e, env) ? nil : e)));
}
/* look up a symbol in an environment, return its value or ERR if not found */
L assoc(L v, L e) {
while (T(e) == CONS && !equ(v, car(car(e))))
e = cdr(e);
return T(e) == CONS ? cdr(car(e)) : err;
}
/* not(x) is nonzero if x is the Lisp () empty list */
I not(L x) {
return T(x) == NIL;
}
/* let(x) is nonzero if x is a Lisp let/let* pair */
I let(L x) {
return T(x) != NIL && !not(cdr(x));
}
/* return a new list of evaluated Lisp expressions t in environment e */
L eval(L, L);
L evlis(L t, L e) {
return T(t) == CONS ? cons(eval(car(t), e), evlis(cdr(t), e)) : T(t) == ATOM ? assoc(t,e) : nil;
}
/* Lisp primitives:
(eval x) return evaluated x (such as when x was quoted)
(quote x) special form, returns x unevaluated "as is"
(cons x y) construct pair (x . y)
(car p) car of pair p
(cdr p) cdr of pair p
(add n1 n2 ... nk) sum of n1 to nk
(sub n1 n2 ... nk) n1 minus sum of n2 to nk
(mul n1 n2 ... nk) product of n1 to nk
(div n1 n2 ... nk) n1 divided by the product of n2 to nk
(int n) integer part of n
(< n1 n2) #t if n1<n2, otherwise ()
(eq? x y) #t if x equals y, otherwise ()
(not x) #t if x is (), otherwise ()
(or x1 x2 ... xk) first x that is not (), otherwise ()
(and x1 x2 ... xk) last x if all x are not (), otherwise ()
(cond (x1 y1)
(x2 y2)
...
(xk yk)) the first yi for which xi evaluates to non-()
(if x y z) if x is non-() then y else z
(let* (v1 x1)
(v2 x2)
...
y) sequentially binds each variable v1 to xi to evaluate y
(lambda v x) construct a closure
(define v x) define a named value globally */
L f_eval(L t, L e) {
return eval(car(evlis(t, e)), e);
}
L f_quote(L t, L _) {
return car(t);
}
L f_cons(L t, L e) {
t = evlis(t, e);
return cons(car(t), car(cdr(t)));
}
L f_car(L t, L e) {
return car(car(evlis(t, e)));
}
L f_cdr(L t, L e) {
return cdr(car(evlis(t, e)));
}
L f_add(L t, L e) {
L n;
t = evlis(t, e);
n = car(t);
while (!not(t = cdr(t)))
n += car(t);
return num(n);
}
L f_sub(L t, L e) {
L n;
t = evlis(t, e);
n = car(t);
while (!not(t = cdr(t)))
n -= car(t);
return num(n);
}
L f_mul(L t, L e) {
L n;
t = evlis(t, e);
n = car(t);
while (!not(t = cdr(t)))
n *= car(t);
return num(n);
}
L f_div(L t, L e) {
L n;
t = evlis(t, e);
n = car(t);
while (!not(t = cdr(t)))
n /= car(t);
return num(n);
}
L f_int(L t, L e) {
L n = car(evlis(t, e));
return n<1e16 && n>-1e16 ? (long long)n : n;
}
L f_lt(L t, L e) {
return t = evlis(t, e), car(t) - car(cdr(t)) < 0 ? tru : nil;
}
L f_eq(L t, L e) {
return t = evlis(t, e), equ(car(t), car(cdr(t))) ? tru : nil;
}
L f_not(L t, L e) {
return not(car(evlis(t, e))) ? tru : nil;
}
L f_or(L t,L e) {
L x = nil;
while (T(t) != NIL && not(x = eval(car(t),e)))
t = cdr(t);
return x;
}
L f_and(L t,L e) {
L x = nil;
while (T(t) != NIL && !not(x = eval(car(t),e)))
t = cdr(t);
return x;
}
L f_cond(L t, L e) {
while (T(t) != NIL && not(eval(car(car(t)), e)))
t = cdr(t);
return eval(car(cdr(car(t))), e);
}
L f_if(L t, L e) {
return eval(car(cdr(not(eval(car(t), e)) ? cdr(t) : t)), e);
}
L f_leta(L t, L e) {
for (; let(t); t = cdr(t))
e = pair(car(car(t)), eval(car(cdr(car(t))), e), e);
return eval(car(t), e);
}
L f_lambda(L t, L e) {
return closure(car(t), car(cdr(t)), e);
}
L f_define(L t, L e) {
env = pair(car(t), eval(car(cdr(t)), e), env);
return car(t);
}
/* table of Lisp primitives, each has a name s and function pointer f */
struct {
const char *s;
L (*f)(L, L);
} prim[] = {
{"eval", f_eval},
{"quote", f_quote},
{"cons", f_cons},
{"car", f_car},
{"cdr", f_cdr},
{"+", f_add},
{"-", f_sub},
{"*", f_mul},
{"/", f_div},
{"int", f_int},
{"<", f_lt},
{"eq?", f_eq},
{"or", f_or},
{"and", f_and},
{"not", f_not},
{"cond", f_cond},
{"if", f_if},
{"let*", f_leta},
{"lambda", f_lambda},
{"define", f_define},
{0}};
/* create environment by extending e with variables v bound to values t */
L bind(L v, L t, L e) {
return T(v) == NIL ? e :
T(v) == CONS ? bind(cdr(v), cdr(t), pair(car(v), car(t), e)) :
pair(v, t, e);
}
/* apply closure f to arguments t in environemt e */
L reduce(L f, L t, L e) {
return eval(cdr(car(f)), bind(car(car(f)), evlis(t, e), not(cdr(f)) ? env : cdr(f)));
}
/* apply closure or primitive f to arguments t in environment e, or return ERR */
L apply(L f, L t, L e) {
return T(f) == PRIM ? prim[ord(f)].f(t, e) :
T(f) == CLOS ? reduce(f, t, e) :
err;
}
/* evaluate x and return its value in environment e */
L eval(L x, L e) {
return T(x) == ATOM ? assoc(x, e) :
T(x) == CONS ? apply(eval(car(x), e), cdr(x), e) :
x;
}
/* tokenization buffer and the next character that we are looking at */
char buf[40], see = ' ';
/* advance to the next character */
void look() {
int c = getchar();
see = c;
if (c == EOF)
exit(0);
}
/* return nonzero if we are looking at character c, ' ' means any white space */
I seeing(char c) {
return c == ' ' ? see > 0 && see <= c : see == c;
}
/* return the look ahead character from standard input, advance to the next */
char get() {
char c = see;
look();
return c;
}
/* tokenize into buf[], return first character of buf[] */
char scan() {
I i = 0;
while (seeing(' '))
look();
if (seeing('(') || seeing(')') || seeing('\''))
buf[i++] = get();
else
do
buf[i++] = get();
while (i < 39 && !seeing('(') && !seeing(')') && !seeing(' '));
buf[i] = 0;
return *buf;
}
/* return the Lisp expression read from standard input */
L parse();
L Read() {
scan();
return parse();
}
/* return a parsed Lisp list */
L list() {
L x;
if (scan() == ')')
return nil;
if (!strcmp(buf, ".")) {
x = Read();
scan();
return x;
}
x = parse();
return cons(x, list());
}
/* return a parsed Lisp expression x quoted as (quote x) */
L quote() {
return cons(atom("quote"), cons(Read(), nil));
}
/* return a parsed atomic Lisp expression (a number or an atom) */
L atomic() {
L n; I i;
return (sscanf(buf, "%lg%n", &n, &i) > 0 && !buf[i]) ? n :
atom(buf);
}
/* return a parsed Lisp expression */
L parse() {
return *buf == '(' ? list() :
*buf == '\'' ? quote() :
atomic();
}
/* display a Lisp list t */
void print(L);
void printlist(L t) {
for (putchar('('); ; putchar(' ')) {
print(car(t));
t = cdr(t);
if (T(t) == NIL)
break;
if (T(t) != CONS) {
printf(" . ");
print(t);
break;
}
}
putchar(')');
}
/* display a Lisp expression x */
void print(L x) {
if (T(x) == NIL)
printf("()");
else if (T(x) == ATOM)
printf("%s", A+ord(x));
else if (T(x) == PRIM)
printf("<%s>", prim[ord(x)].s);
else if (T(x) == CONS)
printlist(x);
else if (T(x) == CLOS)
printf("{%u}", ord(x));
else
printf("%.10lg", x);
}
/* garbage collection removes temporary cells, keeps global environment */
void gc() {
sp = ord(env);
}
/* Lisp initialization and REPL */
int main() {
I i;
printf("tinylisp");
nil = box(NIL, 0);
err = atom("ERR");
tru = atom("#t");
env = pair(tru, tru, nil);
for (i = 0; prim[i].s; ++i)
env = pair(atom(prim[i].s), box(PRIM, i), env);
while (1) {
printf("\n%u>", sp-hp/8);
print(eval(Read(), env));
gc();
}
}