-
Notifications
You must be signed in to change notification settings - Fork 3
/
wart.c
4616 lines (4311 loc) · 146 KB
/
wart.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
/*
* wart.c -- WebAssembly Actor Runtime
* Copyright 2022 Dale Schumacher
*/
/**
See further [https://github.com/organix/mycelia/blob/master/wart.md]
**/
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h> // for intptr_t, uintptr_t, uint8_t, uint16_t, etc.
#include <inttypes.h> // for PRIiPTR, PRIuPTR, PRIXPTR, etc.
#include <time.h> // for clock_t, clock(), etc.
#define ERROR(x) x // include/exclude error instrumentation
#define WARN(x) x // include/exclude warning instrumentation
#define DEBUG(x) // include/exclude debug instrumentation
#define XDEBUG(x) // include/exclude extra debugging
#define MTRACE(x) // include/exclude macro tracing
#define ATRACE(x) // include/exclude meta-actor tracing
#define PTRACE(x) // include/exclude PEG-actor tracing
#define NO_CELL_FREE 0 // never release allocated cells
#define GC_CALL_DEPTH 0 // count recursion depth during garbage collection
#define GC_TRACE_FREE 1 // trace free list during mark phase
#define CONCURRENT_GC 0 // interleave garbage collection with event dispatch
#define MULTIPHASE_GC 0 // perform gc mark and sweep separately
#define TIME_DISPATCH 1 // measure execution time for message dispatch
#define META_ACTORS 1 // include meta-actors facilities
#define PEG_ACTORS 1 // include PEG parsing facilities
#define RUN_SELF_TEST 1 // include and run unit-test suite
#define RUN_FILE_REPL 1 // evalutate code from files and interactive REPL
#ifndef __SIZEOF_POINTER__
#error "need __SIZEOF_POINTER__ for hexdump()"
#endif
typedef intptr_t int_t;
typedef uintptr_t nat_t;
typedef void *ptr_t;
#define INT(n) ((int_t)(n))
#define NAT(n) ((nat_t)(n))
#define PTR(n) ((ptr_t)(n))
// WASM base types
typedef int32_t i32;
typedef int64_t i64;
typedef struct cell {
int_t head;
int_t tail;
} cell_t;
#define PROC_DECL(name) int_t name(int_t self, int_t arg)
typedef PROC_DECL((*proc_t));
#define TAG_MASK INT(0x3)
#define TAG_FIXNUM INT(0x0)
#define TAG_PAIR INT(0x1)
#define TAG_ENUM INT(0x2)
#define TAG_ACTOR INT(0x3)
#define ENUM_MASK INT(0xF)
#define ENUM_PROC INT(0x2)
#define ENUM_SYMBOL INT(0x6)
#define ENUM_RSVD1 INT(0xA)
#define ENUM_RSVD2 INT(0xE)
#define IS_ADDR(v) ((v)&1)
#define MK_NUM(n) INT(NAT(n)<<2)
#define MK_PAIR(p) INT(PTR(p)+TAG_PAIR)
#define MK_ENUM(n) INT((NAT(n)<<4)|TAG_ENUM)
#define MK_ACTOR(p) INT(PTR(p)+TAG_ACTOR)
#define MK_SYM(n) (MK_ENUM(n)|ENUM_SYMBOL)
#define MK_PROC(f) INT(PTR(f)+TAG_ENUM)
#define MK_BOOL(b) ((b) ? TRUE : FALSE)
#define IS_NUM(v) (((v)&TAG_MASK) == TAG_FIXNUM)
#define IS_PAIR(v) (((v)&TAG_MASK) == TAG_PAIR)
#define IS_ENUM(v) (((v)&TAG_MASK) == TAG_ENUM)
#define IS_ACTOR(v) (((v)&TAG_MASK) == TAG_ACTOR)
//#define IS_SYM(v) (((v)&ENUM_MASK) == ENUM_SYMBOL)
#define IS_SYM(v) (IS_ENUM(v)&&((v)<0xFFFF))
#define IS_PROC(v) (IS_ENUM(v)&&((v)>0xFFFF))
#define TO_INT(v) (INT(v)>>2)
#define TO_NAT(v) (NAT(v)>>2)
#define TO_PTR(v) PTR(NAT(v)&~TAG_MASK)
#define TO_ENUM(v) (INT(v)>>4)
#define TO_PROC(v) ((proc_t)(PTR(v)-TAG_ENUM))
void newline() { // DO NOT MOVE -- USED TO DEFINE is_proc()
printf("\n");
fflush(stdout);
}
#define OK (0)
#define INF MK_NUM(TO_INT(~(NAT(-1)>>1)))
#define UNDEF MK_ACTOR(&a_undef)
#define UNIT MK_ACTOR(&a_unit)
#define FALSE MK_ACTOR(&a_false)
#define TRUE MK_ACTOR(&a_true)
#define NIL MK_ACTOR(&a_nil)
#define FAIL MK_ACTOR(&a_fail)
// FORWARD DECLARATIONS
PROC_DECL(Undef);
PROC_DECL(Unit);
PROC_DECL(Boolean);
PROC_DECL(Null);
PROC_DECL(Pair);
PROC_DECL(Symbol);
PROC_DECL(Fixnum);
PROC_DECL(Fail);
int is_proc(int_t val);
void print(int_t value);
void debug_print(char *label, int_t value);
static void hexdump(char *label, int_t *addr, size_t cnt);
const cell_t a_undef = { .head = MK_PROC(Undef), .tail = UNDEF };
const cell_t a_unit = { .head = MK_PROC(Unit), .tail = UNIT };
const cell_t a_false = { .head = MK_PROC(Boolean), .tail = FALSE };
const cell_t a_true = { .head = MK_PROC(Boolean), .tail = TRUE };
const cell_t a_nil = { .head = MK_PROC(Null), .tail = NIL };
const cell_t a_fail = { .head = MK_PROC(Fail), .tail = FAIL };
/*
* error handling
*/
int_t panic(char *reason) {
fprintf(stderr, "\nPANIC! %s\n", reason);
exit(-1);
return UNDEF; // not reached, but typed for easy swap with error()
}
int_t error(char *reason) {
fprintf(stderr, "\nERROR! %s\n", reason);
return UNDEF;
}
int_t failure(char *_file_, int _line_) {
fprintf(stderr, "\nASSERT FAILED! %s:%d\n", _file_, _line_);
return UNDEF;
}
#define ASSERT(cond) if (!(cond)) return failure(__FILE__, __LINE__)
/*
* heap memory management (cells)
*/
#define CELL_MAX (1 << 12) // 4K cells
cell_t cell[CELL_MAX] = {
{ .head = 1, .tail = 1 }, // root cell (limit,free)
{ .head = 0, .tail = 0 }, // end of free-list
};
// note: free-list is linked by index, not with pointers
int in_heap(int_t val) {
return IS_ADDR(val) && (NAT(TO_PTR(val) - PTR(cell)) < sizeof(cell));
}
PROC_DECL(FreeCell) {
ERROR(debug_print("FreeCell self", self));
return panic("DISPATCH TO FREE CELL!");
}
#define FREE_CELL MK_PROC(FreeCell)
static int gc_running = 0; // set during unsafe gc phase(s)
#if CONCURRENT_GC
static void gc_set_mark(i32 ofs); // FORWARD DECLARATION
static void gc_clr_mark(i32 ofs); // FORWARD DECLARATION
#else
static int gc_free_cnt = 0;
#endif
static cell_t *cell_new() {
int_t head = cell[0].tail;
int_t next = cell[head].tail;
if (next) {
// use cell from free-list
cell[0].tail = next;
#if CONCURRENT_GC
gc_set_mark(head);
#else
--gc_free_cnt;
#endif
return &cell[head];
}
next = head + 1;
if (next < CELL_MAX) {
// extend top of heap
cell[next].head = 0;
cell[next].tail = 0;
cell[0].head = next;
cell[0].tail = next;
#if CONCURRENT_GC
gc_set_mark(head);
#endif
return &cell[head];
}
panic("out of cell memory");
return PTR(0); // NOT REACHED!
}
static void cell_reclaim(cell_t *p) {
XDEBUG(fprintf(stderr, "cell_reclaim: p=%p\n", p));
#if !NO_CELL_FREE
// link into free-list
p->tail = cell[0].tail;
int_t ofs = INT(p - cell);
XDEBUG(fprintf(stderr, "cell_reclaim: ofs=%"PRIdPTR"\n", ofs));
cell[0].tail = ofs;
#if !CONCURRENT_GC
++gc_free_cnt;
#endif
#endif
}
int_t cell_free(int_t val) {
XDEBUG(debug_print("cell_free val", val));
if (!in_heap(val)) panic("free() of non-heap cell");
cell_t *p = TO_PTR(val);
ASSERT(p->head != FREE_CELL); // double-free
p->head = FREE_CELL;
p->tail = FREE_CELL;
#if CONCURRENT_GC
if (gc_running) {
int_t ofs = INT(p - cell);
XDEBUG(fprintf(stderr, "cell_free: *running* ofs=%"PRIdPTR"\n", ofs));
gc_clr_mark(ofs);
return NIL;
}
#endif
cell_reclaim(p);
return NIL;
}
int_t cons(int_t head, int_t tail) {
cell_t *p = cell_new();
p->head = head;
p->tail = tail;
return MK_PAIR(p);
}
#define list_0 NIL
#define list_1(v1) cons((v1), NIL)
#define list_2(v1,v2) cons((v1), cons((v2), NIL))
#define list_3(v1,v2,v3) cons((v1), cons((v2), cons((v3), NIL)))
#define list_4(v1,v2,v3,v4) cons((v1), cons((v2), cons((v3), cons((v4), NIL))))
#define list_5(v1,v2,v3,v4,v5) cons((v1), cons((v2), cons((v3), cons((v4), cons((v5), NIL)))))
#define list_6(v1,v2,v3,v4,v5,v6) cons((v1), cons((v2), cons((v3), cons((v4), cons((v5), cons((v6), NIL))))))
int_t car(int_t val) {
if (!IS_PAIR(val)) return error("car() of non-PAIR");
cell_t *p = TO_PTR(val);
return p->head;
}
int_t cdr(int_t val) {
if (!IS_PAIR(val)) return error("cdr() of non-PAIR");
cell_t *p = TO_PTR(val);
return p->tail;
}
int equal(int_t x, int_t y) {
XDEBUG(debug_print("equal x", x));
XDEBUG(debug_print("equal y", y));
#if 0
return (x == y)
|| (IS_PAIR(x) && IS_PAIR(y) && equal(car(x), car(y)) && equal(cdr(x), cdr(y)));
#else
if (x == y) return 1;
while (IS_PAIR(x) && IS_PAIR(y)) {
if (!equal(car(x), car(y))) break;
x = cdr(x);
y = cdr(y);
if (x == y) return 1;
}
return 0;
#endif
}
int list_len(int_t val) {
int len = 0;
while (IS_PAIR(val)) {
++len;
val = cdr(val);
}
return len;
}
int_t set_car(int_t val, int_t head) {
if (!in_heap(val)) panic("set_car() of non-heap cell");
cell_t *p = TO_PTR(val);
return p->head = head;
}
int_t set_cdr(int_t val, int_t tail) {
if (!in_heap(val)) panic("set_cdr() of non-heap cell");
cell_t *p = TO_PTR(val);
return p->tail = tail;
}
int_t get_code(int_t val) {
int_t code = UNDEF; // polymorphic dispatch procedure
if (IS_ACTOR(val)) {
cell_t *p = TO_PTR(val);
code = p->head;
} else if (IS_PAIR(val)) {
code = MK_PROC(Pair);
} else if (IS_NUM(val)) {
code = MK_PROC(Fixnum);
} else if (IS_SYM(val)) {
code = MK_PROC(Symbol);
} else if (IS_PROC(val)) {
code = val;
} else {
code = error("undefined dispatch procedure");
}
return code;
}
int_t get_data(int_t val) {
int_t data = val;
if (IS_ACTOR(val)) {
cell_t *p = TO_PTR(val);
data = p->tail;
}
return data;
}
PROC_DECL(obj_call) {
int_t code = get_code(self);
if (!IS_PROC(code)) return error("obj_call() requires a procedure");
proc_t proc = TO_PROC(code);
return (*proc)(self, arg);
}
/*
* garbage collection (reclaiming the heap)
*/
#define GC_LO_BITS(ofs) ((ofs) & 0x1F)
#define GC_HI_BITS(ofs) ((ofs) >> 5)
#define GC_MAX_BITS GC_HI_BITS(CELL_MAX)
i32 gc_bits[GC_MAX_BITS];
i32 gc_clear() { // clear all GC bits
XDEBUG(fprintf(stderr, "> gc_clear\n"));
for (i32 i = 0; i < GC_MAX_BITS; ++i) {
gc_bits[i] = 0;
}
XDEBUG(fprintf(stderr, "< gc_clear\n"));
return 0;
}
static i32 gc_get_mark(i32 ofs) {
return ((gc_bits[GC_HI_BITS(ofs)] & (1 << GC_LO_BITS(ofs))));
}
static void gc_set_mark(i32 ofs) {
XDEBUG(fprintf(stderr, " gc_set_mark(%d)\n", ofs));
gc_bits[GC_HI_BITS(ofs)] |= (1 << GC_LO_BITS(ofs));
}
static void gc_clr_mark(i32 ofs) {
XDEBUG(fprintf(stderr, " gc_clr_mark(%d)\n", ofs));
gc_bits[GC_HI_BITS(ofs)] &= ~(1 << GC_LO_BITS(ofs));
}
i32 gc_mark_free() { // mark cells in the free-list
XDEBUG(fprintf(stderr, "> gc_mark_free\n"));
//gc_set_mark(0);
i32 cnt = 0;
#if GC_TRACE_FREE
i32 ofs = cell[0].tail;
while (ofs) {
gc_set_mark(ofs);
++cnt;
ofs = cell[ofs].tail;
}
#else
i32 ofs = cell[0].head;
DEBUG(fprintf(stderr, " gc_mark_free: top=%d\n", ofs));
//gc_set_mark(ofs);
cell[0].tail = ofs; // empty free-list
#endif
XDEBUG(fprintf(stderr, "< gc_mark_free (cnt=%d)\n", cnt));
return cnt;
}
#if GC_CALL_DEPTH
i32 gc_mark_cell(int_t val, i32 depth)
#else
i32 gc_mark_cell(int_t val)
#endif
{ // mark cells reachable from `val`
//DEBUG(fprintf(stderr, "> gc_mark_cell val=16#%"PRIxPTR"\n", val));
XDEBUG(debug_print("> gc_mark_cell", val));
i32 cnt = 0;
while (in_heap(val)) {
cell_t *p = TO_PTR(val);
i32 ofs = INT(p - cell);
if (gc_get_mark(ofs)) {
break; // cell already marked
}
gc_set_mark(ofs);
++cnt;
#if GC_CALL_DEPTH
cnt += gc_mark_cell(p->head, ++depth); // recurse on head
#else
cnt += gc_mark_cell(p->head); // recurse on head
#endif
val = p->tail; // iterate over tail
}
#if GC_CALL_DEPTH
XDEBUG(fprintf(stderr, "< gc_mark_cell depth=%d (cnt=%d)\n", depth, cnt));
#else
XDEBUG(fprintf(stderr, "< gc_mark_cell (cnt=%d)\n", cnt));
#endif
//XDEBUG(fprintf(stderr, "< gc_mark_cell val=16#%"PRIxPTR" (cnt=%d)\n", val, cnt));
return cnt;
}
static cell_t event_q; // FORWARD DECLARATION
static cell_t gnd_locals; // FORWARD DECLARATION
i32 gc_mark_roots() { // mark cells reachable from the root-set
XDEBUG(fprintf(stderr, "> gc_mark_roots\n"));
i32 n = 0;
#if GC_CALL_DEPTH
n += gc_mark_cell(event_q.head, 0);
n += gc_mark_cell(gnd_locals.head, 0);
#else
n += gc_mark_cell(event_q.head);
n += gc_mark_cell(gnd_locals.head);
#endif
XDEBUG(fprintf(stderr, "< gc_mark_roots (n=%d)\n", n));
return n;
}
i32 gc_sweep() { // free unmarked cells
XDEBUG(fprintf(stderr, "> gc_sweep\n"));
i32 cnt = 0;
//if (!gc_get_mark(0)) panic("heap root not marked");
i32 next = cell[0].head;
//if (!gc_get_mark(next)) panic("heap next not marked");
DEBUG(fprintf(stderr, " gc_sweep: top=%d\n", next));
while (--next > 0) {
if (!gc_get_mark(next)) {
cell_reclaim(&cell[next]);
++cnt;
}
}
XDEBUG(fprintf(stderr, "< gc_sweep (cnt=%d)\n", cnt));
return cnt;
}
i32 gc_mark_and_sweep() {
i32 n = gc_clear();
n = gc_mark_free();
XDEBUG(printf("gc_mark_and_sweep: marked %d free cells\n", n));
n = gc_mark_roots();
XDEBUG(printf("gc_mark_and_sweep: marked %d used cells\n", n));
n = gc_sweep();
XDEBUG(printf("gc_mark_and_sweep: free'd %d dead cells\n", n));
return n;
}
int_t cell_usage() {
WARN(fprintf(stderr,
"> cell_usage: limit=%"PRIdPTR" free=%"PRIdPTR" max=%"PRIdPTR"\n",
cell[0].head, cell[0].tail, INT(CELL_MAX)));
#if !CONCURRENT_GC
WARN(fprintf(stderr, " cell_usage: gc_free_cnt %d\n", gc_free_cnt));
#endif
int_t count = 0;
int_t prev = 0;
int_t next = cell[0].tail;
while (cell[next].tail) {
XDEBUG(fprintf(stderr, " cell_usage: trace %"PRIdPTR"\n", next));
++count;
prev = next;
next = cell[prev].tail;
}
WARN(fprintf(stderr,
"< cell_usage: free=%"PRIdPTR" total=%"PRIdPTR" max=%"PRIdPTR"\n",
count, next-1, INT(CELL_MAX)));
return cons(MK_NUM(count), MK_NUM(next-1)); // cells (free, heap)
}
/*
* interned strings (symbols)
*/
#define INTERN_MAX (4096)
char intern[INTERN_MAX] = {
0, // end of interned strings
};
int is_symbol(int_t val) {
return IS_SYM(val) && (NAT(PTR(&intern[TO_ENUM(val)]) - PTR(intern)) < sizeof(intern));
}
int_t symbol(char *s) {
int_t j;
int_t n = 0;
while (s[n]) ++n; // compute c-string length
int_t i = 0;
while (intern[i]) {
int_t m = intern[i++]; // symbol length
if (n == m) {
for (j = 0; (j < n); ++j) {
if (s[j] != intern[i+j]) {
goto next;
}
}
// found it!
return MK_SYM(i-1);
}
next: i += m;
}
// new symbol
if ((i + n + 1) >= INTERN_MAX) return panic("out of symbol memory");
intern[i++] = n;
for (j = 0; (j < n); ++j) {
intern[i+j] = s[j];
}
intern[i+n] = 0;
return MK_SYM(i-1);
}
int_t s_ignore;
int_t s_quote;
int_t s_typeq;
int_t s_eval;
int_t s_apply;
int_t s_map;
int_t s_list;
int_t s_cons;
int_t s_car;
int_t s_cdr;
int_t s_if;
int_t s_and;
int_t s_or;
int_t s_eqp;
int_t s_equalp;
int_t s_seq;
int_t s_lambda;
int_t s_macro;
int_t s_vau;
int_t s_define;
int_t s_booleanp;
int_t s_nullp;
int_t s_pairp;
int_t s_symbolp;
int_t s_numberp;
int_t s_add;
int_t s_sub;
int_t s_mul;
int_t s_lt;
int_t s_le;
int_t s_eqn;
int_t s_ge;
int_t s_gt;
int_t s_list_to_number;
int_t s_list_to_symbol;
int_t s_print;
int_t s_emit;
int_t s_debug_print;
int_t s_fold;
int_t s_foldr;
int_t s_bind;
int_t s_lookup;
int_t s_content;
#if META_ACTORS
int_t s_BEH;
int_t s_SELF;
int_t s_CREATE;
int_t s_SEND;
int_t s_BECOME;
int_t s_FAIL;
#endif
// runtime initialization
int_t symbol_boot() {
s_ignore = symbol("_");
s_quote = symbol("quote");
s_typeq = symbol("typeq");
s_eval = symbol("eval");
s_apply = symbol("apply");
s_map = symbol("map");
s_list = symbol("list");
s_cons = symbol("cons");
s_car = symbol("car");
s_cdr = symbol("cdr");
s_if = symbol("if");
s_and = symbol("and");
s_or = symbol("or");
s_eqp = symbol("eq?");
s_equalp = symbol("equal?");
s_seq = symbol("seq");
s_lambda = symbol("lambda");
s_macro = symbol("macro");
s_vau = symbol("vau");
s_define = symbol("define");
s_booleanp = symbol("boolean?");
s_nullp = symbol("null?");
s_pairp = symbol("pair?");
s_symbolp = symbol("symbol?");
s_numberp = symbol("number?");
s_add = symbol("+");
s_sub = symbol("-");
s_mul = symbol("*");
s_lt = symbol("<");
s_le = symbol("<=");
s_eqn = symbol("=");
s_ge = symbol(">=");
s_gt = symbol(">");
s_list_to_number = symbol("list->number");
s_list_to_symbol = symbol("list->symbol");
s_print = symbol("print");
s_emit = symbol("emit");
s_debug_print = symbol("debug-print");
s_fold = symbol("fold");
s_foldr = symbol("foldr");
s_bind = symbol("bind");
s_lookup = symbol("lookup");
s_content = symbol("content");
#if META_ACTORS
s_BEH = symbol("BEH");
s_SELF = symbol("SELF");
s_CREATE = symbol("CREATE");
s_SEND = symbol("SEND");
s_BECOME = symbol("BECOME");
s_FAIL = symbol("FAIL");
#endif
return OK;
}
/*
* actor event dispatch
*/
static cell_t event_q = { .head = NIL, .tail = NIL };
int_t event_q_put(int_t event) {
if (!IS_PAIR(event)) return FAIL;
int_t tail = cons(event, NIL);
if (event_q.head == NIL) {
event_q.head = tail;
} else {
set_cdr(event_q.tail, tail);
}
event_q.tail = tail;
return OK;
}
int_t event_q_pop() {
if (event_q.head == NIL) return UNDEF; // event queue empty
int_t head = event_q.head;
event_q.head = cdr(head);
if (event_q.head == NIL) {
event_q.tail = NIL; // empty queue
}
int_t event = car(head);
head = cell_free(head);
return event;
}
static cell_t saved_q = { .head = NIL, .tail = NIL };
static cell_t saved_a = { .head = UNDEF, .tail = UNDEF };
int_t event_begin(int_t event) {
XDEBUG(debug_print("event_begin event", event));
saved_q = event_q; // snapshot event queue
saved_a.head = UNDEF; // prepare for BECOME
saved_a.tail = UNDEF;
XDEBUG(hexdump("event_begin saved", PTR(&saved_q), 4));
return event;
}
int_t event_commit(int_t event) {
XDEBUG(debug_print("event_commit event", event));
int_t target = car(event);
XDEBUG(debug_print("event_commit target", target));
if ((saved_a.head != UNDEF) && IS_ACTOR(target)) {
cell_t *p = TO_PTR(target);
*p = saved_a; // update target actor
XDEBUG(hexdump("event_commit become", PTR(p), 2));
}
return cell_free(event);
}
int_t event_rollback(int_t event) {
XDEBUG(debug_print("event_rollback event", event));
event_q = saved_q; // restore event queue (un-SEND)
return cell_free(event);
}
i64 event_dispatch_count = 0;
i64 event_dispatch_ticks = 0;
int_t event_dispatch() {
#if TIME_DISPATCH
clock_t t0 = clock();
#endif
int_t event = event_q_pop();
if (!IS_PAIR(event)) return UNDEF; // nothing to dispatch
int_t target = car(event);
XDEBUG(debug_print("event_dispatch target", target));
int_t code = get_code(target);
XDEBUG(debug_print("event_dispatch code", code));
if (!IS_PROC(code)) return error("event_dispatch requires a procedure");
int_t msg = cdr(event);
XDEBUG(debug_print("event_dispatch msg", msg));
event = event_begin(event);
// invoke actor behavior
proc_t proc = TO_PROC(code);
int_t ok = (*proc)(target, msg);
XDEBUG(debug_print("event_dispatch ok", ok));
// apply effect(s)
if (ok == OK) {
event = event_commit(event);
} else {
event = event_rollback(event);
}
// gather statistics
#if TIME_DISPATCH
clock_t t1 = clock();
++event_dispatch_count;
#endif
#if CONCURRENT_GC
#if TIME_DISPATCH
event_dispatch_ticks += (t1 - t0); // exclude gc
DEBUG(double dt = (double)(t1 - t0) / CLOCKS_PER_SEC;
printf("event_dispatch: t0=%ld t1=%ld dt=%.6f (%ld CPS)\n", t0, t1, dt, (long)CLOCKS_PER_SEC));
#endif
#else // !CONCURRENT_GC
if ((gc_free_cnt < 128) && (cell[0].head > (CELL_MAX - 256))) {
int freed = gc_mark_and_sweep();
clock_t t2 = clock();
DEBUG(printf("event_dispatch: gc reclaimed %d cells\n", freed));
#if TIME_DISPATCH
event_dispatch_ticks += (t2 - t0); // include gc
DEBUG(double gc = (double)(t2 - t1) / CLOCKS_PER_SEC;
printf("event_dispatch: t1=%ld t2=%ld gc=%.6f (%ld CPS)\n", t1, t2, gc, (long)CLOCKS_PER_SEC));
#endif
} else {
#if TIME_DISPATCH
event_dispatch_ticks += (t1 - t0); // exclude gc
#endif
}
#if TIME_DISPATCH
DEBUG(double dt = (double)(t1 - t0) / CLOCKS_PER_SEC;
printf("event_dispatch: t0=%ld t1=%ld dt=%.6f (%ld CPS)\n", t0, t1, dt, (long)CLOCKS_PER_SEC));
#endif
#endif // CONCURRENT_GC
return OK;
}
static cell_t a_concurrent_gc; // FORWARD DECLARATION
int_t event_loop() {
#if CONCURRENT_GC
SEND(MK_ACTOR(&a_concurrent_gc), MK_NUM(0)); // start GC actor
#endif
#if TIME_DISPATCH
event_dispatch_count = 0;
event_dispatch_ticks = 0;
#endif
int_t result = OK;
while (result == OK) {
result = event_dispatch();
}
#if TIME_DISPATCH
double average = ((double)event_dispatch_ticks / (double)event_dispatch_count);
printf("event_loop: count=%"PRId64" ticks=%"PRId64" average=%.3f\n",
event_dispatch_count, event_dispatch_ticks, average);
#endif
return result;
}
/*
* actor primitives
*/
int_t actor_create(int_t code, int_t data) {
XDEBUG(debug_print("actor_create code", code));
XDEBUG(debug_print("actor_create data", data));
if (!IS_PROC(code)) return error("CREATE code must be a procedure");
cell_t *p = cell_new();
p->head = code;
p->tail = data;
return MK_ACTOR(p);
}
int_t actor_send(int_t target, int_t msg) {
XDEBUG(debug_print("actor_send target", target));
XDEBUG(debug_print("actor_send msg", msg));
int_t event = cons(target, msg);
return event_q_put(event);
}
int_t actor_become(int_t code, int_t data) {
XDEBUG(debug_print("actor_become code", code));
XDEBUG(debug_print("actor_become data", data));
if (!IS_PROC(code)) return error("BECOME code must be a procedure");
if (IS_PROC(saved_a.head)) return error("only one BECOME allowed");
saved_a.head = code;
saved_a.tail = data;
return OK;
}
/*
* actor behaviors
*/
#define CREATE(c,d) actor_create((c),(d))
#define SEND(t,m) if (actor_send((t),(m)) != OK) return FAIL
#define BECOME(c,d) if (actor_become((c),(d)) != OK) return FAIL
#define GET_VARS() int_t vars = get_data(self)
#define POP_VAR(name) int_t name = car(vars); vars = cdr(vars)
#define TAIL_VAR(name) int_t name = vars
#define GET_ARGS() int_t args = arg
#define POP_ARG(name) int_t name = car(args); args = cdr(args)
#define TAIL_ARG(name) int_t name = args
#define END_ARGS() if (args != NIL) return error("too many args")
PROC_DECL(sink_beh) {
XDEBUG(debug_print("sink_beh self", self));
DEBUG(debug_print("sink_beh arg", arg));
GET_VARS(); // ok
XDEBUG(debug_print("sink_beh vars", vars));
TAIL_VAR(ok);
return ok;
}
const cell_t a_sink = { .head = MK_PROC(sink_beh), .tail = OK };
#define SINK MK_ACTOR(&a_sink)
PROC_DECL(println_beh) {
XDEBUG(debug_print("println_beh self", self));
GET_ARGS(); // value
DEBUG(debug_print("println_beh args", args));
TAIL_ARG(value);
print(value);
newline();
fflush(stdout);
return OK;
}
const cell_t a_println = { .head = MK_PROC(println_beh), .tail = UNDEF };
PROC_DECL(tag_beh) {
XDEBUG(debug_print("tag_beh self", self));
GET_VARS(); // cust
XDEBUG(debug_print("tag_beh vars", vars));
TAIL_VAR(cust);
GET_ARGS(); // msg
XDEBUG(debug_print("tag_beh args", args));
TAIL_ARG(msg);
SEND(cust, cons(self, msg));
return OK;
}
static PROC_DECL(join_h_beh) {
XDEBUG(debug_print("join_h_beh self", self));
GET_VARS(); // (cust head . k_tail)
XDEBUG(debug_print("join_h_beh vars", vars));
POP_VAR(cust);
POP_VAR(head);
TAIL_VAR(k_tail);
GET_ARGS(); // (tag . tail)
XDEBUG(debug_print("join_h_beh args", args));
POP_ARG(tag);
TAIL_ARG(tail);
if (tag == k_tail) {
int_t value = cons(head, tail);
XDEBUG(debug_print("join_h_beh value", value));
SEND(cust, value);
} else {
SEND(cust, error("unexpected join tag"));
}
return OK;
}
static PROC_DECL(join_t_beh) {
XDEBUG(debug_print("join_t_beh self", self));
GET_VARS(); // (cust k_head . tail)
XDEBUG(debug_print("join_t_beh vars", vars));
POP_VAR(cust);
POP_VAR(k_head);
TAIL_VAR(tail);
GET_ARGS(); // (tag . head)
XDEBUG(debug_print("join_t_beh args", args));
POP_ARG(tag);
TAIL_ARG(head);
if (tag == k_head) {
int_t value = cons(head, tail);
XDEBUG(debug_print("join_t_beh value", value));
SEND(cust, value);
} else {
SEND(cust, error("unexpected join tag"));
}
return OK;
}
PROC_DECL(join_beh) {
XDEBUG(debug_print("join_beh self", self));
GET_VARS(); // (cust k_head . k_tail)
XDEBUG(debug_print("join_beh vars", vars));
POP_VAR(cust);
POP_VAR(k_head);
TAIL_VAR(k_tail);
GET_ARGS(); // (tag . value)
XDEBUG(debug_print("join_beh args", args));
POP_ARG(tag);
TAIL_ARG(value);
if (tag == k_head) {
BECOME(MK_PROC(join_h_beh), cons(cust, cons(value, k_tail)));
} else if (tag == k_tail) {
BECOME(MK_PROC(join_t_beh), cons(cust, cons(k_head, value)));
} else {
SEND(cust, error("unexpected join tag"));
}
return OK;
}
PROC_DECL(fork_beh) {
XDEBUG(debug_print("fork_beh self", self));
GET_VARS(); // (cust head . tail)
XDEBUG(debug_print("fork_beh vars", vars));
POP_VAR(cust);
POP_VAR(head);
TAIL_VAR(tail);
GET_ARGS(); // (h_req . t_req)
XDEBUG(debug_print("fork_beh args", args));
POP_ARG(h_req);
TAIL_ARG(t_req);
int_t k_head = CREATE(MK_PROC(tag_beh), self);
int_t k_tail = CREATE(MK_PROC(tag_beh), self);
SEND(head, cons(k_head, h_req));
SEND(tail, cons(k_tail, t_req));
BECOME(MK_PROC(join_beh), cons(cust, cons(k_head, k_tail)));
return OK;
}
#if CONCURRENT_GC
PROC_DECL(gc_sweep_beh); // FORWARD DECLARATION
PROC_DECL(gc_mark_beh) {
XDEBUG(debug_print("gc_mark_beh self", self));
int_t root = event_q.head; // everything is reachable from the event queue
if (root == NIL) {
// if event queue is empty, stop concurrent gc
DEBUG(printf("gc_mark_beh: STOP CONCURRENT GC\n"));
return OK;
}
gc_clear();
XDEBUG(printf("gc_mark_beh: gc marks cleared\n"));
int n = gc_mark_free();
XDEBUG(printf("gc_mark_beh: marked %d free cells\n", n));
#if GC_CALL_DEPTH
int m = gc_mark_cell(root, 0);
#else
int m = gc_mark_cell(root);
#endif
XDEBUG(printf("gc_mark_beh: marked %d used cells\n", m));
gc_running = 1; // enter unsafe gc phase
BECOME(MK_PROC(gc_sweep_beh), UNDEF);
SEND(self, arg);