-
Notifications
You must be signed in to change notification settings - Fork 0
/
Interpreter.cpp
419 lines (362 loc) · 12.3 KB
/
Interpreter.cpp
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
// Copyright 2020 <Copyright hulin>
#include <string>
#include <memory>
#include <iostream>
#include <vector>
#include <stdexcept>
#include "./Interpreter.hpp"
#include "./Expr.hpp"
#include "./Token.hpp"
#include "./Stmt.hpp"
#include "./RuntimeError.hpp"
#include "./Environment.hpp"
#include "./LoxCallable.hpp"
#include "./LoxInstance.hpp"
#include "./LoxClass.hpp"
#include "./LoxFunction.hpp"
#include "./ReturnError.hpp"
#include "./lox.hpp"
using std::stod;
using std::shared_ptr;
using std::cout;
using std::endl;
using std::vector;
using std::exception;
using std::to_string;
bool endsWith(std::string str, std::string suffix) {
if (str.length() < suffix.length()) {
return false;
}
return str.substr(str.length() - suffix.length()) == suffix;
}
void Interpreter::interpret(vector<shared_ptr<Stmt>> statements) {
try {
for (auto statement : statements) {
execute(statement);
}
} catch (RuntimeError error) {
lox::runtimeError(error);
}
}
Interpreter::Interpreter() {
environment = globals;
}
string Interpreter::stringify(Object object) {
string text = object.toString();
string check_str = ".000000";
if (endsWith(text, check_str)) {
return text.erase(text.size() - check_str.size());
}
return text;
}
Object Interpreter::visitLiteralExpr(shared_ptr<Literal<Object>> expr) {
switch (expr->value.type) {
case Object::Object_bool:
return Object::make_bool_obj(expr->value.boolean);
case Object::Object_nil:
return Object::make_nil_obj();
case Object::Object_num:
return Object::make_num_obj(expr->value.num);
default:
return Object::make_str_obj(expr->value.str);
}
}
Object Interpreter::visitGroupingExpr(shared_ptr<Grouping<Object>> expr) {
return evaluate(expr->expression);
}
Object Interpreter::visitUnaryExpr(shared_ptr<Unary<Object>> expr) {
Object right = evaluate(expr->right);
switch (expr->operation.type) {
case BANG:
return Object::make_bool_obj(!isTruthy(right));
case MINUS:
return Object::make_num_obj(-stod(right.toString()));
default:
// Unreachable.
return Object::make_nil_obj();
}
}
Object Interpreter::visitBinaryExpr(shared_ptr<Binary<Object>> expr) {
Object left = evaluate(expr->left);
Object right = evaluate(expr->right);
bool result_bool = false;
string result_str = "";
double result_num = 0;
Object foo;
switch (expr->operation.type) {
case GREATER:
checkNumberOperands(expr->operation, left, right);
result_bool = left.num > right.num;
return Object::make_bool_obj(result_bool);
case GREATER_EQUAL:
checkNumberOperands(expr->operation, left, right);
result_bool = left.num >= right.num;
return Object::make_bool_obj(result_bool);
case LESS:
checkNumberOperands(expr->operation, left, right);
result_bool = left.num < right.num;
foo = Object::make_bool_obj(result_bool);
foo = Object::make_bool_obj(result_bool);
return Object::make_bool_obj(result_bool);
case LESS_EQUAL:
checkNumberOperands(expr->operation, left, right);
result_bool = left.num <= right.num;
return Object::make_bool_obj(result_bool);
case MINUS:
checkNumberOperand(expr->operation, right);
result_num = left.num - right.num;
return Object::make_num_obj(result_num);
case PLUS:
if (left.type == Object::Object_num &&
right.type == Object::Object_num) {
result_num = left.num + right.num;
return Object::make_num_obj(result_num);
}
if (left.type == Object::Object_str &&
right.type == Object::Object_str) {
result_str = left.toString() + right.toString();
return Object::make_str_obj(result_str);
}
throw RuntimeError(expr->operation,
"Operands must be two numbers or two strings.");
case SLASH:
checkNumberOperands(expr->operation, left, right);
result_num = left.num / right.num;
return Object::make_num_obj(result_num);
case STAR:
checkNumberOperands(expr->operation, left, right);
result_num = left.num * right.num;
return Object::make_num_obj(result_num);
case BANG_EQUAL: return Object::make_bool_obj(!isEqual(left, right));
case EQUAL_EQUAL: return Object::make_bool_obj(isEqual(left, right));
default:
return Object::make_nil_obj();
}
}
Object Interpreter::visitAssignExpr(shared_ptr<Assign<Object>> expr) {
Object value = evaluate(expr->value);
// environment->assign(expr->name, value);
auto distance = locals.find(expr);
if (distance != locals.end()) {
environment->assignAt(distance->second, expr->name, value);
} else {
globals->assign(expr->name, value);
}
return value;
}
Object Interpreter::visitLogicalExpr(shared_ptr<Logical<Object>> expr) {
Object left = evaluate(expr->left);
if (expr->operation.type == OR) {
if (isTruthy(left)) return left;
} else {
if (!isTruthy(left)) return left;
}
return evaluate(expr->right);
}
Object Interpreter::visitVariableExpr(shared_ptr<Variable<Object>> expr) {
return lookUpVariable(expr->name, expr);
}
Object Interpreter::lookUpVariable(
Token name, shared_ptr<Expr<Object>> expr) {
auto distance = locals.find(expr);
if (distance != locals.end()) {
return environment->getAt(distance->second, name.lexeme);
} else {
return globals->get(name);
}
}
Object Interpreter::visitCallExpr(shared_ptr<Call<Object>> expr) {
Object callee = evaluate(expr->callee);
vector<Object> arguments;
for (auto argument : expr->arguments) {
arguments.push_back(evaluate(argument));
}
if (callee.type != Object::Object_fun &&
callee.type != Object::Object_class) {
throw RuntimeError(expr->paren,
"Can only call functions and classes.");
}
shared_ptr<LoxCallable> callable;
if (callee.type == Object::Object_fun) {
callable = callee.function;
}
if (callee.type == Object::Object_class) {
callable = callee.lox_class;
}
if (arguments.size() != callable->arity()) {
throw RuntimeError(expr->paren, "Expected " +
to_string(callable->arity()) + " arguments but got " +
to_string(arguments.size()) + ".");
}
return callable->call(shared_from_this(), arguments);
}
Object Interpreter::visitGetExpr(shared_ptr<Get<Object>> expr) {
Object object = evaluate(expr->object);
if (object.type == Object::Object_instance) {
return (object.instance)->get(expr->name);
}
throw RuntimeError(expr->name,
"Only instances have properties.");
}
Object Interpreter::visitSetExpr(shared_ptr<Set<Object>> expr) {
Object object = evaluate(expr->object);
if (object.type != Object::Object_instance) {
throw RuntimeError(expr->name, "Only instances have fields.");
}
Object value = evaluate(expr->value);
object.instance->set(expr->name, value);
return value;
}
Object Interpreter::visitThisExpr(shared_ptr<This<Object>> expr) {
return lookUpVariable(expr->keyword, expr);
}
Object Interpreter::visitSuperExpr(shared_ptr<Super<Object>> expr) {
int distance = locals[expr];
Object superclass = environment->getAt(distance, "super");
// "this" is always one level nearer than "super"'s environment.
Object instance = environment->getAt(distance - 1, "this");
shared_ptr<LoxFunction> method =
superclass.lox_class->findMethod(expr->method.lexeme);
if (method == nullptr) {
throw RuntimeError(expr->method,
"Undefined property '" + expr->method.lexeme + "'.");
}
shared_ptr<LoxFunction> binded_method = method->bind(instance.instance);
return Object::make_fun_obj(binded_method);
}
void Interpreter::visitExpressionStmt(const Expression& stmt) {
evaluate(stmt.expression);
}
void Interpreter::visitPrintStmt(const Print& stmt) {
Object value = evaluate(stmt.expression);
cout << stringify(value) << endl;
}
void Interpreter::visitReturnStmt(const Return& stmt) {
Object value;
if (stmt.value != nullptr) value = evaluate(stmt.value);
throw ReturnError(value);
}
void Interpreter::visitVarStmt(const Var& stmt) {
Object value = Object::make_nil_obj();
if (stmt.initializer != nullptr) {
value = evaluate(stmt.initializer);
}
environment->define(stmt.name.lexeme, value);
}
void Interpreter::visitBlockStmt(const Block& stmt) {
shared_ptr<Environment> env(new Environment(environment));
executeBlock(stmt.statements, env);
}
void Interpreter::visitClassStmt(const Class& stmt) {
Object superclass = Object::make_nil_obj();
if (stmt.superclass != nullptr) {
superclass = evaluate(stmt.superclass);
if (superclass.type != Object::Object_class) {
throw RuntimeError(stmt.superclass->name,
"Superclass must be a class.");
}
}
environment->define(stmt.name.lexeme, Object::make_nil_obj());
if (stmt.superclass != nullptr) {
environment = shared_ptr<Environment>(new Environment(environment));
environment->define("super", superclass);
}
map<string, shared_ptr<LoxFunction>> methods;
for (auto method : stmt.methods) {
bool is_init = method->name.lexeme == "init";
shared_ptr<LoxFunction> function(
new LoxFunction(method, environment, is_init)
);
methods[method->name.lexeme] = function;
}
auto klass = shared_ptr<LoxClass>(
new LoxClass(stmt.name.lexeme, superclass.lox_class, methods)
);
if (superclass.type != Object::Object_nil) {
environment = environment->enclosing;
}
environment->assign(stmt.name, Object::make_class_obj(klass));
}
void Interpreter::visitWhileStmt(const While& stmt) {
while (isTruthy(evaluate(stmt.condition))) {
Object obj = evaluate(stmt.condition);
execute(stmt.body);
}
}
void Interpreter::visitIfStmt(const If& stmt) {
if (isTruthy(evaluate(stmt.condition))) {
execute(stmt.thenBranch);
} else if (stmt.elseBranch != nullptr) {
execute(stmt.elseBranch);
}
}
void Interpreter::visitFunctionStmt(shared_ptr<Function> stmt) {
shared_ptr<LoxFunction> function(new LoxFunction(stmt, environment, false));
Object obj = Object::make_fun_obj(function);
environment->define(stmt->name.lexeme, obj);
}
Object Interpreter::evaluate(shared_ptr<Expr<Object>> expr) {
return expr->accept(shared_from_this());
}
void Interpreter::execute(shared_ptr<Stmt> stmt) {
stmt->accept(shared_from_this());
}
void Interpreter::resolve(shared_ptr<Expr<Object>> expr, int depth) {
locals[expr] = depth;
}
void Interpreter::executeBlock(
vector<shared_ptr<Stmt>> statements,
shared_ptr<Environment> env
) {
shared_ptr<Environment> previous = environment;
environment = env;
for (auto statement : statements) {
execute(statement);
}
environment = previous;
}
bool Interpreter::isTruthy(Object object) {
if (object.type == Object::Object_nil) {
return false;
}
if (object.type == Object::Object_bool) {
return object.boolean;
}
return true;
}
bool Interpreter::isEqual(Object a, Object b) {
if (a.type == Object::Object_nil
&& b.type == Object::Object_nil) {
return true;
}
if (a.type == Object::Object_nil) return false;
if (a.type == b.type) {
switch (a.type) {
case Object::Object_bool:
return a.boolean == b.boolean;
case Object::Object_nil:
return a.nil == b.nil;
case Object::Object_num:
return a.num == b.num;
case Object::Object_str:
return a.str == b.str;
default:
return false;
}
} else {
return false;
}
}
void Interpreter::checkNumberOperand(Token operation, Object operand) {
if (operand.type == Object::Object_num) return;
throw RuntimeError(operation, "Operand must be a number.");
}
void Interpreter::checkNumberOperands(
Token operation,
Object left,
Object right
) {
if (left.type == Object::Object_num &&
right.type == Object::Object_num) return;
throw RuntimeError(operation, "Operand must be a number.");
}