-
Notifications
You must be signed in to change notification settings - Fork 0
/
Interpreter.cpp
667 lines (599 loc) · 16.7 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
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
#include "Interpreter.h"
#include "NativeFunctions.h"
#include "LoxLambda.h"
#include "LoxClass.h"
#include "LoxInstance.h"
Environment *Interpreter::environment;
Environment *Interpreter::globals;
std::unordered_map<Expr *, int> *Interpreter::locals;
Interpreter::Interpreter(bool repl)
{
this->repl = repl;
if (!environment)
{
globals = new Environment();
environment = globals;
locals = new std::unordered_map<Expr *, int>();
Object clock(new ClockFunction());
environment->define("clock", clock);
}
}
void Interpreter::runtimeError(Token oper, std::string message)
{
Lox::runtimeError(oper, message);
}
bool Interpreter::isTruthy(Object value)
{
switch (value.type)
{
case TYPE_NIL:
return false;
case TYPE_BOOL:
return value.boolLiteral;
default:
return true;
}
}
bool Interpreter::isEqual(Object a, Object b)
{
if (a.type != b.type)
{
return false;
}
switch (a.type)
{
case TYPE_NIL: return true;
case TYPE_BOOL: return a.boolLiteral == b.boolLiteral;
case TYPE_NUMBER: return a.numLiteral == b.numLiteral;
case TYPE_STRING: return a.strLiteral == b.strLiteral;
case TYPE_FUNCTION: return a.function == b.function;
case TYPE_CLASS: return a.loxClass == b.loxClass;
case TYPE_INSTANCE: return a.loxInstance == b.loxInstance;
}
return false;
}
bool Interpreter::checkNumberOperand(Token oper, Object value)
{
if (value.type == TYPE_NUMBER)
{
return true;
}
else
{
runtimeError(oper, "Operand must be a number.");
return false;
}
}
bool Interpreter::checkNumberOperands(Token oper, Object a, Object b)
{
if (a.type == TYPE_NUMBER && b.type == TYPE_NUMBER)
{
return true;
}
else
{
runtimeError(oper, "Operands must be numbers.");
return false;
}
}
Object Interpreter::visitAssign(Assign *expr)
{
Object value = evaluate(expr->value);
auto it = locals->find(expr);
if (it != locals->end())
{
int distance = it->second;
environment->defineAt(distance, expr->name, value);
}
else
{
globals->assign(expr->name, value);
}
return value;
}
Object Interpreter::visitTernary(Ternary *expr)
{
Object cond = evaluate(expr->first);
if (isTruthy(cond))
{
return evaluate(expr->second);
}
else
{
return evaluate(expr->third);
}
}
Object Interpreter::visitBinary(Binary *expr)
{
Object left = evaluate(expr->left);
Object right = evaluate(expr->right);
switch (expr->oper->type)
{
case MINUS:
{
checkNumberOperands(*expr->oper, left, right);
Object value(left.numLiteral - right.numLiteral);
return value;
}
case STAR:
{
checkNumberOperands(*expr->oper, left, right);
Object value(left.numLiteral * right.numLiteral);
return value;
}
case SLASH:
{
checkNumberOperands(*expr->oper, left, right);
if (right.numLiteral == 0)
{
runtimeError(*expr->oper, "Divide by zero.");
}
Object value(left.numLiteral / right.numLiteral);
return value;
}
case PLUS:
{
if (left.type == TYPE_NUMBER && right.type == TYPE_NUMBER)
{
Object value(left.numLiteral + right.numLiteral);
return value;
}
else if (left.type == TYPE_STRING && right.type == TYPE_STRING)
{
Object value(left.strLiteral + right.strLiteral);
return value;
}
else if (left.type == TYPE_STRING)
{
Object value(left.strLiteral + right.str());
return value;
}
else if (right.type == TYPE_STRING)
{
Object value(left.str() + right.strLiteral);
return value;
}
else
{
runtimeError(*expr->oper, "Operands must be both numbers or at least one should be a string.");
}
}
case EQUAL_EQUAL:
{
Object value(isEqual(left, right));
return value;
}
case BANG_EQUAL:
{
Object value(!isEqual(left, right));
return value;
}
case LESS:
{
if (left.type == TYPE_NUMBER && right.type == TYPE_NUMBER)
{
Object value(left.numLiteral < right.numLiteral);
return value;
}
else if (left.type == TYPE_STRING && right.type == TYPE_STRING)
{
Object value(left.strLiteral < right.strLiteral);
return value;
}
else
{
runtimeError(*expr->oper, "Operands must be both strings or both numbers.");
}
}
case GREATER:
{
if (left.type == TYPE_NUMBER && right.type == TYPE_NUMBER)
{
Object value(left.numLiteral > right.numLiteral);
return value;
}
else if (left.type == TYPE_STRING && right.type == TYPE_STRING)
{
Object value(left.strLiteral > right.strLiteral);
return value;
}
else
{
runtimeError(*expr->oper, "Operands must be both strings or both numbers.");
}
}
case LESS_EQUAL:
{
if (left.type == TYPE_NUMBER && right.type == TYPE_NUMBER)
{
Object value(left.numLiteral <= right.numLiteral);
return value;
}
else if (left.type == TYPE_STRING && right.type == TYPE_STRING)
{
Object value(left.strLiteral <= right.strLiteral);
return value;
}
else
{
runtimeError(*expr->oper, "Operands must be both strings or both numbers.");
}
}
case GREATER_EQUAL:
{
if (left.type == TYPE_NUMBER && right.type == TYPE_NUMBER)
{
Object value(left.numLiteral >= right.numLiteral);
return value;
}
else if (left.type == TYPE_STRING && right.type == TYPE_STRING)
{
Object value(left.strLiteral >= right.strLiteral);
return value;
}
else
{
runtimeError(*expr->oper, "Operands must be both strings or both numbers.");
}
}
default:
runtimeError(*expr->oper, "Invalid binary operator.");
}
return left;
}
Object Interpreter::visitLogical(Logical *expr)
{
Object left = evaluate(expr->left);
if (expr->oper->type == AND)
{
if (isTruthy(left))
{
return evaluate(expr->right);
}
}
else
{
if (!isTruthy(left))
{
return evaluate(expr->right);
}
}
return left;
}
Object Interpreter::visitGrouping(Grouping *expr)
{
Object value = evaluate(expr->expression);
return value;
}
Object Interpreter::visitLiteral(Literal *expr)
{
return *expr->value;
}
Object Interpreter::visitUnary(Unary *expr)
{
Object right = evaluate(expr->right);
switch (expr->oper->type)
{
case MINUS:
{
checkNumberOperand(*expr->oper, right);
Object value(-right.numLiteral);
return value;
}
case BANG:
{
Object value(!isTruthy(right));
return value;
}
default:
runtimeError(*expr->oper, "Invalid unary operator.");
}
return right;
}
Object Interpreter::visitVariable(Variable *expr)
{
return lookUpVariable(expr->name, expr);
}
Object Interpreter::visitCall(Call *stmt)
{
Object callee = evaluate(stmt->callee);
if (Lox::hadRuntimeError)
{
return callee;
}
std::vector<Object> arguments;
for (auto &argument : stmt->arguments->list)
{
arguments.push_back(evaluate(argument));
}
if ((callee.type != TYPE_FUNCTION) && (callee.type != TYPE_CLASS))
{
runtimeError(*stmt->paren, "Can only call functions and methods.");
}
else
{
LoxCallable *callable = callee.type == TYPE_CLASS ? callee.loxClass : callee.function;
if (callable->arity() != arguments.size())
{
std::stringstream ss;
ss << "Expected " << callable->arity() << " arguments but got " << arguments.size() << ".";
runtimeError(*stmt->paren, ss.str());
return callee;
}
else
{
Object result = callable->call(this, arguments);
returnSet = false;
return result;
}
}
return callee;
}
Object Interpreter::visitGet(Get *expr)
{
Object obj = evaluate(expr->object);
if (obj.type == TYPE_INSTANCE)
{
return obj.loxInstance->get(expr->name);
}
else if (obj.type == TYPE_CLASS)
{
LoxFunction *fn = obj.loxClass->findStatic(expr->name->lexeme);
if (fn)
{
return Object(fn);
}
runtimeError(*expr->name, "Class has no such static method.");
}
runtimeError(*expr->name, "Only instances have properties.");
return Object();
}
Object Interpreter::visitSet(Set *expr)
{
Object obj = evaluate(expr->object);
if (obj.type == TYPE_INSTANCE)
{
Object value = evaluate(expr->value);
obj.loxInstance->set(expr->name, value);
return value;
}
runtimeError(*expr->name, "Only instances have properties.");
return Object();
}
Object Interpreter::visitSuper(Super *expr)
{
auto it = locals->find(expr);
if (it != locals->end())
{
int distance = it->second;
Object superclass = environment->getAt(distance, "super");
Object object = environment->getAt(distance - 1, "this");
LoxFunction *method = superclass.loxClass->findMethod(expr->method->lexeme);
if (method)
{
return method->bind(object.loxInstance);
}
else
{
runtimeError(*expr->method, "Undefined property '" + expr->method->lexeme + "'.");
return Object();
}
}
runtimeError(*expr->keyword, "Class has no superclass");
return Object();
}
Object Interpreter::visitThis(This *expr)
{
return lookUpVariable(expr->keyword, expr);
}
Object Interpreter::visitLambda(Lambda *expr)
{
Object lambda(new LoxLambda(expr, environment));
return lambda;
}
Object Interpreter::evaluate(Expr *expr)
{
if (expr)
{
switch (expr->type)
{
case ExprType_Assign: return visitAssign((Assign *)expr);
case ExprType_Ternary: return visitTernary((Ternary *)expr);
case ExprType_Binary: return visitBinary((Binary *)expr);
case ExprType_Logical: return visitLogical((Logical *)expr);
case ExprType_Grouping: return visitGrouping((Grouping *)expr);
case ExprType_Literal: return visitLiteral((Literal *)expr);
case ExprType_Unary: return visitUnary((Unary *)expr);
case ExprType_Variable: return visitVariable((Variable *)expr);
case ExprType_Call: return visitCall((Call *)expr);
case ExprType_Get: return visitGet((Get *)expr);
case ExprType_Set: return visitSet((Set *)expr);
case ExprType_Super: return visitSuper((Super *)expr);
case ExprType_This: return visitThis((This *)expr);
case ExprType_Lambda: return visitLambda((Lambda *)expr);
default: Lox::error(0, "Invalid expression type.");
}
}
Object nil;
return nil;
}
void Interpreter::visitPrint(Print *stmt)
{
Object value = evaluate(stmt->expression);
if (!Lox::hadRuntimeError)
{
std::cout << value.str() << std::endl;
}
}
void Interpreter::visitExpression(Expression *stmt)
{
Object value = evaluate(stmt->expression);
if (repl && !Lox::hadRuntimeError)
{
std::cout << value.str() << std::endl;
}
}
void Interpreter::visitVar(Var *stmt)
{
Object value;
if (stmt->initializer)
{
value = evaluate(stmt->initializer);
}
else
{
value.type = TYPE_UNINITIALIZED;
}
environment->define(stmt->name, value);
}
Object Interpreter::executeBlock(Block *stmt, Environment *execEnvironment)
{
Environment *savedEnvironment = environment;
environment = execEnvironment;
for (auto &s : stmt->statements->list)
{
execute(s);
if (breakSet || returnSet || Lox::hadRuntimeError)
{
break;
}
}
environment = savedEnvironment;
if (returnSet)
{
return returnValue;
}
Object nil;
return nil;
}
void Interpreter::visitBlock(Block *stmt)
{
Environment locals(environment);
executeBlock(stmt, &locals);
}
void Interpreter::visitIf(If *stmt)
{
if (isTruthy(evaluate(stmt->condition)))
{
execute(stmt->thenBranch);
}
else
{
execute(stmt->elseBranch);
}
}
void Interpreter::visitWhile(While *stmt)
{
while (isTruthy(evaluate(stmt->condition)))
{
execute(stmt->body);
if (breakSet || returnSet || Lox::hadRuntimeError)
{
breakSet = false;
break;
}
}
}
void Interpreter::visitBreak(Break *stmt)
{
breakSet = true;
}
void Interpreter::visitFunction(Function *stmt)
{
Object declaration(new LoxFunction(stmt, environment, false));
environment->define(stmt->name, declaration);
}
void Interpreter::visitClass(Class *stmt)
{
Object superclass;
if (stmt->superclass)
{
superclass = evaluate(stmt->superclass);
if (superclass.type != TYPE_CLASS)
{
Lox::runtimeError(*stmt->superclass->name, "Superclass must be a class.");
return;
}
environment = new Environment(environment);
environment->define("super", superclass);
}
std::unordered_map<std::string, LoxFunction*>* methods = new std::unordered_map<std::string, LoxFunction*>();
for (const auto &method : stmt->methods->list)
{
LoxFunction* function = new LoxFunction(method, environment, method->name->lexeme == "init");
methods->emplace(method->name->lexeme, function);
}
std::unordered_map<std::string, LoxFunction*>* statics = new std::unordered_map<std::string, LoxFunction*>();
for (const auto &method : stmt->statics->list)
{
LoxFunction* function = new LoxFunction(method, environment, false);
statics->emplace(method->name->lexeme, function);
}
Object loxClass(new LoxClass(stmt->name->lexeme, superclass.loxClass, methods, statics));
if (stmt->superclass)
{
environment = environment->ancestor(1);
}
environment->define(stmt->name, loxClass);
}
void Interpreter::visitReturn(Return *stmt)
{
returnValue = evaluate(stmt->value);
returnSet = true;
}
void Interpreter::execute(Stmt *stmt)
{
if (stmt)
{
switch (stmt->type)
{
case StmtType_Print: visitPrint((Print *)stmt); break;
case StmtType_Expression: visitExpression((Expression *)stmt); break;
case StmtType_Var: visitVar((Var *)stmt); break;
case StmtType_Block: visitBlock((Block *)stmt); break;
case StmtType_If: visitIf((If *)stmt); break;
case StmtType_While: visitWhile((While *)stmt); break;
case StmtType_Break: visitBreak((Break *)stmt); break;
case StmtType_Function: visitFunction((Function *)stmt); break;
case StmtType_Class: visitClass((Class *)stmt); break;
case StmtType_Return: visitReturn((Return *)stmt); break;
default: Lox::error(0, "Invalid statement type.");
}
}
}
void Interpreter::interpret(std::vector<Stmt *> statements)
{
for (auto &statement : statements)
{
if (statement)
{
execute(statement);
}
if (Lox::hadRuntimeError)
{
Lox::hadRuntimeError = false;
break;
}
else if (Lox::hadError)
{
break;
}
}
}
void Interpreter::resolve(Expr * expr, int depth)
{
(*locals)[expr] = depth;
}
Object Interpreter::lookUpVariable(Token *name, Expr *expr)
{
auto it = locals->find(expr);
if (it != locals->end())
{
int distance = it->second;
return environment->getAt(distance, name);
}
else
{
return globals->get(name);
}
}