-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathInterpreter.cpp
More file actions
1488 lines (1354 loc) · 60.8 KB
/
Interpreter.cpp
File metadata and controls
1488 lines (1354 loc) · 60.8 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
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Interpreter.h"
#include "TreeTags.h"
#include "error_handler.h"
#include <stdexcept>
#include <vector>
#include <set>
#include <algorithm>
#include <assert.h>
#include <string.h>
#include <regex>
#include <algorithm>
#include <iostream>
#include <sstream>
#include "ASTCreator.h"
#include "CopyTreeVisitor.h"
#include "TreeHost.h"
#include "SetParentTreeVisitor.h"
#include "EvalEscapesTreeVisitor.h"
#include "ControlFlowVisitor.h"
#include "TreeCorrectnessVisitor.h"
struct BreakException {};
struct ContinueException {};
struct ReturnException{
public:
Value v = (Value::Type::UndefType);
ReturnException(const Value _v) {
v = _v;
}
};
Interpreter::Interpreter(EvalDispatcher *d) : retVal(Value::Type::UndefType), objField(Value::Type::UndefType) {
noScope = false;
dispatcher = d;
install();
installBinaryOpDispatcher();
validDollarFields = {"$previous", "$outer", "$local", "$closure", "$local"};
validDollarIdents = {"$lambda", "$env"};
currentFunction = nullptr;
}
Interpreter::~Interpreter() {
valRegister = nullptr;
}
const Value Interpreter::interpret(Object& node) {
return dispatcher->eval(node);
}
const Value* Interpreter::getVarByName(std::string id){
return lookupId(id);
}
const Value* Interpreter::getGlobalVarByName(std::string id){
return lookupGlobalId(id);
}
const Value* Interpreter::getLocalVarByName(std::string id){
return lookupIdCurrEnvOnly(id);
}
const Object* Interpreter::getTopEnvinroment(){
return envs.top().toObject();
}
const Object* Interpreter::getGlobalEnvinroment(){
return globalScope;
}
void Interpreter::pushScopeSpace(Object* scope) {
envs.push(Value(scope));
}
void Interpreter::pushNested() {
Object* tmp = new Object();
auto topEnv = envs.getTopAndPop();
tmp->set(std::string("$outer"), topEnv);
envs.push(Value(tmp));
}
void Interpreter::pushSlice() {
Object *tmp = new Object();
tmp->set(std::string("$previous"), envs.getTopAndPop());
envs.push(Value(tmp));
if(envs.size() == 1)
globalScope = tmp;
}
void Interpreter::popScopeSpace() {
envs.getTopAndPop();
}
Value *Interpreter::lookupId(std::string id) {
assert(!envs.isEmpty());
Object *currChain = envs.top().toObjectNoConst();
while(true){
Value *possibleId = (*currChain)[id];
if(possibleId != nullptr)
return possibleId;
if ((*currChain)["$local"] != nullptr) {
auto localenv = (*currChain)["$local"]->toObjectNoConst();
possibleId = (*localenv)[id];
if (possibleId != nullptr) {
return possibleId;
}
}
if((*currChain)["$previous"] != nullptr){
assert((*currChain)["$outer"] == nullptr);
currChain = (*currChain)["$previous"]->toObjectNoConst();
}
else if((*currChain)["$outer"] != nullptr)
currChain = (*currChain)["$outer"]->toObjectNoConst();
else
return lookupGlobalId(id);
}
}
Value *Interpreter::declareId(std::string id){
assert(!envs.isEmpty());
Object *currChain = envs.top().toObjectNoConst();
currChain->set(id, Value(Value::Type::UndefType));
return (*currChain)[id];
}
Value *Interpreter::lookupGlobalId(std::string id){
Object *currChain = globalScope;
while(true){
Value *possibleId = (*currChain)[id];
if(possibleId != nullptr)
return possibleId;
if((*currChain)["$previous"] != nullptr){
assert((*currChain)["$outer"] == nullptr);
currChain = (*currChain)["$previous"]->toObjectNoConst();
}
else
return nullptr;
}
}
Value *Interpreter::lookupIdCurrEnvOnly(std::string id){
assert(!envs.isEmpty());
Object *currChain = envs.top().toObjectNoConst();
while(true){
Value *possibleId = (*currChain)[id];
if(possibleId != nullptr)
return possibleId;
if ((*currChain)["$local"] != nullptr) {
auto localenv = (*currChain)["$local"]->toObjectNoConst();
possibleId = (*localenv)[id];
if (possibleId != nullptr) {
return possibleId;
}
}
if((*currChain)["$previous"] != nullptr){
assert((*currChain)["$outer"] == nullptr);
currChain = (*currChain)["$previous"]->toObjectNoConst();
}
else
return nullptr;
}
}
const Value* Interpreter::getArgument(Object& env, unsigned argNo, const std::string& optArgName) {
auto* arg = env[optArgName];
if (!arg) arg = env[argNo];
return arg;
}
void Interpreter::forceClosureClear(Object& env){
env.apply([this](const Value& key, Value *val){
if(val->isProgramFunction()) {
val->clear();
}
else if(val->isObject() && val->toObject()->getRefCounter() == 1){
auto tmp = (key.isString())?(std::string(key.toString())):(std::string(""));
if(!key.isString() || validDollarFields.find(tmp) == validDollarFields.end() || tmp == "$local")
forceClosureClear(*val->toObjectNoConst());
}
});
}
const Value Interpreter::evalProgram(Object& node){
valRegister = nullptr;
currentFunction = nullptr;
currentFuncNumArgs = -1;
currFuncArgsEnv = nullptr;
objField = Value(Value::Type::UndefType);
globalScope = new Object();
pushScopeSpace(globalScope);
globalScope->set("print", Value(libfuncPrint, "print"));
globalScope->set("typeOf", Value(libfuncTypeOf, "typeOf"));
globalScope->set("objectKeys", Value(libfuncObjectKeys, "objectKeys"));
globalScope->set("objectSize", Value(libfuncObjectSize, "objectSize"));
globalScope->set("input", Value(libfuncInput, "input"));
globalScope->set("strToNum", Value(libfuncStrToNum, "strToNum"));
globalScope->set("sqrt", Value(libfuncSqrt, "sqrt"));
globalScope->set("cos", Value(libfuncCos, "cos"));
globalScope->set("sin", Value(libfuncSin, "sin"));
globalScope->set("floor", Value(libfuncFloor, "floor"));
globalScope->set("ceil", Value(libfuncCeiling, "ceil"));
globalScope->set("totalArguments", Value(libfuncTotalArguments, "totalArguments"));
globalScope->set("getArgument", Value(libfuncGetArgument, "getArgument"));
globalScope->set("objectCopy", Value(libfuncObjectCopy, "objectCopy"));
globalScope->set("fileOpen", Value(libfuncFileOpen, "fileOpen"));
globalScope->set("fileClose", Value(libfuncFileClose, "fileClose"));
globalScope->set("fileGetLine", Value(libfuncFileGetLine, "fileGetLine"));
globalScope->set("fileGetWord", Value(libfuncFileGetWord, "fileGetWord"));
globalScope->set("fileRead", Value(libfuncFileRead, "fileRead"));
globalScope->set("eval", Value(libfuncEval, "eval"));
globalScope->set("exit", Value(libfuncExit, "exit"));
dispatcher->eval(*(node[AST_TAG_CHILD]->toObjectNoConst()));
retVal.clear();
auto currEnv = envs.getTopAndPop();
while ((*currEnv.toObject())["$previous"] != nullptr) {
currEnv = *((*currEnv.toObjectNoConst())["$previous"]);
forceClosureClear(*currEnv.toObjectNoConst());
}
return Value(Value::Type::NilType);
}
const Value Interpreter::evalStmts(Object& node){
for(unsigned int i = 0; i < node[AST_TAG_NUMCHILDREN]->toNumber(); i++){
Object* stmt = node[i]->toObjectNoConst();
dispatcher->eval(*stmt);
}
return Value(Value::Type::NilType);
}
const Value Interpreter::evalReduction(Object& node){
if(node[AST_TAG_CHILD] != nullptr)
return dispatcher->eval(*(node[AST_TAG_CHILD]->toObjectNoConst()));
return Value(Value::Type::NilType);
}
const Value Interpreter::evalBinaryOp(const Value leftOp, const Value rightOp, std::string op){
auto operatorFunc = binaryOpDispatcher[op];
Value res = Value(Value::Type::UndefType);
try{
res = operatorFunc(leftOp, rightOp);
}
catch(std::runtime_error &e){
auto tmp = ("A++ runtime error: " + std::string(e.what()) + "\n");
error(ErrorType::Error, currLineNo, tmp.c_str());
exit(1);
}
return res;
}
const Value Interpreter::evalArithExpr(Object& node){
auto leftOperandNode = node[AST_TAG_LEFTEXPR]->toObjectNoConst();
auto rightOperandNode = node[AST_TAG_RIGHTEXPR]->toObjectNoConst();
auto val1 = dispatcher->eval(*leftOperandNode);
auto val2 = dispatcher->eval(*rightOperandNode);
currLineNo = node[AST_TAG_LINE_KEY]->toNumber();
return evalBinaryOp(val1, val2, node[AST_TAG_ARITHOP_TYPE]->toString());
}
const Value Interpreter::evalRelExpr(Object& node){
auto leftOperandNode = node[AST_TAG_LEFTEXPR]->toObjectNoConst();
auto rightOperandNode = node[AST_TAG_RIGHTEXPR]->toObjectNoConst();
auto val1 = dispatcher->eval(*leftOperandNode);
auto val2 = dispatcher->eval(*rightOperandNode);
currLineNo = node[AST_TAG_LINE_KEY]->toNumber();
return evalBinaryOp(val1, val2, node[AST_TAG_RELOP_TYPE]->toString());
}
const Value Interpreter::evalBoolExpr(Object& node){
auto leftOperandNode = node[AST_TAG_LEFTEXPR]->toObjectNoConst();
auto rightOperandNode = node[AST_TAG_RIGHTEXPR]->toObjectNoConst();
auto val1 = dispatcher->eval(*leftOperandNode);
auto op = std::string(node[AST_TAG_BOOLOP_TYPE]->toString());
try {
if (val1){
if (op == "or")
return Value(true);
}
else {
if (op == "and")
return Value(false);
}
}
catch (const std::exception& e) {
error(ErrorType::Error, currLineNo, e.what());
exit(-1);
}
auto val2 = dispatcher->eval(*rightOperandNode);
currLineNo = node[AST_TAG_LINE_KEY]->toNumber();
return evalBinaryOp(val1, val2, node[AST_TAG_BOOLOP_TYPE]->toString());
}
const Value Interpreter::evalTermParensExpr(Object& node){
auto exprNode = node[AST_TAG_EXPR]->toObjectNoConst();
return dispatcher->eval(*exprNode);
}
const Value Interpreter::evalTermMinusExpr(Object& node){
auto exprNode = node[AST_TAG_EXPR]->toObjectNoConst();
auto val = dispatcher->eval(*exprNode);
if(val.isNumber())
return Value(-val.toNumber());
else{
auto tmp = "A++ runtime error: non-arithmetic operand to unary minus\n";
error(ErrorType::Error, node[AST_TAG_LINE_KEY]->toNumber(), tmp);
exit(1);
}
}
const Value Interpreter::evalTermNotExpr(Object& node){
auto exprNode = node[AST_TAG_EXPR]->toObjectNoConst();
auto val = dispatcher->eval(*exprNode);
try{
return Value(!val);
}
catch(std::runtime_error &e){
auto tmp = ("A++ runtime error: " + std::string(e.what()) + "\n");
error(ErrorType::Error, node[AST_TAG_LINE_KEY]->toNumber(), tmp.c_str());
exit(1);
}
}
void Interpreter::indexValRegIfTableOrFunc(){
if(!objField.isUndef()){
if(valRegister->isObject())
valRegister = (*valRegister->toObjectNoConst())[&objField];
else if(valRegister->isProgramFunction() &&
!(objField.isString() && std::string(objField.toString()) == "$closure"))
valRegister = (*valRegister->toProgramFunctionClosureNoConst())[&objField];
if(valRegister == nullptr){
error(ErrorType::Error, currLineNo, "A++ runtime error: Non-existent object field \"%s\"\n", objField.makeString().c_str());
exit(1);
}
}
}
const Value Interpreter::evalTermPlusPlusLvalue(Object& node){
auto lvalueNode = node[AST_TAG_LVALUE]->toObjectNoConst();
dispatcher->eval(*lvalueNode);
currLineNo = node[AST_TAG_LINE_KEY]->toNumber();
indexValRegIfTableOrFunc();
//pre-increment
if(!valRegister->isNumber()){
auto tmp = "A++ runtime error: non-numeric operand to ++\n";
error(ErrorType::Error, node[AST_TAG_LINE_KEY]->toNumber(), tmp);
exit(1);
}
valRegister->fromDouble(valRegister->toNumber() + 1);
return *valRegister;
}
const Value Interpreter::evalTermMinusMinusLvalue(Object& node){
auto lvalueNode = node[AST_TAG_LVALUE]->toObjectNoConst();
dispatcher->eval(*lvalueNode);
currLineNo = node[AST_TAG_LINE_KEY]->toNumber();
indexValRegIfTableOrFunc();
if(!valRegister->isNumber()){
auto tmp = "A++ runtime error: non-numeric operand to --\n";
error(ErrorType::Error, node[AST_TAG_LINE_KEY]->toNumber(), tmp);
exit(1);
}
//pre-decrement
valRegister->fromDouble(valRegister->toNumber() - 1);
return *valRegister;
}
const Value Interpreter::evalTermLvaluePlusPlus(Object& node){
auto lvalueNode = node[AST_TAG_LVALUE]->toObjectNoConst();
dispatcher->eval(*lvalueNode);
currLineNo = node[AST_TAG_LINE_KEY]->toNumber();
indexValRegIfTableOrFunc();
if(!valRegister->isNumber()){
auto tmp = "A++ runtime error: non-numeric operand to ++\n";
error(ErrorType::Error, node[AST_TAG_LINE_KEY]->toNumber(), tmp);
exit(1);
}
auto retVal = *valRegister;
//post-increment
valRegister->fromDouble(valRegister->toNumber() + 1);
return retVal;
}
const Value Interpreter::evalTermLvalueMinusMinus(Object& node){
auto lvalueNode = node[AST_TAG_LVALUE]->toObjectNoConst();
dispatcher->eval(*lvalueNode);
currLineNo = node[AST_TAG_LINE_KEY]->toNumber();
indexValRegIfTableOrFunc();
if(!valRegister->isNumber()){
auto tmp = "A++ runtime error: non-numeric operand to --\n";
error(ErrorType::Error, node[AST_TAG_LINE_KEY]->toNumber(), tmp);
exit(1);
}
auto retVal = *valRegister;
//post-decrement
valRegister->fromDouble(valRegister->toNumber() - 1);
return retVal;
}
const Value Interpreter::evalAssignExpr(Object& node) {
objField = Value(Value::Type::UndefType);
auto lvalueNode = *(node[AST_TAG_LVALUE]->toObjectNoConst());
Value lvalue = dispatcher->eval(lvalueNode);
Value* lvalue_md = valRegister;
Value lvalueObjField = objField;
if(lvalueNode[AST_TAG_ID] != nullptr && validDollarIdents.find(lvalueNode[AST_TAG_ID]->toString()) != validDollarIdents.end()){
auto tmp = lvalueNode[AST_TAG_ID]->toString();
error(ErrorType::Error, node[AST_TAG_LINE_KEY]->toNumber(), "A++ Runtime Error: \"%s\" is not an lvalue\n", tmp);
exit(1);
}
if (lvalue_md->isLibraryFunction()) {
error(ErrorType::Error, node[AST_TAG_LINE_KEY]->toNumber(), "A++ Runtime Error: Cannot assign expression to library function\n");
exit(1);
}
Value expr = dispatcher->eval(*(node[AST_TAG_EXPR]->toObjectNoConst()));
if(!lvalueObjField.isUndef()&& !(lvalueObjField.isString()
&& std::string(lvalueObjField.toString()) == "$closure")){ //trying to index something
assert(lvalue_md->isObject() || lvalue_md->isProgramFunction());
if(lvalueObjField.isString()){
std::string idString = lvalueObjField.toString();
if(idString.length() >= 1 && idString[0] == '$' && validDollarFields.find(idString) == validDollarFields.end()){
error(ErrorType::Error, node[AST_TAG_LINE_KEY]->toNumber(), "A++ Runtime Error: invalid \"$\" index\n");
exit(1);
}
}
Object *affectedObject = (lvalue_md->isObject()) ? (lvalue_md->toObjectNoConst()) : (lvalue_md->toProgramFunctionClosureNoConst());
if(expr.isNil())
affectedObject->remove(&lvalueObjField); //field removal
else
affectedObject->set(&lvalueObjField, expr); //field modification
}
else if(lvalueObjField.isString() && std::string(lvalueObjField.toString()) == "$closure") {//trying to modify function.$closure
assert(lvalue_md->isProgramFunction());
auto tmp = strdup(lvalue_md->toProgramFunctionName());
lvalue_md->fromProgramFunction(lvalue_md->toProgramFunctionASTNoConst(),
expr.toObjectNoConst(), tmp);
free(tmp);
}
else
*lvalue_md = expr;
return expr;
}
const Value Interpreter::evalLvalueId(Object& node) {
auto id = node[AST_TAG_ID]->toString();
//lookup id in env
if (std::string(id).size() >= 1 && id[0] == '$') {
if (validDollarIdents.find(std::string(id)) == validDollarIdents.end()) {
error(ErrorType::Error, node[AST_TAG_LINE_KEY]->toNumber(), "A++ Runtime Error: %s keyword not supported as lvalue\n", id);
exit(1);
}
}
if (std::string(id) == "$env") {
retVal = envs.top();
valRegister = &retVal;
return retVal;
}
if (std::string(id) == "$lambda") {
return *currentFunction;
}
Value *existentSymbol = lookupId(id);
if(existentSymbol == nullptr)
existentSymbol = declareId(id);
valRegister = existentSymbol;
Value v = *existentSymbol;
return *existentSymbol;
}
const Value Interpreter::evalLvalueGlobalId(Object& node) {
auto id = node[AST_TAG_GLOBALID]->toString();
//lookup id in global env
Value *existentSymbol = lookupGlobalId(id);
if(existentSymbol == nullptr){
error(ErrorType::Error, node[AST_TAG_LINE_KEY]->toNumber(), "A++ runtime error: reference to undeclared global id \"%s\"\n", id);
exit(1);
}
valRegister = existentSymbol;
return *existentSymbol;
}
const Value Interpreter::evalLvalueLocalId(Object& node) {
auto id = node[AST_TAG_LOCALID]->toString();
//lookup id in current env
Value *existentSymbol = lookupIdCurrEnvOnly(id);
if(existentSymbol == nullptr)
existentSymbol = declareId(id);
valRegister = existentSymbol;
return *existentSymbol;
}
const Value Interpreter::evalLvalueMember(Object& node) {
const Value member = dispatcher->eval(*(node[AST_TAG_MEMBER]->toObjectNoConst()));
return member;
}
const Value Interpreter::fieldAccess(const Value caller, const Value* id, double lineNo) {
Object* object;
if(id->isString()){ //checks for valid $ indices
auto idString = std::string(id->toString());
if (caller.isProgramFunction() && idString == "$closure") {
objField = *id;
return Value(caller.toProgramFunctionClosureNoConst());
}
else if(idString == "$closure"){
error(ErrorType::Error, lineNo, "A++ Runtime Error: only functions support \"$closure\" indices\n");
exit(1);
}
}
if (caller.isObject()) object = caller.toObjectNoConst();
else if (caller.isProgramFunction()) object = caller.toProgramFunctionClosureNoConst();
else {
error(ErrorType::Error, lineNo, "A++ Runtime Error: indexing non-table variable\n");
exit(1);
}
if(!id->isNumber() && !id->isString()){
error(ErrorType::Error, lineNo, "A++ Runtime Error: Unsupported key type, supported key types are: number, string\n");
exit(1);
}
Value *fieldContents = (*object)[id];
objField = *id;
if(fieldContents == nullptr) {//field not found
return Value(Value::Type::NilType);
}
return *fieldContents;
}
const Value Interpreter::evalMemberId(Object& node) {
objField = Value(Value::Type::UndefType);
const Value caller = dispatcher->eval(*(node[AST_TAG_CALLER]->toObjectNoConst()));
currLineNo = node[AST_TAG_LINE_KEY]->toNumber();
indexValRegIfTableOrFunc();
Value* id = node[AST_TAG_ID];
return fieldAccess(caller, id, node[AST_TAG_LINE_KEY]->toNumber());
}
const Value Interpreter::evalMemberExpr(Object& node) {
objField = Value(Value::Type::UndefType);
Value *indexedObj = nullptr;
const Value caller = dispatcher->eval(*(node[AST_TAG_CALLER]->toObjectNoConst()));
currLineNo = node[AST_TAG_LINE_KEY]->toNumber();
indexValRegIfTableOrFunc();
indexedObj = valRegister;
const Value expr = dispatcher->eval(*(node[AST_TAG_EXPR]->toObjectNoConst()));
valRegister = indexedObj;
return fieldAccess(caller, &expr, node[AST_TAG_LINE_KEY]->toNumber());
}
Value Interpreter::makeCallFromObject(const Value* calledFunc, const Value callsuffix, double lineNo) {
auto func = (*(calledFunc->toObjectNoConst()))["()"];
if (func != nullptr) {
//add calledFunc to callsuffix
const Object *oldCallsuffix = callsuffix.toObjectNoConst();
Object* newCallsuffix = new Object();
Object *lvalueArg = new Object();
lvalueArg->set("$$value", *calledFunc);
newCallsuffix->set((double) 0, Value(lvalueArg));
if (callsuffix.isObject()) {
for (unsigned int i = 0; i < oldCallsuffix->getTotal(); i++) {
newCallsuffix->set((double) i + 1, (*(*oldCallsuffix)[i]));
}
}
return makeCall(func, newCallsuffix, lineNo);
} else {
error(ErrorType::Error, lineNo, "A++ Runtime Error: Object is not a functor\n");
exit(1);
}
}
Value Interpreter::makeCallFromLibFunc(const Value* calledFunc, const Value callsuffix, double lineNo) {
Object fscope = Object();
if (!callsuffix.isNil()) {
for (unsigned int i = 0; i < callsuffix.toObject()->getTotal(); i++) {
auto argPair = *(*callsuffix.toObjectNoConst())[i];
if (((*(argPair.toObjectNoConst()))["$$key"] != nullptr)) {
error(ErrorType::Error, lineNo, "A++ Runtime Error: Keyword arguments are not allowed in library functions\n");
exit(1);
}
fscope.set(i, *((*(argPair.toObjectNoConst()))["$$value"]));
}
}
if(currentFunction == nullptr)
fscope.set("$caller", Value("@_invalid"));
else fscope.set("$caller", *currentFunction);
fscope.set("$lineNo", lineNo);
if(currFuncArgsEnv == nullptr)
fscope.set("$callerEnv", Value("@_invalid"));
else fscope.set("$callerEnv", Value(currFuncArgsEnv));
fscope.set("$numCallerArgs", (double)currentFuncNumArgs);
//call lvalue
(calledFunc->toLibraryFunction())(fscope);
if (fscope["$retval"] != nullptr) {
return *fscope["$retval"];
}
return Value(Value::Type::NilType);
}
Value Interpreter::makeCallFromProgFunc(const Value* calledFunc, const Value callsuffix, double lineNo) {
auto idlist = (*calledFunc->toProgramFunctionAST())[AST_TAG_IDLIST];
Object *node = nullptr;
//std::vector<Object*> *formals = nullptr;
unsigned formalsLen = 0;
if (idlist != nullptr) {
node = idlist->toObjectNoConst();
formalsLen = (*node)[AST_TAG_NUMCHILDREN]->toNumber();
}
Object *actuals = nullptr;
unsigned actualsLen = 0;
if (!callsuffix.isNil()) {
actuals = callsuffix.toObjectNoConst();
actualsLen = actuals->getTotal();
}
unsigned int i;
pushScopeSpace(calledFunc->toProgramFunctionClosureNoConst());
pushNested();
Value* prevFunc = currentFunction;
int prevNumArgs = currentFuncNumArgs;
Object *prevEnv = currFuncArgsEnv;
currentFunction = const_cast<Value*>(calledFunc);
currentFuncNumArgs = actualsLen;
currFuncArgsEnv = envs.top().toObjectNoConst();
std::set<std::string> insertedArgs;
std::vector<std::string> formalsNames;
for (i = 0; i < formalsLen; i++)
formalsNames.push_back((*(*node)[i]->toObjectNoConst())[AST_TAG_ID]->toString());
//this loop inserts the actuals in the function scope
for (i = 0; i < actualsLen; i++) {
auto arg = ((*actuals)[i]->toObjectNoConst());
std::string newIdName;
if ((*arg)["$$key"] == nullptr) { //positional arg
if (i < formalsLen) { //is matched to an actual
newIdName = (*((*node)[i]->toObjectNoConst()))[AST_TAG_ID]->toString();
auto newId = declareId(newIdName);
*newId = *((*arg)["$$value"]);
} else {
newIdName = std::to_string(i);
auto newId = declareId(newIdName);
*newId = *((*arg)["$$value"]);
}
insertedArgs.insert(newIdName);
}
else { //keyword arg
std::string newIdName = std::string((*arg)["$$key"]->toString());
if(insertedArgs.find(newIdName) != insertedArgs.end()){
error(ErrorType::Error, lineNo, "A++ runtime error: argument set more than once\n");
exit(1);
}
auto it = find(formalsNames.begin(), formalsNames.end(), newIdName);
if(it == formalsNames.end()){
error(ErrorType::Error, lineNo, "A++ runtime error: unexpected keyword argument\n");
exit(1);
}
int index = std::distance(formalsNames.begin(), it);
auto newId = declareId(formalsNames[index]);
*newId = *((*arg)["$$value"]);
insertedArgs.insert(newIdName);
}
}
for (i = 0; i < formalsLen; i++) {
auto formalName = formalsNames[i];
if(lookupIdCurrEnvOnly(formalName) == nullptr){
auto formal = declareId(formalName);
auto defaultValueNode = ((*(*node)[i]->toObjectNoConst()))[AST_TAG_EXPR];
if(defaultValueNode != nullptr){
auto defaultValue = dispatcher->eval(*defaultValueNode->toObjectNoConst());
*formal = defaultValue;
}
else{
*formal = Value(Value::Type::UndefType);
error(ErrorType::Warning, lineNo, "Argument %s is undefined\n", formalName.c_str());
}
}
}
auto funcNode = calledFunc->toProgramFunctionASTNoConst();
noScope = true;
Value toReturn = Value(Value::Type::NilType);
try {
dispatcher->eval(*((*funcNode)[AST_TAG_BLOCK]->toObjectNoConst()));
}
catch (const ReturnException& e) {
toReturn = e.v;
}
currentFunction = prevFunc;
currentFuncNumArgs = prevNumArgs;
currLineNo = lineNo;
currFuncArgsEnv = prevEnv;
tmpFunc();
popScopeSpace();
return toReturn;
}
const Value Interpreter::makeCall(const Value* calledFunc, const Value callsuffix, double lineNo) {
//check if lvalue function (user or lib)
if (calledFunc->isLibraryFunction()) {
retVal = makeCallFromLibFunc(calledFunc, callsuffix, lineNo);
} else if (calledFunc->isProgramFunction()){
retVal = makeCallFromProgFunc(calledFunc, callsuffix, lineNo);
} else if (calledFunc->isObject()) {
retVal = makeCallFromObject(calledFunc, callsuffix, lineNo);
} else {
error(ErrorType::Error, lineNo, "A++ Runtime Error: Not a function\n");
exit(1);
}
valRegister = &retVal;
objField = Value(Value::Type::UndefType);
return retVal;
}
const Value Interpreter::evalCall(Object& node) {
ASTCreator::setOptionalParent(&node);
const Value lvalue = dispatcher->eval(*(node[AST_TAG_LVALUE]->toObjectNoConst()));
Value* caller = new Value(lvalue);
const Value tmpCallsuffix = dispatcher->eval(*(node[AST_TAG_CALLSUFFIX]->toObjectNoConst()));
bool isMethodCall = false;
Object *newCallsuffix;
Value* calledFunc = valRegister;
if (calledFunc != nullptr) {
if(!caller->isObject()){
error(ErrorType::Error, node[AST_TAG_LINE_KEY]->toNumber(), "A++ runtime error: method caller is not an object\n");
exit(1);
}
calledFunc = (*caller->toObject())[calledFunc->toString()];
if (calledFunc == nullptr) {
error(ErrorType::Error, node[AST_TAG_LINE_KEY]->toNumber(), "A++ runtime error: non-existent object field\n");
exit(1);
}
if ((*(node[AST_TAG_CALLSUFFIX]->toObject()))[AST_TAG_METHODCALL] != nullptr) {
isMethodCall = true;
const Object *oldCallsuffix;
newCallsuffix = new Object();
Object *lvalueArg = new Object();
lvalueArg->set("$$value", *caller);
newCallsuffix->set((double) 0, Value(lvalueArg));
if (tmpCallsuffix.isObject()) {
oldCallsuffix = tmpCallsuffix.toObjectNoConst();
for (unsigned int i = 0; i < oldCallsuffix->getTotal(); i++) {
newCallsuffix->set((double) i + 1, (*(*oldCallsuffix)[i]));
}
}
}
} else {
calledFunc = caller;
}
const Value callsuffix = (isMethodCall) ? Value(newCallsuffix) : tmpCallsuffix;
auto ret = makeCall(calledFunc, callsuffix, (node[AST_TAG_LINE_KEY]->toNumber()));
caller->clear();
delete caller;
return ret;
}
const Value Interpreter::evalMultiCall(Object& node) {
ASTCreator::setOptionalParent(&node);
const Value call = dispatcher->eval(*(node[AST_TAG_CALL]->toObjectNoConst()));
Value elist = Value(Value::Type::NilType);
if (node[AST_TAG_ELIST] != nullptr) elist = dispatcher->eval(*(node[AST_TAG_ELIST]->toObjectNoConst()));
return makeCall(&call, elist, node[AST_TAG_LINE_KEY]->toNumber());
}
const Value Interpreter::evalFdefCall(Object& node) {
const Value funcdef = dispatcher->eval(*(node[AST_TAG_FUNCDEF]->toObjectNoConst()));
Value elist = Value(Value::Type::NilType);
if (node[AST_TAG_ELIST] != nullptr) elist = dispatcher->eval(*(node[AST_TAG_ELIST]->toObjectNoConst()));
return makeCall(&funcdef, elist, node[AST_TAG_LINE_KEY]->toNumber());
}
const Value Interpreter::evalNormCallSuffix(Object& node) {
const Value normcall = dispatcher->eval(*(node[AST_TAG_NORMCALL]->toObjectNoConst()));
return normcall;
}
const Value Interpreter::evalMethodCallSuffix(Object& node) {
const Value methodcall = dispatcher->eval(*(node[AST_TAG_METHODCALL]->toObjectNoConst()));
return methodcall;
}
const Value Interpreter::evalNormCall(Object& node) {
if (node[AST_TAG_ELIST] != nullptr) {
const Value elist = dispatcher->eval(*(node[AST_TAG_ELIST]->toObjectNoConst()));
valRegister = nullptr;
return elist;
}
valRegister = nullptr;
return Value(Value::Type::NilType);
}
const Value Interpreter::evalMethodCall(Object& node) {
Value *tmp = node[AST_TAG_ID];
valRegister = tmp;
if (node[AST_TAG_ELIST] != nullptr) {
const Value toReturn = dispatcher->eval(*(node[AST_TAG_ELIST]->toObjectNoConst()));
valRegister = tmp;
return toReturn;
}
return Value(Value::Type::NilType);
}
const Value Interpreter::evalElist(Object& node) {
if (node[AST_TAG_ELISTNOTEMPTY] != nullptr) {
return dispatcher->eval(*node[AST_TAG_ELISTNOTEMPTY]->toObjectNoConst());
}
return Value(Value::Type::NilType);
}
const Value Interpreter::evalElistNotEmpty(Object& node) {
Object *tmp = new Object();
for (unsigned i = 0; i < (node[AST_TAG_NUMCHILDREN]->toNumber()); i++) {
auto e = node[i]->toObjectNoConst();
assert(std::string((*e)[AST_TAG_SUBTYPE_KEY]->toString()) == std::string(AST_TAG_ARGUMENT));
const Value val = dispatcher->eval(*((*e)[AST_TAG_EXPR]->toObjectNoConst()));
Object* argPair = new Object();
if ((*e)[AST_TAG_ID] != nullptr)
argPair->set("$$key", (*e)[AST_TAG_ID]->toString());
argPair->set("$$value", val);
tmp->set(i, Value(argPair));
}
return Value(tmp);
}
const Value Interpreter::evalObjElistNotEmpty(Object& node) {
Object *tmp = new Object();
for (unsigned i = 0; i < (node[AST_TAG_NUMCHILDREN]->toNumber()); i++) {
auto e = node[i]->toObjectNoConst();
const Value val = dispatcher->eval(*e);
if(!val.isNil())
tmp->set(i, Value(val));
}
return Value(tmp);
}
const Value Interpreter::evalObjectDef(Object& node) {
if (node[AST_TAG_OBJECTDINNER] != nullptr)
return dispatcher->eval(*node[AST_TAG_OBJECTDINNER]->toObjectNoConst());
return Value(new Object());
}
const Value Interpreter::evalObjectDinnerElistnotempty(Object& node) {
return dispatcher->eval(*(node[AST_TAG_OBJELISTNOTEMPTY]->toObjectNoConst()));
}
const Value Interpreter::evalObjectDinnerIndexed(Object& node) {
return dispatcher->eval(*(node[AST_TAG_INDEXED]->toObjectNoConst()));
}
const Value Interpreter::evalIndexed(Object& node){
return dispatcher->eval(*(node[AST_TAG_COMMAINDEXED]->toObjectNoConst()));
}
const Value Interpreter::evalCommaIndexed(Object& node){
Object* toReturn = new Object();
Object* tmp;
for (unsigned int i = 0; i < node[AST_TAG_NUMCHILDREN]->toNumber(); i++) {
Object* e = node[i]->toObjectNoConst();
auto v = dispatcher->eval(*e);
tmp = v.toObjectNoConst();
if (!((*tmp)["$$key"]->isNumber() || (*tmp)["$$key"]->isString())) {
error(ErrorType::Error, node[AST_TAG_LINE_KEY]->toNumber(), "A++ Runtime Error: Unsupported key type, supported key types are: number, string\n");
exit(1);
}
if(!(*tmp)["$$val"]->isNil())
toReturn->set((*tmp)["$$key"], *(*tmp)["$$val"]);
}
return Value(toReturn);
}
const Value Interpreter::evalIndexedElem(Object& node){
const Value key = dispatcher->eval(*(node[AST_TAG_OBJECT_KEY]->toObjectNoConst()));
const Value value = dispatcher->eval(*(node[AST_TAG_OBJECT_VALUE]->toObjectNoConst()));
Object *tmp = new Object();
tmp->set(std::string("$$key"), key);
tmp->set(std::string("$$val"), value);
return Value(tmp);
}
void Interpreter::tmpFunc() {
auto currEnv = envs.getTopAndPop();
bool shouldSliceOuter = (*currEnv.toObject())["$previous"] != nullptr;
retVal.clear();
while ((*currEnv.toObject())["$previous"] != nullptr){
currEnv = *((*currEnv.toObjectNoConst())["$previous"]);
forceClosureClear(*currEnv.toObjectNoConst());
}
if ((*currEnv.toObjectNoConst())["$outer"] == nullptr) {
error(ErrorType::Error, currLineNo, "A++ Runtime Error: Corrupted outer environment chain\n");
exit(1);
}
envs.push(*(*currEnv.toObjectNoConst())["$outer"]);
if (shouldSliceOuter) {
pushSlice();
}
}
const Value Interpreter::evalBlock(Object& node){
try {
if (node[AST_TAG_STMTS] != nullptr) {
if (noScope){
noScope = false;
dispatcher->eval(*(node[AST_TAG_STMTS]->toObjectNoConst()));
}
else {
pushNested();
dispatcher->eval(*(node[AST_TAG_STMTS]->toObjectNoConst()));
currLineNo = node[AST_TAG_LINE_KEY]->toNumber();
tmpFunc();
}
}
}
catch (const BreakException&) {
throw;
}
catch (const ContinueException&) {
throw;
}
catch (const ReturnException&) {
throw;
}
return Value(Value::Type::NilType);
}
const Value Interpreter::evalFuncDef(Object& node){
Value fvalue = Value(Value::Type::UndefType);
Value fname = dispatcher->eval(*(node[AST_TAG_FUNCPREFIX]->toObjectNoConst()));
if (valRegister != nullptr) {
valRegister->fromProgramFunction(&node, envs.top().toObjectNoConst(), fname.toString());
fvalue = *valRegister;
} else {
fvalue.fromProgramFunction(&node, envs.top().toObjectNoConst(), "<ANONYMOUS_FUNCTION>");
}
valRegister = nullptr;
pushSlice();
return fvalue;
}
const Value Interpreter::evalFuncPrefix(Object& node){
if (node[AST_TAG_CHILD] != nullptr)
return dispatcher->eval(*(node[AST_TAG_CHILD]->toObjectNoConst()));
valRegister = nullptr;
return Value(Value::Type::NilType);
}
const Value Interpreter::evalFuncNameId(Object& node){
auto fname = node[AST_TAG_ID];
if (lookupIdCurrEnvOnly(fname->toString()) != nullptr) {
error(ErrorType::Error, node[AST_TAG_LINE_KEY]->toNumber(),
"A++ runtime error: identifier %s has already been declared\n", fname->toString());
exit(1);
}
valRegister = declareId(fname->toString());
return Value(fname->toString());
}
const Value Interpreter::evalConst(Object& node){
return *(node[AST_TAG_VALUE]);
}
const Value Interpreter::evalCommaIdList(Object& node){
for (unsigned int i = 0; i < node[AST_TAG_NUMCHILDREN]->toNumber(); i++) {
Object* e = node[i]->toObjectNoConst();
dispatcher->eval(*((*e)[AST_TAG_ID]->toObjectNoConst()));
}
return Value(Value::Type::NilType);
}
const Value Interpreter::evalIfPrefix(Object& node){
return dispatcher->eval(*(node[AST_TAG_EXPR]->toObjectNoConst()));
}
const Value Interpreter::evalIfStmt(Object& node){
const Value cond = dispatcher->eval(*node[AST_TAG_IFPREFIX]->toObjectNoConst());
bool condBool;
try {
condBool = cond;
}
catch (const std::exception& e) {
error(ErrorType::Error, currLineNo, e.what());
exit(-1);
}
if (condBool)
dispatcher->eval(*(node[AST_TAG_IFSTMT_IFBODY]->toObjectNoConst()));
else {
if (node[AST_TAG_IFSTMT_ELSEBODY] != nullptr)
dispatcher->eval(*(node[AST_TAG_IFSTMT_ELSEBODY]->toObjectNoConst()));
}
return Value(Value::Type::NilType);
}
const Value Interpreter::evalWhileCond(Object& node){