-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterp.cc
331 lines (262 loc) · 8.27 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
/** @file interp.cc
*
* PL/0 interpreter in C++
*
* @author Randy Merkel, Slowly but Surly Software.
* @copyright (c) 2017 Slowly but Surly Software. All rights reserved.
*/
#include <algorithm>
#include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
#include "interp.h"
using namespace std;
// private:
/// Dump the current machine state
void Interp::dump() {
cout << fixed; // Use fixed format for floating point values;
// Dump the last write
if (lastWrite.valid())
cout
<< " "
<< setw(5) << lastWrite << ": "
<< setw(10) << stack[lastWrite]
<< std::endl;
lastWrite.invalidate();
if (!verbose) return;
// Dump the current activation frame...
assert(sp >= fp);
cout << "fp: " << setw(5) << fp << ": "
<< right << setw(10) << stack[fp]
<< endl;
for (auto bl = fp+1; bl < sp; ++bl)
cout
<< " " << setw(5) << bl << ": "
<< right << setw(10) << stack[bl]
<< endl;
cout << "sp: " << setw(5) << sp << ": "
<< right << setw(10) << stack[sp]
<< endl;
disasm(cout, pc, code[pc], "pc");
cout << endl;
}
// protected:
/**
* @param lvl Number of levels down
* @return The base, lvl's down the stack
*/
Datum::Unsigned Interp::base(Datum::Unsigned lvl) {
auto b = fp;
for (; lvl > 0; --lvl)
b = stack[b].uinteger();
return b;
}
/**
* Make sure that there is room for at least sp+n elements in the stack.
* @param n Maximum number of entries pushed down on the stack, if necessary, to make
* sufficient room for sp+n entries.
*/
void Interp::mkStackSpace(Datum::Unsigned n) {
while (stack.size() <= static_cast<unsigned> (sp + n))
stack.push_back(-1);
}
/// @return the top-of-stack
Datum Interp::pop() { return stack[sp--]; }
/// @param d Datum to push on to the stack
void Interp::push(Datum d) {
mkStackSpace(1);
stack[++sp] = d;
}
/**
* @param nlevel Set the subroutines frame base nlevel's down
* @param addr The address of the subroutine.
*/
void Interp::call(int8_t nlevel, Datum::Unsigned addr) {
mkStackSpace(FrameSize);
const auto oldFp = fp; // Save a copy before we modify it
// Push a new activation frame block on the stack:
push(base(nlevel)); // FrameBase
fp = sp; // fp points to the start of the new frame
push(oldFp); // FrameOldFp
push(pc); // FrameRetAddr
push(0u); // FrameRetVal
pc = addr;
}
/**
* Unlinks the stack frame, setting the return address as the next instruciton.
*/
void Interp::ret() {
sp = fp - 1; // "pop" the activaction frame
pc = stack[fp + FrameRetAddr].uinteger();
fp = stack[fp + FrameOldFp].uinteger();
sp -= ir.addr.uinteger(); // Pop parameters, if any...
}
/// Unlink the stack frame, set the return address, and then push the function result
void Interp::retf() {
// Save the function result, unlink the stack frame, return the result
auto temp = stack[fp + FrameRetVal];
ret();
push(temp);
}
/// @return Result::success or...
Interp::Result Interp::step() {
auto prevPc = pc; // The previous pc
ir = code[pc++]; // Fetch next instruction...
++ncycles;
auto info = OpCodeInfo::info(ir.op);
if (sp < info.nElements()) {
cerr << "Out of bounds stack access @ pc (" << prevPc << "), sp == " << sp << "!\n";
return Result::stackUnderflow;
}
Datum rhand; // right-hand side of a binary operation
switch(ir.op) {
case OpCode::ITOR:
stack[sp] = stack[sp].integer() * 1.0;
break;
case OpCode::ITOR2:
stack[sp-1] = stack[sp-1].integer() * 1.0;
break;
case OpCode::RTOI:
stack[sp] = static_cast<Datum::Integer>(round(stack[sp].real()));
break;
case OpCode::Not: stack[sp] = !stack[sp]; break;
case OpCode::Neg: stack[sp] = -stack[sp]; break;
case OpCode::Comp: stack[sp] = ~stack[sp]; break;
case OpCode::Add: rhand = pop(); push(pop() + rhand); break;
case OpCode::Sub: rhand = pop(); push(pop() - rhand); break;
case OpCode::Mul: rhand = pop(); push(pop() * rhand); break;
case OpCode::Div:
rhand = pop();
if ((rhand.kind() == Datum::Kind::Real && rhand.real() != 0) || rhand.integer() != 0)
push(pop() / rhand);
else {
cerr << "Attempt to divide by zero @ pc (" << prevPc << ")!\n";
return Result::divideByZero;
}
break;
case OpCode::Rem:
rhand = pop();
if ((rhand.kind() == Datum::Kind::Real && rhand.real() != 0) || rhand.real() != 0)
push(pop() % rhand);
else {
cerr << "attempt to divide by zero @ pc (" << prevPc << ")!\n";
return Result::divideByZero;
}
break;
case OpCode::BOR: rhand = pop(); push(pop() | rhand); break;
case OpCode::BAND: rhand = pop(); push(pop() & rhand); break;
case OpCode::BXOR: rhand = pop(); push(pop() ^ rhand); break;
case OpCode::LShift: rhand = pop(); push(pop() << rhand); break;
case OpCode::RShift: rhand = pop(); push(pop() >> rhand); break;
case OpCode::LT: rhand = pop(); push(pop() < rhand); break;
case OpCode::LTE: rhand = pop(); push(pop() <= rhand); break;
case OpCode::EQU: rhand = pop(); push(pop() == rhand); break;
case OpCode::GTE: rhand = pop(); push(pop() >= rhand); break;
case OpCode::GT: rhand = pop(); push(pop() > rhand); break;
case OpCode::NEQU: rhand = pop(); push(pop() != rhand); break;
case OpCode::LOR: rhand = pop(); push(pop() || rhand); break;
case OpCode::LAND: rhand = pop(); push(pop() && rhand); break;
case OpCode::Push: push(ir.addr); break;
case OpCode::PushVar:
push(base(ir.level) + ir.addr.integer());
break;
case OpCode::Eval: { auto ea = pop(); push(stack[ea.uinteger()]); }
break;
case OpCode::Assign:
lastWrite = pop().uinteger(); // Save the effective address for dump()...
stack[lastWrite] = pop();
break;
case OpCode::Call: call(ir.level, ir.addr.uinteger()); break;
case OpCode::Ret: ret(); break;
case OpCode::Retf: retf(); break;
case OpCode::Enter:
mkStackSpace(ir.addr.uinteger());
sp+=ir.addr.uinteger();
break;
case OpCode::Jump: pc = ir.addr.uinteger(); break;
case OpCode::JNEQ:
if (pop().integer() == 0)
pc = ir.addr.uinteger();
break;
case OpCode::Halt: return Result::halted; break;
default:
cerr << "Unknown op code: " << OpCodeInfo::info(ir.op).name()
<< " found at pc (" << prevPc << ")!\n" << endl;
return Result::unknownInstr;
};
return Result::success;
}
/**
* @return Result::success, or ...
*/
Interp::Result Interp::run() {
if (verbose)
cout << "Reg Addr Value/Instr\n"
<< "---------------------\n";
Result status = Result::success;
do {
if (pc >= code.size()) {
cerr << "pc (" << pc << ") is out of range: [0.." << code.size() << ")!\n";
status = Result::badFetch;
} else if (sp >= stack.size()) {
cerr << "sp (" << sp << ") is out of range [0.." << stack.size() << ")!\n";
status = Result::stackUnderflow;
} else {
dump(); // Dump state and disasm the next instruction
status = step();
}
} while (Result::success == status);
return status;
}
//public
/**
* Initialize the machine into a reset state with verbose == false.
*/
Interp::Interp() : stack(FrameSize), verbose(false), ncycles(0) {
reset();
}
/**
* @param program The program to run
* @param ver True for verbose/debugging messages
* @return The number of machine cycles run
*/
Interp::Result Interp::operator()(const InstrVector& program, bool ver) {
verbose = ver;
code = program;
reset();
auto result = run();
if (Result::halted == result)
result = Result::success; // halted is normal!
return result;
}
void Interp::reset() {
pc = 0;
fp = 0; // Setup the initial activacation frame
for (sp = 0; sp < FrameSize; ++sp)
stack[sp] = 0;
sp = stack.size() - 1;
ncycles = 0;
}
/// @return number of machien cycles run so far
size_t Interp::cycles() const {
return ncycles;
}
// public static
/**
* @param r Result who's name we want
* @return r's name string.
*/
string Interp::toString(Result r) {
switch (r) {
case Result::success: return "success"; break;
case Result::divideByZero: return "divideByZero"; break;
case Result::badFetch: return "badFetch"; break;
case Result::unknownInstr: return "unknownInstr"; break;
case Result::stackOverflow: return "stackOverflow"; break;
case Result::stackUnderflow: return "stackUnderflow"; break;
case Result::halted: return "halted"; break;
default: return "undefined error!";
}
}