-
Notifications
You must be signed in to change notification settings - Fork 7
/
interp.cc
1706 lines (1528 loc) · 46 KB
/
interp.cc
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 <stdio.h>
#include <stdlib.h>
#include <cstdint>
#include <cstring>
#include <memory>
#include <set>
#include <string>
#include <vector>
#ifdef LIBRARY
#define EXPORT(name) __attribute__((export_name(name)))
void throw_error() __attribute__((noreturn))
__attribute__((import_module("env")))
__attribute__((import_name("throw_error")));
#else
#define EXPORT(name) static
static void throw_error() __attribute__((noreturn));
static void throw_error() {
exit(1);
}
#endif
static void signal_error(const char* message, const char *what) {
if (what)
fprintf(stderr, "error: %s: %s\n", message, what);
else
fprintf(stderr, "error: %s\n", message);
throw_error();
}
class Expr {
public:
enum class Kind { Func, LetRec, Var, Prim, Literal, Call, If };
const Kind kind;
Expr() = delete;
virtual ~Expr() {}
protected:
Expr(Kind kind) : kind(kind) {}
};
class Func : public Expr {
public:
static const uint32_t argCount = 1;
const std::unique_ptr<Expr> body;
void *jitCode;
// FIXME: We need to be able to get to the body from JIT code. Does this mean
// we shouldn't be using unique_ptr ?
static size_t offsetOfBody() { return sizeof(Expr); }
static size_t offsetOfJitCode() { return offsetOfBody() + sizeof(body); }
explicit Func(Expr* body)
: Expr(Kind::Func), body(body), jitCode(nullptr) {}
};
class LetRec : public Expr {
public:
static const uint32_t argCount = 1;
const std::unique_ptr<Expr> arg;
const std::unique_ptr<Expr> body;
LetRec(Expr* arg, Expr* body)
: Expr(Kind::LetRec), arg(arg), body(body) {}
};
class Var : public Expr {
public:
uint32_t depth;
explicit Var(uint32_t depth)
: Expr(Kind::Var), depth(depth) {};
};
class Prim : public Expr {
public:
enum class Op { Eq, LessThan, Sub, Add, Mul };
const Op op;
const std::unique_ptr<Expr> lhs;
const std::unique_ptr<Expr> rhs;
Prim(Op op, Expr* lhs, Expr* rhs)
: Expr(Kind::Prim), op(op), lhs(lhs), rhs(rhs) {};
};
class Literal : public Expr {
public:
const int32_t val;
Literal(int32_t val)
: Expr(Kind::Literal), val(val) {};
};
class Call : public Expr {
public:
const std::unique_ptr<Expr> func;
const std::unique_ptr<Expr> arg;
Call(Expr* func, Expr* arg)
: Expr(Kind::Call), func(func), arg(arg) {};
};
class If : public Expr {
public:
const std::unique_ptr<Expr> test;
const std::unique_ptr<Expr> consequent;
const std::unique_ptr<Expr> alternate;
If(Expr *test, Expr* consequent, Expr* alternate)
: Expr(Kind::If), test(test), consequent(consequent), alternate(alternate) {};
};
class Parser {
std::vector<std::string> boundVars;
void pushBound(std::string &&id) { boundVars.push_back(id); }
void popBound() { boundVars.pop_back(); }
uint32_t lookupBound(const std::string &id) {
for (size_t i = 0; i < boundVars.size(); i++)
if (boundVars[boundVars.size() - i - 1] == id)
return i;
signal_error("unbound identifier", id.c_str());
return -1;
}
const char *buf;
size_t pos;
size_t len;
static bool isAlphabetic(char c) {
return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
}
static bool isNumeric(char c) {
return '0' <= c && c <= '9';
}
static bool isAlphaNumeric(char c) {
return isAlphabetic(c) || isNumeric(c);
}
static bool isWhitespace(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r';
}
void error(const char *message) {
signal_error(message, eof() ? buf : buf + pos);
}
bool eof() const { return pos == len; }
char peek() {
if (eof()) return '\0';
return buf[pos];
}
void advance() {
if (!eof()) pos++;
}
char next() {
char ret = peek();
advance();
return ret;
}
bool matchChar(char c) {
if (eof() || peek() != c)
return false;
advance();
return true;
}
void skipWhitespace() {
while (!eof() && isWhitespace(peek()))
advance();
}
bool startsIdentifier() {
return !eof() && isAlphabetic(peek());
}
bool continuesIdentifier() {
return !eof() && isAlphaNumeric(peek());
}
bool matchIdentifier(const char *literal) {
size_t match_len = std::strlen(literal);
if (match_len < (len - pos))
return false;
if (strncmp(buf + pos, literal, match_len) != 0)
return false;
if ((len - pos) < match_len && isAlphaNumeric(buf[pos + match_len]))
return false;
pos += match_len;
return true;
}
std::string takeIdentifier() {
size_t start = pos;
while (continuesIdentifier())
advance();
size_t end = pos;
return std::string(buf + start, end - start);
}
bool matchKeyword(const char *kw) {
size_t kwlen = std::strlen(kw);
size_t remaining = len - pos;
if (remaining < kwlen)
return false;
if (strncmp(buf + pos, kw, kwlen) != 0)
return false;
pos += kwlen;
if (!continuesIdentifier())
return true;
pos -= kwlen;
return false;
if ((len - pos) < kwlen && isalnum(buf[pos + kwlen]))
return 0;
pos += kwlen;
return 1;
}
Expr *parsePrim(Prim::Op op) {
Expr *lhs = parseOne();
Expr *rhs = parseOne();
return new Prim(op, lhs, rhs);
}
int32_t parseInt32() {
uint64_t ret = 0;
while (!eof() && isNumeric(peek())) {
ret *= 10;
ret += next() - '0';
if (ret > 0x7fffffff)
error("integer too long");
}
if (!eof() && !isWhitespace(peek()) && peek() != ')')
error("unexpected integer suffix");
return ret;
}
Expr *parseOne() {
skipWhitespace();
if (eof())
error("unexpected end of input");
if (matchChar('(')) {
skipWhitespace();
Expr *ret;
if (matchKeyword("lambda")) {
skipWhitespace();
if (!matchChar('('))
error("expected open paren after lambda");
skipWhitespace();
if (!startsIdentifier())
error("expected an argument for lambda");
pushBound(takeIdentifier());
skipWhitespace();
if (!matchChar(')'))
error("expected just one argument for lambda");
Expr *body = parseOne();
popBound();
ret = new Func(body);
} else if (matchKeyword("letrec")) {
skipWhitespace();
if (!matchChar('('))
error("expected open paren after letrec");
if (!matchChar('('))
error("expected two open parens after letrec");
skipWhitespace();
if (!startsIdentifier())
error("expected an identifier for letrec");
pushBound(takeIdentifier());
skipWhitespace();
Expr *arg = parseOne();
if (!matchChar(')'))
error("expected close paren after letrec binding");
skipWhitespace();
if (!matchChar(')'))
error("expected just one binding for letrec");
Expr *body = parseOne();
popBound();
ret = new LetRec(arg, body);
} else if (matchKeyword("+")) {
ret = parsePrim(Prim::Op::Add);
} else if (matchKeyword("-")) {
ret = parsePrim(Prim::Op::Sub);
} else if (matchKeyword("<")) {
ret = parsePrim(Prim::Op::LessThan);
} else if (matchKeyword("eq?")) {
ret = parsePrim(Prim::Op::Eq);
} else if (matchKeyword("*")) {
ret = parsePrim(Prim::Op::Mul);
} else if (matchKeyword("if")) {
Expr *test = parseOne();
Expr *consequent = parseOne();
Expr *alternate = parseOne();
ret = new If(test, consequent, alternate);
} else {
// Otherwise it's a call.
Expr *func = parseOne();
Expr *arg = parseOne();
ret = new Call(func, arg);
}
skipWhitespace();
if (!matchChar(')'))
error("expected close parenthesis");
return ret;
} else if (startsIdentifier()) {
return new Var(lookupBound(takeIdentifier()));
} else if (isNumeric(peek())) {
return new Literal(parseInt32());
} else {
error("unexpected input");
return nullptr;
}
}
public:
explicit Parser(const char *buf)
: buf(buf), pos(0), len(strlen(buf)) {}
Expr *parse() {
Expr *e = parseOne();
skipWhitespace();
if (!eof())
error("expected end of input after expression");
return e;
}
};
EXPORT("parse")
Expr* parse(const char *str) {
return Parser(str).parse();
}
#define FOR_EACH_HEAP_OBJECT_KIND(M) \
M(env, Env) \
M(closure, Closure)
#define DECLARE_CLASS(name, Name) class Name;
FOR_EACH_HEAP_OBJECT_KIND(DECLARE_CLASS)
#undef DECLARE_CLASS
class Heap;
class HeapObject {
public:
// Any other kind value indicates a forwarded object.
enum class Kind : uintptr_t {
#define DECLARE_KIND(name, Name) Name,
FOR_EACH_HEAP_OBJECT_KIND(DECLARE_KIND)
#undef DECLARE_KIND
};
static const uintptr_t NotForwardedBit = 1;
static const uintptr_t NotForwardedBits = 1;
static const uintptr_t NotForwardedBitMask = (1 << NotForwardedBits) - 1;
protected:
uintptr_t tag;
HeapObject(Kind kind)
: tag((static_cast<uintptr_t>(kind) << NotForwardedBits) | NotForwardedBit) {}
public:
static size_t offsetOfTag() { return 0; }
bool isForwarded() const { return (tag & NotForwardedBit) == 0; }
HeapObject *forwarded() const { return reinterpret_cast<HeapObject*>(tag); }
void forward(HeapObject *new_loc) { tag = reinterpret_cast<uintptr_t>(new_loc); }
Kind kind() const { return static_cast<Kind>(tag >> 1); }
#define DEFINE_METHODS(name, Name) \
bool is##Name() const { return kind() == Kind::Name; } \
Name* as##Name() { return reinterpret_cast<Name*>(this); }
FOR_EACH_HEAP_OBJECT_KIND(DEFINE_METHODS)
#undef DEFINE_METHODS
const char *kindName() const {
switch (kind()) {
#define RETURN_KIND_NAME(name, Name) case Kind::Name: return #name;
FOR_EACH_HEAP_OBJECT_KIND(RETURN_KIND_NAME)
#undef RETURN_KIND_NAME
default:
signal_error("unexpected heap object kind", nullptr);
return nullptr;
}
}
inline void* operator new(size_t nbytes, Heap& heap);
};
class Value;
class Heap {
uintptr_t hp;
uintptr_t limit;
uintptr_t base;
size_t size;
long count;
char *mem;
std::vector<Value> roots;
static const uintptr_t ALIGNMENT = 8;
static uintptr_t alignUp(uintptr_t val) {
return (val + ALIGNMENT - 1) & ~(ALIGNMENT - 1);
}
void flip() {
uintptr_t split = base + (size >> 1);
if (hp <= split) {
hp = split;
limit = base + size;
} else {
hp = base;
limit = split;
}
count++;
}
HeapObject* copy(HeapObject *obj);
size_t scan(HeapObject *obj);
void visitRoots();
void collect() {
flip();
uintptr_t grey = hp;
visitRoots();
while(grey < hp)
grey += alignUp(scan(reinterpret_cast<HeapObject*>(grey)));
}
public:
explicit Heap(size_t heap_size) {
mem = new char[alignUp(heap_size)];
if (!mem) {
signal_error("malloc failed", NULL);
}
hp = base = reinterpret_cast<uintptr_t>(mem);
size = heap_size;
count = -1;
flip();
}
~Heap() { delete[] mem; }
static size_t pushRoot(Heap* heap, Value v);
static Value getRoot(Heap* heap, size_t idx);
static void setRoot(Heap* heap, size_t idx, Value v);
static void popRoot(Heap* heap);
template<typename T>
void visit(T **loc) {
HeapObject *obj = *loc;
if (obj != NULL)
*loc = static_cast<T*>(obj->isForwarded() ? obj->forwarded() : copy(obj));
}
inline HeapObject* allocate(size_t size) {
while (1) {
uintptr_t addr = hp;
uintptr_t new_hp = alignUp(addr + size);
if (limit < new_hp) {
collect();
if (limit - hp < size)
signal_error("ran out of space", NULL);
continue;
}
hp = new_hp;
return reinterpret_cast<HeapObject*>(addr);
}
}
};
inline void* HeapObject::operator new(size_t bytes, Heap& heap) {
return heap.allocate(bytes);
}
class Value {
uintptr_t payload;
public:
static const uintptr_t HeapObjectTag = 0;
static const uintptr_t SmiTag = 1;
static const uintptr_t TagBits = 1;
static const uintptr_t TagMask = (1 << TagBits) - 1;
explicit Value(HeapObject *obj)
: payload(reinterpret_cast<uintptr_t>(obj)) {}
explicit Value(intptr_t val)
: payload((static_cast<uintptr_t>(val) << TagBits) | SmiTag) {}
bool isSmi() const { return (payload & TagBits) == SmiTag; }
bool isHeapObject() const { return (payload & TagMask) == HeapObjectTag; }
intptr_t getSmi() const {
return static_cast<intptr_t>(payload) >> TagBits;
}
HeapObject* getHeapObject() {
return reinterpret_cast<HeapObject*>(payload & ~HeapObjectTag);
}
uintptr_t bits() { return payload; }
const char* kindName() {
return isSmi() ? "small integer" : getHeapObject()->kindName();
}
#define DEFINE_METHODS(name, Name) \
bool is##Name() { return isHeapObject() && getHeapObject()->is##Name(); } \
Name* as##Name() { return getHeapObject()->as##Name(); }
FOR_EACH_HEAP_OBJECT_KIND(DEFINE_METHODS)
#undef DEFINE_METHODS
void visitFields(Heap& heap) {
if (isHeapObject())
heap.visit(reinterpret_cast<HeapObject**>(&payload));
}
};
size_t Heap::pushRoot(Heap* heap, Value v) {
size_t ret = heap->roots.size();
heap->roots.push_back(v);
return ret;
}
Value Heap::getRoot(Heap* heap, size_t idx) {
return heap->roots[idx];
}
void Heap::setRoot(Heap* heap, size_t idx, Value v) {
heap->roots[idx] = v;
}
void Heap::popRoot(Heap* heap) { heap->roots.pop_back(); }
template<typename T>
class Rooted {
Heap& heap;
size_t idx;
public:
Rooted(Heap& heap, T* obj) : heap(heap), idx(Heap::pushRoot(&heap, Value(obj))) { }
~Rooted() { Heap::popRoot(&heap); }
T* get() const { return static_cast<T*>(Heap::getRoot(&heap, idx).getHeapObject()); }
void set(T* obj) { Heap::setRoot(&heap, idx, Value(obj)); }
};
template<>
class Rooted<Value> {
Heap& heap;
size_t idx;
public:
Rooted(Heap& heap, Value obj) : heap(heap), idx(Heap::pushRoot(&heap, obj)) { }
~Rooted() { Heap::popRoot(&heap); }
Value get() const { return Heap::getRoot(&heap, idx); }
void set(Value obj) { Heap::setRoot(&heap, idx, obj); }
};
class Env : public HeapObject {
public:
Env *prev;
Value val;
static size_t offsetOfPrev() { return sizeof(HeapObject) + 0; }
static size_t offsetOfVal() { return sizeof(HeapObject) + sizeof(Env*); }
Env(Rooted<Env> &prev, Rooted<Value> &val)
: HeapObject(Kind::Env), prev(prev.get()), val(val.get()) {}
size_t byteSize() { return sizeof(*this); }
void visitFields(Heap& heap) {
heap.visit(&prev);
val.visitFields(heap);
}
static Value lookup(Env *env, uint32_t depth) {
while (depth--)
env = env->prev;
return env->val;
}
};
class Closure : public HeapObject {
public:
Env *env;
Func *func;
static size_t offsetOfEnv() { return sizeof(HeapObject) + 0; }
static size_t offsetOfFunc() { return sizeof(HeapObject) + sizeof(Env*); }
Closure(Rooted<Env>& env, Func *func)
: HeapObject(Kind::Closure), env(env.get()), func(func) {}
size_t byteSize() { return sizeof(*this); }
void visitFields(Heap& heap) {
heap.visit(&env);
}
};
HeapObject* Heap::copy(HeapObject *obj) {
size_t size;
switch (obj->kind()) {
#define COMPUTE_SIZE(name, Name) \
case HeapObject::Kind::Name: \
size = obj->as##Name()->byteSize(); \
break;
FOR_EACH_HEAP_OBJECT_KIND(COMPUTE_SIZE)
#undef COMPUTE_SIZE
}
HeapObject *new_obj = reinterpret_cast<HeapObject*>(hp);
memcpy(new_obj, obj, size);
obj->forward(new_obj);
hp += alignUp(size);
return new_obj;
}
size_t Heap::scan(HeapObject *obj) {
switch (obj->kind()) {
#define SCAN_OBJECT(name, Name) \
case HeapObject::Kind::Name: \
obj->as##Name()->visitFields(*this); \
return obj->as##Name()->byteSize();
FOR_EACH_HEAP_OBJECT_KIND(SCAN_OBJECT)
#undef SCAN_OBJECT
default:
abort ();
}
}
void Heap::visitRoots() {
for (Value& root : roots)
root.visitFields(*this);
}
static Value
eval_primcall(Prim::Op op, intptr_t lhs, intptr_t rhs) {
// FIXME: What to do on overflow.
switch(op) {
case Prim::Op::Eq:
return Value(lhs == rhs);
case Prim::Op::LessThan:
return Value(lhs < rhs);
case Prim::Op::Add:
return Value(lhs + rhs);
case Prim::Op::Sub:
return Value(lhs - rhs);
case Prim::Op::Mul:
return Value(lhs * rhs);
default:
signal_error("unexpected primcall op", nullptr);
return Value(nullptr);
}
}
static std::set<Func*> jitCandidates;
typedef Value (*JitFunction)(Env*, Heap*);
static Value
eval(Expr *expr, Env* unrooted_env, Heap& heap) {
Rooted<Env> env(heap, unrooted_env);
tail:
switch (expr->kind) {
case Expr::Kind::Func: {
Func *func = static_cast<Func*>(expr);
if (!func->jitCode)
jitCandidates.insert(func);
return Value(new(heap) Closure(env, func));
}
case Expr::Kind::Var: {
Var *var = static_cast<Var*>(expr);
return Env::lookup(env.get(), var->depth);
}
case Expr::Kind::Prim: {
Prim *prim = static_cast<Prim*>(expr);
Value lhs = eval(prim->lhs.get(), env.get(), heap);
if (!lhs.isSmi())
signal_error("primcall expected integer lhs, got", lhs.kindName());
Value rhs = eval(prim->rhs.get(), env.get(), heap);
if (!rhs.isSmi())
signal_error("primcall expected integer rhs, got", rhs.kindName());
return eval_primcall(prim->op, lhs.getSmi(), rhs.getSmi());
}
case Expr::Kind::Literal: {
Literal *literal = static_cast<Literal*>(expr);
return Value(literal->val);
}
case Expr::Kind::Call: {
Call *call = static_cast<Call*>(expr);
Rooted<Value> func(heap, eval(call->func.get(), env.get(), heap));
if (!func.get().isClosure())
signal_error("call expected closure, got", func.get().kindName());
Rooted<Value> arg(heap, eval(call->arg.get(), env.get(), heap));
Closure *closure = func.get().asClosure();
Rooted<Env> closure_env(heap, closure->env);
Env *call_env = new(heap) Env(closure_env, arg);
if (closure->func->jitCode) {
JitFunction f = reinterpret_cast<JitFunction>(closure->func->jitCode);
return f(call_env, &heap);
} else {
expr = closure->func->body.get();
env.set(call_env);
goto tail;
}
}
case Expr::Kind::LetRec: {
LetRec *letrec = static_cast<LetRec*>(expr);
{
Rooted<Value> filler(heap, Value(intptr_t(0)));
env.set(new(heap) Env(env, filler));
}
Value arg = eval(letrec->arg.get(), env.get(), heap);
env.get()->val = arg;
expr = letrec->body.get();
goto tail;
}
case Expr::Kind::If: {
If *if_ = static_cast<If*>(expr);
Value test = eval(if_->test.get(), env.get(), heap);
if (!test.isSmi())
signal_error("if expected integer, got", test.kindName());
expr = test.getSmi() ? if_->consequent.get() : if_->alternate.get();
goto tail;
}
default:
signal_error("unexpected expr kind", nullptr);
return Value(nullptr);
}
}
EXPORT("eval")
void eval(Expr* expr, size_t heap_size) {
Heap heap(heap_size);
Value res = eval(expr, nullptr, heap);
fprintf(stdout, "result: %zu\n", res.getSmi());
}
enum class WasmSimpleBlockType : uint8_t {
Void = 0x40, // SLEB128(-0x40)
};
enum class WasmValType : uint8_t {
I32 = 0x7f, // SLEB128(-0x01)
I64 = 0x7e, // SLEB128(-0x02)
F32 = 0x7d, // SLEB128(-0x03)
F64 = 0x7c, // SLEB128(-0x04)
FuncRef = 0x70, // SLEB128(-0x10)
};
using WasmResultType = std::vector<WasmValType>;
struct WasmFuncType {
const WasmResultType params;
const WasmResultType results;
};
struct WasmFunc {
size_t typeIdx;
const std::vector<WasmValType> locals;
const std::vector<uint8_t> code;
};
struct WasmWriter {
std::vector<uint8_t> code;
std::vector<uint8_t> finish() { return code; }
void emit(uint8_t byte) { code.push_back(byte); }
void emitVarU32(uint32_t i) {
do {
uint8_t byte = i & 0x7f;
i >>= 7;
if (i != 0)
byte |= 0x80;
emit(byte);
} while (i != 0);
}
void emitVarI32(int32_t i) {
bool done;
do {
uint8_t byte = i & 0x7f;
i >>= 7;
done = ((i == 0) && !(byte & 0x40)) || ((i == -1) && (byte & 0x40));
if (!done)
byte |= 0x80;
emit(byte);
} while (!done);
}
size_t emitPatchableVarU32() {
size_t offset = code.size();
emitVarU32(UINT32_MAX);
return offset;
}
size_t emitPatchableVarI32() {
size_t offset = code.size();
emitVarI32(INT32_MAX);
return offset;
}
void patchVarI32(size_t offset, int32_t val) {
for (size_t i = 0; i < 5; i++, val >>= 7) {
uint8_t byte = val & 0x7f;
if (i < 4)
byte |= 0x80;
code[offset + i] = byte;
}
}
void patchVarU32(size_t offset, uint32_t val) {
for (size_t i = 0; i < 5; i++, val >>= 7) {
uint8_t byte = val & 0x7f;
if (i < 4)
byte |= 0x80;
code[offset + i] = byte;
}
}
void emitValType(WasmValType t) { emit(static_cast<uint8_t>(t)); }
};
struct WasmAssembler : public WasmWriter {
enum class Op : uint8_t {
Unreachable = 0x00,
Nop = 0x01,
Block = 0x02,
Loop = 0x03,
If = 0x04,
Else = 0x05,
End = 0x0b,
Br = 0x0c,
BrIf = 0x0d,
Return = 0x0f,
// Call operators
Call = 0x10,
CallIndirect = 0x11,
// Parametric operators
Drop = 0x1a,
// Variable access
LocalGet = 0x20,
LocalSet = 0x21,
LocalTee = 0x22,
// Memory-related operators
I32Load = 0x28,
I32Store = 0x36,
// Constants
I32Const = 0x41,
// Comparison operators
I32Eqz = 0x45,
I32Eq = 0x46,
I32Ne = 0x47,
I32LtS = 0x48,
I32LtU = 0x49,
// Numeric operators
I32Add = 0x6a,
I32Sub = 0x6b,
I32Mul = 0x6c,
I32And = 0x71,
I32Or = 0x72,
I32Xor = 0x73,
I32Shl = 0x74,
I32ShrS = 0x75,
I32ShrU = 0x76,
RefNull = 0xd0,
MiscPrefix = 0xfc,
};
enum class MiscOp : uint8_t {
TableGrow = 0x0f,
TableInit = 0x0c,
};
void emitOp(Op op) { emit(static_cast<uint8_t>(op)); }
size_t emitPatchableI32Const() {
emitOp(Op::I32Const);
return emitPatchableVarI32();
}
void emitI32Const(int32_t val) {
emitOp(Op::I32Const);
emitVarI32(val);
}
void emitMemArg(uint32_t align, uint32_t offset) {
emitVarU32(align);
emitVarU32(offset);
}
static const uint32_t Int32SizeLog2 = 2;
void emitI32Load(uint32_t offset = 0) {
// Base address on stack.
emitOp(Op::I32Load);
emitMemArg(Int32SizeLog2, offset);
}
void emitI32Store(uint32_t offset = 0) {
// Base address and value to store on stack.
emitOp(Op::I32Store);
emitMemArg(Int32SizeLog2, offset);
}
void emitLocalGet(uint32_t idx) {
emitOp(Op::LocalGet);
emitVarU32(idx);
}
void emitLocalSet(uint32_t idx) {
emitOp(Op::LocalSet);
emitVarU32(idx);
}
void emitLocalTee(uint32_t idx) {
emitOp(Op::LocalTee);
emitVarU32(idx);
}
void emitI32Eqz() { emitOp(Op::I32Eqz); }
void emitI32Eq() { emitOp(Op::I32Eq); }
void emitI32Ne() { emitOp(Op::I32Ne); }
void emitI32LtS() { emitOp(Op::I32LtS); }
void emitI32LtU() { emitOp(Op::I32LtU); }
void emitI32Add() { emitOp(Op::I32Add); }
void emitI32Sub() { emitOp(Op::I32Sub); }
void emitI32Mul() { emitOp(Op::I32Mul); }
void emitI32And() { emitOp(Op::I32And); }
void emitI32Or() { emitOp(Op::I32Or); }
void emitI32Xor() { emitOp(Op::I32Xor); }
void emitI32Shl() { emitOp(Op::I32Shl); }
void emitI32ShrS() { emitOp(Op::I32ShrS); }
void emitI32ShrU() { emitOp(Op::I32ShrU); }
void emitCallIndirect(uint32_t calleeType, uint32_t table = 0) {
emitOp(Op::CallIndirect);
emitVarU32(calleeType);
emitVarU32(table);
}
void emitRefNull(WasmValType type) {
emitOp(Op::RefNull);
emitValType(type);
}
void emitMiscOp(MiscOp op) {
emitOp(Op::MiscPrefix);
emit(static_cast<uint8_t>(op));
}
void emitTableGrow(uint32_t idx) {
emitMiscOp(MiscOp::TableGrow);
emitVarU32(idx);
}
void emitTableInit(uint32_t dst, uint32_t src) {
emitMiscOp(MiscOp::TableInit);
emitVarU32(dst);
emitVarU32(src);
}
void emitBlock() {
emitOp(Op::Block);
emit(static_cast<uint8_t>(WasmSimpleBlockType::Void));
}
void emitBlock(WasmValType blockType) {
emitOp(Op::Block);
emit(static_cast<uint8_t>(blockType));
}
void emitEnd() { emitOp(Op::End); }
void emitBr(uint32_t offset) {
emitOp(Op::Br);
emitVarU32(offset);
}
void emitBrIf(uint32_t offset) {
emitOp(Op::BrIf);
emitVarU32(offset);
}
void emitUnreachable() {
emitOp(Op::Unreachable);
}
void emitReturn() {
emitOp(Op::Return);
}
};
struct WasmModuleWriter : WasmWriter {
enum class SectionId : uint8_t {
Custom = 0,
Type = 1,
Import = 2,
Function = 3,
Table = 4,
Memory = 5,
Global = 6,
Export = 7,
Start = 8,
Elem = 9,
Code = 10,
Data = 11,
DataCount = 12,
};
enum class DefinitionKind : uint8_t {
Function = 0x00,
Table = 0x01,
Memory = 0x02,
Global = 0x03,
};
enum class LimitsFlags : uint8_t {
Default = 0x0,
HasMaximum = 0x1,
IsShared = 0x2,
IsI64 = 0x4,