-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschaf.c
2101 lines (1861 loc) · 52.3 KB
/
schaf.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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <inttypes.h>
#include <math.h>
#include <setjmp.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <libgen.h>
#include <limits.h>
#include <unistd.h>
#include "schaf.h"
#include "intern.h"
#include "utils.h"
//
// Types
//
static const char *TYPE_NAMES[] = {
[TYPE_NULL] = "null",
[TYPE_BOOL] = "boolean",
[TYPE_INT] = "integer",
[TYPE_SYMBOL] = "symbol",
[TYPE_UNDEF] = "undef",
[TYPE_PAIR] = "pair",
[TYPE_STRING] = "string",
[TYPE_PROC] = "procedure",
};
#define VALUE_TAG(v) (*(ValueTag*)(v))
#define OF_BOOL(v) ((v) ? Qtrue : Qfalse)
// Value (uintptr_t):
// 0b.....000 Pointer (Unchangeable pattern!)
// 0b.......1 Integer
// 0b......10 Symbol
// 0b0--00100 #f
// 0b0--01100 #t
// 0b0-010100 <undef>
typedef const uintptr_t Flag;
static Flag FLAG_NBIT_SYM = 2;
static Flag FLAG_NBIT_INT = 1;
static Flag FLAG_MASK = 0b111; // for 64 bit machine
static Flag FLAG_MASK_SYM = 0b11;
static Flag FLAG_MASK_INT = 0b1;
static Flag FLAG_SYM = 0b10;
static Flag FLAG_INT = 0b1;
const Value Qnil = 0b11100U;
const Value Qfalse = 0b00100U;
const Value Qtrue = 0b01100U;
const Value Qundef = 0b10100U; // may be an error or something
static const int64_t CFUNCARG_MAX = 3;
//
// Runtime-locals (aka global variables)
//
// Environment: list of Frames
// Frame: Table of 'symbol => <value>
static Table *toplevel_environment;
static Value symbol_names = Qnil; // ("name0" "name1" ...)
Value SYM_ELSE, SYM_QUOTE, SYM_QUASIQUOTE, SYM_UNQUOTE, SYM_UNQUOTE_SPLICING,
SYM_RARROW;
static const char *load_basedir = NULL;
static Value call_stack = Qnil; // list of pairs
static Value source_data = Qnil; // (a)list of AST: (filename syntax_list newline_positions)
// newline_positions: list of pos | int
//
// value_is_*: Type Checks
//
inline bool value_is_int(Value v)
{
return v & FLAG_MASK_INT;
}
inline bool value_is_symbol(Value v)
{
return (v & FLAG_MASK_SYM) == FLAG_SYM;
}
static bool value_is_immediate(Value v)
{
return v & FLAG_MASK;
}
static inline bool value_tag_is(Value v, ValueTag expected)
{
return !value_is_immediate(v) && VALUE_TAG(v) == expected;
}
inline bool value_is_string(Value v)
{
return value_tag_is(v, TAG_STRING);
}
static inline bool value_is_procedure(Value v)
{
if (value_is_immediate(v))
return false;
switch (VALUE_TAG(v)) {
case TAG_SYNTAX:
case TAG_CFUNC:
case TAG_CLOSURE:
case TAG_CONTINUATION:
return true;
case TAG_STRING:
case TAG_PAIR:
return false;
}
UNREACHABLE();
}
inline bool value_is_pair(Value v)
{
return value_tag_is(v, TAG_PAIR);
}
static Type immediate_type_of(Value v)
{
if (v == Qnil)
return TYPE_NULL;
if (value_is_int(v))
return TYPE_INT;
if (value_is_symbol(v))
return TYPE_SYMBOL;
if (v == Qtrue || v == Qfalse)
return TYPE_BOOL;
if (v == Qundef)
return TYPE_UNDEF;
UNREACHABLE();
}
Type value_type_of(Value v)
{
if (value_is_immediate(v))
return immediate_type_of(v);
switch (VALUE_TAG(v)) {
case TAG_STRING:
return TYPE_STRING;
case TAG_PAIR:
return TYPE_PAIR;
case TAG_CFUNC:
case TAG_SYNTAX:
case TAG_CLOSURE:
case TAG_CONTINUATION:
return TYPE_PROC;
}
UNREACHABLE();
}
static inline const char *value_type_to_string(Type t)
{
return TYPE_NAMES[t];
}
const char *value_to_type_name(Value v)
{
Type t = value_type_of(v);
return value_type_to_string(t);
}
// value_to_*: Convert internal data to external plain C
inline int64_t value_to_int(Value x)
{
#if __x86_64__
return (int64_t) x >> FLAG_NBIT_INT;
#else
int64_t i = x;
return (i - 1) / (1 << FLAG_NBIT_INT);
#endif
}
inline Symbol value_to_symbol(Value v)
{
return (Symbol) v >> FLAG_NBIT_SYM;
}
static const char *name_nth(Value list, int64_t n)
{
for (int64_t i = 0; i < n; i++) {
list = cdr(list);
if (list == Qnil)
return NULL;
}
Value name = car(list);
return STRING(name)->body;
}
static const char *unintern(Symbol sym)
{
const char *name = name_nth(symbol_names, (int64_t) sym);
if (name == NULL) // fatal; every known symbols should have a name
error("symbol %lu not found", sym);
return name;
}
inline const char *value_to_string(Value v)
{
if (value_is_symbol(v))
return unintern(value_to_symbol(v));
return STRING(v)->body;
}
// value_of_*: Convert external plain C data to internal
inline Value value_of_int(int64_t i)
{
Value v = i;
return v << FLAG_NBIT_INT | FLAG_INT;
}
static Symbol intern(const char *name)
{
Value last = Qnil;
int64_t i = 0;
// find
for (Value p = symbol_names; p != Qnil; last = p, p = cdr(p)) {
Value v = car(p);
if (strcmp(STRING(v)->body, name) == 0)
return i;
i++;
}
// or put at `i`
Value s = value_of_string(name);
Value next = list1(s);
if (last == Qnil)
symbol_names = next;
else
PAIR(last)->cdr = next;
return i;
}
inline Value value_of_symbol(const char *s)
{
Symbol sym = intern(s);
return (Value) (sym << FLAG_NBIT_SYM | FLAG_SYM);
}
void *obj_new(size_t size, ValueTag t)
{
void *p = gc_malloc(size);
VALUE_TAG(p) = t;
return p;
}
Value value_of_string(const char *s)
{
size_t len = strlen(s) + 1;
String *str = obj_new(sizeof(String) + len, TAG_STRING);
strcpy(str->body, s);
return (Value) str;
}
static void expect_cfunc_arity(int64_t actual)
{
if (actual <= CFUNCARG_MAX)
return;
error("arity too large: expected ..%"PRId64" but got %"PRId64,
CFUNCARG_MAX, actual);
}
static Value value_of_cfunc(cfunc_t cfunc, int64_t arity)
{
expect_cfunc_arity(arity);
CFunc *f = obj_new(sizeof(CFunc), TAG_CFUNC);
f->proc.arity = arity;
f->cfunc = cfunc;
return (Value) f;
}
static Value value_of_syntax(cfunc_t cfunc, int64_t arity)
{
Value sp = value_of_cfunc(cfunc, arity);
VALUE_TAG(sp) = TAG_SYNTAX;
return sp;
}
static Value value_of_closure(Table *env, Value params, Value body)
{
Closure *f = obj_new(sizeof(Closure), TAG_CLOSURE);
f->proc.arity = (params == Qnil || value_is_pair(params)) ? length(params) : -1;
f->env = env;
f->params = params;
f->body = body;
return (Value) f;
}
// and `cons` is well-known name than "value_of_pair"
//
// Errors
//
#define error(fmt, ...) \
error("%s:%d of %s: " fmt, __FILE__, __LINE__, __func__ __VA_OPT__(,) __VA_ARGS__)
static jmp_buf jmp_runtime_error, jmp_exit;
static uint8_t exit_status; // to be portable
static char errmsg[BUFSIZ];
#define runtime_error(...) raise_error(jmp_runtime_error, __VA_ARGS__)
ATTR(noreturn)
void raise_error(jmp_buf buf, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(errmsg, sizeof(errmsg), fmt, ap);
va_end(ap);
longjmp(buf, 1);
}
const char *error_message(void)
{
return errmsg;
}
static void expect_type(const char *header, Type expected, Value v)
{
Type t = value_type_of(v);
if (t == expected)
return;
runtime_error("type error in %s: expected %s but got %s",
header, value_type_to_string(expected), value_type_to_string(t));
}
#define expect_type_twin(h, t, x, y) expect_type(h, t, x), expect_type(h, t, y)
static void expect_type_or(const char *header, Type e1, Type e2, Value v)
{
Type t = value_type_of(v);
if (t == e1 || t == e2)
return;
runtime_error("type error in %s: expected %s or %s but got %s",
header, value_type_to_string(e1), value_type_to_string(e2),
value_type_to_string(t));
}
static void expect_list_head(const char *header, Value v)
{
expect_type_or(header, TYPE_NULL, TYPE_PAIR, v);
}
static void expect_arity_range(const char *func, int64_t min, int64_t max, Value args)
{
int64_t actual = length(args);
if (min <= actual && (max == -1 || actual <= max))
return;
runtime_error("%s: wrong number of arguments: expected %"PRId64"..%"PRId64" but got %"PRId64,
func, min, max, actual);
}
static void expect_arity_min(const char *func, int64_t min, Value args)
{
expect_arity_range(func, min, -1, args);
}
static void expect_arity(int64_t expected, Value args)
{
int64_t actual = length(args);
if (expected < 0 || expected == actual)
return;
runtime_error("wrong number of arguments: expected %"PRId64" but got %"PRId64,
expected, actual);
}
static Value apply_cfunc(Table *env, Value proc, Value args)
{
Value a[CFUNCARG_MAX];
CFunc *cf = CFUNC(proc);
int64_t n = cf->proc.arity;
Value arg = args;
for (int i = 0; i < n; i++) {
a[i] = car(arg);
arg = cdr(arg);
}
cfunc_t f = cf->cfunc;
#if defined(__clang__) && __clang_major__ >= 15
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-non-prototype"
#endif
switch (n) {
case -1:
return (*f)(env, args);
case 0:
return (*f)(env);
case 1:
return (*f)(env, a[0]);
case 2:
return (*f)(env, a[0], a[1]);
case 3:
return (*f)(env, a[0], a[1], a[2]);
default:
error("arity too large: %"PRId64, n);
}
#if defined(__clang__) && __clang_major__ >= 15
#pragma clang diagnostic pop
#endif
}
static Value append2(Value l1, Value l2)
{
if (l2 == Qnil)
return l1;
if (l1 == Qnil)
return l2;
Value ret = list1(car(l1)), prev = ret;
for (Value p = cdr(l1); p != Qnil; p = cdr(p)) {
Value curr = list1(car(p));
PAIR(prev)->cdr = curr;
prev = curr;
}
PAIR(prev)->cdr = l2;
return ret;
}
static Table *env_put(Table *env, Value sym, Value val)
{
return table_put(env, value_to_symbol(sym), val);
}
static bool env_set(Table *env, Value sym, Value val)
{
return table_set(env, value_to_symbol(sym), val);
}
static Value env_get(const Table *env, Value sym)
{
Value found = table_get(env, value_to_symbol(sym));
if (found == TABLE_NOT_FOUND)
return Qundef;
return found;
}
static Value eval_body(Table *env, Value body);
//PTR
static Value apply_closure(Value proc, Value args)
{
Closure *cl = CLOSURE(proc);
int64_t arity = cl->proc.arity;
Table *clenv = table_inherit(cl->env);
Value params = cl->params;
if (arity == -1)
env_put(clenv, params, args);
else {
for (; args != Qnil; args = cdr(args), params = cdr(params))
env_put(clenv, car(params), car(args));
}
return eval_body(clenv, cl->body); // XXX: table_free(clenv)?
}
ATTR(noreturn) ATTR(noinline)
static void jump(Continuation *cont)
{
call_stack = cont->call_stack;
memcpy(cont->sp, cont->shelter, cont->shelter_len);
longjmp(cont->state, 1);
}
#define GET_SP(p) uintptr_t v##p = 0, *p = &v##p
ATTR(noreturn) ATTR(noinline)
static void apply_continuation(Value f, Value args)
{
GET_SP(sp);
Continuation *cont = CONTINUATION(f);
cont->retval = car(args);
int64_t d = sp - cont->sp;
if (d < 1)
d = 1;
volatile uintptr_t pad[d];
pad[0] = pad[d-1] = 0; // avoid unused
jump(cont);
}
// expects proc and args have been evaluated if necessary
static Value apply(Table *env, Value proc, Value args)
{
expect_arity(PROCEDURE(proc)->arity, args);
switch (VALUE_TAG(proc)) {
case TAG_SYNTAX:
case TAG_CFUNC:
return apply_cfunc(env, proc, args);
case TAG_CLOSURE:
return apply_closure(proc, args);
case TAG_CONTINUATION:
apply_continuation(proc, args); // no return!
default:
UNREACHABLE();
}
}
// Note: Do not mistake this for "(define-syntax ...)" which related to macros
static void define_syntax(Table *env, const char *name, cfunc_t cfunc, int64_t arity)
{
env_put(env, value_of_symbol(name), value_of_syntax(cfunc, arity));
}
static void define_procedure(Table *env, const char *name, cfunc_t cfunc, int64_t arity)
{
env_put(env, value_of_symbol(name), value_of_cfunc(cfunc, arity));
}
static Value assq(Value key, Value l);
#define CXR1(f, x) f(a, x); f(d, x);
#define CXR2(f, x) CXR1(f, a ## x) CXR1(f, d ## x)
#define CXR3(f, x) CXR2(f, a ## x) CXR2(f, d ## x)
#define CXR4(f, x) CXR3(f, a) CXR3(f, d)
#define CXRS(f) CXR2(f,) CXR3(f,) CXR4(f,)
#define DEF_CXR(x, y) \
static Value c##x##y##r(Value v) { return c##x##r(c##y##r(v)); }
CXRS(DEF_CXR)
//
// Evaluation
//
static Value eval(Table *env, Value v);
static Value eval_body(Table *env, Value body)
{
if (body == Qnil)
return Qnil;
Value p = body;
for (Value next; (next = cdr(p)) != Qnil; p = next)
eval(env, car(p));
return eval(env, car(p));
}
static Value eval_body_tmpenv(Table *env, Value body)
{
Value ret = eval_body(env, body);
table_free(env);
return ret;
}
static Value map_eval(Table *env, Value l)
{
Value mapped = DUMMY_PAIR();
for (Value last = mapped; l != Qnil; l = cdr(l))
last = PAIR(last)->cdr = list1(eval(env, car(l)));
return cdr(mapped);
}
static void call_stack_push(Value l)
{
call_stack = cons(l, call_stack);
}
static void call_stack_pop(void)
{
expect_type("apply", TYPE_PAIR, call_stack);
call_stack = cdr(call_stack);
}
static Value eval_apply(Table *env, Value l)
{
call_stack_push(l);
Value symproc = car(l), args = cdr(l);
Value proc = eval(env, symproc);
expect_type("eval", TYPE_PROC, proc);
if (!value_tag_is(proc, TAG_SYNTAX))
args = map_eval(env, args);
Value ret = apply(env, proc, args);
call_stack_pop();
return ret;
}
static Value lookup_or_error(Table *env, Value v)
{
Value p = env_get(env, v);
if (p == Qundef)
runtime_error("unbound variable: %s", value_to_string(v));
return p;
}
static Value eval(Table *env, Value v)
{
if (value_is_symbol(v))
return lookup_or_error(env, v);
if (v == Qnil || !value_is_pair(v))
return v;
return eval_apply(env, v);
}
ATTR(format(printf, 1, 2))
static int append_error_message(const char *fmt, ...)
{
size_t len = strlen(errmsg);
va_list ap;
va_start(ap, fmt);
int n = vsnprintf(errmsg + len, sizeof(errmsg) - len, fmt, ap);
va_end(ap);
return n;
}
static void dump_line_column(Value vfilename, int64_t pos)
{
int64_t line, col;
Value data = assq(vfilename, source_data);
if (data == Qnil) {
append_error_message("\n\t<unknown>");
return;
}
Value newline_pos = caddr(data);
pos_to_line_col(pos, newline_pos, &line, &col);
const char *filename = value_to_string(vfilename);
append_error_message("\n\t%s:%"PRId64":%"PRId64" in ", filename, line, col);
}
static bool find_pair(Value tree, Value pair)
{
for (; tree != Qnil; tree = cdr(tree)) {
if (tree == pair)
return true;
if (!value_is_pair(tree))
return false;
Value v = car(tree);
if (value_is_pair(v) && find_pair(v, pair))
return true;
}
return false;
}
static Value find_filename(Value pair)
{
for (Value p = source_data; p != Qnil; p = cdr(p)) {
Value tree = cadar(p);
if (find_pair(tree, pair))
return caar(p); // filename
}
return Qfalse;
}
static void dump_callee_name(Value callers)
{
if (callers == Qnil) {
append_error_message("<toplevel>");
return;
}
Value sym = caar(callers);
if (!value_is_symbol(sym)) {
append_error_message("<unknown>");
return;
}
const char *name = value_to_string(sym);
append_error_message("'%s'", name);
}
static void dump_frame(Value pair, Value callers)
{
Value filename = find_filename(pair);
if (filename == Qfalse) {
append_error_message("\n\t<unknown>");
return;
}
dump_line_column(filename, LOCATED_PAIR(pair)->pos);
dump_callee_name(callers);
}
static void dump_stack_trace()
{
for (Value p = call_stack, next; p != Qnil; p = next) {
next = cdr(p);
dump_frame(car(p), next);
}
}
static void fdisplay(FILE* f, Value v);
static void call_stack_check_consistency(void)
{
if (call_stack == Qnil)
return;
fprintf(stderr, "BUG: got non-null call stack: ");
fdisplay(stderr, call_stack);
fprintf(stderr, "\n");
}
static Value iload(FILE *in, const char *filename)
{
Value ast = iparse(in, filename), l = cadr(ast);
source_data = cons(ast, source_data);
if (l == Qundef)
return Qundef;
if (setjmp(jmp_runtime_error) != 0) {
dump_stack_trace();
return Qundef;
}
if (setjmp(jmp_exit) != 0)
return value_of_int(exit_status);
call_stack = Qnil;
Value ret = eval_body(toplevel_environment, l);
call_stack_check_consistency();
return ret;
}
static Value iload_inner(FILE *in, const char *path)
{
Value ast = iparse(in, path), l = cadr(ast);
source_data = cons(ast, source_data);
if (l == Qundef)
return Qundef;
return eval_body(toplevel_environment, l);
}
Value eval_string(const char *in)
{
FILE *f = fmemopen((char *) in, strlen(in), "r");
Value v = iload(f, "<inline>");
fclose(f);
return v;
}
static FILE *open_loadable(const char *path)
{
static char rpath[PATH_MAX];
char joined[PATH_MAX];
snprintf(joined, sizeof(joined), "%s/%s", load_basedir, path);
(void)!realpath(joined, rpath);
FILE *in = fopen(rpath, "r");
if (in == NULL)
error("load: can't open file: %s", path);
load_basedir = dirname(rpath);
return in;
}
Value load(const char *path)
{
FILE *in = open_loadable(path);
Value retval = iload(in, path);
fclose(in);
return retval;
}
static Value load_inner(const char *path)
{
const char *basedir_saved = load_basedir;
FILE *in = open_loadable(path);
Value retval = iload_inner(in, path);
fclose(in);
load_basedir = basedir_saved;
return retval;
}
//
// Built-in Procedures / Syntax
//
#define UNUSED ATTR(unused)
// 4.1. Primitive expression types
// 4.1.2. Literal expressions
static Value syn_quote(UNUSED Table *env, Value datum)
{
return datum;
}
// 4.1.4. Procedures
//PTR -- proper tail recursion needed
static Value syn_lambda(Table *env, Value args)
{
Value params = car(args), body = cdr(args);
if (params != Qnil)
expect_type_or("lambda", TYPE_PAIR, TYPE_SYMBOL, params);
expect_type("lambda", TYPE_PAIR, body);
return value_of_closure(env, params, body);
}
// 4.1.5. Conditionals
//PTR
static Value syn_if(Table *env, Value args)
{
expect_arity_range("if", 2, 3, args);
Value cond = car(args), then = cadr(args);
if (eval(env, cond) != Qfalse)
return eval(env, then);
Value els = cddr(args);
if (els == Qnil)
return Qnil;
return eval(env, car(els));
}
// 4.1.6. Assignments
static Value iset(Table *env, Value ident, Value val)
{
bool found = env_set(env, ident, val);
if (!found)
runtime_error("set!: unbound variable: %s", value_to_string(ident));
return Qnil;
}
static Value syn_set(Table *env, Value ident, Value expr)
{
expect_type("set!", TYPE_SYMBOL, ident);
return iset(env, ident, eval(env, expr));
}
// 4.2. Derived expression types
// 4.2.1. Conditionals
static inline void expect_null(const char *msg, Value l)
{
if (l != Qnil)
runtime_error("%s: expected null?", msg);
}
static Value cond_eval_recipient(Table *env, Value test, Value recipients)
{
expect_type("recipient in cond", TYPE_PAIR, recipients);
Value recipient = eval(env, car(recipients)), rest = cdr(recipients);
expect_type("end of => in cond", TYPE_PROC, recipient);
expect_null("end of => in cond", rest);
return apply(env, recipient, list1(test));
}
//PTR
static Value syn_cond(Table *env, Value clauses)
{
expect_arity_min("cond", 1, clauses);
for (; clauses != Qnil; clauses = cdr(clauses)) {
Value clause = car(clauses);
expect_type("clause in cond", TYPE_PAIR, clause);
Value test = car(clause);
Value exprs = cdr(clause);
if (test == SYM_ELSE)
return eval_body(env, exprs);
Value t = eval(env, test);
if (t != Qfalse) {
if (exprs == Qnil)
return t;
if (car(exprs) == SYM_RARROW)
return cond_eval_recipient(env, t, cdr(exprs));
return eval_body(env, exprs);
}
}
return Qnil;
}
static Value memq(Value key, Value l);
//PTR
static Value syn_case(Table *env, Value args)
{
expect_arity_min("case", 2, args);
Value key = eval(env, car(args)), clauses = cdr(args);
expect_list_head("case", clauses);
for (; clauses != Qnil; clauses = cdr(clauses)) {
Value clause = car(clauses);
expect_type("case", TYPE_PAIR, clause);
Value data = car(clause), exprs = cdr(clause);
expect_type("case", TYPE_PAIR, exprs);
if (data == SYM_ELSE || memq(key, data) != Qfalse)
return eval_body(env, exprs);
}
return Qnil;
}
//PTR
static Value syn_and(Table *env, Value args)
{
if (args == Qnil)
return Qtrue;
Value p = args;
for (Value next; (next = cdr(p)) != Qnil; p = next) {
if (eval(env, car(p)) == Qfalse)
return Qfalse;
}
return eval(env, car(p));
}
//PTR
static Value syn_or(Table *env, Value args)
{
if (args == Qnil)
return Qfalse;
Value p = args;
for (Value next, v; (next = cdr(p)) != Qnil; p = next) {
if ((v = eval(env, car(p))) != Qfalse)
return v;
}
return eval(env, car(p));
}
// 4.2.2. Binding constructs
static void transpose_2xn(Value ls, Value *pfirsts, Value *pseconds) // 2 * n
{
Value firsts = DUMMY_PAIR(), seconds = DUMMY_PAIR();
for (Value lfirsts = firsts, lseconds = seconds; ls != Qnil; ls = cdr(ls)) {
Value l = car(ls);
expect_arity(2, l);
lfirsts = PAIR(lfirsts)->cdr = list1(car(l));
lseconds = PAIR(lseconds)->cdr = list1(cadr(l));
}
*pfirsts = cdr(firsts);
*pseconds = cdr(seconds);
}
static Value let(Table *env, Value var, Value bindings, Value body)
{
expect_list_head("let", bindings);
Value params = Qnil, symargs = Qnil;
transpose_2xn(bindings, ¶ms, &symargs);
Value args = map_eval(env, symargs);
if (var == Qfalse) {
Value proc = value_of_closure(env, params, body);
return apply_closure(proc, args);
}
Table *letenv = table_inherit(env);
Value proc = value_of_closure(letenv, params, body);
env_put(letenv, var, proc); // affects as proc->env
Value ret = apply_closure(proc, args);
table_free(letenv);
return ret;
}
//PTR
static Value syn_let(Table *env, Value args)
{
expect_arity_min("let", 2, args);
Value bind_or_var = car(args), body = cdr(args);
Value var = Qfalse, bindings = bind_or_var;
if (value_is_symbol(bind_or_var)) {
var = bind_or_var;
bindings = car(body);
body = cdr(body);
}
return let(env, var, bindings, body);
}
static Value let_star(Table *env, Value bindings, Value body)
{
expect_list_head("let*", bindings);
Table *letenv = env;
for (; bindings != Qnil; bindings = cdr(bindings)) {
Value b = car(bindings);
expect_type("let*", TYPE_PAIR, b);
if (length(b) != 2)
runtime_error("let*: malformed binding in let: %s", stringify(b));
Value ident = car(b), expr = cadr(b);
expect_type("let*", TYPE_SYMBOL, ident);
letenv = table_inherit(letenv);
Value val = eval(letenv, expr);
env_put(letenv, ident, val);
}
return eval_body(letenv, body);
}
//PTR
static Value syn_let_star(Table *env, Value args)
{
expect_arity_min("let*", 2, args);
return let_star(env, car(args), cdr(args));
}
//PTR
static Value syn_letrec(Table *env, Value args)
{
expect_arity_min("letrec", 2, args);
Value bindings = car(args);
Value body = cdr(args);
expect_list_head("letrec", bindings);
expect_type("letrec", TYPE_PAIR, body);
Table *letenv = table_inherit(env);
for (; bindings != Qnil; bindings = cdr(bindings)) {
Value b = car(bindings);
expect_type("letrec", TYPE_PAIR, b);
Value ident = car(b);
expect_type("letrec", TYPE_SYMBOL, ident);
Value val = eval(letenv, cadr(b));
env_put(letenv, ident, val);
}
return eval_body_tmpenv(letenv, body);
}
// 4.2.3. Sequencing
//PTR
static Value syn_begin(Table *env, Value body)
{
return eval_body(env, body);
}
// 4.2.4. Iteration
//PTR
static Value syn_do(Table *env, Value args)