-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterpreter.cpp
More file actions
480 lines (399 loc) · 12.9 KB
/
interpreter.cpp
File metadata and controls
480 lines (399 loc) · 12.9 KB
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
#include "interpreter.hpp"
#include <iostream>
#include <stdexcept>
#include <utility>
Interpreter::Value Interpreter::Value::makeInt(long long v) {
Value x;
x.type = TypeKind::Int;
x.intValue = v;
return x;
}
Interpreter::Value Interpreter::Value::makeBool(bool v) {
Value x;
x.type = TypeKind::Bool;
x.boolValue = v;
return x;
}
Interpreter::Value Interpreter::Value::makeStr(std::string v) {
Value x;
x.type = TypeKind::Str;
x.strValue = std::move(v);
return x;
}
Interpreter::Value Interpreter::Value::makeArray(std::size_t size) {
Value x;
x.type = TypeKind::Array;
x.arrayValue.resize(size);
x.elementType = TypeKind::Unknown;
return x;
}
Interpreter::RuntimeEnvironment::RuntimeEnvironment() { beginScope(); }
void Interpreter::RuntimeEnvironment::beginScope() { scopes_.push_back({}); }
void Interpreter::RuntimeEnvironment::endScope() {
if (scopes_.empty()) {
throw std::runtime_error("runtime error: no scope to pop");
}
scopes_.pop_back();
}
void Interpreter::RuntimeEnvironment::define(const std::string &name,
Value value) {
if (scopes_.empty()) {
throw std::runtime_error("runtime error: no active scope");
}
auto &scope = scopes_.back();
auto [it, inserted] = scope.emplace(name, std::move(value));
if (!inserted) {
throw std::runtime_error("runtime error: redeclaration of variable '" +
name + "'");
}
}
Interpreter::Value *
Interpreter::RuntimeEnvironment::resolve(const std::string &name) {
for (int i = (int)scopes_.size() - 1; i >= 0; --i) {
auto it = scopes_[i].find(name);
if (it != scopes_[i].end()) {
return &it->second;
}
}
return nullptr;
}
const Interpreter::Value *
Interpreter::RuntimeEnvironment::resolve(const std::string &name) const {
for (int i = (int)scopes_.size() - 1; i >= 0; --i) {
auto it = scopes_[i].find(name);
if (it != scopes_[i].end()) {
return &it->second;
}
}
return nullptr;
}
void Interpreter::RuntimeEnvironment::assign(const std::string &name,
Value value) {
Value *slot = resolve(name);
if (!slot) {
throw std::runtime_error(
"runtime error: assignment to undefined variable '" + name + "'");
}
*slot = std::move(value);
}
Interpreter::Interpreter() = default;
void Interpreter::execute(const std::vector<std::unique_ptr<Stmt>> &program) {
// Register functions before executing top-level statements. Function bodies
// are executed only when the function is called.
for (const auto &st : program) {
if (auto *fn = dynamic_cast<const FuncStmt *>(st.get())) {
functions_[fn->name] = fn;
}
}
for (const auto &st : program) {
if (dynamic_cast<const FuncStmt *>(st.get()))
continue;
executeStmt(st.get());
}
}
void Interpreter::executeStmt(const Stmt *st) {
if (dynamic_cast<const FuncStmt *>(st)) {
return;
}
if (auto *s = dynamic_cast<const ReturnStmt *>(st)) {
Value v = defaultValue();
if (s->value)
v = evalExpr(s->value.get());
throw ReturnSignal{std::move(v)};
}
if (auto *s = dynamic_cast<const VarStmt *>(st)) {
Value init = defaultValue();
if (s->arraySize > 0) {
init = Value::makeArray(s->arraySize);
env_.define(s->name, std::move(init));
return;
}
if (s->init) {
init = evalExpr(s->init.get());
}
env_.define(s->name, std::move(init));
return;
}
if (auto *s = dynamic_cast<const PrintStmt *>(st)) {
Value v = evalExpr(s->expr.get());
std::cout << valueToString(v) << "\n";
return;
}
if (auto *s = dynamic_cast<const ExprStmt *>(st)) {
(void)evalExpr(s->expr.get());
return;
}
if (auto *s = dynamic_cast<const BlockStmt *>(st)) {
env_.beginScope();
try {
for (const auto &child : s->stmts) {
executeStmt(child.get());
}
env_.endScope();
} catch (...) {
env_.endScope();
throw;
}
return;
}
if (auto *s = dynamic_cast<const IfStmt *>(st)) {
Value cond = evalExpr(s->cond.get());
if (cond.type != TypeKind::Bool) {
throw std::runtime_error("runtime error: if condition is not bool");
}
if (cond.boolValue) {
executeStmt(s->thenBranch.get());
} else if (s->elseBranch) {
executeStmt(s->elseBranch.get());
}
return;
}
if (auto *s = dynamic_cast<const WhileStmt *>(st)) {
while (true) {
Value cond = evalExpr(s->cond.get());
if (cond.type != TypeKind::Bool) {
throw std::runtime_error("runtime error: while condition is not bool");
}
if (!cond.boolValue) {
break;
}
executeStmt(s->body.get());
}
return;
}
throw std::runtime_error("runtime error: unknown statement node");
}
Interpreter::Value Interpreter::evalExpr(const Expr *e) {
if (auto *x = dynamic_cast<const NumberExpr *>(e)) {
return Value::makeInt(x->value);
}
if (auto *x = dynamic_cast<const StringExpr *>(e)) {
return Value::makeStr(x->value);
}
if (auto *x = dynamic_cast<const BoolExpr *>(e)) {
return Value::makeBool(x->value);
}
if (auto *x = dynamic_cast<const IdentExpr *>(e)) {
const Value *v = env_.resolve(x->name);
if (!v) {
throw std::runtime_error("runtime error: undefined variable '" + x->name +
"'");
}
if (v->type == TypeKind::Array) {
throw std::runtime_error("runtime error: array '" + x->name +
"' cannot be used as a scalar value");
}
return *v;
}
if (auto *x = dynamic_cast<const CallExpr *>(e)) {
return callFunction(x);
}
if (auto *x = dynamic_cast<const IndexExpr *>(e)) {
Value *array = env_.resolve(x->name);
if (!array) {
throw std::runtime_error("runtime error: undefined array '" + x->name +
"'");
}
if (array->type != TypeKind::Array) {
throw std::runtime_error("runtime error: variable '" + x->name +
"' is not an array");
}
Value index = evalExpr(x->index.get());
if (index.type != TypeKind::Int) {
throw std::runtime_error("runtime error: array index must be int");
}
if (index.intValue < 0 ||
static_cast<std::size_t>(index.intValue) >= array->arrayValue.size()) {
throw std::runtime_error("runtime error: array index out of bounds");
}
const Value &slot =
array->arrayValue[static_cast<std::size_t>(index.intValue)];
if (slot.type == TypeKind::Unknown) {
throw std::runtime_error(
"runtime error: reading uninitialized array element");
}
return slot;
}
if (auto *x = dynamic_cast<const ArrayAssignExpr *>(e)) {
Value *array = env_.resolve(x->name);
if (!array) {
throw std::runtime_error("runtime error: undefined array '" + x->name +
"'");
}
if (array->type != TypeKind::Array) {
throw std::runtime_error("runtime error: variable '" + x->name +
"' is not an array");
}
Value index = evalExpr(x->index.get());
if (index.type != TypeKind::Int) {
throw std::runtime_error("runtime error: array index must be int");
}
if (index.intValue < 0 ||
static_cast<std::size_t>(index.intValue) >= array->arrayValue.size()) {
throw std::runtime_error("runtime error: array index out of bounds");
}
Value rhs = evalExpr(x->value.get());
if (rhs.type == TypeKind::Array) {
throw std::runtime_error(
"runtime error: arrays cannot be stored inside arrays");
}
if (array->elementType == TypeKind::Unknown) {
array->elementType = rhs.type;
} else if (array->elementType != rhs.type) {
throw std::runtime_error("runtime error: array element type mismatch");
}
array->arrayValue[static_cast<std::size_t>(index.intValue)] = rhs;
return rhs;
}
if (auto *x = dynamic_cast<const AssignExpr *>(e)) {
Value rhs = evalExpr(x->value.get());
env_.assign(x->name, rhs);
return rhs;
}
if (auto *x = dynamic_cast<const UnaryExpr *>(e)) {
Value rhs = evalExpr(x->rhs.get());
if (x->op == "-") {
if (rhs.type != TypeKind::Int) {
throw std::runtime_error("runtime error: unary '-' expects int");
}
return Value::makeInt(-rhs.intValue);
}
if (x->op == "!") {
if (rhs.type != TypeKind::Bool) {
throw std::runtime_error("runtime error: unary '!' expects bool");
}
return Value::makeBool(!rhs.boolValue);
}
throw std::runtime_error("runtime error: unknown unary operator '" + x->op +
"'");
}
if (auto *x = dynamic_cast<const BinaryExpr *>(e)) {
Value lhs = evalExpr(x->lhs.get());
Value rhs = evalExpr(x->rhs.get());
if (x->op == "+") {
if (lhs.type == TypeKind::Int && rhs.type == TypeKind::Int) {
return Value::makeInt(lhs.intValue + rhs.intValue);
}
if (lhs.type == TypeKind::Str && rhs.type == TypeKind::Str) {
return Value::makeStr(lhs.strValue + rhs.strValue);
}
throw std::runtime_error("runtime error: invalid operands for '+'");
}
if (x->op == "-") {
requireInts(lhs, rhs, "-");
return Value::makeInt(lhs.intValue - rhs.intValue);
}
if (x->op == "*") {
requireInts(lhs, rhs, "*");
return Value::makeInt(lhs.intValue * rhs.intValue);
}
if (x->op == "/") {
requireInts(lhs, rhs, "/");
if (rhs.intValue == 0) {
throw std::runtime_error("runtime error: division by zero");
}
return Value::makeInt(lhs.intValue / rhs.intValue);
}
if (x->op == "<") {
requireInts(lhs, rhs, "<");
return Value::makeBool(lhs.intValue < rhs.intValue);
}
if (x->op == "<=") {
requireInts(lhs, rhs, "<=");
return Value::makeBool(lhs.intValue <= rhs.intValue);
}
if (x->op == ">") {
requireInts(lhs, rhs, ">");
return Value::makeBool(lhs.intValue > rhs.intValue);
}
if (x->op == ">=") {
requireInts(lhs, rhs, ">=");
return Value::makeBool(lhs.intValue >= rhs.intValue);
}
if (x->op == "==") {
return Value::makeBool(equals(lhs, rhs));
}
if (x->op == "!=") {
return Value::makeBool(!equals(lhs, rhs));
}
throw std::runtime_error("runtime error: unknown binary operator '" +
x->op + "'");
}
throw std::runtime_error("runtime error: unknown expression node");
}
Interpreter::Value Interpreter::callFunction(const CallExpr *call) {
auto it = functions_.find(call->callee);
if (it == functions_.end()) {
throw std::runtime_error("runtime error: undefined function '" +
call->callee + "'");
}
const FuncStmt *fn = it->second;
if (call->args.size() != fn->params.size()) {
throw std::runtime_error("runtime error: function '" + call->callee +
"' expects " + std::to_string(fn->params.size()) +
" arguments, got " +
std::to_string(call->args.size()));
}
std::vector<Value> argValues;
argValues.reserve(call->args.size());
for (const auto &arg : call->args)
argValues.push_back(evalExpr(arg.get()));
env_.beginScope();
try {
for (std::size_t i = 0; i < fn->params.size(); ++i) {
env_.define(fn->params[i], std::move(argValues[i]));
}
if (auto *body = dynamic_cast<const BlockStmt *>(fn->body.get())) {
for (const auto &child : body->stmts)
executeStmt(child.get());
} else {
executeStmt(fn->body.get());
}
env_.endScope();
return defaultValue();
} catch (const ReturnSignal &ret) {
env_.endScope();
return ret.value;
} catch (...) {
env_.endScope();
throw;
}
}
std::string Interpreter::valueToString(const Value &v) {
switch (v.type) {
case TypeKind::Int:
return std::to_string(v.intValue);
case TypeKind::Bool:
return v.boolValue ? "true" : "false";
case TypeKind::Str:
return v.strValue;
case TypeKind::Array:
return "<array>";
default:
return "<unknown>";
}
}
void Interpreter::requireInts(const Value &lhs, const Value &rhs,
const std::string &op) {
if (lhs.type != TypeKind::Int || rhs.type != TypeKind::Int) {
throw std::runtime_error("runtime error: operator '" + op +
"' expects int operands");
}
}
bool Interpreter::equals(const Value &lhs, const Value &rhs) {
if (lhs.type != rhs.type) {
throw std::runtime_error(
"runtime error: '=='/'!=' require operands of the same type");
}
switch (lhs.type) {
case TypeKind::Int:
return lhs.intValue == rhs.intValue;
case TypeKind::Bool:
return lhs.boolValue == rhs.boolValue;
case TypeKind::Str:
return lhs.strValue == rhs.strValue;
default:
throw std::runtime_error("runtime error: cannot compare unknown values");
}
}
Interpreter::Value Interpreter::defaultValue() { return Value{}; }