-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparse.cpp
1519 lines (1318 loc) · 44.8 KB
/
parse.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
#include "type.h"
#include "lex.h"
#include "parse.h"
#include "error.h"
#include "utils.h"
#include "IR.h"
bool isPreCheck = false;
TokenContext lastToken;
int curScopeIndex = ROOT;
string getOffset(const vector<string>& calledAxis, const vector<int> & offsets) {
if (calledAxis.empty()) return "0";
string offset;
IR::addArithmetic(offset, Add, "0", "0");
for (int i = 0; i < calledAxis.size(); ++i) {
string result;
IR::addArithmetic(result, Mul, calledAxis[i], to_string(offsets[i]));
string temp;
IR::addArithmetic(temp, Add, offset, result);
offset = temp;
}
return offset;
}
int getOffset(const vector<int>& calledAxis, const vector<int> & offsets) {
if (calledAxis.empty()) {
return 0;
}
int offset = 0;
for (int i = 0; i < calledAxis.size(); ++i) {
offset += calledAxis[i] * offsets[i];
}
offset += calledAxis.back();
return offset;
}
void addGlobalArrayPointerNames() {
for (auto & symbolItem:SymbolTable::allScopes.front().allSymbols) {
if (symbolItem.kind == Var && symbolItem.dimension > 0) {
string newPointerName = IR::generateRegister();
IR::addGetElePtr(newPointerName, "@" + symbolItem.name, symbolItem.axis);
symbolItem.pointerName = newPointerName;
}
}
}
void addLocalizedParam(int scopeIdx) {
for (auto & symbolItem:SymbolTable::allScopes.at(scopeIdx).allSymbols) {
if (symbolItem.kind == Param && symbolItem.dimension == 0) {
string newPointerName = IR::generateRegister();
vector<int> unused;
IR::addAlloca(newPointerName, unused);
IR::addStore(symbolItem.regName, newPointerName);
symbolItem.pointerName = newPointerName;
}
}
}
void tryReplaceConst(string &name, const vector<string>& calledAxis) {
if (isValue(name)) {
return;
}
symbolTableNode *item = SymbolTable::findVarSymbol(curScopeIndex, name);
if (item == nullptr) {
return;
}
if (item->kind == Const) {
if (calledAxis.size() == item->dimension) {
vector<int> intCalledAxis;
for (auto iter:calledAxis) {
if (!isValue(iter)) return;
intCalledAxis.emplace_back(stoi(iter));
}
name = to_string(item->constValues.at(getOffset(intCalledAxis, item->offsets)));
} else exit(-1);
}
}
vector<int> getOffsetsVector(vector<int> &axis);
// called only when the curToken is Ident
/**
* 往后看确定次数个不能决定分支,用预检查机制
* stmt -> assignStmt -> lVal '=' exp ';'
* stmt -> [exp] ';' -> lVal ';'
* 所以通过'='判断
* @return true if it should jump to assignStmt
*/
bool assignStmtPreCheck() {
TokenContext lastTmp = lastToken;
TokenContext curTmp = curTokenContext;
isPreCheck = true;
peekPos = 0;
bool isAssign = assignStmt();
isPreCheck = false;
lastToken = lastTmp;
curTokenContext = curTmp;
return isAssign;
}
/**
* 根据类型获取token,如果不匹配则报错
* @param type expected token type
* @return token context
*/
TokenContext getToken(int type) {
ErrorCheckUnit::checkTokenUnmatched(curTokenContext.tokenType, type);
TokenContext ret = curTokenContext;
lastToken = curTokenContext;
getNextToken();
return ret;
}
/**
* compUnit -> [compUnit] (Decl | FuncDef)
*/
void compUnit() {
// create the root scope: index=0, aka global
curScopeIndex = SymbolTable::addScope(ROOT, NormalScope);
addLibFun();
IR::addFuncDecl();
while (isDeclBranch()) {
decl();
}
while (isFuncDefBranch()) {
if (isDeclBranch()) {
decl();
} else {
funcDef();
}
}
// 因为不能调用声明在后面的函数,所以main函数后面的函数对程序结果没有影响,不用管了。yeah!
mainFuncDef();
curScopeIndex = SymbolTable::exitScope(curScopeIndex);
}
void constDecl() {
getToken(ConstToken);
IdentType type;
bType(type);
constDef(type);
while (curTokenContext.tokenType == Comma) {
getToken(Comma);
// didn't clean the shared constEntry, because all attrib will be reset.
constDef(type);
}
getToken(Semicolon);
}
void bType(IdentType &type) {
getToken(Int);
type = IntType;
}
/**
* ConstDef -> Ident { '[' ConstExp ']' } '=' ConstInitVal
* @param type
*/
void constDef(IdentType type) {
TokenContext ident = getToken(Ident);
vector<int> axis;
while (curTokenContext.tokenType == LBracket) {
getToken(LBracket);
string len = "0";
constExp(len);
axis.emplace_back(stoi(len));
getToken(RBracket);
}
getToken(Assign);
vector<vector<string>> initValues;
vector<string> ipb;
constInitVal(initValues, ipb, 0, (int)axis.size());
/*************************** new symbolTable *************************/
ErrorCheckUnit::checkDupDef(curScopeIndex, ident.token, false);
if (!axis.empty()) { // array
vector<int> offsets = getOffsetsVector(axis);
vector<int> constValues(offsets.front() * axis.front());
int idxConst;
for (int i = 0; i < initValues.size(); ++i) {
vector<string> cipb = initValues[i];
idxConst = i * axis.back();
for (int j = 0; j < cipb.size(); ++j) {
constValues[idxConst+j] = stoi(cipb[j]);
}
}
SymbolTable::addConstSymbol(curScopeIndex, ident.token, type, axis, constValues);
// 常量中除了全局常量,都不输出IR,只填表
symbolTableNode* sNode = SymbolTable::findVarSymbol(curScopeIndex, ident.token);
sNode->offsets = offsets;
if (curScopeIndex == 0) { // global array
IR::addGlobalArray(ident.token, true, axis, initValues);
}
} else {
vector<int> constValues(1);
constValues[0] = stoi(ipb.front());
SymbolTable::addConstSymbol(curScopeIndex, ident.token, type, axis, constValues);
}
}
vector<int> getOffsetsVector(vector<int> &axis) {
vector<int> offsets(axis.size());
if (axis.empty()) {
return offsets;
}
offsets.back() = 1;
for (int i = (int)axis.size()-1; i > 0; --i) {
offsets[i-1] = offsets[i] * axis[i];
}
return offsets;
}
void varDecl() {
IdentType type;
bType(type);
varDef(type);
while (curTokenContext.tokenType == Comma) {
getToken(Comma);
varDef(type);
}
getToken(Semicolon);
}
/**
* varDef -> ident { '[' constExp ']' }
| ident { '[' constExp ']' } '=' initVal
* 全局变/常量声明中指定的初值表达式必须是常量表达式;
局部变量可以和全局变量同名,在局部变量作用域内,局部变量隐藏了同名全局变量的定义;
未显式初始化的局部变量,其值是不确定的;而未显式初始化的全局变量,其值均被初始化为 0
全局 int 类型变量/常量的初值必须是编译时可求值的常量表达式。
局部 int 类型常量的初值必须是编译时可求值的表达式。(和 C 语言略有不同)
* @param type must be int
*/
void varDef(IdentType type) {
TokenContext ident = getToken(Ident);
vector<int> axis;
while (curTokenContext.tokenType == LBracket) {
getToken(LBracket);
string value;
constExp(value);
axis.emplace_back(stoi(value));
getToken(RBracket);
}
ErrorCheckUnit::checkDupDef(curScopeIndex, ident.token, false);
if (curScopeIndex > 0) { // local
string pointerName = IR::generateRegister();
IR::addAlloca(pointerName, axis);
SymbolTable::addVarSymbol(curScopeIndex, ident.token, pointerName, type, axis);
if (curTokenContext.tokenType == Assign) {
getToken(Assign);
vector<vector<string>> initValues;
vector<string> ipb;
initVal(initValues, ipb, 0, axis.size());
// assign with the init values, and iniValues.size() is the count of the var
if (initValues.empty() && !ipb.empty()) {
// prevent int a[4][2] = {};
IR::addStore(ipb[0], pointerName);
} else {
// array init
vector<int> offsets = getOffsetsVector(axis);
int bytes = offsets.front() * axis.front() * 4;
// 拿数组的i32*的指针
string pointer = IR::generateRegister();
IR::addGetElePtr(pointer, pointerName, axis);
// 更新pointerName为i32*型的,添加offsets
symbolTableNode* sNode = SymbolTable::findVarSymbol(curScopeIndex, ident.token);
sNode->pointerName = pointer;
sNode->offsets = offsets;
// 初始化第一步: memset
IR::addMemset(pointer, 0, bytes);
// 第二步:根据初始值补全
int baseOffset = 0;
if (offsets.size() >= 2) baseOffset = offsets[offsets.size()-2];
for (int i = 0; i < initValues.size(); ++i) {
vector<string> vs = initValues[i];
for (int j = 0; j < vs.size(); ++j) {
string curPointer = IR::generateRegister();
int curOffset = baseOffset * i + j;
vector<int> temp;
IR::addGetElePtr(curPointer, pointer, temp, to_string(curOffset));
IR::addStore(vs[j], curPointer);
}
}
}
} else {
if (!axis.empty()) {
vector<int> offsets = getOffsetsVector(axis);
// 拿数组的i32*的指针
string pointer = IR::generateRegister();
IR::addGetElePtr(pointer, pointerName, axis);
// 更新pointerName为i32*型的,添加offsets
symbolTableNode* sNode = SymbolTable::findVarSymbol(curScopeIndex, ident.token);
sNode->pointerName = pointer;
sNode->offsets = offsets;
}
}
} else { // Global
string pointerName;
SymbolTable::addVarSymbol(curScopeIndex, ident.token, pointerName, type, axis);
symbolTableNode* sNode = SymbolTable::findVarSymbol(curScopeIndex, ident.token);
if (curTokenContext.tokenType == Assign) {
getToken(Assign);
vector<vector<string>> initValues;
vector<string> ipb;
initVal(initValues, ipb, 0, axis.size());
// assign with the init values, and iniValues.size() is the count of the var
if (axis.empty()) { // global normal var
if (ipb.size() == 1) { // normalVar init
if (!isValue(ipb[0])) {
exit(-1);
}
IR::addGlobal(sNode->name, ipb[0]);
} else if (initValues.empty()) { // global normal var no-assign
IR::addGlobal(sNode->name, "0");
}
sNode->pointerName = "@" + sNode->name;
}
else { // dimension > 0 global array
// TODO: global array declare (with assign)
vector<int> offsets = getOffsetsVector(axis);
// 更新pointerName为i32*型的,添加offsets
sNode->offsets = offsets;
IR::addGlobalArray(ident.token, false, axis, initValues);
}
} else { // global no-assign
if (axis.empty()) { // normal var
IR::addGlobal(ident.token, "0");
sNode->pointerName = "@" + sNode->name;
} else { // global no-assign array
vector<vector<string>> initValues;
sNode->offsets = getOffsetsVector(axis);
IR::addGlobalArray(ident.token, false, axis, initValues);
}
}
}
}
/**
* funcDef -> funcType ident '(' [funcFParams] ')' block
*/
void funcDef() {
IdentType type;
funcType(type);
TokenContext ident = getToken(Ident);
vector<symbolTableNode> funcFPsListLinkVersion;
IR::resetIndex();
getToken(LParen);
if (isFuncFPsAtFuncDef())
funcFParams(funcFPsListLinkVersion);
getToken(RParen);
IR::addFuncDef(type, ident.token, funcFPsListLinkVersion);
//------------------- new symbolTable --------------------
vector<pair<IdentType, int>> paramsTypeDimList;
vector<string> FParamsNames;
for (const auto& iter:funcFPsListLinkVersion) {
paramsTypeDimList.emplace_back(make_pair(iter.type, iter.dimension));
FParamsNames.emplace_back(iter.regName);
}
ErrorCheckUnit::checkDupDef(curScopeIndex, ident.token, true);
SymbolTable::addFuncSymbol(curScopeIndex, ident.token, type, paramsTypeDimList, FParamsNames);
IR::addLBrace();
addGlobalArrayPointerNames();
block(funcFPsListLinkVersion, FuncScope, (type == VoidType), ident.token);
IR::addRBrace();
}
void mainFuncDef() {
getToken(Int);
TokenContext ident = getToken(Main);
getToken(LParen);
getToken(RParen);
vector<symbolTableNode> temp;
IR::addFuncDef(IntType, "main", temp);
/********************* new SymbolTable ************************/
vector<pair<IdentType, int>> emptyDimType;
vector<string> emptyNames;
ErrorCheckUnit::checkDupDef(curScopeIndex, ident.token, true);
SymbolTable::addFuncSymbol(curScopeIndex, ident.token, IntType, emptyDimType, emptyNames);
IR::resetIndex();
IR::addLBrace();
addGlobalArrayPointerNames();
block(vector<symbolTableNode>(), FuncScope, false, "main");
IR::addRBrace();
}
/**
* funcType -> 'void' | 'int'
* @param type
*/
void funcType(IdentType &type) {
if (curTokenContext.tokenType == Void) {
getToken(Void);
type = VoidType;
} else {
getToken(Int);
type = IntType;
}
}
/**
* funcFParams -> funcFParam { ',' funcFParam }
* @param FPsLinkVersion 当前作用域符号表
*/
void funcFParams(vector<symbolTableNode> &FPsLinkVersion) {
funcFParam(FPsLinkVersion);
while (curTokenContext.tokenType == Comma) {
getToken(Comma);
funcFParam(FPsLinkVersion);
}
}
/**
* funcFParam -> bType ident ['[' ']' { '[' exp ']' }]
* @param FPsLinkVersion 当前作用域符号表
*/
void funcFParam(vector<symbolTableNode> &FPsLinkVersion) {
IdentType varType;
bType(varType);
TokenContext ident = getToken(Ident);
vector<int> axis;
// array as param
if (curTokenContext.tokenType == LBracket) {
// e.g. int a[][3], 第一维为空,不考虑
getToken(LBracket);
getToken(RBracket);
axis.emplace_back(1);
while (curTokenContext.tokenType == LBracket) {
getToken(LBracket);
string value;
constExp(value);
axis.emplace_back(stoi(value));
getToken(RBracket);
}
}
string regName = IR::generateRegister();
symbolTableNode param = SymbolTable::createParamItem(ident.token, regName, varType, axis);
if (!axis.empty()) {
vector<int> offsets = getOffsetsVector(axis);
param.offsets = offsets;
}
FPsLinkVersion.emplace_back(param);
}
/**
* block -> '{' { BlockItem } '}'
* @param funcFPsLinkVersion
* @param kind in FuncScope, NormalScope, LoopScope
* @param isVoidFunc true if void, false if int
* @param funcName plain funcname
*/
void block(vector<symbolTableNode> funcFPsLinkVersion, ScopeKind kind, bool isVoidFunc,
string funcName) {
// lastToken must be ')'
getToken(LBrace);
curScopeIndex = SymbolTable::addScope(curScopeIndex, kind, isVoidFunc, std::move(funcName));
// add FParams
for (auto& iter:funcFPsLinkVersion) {
ErrorCheckUnit::checkDupDef(curScopeIndex, iter.name, false);
SymbolTable::addParamSymbol(curScopeIndex, iter);
}
addLocalizedParam(curScopeIndex);
while (curTokenContext.tokenType != RBrace) {
blockItem();
}
getToken(RBrace);
ErrorCheckUnit::checkNoReturn(curScopeIndex);
Scope* scope = SymbolTable::findScope(curScopeIndex);
if (scope->scopeKind == FuncScope && scope->isVoidFunc && !scope->hasReturned) {
IR::addRet();
} else if (scope->scopeKind == NormalScope) {
if (scope->hasReturned) {
SymbolTable::findScope(scope->parentScopeIndex)->hasReturned = true;
}
}
curScopeIndex = SymbolTable::exitScope(curScopeIndex);
}
/**
* exp -> addExp
* @param result
* @return
*/
pair<IdentType, int> exp(string &result) {
bool isI1;
pair<IdentType, int> ret = addExp(result, isI1);
return ret;
}
/**
* cond -> lOrExp
* @param trueLabel
* @param falseLabel
*/
void cond(string &trueLabel, string &falseLabel) {
lOrExp(trueLabel, falseLabel);
}
bool preCheckUndef(int curScope, string &name, bool isFunc) {
symbolTableNode *item;
if (isFunc) {
item = SymbolTable::findFuncSymbol(name);
} else {
item = SymbolTable::findVarSymbol(curScope, name);
}
if (item == nullptr) return true;
return false;
}
/**
* lVal -> ident {'[' exp ']'}
* @param result
* @param dimIdx
* @param isAssigned
* @return
*/
pair<IdentType, int> lVal(string &result, vector<string> &dimIdx, bool isAssigned) {
// init value, only useful when varEntry == nullptr
pair<IdentType, int> ret(IntType, 0);
TokenContext ident = getToken(Ident);
string lvalName = ident.token;
// 防止预检查时乱走
if(preCheckUndef(curScopeIndex, lvalName, false)) {
// cout << "lvalName: " + lvalName << endl;
return ret;
}
if (isAssigned) {
ErrorCheckUnit::checkConstAssign(curScopeIndex, lvalName);
}
symbolTableNode *item = SymbolTable::findVarSymbol(curScopeIndex, lvalName);
ret.first = item->type;
ret.second = item->dimension;
// must execute even if error already happened, because we need checkAndGet to push forward.
vector<string> dimIndex;
// string dimIndex[MAX_AXIS_NUM];
while (curTokenContext.tokenType == LBracket) {
getToken(LBracket);
// TODO: 如果数组exp出现a == b, !a就麻烦了
string tempResult;
exp(tempResult);
dimIndex.emplace_back(tempResult);
getToken(RBracket);
ret.second--;
}
if (isPreCheck) {
return ret;
}
string name = ident.token;
symbolTableNode *identSym = SymbolTable::findVarSymbol(curScopeIndex, name);
if (!isAssigned) { // rvalue, get the value
tryReplaceConst(name, dimIndex);
symbolTableNode *identSym = SymbolTable::findVarSymbol(curScopeIndex, name);
if (isValue(name)) {
result = name;
return ret;
}
if (identSym->dimension == 0) {
// if (identSym->regName.empty()) {
// string temp = IR::generateRegister();
// identSym->regName = temp;
// IR::addLoad(temp, identSym->pointerName);
// }
// result = identSym->regName;
// 还是不做这种优化了,容易出现Instruction does not dominate all uses!的错误
if (identSym->kind == Param && identSym->pointerName.empty()) {
string pointer = IR::generateRegister();
vector<int> unused;
IR::addAlloca(pointer, unused);
IR::addStore(identSym->regName, pointer);
identSym->pointerName = pointer;
}
string temp = IR::generateRegister();
IR::addLoad(temp, identSym->pointerName);
result = temp;
return ret;
} else {
// array
if (identSym->pointerName.empty()) {
string newPointer = IR::generateRegister();
IR::addGetElePtr(newPointer, "@" + identSym->name, identSym->axis);
identSym->pointerName = newPointer;
}
/***********************到这里说明 tryReplaceConst 没有成功 用str版的getOffset ****************************/
string offset = getOffset(dimIndex, identSym->offsets);
string newPointer = IR::generateRegister();
vector<int> temp;
IR::addGetElePtr(newPointer, identSym->pointerName, temp, offset);
if (identSym->dimension > dimIndex.size()) {
result = newPointer;
} else if (identSym->dimension == dimIndex.size()){
result = IR::generateRegister();
IR::addLoad(result, newPointer);
} else {
exit(-1);
}
}
} else {
// assigned, as left value
// normalVar, result is its name
if (identSym->dimension == 0) {
result = name;
return ret;
} else {
// lval is array and is going to be assigned,
// so do nothing here, but return the dim info to assignStmt
// to generate OP_STORE_ARRAY
/****************************维数不匹配*****************************/
// TODO: 不确定能不能对指针赋值,过点看看先
if (identSym->dimension != dimIndex.size()) exit(-1);
/*****************************************************************/
result = name;
dimIdx = dimIndex;
return ret;
}
}
return ret;
}
pair<IdentType, int> number(string &result) {
TokenContext intcon = getToken(IntConst);
pair<IdentType, int> ret(IntType, 0);
result = intcon.token;
return ret;
}
TokenType unaryOp() {
TokenType ret;
if (curTokenContext.tokenType == Add) {
getToken(Add);
ret = Add;
} else if (curTokenContext.tokenType == Minus) {
getToken(Minus);
ret = Minus;
} else {
getToken(Not);
ret = Not;
}
return ret;
}
void funcRParams(vector<pair<IdentType, int>> &argumentsType, vector<string> &arguments) {
// shared argument for all the RParams
pair<IdentType, int> argument;
string result;
argument = exp(result);
// when return, the argument is always considered as well-set.
argumentsType.emplace_back(argument);
arguments.emplace_back(result);
while (curTokenContext.tokenType == Comma) {
getToken(Comma);
string tempResult;
argument = exp(tempResult);
argumentsType.emplace_back(argument);
arguments.emplace_back(tempResult);
}
}
/**
* mulExp -> unaryExp
| mulExp ('*' | '/' | '%') unaryExp
* @param result
* @return
*/
pair<IdentType, int> mulExp(string &result, bool& isI1) {
string tempResult1;
bool tempRes1IsI1 = false;
pair<IdentType, int> ret = unaryExp(tempResult1, tempRes1IsI1);
result = tempResult1;
TokenType op = static_cast<TokenType>(curTokenContext.tokenType);
while (op == Mul || op == Div || op == Mod) {
getNextToken();
string tempResult2;
bool tempRes2IsI1 = false;
unaryExp(tempResult2, tempRes2IsI1);
vector<string> t;
tryReplaceConst(tempResult1, t);
tryReplaceConst(tempResult2, t);
if (isValue(tempResult1) && isValue(tempResult2)) {
switch (op) {
case Mul:
tempResult1 = to_string(stoi(tempResult1) * stoi(tempResult2));
break;
case Div:
tempResult1 = to_string(stoi(tempResult1) / stoi(tempResult2));
break;
case Mod:
tempResult1 = to_string(stoi(tempResult1) % stoi(tempResult2));
break;
}
result = tempResult1;
tempRes1IsI1 = false;
} else {
string temp;
IR::addArithmetic(temp, op, tempResult1, tempResult2, tempRes1IsI1, tempRes2IsI1);
SymbolTable::addTempSymbol(curScopeIndex, temp, IntType);
tempResult1 = temp;
tempRes1IsI1 = false;
}
op = static_cast<TokenType>(curTokenContext.tokenType);
}
result = tempResult1;
isI1 = tempRes1IsI1;
return ret;
}
/**
* addExp -> mulExp
| addExp ('+' | '−') mulExp
* @param result
* @return
*/
pair<IdentType, int> addExp(string &result, bool& isI1) {
string tempResult1;
bool tempRes1IsI1 = false;
pair<IdentType, int> ret = mulExp(tempResult1, tempRes1IsI1);
TokenType op = static_cast<TokenType>(curTokenContext.tokenType);
while (op == Add || op == Minus) {
getNextToken();
string tempResult2;
bool tempRes2IsI1 = false;
mulExp(tempResult2, tempRes2IsI1);
// const replace
vector<string> t;
tryReplaceConst(tempResult1, t);
tryReplaceConst(tempResult2, t);
// const calculate
if (isValue(tempResult1) && isValue(tempResult2)) {
switch (op) {
case Add:
tempResult1 = to_string(stoi(tempResult1) + stoi(tempResult2));
break;
case Minus:
tempResult1 = to_string(stoi(tempResult1) - stoi(tempResult2));
break;
}
result = tempResult1;
tempRes1IsI1 = false;
} else {
string temp;
IR::addArithmetic(temp, op, tempResult1, tempResult2, tempRes1IsI1, tempRes2IsI1);
result = tempResult1 = temp;
tempRes1IsI1 = false;
}
op = static_cast<TokenType>(curTokenContext.tokenType);
}
result = tempResult1;
isI1 = tempRes1IsI1;
return ret;
}
/**
* RelExp -> AddExp
| RelExp ('<' | '>' | '<=' | '>=') AddExp
* @param result Make sure its type is i32
*/
void relExp(string &result, bool& isI1) {
string tempResult1;
bool tempResIsI1 = false;
addExp(tempResult1, tempResIsI1);
auto op = static_cast<TokenType>(curTokenContext.tokenType);
while (op == Lt || op == Leq || op == Gt || op == Geq) {
getNextToken();
string tempResult2;
bool tempResIsI2 = false;
addExp(tempResult2, tempResIsI2);
// 处理 a > b > c的情况
// if (t1IsBool){
// string temp = IR::generateRegister();
// IR::addZextTo(temp, tempResult1);
// tempResult1 = temp;
// t1IsBool = false;
// }
if (isValue(tempResult1) && isValue(tempResult2)) {
switch (op) {
case Lt:
tempResult1 = to_string(stoi(tempResult1) < stoi(tempResult2));
break;
case Leq:
tempResult1 = to_string(stoi(tempResult1) <= stoi(tempResult2));
break;
case Gt:
tempResult1 = to_string(stoi(tempResult1) > stoi(tempResult2));
break;
case Geq:
tempResult1 = to_string(stoi(tempResult1) >= stoi(tempResult2));
break;
}
} else {
string temp;
IR::addIcmp(temp, op, tempResult1, tempResult2, tempResIsI1, tempResIsI2);
SymbolTable::addTempSymbol(curScopeIndex, temp, IntType);
tempResult1 = temp;
tempResIsI1 = true;
}
op = static_cast<TokenType>(curTokenContext.tokenType);
}
result = tempResult1;
isI1 = tempResIsI1;
}
/**
* eqExp -> relExp
| eqExp ('==' | '!=') relExp
* ------------kill left recursion-------------
* eqExp -> relExp {('==' | '!=') relExp}*
* @param cond make sure its type is i1
*/
void eqExp(string &cond) {
string tempResult1;
bool tempRes1IsI1 = false;
relExp(tempResult1, tempRes1IsI1);
auto op = static_cast<TokenType>(curTokenContext.tokenType);
while (op == Eq || op == Neq) {
getNextToken();
string tempResult2;
bool tempRes2IsI1 = false;
relExp(tempResult2, tempRes2IsI1);
switch (op) {
case Eq:
if (isValue(tempResult1) && isValue(tempResult2)) {
// 数字之间比较就直接比了
tempResult1 = to_string(stoi(tempResult1) == stoi(tempResult2));
} else {
// 不全为数字才需要生成代码
string temp;
IR::addIcmp(temp, op, tempResult1, tempResult2, tempRes1IsI1, tempRes2IsI1);
tempResult1 = temp;
tempRes1IsI1 = true;
}
break;
case Neq:
if (isValue(tempResult1) && isValue(tempResult2)) {
tempResult1 = to_string(stoi(tempResult1) != stoi(tempResult2));
} else {
// tempResult1 = addIR(OP_NEQ, tempResult1, tempResult2, AUTO_TMP);
string temp;
IR::addIcmp(temp, op, tempResult1, tempResult2, tempRes1IsI1, tempRes2IsI1);
tempResult1 = temp;
tempRes1IsI1 = true;
}
break;
}
op = static_cast<TokenType>(curTokenContext.tokenType);
}
if (!tempRes1IsI1) {
string temp;
IR::addIcmp(temp, Neq, tempResult1, "0", tempRes1IsI1, false);
tempResult1 = temp;
}
cond = tempResult1;
}
/**
* lAndExp -> eqExp
| lAndExp '&&' eqExp
* ------------kill left recursion-------------
* lAndExp -> eqExp {(&&) eqExp}*
* @param trueLabel Synthesis Attribute
* @param falseLabel Synthesis Attribute
*/
void lAndExp(string &trueLabel, string &falseLabel) {
// always continue the following code if true without jumping, only jump to falseLabel when false.
string newTrueLabel;
string cond;
eqExp(cond);
bool flag = false;
while (curTokenContext.tokenType == And) {
if (!flag) {
flag = true;
}
getToken(And);
newTrueLabel = IR::generateRegister();
IR::addBr(cond, newTrueLabel, falseLabel);
IR::addLabel(newTrueLabel);
eqExp(cond);
}
// once execute to here, means all the eqExp is true, then jump to trueLabel as overall result of this lAndExp.
IR::addBr(cond, trueLabel, falseLabel);
}
/**
* lOrExp -> lAndExp
| lOrExp '||' lAndExp
* ------------kill left recursion-------------
* lOrExp -> lAndExp {('||') lAndExp}*
* @param trueLabel Synthesis Attribute
* @param falseLabel Synthesis Attribute
*/
void lOrExp(string &trueLabel, string &falseLabel) {
string lAndFalseLabel = IR::generateRegister();
lAndExp(trueLabel, lAndFalseLabel);
while (curTokenContext.tokenType == Or) {
getToken(Or);
IR::addLabel(lAndFalseLabel);
lAndFalseLabel = IR::generateRegister();
lAndExp(trueLabel, lAndFalseLabel);
}
// if still didn't jump to the true labell, means every lAndExp is false, then the whole lOr is false, goto false location.
IR::addLabel(lAndFalseLabel);
IR::addBr(falseLabel);
}
/**
* constExp -> addExp
* 在语义上额外约束这里的 addExp 必须是一个可以在编译期求出值的常量
* @param result Synthesis Attribute
*/
void constExp(string &result) {
bool unused = false;
addExp(result, unused);