-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfuture.cpp
More file actions
1585 lines (1504 loc) · 74.5 KB
/
future.cpp
File metadata and controls
1585 lines (1504 loc) · 74.5 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 <iostream>
#include <unordered_map>
#include <string>
#include <sstream>
#include <queue>
#include <deque>
#include <stack>
#include <cstdint>
#include <vector>
#include <regex>
namespace CPlus {
constexpr int strippedLineLength = 3;
const std::string strippedLines[] = {"#include<iostream>", "#include<cstdio>", "using namespace std;"};
enum SymbolOperatorEnum {
LeftParen = 1,
RightParen,
LeftSquareBracket,
RightSquareBracket,
Not,
Positive,
Negative,
Multiply,
Divide,
Modulo,
Plus,
Minus,
LessEqual,
GreaterEqual,
LessThan,
GreaterThan,
Equal,
NotEqual,
Xor,
LogicalAnd,
LogicalOr,
Assign,
Comma,
CoutFrom,
CinTo,
LeftBracket,
RightBracket,
Semicolon,
PlusOrPositive, // 加法和正号的二义性
MinusOrNegative, // 减法和负号的二义性
ArrayMemoryDereference,
};
std::unordered_map<std::string, SymbolOperatorEnum> SymbolOperators = {
{"(", LeftParen}, {")", RightParen}, {"[", LeftSquareBracket}, {"]", RightSquareBracket},
{"!", Not}, /* {"+", Positive}, {"-", Negative}, */
{"*", Multiply}, {"/", Divide}, {"%", Modulo},
/* {"+", Plus}, {"-", Minus}, */
{"<=", LessEqual}, {">=", GreaterEqual}, {"<", LessThan}, {">", GreaterThan},
{"==", Equal}, {"!=", NotEqual},
{"^", Xor},
{"&&", LogicalAnd},
{"||", LogicalOr},
{"=", Assign},
{",", Comma},
{"<<", CoutFrom}, {">>", CinTo},
{"{", LeftBracket}, {"}", RightBracket}, {";", Semicolon},
{"+", PlusOrPositive}, {"-", MinusOrNegative}
};
std::unordered_map<SymbolOperatorEnum, uint8_t> OperatorPrecedence = {
{Not, 1}, {Positive, 1}, {Negative, 1},
{Multiply, 2}, {Divide, 2}, {Modulo, 2},
{Plus, 3}, {Minus, 3},
{LessEqual, 4}, {GreaterEqual, 4}, {LessThan, 4}, {GreaterThan, 4},
{Equal, 5}, {NotEqual, 5},
{Xor, 6},
{LogicalAnd, 7},
{LogicalOr, 8},
{CoutFrom, 9}, {CinTo, 9},
{Assign, 10}
};
enum SymbolEnum {
FunctionCallDefBegin = 1,
FunctionCallDefEnd,
ControlBlockBegin,
ControlBlockEnd,
ArrayAccessDefBegin,
ArrayAccessDefEnd,
BlockBegin,
BlockEnd,
FunctionBodyBegin,
FunctionBodyEnd,
CommaSeparator,
StatementSeparator,
ConditionSeparator
};
enum KeywordEnum {
_KeywordNil = 0,
Int = 1,
If,
Else,
For,
While,
Return,
};
std::unordered_map<std::string, KeywordEnum> Keywords = {
{"int", Int}, {"if", If}, {"else", Else}, {"for", For}, {"while", While}, {"return", Return}};
enum LexemeType {
_LexemeTypeNil = 0,
IntConstant = 1,
Keyword,
Identifier,
SymbolOperator,
Symbol,
Operator
};
enum PredefinedIdentifierEnum {
Main = 1,
Cin,
Cout,
Endl,
Putchar,
_PredefinedIdentifierUpperBound
};
const std::string predefinedIdentifiers[_PredefinedIdentifierUpperBound] = {"",
"main", "cin", "cout", "endl", "putchar"
};
enum IdentifierType {
_IdentifierTypeNil,
Integer = 1,
Function,
IntegerArray,
BuiltInObjects
};
enum AbstractSyntaxTreeNodeType {
BaseASTNode,
IdentifierASTNode,
IntConstantASTNode,
BinaryExpressionASTNode,
FunctionCallASTNode,
BlockASTNode,
IfStatementASTNode,
WhileStatementASTNode,
ForStatementASTNode,
ReturnStatementASTNode
};
constexpr int GlobalObjectsNilBaseOffset = 0;
constexpr int GlobalVariablesInitialBaseOffset = 1;
constexpr int NullPointer = 0;
class CompileError : public std::runtime_error {
public:
CompileError(std::string&& message) : std::runtime_error(message) {}
};
class RuntimeError : public std::runtime_error {
public:
RuntimeError(std::string&& message) : std::runtime_error(message) {}
};
}
namespace Utilities {
bool isdigits(std::string const &str) {
for (char i : str) {
if (!isdigit(i)) return false;
}
return true;
}
int strToUInt(std::string const& str) {
int ret = 0;
for (char i : str) {
if (!isdigit(i)) return -1;
ret = ret * 10 + i - '0';
}
return ret;
}
}
class LexicalAnalyzer {
private:
class Tokenizer {
private:
int ptr;
std::string source;
// 对于本题所简化的 C++,所有多于一个字符的 symbol/operator,除了 '||' 和 '&&' 的首字符均为一个合法的 symbol/operator
// 因此此方法十分实用
bool isPartOfSymbolOperator(std::string ch) {
return CPlus::SymbolOperators.count(ch) || ch == "|" || ch == "&";
}
public:
Tokenizer(std::string source) : ptr(0), source(source) {}
bool hasNextToken() {
return this->ptr < this->source.length();
}
std::string nextToken() {
// 过滤空白字符
while (this->ptr < source.length()) {
if (!isspace(this->source[this->ptr]))
break;
ptr++;
}
int s = this->ptr;
// 判断是否为 symbol 或 operator 开始
std::string ch = this->source.substr(this->ptr, 1);
bool startWithSymbolOperator = isPartOfSymbolOperator(this->source.substr(this->ptr, 1));
for (; this->ptr < source.length(); ptr++) {
if (s == this->ptr)
continue;
// 检测到空白字符,结束
if (isspace(this->source[this->ptr])) {
break;
}
// 如果以 symbol/operator 开始,且字符串加入下一个字符后无法构成 symbol/operator,结束
if (startWithSymbolOperator) {
if (this->ptr + 1 < source.length()) {
if (!(CPlus::SymbolOperators.count(this->source.substr(s, this->ptr + 1 - s))))
break;
}
else {
break;
}
}
// 如果不以 symbol/operator 开始,且当前字符为 symbol/operator 的部分,则结束
if (!startWithSymbolOperator && isPartOfSymbolOperator(this->source.substr(this->ptr, 1))) {
break;
}
}
return this->source.substr(s, this->ptr - s);
}
};
public:
struct Lexeme {
CPlus::LexemeType type;
int value;
};
private:
std::shared_ptr<Tokenizer> tokenizer;
bool analyzed;
std::vector<Lexeme> lexemes;
std::unordered_map<std::string, int> identifierMap;
int identifierCounter;
int ptr;
// 初步解析 token,进行简单的 token 分类,形成最初的词素
void parseTokens() {
for (std::string token; tokenizer->hasNextToken();) {
token = tokenizer->nextToken();
if (token.empty()) break;
Lexeme lexeme = {CPlus::LexemeType::_LexemeTypeNil, 0};
if (CPlus::SymbolOperators.count(token)) {
lexeme.type = CPlus::LexemeType::SymbolOperator;
lexeme.value = CPlus::SymbolOperators[token];
} else if (CPlus::Keywords.count(token)) {
lexeme.type = CPlus::LexemeType::Keyword;
lexeme.value = CPlus::Keywords[token];
} else if (Utilities::isdigits(token)) {
lexeme.type = CPlus::LexemeType::IntConstant;
lexeme.value = Utilities::strToUInt(token);
} else {
lexeme.type = CPlus::LexemeType::Identifier;
if (!this->identifierMap.count(token)) {
lexeme.value = this->identifierCounter++;
this->identifierMap[token] = lexeme.value;
} else
lexeme.value = this->identifierMap[token];
}
lexemes.push_back(lexeme);
}
}
// 二次解析词素,消除词素的二义性
void resolveLexemeTypes() {
std::stringstream err;
// 使用栈记录小括号和花括号,从而判断其含义
std::stack<Lexeme> parenStack, bracketStack;
// 记录上一次的控制字符,这会影响"()"的含义
auto lastControlKeyword = CPlus::_KeywordNil;
// 判断是否在 int 定义内,这会影响"()"和"[]"的含义
bool insideIntDefinition = false;
for (size_t i = 0; i < lexemes.size(); i++) {
Lexeme& lexeme = this->lexemes[i];
switch (lexeme.type) {
case CPlus::LexemeType::Keyword: {
switch (lexeme.value) {
// 若为 if、for、while 关键字,记录控制字符
case CPlus::If:
case CPlus::For:
case CPlus::While:
lastControlKeyword = (CPlus::KeywordEnum)lexeme.value;
break;
// 若为 int 关键字,设定 int 定义
case CPlus::Int:
insideIntDefinition = true;
break;
default:
break;
}
} break;
case CPlus::LexemeType::SymbolOperator: {
switch (lexeme.value) {
// 消除"+"、"-"二义性
case CPlus::PlusOrPositive:
case CPlus::MinusOrNegative:
// "+"、"-" 不可能在开头出现
if (!i) {
err << "Found + or - at position 0";
throw CPlus::CompileError(err.str());
}
lexeme.type = CPlus::Operator;
// 如果左侧的词素是 symbol/operator,且不是")"、"]",则必为正负含义,否则为加减
if ((lexemes[i - 1].type == CPlus::Operator && lexemes[i - 1].value != CPlus::RightParen) ||
(lexemes[i - 1].type == CPlus::Symbol && lexemes[i - 1].value != CPlus::FunctionCallDefEnd && lexemes[i - 1].value != CPlus::ArrayAccessDefEnd)) {
lexeme.value = lexeme.value == CPlus::PlusOrPositive ? CPlus::Positive : CPlus::Negative;
} else {
lexeme.value = lexeme.value == CPlus::PlusOrPositive ? CPlus::Plus : CPlus::Minus;
}
break;
case CPlus::LeftParen:
if (!i) {
err << "Found ( at position 0";
throw CPlus::CompileError(err.str());
}
// 如果左侧相邻词素是标识符,则必为函数调用或声明
if (lexemes[i - 1].type == CPlus::Identifier)
lexeme.type = CPlus::Symbol, lexeme.value = CPlus::FunctionCallDefBegin;
// 如果左侧相邻词素是关键字,且不是 return,则必为控制块起始
else if (lexemes[i - 1].type == CPlus::Keyword && lexemes[i - 1].value != CPlus::Return)
lexeme.type = CPlus::Symbol, lexeme.value = CPlus::ControlBlockBegin;
// 否则作为普通括号运算符处理
else
lexeme.type = CPlus::Operator;
// 左括号入栈,用于判断对应右括号类型
parenStack.push(lexeme);
break;
case CPlus::RightParen: {
// 若栈为空则括号不匹配,不合法
if (parenStack.empty()) {
err << "Unmatching paren at lexeme " << i << ".";
throw CPlus::CompileError(err.str());
}
Lexeme& correspondent = parenStack.top();
// 取栈顶对应的左括号判断
if (correspondent.type == CPlus::Symbol) {
lexeme.type = CPlus::Symbol;
if (correspondent.value == CPlus::FunctionCallDefBegin)
lexeme.value = CPlus::FunctionCallDefEnd;
else if (correspondent.value == CPlus::ControlBlockBegin) {
lexeme.value = CPlus::ControlBlockEnd;
// 若为控制块结束
lastControlKeyword = CPlus::_KeywordNil;
}
} else
lexeme.type = CPlus::Operator, lexeme.value = CPlus::RightParen;
parenStack.pop();
} break;
case CPlus::LeftBracket: {
lexeme.type = CPlus::Symbol,
// 同理如果在 int 定义内部,{ 表示函数体开始,否则是语句块开始
lexeme.value = insideIntDefinition ? CPlus::FunctionBodyBegin : CPlus::BlockBegin;
// 若进入函数体,则不属于 int 定义内部,将其置为 false。
insideIntDefinition = false;
// 左花括号入栈
bracketStack.push(lexeme);
} break;
case CPlus::RightBracket: {
if (bracketStack.empty()) {
err << "Unmatching bracket at lexeme " << i << ".";
throw CPlus::CompileError(err.str());
}
Lexeme& correspondent = bracketStack.top();
lexeme.type = CPlus::Symbol;
// 同理,根据左花括号判断
lexeme.value = correspondent.value == CPlus::FunctionBodyBegin ? CPlus::FunctionBodyEnd : CPlus::BlockEnd;
bracketStack.pop();
} break;
case CPlus::LeftSquareBracket:
lexeme.type = CPlus::Symbol, lexeme.value = CPlus::ArrayAccessDefBegin;
break;
case CPlus::RightSquareBracket:
lexeme.type = CPlus::Symbol, lexeme.value = CPlus::ArrayAccessDefEnd;
break;
case CPlus::Comma:
lexeme.type = CPlus::Symbol, lexeme.value = CPlus::CommaSeparator;
break;
case CPlus::Semicolon:
lexeme.type = CPlus::Symbol;
// 若当前不存在控制关键字,则 ; 表示语句分隔符,否则为控制块中的条件分隔符
lexeme.value = lastControlKeyword == CPlus::_KeywordNil ? CPlus::StatementSeparator : CPlus::ConditionSeparator;
// 同时结束 int 定义
insideIntDefinition = false;
break;
default:
lexeme.type = CPlus::Operator;
break;
}
} break;
default:
break;
}
}
}
public:
LexicalAnalyzer(std::string source) {
// 去除头文件等内容
for (size_t i = 0; i < CPlus::strippedLineLength; i++) {
const std::string& line = CPlus::strippedLines[i];
size_t pos = source.find(line);
if (pos != std::string::npos)
source = source.substr(0, pos) + source.substr(pos + line.length());
}
this->tokenizer = std::make_shared<Tokenizer>(source);
this->analyzed = false;
this->identifierCounter = CPlus::_PredefinedIdentifierUpperBound;
this->ptr = 0;
/* 初始化预定义的标识符 */
for (size_t i = 1; i < CPlus::_PredefinedIdentifierUpperBound; i++) {
identifierMap[CPlus::predefinedIdentifiers[i]] = i;
}
}
bool isAnalyzed() {
return this->analyzed;
}
void analyze() {
if (this->analyzed) return;
this->parseTokens();
this->resolveLexemeTypes();
this->tokenizer = nullptr; // cleanup
this->analyzed = true;
}
std::vector<Lexeme>& getLexemesRef() { return this->lexemes; }
std::unordered_map<std::string, int> getIdentifierMap() { return this->identifierMap; }
};
class SyntaxAnalyzer {
public:
class BaseASTNode {
public:
virtual ~BaseASTNode() = default;
virtual CPlus::AbstractSyntaxTreeNodeType getNodeType() { return CPlus::BaseASTNode; }
};
class IdentifierASTNode : public BaseASTNode {
private:
CPlus::IdentifierType type;
int id;
std::vector<uint32_t> dimensions;
std::vector<uint32_t> dimensionOffsets;
uint32_t size;
bool _static;
uint32_t baseOffset;
/**
* 计算多维数组偏移量
*/
static std::vector<uint32_t> calcDimensionOffsets(std::vector<uint32_t> dim) {
std::vector<uint32_t> offsets;
std::stack<uint32_t> s;
s.push(1);
for (std::vector<uint32_t>::reverse_iterator it = dim.rbegin(); !dim.empty() && it != dim.rend() - 1; it++)
s.push((*it) * s.top());
while (!s.empty()) {
offsets.push_back(s.top());
s.pop();
}
return offsets;
}
static uint32_t calcSize(std::vector<uint32_t> dimensions) {
uint32_t size = 1;
for (uint32_t dim : dimensions)
size *= dim;
return size;
}
public:
IdentifierASTNode() : type(CPlus::_IdentifierTypeNil), id(0), size(0), baseOffset(0), _static(true) {}
IdentifierASTNode(int id, uint32_t baseOffset, bool _static) : type(CPlus::Integer), id(id), baseOffset(baseOffset), size(1), _static(_static) {}
IdentifierASTNode(int id, std::vector<uint32_t> dimensions, uint32_t baseOffset, bool _static) :
type(CPlus::IntegerArray), id(id), dimensions(dimensions), dimensionOffsets(calcDimensionOffsets(dimensions)), size(calcSize(dimensions)), _static(_static) {}
IdentifierASTNode(CPlus::IdentifierType type, int id, uint32_t baseOffset, bool _static) : type(type), id(id), size(type == CPlus::Integer ? 1 : 0), baseOffset(baseOffset), _static(_static) {}
IdentifierASTNode(CPlus::IdentifierType type, int id, std::vector<uint32_t> dimensions, uint32_t baseOffset, bool _static) :
type(type), id(id), dimensions(dimensions), dimensionOffsets(calcDimensionOffsets(dimensions)), size(calcSize(dimensions)), baseOffset(baseOffset), _static(_static) {}
virtual CPlus::AbstractSyntaxTreeNodeType getNodeType() override {
return CPlus::IdentifierASTNode;
}
static bool isThisBuiltInObject(std::shared_ptr<BaseASTNode> astNode, CPlus::PredefinedIdentifierEnum objectId) {
if (astNode == nullptr) return false;
if (astNode->getNodeType() != CPlus::IdentifierASTNode) return false;
std::shared_ptr<IdentifierASTNode> identifier = std::dynamic_pointer_cast<IdentifierASTNode>(std::move(astNode));
if (identifier->getIdentifierType() != CPlus::BuiltInObjects) return false;
return identifier->getIdentifierId() == objectId;
}
bool isNilIdentifier() {
return this->type == CPlus::_IdentifierTypeNil;
}
CPlus::IdentifierType getIdentifierType() { return this->type; }
int getIdentifierId() { return this->id; }
std::vector<uint32_t>& getDimensions() { return this->dimensions; }
std::vector<uint32_t>& getDimensionOffsets() { return this->dimensionOffsets; }
uint32_t getSize() { return this->size; }
uint32_t& getBaseOffsetRef() { return this->baseOffset; }
bool isStatic() { return this->_static; }
};
class IntConstantASTNode : public BaseASTNode {
int value;
public:
IntConstantASTNode(int value) : value(value) {}
virtual CPlus::AbstractSyntaxTreeNodeType getNodeType() override {
return CPlus::IntConstantASTNode;
}
int getValue() { return value; }
};
// 由于我们的实现中不包含三元运算符,Not 等一元运算符也通过 BinaryExpressionASTNode 描述
// 对于这类一元运算符,将只有 RHS
class BinaryExpressionASTNode : public BaseASTNode {
CPlus::SymbolOperatorEnum op;
std::shared_ptr<BaseASTNode> left;
std::shared_ptr<BaseASTNode> right;
public:
BinaryExpressionASTNode(CPlus::SymbolOperatorEnum op,
std::shared_ptr<BaseASTNode> left,
std::shared_ptr<BaseASTNode> right) :
op(op), left(std::move(left)), right(std::move(right)) {}
virtual CPlus::AbstractSyntaxTreeNodeType getNodeType() override {
return CPlus::BinaryExpressionASTNode;
}
CPlus::SymbolOperatorEnum& getOperatorRef() { return this->op; }
std::shared_ptr<BaseASTNode>& getLeftRef() { return this->left; }
std::shared_ptr<BaseASTNode>& getRightRef() { return this->right; }
bool initialized() { return this->left != nullptr || this->right != nullptr; }
};
class FunctionCallASTNode : public BaseASTNode {
int funcId;
std::vector<std::shared_ptr<BaseASTNode> > arguments;
public:
FunctionCallASTNode(int funcId,
std::vector<std::shared_ptr<BaseASTNode>> arguments) :
funcId(funcId), arguments(std::move(arguments)) {}
virtual CPlus::AbstractSyntaxTreeNodeType getNodeType() override {
return CPlus::FunctionCallASTNode;
}
int getFuncId() { return this->funcId; }
std::vector<std::shared_ptr<BaseASTNode>>& getArgumentsRef() { return this->arguments; }
};
class BlockASTNode : public BaseASTNode {
std::vector<std::shared_ptr<BaseASTNode> > statements;
int localVarSize;
public:
BlockASTNode(std::vector<std::shared_ptr<BaseASTNode> > statements, int localVarSize) :
statements(std::move(statements)), localVarSize(localVarSize) {}
virtual CPlus::AbstractSyntaxTreeNodeType getNodeType() override {
return CPlus::BlockASTNode;
}
std::vector<std::shared_ptr<BaseASTNode> >& getStatementsRef() {
return this->statements;
}
int& getLocalVarSizeRef() { return this->localVarSize; }
};
class IfStatementASTNode : public BaseASTNode {
std::shared_ptr<BaseASTNode> condition;
std::shared_ptr<BaseASTNode> truthy_stmt;
std::shared_ptr<BaseASTNode> falsy_stmt;
public:
IfStatementASTNode(std::shared_ptr<BaseASTNode> condition,
std::shared_ptr<BaseASTNode> truthy_stmt) :
condition(std::move(condition)), truthy_stmt(std::move(truthy_stmt)) {}
IfStatementASTNode(std::shared_ptr<BaseASTNode> condition,
std::shared_ptr<BaseASTNode> truthy_stmt,
std::shared_ptr<BaseASTNode> falsy_stmt) :
condition(std::move(condition)), truthy_stmt(std::move(truthy_stmt)), falsy_stmt(std::move(falsy_stmt)) {}
virtual CPlus::AbstractSyntaxTreeNodeType getNodeType() override {
return CPlus::IfStatementASTNode;
}
std::shared_ptr<BaseASTNode>& getConditionRef() { return this->condition; }
std::shared_ptr<BaseASTNode>& getTruthyStmtRef() { return this->truthy_stmt; }
std::shared_ptr<BaseASTNode>& getFalsyStmtRef() { return this->falsy_stmt; }
};
class WhileStatementASTNode : public BaseASTNode {
std::shared_ptr<BaseASTNode> condition;
std::shared_ptr<BaseASTNode> loop_stmt;
public:
WhileStatementASTNode(std::shared_ptr<BaseASTNode> condition,
std::shared_ptr<BaseASTNode> loop_stmt) :
condition(std::move(condition)), loop_stmt(std::move(loop_stmt)) {}
virtual CPlus::AbstractSyntaxTreeNodeType getNodeType() override {
return CPlus::WhileStatementASTNode;
}
std::shared_ptr<BaseASTNode>& getConditionRef() { return this->condition; }
std::shared_ptr<BaseASTNode>& getLoopStmtRef() { return this->loop_stmt; }
};
class ForStatementASTNode : public BaseASTNode {
std::shared_ptr<BaseASTNode> init;
std::shared_ptr<BaseASTNode> condition;
std::shared_ptr<BaseASTNode> iteration;
std::shared_ptr<BaseASTNode> loop_stmt;
public:
ForStatementASTNode(std::shared_ptr<BaseASTNode> init,
std::shared_ptr<BaseASTNode> condition,
std::shared_ptr<BaseASTNode> iteration,
std::shared_ptr<BaseASTNode> loop_stmt) :
init(std::move(init)),
// 这里注意如果 for 循环的条件为空则令其为 1
condition((condition == nullptr || (condition != nullptr && condition->getNodeType() == CPlus::BaseASTNode)) ?
std::make_shared<IntConstantASTNode>(1) : std::move(condition)),
iteration(std::move(iteration)), loop_stmt(std::move(loop_stmt)) {}
virtual CPlus::AbstractSyntaxTreeNodeType getNodeType() override {
return CPlus::ForStatementASTNode;
}
std::shared_ptr<BaseASTNode>& getInitRef() { return this->init; }
std::shared_ptr<BaseASTNode>& getConditionRef() { return this->condition; }
std::shared_ptr<BaseASTNode>& getIterationRef() { return this->iteration; }
std::shared_ptr<BaseASTNode>& getLoopStmtRef() { return this->loop_stmt; }
};
class ReturnStatementASTNode : public BaseASTNode {
std::shared_ptr<BaseASTNode> expr;
public:
ReturnStatementASTNode(std::shared_ptr<BaseASTNode> expr) : expr(std::move(expr)) {}
virtual CPlus::AbstractSyntaxTreeNodeType getNodeType() override {
return CPlus::ReturnStatementASTNode;
}
std::shared_ptr<BaseASTNode>& getExprRef() { return this->expr; }
};
class Function {
int funcId;
std::vector<std::shared_ptr<IdentifierASTNode> > argumentIds;
std::shared_ptr<BlockASTNode> statements;
uint32_t maxStackSize;
public:
Function(int funcId, std::vector<std::shared_ptr<IdentifierASTNode> > argumentIds) :
funcId(funcId), argumentIds(std::move(argumentIds)), statements(nullptr), maxStackSize(0) {}
Function(int funcId, std::vector<std::shared_ptr<IdentifierASTNode> > argumentIds,
std::shared_ptr<BlockASTNode> statements, uint32_t maxStackSize) :
funcId(funcId), argumentIds(std::move(argumentIds)), statements(std::move(statements)), maxStackSize(maxStackSize) {}
int getFuncId() { return this->funcId; }
std::vector<std::shared_ptr<IdentifierASTNode> >& getArgumentIdsRef() { return this->argumentIds; }
std::shared_ptr<BlockASTNode>& getStatementsRef() { return this->statements; }
uint32_t& getMaxStackSizeRef() { return this->maxStackSize; }
};
class Scope {
std::unordered_map<int, std::shared_ptr<class IdentifierASTNode> > identifiers;
std::unordered_map<int, std::shared_ptr<class Function> > functions;
std::shared_ptr<Scope> parentScope;
public:
Scope() : parentScope(nullptr) {}
Scope(std::shared_ptr<Scope> parentScope) : parentScope(parentScope) {}
void setIdentifier(int id, std::shared_ptr<class IdentifierASTNode> identifier) {
this->identifiers[id] = std::move(identifier);
}
void setFunction(int id, std::shared_ptr<class Function> function) {
this->functions[id] = std::move(function);
}
std::shared_ptr<class IdentifierASTNode> lookup(int identifierId) {
if (this->identifiers.count(identifierId))
return (*(this->identifiers.find(identifierId))).second;
else if (this->parentScope != nullptr)
return this->parentScope->lookup(identifierId);
else
return nullptr;
}
std::shared_ptr<class Function> lookupFunc(int funcId) {
if (this->identifiers.count(funcId))
return (*(this->functions.find(funcId))).second;
else if (this->parentScope != nullptr)
return this->parentScope->lookupFunc(funcId);
else
return nullptr;
}
std::unordered_map<int, std::shared_ptr<class Function> >::const_iterator funcBegin() {
return this->functions.cbegin();
}
std::unordered_map<int, std::shared_ptr<class Function> >::const_iterator funcEnd() {
return this->functions.cend();
}
std::unordered_map<int, std::shared_ptr<class IdentifierASTNode> >::const_iterator idBegin() {
return this->identifiers.cbegin();
}
std::unordered_map<int, std::shared_ptr<class IdentifierASTNode> >::const_iterator idEnd() {
return this->identifiers.cend();
}
};
private:
bool analyzed = false;
std::shared_ptr<LexicalAnalyzer> lex;
std::shared_ptr<Scope> globalScope;
public:
SyntaxAnalyzer(std::shared_ptr<LexicalAnalyzer> lex) : lex(std::move(lex)) {
this->globalScope = std::make_shared<Scope>();
globalScope->setIdentifier(CPlus::Cin, std::make_shared<IdentifierASTNode>(CPlus::BuiltInObjects, CPlus::Cin, CPlus::GlobalObjectsNilBaseOffset, true));
globalScope->setIdentifier(CPlus::Cout, std::make_shared<IdentifierASTNode>(CPlus::BuiltInObjects, CPlus::Cout, CPlus::GlobalObjectsNilBaseOffset, true));
globalScope->setIdentifier(CPlus::Endl, std::make_shared<IdentifierASTNode>(CPlus::BuiltInObjects, CPlus::Endl, CPlus::GlobalObjectsNilBaseOffset, true));
globalScope->setIdentifier(CPlus::Putchar, std::make_shared<IdentifierASTNode>(CPlus::Function, CPlus::Putchar, CPlus::GlobalObjectsNilBaseOffset, true));
std::vector<std::shared_ptr<IdentifierASTNode> > putcharArgs;
std::vector<std::shared_ptr<BaseASTNode> > putcharStmt;
putcharArgs.push_back(std::make_shared<IdentifierASTNode>(CPlus::Integer, 0, 0, false));
globalScope->setFunction(CPlus::Putchar, std::make_shared<Function>(CPlus::Putchar, std::move(putcharArgs), nullptr /* putchar 特别处理*/, 0 ));
}
~SyntaxAnalyzer() {}
static std::pair<uint32_t, std::vector<std::shared_ptr<IdentifierASTNode> > > declarationAnalyze(std::vector<LexicalAnalyzer::Lexeme>& lexemes, size_t& ptr, uint32_t baseOffset, bool isStatic = false) {
std::vector<std::shared_ptr<IdentifierASTNode> > ret;
std::vector<uint32_t> dimensions;
int id = 0, currentDimension = 0;
CPlus::IdentifierType type = CPlus::_IdentifierTypeNil;
bool insideArrayDefinition = false;
for (bool iterate = true; iterate; ptr++) {
LexicalAnalyzer::Lexeme& current = lexemes[ptr];
switch (current.type) {
case CPlus::Symbol: {
switch (current.value) {
case CPlus::StatementSeparator:
case CPlus::FunctionCallDefEnd:
iterate = false;
continue;
break;
case CPlus::CommaSeparator: {
// 完成当前的一个定义解析
std::shared_ptr<IdentifierASTNode> identifier = std::make_shared<IdentifierASTNode>(type, id, dimensions, baseOffset, isStatic);
baseOffset += identifier->getSize();
ret.push_back(std::move(identifier));
dimensions.clear();
id = 0;
// 重置类型
type = CPlus::_IdentifierTypeNil;
continue;
} break;
// 鉴定为数组
case CPlus::ArrayAccessDefBegin:
type = CPlus::IntegerArray;
insideArrayDefinition = true;
break;
case CPlus::ArrayAccessDefEnd:
dimensions.push_back(currentDimension);
currentDimension = 0;
insideArrayDefinition = false;
break;
}
} break;
case CPlus::Keyword:
continue;
break;
case CPlus::IntConstant:
// 如果是数组内部则是当前数组维度
if (insideArrayDefinition)
currentDimension = current.value;
else
continue;
break;
case CPlus::Identifier:
id = current.value;
type = CPlus::Integer;
break;
default:
continue;
break;
}
}
// 若最终类型未重置,说明有一个未添加的
if (type != CPlus::_IdentifierTypeNil) {
std::shared_ptr<IdentifierASTNode> identifier = std::make_shared<IdentifierASTNode>(type, id, dimensions, baseOffset, isStatic);
baseOffset += identifier->getSize();
ret.push_back(std::move(identifier));
}
// 返回添加当前所有变量后的偏移量和变量
return std::make_pair(baseOffset, std::move(ret));
}
static std::pair<std::shared_ptr<IdentifierASTNode>, std::shared_ptr<Function> > functionAnalyze(
std::vector<LexicalAnalyzer::Lexeme>& lexemes,
size_t& ptr, std::shared_ptr<Scope> const& scope) {
std::stringstream err;
std::shared_ptr<IdentifierASTNode> funcIdentifier = nullptr;
std::shared_ptr<Function> func = nullptr;
int id = 0;
uint32_t maxStackSize = 0;
std::vector<std::vector<IdentifierASTNode> > args;
std::shared_ptr<Scope> newScope = std::make_shared<Scope>(scope);
uint32_t baseOffset = 0;
for (bool iterate = true; iterate;) {
LexicalAnalyzer::Lexeme& lexeme = lexemes[ptr];
switch (lexeme.type) {
case CPlus::Keyword:
ptr++;
continue;
break;
case CPlus::Identifier:
id = lexeme.value;
ptr++;
continue;
break;
case CPlus::Symbol:
switch (lexeme.value) {
case CPlus::FunctionCallDefBegin: {
ptr++;
std::pair<int, std::vector<std::shared_ptr<IdentifierASTNode> > > offsetAndIds = declarationAnalyze(lexemes, ptr, 0);
std::vector<std::shared_ptr<IdentifierASTNode> > &args = offsetAndIds.second;
baseOffset = offsetAndIds.first;
maxStackSize = baseOffset;
for (std::shared_ptr<IdentifierASTNode> astNode : args) {
int argId = astNode->getIdentifierId();
newScope->setIdentifier(argId, astNode);
}
func = std::make_shared<Function>(id, std::move(args));
funcIdentifier = std::make_shared<IdentifierASTNode>(CPlus::Function, id, CPlus::GlobalObjectsNilBaseOffset, true);
scope->setIdentifier(id, funcIdentifier);
scope->setFunction(id, func);
} break;
case CPlus::FunctionBodyBegin: {
ptr++;
func->getStatementsRef() = std::move(std::dynamic_pointer_cast<BlockASTNode>(statementsAnalyze(lexemes, ptr, newScope, baseOffset, maxStackSize, false, true)));
func->getMaxStackSizeRef() = maxStackSize;
iterate = false;
} break;
}
break;
default:
err << "Unexpected lexeme in function analyze at " << ptr;
throw CPlus::CompileError(err.str());
break;
}
}
if (func == nullptr) {
err << "Unknown problem causes func to be null!";
throw CPlus::CompileError(err.str());
}
return std::make_pair(std::move(funcIdentifier), std::move(func));
}
static std::shared_ptr<BaseASTNode> statementsAnalyze(std::vector<LexicalAnalyzer::Lexeme>& lexemes,
size_t& ptr,
std::shared_ptr<Scope> const& scope,
uint32_t baseOffset, // 基础偏移量
uint32_t& maxStackSize, // 记录整个函数的语句块内分配内存数上限
bool onlyOneStatement = false, // 是否只解析一条语句(用于 if、for、while 等语句块)
bool forceBlock = false // 强制返回语句块
) {
std::stringstream err;
std::vector<std::shared_ptr<BaseASTNode> > statements;
// 为了变量回收,需要记录语句块中直接声明的变量内存
uint32_t maxSize = 0;
// 处理 If-Else-If 结构时,需要记录上一个 If 语句信息
std::shared_ptr<IfStatementASTNode> lastIf = nullptr;
// 初始基础偏移量
uint32_t initialBaseOffset = baseOffset;
for (bool iterate = true; iterate;) {
if (onlyOneStatement && !statements.empty()) {
iterate = false;
continue;
}
LexicalAnalyzer::Lexeme& lexeme = lexemes[ptr];
switch (lexeme.type) {
case CPlus::Symbol: {
switch (lexeme.value) {
case CPlus::BlockEnd:
iterate = false;
ptr++;
break;
case CPlus::FunctionBodyEnd:
iterate = false;
ptr++;
// 补充最后的 ret 指令
if ((!statements.empty() && statements.back()->getNodeType() != CPlus::ReturnStatementASTNode) || statements.empty())
statements.push_back(std::make_shared<ReturnStatementASTNode>(nullptr));
break;
case CPlus::BlockBegin: {
std::shared_ptr<Scope> newScope = std::make_shared<Scope>(scope);
ptr++;
std::shared_ptr<BlockASTNode> block = std::move(std::dynamic_pointer_cast<BlockASTNode>(
statementsAnalyze(lexemes, ptr, newScope, baseOffset, maxStackSize, false, true)
));
statements.push_back(std::move(block));
} break;
}
} break;
case CPlus::Operator:
case CPlus::Identifier: {
std::shared_ptr<BaseASTNode> expr = std::move(expressionAnalyze(lexemes, ptr, scope));
statements.push_back(std::move(expr));
} break;
case CPlus::Keyword: {
switch (lexeme.value) {
case CPlus::Int: {
std::pair<uint32_t, std::vector<std::shared_ptr<IdentifierASTNode> > > offsetAndIds = declarationAnalyze(lexemes, ptr, baseOffset);
baseOffset = offsetAndIds.first;
std::vector<std::shared_ptr<IdentifierASTNode> > &ids = offsetAndIds.second;
for (std::vector<std::shared_ptr<IdentifierASTNode> >::iterator it = ids.begin(); it != ids.end(); it++) {
int id = (*it)->getIdentifierId();
scope->setIdentifier(id, std::move(*it));
}
maxSize = std::max(baseOffset - initialBaseOffset, maxSize);
maxStackSize = std::max(maxStackSize, baseOffset);
} break;
case CPlus::If: {
LexicalAnalyzer::Lexeme& cbBegin = lexemes[++ptr];
if (cbBegin.type != CPlus::Symbol || cbBegin.value != CPlus::ControlBlockBegin) {
err << "Expecting ( at lexeme " << ptr << " for if stmt";
throw CPlus::CompileError(err.str());
}
ptr++;
std::shared_ptr<BaseASTNode> condition = std::move(expressionAnalyze(lexemes, ptr, scope));
std::shared_ptr<BaseASTNode> body = std::move(statementsAnalyze(lexemes, ptr, scope, baseOffset, maxStackSize, true));
lastIf = std::make_shared<IfStatementASTNode>(std::move(condition), std::move(body));
statements.push_back(lastIf);
} break;
case CPlus::Else: {
ptr++;
if (lastIf != nullptr) {
lastIf->getFalsyStmtRef() = std::move(statementsAnalyze(lexemes, ptr, scope, baseOffset, maxStackSize, true));
if (lastIf->getFalsyStmtRef()->getNodeType() == CPlus::IfStatementASTNode)
lastIf = std::dynamic_pointer_cast<IfStatementASTNode>(lastIf->getFalsyStmtRef());
else
lastIf = nullptr;
}
else {
err << "Standalone else found at lexeme " << ptr - 1;
throw CPlus::CompileError(err.str());
}
} break;
case CPlus::While: {
LexicalAnalyzer::Lexeme& cbBegin = lexemes[++ptr];
if (cbBegin.type != CPlus::Symbol || cbBegin.value != CPlus::ControlBlockBegin) {
err << "Expecting ( at lexeme " << ptr << " for if stmt";
throw CPlus::CompileError(err.str());
}
ptr++;
std::shared_ptr<BaseASTNode> condition = std::move(expressionAnalyze(lexemes, ptr, scope));
std::shared_ptr<BaseASTNode> body = std::move(statementsAnalyze(lexemes, ptr, scope, baseOffset, maxStackSize, true));
statements.push_back(std::make_shared<WhileStatementASTNode>(std::move(condition), std::move(body)));
} break;
case CPlus::For: {
LexicalAnalyzer::Lexeme& cbBegin = lexemes[++ptr];
if (cbBegin.type != CPlus::Symbol || cbBegin.value != CPlus::ControlBlockBegin) {
err << "Expecting ( at lexeme " << ptr << " for if stmt";
throw CPlus::CompileError(err.str());
}
ptr++;
std::shared_ptr<BaseASTNode> init = std::move(expressionAnalyze(lexemes, ptr, scope));
std::shared_ptr<BaseASTNode> condition = std::move(expressionAnalyze(lexemes, ptr, scope));
std::shared_ptr<BaseASTNode> iteration = std::move(expressionAnalyze(lexemes, ptr, scope));
std::shared_ptr<BaseASTNode> body = std::move(statementsAnalyze(lexemes, ptr, scope, baseOffset, maxStackSize, true));
statements.push_back(std::make_shared<ForStatementASTNode>(std::move(init),
std::move(condition), std::move(iteration), std::move(body)));
} break;
case CPlus::Return: {
ptr++;
std::shared_ptr<BaseASTNode> expr = std::move(expressionAnalyze(lexemes, ptr, scope));
statements.push_back(std::make_shared<ReturnStatementASTNode>(std::move(expr)));
} break;
}
} break;