-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParser.cpp
1365 lines (1144 loc) · 38.9 KB
/
Parser.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 "Parser.h"
#include "LibraryManager.h"
#include "Utils.h"
#include "Logger.h"
namespace lwscript
{
struct PrecedenceBinding
{
TokenKind kind;
Precedence precedence;
};
constexpr PrecedenceBinding precedenceDict[] = {
{TokenKind::EQUAL, Precedence::ASSIGN},
{TokenKind::PLUS_EQUAL, Precedence::ASSIGN},
{TokenKind::MINUS_EQUAL, Precedence::ASSIGN},
{TokenKind::ASTERISK_EQUAL, Precedence::ASSIGN},
{TokenKind::SLASH_EQUAL, Precedence::ASSIGN},
{TokenKind::PERCENT_EQUAL, Precedence::ASSIGN},
{TokenKind::AMPERSAND_EQUAL, Precedence::ASSIGN},
{TokenKind::VBAR_EQUAL, Precedence::ASSIGN},
{TokenKind::CARET_EQUAL, Precedence::ASSIGN},
{TokenKind::LESS_LESS_EQUAL, Precedence::ASSIGN},
{TokenKind::GREATER_GREATER_EQUAL, Precedence::ASSIGN},
{TokenKind::VBAR_VBAR, Precedence::OR},
{TokenKind::AMPERSAND_AMPERSAND, Precedence::AND},
{TokenKind::QUESTION, Precedence::CONDITION},
{TokenKind::VBAR, Precedence::BIT_OR},
{TokenKind::CARET, Precedence::BIT_XOR},
{TokenKind::AMPERSAND, Precedence::BIT_AND},
{TokenKind::EQUAL_EQUAL, Precedence::EQUAL},
{TokenKind::BANG_EQUAL, Precedence::EQUAL},
{TokenKind::LESS, Precedence::COMPARE},
{TokenKind::LESS_EQUAL, Precedence::COMPARE},
{TokenKind::GREATER, Precedence::COMPARE},
{TokenKind::GREATER_EQUAL, Precedence::COMPARE},
{TokenKind::LESS_LESS, Precedence::BIT_SHIFT},
{TokenKind::GREATER_GREATER, Precedence::BIT_SHIFT},
{TokenKind::PLUS, Precedence::ADD_PLUS},
{TokenKind::MINUS, Precedence::ADD_PLUS},
{TokenKind::ASTERISK, Precedence::MUL_DIV_MOD},
{TokenKind::SLASH, Precedence::MUL_DIV_MOD},
{TokenKind::PERCENT, Precedence::MUL_DIV_MOD},
{TokenKind::LBRACKET, Precedence::INFIX},
{TokenKind::LPAREN, Precedence::INFIX},
{TokenKind::DOT, Precedence::INFIX},
{TokenKind::BANG, Precedence::INFIX},
{TokenKind::PLUS_PLUS, Precedence::POSTFIX},
{TokenKind::MINUS_MINUS, Precedence::POSTFIX},
};
struct AssociativityBinding
{
Precedence precedence;
Associativity associativity;
};
constexpr AssociativityBinding associativityDict[] =
{
{Precedence::LOWEST, Associativity::L2R},
{Precedence::ASSIGN, Associativity::R2L},
{Precedence::CONDITION, Associativity::L2R},
{Precedence::OR, Associativity::L2R},
{Precedence::AND, Associativity::L2R},
{Precedence::BIT_OR, Associativity::L2R},
{Precedence::BIT_XOR, Associativity::L2R},
{Precedence::BIT_AND, Associativity::L2R},
{Precedence::EQUAL, Associativity::L2R},
{Precedence::COMPARE, Associativity::L2R},
{Precedence::BIT_SHIFT, Associativity::L2R},
{Precedence::ADD_PLUS, Associativity::L2R},
{Precedence::MUL_DIV_MOD, Associativity::L2R},
{Precedence::PREFIX, Associativity::R2L},
{Precedence::INFIX, Associativity::L2R},
{Precedence::POSTFIX, Associativity::L2R},
};
std::unordered_map<TokenKind, PrefixFn> Parser::mPrefixFunctions =
{
{TokenKind::IDENTIFIER, &Parser::ParseIdentifierExpr},
{TokenKind::NUMBER, &Parser::ParseLiteralExpr},
{TokenKind::STRING, &Parser::ParseLiteralExpr},
{TokenKind::NIL, &Parser::ParseLiteralExpr},
{TokenKind::TRUE, &Parser::ParseLiteralExpr},
{TokenKind::FALSE, &Parser::ParseLiteralExpr},
{TokenKind::CHAR, &Parser::ParseLiteralExpr},
{TokenKind::MINUS, &Parser::ParsePrefixExpr},
{TokenKind::TILDE, &Parser::ParsePrefixExpr},
{TokenKind::BANG, &Parser::ParsePrefixExpr},
{TokenKind::LPAREN, &Parser::ParseGroupExpr},
{TokenKind::LBRACKET, &Parser::ParseArrayExpr},
{TokenKind::LBRACE, &Parser::ParseDictExpr},
{TokenKind::AMPERSAND, &Parser::ParseRefExpr},
{TokenKind::FUNCTION, &Parser::ParseLambdaExpr},
{TokenKind::PLUS_PLUS, &Parser::ParsePrefixExpr},
{TokenKind::MINUS_MINUS, &Parser::ParsePrefixExpr},
{TokenKind::NEW, &Parser::ParseNewExpr},
{TokenKind::THIS, &Parser::ParseThisExpr},
{TokenKind::BASE, &Parser::ParseBaseExpr},
{TokenKind::MATCH, &Parser::ParseMatchExpr},
{TokenKind::LPAREN_LBRACE, &Parser::ParseCompoundExpr},
{TokenKind::ELLIPSIS, &Parser::ParseVarArgExpr},
{TokenKind::STRUCT, &Parser::ParseStructExpr},
};
std::unordered_map<TokenKind, InfixFn> Parser::mInfixFunctions =
{
{TokenKind::EQUAL, &Parser::ParseInfixExpr},
{TokenKind::PLUS_EQUAL, &Parser::ParseInfixExpr},
{TokenKind::MINUS_EQUAL, &Parser::ParseInfixExpr},
{TokenKind::ASTERISK_EQUAL, &Parser::ParseInfixExpr},
{TokenKind::SLASH_EQUAL, &Parser::ParseInfixExpr},
{TokenKind::PERCENT_EQUAL, &Parser::ParseInfixExpr},
{TokenKind::AMPERSAND_EQUAL, &Parser::ParseInfixExpr},
{TokenKind::VBAR_EQUAL, &Parser::ParseInfixExpr},
{TokenKind::CARET_EQUAL, &Parser::ParseInfixExpr},
{TokenKind::LESS_LESS_EQUAL, &Parser::ParseInfixExpr},
{TokenKind::GREATER_GREATER_EQUAL, &Parser::ParseInfixExpr},
{TokenKind::QUESTION, &Parser::ParseConditionExpr},
{TokenKind::VBAR_VBAR, &Parser::ParseInfixExpr},
{TokenKind::AMPERSAND_AMPERSAND, &Parser::ParseInfixExpr},
{TokenKind::VBAR, &Parser::ParseInfixExpr},
{TokenKind::CARET, &Parser::ParseInfixExpr},
{TokenKind::AMPERSAND, &Parser::ParseInfixExpr},
{TokenKind::LESS_LESS, &Parser::ParseInfixExpr},
{TokenKind::GREATER_GREATER, &Parser::ParseInfixExpr},
{TokenKind::EQUAL_EQUAL, &Parser::ParseInfixExpr},
{TokenKind::BANG_EQUAL, &Parser::ParseInfixExpr},
{TokenKind::LESS, &Parser::ParseInfixExpr},
{TokenKind::LESS_EQUAL, &Parser::ParseInfixExpr},
{TokenKind::GREATER, &Parser::ParseInfixExpr},
{TokenKind::GREATER_EQUAL, &Parser::ParseInfixExpr},
{TokenKind::PLUS, &Parser::ParseInfixExpr},
{TokenKind::MINUS, &Parser::ParseInfixExpr},
{TokenKind::ASTERISK, &Parser::ParseInfixExpr},
{TokenKind::SLASH, &Parser::ParseInfixExpr},
{TokenKind::PERCENT, &Parser::ParseInfixExpr},
{TokenKind::LPAREN, &Parser::ParseCallExpr},
{TokenKind::LBRACKET, &Parser::ParseIndexExpr},
{TokenKind::DOT, &Parser::ParseDotExpr},
{TokenKind::BANG, &Parser::ParseFactorialExpr},
};
std::unordered_map<TokenKind, PostfixFn> Parser::mPostfixFunctions =
{
{TokenKind::PLUS_PLUS, &Parser::ParsePostfixExpr},
{TokenKind::MINUS_MINUS, &Parser::ParsePostfixExpr},
};
Parser::Parser()
: mCurClassInfo(nullptr), mCurPos(0)
{
}
Parser::~Parser()
{
std::unordered_map<TokenKind, PrefixFn>().swap(mPrefixFunctions);
std::unordered_map<TokenKind, InfixFn>().swap(mInfixFunctions);
}
Stmt *Parser::Parse(const std::vector<Token *> &tokens)
{
ResetStatus();
mTokens = tokens;
AstStmts *astStmts = new AstStmts(GetCurToken());
while (!IsMatchCurToken(TokenKind::END))
astStmts->stmts.emplace_back(ParseDecl());
return astStmts;
}
void Parser::ResetStatus()
{
mCurPos = 0;
mCurClassInfo = nullptr;
}
Stmt *Parser::ParseDecl()
{
switch (GetCurToken()->kind)
{
case TokenKind::LET:
case TokenKind::CONST:
return ParseVarDecl();
case TokenKind::FUNCTION:
GetCurTokenAndStepOnce();
return ParseFunctionDecl();
case TokenKind::CLASS:
return ParseClassDecl();
case TokenKind::ENUM:
return ParseEnumDecl();
case TokenKind::MODULE:
return ParseModuleDecl();
default:
return ParseStmt();
}
}
Stmt *Parser::ParseVarDecl()
{
auto curToken = GetCurToken();
auto kind = curToken->kind;
auto varStmt = new VarStmt(curToken);
if (kind == TokenKind::LET)
varStmt->privilege = Privilege::MUTABLE;
else if (kind == TokenKind::CONST)
varStmt->privilege = Privilege::IMMUTABLE;
Consume(kind, TEXT("Expect 'let' or 'const' key word"));
do
{
if (IsMatchCurToken(TokenKind::LBRACKET))
varStmt->variables.emplace_back(ParseDestructuringAssignmentExpr());
else
{
auto varDescExpr = ParseVarDescExpr();
Expr *value = new LiteralExpr(varDescExpr->tagToken);
if (IsMatchCurTokenAndStepOnce(TokenKind::EQUAL))
value = ParseExpr();
varStmt->variables.emplace_back(varDescExpr, value);
}
} while (IsMatchCurTokenAndStepOnce(TokenKind::COMMA));
Consume(TokenKind::SEMICOLON, TEXT("Expect ';' after let or const declaration."));
return varStmt;
}
Stmt *Parser::ParseFunctionDecl()
{
auto funcStmt = new FunctionStmt(GetCurToken());
{
funcStmt->name = (IdentifierExpr *)ParseIdentifierExpr();
if (mCurClassInfo)
{
funcStmt->functionKind = FunctionKind::CLASS_CLOSURE;
if (mCurClassInfo->name == funcStmt->name->literal)
funcStmt->functionKind = FunctionKind::CLASS_CONSTRUCTOR;
}
Consume(TokenKind::LPAREN, TEXT("Expect '(' after 'fn' keyword"));
if (!IsMatchCurToken(TokenKind::RPAREN)) // has parameter
{
do
{
funcStmt->parameters.emplace_back((VarDescExpr *)ParseVarDescExpr());
} while (IsMatchCurTokenAndStepOnce(TokenKind::COMMA));
}
Consume(TokenKind::RPAREN, TEXT("Expect ')' after function stmt's '('"));
std::vector<Type> functionReturnTypes;
{
// TODO: parse function return type
if (IsMatchCurToken(TokenKind::COLON))
{
GetCurTokenAndStepOnce();
do
{
auto type = ParseType();
functionReturnTypes.emplace_back(type);
} while (IsMatchCurTokenAndStepOnce(TokenKind::COMMA));
}
}
funcStmt->returnTypes = functionReturnTypes;
funcStmt->body = (ScopeStmt *)ParseScopeStmt();
if (funcStmt->body->stmts.back()->kind != AstKind::RETURN && funcStmt->functionKind != FunctionKind::CLASS_CONSTRUCTOR)
{
auto tmpReturn = new ReturnStmt(GetCurToken());
funcStmt->body->stmts.emplace_back(tmpReturn);
}
}
return funcStmt;
}
Stmt *Parser::ParseClassDecl()
{
auto classStmt = new ClassStmt(GetCurToken());
Consume(TokenKind::CLASS, TEXT("Expect 'class' keyword"));
classStmt->name = ((IdentifierExpr *)ParseIdentifierExpr())->literal;
ClassInfo classInfo;
classInfo.hasSuperClass = false;
classInfo.enclosing = mCurClassInfo;
classInfo.name = classStmt->name;
mCurClassInfo = &classInfo;
if (IsMatchCurTokenAndStepOnce(TokenKind::COLON))
{
do
{
classStmt->parentClasses.emplace_back((IdentifierExpr *)ParseIdentifierExpr());
} while (IsMatchCurTokenAndStepOnce(TokenKind::COMMA));
mCurClassInfo->hasSuperClass = true;
}
Consume(TokenKind::LBRACE, TEXT("Expect '{' after class name or parent class name"));
while (!IsMatchCurToken(TokenKind::RBRACE))
{
if (IsMatchCurToken(TokenKind::LET) || IsMatchCurToken(TokenKind::CONST))
classStmt->varItems.emplace_back((VarStmt *)ParseVarDecl());
else if (IsMatchCurTokenAndStepOnce(TokenKind::FUNCTION))
{
auto fn = (FunctionStmt *)ParseFunctionDecl();
if (fn->name->literal == classStmt->name)
Logger::Error(fn->name->tagToken, TEXT("The class member function name :{} conflicts with its class:{}, only constructor function name is allowed to same with its class's name"), fn->name->literal);
classStmt->fnItems.emplace_back(fn);
}
else if (IsMatchCurToken(TokenKind::ENUM))
classStmt->enumItems.emplace_back((EnumStmt *)ParseEnumDecl());
else if (GetCurToken()->literal == classStmt->name) // constructor
{
auto fn = (FunctionStmt *)ParseFunctionDecl();
classStmt->constructors.emplace_back(fn);
}
else
Consume({TokenKind::LET, TokenKind::FUNCTION, TokenKind::CONST}, TEXT("UnExpect identifier '") + GetCurToken()->literal + TEXT("'."));
}
Consume(TokenKind::RBRACE, TEXT("Expect '}' after class stmt's '{'"));
mCurClassInfo = mCurClassInfo->enclosing;
return classStmt;
}
Stmt *Parser::ParseEnumDecl()
{
auto enumStmt = new EnumStmt(GetCurToken());
Consume(TokenKind::ENUM, TEXT("Expect 'enum' keyword."));
enumStmt->name = (IdentifierExpr *)ParseIdentifierExpr();
Consume(TokenKind::LBRACE, TEXT("Expect '{' after 'enum' keyword."));
std::unordered_map<IdentifierExpr *, Expr *> items;
while (!IsMatchCurToken(TokenKind::RBRACE))
{
auto name = (IdentifierExpr *)ParseIdentifierExpr();
Expr *value = new LiteralExpr(name->tagToken, name->literal);
if (IsMatchCurTokenAndStepOnce(TokenKind::EQUAL))
{
SAFE_DELETE(value);
value = ParseExpr();
}
items[name] = value;
if (IsMatchCurToken(TokenKind::COMMA))
Consume(TokenKind::COMMA, TEXT("Expect ',' after enum item."));
}
Consume(TokenKind::RBRACE, TEXT("Expect '}' at the end of the 'enum' stmt."));
enumStmt->enumItems = items;
return enumStmt;
}
Stmt *Parser::ParseModuleDecl()
{
auto token = Consume(TokenKind::MODULE, TEXT("Expect 'module' keyword."));
auto moduleDecl = new ModuleStmt(token);
moduleDecl->name = (IdentifierExpr *)ParseIdentifierExpr();
Consume(TokenKind::LBRACE, TEXT("Expect '{' after module name."));
while (!IsMatchCurToken(TokenKind::RBRACE))
{
switch (GetCurToken()->kind)
{
case TokenKind::LET:
case TokenKind::CONST:
moduleDecl->varItems.emplace_back((VarStmt *)ParseVarDecl());
break;
case TokenKind::FUNCTION:
GetCurTokenAndStepOnce();
moduleDecl->functionItems.emplace_back((FunctionStmt *)ParseFunctionDecl());
break;
case TokenKind::CLASS:
moduleDecl->classItems.emplace_back((ClassStmt *)ParseClassDecl());
break;
case TokenKind::ENUM:
moduleDecl->enumItems.emplace_back((EnumStmt *)ParseEnumDecl());
break;
case TokenKind::MODULE:
moduleDecl->moduleItems.emplace_back((ModuleStmt *)ParseModuleDecl());
break;
default:
Logger::Error(GetCurToken(), TEXT("Only let,const,function,class,enum and module is available in module scope"));
}
}
Consume(TokenKind::RBRACE, TEXT("Expect '}'."));
return moduleDecl;
}
Stmt *Parser::ParseStmt()
{
switch (GetCurToken()->kind)
{
case TokenKind::RETURN:
return ParseReturnStmt();
case TokenKind::IF:
return ParseIfStmt();
case TokenKind::LBRACE:
return ParseScopeStmt();
case TokenKind::WHILE:
return ParseWhileStmt();
case TokenKind::FOR:
return ParseForStmt();
case TokenKind::BREAK:
return ParseBreakStmt();
case TokenKind::CONTINUE:
return ParseContinueStmt();
case TokenKind::SWITCH:
return ParseSwitchStmt();
default:
return ParseExprStmt();
}
}
Stmt *Parser::ParseExprStmt()
{
auto exprStmt = new ExprStmt(GetCurToken());
exprStmt->expr = ParseExpr();
Consume(TokenKind::SEMICOLON, TEXT("Expect ';' after expr stmt."));
return exprStmt;
}
Stmt *Parser::ParseReturnStmt()
{
auto returnStmt = new ReturnStmt(GetCurToken());
Consume(TokenKind::RETURN, TEXT("Expect 'return' key word."));
if (!IsMatchCurToken(TokenKind::SEMICOLON))
{
std::vector<Expr *> returnExprs;
do
{
if (IsMatchCurToken(TokenKind::SEMICOLON))
break;
returnExprs.emplace_back(ParseExpr());
} while (IsMatchCurTokenAndStepOnce(TokenKind::COMMA));
if (returnExprs.size() > 1)
returnStmt->expr = new AppregateExpr(returnExprs[0]->tagToken, returnExprs);
else if (returnExprs.size() == 1)
returnStmt->expr = returnExprs[0];
}
Consume(TokenKind::SEMICOLON, TEXT("Expect ';' after return stmt"));
return returnStmt;
}
Stmt *Parser::ParseIfStmt()
{
auto ifStmt = new IfStmt(GetCurToken());
Consume(TokenKind::IF, TEXT("Expect 'if' key word."));
Consume(TokenKind::LPAREN, TEXT("Expect '(' after 'if'."));
ifStmt->condition = ParseExpr();
Consume(TokenKind::RPAREN, TEXT("Expect ')' after if condition"));
ifStmt->thenBranch = ParseStmt();
if (IsMatchCurTokenAndStepOnce(TokenKind::ELSE))
ifStmt->elseBranch = ParseStmt();
return ifStmt;
}
Stmt *Parser::ParseScopeStmt()
{
auto scopeStmt = new ScopeStmt(GetCurToken());
Consume(TokenKind::LBRACE, TEXT("Expect '{'."));
while (!IsMatchCurToken(TokenKind::RBRACE))
scopeStmt->stmts.emplace_back(ParseDecl());
Consume(TokenKind::RBRACE, TEXT("Expect '}'."));
return scopeStmt;
}
Stmt *Parser::ParseWhileStmt()
{
auto whileStmt = new WhileStmt(GetCurToken());
Consume(TokenKind::WHILE, TEXT("Expect 'while' keyword."));
Consume(TokenKind::LPAREN, TEXT("Expect '(' after 'while'."));
whileStmt->condition = ParseExpr();
Consume(TokenKind::RPAREN, TEXT("Expect ')' after while stmt's condition."));
if (IsMatchCurToken(TokenKind::LBRACE)) // scope stmt:while(a<10){a=a+1;}
whileStmt->body = (ScopeStmt *)ParseScopeStmt();
else // single stmt:while(a<10) a=a+1;
{
auto scopeStmt = new ScopeStmt(GetCurToken());
scopeStmt->stmts.emplace_back(ParseStmt());
whileStmt->body = scopeStmt;
}
return whileStmt;
}
Stmt *Parser::ParseForStmt()
{
// for(let i=0,j=0;i<10&&j<10;i=i+1,j=j+1)
//{
// ...
// }
// |
// |
// v
//{
// let i=0,j=0;
// while(i<10&&j<10)
// {
// {
// ...
// }
// increment part:
// {
// i=i+1;
// j=j+1;
// }
// }
// }
auto token = GetCurToken();
auto scopeStmt = new ScopeStmt(token);
Consume(TokenKind::FOR, TEXT("Expect 'for' keyword."));
Consume(TokenKind::LPAREN, TEXT("Expect '(' after 'for'."));
// initializer
if (IsMatchCurToken(TokenKind::LET) || IsMatchCurToken(TokenKind::CONST))
scopeStmt->stmts.emplace_back(ParseVarDecl());
else
{
if (!IsMatchCurToken(TokenKind::SEMICOLON))
{
do
{
scopeStmt->stmts.emplace_back(new ExprStmt(GetCurToken(), ParseExpr()));
} while (IsMatchCurTokenAndStepOnce(TokenKind::COMMA));
}
Consume(TokenKind::SEMICOLON, TEXT("Expect ';' after for stmt's initializer stmt"));
}
Expr *condition = nullptr;
if (!IsMatchCurToken(TokenKind::SEMICOLON))
condition = ParseExpr();
Consume(TokenKind::SEMICOLON, TEXT("Expect ';' after for stmt's condition expr."));
std::vector<Expr *> increment;
auto incrementToken = GetCurToken();
if (!IsMatchCurToken(TokenKind::RPAREN))
{
do
{
increment.emplace_back(ParseExpr());
} while (IsMatchCurTokenAndStepOnce(TokenKind::COMMA));
}
Consume(TokenKind::RPAREN, TEXT("Expect ')' after for stmt's increment expr(s)"));
auto scopeToken = GetCurToken();
std::vector<Stmt *> whileBodyStmts;
if (IsMatchCurToken(TokenKind::LBRACE)) // scope stmt for 'for' stmt:like for(a=0;a<10;a=a+1){println("{}",a);}
whileBodyStmts.emplace_back(ParseScopeStmt());
else // single stmt for 'for' stmt:like for(a=0;a<10;a=a+1) println("{}",a);
{
auto scopeStmt = new ScopeStmt(scopeToken);
scopeStmt->stmts.emplace_back(ParseStmt());
whileBodyStmts.emplace_back(scopeStmt);
}
auto whileStmt = new WhileStmt(token);
whileStmt->condition = condition;
whileStmt->body = new ScopeStmt(scopeToken, whileBodyStmts);
std::vector<Stmt *> incrementStmts;
for (const auto expr : increment)
incrementStmts.emplace_back(new ExprStmt(expr->tagToken, expr));
whileStmt->increment = new ScopeStmt(incrementToken, incrementStmts);
scopeStmt->stmts.emplace_back(whileStmt);
return scopeStmt;
}
Stmt *Parser::ParseBreakStmt()
{
auto breakStmt = new BreakStmt(GetCurToken());
Consume(TokenKind::BREAK, TEXT("Expect 'break' keyword."));
Consume(TokenKind::SEMICOLON, TEXT("Expect ';' after 'break' keyword."));
return breakStmt;
}
Stmt *Parser::ParseContinueStmt()
{
auto continueStmt = new ContinueStmt(GetCurToken());
Consume(TokenKind::CONTINUE, TEXT("Expect 'continue' keyword"));
Consume(TokenKind::SEMICOLON, TEXT("Expect ';' after 'continue' keyword."));
return continueStmt;
}
Stmt *Parser::ParseSwitchStmt()
{
auto ifStmt = new IfStmt(GetCurToken());
Consume(TokenKind::SWITCH, TEXT("Expect 'switch' keyword."));
Consume(TokenKind::LPAREN, TEXT("Expect '(' after 'switch' keyword."));
auto switchExpr = ParseIdentifierExpr();
Consume(TokenKind::RPAREN, TEXT("Expect ')' after switch's expression."));
Consume(TokenKind::LBRACE, TEXT("Expect '{' after 'switch' keyword."));
using Item = std::pair<std::vector<Expr *>, ScopeStmt *>;
std::vector<Item> items;
ScopeStmt *defaultScopeStmt = nullptr;
while (!IsMatchCurToken(TokenKind::RBRACE))
{
if (IsMatchCurTokenAndStepOnce(TokenKind::DEFAULT))
{
Consume(TokenKind::COLON, TEXT("Expect ':' after condition expr."));
defaultScopeStmt = new ScopeStmt(GetCurToken());
if (IsMatchCurTokenAndStepOnce(TokenKind::LBRACE))
{
while (!IsMatchCurToken(TokenKind::RBRACE))
defaultScopeStmt->stmts.emplace_back(ParseStmt());
Consume(TokenKind::RBRACE, TEXT("Expect '}' at the end of default block while has multiple statement"));
}
else
defaultScopeStmt->stmts.emplace_back(ParseStmt());
}
else
{
Item item;
std::vector<Expr *> conditions;
do
{
auto valueCompareExpr = ParseExpr();
auto caseCondition = new InfixExpr(GetCurToken(), TEXT("=="), switchExpr, valueCompareExpr);
conditions.emplace_back(caseCondition);
} while (IsMatchCurTokenAndStepOnce(TokenKind::COMMA));
Consume(TokenKind::COLON, TEXT("Expect ':' after condition expr."));
item.first = conditions;
item.second = new ScopeStmt(GetCurToken());
if (IsMatchCurTokenAndStepOnce(TokenKind::LBRACE))
{
while (!IsMatchCurToken(TokenKind::RBRACE))
item.second->stmts.emplace_back(ParseStmt());
Consume(TokenKind::RBRACE, TEXT("Expect '}' at the end of block while has multiple statements."));
}
else
item.second->stmts.emplace_back(ParseStmt());
items.emplace_back(item);
}
}
Consume(TokenKind::RBRACE, TEXT("Expect '}' after switch stmt"));
if (items.empty() && defaultScopeStmt != nullptr)
return defaultScopeStmt;
else
{
auto loopIfStmt = ifStmt;
for (size_t i = 0; i < items.size(); ++i)
{
if (items[i].first.size() == 1)
loopIfStmt->condition = items[i].first[0];
else
{
Expr *condition = items[i].first[0];
for (size_t j = 1; j < items[i].first.size(); ++j)
condition = new InfixExpr(condition->tagToken, TEXT("||"), condition, items[i].first[j]);
loopIfStmt->condition = condition;
}
loopIfStmt->thenBranch = items[i].second;
if (i + 1 < items.size())
{
loopIfStmt->elseBranch = new IfStmt(ifStmt->tagToken);
loopIfStmt = (IfStmt *)loopIfStmt->elseBranch;
}
}
if (defaultScopeStmt)
loopIfStmt->elseBranch = defaultScopeStmt;
}
return ifStmt;
}
Expr *Parser::ParseLambdaExpr()
{
auto lambdaExpr = new LambdaExpr(GetCurToken());
Consume(TokenKind::FUNCTION, TEXT("Expect 'fn' keyword"));
Consume(TokenKind::LPAREN, TEXT("Expect '(' after 'fn' keyword"));
if (!IsMatchCurToken(TokenKind::RPAREN)) // has parameter
{
do
{
lambdaExpr->parameters.emplace_back((VarDescExpr *)ParseVarDescExpr());
} while (IsMatchCurTokenAndStepOnce(TokenKind::COMMA));
}
Consume(TokenKind::RPAREN, TEXT("Expect ')' after lambda expr's '('"));
lambdaExpr->body = (ScopeStmt *)ParseScopeStmt();
return lambdaExpr;
}
Expr *Parser::ParseNewExpr()
{
auto newExpr = new NewExpr(GetCurToken());
Consume(TokenKind::NEW, TEXT("Expect 'new' keyword"));
Expr *callee = ParseExpr();
newExpr->callee = callee;
return newExpr;
}
Expr *Parser::ParseThisExpr()
{
auto token = Consume(TokenKind::THIS, TEXT("Expect 'this' keyword"));
auto thisExpr = new ThisExpr(token);
if (!mCurClassInfo)
Logger::Error(thisExpr->tagToken, TEXT("Invalid 'this' keyword:Cannot use 'this' outside class."));
return thisExpr;
}
Expr *Parser::ParseBaseExpr()
{
auto token = Consume(TokenKind::BASE, TEXT("Expect 'base' keyword"));
Consume(TokenKind::DOT, TEXT("Expect '.' after base keyword"));
auto baseExpr = new BaseExpr(token, (IdentifierExpr *)ParseIdentifierExpr());
if (!mCurClassInfo)
Logger::Error(baseExpr->tagToken, TEXT("Invalid 'base' keyword:Cannot use 'base' outside class."));
return baseExpr;
}
Expr *Parser::ParseMatchExpr()
{
Expr *defaultBranch = nullptr;
auto matchToken = Consume(TokenKind::MATCH, TEXT("Expect 'match' keyword."));
Consume(TokenKind::LPAREN, TEXT("Expect '(' after 'match' keyword."));
auto judgeExpr = ParseExpr();
Consume(TokenKind::RPAREN, TEXT("Expect ')' after match's expression."));
Consume(TokenKind::LBRACE, TEXT("Expect '{' after 'match' keyword."));
using Item = std::pair<std::vector<Expr *>, Expr *>;
std::vector<Item> items;
bool hasDefaultBranch = false;
if (!IsMatchCurToken(TokenKind::RBRACE))
{
do
{
if (IsMatchCurToken(TokenKind::DEFAULT))
{
if (hasDefaultBranch)
Logger::Error(GetCurToken(), TEXT("Already exists a default branch.only a default branch is available in a match expr."));
GetCurTokenAndStepOnce();
Consume(TokenKind::COLON, TEXT("Expect ':' after default's condition expr."));
defaultBranch = ParseExpr();
hasDefaultBranch = true;
}
else
{
Item item;
std::vector<Expr *> conditions;
do
{
auto valueCompareExpr = ParseExpr();
auto caseCondition = new InfixExpr(GetCurToken(), TEXT("=="), judgeExpr, valueCompareExpr);
conditions.emplace_back(caseCondition);
} while (IsMatchCurTokenAndStepOnce(TokenKind::COMMA));
Consume(TokenKind::COLON, TEXT("Expect ':' after match item's condition expr."));
item.first = conditions;
item.second = ParseExpr();
items.emplace_back(item);
}
} while (IsMatchCurTokenAndStepOnce(TokenKind::COMMA));
}
Consume(TokenKind::RBRACE, TEXT("Expect '}' after match expr"));
auto conditionExpr = new ConditionExpr(matchToken);
auto loopConditionExpr = conditionExpr;
for (int32_t i = 0; i < items.size(); ++i)
{
if (items[i].first.size() == 1)
loopConditionExpr->condition = items[i].first[0];
else
{
Expr *fullCondition = items[i].first[0];
for (size_t j = 1; j < items[i].first.size(); ++j)
fullCondition = new InfixExpr(fullCondition->tagToken, TEXT("||"), fullCondition, items[i].first[j]);
loopConditionExpr->condition = fullCondition;
}
loopConditionExpr->trueBranch = items[i].second;
if (i + 1 < items.size())
{
loopConditionExpr->falseBranch = new ConditionExpr(items[i].second->tagToken);
loopConditionExpr = (ConditionExpr *)loopConditionExpr->falseBranch;
}
}
if (defaultBranch)
loopConditionExpr->falseBranch = defaultBranch;
return conditionExpr;
}
Expr *Parser::ParseCompoundExpr()
{
auto token = Consume(TokenKind::LPAREN_LBRACE, TEXT("Expect '({'."));
mSkippingConsumeTokenKindStack.emplace_back(TokenKind::SEMICOLON);
auto blockExpr = new CompoundExpr(token);
std::vector<struct Stmt *> stmts;
do
{
if (IsMatchCurToken(TokenKind::RBRACE_RPAREN))
Logger::Error(GetCurToken(), TEXT("Expr required at the end of block expression."));
stmts.emplace_back(ParseDecl());
} while (IsMatchCurTokenAndStepOnce(TokenKind::SEMICOLON));
mSkippingConsumeTokenKindStack.pop_back();
if (stmts.back()->kind != AstKind::EXPR)
Logger::Error(stmts.back()->tagToken, TEXT("Expr required at the end of block expression."));
auto expr = ((ExprStmt *)stmts.back())->expr;
stmts.pop_back();
blockExpr->stmts = stmts;
blockExpr->endExpr = expr;
Consume(TokenKind::RBRACE_RPAREN, TEXT("Expect '})'."));
return blockExpr;
}
Expr *Parser::ParseExpr(Precedence precedence)
{
if (mPrefixFunctions.find(GetCurToken()->kind) == mPrefixFunctions.end())
{
auto token = GetCurTokenAndStepOnce();
Logger::Error(token, TEXT("no prefix definition for:{}"), token->literal);
auto nullExpr = new LiteralExpr(token);
return nullExpr;
}
auto prefixFn = mPrefixFunctions[GetCurToken()->kind];
auto leftExpr = (this->*prefixFn)();
while (!IsMatchCurToken(TokenKind::SEMICOLON) && (GetCurTokenAssociativity() == Associativity::L2R ? precedence < GetCurTokenPrecedence() : precedence <= GetCurTokenPrecedence()))
{
if (mPostfixFunctions.find(GetCurToken()->kind) != mPostfixFunctions.end())
{
auto postfixFn = mPostfixFunctions[GetCurToken()->kind];
leftExpr = (this->*postfixFn)(leftExpr);
}
else if (mInfixFunctions.find(GetCurToken()->kind) != mInfixFunctions.end())
{
auto infixFn = mInfixFunctions[GetCurToken()->kind];
leftExpr = (this->*infixFn)(leftExpr);
}
else
break;
}
return leftExpr;
}
Expr *Parser::ParseIdentifierExpr()
{
auto token = Consume(TokenKind::IDENTIFIER, TEXT("Unexpect Identifier'") + GetCurToken()->literal + TEXT("'."));
auto identifierExpr = new IdentifierExpr(token);
identifierExpr->literal = token->literal;
return identifierExpr;
}
Expr *Parser::ParseLiteralExpr()
{
auto token = GetCurTokenAndStepOnce();
if (token->kind == TokenKind::NUMBER)
{
auto literal = token->literal;
Expr *numExpr = nullptr;
if (literal.find('.') != STD_STRING::npos)
numExpr = new LiteralExpr(token, std::stod(literal));
else
numExpr = new LiteralExpr(token, std::stoll(literal));
return numExpr;
}
else if (token->kind == TokenKind::STRING)
return new LiteralExpr(token, token->literal);
else if (token->kind == TokenKind::NIL)
return new LiteralExpr(token);
else if (token->kind == TokenKind::TRUE)
return new LiteralExpr(token, true);
else if (token->kind == TokenKind::FALSE)
return new LiteralExpr(token, false);
Logger::Error(token, TEXT("Unknown Literal."));
return nullptr;
}
Expr *Parser::ParseGroupExpr()
{
auto token = Consume(TokenKind::LPAREN, TEXT("Expect '('."));
auto groupExpr = new GroupExpr(token);
groupExpr->expr = ParseExpr();
Consume(TokenKind::RPAREN, TEXT("Expect ')'."));
return groupExpr;
}
Expr *Parser::ParseArrayExpr()
{
auto token = Consume(TokenKind::LBRACKET, TEXT("Expect '['."));
auto arrayExpr = new ArrayExpr(token);
if (!IsMatchCurToken(TokenKind::RBRACKET))
{
do
{
if (IsMatchCurToken(TokenKind::RBRACKET))
break;
arrayExpr->elements.emplace_back(ParseExpr());
} while (IsMatchCurTokenAndStepOnce(TokenKind::COMMA));
}
Consume(TokenKind::RBRACKET, TEXT("Expect ']'."));
return arrayExpr;
}
Expr *Parser::ParseDictExpr()
{
auto token = Consume(TokenKind::LBRACE, TEXT("Expect '{'."));
auto dictExpr = new DictExpr(token);