-
Notifications
You must be signed in to change notification settings - Fork 0
/
interpreter.h
135 lines (111 loc) · 2.28 KB
/
interpreter.h
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
#ifndef INTERPRETER_H
#define INTERPRETER_H
#include "bc.h"
#include "object.h"
#include <deque>
#include <cassert>
#include <iostream>
#include <stack>
class Interpreter {
class Continuation {
public:
Code* code;
BC* pos;
Continuation(Code* code, BC* pos) :
code(code), pos(pos) {}
};
class Stack {
typedef std::deque<Value*> S;
S s;
public:
void push(Value* v) {
s.push_back(v);
}
size_t size() {
return s.size();
}
Value* pop() {
if (s.empty()) {
std::cout << "Stack underflow\n";
assert(false);
}
Value* t = s.back();
s.pop_back();
return t;
}
Value* top() {
return s.back();
}
template <typename T>
T at(size_t pos) {
T t = dynamic_cast<T>(s[s.size() - pos - 1]);
assert(t);
return t;
}
template <typename T>
T top() {
T t = dynamic_cast<T>(s.back());
assert(t);
return t;
}
template <typename T>
T pop() {
T t = dynamic_cast<T>(s.back());
assert(t);
s.pop_back();
return t;
}
};
typedef std::stack<Continuation*> Ctx;
typedef std::stack<Env*> EnvCtx;
// Global interpreter and context stack
Stack $;
EnvCtx envCtx;
Ctx ctx;
// Interpreter state
Code* code = nullptr;
BC* pc = nullptr;
// Registers local to the function
Env* rho = nullptr;
template <typename T>
T immediate() {
T val = *reinterpret_cast<T*>(pc);
pc = reinterpret_cast<BC*>(
reinterpret_cast<uintptr_t>(pc) + sizeof(T));
return val;
}
void invoke(Code* c) {
storeContext();
code = c;
pc = c->bc;
}
void storeContext() {
Continuation* cont = new Continuation(code, pc);
ctx.push(cont);
}
void storeEnv() {
envCtx.push(rho);
}
void restoreContext() {
assert(!ctx.empty());
Continuation* cont = ctx.top();
ctx.pop();
code = cont->code;
pc = cont->pos;
delete cont;
}
void restoreEnv() {
assert(!envCtx.empty());
rho = envCtx.top();
envCtx.pop();
}
public:
Value* operator () (Code* code) {
return this->operator()(
new Closure(code,
new Env(nullptr),
new Vector({})));
}
Value* operator () (Closure* cls);
};
#endif