-
Notifications
You must be signed in to change notification settings - Fork 8
/
sl3.c
435 lines (374 loc) · 10.8 KB
/
sl3.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
/* A minimal Lisp interpreter
Copyright 2004 Andru Luvisi
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License , or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, write to the Free Software
Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#define error(X) do { fprintf(stderr, "%s\n", X); exit(1); } while (0)
int line_num = 1;
int total_malloc = 0;
/*** List Structured Memory ***/
enum otype { INT, SYM, CONS, PROC, PRIMOP };
typedef struct obj {
enum otype type;
int line_num;
struct obj *p[1];
} obj;
typedef obj * (*primop)(obj *);
obj *all_symbols, *top_env, *nil, *tee, *quote,
*s_if, *s_lambda, *s_define, *s_setb, *s_begin;
#define cons(X, Y) omake(CONS, 2, (X), (Y))
obj *car(obj *X) {
if(X == 0) {
fprintf(stderr, "warning: car argument null on line %d\n", line_num);
return nil;
}
if(X == nil)
return nil;
if(X->type != CONS) {
fprintf(stderr, "warning: car argument not a list (%d) on line %d\n", X->p[0], X->line_num);
return nil;
}
return X->p[0];
}
obj *cdr(obj *X) {
if(X == nil)
return nil;
if(X->type != CONS) {
fprintf(stderr, "warning: cdr argument not a list on line %d\n", X->line_num);
return nil;
}
if(X->p[1] == 0) {
fprintf(stderr, "error: cdr list element is zero-pointer at %d\n", X->line_num);
return nil;
}
return X->p[1];
}
#define setcar(X,Y) (((X)->p[0]) = (Y))
#define setcdr(X,Y) (((X)->p[1]) = (Y))
#define mkint(X) omake(INT, 1, (obj *)(X))
#define intval(X) ((int)((X)->type == INT ? (X)->p[0] : 0)) // intval for INT only
#define mksym(X) omake(SYM, 1, (obj *)(X))
#define symname(X) ((char *)((X)->p[0]))
#define mkprimop(X) omake(PRIMOP, 1, (obj *)(X))
#define primopval(X) ((primop)(X)->p[0])
#define mkproc(X,Y,Z) omake(PROC, 3, (X), (Y), (Z))
#define procargs(X) ((X)->p[0])
#define proccode(X) ((X)->p[1])
#define procenv(X) ((X)->p[2])
#define isnil(X) ((X) == nil)
obj *omake(enum otype type, int count, ...) {
obj *ret;
va_list ap;
int i;
va_start(ap, count);
int object_size = sizeof(obj) + (count - 1)*sizeof(obj *);
total_malloc += object_size;
ret = (obj *) malloc(object_size);
ret->type = type;
ret->line_num = line_num;
for(i = 0; i < count; i++) ret->p[i] = va_arg(ap, obj *);
va_end(ap);
return ret;
}
obj *findsym(char *name) {
obj *symlist;
for(symlist = all_symbols; !isnil(symlist); symlist = cdr(symlist))
if(!strcmp(name, symname(car(symlist))))
return symlist;
return nil;
}
obj *intern(char *name) {
obj *op = findsym(name);
if(!isnil(op)) return car(op);
op = mksym(name);
all_symbols = cons(op, all_symbols);
return op;
}
/*** Environment ***/
#define extend(ENV, SYM, VAL) (cons(cons((SYM), (VAL)), (ENV)))
obj *multiple_extend(obj *env, obj *syms, obj *vals) {
return isnil(syms) ?
env :
multiple_extend(extend(env, car(syms), car(vals)),
cdr(syms), cdr(vals));
}
obj *extend_top(obj *sym, obj *val) {
setcdr(top_env, cons(cons(sym, val), cdr(top_env)));
return val;
}
obj *assoc(obj *key, obj *alist) {
if(isnil(alist)) return nil;
if(car(car(alist)) == key) return car(alist);
return assoc(key, cdr(alist));
}
/*** Input/Output ***/
FILE *ifp;
char *token_la;
int la_valid = 0;
#define MAXLEN 100
char buf[MAXLEN];
int bufused;
void add_to_buf(char ch) { if(bufused < MAXLEN - 1) buf[bufused++] = ch; }
char *buf2str() { buf[bufused++] = '\0'; return strdup(buf); }
void setinput(FILE *fp) { ifp = fp; }
void putback_token(char *token) { token_la = token; la_valid = 1; }
void myexit(int code);
char *gettoken() {
int ch;
char comment=0;
bufused = 0;
if(la_valid) { la_valid = 0; return token_la; }
do {
if((ch = getc(ifp)) == EOF) myexit(0);
if(ch == ';') comment = 1;
if(ch == '\n') {
comment = 0;
line_num++;
}
} while(isspace(ch) || comment);
add_to_buf(ch);
if(strchr("()\'", ch)) return buf2str();
for(;;) {
if((ch = getc(ifp)) == EOF) myexit(0);
if(strchr("()\'", ch) || isspace(ch)) {
ungetc(ch, ifp);
return buf2str();
}
add_to_buf(ch);
}
}
obj *readlist();
obj *readobj() {
char *token;
token = gettoken();
if(!strcmp(token, "(")) return readlist();
if(!strcmp(token, "\'")) return cons(quote, cons(readobj(), nil));
if(token[strspn(token, "0123456789")] == '\0'
|| (token[0] == '-' && strlen(token) > 1))
return mkint(atoi(token));
return intern(token);
}
obj *readlist() {
char *token = gettoken();
obj *tmp;
if(!strcmp(token, ")")) return nil;
if(!strcmp(token, ".")) {
tmp = readobj();
if(strcmp(gettoken(), ")")) exit(1);
return tmp;
}
putback_token(token);
tmp = readobj(); /* Must force evaluation order */
return cons(tmp, readlist());
}
void writeobj(FILE *ofp, obj *op) {
switch(op->type) {
case INT: fprintf(ofp, "%d", intval(op)); break;
case CONS:
fprintf(ofp, "(");
for(;;) {
writeobj(ofp, car(op));
if(isnil(cdr(op))) {
fprintf(ofp, ")");
break;
}
op = cdr(op);
if(op->type != CONS) {
fprintf(ofp, " . ");
writeobj(ofp, op);
fprintf(ofp, ")");
break;
}
fprintf(ofp, " ");
}
break;
case SYM:
if(isnil(op)) fprintf(ofp, "()");
else fprintf(ofp, "%s", symname(op));
break;
case PRIMOP: fprintf(ofp, "#<PRIMOP>"); break;
case PROC: fprintf(ofp, "#<PROC>"); break;
default: exit(1);
}
}
/*** Evaluator (Eval/no Apply) ***/
obj *evlis(obj *exps, obj *env);
obj *eval(obj *exp, obj *env) {
obj *tmp, *proc, *vals;
eval_start:
if(exp == nil) return nil;
switch(exp->type) {
case INT: return exp;
case SYM: tmp = assoc(exp, env);
if(tmp == nil) {
fprintf(stderr, "Unbound symbol ");
writeobj(stderr, exp);
fprintf(stderr, "\n");
return nil;
}
return cdr(tmp);
case CONS:
if(car(exp) == s_if) {
if(eval(car(cdr(exp)), env) != nil)
return eval(car(cdr(cdr(exp))), env);
else
return eval(car(cdr(cdr(cdr(exp)))), env);
}
if(car(exp) == s_lambda)
return mkproc(car(cdr(exp)), cdr(cdr(exp)), env);
if(car(exp) == quote)
return car(cdr(exp));
if(car(exp) == s_define)
return(extend_top(car(cdr(exp)),
eval(car(cdr(cdr(exp))), env)));
if(car(exp) == s_setb) {
obj *pair = assoc(car(cdr(exp)), env);
obj *newval = eval(car(cdr(cdr(exp))), env);
setcdr(pair, newval);
return newval;
}
if(car(exp) == s_begin) {
exp = cdr(exp);
if(exp == nil) return nil;
for(;;) {
if(cdr(exp) == nil) {
exp = car(exp);
goto eval_start;
}
eval(car(exp), env);
exp = cdr(exp);
}
}
proc = eval(car(exp), env);
vals = evlis(cdr(exp), env);
if(proc->type == PRIMOP)
return (*primopval(proc))(vals);
if(proc->type == PROC) {
/* For dynamic scope, use env instead of procenv(proc) */
env = multiple_extend(procenv(proc), procargs(proc), vals);
exp = cons(s_begin, proccode(proc));
goto eval_start;
}
printf("Bad PROC type\n");
return nil;
case PRIMOP: return exp;
case PROC: return exp;
}
/* Not reached */
return exp;
}
obj *evlis(obj *exps, obj *env) {
if(exps == nil) return nil;
return cons(eval(car(exps), env),
evlis(cdr(exps), env));
}
/*** Primitives ***/
obj *prim_sum(obj *args) {
int sum;
for(sum = 0; !isnil(args); sum += intval(car(args)), args = cdr(args));
return mkint(sum);
}
obj *prim_sub(obj *args) {
int sum;
for(sum = intval(car(args)), args = cdr(args);
!isnil(args);
sum -= intval(car(args)), args = cdr(args));
return mkint(sum);
}
obj *prim_prod(obj *args) {
int prod;
for(prod = 1; !isnil(args); prod *= intval(car(args)), args = cdr(args));
return mkint(prod);
}
obj *prim_divide(obj *args) {
int prod = intval(car(args));
args = cdr(args);
while(!isnil(args)) {
prod /= intval(car(args));
args = cdr(args);
}
return mkint(prod);
}
obj *prim_gt(obj *args) {
return intval(car(args)) > intval(car(cdr(args))) ? tee : nil;
}
obj *prim_lt(obj *args) {
return intval(car(args)) < intval(car(cdr(args))) ? tee : nil;
}
obj *prim_ge(obj *args) {
return intval(car(args)) >= intval(car(cdr(args))) ? tee : nil;
}
obj *prim_le(obj *args) {
return intval(car(args)) <= intval(car(cdr(args))) ? tee : nil;
}
obj *prim_numeq(obj *args) {
return intval(car(args)) == intval(car(cdr(args))) ? tee : nil;
}
obj *prim_cons(obj *args) { return cons(car(args), car(cdr(args))); }
obj *prim_car(obj *args) { return car(car(args)); }
obj *prim_cdr(obj *args) { return cdr(car(args)); }
/*** Helpers *****/
obj *prim_print(obj *args) {
while(!isnil(args)) {
writeobj(stdout, car(args));
args = cdr(args);
printf(" ");
}
printf("\n");
return nil;
}
/*** Initialization ***/
void init_sl3() {
nil = mksym("nil");
all_symbols = cons(nil, nil);
top_env = cons(cons(nil, nil), nil);
tee = intern("t");
extend_top(tee, tee);
quote = intern("quote");
s_if = intern("if");
s_lambda = intern("lambda");
s_define = intern("define");
s_setb = intern("set!");
s_begin = intern("begin");
extend_top(intern("+"), mkprimop(prim_sum));
extend_top(intern("-"), mkprimop(prim_sub));
extend_top(intern("*"), mkprimop(prim_prod));
extend_top(intern("/"), mkprimop(prim_divide));
extend_top(intern("="), mkprimop(prim_numeq));
extend_top(intern(">"), mkprimop(prim_gt));
extend_top(intern(">="), mkprimop(prim_ge));
extend_top(intern("<"), mkprimop(prim_lt));
extend_top(intern("<="), mkprimop(prim_le));
extend_top(intern("cons"), mkprimop(prim_cons));
extend_top(intern("car"), mkprimop(prim_car));
extend_top(intern("cdr"), mkprimop(prim_cdr));
extend_top(intern("print"), mkprimop(prim_print));
}
/*** Main Driver ***/
int main() {
init_sl3();
setinput(stdin);
for(;;) {
writeobj(stdout, eval(readobj(), top_env));
printf("\n");
}
return 0;
}
void myexit(int code) {
fprintf(stderr, "%d bytes left hanging\n", total_malloc);
exit(code);
}