forked from gfwilliams/tiny-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmvmCodegen.cpp
1952 lines (1658 loc) · 57.5 KB
/
mvmCodegen.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
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
/*
* File: mvmCodegen.cpp
* Author: ghernan
*
* Code generator for micro VM,
*
* Created on December 2, 2016, 9:59 PM
*/
#include "ascript_pch.hpp"
#include "mvmCodegen.h"
#include "asObjects.h"
#include "ScriptException.h"
#include <set>
#include <map>
#include <string>
using namespace std;
/**
* Code generation scope
*/
class CodegenScope
{
public:
void declare (const std::string& name, int stackPos)
{
m_symbols[name] = stackPos;
}
bool isDeclared (const std::string& name)const
{
return m_symbols.count(name) > 0;
}
int symbolPosition (const string& name)const
{
ASSERT (isDeclared(name));
return m_symbols.at(name);
}
const Ref<AstNode> ownerNode;
const bool isBlock;
const bool isParameters;
CodegenScope (const Ref<AstNode> _ownerNode, bool block, bool params)
: ownerNode (_ownerNode), isBlock(block), isParameters(params)
{
}
private:
std::map < std::string, int> m_symbols;
};
typedef map<ASValue, int> ConstantsMap;
/**
* State of a codegen operation
*/
struct CodegenState
{
Ref<MvmRoutine> curRoutine;
VarMap members;
ConstantsMap constants;
map<string, ASValue > symbols;
ScriptPosition curPos;
CodeMap* pCodeMap = NULL;
int stackSize = 0;
void declare (const std::string& name)
{
assert (!m_scopes.empty());
m_scopes.back().declare(name, stackSize);
}
bool isDeclared (const std::string& name)const
{
auto it = m_scopes.rbegin();
for (; it != m_scopes.rend(); ++it)
{
if (it->isDeclared(name))
return true;
else if (!it->isBlock)
return false;
}
return false;
}
bool isParam (const std::string& name)const
{
auto it = m_scopes.rbegin();
for (; it != m_scopes.rend(); ++it)
{
if (it->isDeclared(name))
return it->isParameters;
}
return false;
}
int getLocalVarOffset(const string& name)const
{
for (auto it = m_scopes.rbegin(); it != m_scopes.rend(); ++it)
{
if (it->isDeclared(name))
{
int pos = it->symbolPosition(name);
ASSERT (pos < stackSize);
return stackSize - (pos+1);
}
}
ASSERT (!"Local symbol not found!");
return -1;
}
int getParamIndex(const string& name)const
{
for (auto it = m_scopes.rbegin(); it != m_scopes.rend(); ++it)
{
if (it->isDeclared(name))
{
if (!it->isParameters)
break;
return it->symbolPosition(name);
}
}
ASSERT (!"Parameter not found!");
return -1;
}
void pushScope (const Ref<AstNode> _ownerNode, bool block, bool params)
{
m_scopes.push_back(CodegenScope(_ownerNode, block, params));
}
void popScope()
{
m_scopes.pop_back();
}
CodegenScope* curScope ()
{
return &m_scopes.back();
}
private:
vector<CodegenScope> m_scopes;
};
//Forward declarations
typedef void (*NodeCodegenFN)(Ref<AstNode> node, CodegenState* pState);
void codegen (Ref<AstNode> statement, CodegenState* pState);
int childrenCodegen (Ref<AstNode> statement, CodegenState* pState);
bool childCodegen (Ref<AstNode> statement, int index, CodegenState* pState);
void invalidNodeCodegen (Ref<AstNode> node, CodegenState* pState);
void blockCodegen (Ref<AstNode> statement, CodegenState* pState);
void varCodegen (Ref<AstNode> statement, CodegenState* pState);
void varCodegen (const string& name, Ref<AstNode> valueNode, bool isConst, CodegenState* pState);
void ifCodegen (Ref<AstNode> statement, CodegenState* pState);
void forCodegen (Ref<AstNode> statement, CodegenState* pState);
void forEachCodegen (Ref<AstNode> statement, CodegenState* pState);
void returnCodegen (Ref<AstNode> statement, CodegenState* pState);
void functionCodegen (Ref<AstNode> statement, CodegenState* pState);
void closureCodegen (Ref<JSFunction> fn, CodegenState* pState);
Ref<JSFunction> createFunction (Ref<AstNode> node, CodegenState* pState);
void assignmentCodegen (Ref<AstNode> statement, CodegenState* pState);
void varWriteCodegen (Ref<AstNode> node, CodegenState* pState);
void fieldWriteCodegen (Ref<AstNode> node, CodegenState* pState);
void arrayWriteCodegen (Ref<AstNode> node, CodegenState* pState);
void fncallCodegen (Ref<AstNode> statement, CodegenState* pState);
void thisCallCodegen (Ref<AstNode> statement, CodegenState* pState);
void literalCodegen (Ref<AstNode> statement, CodegenState* pState);
void varReadCodegen (Ref<AstNode> node, CodegenState* pState);
void varReadCodegen (const string& name, CodegenState* pState);
void arrayCodegen (Ref<AstNode> statement, CodegenState* pState);
void objectCodegen (Ref<AstNode> statement, CodegenState* pState);
void arrayAccessCodegen (Ref<AstNode> statement, CodegenState* pState);
void memberAccessCodegen (Ref<AstNode> statement, CodegenState* pState);
void conditionalCodegen (Ref<AstNode> statement, CodegenState* pState);
void binaryOpCodegen (Ref<AstNode> statement, CodegenState* pState);
void prefixOpCodegen (Ref<AstNode> statement, CodegenState* pState);
void postfixOpCodegen (Ref<AstNode> statement, CodegenState* pState);
void logicalOpCodegen (const int opCode, Ref<AstNode> statement, CodegenState* pState);
void actorCodegen (Ref<AstNode> node, CodegenState* pState);
void connectCodegen (Ref<AstNode> node, CodegenState* pState);
void messageCodegen (Ref<AstNode> node, CodegenState* pState);
void clearLocals (int targetStackSize, CodegenState* pState);
void classCodegen (Ref<AstNode> node, CodegenState* pState);
Ref<JSFunction> classConstructorCodegen (Ref<AstNode> node, CodegenState* pState);
void baseConstructorCallCodegen (Ref<AstNode> node, CodegenState* pState);
StringVector classConstructorParams(Ref<AstNode> node, CodegenState* pState);
Ref<JSClass> getParentClass (Ref<AstNode> node, CodegenState* pState);
void exportCodegen (Ref<AstNode> node, CodegenState* pState);
void importCodegen (Ref<AstNode> node, CodegenState* pState);
void pushConstant (ASValue value, CodegenState* pState);
void pushConstant (const char* str, CodegenState* pState);
void pushConstant (const std::string& str, CodegenState* pState);
void pushConstant (int value, CodegenState* pState);
void pushConstant (bool value, CodegenState* pState);
void pushNull (CodegenState* pState);
void callCodegen (const std::string& fnName, int nParams, CodegenState* pState, const ScriptPosition& pos);
void callInstruction (int nParams, CodegenState* pState, const ScriptPosition& pos);
void copyInstruction (int offset, CodegenState* pState);
void writeInstruction (int offset, CodegenState* pState);
void instruction8 (int opCode, CodegenState* pState);
void instruction16 (int opCode, CodegenState* pState);
int getLastInstruction (CodegenState* pState);
int removeLastInstruction (CodegenState* pState);
void binaryOperatorCode (int tokenCode, CodegenState* pState, const ScriptPosition& pos);
void getEnvCodegen (CodegenState* pState);
void endBlock (int trueJump, int falseJump, CodegenState* pState);
void setTrueJump (int blockId, int destinationId, CodegenState* pState);
void setFalseJump (int blockId, int destinationId, CodegenState* pState);
int curBlockId (CodegenState* pState);
bool isCopyInstruction(int opCode);
int getAssignOp (Ref<AstNode> node);
int calcStackOffset8(int opCode);
int calcStackOffset16(int opCode);
CodegenState initFunctionState (Ref<AstNode> node, const StringVector& params, CodeMap* pMap);
CodegenState initFunctionState (Ref<AstNode> node, CodeMap* pMap);
/**
* Generates MVM code for a script.
* @param script Script AST node.
* @return
*/
Ref<MvmRoutine> scriptCodegen (Ref<AstNode> script, CodeMap* pMap)
{
CodegenState state;
ASSERT (script->getType() == AST_SCRIPT);
state.curRoutine = MvmRoutine::create();
state.pushScope(script, false, false);
state.pCodeMap = pMap;
state.curPos = script->position();
auto statements = script->children();
for (size_t i = 0; i < statements.size(); ++i)
{
//Remove previous result
if (i > 0)
instruction8 (OC_POP, &state);
codegen (statements[i], &state);
}
return state.curRoutine;
}
void codegen (Ref<AstNode> statement, CodegenState* pState)
{
static NodeCodegenFN types[AST_TYPES_COUNT] = {NULL, NULL};
if (types [0] == NULL)
{
types [AST_SCRIPT] = invalidNodeCodegen;
types [AST_BLOCK] = blockCodegen;
types [AST_VAR] = varCodegen;
types [AST_CONST] = varCodegen;
types [AST_IF] = ifCodegen;
types [AST_FOR] = forCodegen;
types [AST_FOR_EACH] = forEachCodegen;
types [AST_RETURN] = returnCodegen;
types [AST_FUNCTION] = functionCodegen;
types [AST_ASSIGNMENT] = assignmentCodegen;
types [AST_FNCALL] = fncallCodegen;
types [AST_LITERAL] = literalCodegen;
types [AST_IDENTIFIER] = varReadCodegen;
types [AST_ARRAY] = arrayCodegen;
types [AST_OBJECT] = objectCodegen;
types [AST_ARRAY_ACCESS] = arrayAccessCodegen;
types [AST_MEMBER_ACCESS] = memberAccessCodegen;
types [AST_CONDITIONAL] = conditionalCodegen;
types [AST_BINARYOP] = binaryOpCodegen;
types [AST_PREFIXOP] = prefixOpCodegen;
types [AST_POSTFIXOP] = postfixOpCodegen;
types [AST_ACTOR] = actorCodegen;
types [AST_CONNECT] = connectCodegen;
types [AST_INPUT] = messageCodegen;
types [AST_OUTPUT] = messageCodegen;
types [AST_CLASS] = classCodegen;
types [AST_EXPORT] = exportCodegen;
types [AST_IMPORT] = importCodegen;
}
auto oldPos = pState->curPos;
pState->curPos = statement->position();
types[statement->getType()](statement, pState);
pState->curPos = oldPos;
}
/**
* Generates code for the children of a given statement
* @param statement
* @param pState
*/
int childrenCodegen (Ref<AstNode> statement, CodegenState* pState)
{
const AstNodeList& children = statement->children();
int count = 0;
for (size_t i=0; i < children.size(); ++i)
{
if (children[i].notNull())
{
codegen (children[i], pState);
++count;
}
}
return count;
}
/**
* Generates code for a child node of an AST node.
* @param statement
* @param index
* @param pState
* @return
*/
bool childCodegen (Ref<AstNode> statement, int index, CodegenState* pState)
{
const AstNodeList& children = statement->children();
if (index >= (int)children.size() || index < 0)
return false;
else if (children[index].notNull())
{
codegen (children[index], pState);
return true;
}
else
return false;
}
/**
* Called if an invalid node is found in the AST
* @param node
* @param pState
*/
void invalidNodeCodegen(Ref<AstNode> node, CodegenState* pState)
{
auto typeString = astTypeToString(node->getType());
errorAt (node->position(), "Invalid AST node found: ", typeString.c_str());
}
/**
* Generates the code for a block of statements.
* @param statement
* @param pState
*/
void blockCodegen (Ref<AstNode> statement, CodegenState* pState)
{
const AstNodeList& children = statement->children();
pState->pushScope(statement, true, false);
const int stackSize = pState->stackSize;
for (size_t i=0; i < children.size(); ++i)
{
if (children[i].notNull())
{
codegen (children[i], pState);
instruction8(OC_POP, pState); //Discard result
}
}
clearLocals(stackSize, pState);
pState->popScope();
//Non expression statements leave a 'null' on the stack.
pushNull(pState);
}
/**
* Generates code for a 'var' declaration
* @param statement
* @param pState
*/
void varCodegen (Ref<AstNode> node, CodegenState* pState)
{
const string name = node->getName();
const bool isLocal = pState->curScope()->isBlock;
const bool isConst = node->getType() == AST_CONST;
if (isLocal)
{
pState->declare(name);
if (!childCodegen(node, 0, pState))
pushNull(pState);
}
else
{
getEnvCodegen(pState); //[env]
pushConstant(name, pState); //[env, name]
if (!childCodegen(node, 0, pState))
pushNull(pState);
//[env, name, value]
const int writeInst = isConst ? OC_NEW_CONST_FIELD : OC_WR_FIELD;
instruction8(writeInst, pState); //[value]
instruction8(OC_POP, pState); //[]
//TODO: It is a bit odd to throw away the value and replace it
//by a 'null' on the stack.
}
//Non-expression statements leave a 'null' on the stack.
pushNull(pState); //[null]
}
/**
* Generates code for an 'if' statement
* @param statement
* @param pState
*/
void ifCodegen (Ref<AstNode> statement, CodegenState* pState)
{
const int conditionBlock = curBlockId(pState)+1;
const bool conditional = statement->getType() == AST_CONDITIONAL;
//Generate code for condition
pushNull(pState);
endBlock (conditionBlock, conditionBlock, pState);
childCodegen(statement, 0, pState);
const int thenInitialBlock = curBlockId(pState)+1;
endBlock (thenInitialBlock, -1, pState);
const int postConditionStack = pState->stackSize;
//Generate code for 'then' block
childCodegen(statement, 1, pState);
if (conditional)
copyInstruction(0, pState);
const int thenFinalBlock = curBlockId(pState);
int nextBlock = thenFinalBlock + 1;
const int elseBlock = nextBlock;
endBlock (nextBlock, nextBlock, pState);
const int postThenStack = pState->stackSize;
//Try to generate 'else'
if (statement->childExists(2))
{
pState->stackSize = postConditionStack;
childCodegen(statement, 2, pState);
if (conditional)
copyInstruction(0, pState);
//Recalculate 'next' block
nextBlock = curBlockId(pState)+1;
endBlock (nextBlock, nextBlock, pState);
//Fix 'then' jump destination
setTrueJump (thenFinalBlock, nextBlock, pState);
setFalseJump (thenFinalBlock, nextBlock, pState);
}
ASSERT (pState->stackSize == postThenStack);
//Fix else jump
setFalseJump (thenInitialBlock-1, elseBlock, pState);
//Non-expression statements leave a 'null' on the stack.
//TODO: make if expressions?
if (!conditional)
pushNull(pState);
}
/**
* Generates code for a 'for' loop.
* It also implements 'while' loops, as they are just a for without initialization
* and increment statements.
* @param statement
* @param pState
*/
void forCodegen (Ref<AstNode> statement, CodegenState* pState)
{
//For loops define its own scope
const int initialStack = pState->stackSize;
//Loop initialization
if (!childCodegen (statement, 0, pState))
pushNull(pState);
const int conditionBlock = curBlockId(pState)+1;
//Generate code for condition
endBlock (conditionBlock, conditionBlock, pState);
if (!childCodegen(statement, 1, pState))
{
//If there is no condition, we replace it by an 'always true' condition
pushConstant(true, pState);
}
const int bodyBegin = curBlockId(pState)+1;
endBlock (bodyBegin, -1, pState);
//loop body & increment
if (childCodegen (statement, 3, pState))
instruction8(OC_POP, pState);
if (!childCodegen (statement, 2, pState))
pushNull(pState);
const int nextBlock = curBlockId(pState)+1;
endBlock(conditionBlock, conditionBlock, pState);
//Fix condition jump destination
setFalseJump(bodyBegin-1, nextBlock, pState);
//Remove loop scope
clearLocals(initialStack, pState);
//Non-expression statements leave a 'null' on the stack.
pushNull(pState);
}
/**
* Generates code for a 'for (... in ...)' loop, which iterates over the members
* of a sequence.
* @param node
* @param pState
*/
void forEachCodegen (Ref<AstNode> node, CodegenState* pState)
{
const ScriptPosition pos = node->position();
//Loop initialization
childCodegen (node, 1, pState); //[sequence]
//Get iterator.
callCodegen ("@iterator",1, pState, pos); //[iterator]
//Generate code for condition
pushConstant(jsNull(), pState); //[null, iterator]
const int conditionBlock = curBlockId(pState)+1;
endBlock (conditionBlock, conditionBlock, pState); //[iterator]
instruction8(OC_CP, pState); //[iterator, iterator]
pushNull(pState); //[null, iterator, iterator]
callCodegen("@notTypeEqual", 2, pState, pos); //[bool, iterator]
endBlock (conditionBlock+1, -1, pState); //[iterator]
//Generate code for body
pState->pushScope(node, true, false);
//Declare item variable name, and read its content
string itemVarName = node->children().front()->getName();
pState->declare(itemVarName);
copyInstruction(0, pState); //[iterator, iterator]
instruction8(OC_WR_THISP, pState);
pushConstant("head", pState); //["head", iterator, iterator]
instruction8(OC_RD_FIELD, pState); //[headFn, iterator]
callInstruction(0, pState, node->children().front()->position()); //[item, iterator]
childCodegen(node, 2, pState); //[body_result, item, iterator]
instruction8(OC_POP, pState); //[item, iterator]
instruction8(OC_POP, pState); //[iterator]
pState->popScope();
//Next iterator.
instruction8(OC_WR_THISP, pState);
pushConstant("tail", pState); //["tail", iterator]
instruction8(OC_RD_FIELD, pState); //[tailFn]
callInstruction(0, pState, pos); //[nextIterator]
pushConstant(jsNull(), pState); //[null, nextIterator]
endBlock(conditionBlock, conditionBlock, pState); //[nextIterator]
//Block after the loop
const int nextBlock = curBlockId(pState);
//Fix condition jump destination
setFalseJump(conditionBlock, nextBlock, pState);
//[iterator] is left on the stack, which should be null at the end of the loop.
}
/**
* Generates code for a 'return' statement
* @param node
* @param pState
*/
void returnCodegen (Ref<AstNode> node, CodegenState* pState)
{
//It just pushes return expression value on the stack, and sets next block
//indexes to (-1), which means that the current function shall end.
if (!childCodegen(node, 0, pState))
{
//If it is an empty return statement, push a 'null' value on the stack
pushNull(pState);
}
//remove locals from the stack
if (pState->stackSize > 1)
{
//Write the result at the new stack top.
writeInstruction(pState->stackSize-2, pState);
//shrink the stack
while (pState->stackSize > 1)
instruction8(OC_POP, pState);
}
ASSERT (pState->stackSize == 1);
endBlock(-1, -1, pState);
}
/**
* Generates code for a function declaration.
* @param node
* @param pState
*/
void functionCodegen (Ref<AstNode> node, CodegenState* pState)
{
//TODO: Closure code generation. Necessary to access globals
auto function = createFunction(node, pState);
if (node->getName().empty())
closureCodegen(function, pState); //Unnamed function
else
{
const string name = node->getName();
const bool isLocal = pState->curScope()->isBlock;
if (isLocal)
{
pState->declare(name);
//Functions are expressions, even named ones
closureCodegen(function, pState);
copyInstruction (0, pState);
//[function, function] (local variable and result)
}
else
{
getEnvCodegen(pState); //[env]
pushConstant(name, pState); //[env, name]
closureCodegen(function, pState); //[env, name, function]
instruction8(OC_NEW_CONST_FIELD, pState); //[function]
}
}
}
/**
* Generates code for a closure
* A closure is a function + environment.
* @param fn
* @param pState
*/
void closureCodegen (Ref<JSFunction> fn, CodegenState* pState)
{
//TODO: This first version just passes the current environment.
getEnvCodegen(pState); //[env]
pushConstant(fn->value(), pState); //[env, function]
callCodegen("@makeClosure", 2, pState, pState->curPos); //[closure]
}
/**
* Compiles and creates a function.
* @param node
* @param pState
* @return
*/
Ref<JSFunction> createFunction (Ref<AstNode> node, CodegenState* pState)
{
Ref<AstFunction> fnNode = node.staticCast<AstFunction>();
const AstFunction::Params& params = fnNode->getParams();
CodegenState fnState = initFunctionState(node, pState->pCodeMap);
auto function = JSFunction::createJS(fnNode->getName(), params, fnState.curRoutine);
codegen (fnNode->getCode(), &fnState);
return function;
}
/**
* Generates code for assignments
* @param node
* @param pState
*/
void assignmentCodegen (Ref<AstNode> node, CodegenState* pState)
{
auto& children = node->children();
ASSERT (children.size() == 2);
auto& lvalue = children[0];
switch (lvalue->getType())
{
case AST_IDENTIFIER:
varWriteCodegen(node, pState);
break;
case AST_MEMBER_ACCESS:
fieldWriteCodegen(node, pState);
break;
case AST_ARRAY_ACCESS:
arrayWriteCodegen(node, pState);
break;
default:
ASSERT (!"Unexpected lvalue node in assignment");
}
}
/**
* Generate code which writes into a variable.
* @param node
* @param pState
*/
void varWriteCodegen (Ref<AstNode> node, CodegenState* pState)
{
string name = node->children().front()->getName();
int op = getAssignOp(node);
if (pState->isDeclared(name))
{
const bool isParam = pState->isParam(name);
if (isParam)
pushConstant (pState->getParamIndex(name), pState); //[index]
//Local variable.
if (op == '=')
childCodegen(node, 1, pState); //[..., result]
else
{
childCodegen(node, 0, pState); //[..., lvalue]
childCodegen(node, 1, pState); //[..., lvalue, rvalue]
binaryOperatorCode (op, pState, node->position()); //[..., result]
}
if (pState->isParam(name))
instruction8(OC_WR_PARAM, pState); //[result]
else
writeInstruction(pState->getLocalVarOffset(name)-1, pState); //[result]
}
else
{
//environment-based variable (global, closure...)
getEnvCodegen(pState); //[env]
pushConstant(name, pState); //[env, name]
if (op == '=')
childCodegen(node, 1, pState); //[env, name, result]
else
{
copyInstruction(1, pState); //[env, name, env]
copyInstruction(1, pState); //[env, name, env, name]
instruction8(OC_RD_FIELD, pState); //[env, name, lvalue];
childCodegen(node, 1, pState); //[env, name, lvalue, rvalue];
binaryOperatorCode (op, pState, node->position()); //[env, name, result];
}
instruction8(OC_WR_FIELD, pState); //[result]
}
}
/**
* Generates code to write into a field
* @param node
* @param pState
*/
void fieldWriteCodegen (Ref<AstNode> node, CodegenState* pState)
{
int op = getAssignOp(node);
auto lexpr = node->children().front();
auto field = lexpr->children()[1]->getName();
//Object access codegen
childCodegen(lexpr, 0 , pState); //[object]
pushConstant(field, pState); //[object, field]
if (op == '=')
childCodegen (node, 1, pState); //[object, field, result]
else
{
copyInstruction(1, pState); //[object, field, object]
copyInstruction(1, pState); //[object, field, object, field]
instruction8(OC_RD_FIELD, pState); //[object, field, lvalue];
childCodegen(node, 1, pState); //[object, field, lvalue, rvalue];
binaryOperatorCode (op, pState, node->position()); //[object, field, result];
}
instruction8(OC_WR_FIELD, pState); //[result]
}
/**
* Generates code to write an array element
* @param node
* @param pState
*/
void arrayWriteCodegen (Ref<AstNode> node, CodegenState* pState)
{
int op = getAssignOp(node);
auto lexpr = node->children().front();
auto field = lexpr->children()[1]->getName();
//Array access and index codegen
childCodegen(lexpr, 0, pState); //[array]
childCodegen(lexpr, 1, pState); //[array, index]
if (op == '=')
childCodegen (node, 1, pState); //[array, index, result]
else
{
copyInstruction(1, pState); //[array, index, array]
copyInstruction(1, pState); //[array, index, array, index]
instruction8(OC_RD_INDEX, pState); //[array, index, lvalue];
childCodegen(node, 1, pState); //[array, index, lvalue, rvalue];
binaryOperatorCode (op, pState, node->position()); //[array, index, result];
}
instruction8(OC_WR_INDEX, pState); //[result]
}
/**
* Generates code for a function call
* @param node
* @param pState
*/
void fncallCodegen (Ref<AstNode> node, CodegenState* pState)
{
const AstNodeTypes fnExprType = node->children()[0]->getType();
//If the expression to get the function reference is an object member access,
//then use generate a 'this' call.
if (fnExprType == AST_MEMBER_ACCESS)
thisCallCodegen (node, pState);
else
{
//Parameters evaluation
const int nChilds = (int)node->children().size();
for (int i = 1; i < nChilds; ++i)
childCodegen(node, i, pState);
//Evaluate function reference expression
childCodegen(node, 0, pState);
callInstruction (nChilds-1, pState, node->position());
}
}
/**
* Generates code for function call which receives a 'this' reference.
* @param node
* @param pState
*/
void thisCallCodegen (Ref<AstNode> node, CodegenState* pState)
{
auto fnExpr = node->children().front();
//Parameters evaluation
const int nChilds = (int)node->children().size();
for (int i = 1; i < nChilds; ++i)
childCodegen(node, i, pState);
//[[params]]
childCodegen(fnExpr, 0, pState); //[this, [params]]
instruction8 (OC_WR_THISP, pState); //[this, [params]]
const string fnName = fnExpr->children()[1]->getName();
pushConstant(fnName, pState); //[fnName, this, [params]]
instruction8(OC_RD_FIELD, pState); //[function, [params]]
callInstruction (nChilds-1, pState, node->position());
}
/**
* Generates code for a literal expression.
* @param node
* @param pState
*/
void literalCodegen (Ref<AstNode> node, CodegenState* pState)
{
pushConstant(node->getValue(), pState);
}
/**
* Code generation for reading a variable.
* Version which takes an AST node.
* @param node
* @param pState
*/
void varReadCodegen (Ref<AstNode> node, CodegenState* pState)
{
return varReadCodegen(node->getName(), pState);
}
/**
* Code generation for reading a variable.
* Version which takes a string naming the variable
* @param name
* @param pState
*/
void varReadCodegen (const string& name, CodegenState* pState)
{
ASSERT (!name.empty());
if (name == "this")
{
instruction8(OC_PUSH_THIS, pState); //[thisPtr]
}
else if (pState->isDeclared(name))
{
if (!pState->isParam(name))
{
const int offset = pState->getLocalVarOffset(name);
copyInstruction (offset, pState); //[varValue]
}
else
{
const int index = pState->getParamIndex(name);
pushConstant(jsInt(index), pState); //[index]
instruction8 (OC_RD_PARAM, pState); //[paramValue]
}
}
else
{
getEnvCodegen(pState); //[env]
pushConstant(name, pState); //[env, name]
instruction8(OC_RD_FIELD, pState); //[varValue]
}
}
/**
* Generates code for an array literal.
* @param statement
* @param pState
*/
void arrayCodegen (Ref<AstNode> statement, CodegenState* pState)
{
const AstNodeList children = statement->children();
pushConstant(0, pState);
callCodegen("@newArray", 1, pState, statement->position()); //[array]
instruction8(OC_CP, pState); //[array, array]
pushConstant("push", pState); //["push", array, array]
instruction8(OC_RD_FIELD, pState); //[push, array]
for (int i=0; i < (int)children.size(); ++i)
{
childCodegen(statement, i, pState); //[value, push, array]
copyInstruction(1, pState); //[push, value, push, array]
copyInstruction(3, pState); //[array, push, value, push, array]
instruction8(OC_WR_THISP, pState);
instruction8(OC_POP, pState); //[push, value, push, array]
callInstruction(1, pState, children[i]->position()); //[array, push, array]
instruction8(OC_POP, pState); //[push, array]
}
instruction8(OC_POP, pState); //[array]
}
/**
* Generates code for an object literal.
* @param statement
* @param pState
*/
void objectCodegen (Ref<AstNode> statement, CodegenState* pState)
{
Ref<AstObject> obj = statement.staticCast<AstObject>();
const AstObject::PropertyList properties= obj->getProperties();
callCodegen("Object", 0, pState, statement->position());