-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcodegen.cpp
More file actions
1593 lines (1504 loc) · 44.4 KB
/
codegen.cpp
File metadata and controls
1593 lines (1504 loc) · 44.4 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 "codegen.h"
#include "engine.h"
#include "import.h"
#include "loader.h"
#include "printer.h"
#include "objects/bytecodecompilationctx.h"
#include "objects/function.h"
#include "objects/functioncompilationctx.h"
#include "objects/object.h"
#include "objects/symtab.h"
#define lnerr_(t, ...) \
{ \
Printer::LnErr(t, ##__VA_ARGS__); \
t.highlight(false, "", Token::HighlightType::ERR); \
errorsOccurred++; \
}
CodeGenerator::CodeGenerator() {
state = COMPILE_DECLARATION;
onLHS = false;
scopeID = 0;
inClass = false;
currentVisibility = Visibility::VIS_PRIV;
onRefer = false;
tryBlockStart = 0;
tryBlockEnd = 0;
lastMemberReferenced = 0;
variableInfo = {0, VariablePosition::UNDEFINED, false};
errorsOccurred = 0;
inThis = false;
inSuper = false;
inLoop = 0;
pendingBreaks = CustomArray<Break>();
mtx = NULL;
ctx = NULL;
ftx = NULL;
btx = NULL;
corectx = Value(ExecutionEngine::CoreObject).getClass();
currentlyCompiling = nullptr;
expressionNoPop = false;
}
Class *CodeGenerator::compile(String *name, Array *stmts) {
currentlyCompiling = stmts;
ClassCompilationContext2 ctx = ClassCompilationContext::create(NULL, name);
compile(ctx, stmts);
return ctx->get_class();
}
void CodeGenerator::compile(ClassCompilationContext *compileIn, Array *stmts) {
// ExecutionEngine::registermtx(compileIn);
currentlyCompiling = stmts;
ctx = compileIn;
mtx = compileIn;
initFtx(compileIn->get_default_constructor(),
stmts->size > 0 ? stmts->values[0].toStatement()->token
: Token::PlaceholderToken);
btx->insert_token(Token::PlaceholderToken);
// if the number of statements is 1 and the only statement
// is an expression statement, then make it an implicit print
if(stmts->size == 1 &&
stmts->values[0].toStatement()->isExpressionStatement()) {
loadCoreModule();
expressionNoPop =
true; // tells the expression statement to not pop the result
compileAll(stmts);
CallInfo info = resolveCall(String::from(" printRepl"),
String::from(" printRepl(_)"));
int numexprs = stmts->values[0]
.toStatement()
->toExpressionStatement()
->exprs->size;
btx->call_(info.frameIdx, numexprs);
for(int i = 0; i < numexprs; i++) btx->pop_();
} else {
compileAll(stmts);
}
// after everything is done, load the instance,
// and return it
btx->load_slot_0();
btx->ret();
popFrame();
#ifdef DEBUG
Printer::println("Code generated for mtx ",
compileIn->get_class()->name->str());
compileIn->disassemble(Printer::StdOutStream);
#endif
if(errorsOccurred)
throw CodeGeneratorException(errorsOccurred);
}
int CodeGenerator::pushScope() {
return ++scopeID;
}
void CodeGenerator::popScope() {
if(ctx == nullptr)
return;
// just decrement the scopeID
// ftx manages everything else
--scopeID;
}
void CodeGenerator::compileAll(Array *stmts) {
// Backup current state
CompilationState bak = state;
// First compile all declarations
state = COMPILE_DECLARATION;
for(int i = 0; i < stmts->size; i++) {
Statement *s = stmts->values[i].toStatement();
// Pass only declaration statements
if(s->isDeclaration())
s->accept(this);
}
// Mark this mtx as already compiled, so that even if a
// cyclic import occures, this mtx is not recompiled
ctx->isCompiled = true;
// Then compile all imports
state = COMPILE_IMPORTS;
for(int i = 0; i < stmts->size; i++) {
Statement *s = stmts->values[i].toStatement();
// Pass only import statements
if(s->isImport())
s->accept(this);
}
// Then compile all bodies
state = COMPILE_BODY;
for(int i = 0; i < stmts->size; i++) {
Statement *s = stmts->values[i].toStatement();
s->accept(this);
}
state = bak;
}
void CodeGenerator::initFtx(FunctionCompilationContext *f, Token t) {
ftx = f;
btx = f->get_codectx();
btx->insert_token(t);
}
CodeGenerator::CompilationState CodeGenerator::getState() {
return state;
}
void CodeGenerator::popFrame() {
if(btx != NULL)
btx->finalize();
ftx = ctx->get_default_constructor();
if(ftx != NULL)
btx = ftx->get_codectx();
else
btx = NULL;
}
int CodeGenerator::createTempSlot() {
char tempname[20] = {0};
snprintf(&tempname[0], 20, "temp %d", ftx->slotCount);
int slot = ftx->create_slot(String::from(tempname), scopeID);
return slot;
}
void CodeGenerator::loadPresentModule() {
// check if we're in a class
if(ctx != mtx) {
btx->load_module();
} else {
// if we're not inside of any class, then
// the 0th slot is the present module
btx->load_slot_n(0);
}
}
void CodeGenerator::loadCoreModule() {
btx->load_module_core();
}
void CodeGenerator::patchBreaks() {
while(!pendingBreaks.isEmpty() && pendingBreaks.last().loopID == inLoop) {
Break b = pendingBreaks.popLast();
btx->jump(b.ip, btx->getip() - b.ip);
}
}
void CodeGenerator::visit(BinaryExpression *bin) {
#ifdef DEBUG_CODEGEN
dinfo("");
bin->token.highlight();
#endif
bin->left->accept(this);
int jumpto = -1;
switch(bin->token.type) {
case Token::Type::TOKEN_and: jumpto = btx->land(0); break;
case Token::Type::TOKEN_or: jumpto = btx->lor(0); break;
default: break;
}
bin->right->accept(this);
btx->insert_token(bin->token);
switch(bin->token.type) {
case Token::Type::TOKEN_PLUS: btx->add(); break;
case Token::Type::TOKEN_MINUS: btx->sub(); break;
case Token::Type::TOKEN_STAR: btx->mul(); break;
case Token::Type::TOKEN_SLASH: btx->div(); break;
case Token::Type::TOKEN_CARET: btx->bxor(); break;
case Token::Type::TOKEN_PIPE: btx->bor(); break;
case Token::Type::TOKEN_AMPERSAND: btx->band(); break;
case Token::Type::TOKEN_BANG: btx->lnot(); break;
case Token::Type::TOKEN_EQUAL_EQUAL: btx->eq_(); break;
case Token::Type::TOKEN_BANG_EQUAL: btx->neq_(); break;
case Token::Type::TOKEN_LESS: btx->less(); break;
case Token::Type::TOKEN_LESS_EQUAL: btx->lesseq(); break;
case Token::Type::TOKEN_LESS_LESS: btx->blshift(); break;
case Token::Type::TOKEN_GREATER: btx->greater(); break;
case Token::Type::TOKEN_GREATER_EQUAL: btx->greatereq(); break;
case Token::Type::TOKEN_GREATER_GREATER: btx->brshift(); break;
case Token::Type::TOKEN_and:
btx->land(jumpto, btx->getip() - jumpto);
break;
case Token::Type::TOKEN_or:
btx->lor(jumpto, btx->getip() - jumpto);
break;
default:
panic("Invalid binary operator '",
Token::FormalNames[bin->token.type], "'!");
}
}
void CodeGenerator::visit(GroupingExpression *g) {
#ifdef DEBUG_CODEGEN
dinfo("");
g->token.highlight();
#endif
for(int j = 0; j < g->exprs->size; j++) {
g->exprs->values[j].toExpression()->accept(this);
}
if(g->istuple) {
btx->tuple_build(g->exprs->size);
btx->stackEffect(-g->exprs->size + 1);
}
}
CodeGenerator::CallInfo CodeGenerator::resolveCall(const String2 &name,
const String2 &signature) {
CallInfo info = {UNDEFINED, 0, true, false};
// the order of preference is as following
// local > class > module > core > builtin
// softcalls are always preferred
if(ftx->has_slot(name, scopeID)) {
info.type = LOCAL;
info.frameIdx = ftx->get_slot(name);
return info;
}
// if we're not inside a user defined class,
// mtx and ctx will point to the same
// CompilationContext
// Since we are always inside of a class,
// first search for methods inside
// of it
if(ctx->has_mem(name)) {
info.type = CLASS;
info.frameIdx = ctx->get_mem_slot(name);
return info;
}
if(ctx->has_fn(signature)) {
info.type = CLASS;
info.frameIdx = ctx->get_fn_sym(signature);
info.soft = false;
info.isStatic =
ctx->get_class()->get_fn(info.frameIdx).toFunction()->isStatic();
// Search for the frame in the class
return info;
}
// Search for methods with generated signature in the present
// module
if(mtx->has_mem(name)) {
info.type = MODULE;
info.frameIdx = mtx->get_mem_slot(name);
return info;
} else if(mtx->has_fn(signature)) {
info.type = MODULE;
info.frameIdx = mtx->get_fn_sym(signature);
info.soft = false;
info.isStatic =
mtx->get_class()->get_fn(info.frameIdx).toFunction()->isStatic();
return info;
}
int64_t nid = SymbolTable2::insert(name);
// try searching in core
if(corectx->has_fn(nid) && corectx->get_fn(nid).isInteger()) {
info.type = CORE;
info.frameIdx = corectx->get_fn(nid).toInteger();
return info;
}
int64_t sid = SymbolTable2::insert(signature);
if(corectx->has_fn(sid) && corectx->get_fn(sid).isFunction()) {
info.type = CORE;
info.frameIdx = sid;
info.soft = false;
info.isStatic = corectx->get_fn(sid).toFunction()->isStatic();
return info;
}
// undefined
info.soft = false;
return info;
}
void CodeGenerator::emitCall(CallExpression *call) {
#ifdef DEBUG_CODEGEN
dinfo("Generating call for");
call->callee->token.highlight();
#endif
int argSize = call->arguments->size;
String2 signature = generateSignature(call->callee->token, argSize);
String2 name =
String::from(call->callee->token.start, call->callee->token.length);
// 0 denotes no super or this call
// 1 denotes its a 'this(_,..)' call
// 2 denotes its a 'super(,..)' call
int thisOrSuper = 0;
if(call->callee->token.type == Token::Type::TOKEN_this)
thisOrSuper = 1;
else if(call->callee->token.type == Token::Type::TOKEN_super)
thisOrSuper = 2;
// if callee is a method reference, we force a soft
// call
bool force_soft = false;
CallInfo info = {UNDEFINED, 0, true, false};
if(call->callee->type == Expression::EXPR_MethodReference) {
call->callee->accept(this);
force_soft = true;
} else if(thisOrSuper > 0) {
validateThisOrSuper(call->callee->token);
// prepare the call, but make it a method call by toggling
// onRefer
btx->load_slot_n(0);
onRefer = true;
} else if(!onRefer) { // if this is a method call, we
// don't need to resolve anything
info = resolveCall(name, signature);
if(!info.soft) {
// not undefined, and not a soft call
// so load the receiver first
switch(info.type) {
case CLASS: btx->load_slot_n(0); break;
case MODULE: loadPresentModule(); break;
case CORE: loadCoreModule(); break;
default: break;
}
} else if(info.type != UNDEFINED) {
// resolved soft call
// the receiver will be stored where
// the class or the boundmethod is
// stored
variableInfo.position = info.type;
variableInfo.slot = info.frameIdx;
variableInfo.isStatic =
info.type == CLASS && ctx->get_mem_info(name).isStatic;
loadVariable(variableInfo);
}
} else if(inSuper || inThis) {
// if this is a super/this call, load the object first
btx->load_slot_0();
}
// Reset the referral status for arguments
bool bak = onRefer;
onRefer = false;
for(int j = 0; j < call->arguments->size; j++) {
call->arguments->values[j].toExpression()->accept(this);
}
onRefer = bak;
btx->insert_token(call->callee->token);
// argsize + 1 arguments including the receiver
// 1 return value
btx->stackEffect(-argSize);
// if this is a force soft call, we don't care
if(force_soft) {
// generate the no name signature
int sig = SymbolTable2::insert(generateSignature(argSize));
btx->call_soft_(sig, argSize);
}
// If this a reference expression, dynamic dispatch will be used
else if(onRefer) {
if(inThis) {
// if its a 'this.' call, perform it like a method call
// on present object
btx->call_method_(SymbolTable2::insert(signature), argSize);
inThis = false;
} else if(thisOrSuper == 1) {
// this() calls are directly dispatched, intraclass
info = resolveCall(String::const_EmptyString, signature);
switch(info.type) {
case CLASS: btx->call_intra_(info.frameIdx, argSize); break;
default:
lnerr_(call->callee->token,
"No constructor with specified signature found in "
"class '",
ctx->get_class()->name, "'!");
break;
}
onRefer = false;
} else {
if(inSuper) {
btx->call_method_super_(SymbolTable2::insert(signature),
argSize);
inSuper = false;
} else if(thisOrSuper > 0) {
onRefer = false;
btx->call_method_super_(SymbolTable2::insert(signature),
argSize);
} else {
btx->call_method_(SymbolTable2::insert(signature), argSize);
}
}
} else {
// this call can be resolved compile time
if(info.type == UNDEFINED) {
// Function is not found
lnerr_(call->callee->token,
"No function with the specified signature found "
"in module '",
mtx->get_class()->name, "'!");
// String *s = String::from(call->callee->token.start,
// call->callee->token.length);
// TODO: Error reporting
/*
for(auto const &i : ctx->public_signatures->vv) {
if(s == i.second->name) {
lninfo("Found similar function (takes %zu arguments, "
"provided "
"%zu)",
i.second->token, i.second->arity, argSize);
i.second->token.highlight();
}
}*/
return;
}
if(info.soft) {
// generate the no name signature
int sig = SymbolTable2::insert(generateSignature(argSize));
btx->call_soft_(sig, argSize);
} else {
// function call
// the receiver is already loaded
if(ftx->get_fn()->isStatic() && !info.isStatic &&
info.type == CLASS) {
lnerr_(call->token,
"Cannot call a non static function from a static "
"function!");
}
if(info.type == CLASS)
btx->call_intra_(info.frameIdx, argSize);
else
btx->call_(info.frameIdx, argSize);
}
}
}
void CodeGenerator::visit(CallExpression *call) {
emitCall(call);
}
CodeGenerator::VarInfo CodeGenerator::lookForVariable2(String * name,
bool declare,
Visibility vis,
bool force) {
int slot = 0;
if(!force) {
// first check the present context
if(ftx->has_slot(name, scopeID)) {
slot = ftx->get_slot(name);
return VarInfo{slot, LOCAL, false};
} else { // It's in an enclosing class, or parent frame or another mtx
// Check if it is in present class
if(ctx->has_mem(name)) {
return VarInfo{ctx->get_mem_slot(name), CLASS,
ctx->is_static_slot(name)};
}
// Check if it is in the parent module
if(mtx->has_mem(name)) {
return VarInfo{mtx->get_mem_slot(name), MODULE, false};
}
int64_t nid = SymbolTable2::insert(name);
// Check if it is in core
if(corectx->has_fn(nid) && corectx->get_fn(nid).isInteger()) {
return VarInfo{(int)corectx->get_fn(nid).toInteger(), CORE,
false};
}
}
}
if(declare || force) {
// Finally, declare the variable in the present frame
// If we're in the default constructor of a module,
// make the variable a class member
if(ctx->moduleContext == NULL &&
ftx == ctx->get_default_constructor()) {
Visibility v = vis != VIS_DEFAULT ? vis : currentVisibility;
switch(v) {
case VIS_PUB: ctx->add_public_mem(name); break;
default: ctx->add_private_mem(name); break;
}
slot = ctx->get_mem_slot(name);
return VarInfo{slot, CLASS, false};
} else {
// otherwise, declare it in the present scope
slot = ftx->create_slot(name, scopeID);
return VarInfo{slot, LOCAL, false};
}
}
return VarInfo{-1, UNDEFINED, false};
}
CodeGenerator::VarInfo CodeGenerator::lookForVariable(Token t, bool declare,
bool showError,
Visibility vis) {
String *name = String::from(t.start, t.length);
VarInfo var = lookForVariable2(name, declare, vis);
if(var.position == UNDEFINED && showError) {
lnerr_(t, "No such variable found : '", name, "'");
} else if(var.position == CLASS) {
// check if non static variable is used in a static method
ClassCompilationContext::MemberInfo m = ctx->get_mem_info(name);
if(ftx->f->isStatic() && !m.isStatic) {
lnerr_(t, "Non-static variable '", name,
"' cannot be accessed from static "
"method '",
ftx->f->name, "'!");
}
}
return var;
}
void CodeGenerator::visit(AssignExpression *as) {
#ifdef DEBUG_CODEGEN
dinfo("");
as->token.highlight();
#endif
if(as->target->isMemberAccess())
panic("AssignExpression should not contain member access!");
if(as->target->type == Expression::EXPR_Subscript) {
// it is a subscript setter
// subscript setters are compiled as the
// target first, then the value to avoid
// stack manipulation in case we need to
// call op method [](_,_)
btx->insert_token(as->target->token);
bool b = onLHS;
onLHS = true;
as->target->accept(this);
onLHS = b;
btx->insert_token(as->val->token);
as->val->accept(this);
btx->insert_token(as->token);
btx->call_method_(SymbolTable2::const_sig_subscript_set, 2);
} else {
// Resolve the expression
btx->insert_token(as->val->token);
as->val->accept(this);
variableInfo = lookForVariable(as->target->token, true);
btx->insert_token(as->token);
// target of an assignment expression cannot be a
// builtin constant
if(variableInfo.position == CORE) {
// force declare in present scope
variableInfo = lookForVariable2(
String::from(as->target->token.start, as->target->token.length),
true, currentVisibility, true);
}
storeVariable(variableInfo);
}
}
void CodeGenerator::visit(ArrayLiteralExpression *al) {
#ifdef DEBUG_CODEGEN
dinfo("");
al->token.highlight();
#endif
if(al->exprs->size > 0) {
// evalute all the expressions
for(int j = 0; j < al->exprs->size; j++) {
al->exprs->values[j].toExpression()->accept(this);
}
}
// finally emit opcode to create an
// array, assign those
// expressions to the array, and leave
// the array at the top of the stack
btx->array_build(al->exprs->size);
btx->stackEffect(-(int)al->exprs->size + 1);
}
void CodeGenerator::visit(HashmapLiteralExpression *al) {
#ifdef DEBUG_CODEGEN
dinfo("");
al->token.highlight();
#endif
if(al->keys->size > 0) {
// now evalute all the key:value pairs
for(int j = 0; j < al->keys->size; j++) {
al->keys->values[j].toExpression()->accept(this);
al->values->values[j].toExpression()->accept(this);
}
}
btx->map_build(al->keys->size);
btx->stackEffect(-(int)al->keys->size + 1);
}
void CodeGenerator::visit(LiteralExpression *lit) {
#ifdef DEBUG_CODEGEN
dinfo("");
lit->token.highlight();
#endif
btx->insert_token(lit->token);
// use explicit opcode for nil, since call optimizations
// pushes ValueNil in the preallocated local slots in
// the bytecode.
if(lit->value.isNil())
btx->pushn();
else
btx->push(lit->value);
}
void CodeGenerator::visit(SetExpression *sete) {
if(state == COMPILE_BODY) {
#ifdef DEBUG_CODEGEN
dinfo("");
sete->token.highlight();
#endif
sete->value->accept(this);
bool b = onLHS;
onLHS = true;
sete->object->accept(this);
btx->store_field_(lastMemberReferenced);
onLHS = b;
}
}
void CodeGenerator::visit(GetExpression *get) {
#ifdef DEBUG_CODEGEN
dinfo("");
get->token.highlight();
#endif
bool lb = onLHS;
onLHS = false;
get->object->accept(this);
bool b = onRefer;
onRefer = true;
onLHS = lb;
get->refer->accept(this);
onRefer = b;
}
void CodeGenerator::validateThisOrSuper(Token tos) {
// at top level, neither this nor super can be used
if(mtx == ctx) {
lnerr_(tos, "Cannot use this/super in the module scope!");
} else if(ftx->f->isStatic()) {
// if we're inside a static method, we cannot use this/super
lnerr_(tos, "Cannot use this/super inside a static method!");
} else if(!ctx->isDerived && tos.type == Token::Type::TOKEN_super) {
// we cannot use super inside a class which is not derived
lnerr_(tos, "Cannot use 'super' inside class '",
ctx->compilingClass->name,
"' which is not derived "
"from anything!");
}
}
void CodeGenerator::visit(GetThisOrSuperExpression *get) {
#ifdef DEBUG_CODEGEN
dinfo("");
get->token.highlight();
#endif
// right side can be either one of
// 1) reference expression
// 2) method call
// 3) literal expression
// also, neither one of this can be part of
// another expression, so we are free to
// toggle onRefer on and off
onRefer = true;
if(get->token.type == Token::Type::TOKEN_this) {
inThis = true;
validateThisOrSuper(get->token);
get->refer->accept(this);
inThis = false;
} else {
inSuper = true;
validateThisOrSuper(get->token);
get->refer->accept(this);
inSuper = false;
}
onRefer = false;
}
void CodeGenerator::visit(SubscriptExpression *sube) {
#ifdef DEBUG_CODEGEN
dinfo("");
sube->token.highlight();
#endif
bool b = onLHS;
onLHS = false;
sube->object->accept(this);
sube->idx->accept(this);
onLHS = b;
if(!onLHS)
btx->call_method_(SymbolTable2::const_sig_subscript_get, 1);
}
void CodeGenerator::loadVariable(VarInfo variableInfo, bool isref) {
if(isref) {
btx->load_field_(lastMemberReferenced);
} else {
switch(variableInfo.position) {
case LOCAL: btx->load_slot_n(variableInfo.slot); break;
case MODULE:
loadPresentModule();
btx->load_tos_slot(variableInfo.slot);
break;
case CLASS:
if(variableInfo.isStatic)
btx->load_static_slot(variableInfo.slot,
ctx->compilingClass);
else
btx->load_object_slot(variableInfo.slot);
break;
case CORE:
loadCoreModule();
btx->load_tos_slot(variableInfo.slot);
break;
case UNDEFINED: // should already be handled
break;
}
}
}
void CodeGenerator::storeVariable(VarInfo variableInfo, bool isref) {
if(isref) {
btx->store_field_(lastMemberReferenced);
} else {
switch(variableInfo.position) {
case LOCAL: btx->store_slot_n(variableInfo.slot); break;
case MODULE:
loadPresentModule();
btx->store_tos_slot(variableInfo.slot);
break;
case CLASS:
if(variableInfo.isStatic)
btx->store_static_slot(variableInfo.slot,
ctx->compilingClass);
else
btx->store_object_slot(variableInfo.slot);
break;
case CORE:
loadCoreModule();
btx->store_tos_slot(variableInfo.slot);
break;
case UNDEFINED: // should already be handled
break;
}
}
}
void CodeGenerator::visit(PrefixExpression *pe) {
#ifdef DEBUG_CODEGEN
dinfo("");
pe->token.highlight();
#endif
switch(pe->token.type) {
case Token::Type::TOKEN_PLUS: pe->right->accept(this); break;
case Token::Type::TOKEN_BANG:
pe->right->accept(this);
btx->lnot();
break;
case Token::Type::TOKEN_MINUS:
pe->right->accept(this);
btx->insert_token(pe->token);
btx->neg();
break;
case Token::Type::TOKEN_TILDE:
pe->right->accept(this);
btx->insert_token(pe->token);
btx->bnot();
break;
case Token::Type::TOKEN_PLUS_PLUS:
case Token::Type::TOKEN_MINUS_MINUS:
if(!pe->right->isAssignable()) {
lnerr_(pe->token,
"Cannot apply '++' on a non-assignable expression!");
} else {
// perform the load
pe->right->accept(this);
if(pe->token.type == Token::Type::TOKEN_PLUS_PLUS)
btx->incr();
else
btx->decr();
// if this is a member access, reload the object,
// then store
if(pe->right->isMemberAccess()) {
onLHS = true;
pe->right->accept(this);
onLHS = false;
}
storeVariable(variableInfo, pe->right->isMemberAccess());
}
break;
default: panic("Bad prefix operator!");
}
}
void CodeGenerator::visit(PostfixExpression *pe) {
#ifdef DEBUG_CODEGEN
dinfo("");
pe->token.highlight();
#endif
if(!pe->left->isAssignable()) {
lnerr_(pe->token,
"Cannot apply postfix operator on a non-assignable expression!");
}
// perform the load
pe->left->accept(this);
switch(pe->token.type) {
case Token::Type::TOKEN_PLUS_PLUS:
case Token::Type::TOKEN_MINUS_MINUS:
if(pe->token.type == Token::Type::TOKEN_PLUS_PLUS) {
btx->copy(SymbolTable2::const_sig_incr);
btx->incr();
} else {
btx->copy(SymbolTable2::const_sig_decr);
btx->decr();
}
// if this is a member access, reload the object,
// then store
if(pe->left->isMemberAccess()) {
onLHS = true;
pe->left->accept(this);
onLHS = false;
}
storeVariable(variableInfo, pe->left->isMemberAccess());
btx->pop_();
break;
default:
panic("Bad postfix operator '", Token::TokenNames[pe->token.type],
"'!");
}
}
void CodeGenerator::visit(VariableExpression *vis) {
#ifdef DEBUG_CODEGEN
dinfo("");
vis->token.highlight();
#endif
if(vis->token.type == Token::Type::TOKEN_this) {
// it cannot come as a part of another expression or
// in the lhs. so it must have come as only 'this'.
// so load it, and we're done
validateThisOrSuper(vis->token);
// the object is stored in the 0th slot
btx->load_slot_n(0);
return;
}
String *name = String::from(vis->token.start, vis->token.length);
btx->insert_token(vis->token);
if(!onRefer) {
variableInfo = lookForVariable(vis->token);
if(onLHS) { // in case of LHS, just pass on the information
onLHS = false;
} else {
loadVariable(variableInfo);
}
} else {
if(inThis) {
// the field needs to be resolved on the present class
// at runtime
btx->load_slot_0();
inThis = false;
} else if(inSuper) {
// append "s " in the name
name = String::append("s ", name);
// we want the name resolution to happen at runtime.
// but even if we are setting to a field, we need to load
// the object for runtime resolution.
btx->load_slot_0();
inSuper = false;
}
if(onLHS)
lastMemberReferenced = SymbolTable2::insert(name);
else
btx->load_field_(SymbolTable2::insert(name));
}
}
void CodeGenerator::visit(MethodReferenceExpression *ifs) {
#ifdef DEBUG_CODEGEN
dinfo("");
ifs->token.highlight();
#endif
String *sig = generateSignature(ifs->token, ifs->args);
btx->insert_token(ifs->token);
if(onRefer) {
// if we're on a 'this.' reference, we need
// to resolve the signature in present class
if(inThis) {
if(!ctx->has_fn(sig)) {
lnerr_(ifs->token, "Method '", sig,
"' not found in present class!");
} else {
btx->load_slot_0();
btx->load_method(SymbolTable2::insert(sig));
btx->bind_method();
}
inThis = false;
} else {
// otherwise if we're in a 'super.' reference,
// load the object before search
if(inSuper) {
btx->load_slot_0();
inSuper = false;
}
// if we're on reference,
// emit code for search
//
int sym = SymbolTable2::insert(sig);
btx->search_method(sym);
// if successful, bind it too
btx->bind_method();
}
} else {
// we necessarily don't want this lookup to be
// a softcall. so we pass NULL as name to
// resolveCall
CallInfo info = resolveCall(NULL, sig);
switch(info.type) {
case LOCAL:
// this is impossible. since
// this is not a soft call, we
// have no way of resolving the
// signature in a local variable
panic("Method reference must not resolve to a local "
"variable!");
break;
case CLASS:
// load the object
btx->load_slot_n(0);
break;
case MODULE:
// load the module
loadPresentModule();
break;
case CORE:
// load the module
loadCoreModule();
break;
case UNDEFINED:
lnerr_(ifs->token, "No such method with siganture '", sig,
"' found in present "
"context!");
break;
}
// load the method
btx->load_method(info.frameIdx);
// finally, bind the method
btx->bind_method();
}
}
void CodeGenerator::visit(IfStatement *ifs) {
#ifdef DEBUG_CODEGEN
dinfo("");
ifs->token.highlight();
#endif
ifs->condition->accept(this);
btx->insert_token(ifs->token);
int jif = btx->jumpiffalse(0), jumpto = 0, exitif = -1;
ifs->thenBlock->accept(this);
if(ifs->elseBlock != nullptr) {
exitif = btx->jump(0);
jumpto = btx->getip();