-
Notifications
You must be signed in to change notification settings - Fork 0
/
interp.cpp
766 lines (649 loc) · 19.6 KB
/
interp.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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
#include <iostream>
#include <list>
#include <string>
// floating-point arithmetic
#include <cmath>
#include <memory>
// measure run time
// #include <chrono>
// for readAll -- reading from a file
#include <cassert>
#include <fstream>
#include <optional>
#include <variant>
#include "assert.hpp"
#include "expr.hpp"
#include "func.hpp"
#include "io.hpp"
#include "parser.hpp"
#include "resolver.hpp"
#include "scanner.hpp"
#include "stmt.hpp"
#include "token.hpp"
#include "interp.hpp"
using enum Token::Type;
bool Interp::floatEquality(double a, double b) const {
const double absEps = 1e-15;
const double relEps = 1e-14;
double diff;
if ((diff = std::abs(a - b)) < absEps)
return 1;
return diff <= std::max(std::abs(a), std::abs(b)) * relEps;
}
template <typename T>
constexpr bool always_false_v = false;
bool Interp::equality(const Ltype& left, const Ltype& right) const {
bool ret;
std::visit(
[this, &ret](auto x, auto y) -> void {
using T = decltype(x);
using U = decltype(y);
if constexpr (!std::is_same_v<T, U>) {
ret = 0;
} else {
if constexpr (std::is_same_v<T, Lstring> || std::is_same_v<T, bool>)
ret = x == y;
else if constexpr (std::is_same_v<T, double>)
ret = floatEquality(x, y);
else if constexpr (std::is_same_v<T, Lnil>)
ret = 1;
else if constexpr (std::is_same_v<T, FunPtr> ||
std::is_same_v<T, LfunPtr> ||
std::is_same_v<T, InstPtr> ||
std::is_same_v<T, ClassPtr>)
ret = !std::less<T>()(x, y) && !std::less<T>()(y, x);
else
static_assert(always_false_v<T>);
}
},
left, right);
return ret;
}
Ltype Interp::visit(const ExprBinary* expr) {
Ltype ret, left, right;
ReclaimerCtx ctx(*this);
left = ctx.add(eval(expr->left));
right = ctx.add(eval(expr->right));
switch (expr->oper.type) {
case MINUS:
checkNumberOperands(expr->oper, left, right);
ret = std::get<double>(left) - std::get<double>(right);
break;
case STAR:
checkNumberOperands(expr->oper, left, right);
ret = std::get<double>(left) * std::get<double>(right);
break;
case SLASH:
checkNumberOperands(expr->oper, left, right);
if (floatEquality(std::get<double>(right), 0.0))
throw RuntimeError(expr->oper, "division by zero");
ret = std::get<double>(left) / std::get<double>(right);
break;
case PERCENT:
checkNumberOperands(expr->oper, left, right);
if (floatEquality(std::get<double>(right), 0.0))
throw RuntimeError(expr->oper, "division by zero");
ret = std::fmod(std::get<double>(left), std::get<double>(right));
break;
case PLUS:
if (std::holds_alternative<double>(left) &&
std::holds_alternative<double>(right))
ret = std::get<double>(left) + std::get<double>(right);
else if (std::holds_alternative<Lstring>(left) &&
std::holds_alternative<Lstring>(right))
ret = std::get<Lstring>(left) + std::get<Lstring>(right);
else
throw RuntimeError(expr->oper,
"operands must be numbers or strings, got: " +
typeToString(left) + ", " + typeToString(right));
break;
case EQUAL_EQUAL:
ret = equality(left, right);
break;
case BANG_EQUAL:
ret = !equality(left, right);
break;
case LESS:
checkNumberOperands(expr->oper, left, right);
ret = std::get<double>(left) < std::get<double>(right);
break;
case LESS_EQUAL:
checkNumberOperands(expr->oper, left, right);
ret = std::get<double>(left) <= std::get<double>(right);
break;
case GREATER:
checkNumberOperands(expr->oper, left, right);
ret = std::get<double>(left) > std::get<double>(right);
break;
case GREATER_EQUAL:
checkNumberOperands(expr->oper, left, right);
ret = std::get<double>(left) >= std::get<double>(right);
break;
default:
myAssert(expr->oper, "unhandled binary operator");
break;
}
return ret;
}
Ltype Interp::visit(const ExprComma* expr) {
static_cast<void>(eval(expr->left));
return eval(expr->right);
}
Ltype Interp::visit(const ExprLogical* expr) {
Ltype ret, left, right;
ReclaimerCtx ctx(*this);
left = ctx.add(eval(expr->left));
switch (expr->oper.type) {
case OR:
if (isTruthful(left))
ret = left;
else
ret = eval(expr->right);
break;
case AND:
if (!isTruthful(left))
ret = left;
else
ret = eval(expr->right);
break;
default:
myAssert(expr->oper, "unhandled logical operator");
break;
}
return ret;
}
Ltype Interp::visit(const ExprGrouping* expr) {
return eval(expr->exprp);
}
Ltype Interp::visit(const ExprLiteral* expr) {
return expr->value;
}
Ltype Interp::visit(const ExprUnary* expr) {
Ltype right, ret;
right = eval(expr->exprp);
switch (expr->oper.type) {
case MINUS:
checkNumberOperands(expr->oper, right);
ret = -std::get<double>(right);
break;
case BANG:
ret = !isTruthful(right);
break;
default:
myAssert(expr->oper, "unhandled unary operator");
break;
}
return ret;
}
Ltype Interp::visit(const ExprTern* expr) {
ReclaimerCtx ctx(*this);
Ltype res;
res = ctx.add(eval(expr->cond));
if (isTruthful(res))
return eval(expr->thenp);
return eval(expr->elsep);
}
Ltype Interp::visit(const ExprVar* expr) {
return lookupVariable(expr->token, expr);
}
Ltype Interp::visit(const ExprAssign* expr) {
Ltype value;
auto distance = locals.find(expr);
value = eval(expr->exprp);
if (distance != locals.end())
envp->assignAt(expr->token, value, distance->second);
else
global.assign(expr->token, value);
return value;
}
Ltype Interp::visit(const ExprCall* expr) {
Ltype callee;
FunPtr ptr;
std::list<Ltype> evaluatedArgs;
ReclaimerCtx ctx(*this);
ctx.add(callee = eval(expr->exprp));
std::visit(
[&ptr, &expr, &callee](auto x) -> void {
using T = decltype(x);
if constexpr (std::is_convertible_v<T, FunPtr>) {
ptr = x;
} else {
throw RuntimeError(expr->savedParen,
"call to " + typeToString(callee) +
": can only call functions and constructors");
}
},
callee);
if (ptr->arity != expr->args.size())
throw RuntimeError(expr->savedParen, "expected " +
std::to_string(ptr->arity) +
" arguments, got " +
std::to_string(expr->args.size()));
for (const std::shared_ptr<const Expr>& exprp : expr->args)
evaluatedArgs.push_back(ctx.add(eval(exprp)));
return ptr->call(*this, evaluatedArgs);
}
Ltype Interp::visit(const ExprGet* expr) {
Ltype obj;
std::optional<Ltype> ret;
ReclaimerCtx ctx(*this);
obj = ctx.add(eval(expr->exprp));
if (std::holds_alternative<InstPtr>(obj))
ret = std::get<InstPtr>(obj)->get(*this, expr->token.lexeme);
else if (std::holds_alternative<ClassPtr>(obj))
// treat as an access to a static method
ret = std::get<ClassPtr>(obj)->getStaticMethod(expr->token.lexeme);
else
throw RuntimeError(expr->token, "property access on a non-class object");
if (!ret.has_value())
throw RuntimeError(expr->token, "undefined property");
return ret.value();
}
Ltype Interp::visit(const ExprSet* expr) {
Ltype obj;
Ltype rvalue;
ReclaimerCtx ctx(*this);
obj = ctx.add(eval(expr->get->exprp));
if (!std::holds_alternative<InstPtr>(obj))
throw RuntimeError(expr->token, "only class instances have fields");
rvalue = ctx.add(eval(expr->exprp));
std::get<InstPtr>(obj)->set(expr->token.lexeme, rvalue);
return rvalue;
}
Ltype Interp::visit(const ExprThis* expr) {
return lookupVariable(expr->token, expr);
}
Ltype Interp::visit(const ExprSuper* expr) {
ClassPtr superPtr;
std::optional<Lfunc*> method;
std::size_t distance;
distance = locals[expr];
superPtr = std::get<ClassPtr>(envp->getAt(expr->token, distance));
if ((method = superPtr->getMethod(expr->method.lexeme)).has_value())
return method.value()->bind(
*this, std::get<InstPtr>(envp->getAt(
Token(Token::Type::THIS, "this", "", 0), distance - 1)));
method = superPtr->getStaticMethod(expr->method.lexeme);
if (method.has_value())
return method.value();
throw RuntimeError(expr->method, "undefined property");
}
Ltype Interp::visit(std::shared_ptr<const ExprFun> expr) {
ReclaimerCtx ctx(*this);
return alloc<Lfunc>(ctx, expr, envp, false);
}
Ltype Interp::eval(std::shared_ptr<const Expr> expr) {
return expr->accept(*this);
}
bool Interp::isTruthful(const Ltype& obj) const {
if ((std::holds_alternative<bool>(obj) && std::get<bool>(obj) == 0) ||
std::holds_alternative<Lnil>(obj))
return 0;
return 1;
}
void Interp::checkNumberOperands(Token oper, const Ltype& obj) const {
if (!std::holds_alternative<double>(obj))
throw RuntimeError(oper,
"operand must be a number, got: " + typeToString(obj));
}
void Interp::checkNumberOperands(Token oper,
const Ltype& left,
const Ltype& right) const {
if (!std::holds_alternative<double>(left) ||
!std::holds_alternative<double>(right))
throw RuntimeError(
oper, "operands must be numbers, got: " + typeToString(left) + ", " +
typeToString(right));
}
void Interp::interpret(const std::list<std::shared_ptr<const Stmt>>& list) {
try {
for (const std::shared_ptr<const Stmt>& s : list)
execute(*s.get());
// lets through std::runtime_error, which is OOM and is unrecoverable
} catch (RuntimeError& e) {
handleRuntimeError(e);
}
}
void Interp::execute(const Stmt& stmt) {
stmt.accept(*this);
}
void Interp::execute(const StmtList& stmt, Env* setEnv) {
Env* save;
save = envp;
envp = setEnv;
for (const std::shared_ptr<const Stmt>& p : stmt.stmts) {
try {
execute(*p.get());
// control flow or any other, such as division by zero.
} catch (std::exception& ex) {
envp = save;
throw;
}
}
envp = save;
}
void Interp::visit(const StmtList& stmt) {
ReclaimerCtx ctx(*this);
execute(stmt, alloc<Env>(ctx, envp));
}
Interp::Env::Env() : enclosing(nullptr), m{} {}
Interp::Env::Env(Env* enclosing) : enclosing(enclosing), m{} {}
void Interp::Env::def(const Token& token, std::optional<Ltype> obj) {
// allow redeclaring in global -- for REPL
if (enclosing != nullptr) {
// case 1: case 2:
// var x; var x; == nullopt
// var x = 5; var x; == nullopt again
auto ret = m.find(token.lexeme);
if (ret != m.end() && (ret->second != std::nullopt || !obj.has_value()))
throw RuntimeError(token, "redeclaration");
}
m[token.lexeme] = obj;
}
Ltype Interp::Env::get(const Token& token) const {
auto ret = m.find(token.lexeme);
if (ret == m.end()) {
if (enclosing != nullptr)
return enclosing->get(token);
else
throw RuntimeError(token, "undeclared variable");
} else if (!ret->second.has_value()) {
throw RuntimeError(token, "uninitialized variable");
}
return ret->second.value();
}
Ltype Interp::Env::assertGet(const Token& token) const {
auto ret = m.find(token.lexeme);
assert(ret != m.end());
if (!ret->second.has_value()) {
throw RuntimeError(token, "uninitialized variable");
}
return ret->second.value();
}
Ltype Interp::Env::getAt(const Token& token, std::size_t distance) {
return ancestor(distance)->assertGet(token);
}
Interp::Env* Interp::Env::ancestor(std::size_t distance) {
Env* env;
std::size_t i;
for (i = 0, env = this; i < distance; i++)
env = env->enclosing;
return env;
}
void Interp::Env::assign(const Token& token, Ltype obj) {
auto ret = m.find(token.lexeme);
if (ret == m.end()) {
if (enclosing != nullptr) {
enclosing->assign(token, obj);
return;
} else {
throw RuntimeError(token, "undeclared variable");
}
}
ret->second = obj;
}
void Interp::Env::assignAt(const Token& token,
Ltype obj,
std::size_t distance) {
ancestor(distance)->assign(token, obj);
}
void Interp::visit(const StmtExpr& stmt) {
eval(stmt.exprp);
}
void Interp::visit(const StmtPrint& stmt) {
std::cout << valueToString(eval(stmt.exprp)) << '\n';
}
void Interp::visit(const StmtLoop& stmt) {
ReclaimerCtx ctx(*this);
if (stmt.exprp == nullptr) {
while (isTruthful(ctx.add(eval(stmt.condp)))) {
try {
execute(*stmt.body);
} catch (Break& exception) {
break;
} catch (Continue& exception) {
;
}
}
} else {
while (isTruthful(ctx.add(eval(stmt.condp)))) {
try {
execute(*stmt.body);
} catch (Break& exception) {
break;
} catch (Continue& exception) {
;
}
ctx.add(eval(stmt.exprp));
}
}
}
void Interp::visit(const StmtVar& stmt) {
// always set variables to uninitialized before attempting to evaluate
// the possible initializing expression. This makes weird code in global
// scope like the following erroneous
// var x = x;
envp->def(stmt.token, std::nullopt);
if (stmt.exprp != nullptr)
envp->def(stmt.token, eval(stmt.exprp));
}
void Interp::visit(const StmtIf& stmt) {
ReclaimerCtx ctx(*this);
if (isTruthful(ctx.add(eval(stmt.condp))))
execute(*stmt.thenBranch);
else if (stmt.elseBranch != nullptr)
execute(*stmt.elseBranch);
}
void Interp::visit(const StmtLoopFlow& stmt) {
switch (stmt.token.type) {
case BREAK:
throw Interp::Break();
break;
case CONTINUE:
throw Interp::Continue();
break;
default:
myAssert(stmt.token, "unhandled loop flow control statement");
break;
}
}
void Interp::visit(std::shared_ptr<const StmtFun> stmtp) {
ReclaimerCtx ctx(*this);
// false -- not a ctor
envp->def(stmtp->token, alloc<Lfunc>(ctx, stmtp, envp, false));
}
void Interp::visit(const StmtReturn& stmt) {
Ltype retVal;
// implicitly return nil by default
retVal = Lnil();
if (stmt.exprp != nullptr)
retVal = eval(stmt.exprp);
throw Interp::Return(retVal);
}
void Interp::visit(const StmtClass& stmt) {
Ltype obj;
ClassPtr superPtr;
std::unordered_map<std::string, Lfunc*> methods, staticMethods;
std::size_t ctorArity;
ClassPtr cptr;
Env *save, *enclose;
ReclaimerCtx ctx(*this);
ctorArity = 0;
superPtr = nullptr;
enclose = nullptr;
if (stmt.superExpr != nullptr) {
obj = ctx.add(eval(stmt.superExpr));
if (!std::holds_alternative<ClassPtr>(obj))
throw RuntimeError(stmt.superExpr->token,
"expected class, got " + typeToString(obj));
superPtr = std::get<ClassPtr>(obj);
enclose = alloc<Env>(ctx, envp);
enclose->def(Token(Token::Type::SUPER, "super", "", 0), superPtr);
save = envp;
envp = enclose;
}
for (const std::shared_ptr<const StmtFun>& ptr : stmt.methods)
methods[ptr->token.lexeme] = alloc<Lfunc>(ctx, ptr, envp, false);
for (const std::shared_ptr<const StmtFun>& ptr : stmt.staticMethods)
staticMethods[ptr->token.lexeme] = alloc<Lfunc>(ctx, ptr, envp, false);
// look for optional ctor definition
if (stmt.ctor != nullptr) {
ctorArity = stmt.ctor->params.size();
// true -- is a ctor
methods[stmt.token.lexeme] = alloc<Lfunc>(ctx, stmt.ctor, envp, true);
}
cptr = alloc<Lclass>(ctx, stmt.token.lexeme, ctorArity, methods,
staticMethods, superPtr, enclose);
// does not restore if previous code throws an exception, but the only
// possible is OOM, which is unrecoverable
if (stmt.superExpr != nullptr)
envp = save;
envp->def(stmt.token, cptr);
}
void Interp::handleRuntimeError(RuntimeError& ex) {
error(ex.token, ex.what());
}
Interp::RuntimeError::RuntimeError(Token token, std::string what)
: std::runtime_error(what), token(token) {}
void Interp::run(std::string inputStr) {
std::list<Token> tokenList;
std::list<std::shared_ptr<const Stmt>> stmtPList;
Resolver resolver(*this);
Scanner scanner(inputStr);
tokenList = scanner.scanTokens();
if (hadError)
return;
stmtPList = Parser::parse(tokenList);
if (hadError)
return;
resolver.resolve(stmtPList);
if (hadError)
return;
interpret(stmtPList);
}
void Interp::testScanner(std::string inputStr) {
Scanner s(inputStr);
for (Token t : s.scanTokens())
std::cout << std::string(t) << '\n';
}
void Interp::runPrompt() {
std::string inputStr;
while (1) {
std::cout << "> ";
std::getline(std::cin, inputStr);
if (inputStr.size() == 0) {
std::cout << '\n';
break;
}
run(inputStr);
hadError = 0;
}
}
int Interp::runFile(std::string path) {
std::string input;
std::ifstream inputFileStream(path, std::ios::binary);
if (!inputFileStream)
throw std::runtime_error("error opening file");
input = readAll(inputFileStream);
run(input);
return hadError;
}
bool Interp::hadError;
void Interp::error(std::size_t lineNum, std::string msg) {
report(lineNum, "", msg);
hadError = 1;
}
void Interp::error(const Token& token, std::string msg) {
report(token, msg);
hadError = 1;
}
void Interp::report(const Token& token, std::string msg) {
if (token.type == EOFF)
report(token.lineNum, "at end", msg);
else
report(token.lineNum, "at '" + token.lexeme + "'", msg);
}
void Interp::report(std::size_t lineNum,
std::string location,
std::string msg) {
std::cerr << "line " << lineNum << ": location: " << location << ": " << msg
<< '\n';
}
Interp::Interp() : envp(&global), heapSize(0) {
envp->def(Token(Token::Type::EOFF, "clock", "clock", 0),
Clock::get());
}
Interp::~Interp() {
reclaim();
}
void Interp::resolve(const Expr* expr, std::size_t distance) {
locals[expr] = distance;
}
Ltype Interp::lookupVariable(const Token& token, const Expr* expr) {
auto distance = locals.find(expr);
if (distance != locals.end())
return envp->getAt(token, distance->second);
return global.get(token);
}
void Interp::mark(Env* env) {
env->isReachable = 1;
for (auto& [_, optObj] : env->m) {
if (optObj.has_value())
markLtype(optObj.value());
}
if (env->enclosing != nullptr)
mark(env->enclosing);
}
void Interp::mark(Lfunc* func) {
func->isReachable = 1;
mark(func->enclosing);
}
void Interp::mark(Lclass* lclass) {
lclass->isReachable = 1;
for (auto& [_, method] : lclass->methods)
mark(method);
for (auto& [_, staticMethod] : lclass->staticMethods)
mark(staticMethod);
if (lclass->base != nullptr) {
mark(lclass->base);
mark(lclass->superEnv);
}
}
void Interp::mark(Linstance* obj) {
obj->isReachable = 1;
for (auto& [_, lobj] : obj->properties)
markLtype(lobj);
mark(obj->lclass);
}
void Interp::markLtype(Ltype& l) {
std::visit(
[this](auto x) -> void {
using T = decltype(x);
if constexpr (std::is_convertible_v<T, RunEnt*>) {
if (!x->isReachable)
mark(x);
}
},
l);
}
void Interp::reclaim() {
auto it = traced.begin();
auto prev = it;
while (it != traced.end()) {
prev = it++;
std::visit(
[this, prev](auto y) -> void {
if (y->isReachable)
return;
delete y;
heapSize -= sizeof(std::remove_pointer_t<decltype(y)>);
traced.erase(prev);
},
*prev);
}
}
void Interp::unmark() {
for (auto x : traced) {
std::visit([](auto y) -> void { y->unmarkSelf(); }, x);
}
}