-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.cpp
1344 lines (1176 loc) · 43.1 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 <cassert>
#include <iostream>
#include <stack>
#include <vector>
#include <functional>
#include "parser.h"
#include "error.h"
#include "SymbolTable.h"
// utils
void Parser::skipUntil(Token::TokenType t)
{
while (tokens_.peek().type() != Token::Eof
&& tokens_.peek().type() != t)
tokens_.next();
}
bool Parser::isAboutType(const Token& tok)
{
SymbolTable& scope = currScope();
if (tok.type() == Token::Keyword) {
auto t = tok.keyword();
return (int) t >= 0 && (int) t <= (int) Token::Static;
} else if (tok.type() == Token::Name) {
auto entry = scope.find(tok.name());
if (entry) {
auto tag = entry->type->tag();
if (tag == Type::Incomplete || tag == Type::Compound
|| tag == Type::Enum) {
// TODO maybe addQuad type alias
return true;
} else {
return false;
}
} else
return false;
} else
return false;
}
bool Parser::isTypeSpecifier(const Token& tok)
{
return tok.type() == Token::Keyword
&& (int) tok.keyword() <= (int) Token::Void;
}
void Parser::skipErrorParts()
{
while (tokens_.peek().type() != Token::Eof) {
const Token& n = tokens_.next();
auto t = n.type();
if (t == Token::Semicolon || t == Token::RBrace)
break;
}
}
bool Parser::isUserDefinedType(Type::Tag tag)
{
// TODO maybe addQuad type alias
return tag == Type::Incomplete || tag == Type::Compound
|| tag == Type::Enum || tag == Type::Alias;
}
// end utils
Parser::Parser(TokenStream& ts, ErrorLog& el)
: tokens_(ts), errors_(el)
{
// TODO this is a work around for test. delete later.
scopeStack_.push(new HashSymtab(nullptr));
}
std::shared_ptr<ASTRoot> Parser::goal()
{
auto root = std::make_shared<ASTRoot>(&(tokens_.peek()));
scopeStack_.push(&root->scope());
// open hole for scan and print
auto voidType = BuiltInType::make(BuiltInType::BI_VOID, 0);
auto scanType = std::make_shared<FuncType>("scan", voidType);
auto printType = std::make_shared<FuncType>("print", voidType);
scanType->defined(true);
root->scope().insert("scan", scanType, nullptr);
root->scope().insert("print", printType, nullptr);
while (tokens_.peek().type() == Token::Semicolon)
tokens_.next();
while (errors_.count() < stopErrorNum && tokens_.peek().type() != Token::Eof) {
try {
// skip unnecessary ';'s
auto curr = tokens_.curr();
if (curr->type() == Token::Keyword &&
(curr->keyword() == Token::Struct ||
curr->keyword() == Token::Union ||
curr->keyword() == Token::Enum ||
curr->keyword() == Token::Typedef)) {
// this branch matches struct/union declaration and definition
root->add(parseTypeDeclOrDef());
} else {
if (isAboutType(*curr)) {
auto typeHead = parseTypeHead();
// if success then continue else exception
auto p2peek = tokens_.curr();
if (p2peek->type() == Token::Name
&& (p2peek + 1)->type() == Token::LParen) {
// function declaration or definition
root->add(parseFuncDeclOrDef(typeHead));
} else {
// var, array, pointer to array
root->add(parseVarDef(typeHead));
}
} else {
errors_.add(Error(&tokens_.peek(), "unrecognized token"));
skipErrorParts();
}
}
} catch (const Error& err) {
errors_.add(err);
skipErrorParts();
} catch (...) {
std::cerr << "Unknown exception. Bye." << std::endl;
std::exit(1);
}
while (tokens_.peek().type() == Token::Semicolon)
tokens_.next();
}
return root;
}
std::shared_ptr<CompoundDecl> Parser::parseCompoundDecl()
{
// struct/union name; has been parsed.
// so yi ma ping chuan
auto& startTok = tokens_.next();
CompoundType::MemModel memModel;
assert(startTok.type() == Token::Keyword);
if (startTok.keyword() == Token::Struct) {
memModel = CompoundType::Compound_Struct;
} else {
assert(startTok.keyword() == Token::Union);
memModel = CompoundType::Compound_Union;
}
auto& nameTok = tokens_.next();
assert(nameTok.type() == Token::Name);
auto& endTok = tokens_.next();
assert(endTok.type() == Token::Semicolon);
auto type = std::make_shared<IncompleteType>(nameTok.name(), memModel,
&currScope());
bool inserted = currScope().insert(nameTok.name(), type, &startTok);
if (!inserted) {
throw Error(&startTok, std::string("name ") + nameTok.name() + " has already been used.");
}
return std::make_shared<CompoundDecl>(&startTok, nameTok.name(), type);
}
std::shared_ptr<VarDef> Parser::parseVarDef(std::shared_ptr<Type> typeHead)
{
auto& startTok = tokens_.peek();
auto pair = parseTypeRest(std::move(typeHead));
if (pair.second.empty()) {
throw Error(&startTok, "a variable identifier is needed");
}
auto& type = pair.first;
if (Type::isVoid(type)) {
throw Error(&startTok, "variable of type void is not permitted");
}
auto inserted = currScope().insert(pair.second, pair.first, &startTok);
if (!inserted) {
errors_.add(Error(&startTok, std::string("name ") + pair.second + " has already been used"));
}
std::shared_ptr<Expr> initExpr;
if (tokens_.peek().type() == Token::Operator
&& tokens_.peek().getOperator() == Token::Assign) {
// init
// sth like: int a = 1 + 2;
tokens_.next();
initExpr = parseConditional();
}
auto def = std::make_shared<VarDef>(&startTok, pair.second, pair.first, initExpr);
if (tokens_.peek().type() != Token::Semicolon) {
errors_.add(Error(&tokens_.peek(), "miss ';' after variable definition"));
} else {
tokens_.next();
}
return def;
}
std::shared_ptr<EnumDef> Parser::parseEnumDef()
{
throw Error(&tokens_.peek(), "enum not supported yet");
}
std::shared_ptr<CompoundDef> Parser::parseCompoundDef()
{
// assume 'struct 'ident and '{ have been checked
auto& startTok = tokens_.next();
assert(startTok.type() == Token::Keyword);
CompoundType::MemModel memModel;
if (startTok.keyword() == Token::Struct) {
memModel = CompoundType::Compound_Struct;
} else {
assert(startTok.keyword() == Token::Union);
memModel = CompoundType::Compound_Union;
}
auto& nameTok = tokens_.next();
assert(nameTok.type() == Token::Name);
const std::string& name = nameTok.name();
auto& lbraceTok = tokens_.next();
assert(lbraceTok.type() == Token::LBrace);
// to support behavior like this:
// struct node { int data; node* next; };
auto ent = currScope().findInCurr(name);
if (ent) {
if (ent->type->tag() != Type::Incomplete
|| static_cast<IncompleteType*>(ent->type.get())->model() != memModel) {
skipUntil(Token::RBracket);
throw Error(&nameTok, std::string("name ") + name + " has already been used");
}
} else {
auto fwdType = std::make_shared<IncompleteType>(name, memModel, &currScope());
if (!currScope().insert(name, fwdType, &startTok)) {
skipUntil(Token::RBracket);
throw Error(&nameTok, std::string("name ") + name + " has already been used");
}
}
ListSymtab members;
// auto type = std::make_shared<CompoundType>(name, memModel, &currScope());
while (true) {
if (tokens_.peek().type() == Token::RBrace) {
tokens_.next();
if (tokens_.peek().type() == Token::Semicolon) {
tokens_.next();
} else {
errors_.add(Error(&tokens_.peek(), "miss ; after struct/union definition"));
}
auto type = std::make_shared<CompoundType>(name, memModel, &currScope(), std::move(members));
// insert into symbol table
auto shouldReplace = [memModel](const Type& ty) -> bool {
if (ty.tag() == Type::Incomplete) {
return static_cast<IncompleteType const*>(&ty)->model() == memModel;
} else
return false;
};
auto inserted =
currScope().insertOrConditionalAssign(name, type, &startTok, shouldReplace);
if (!inserted) {
throw Error(&startTok, std::string("name ") + name + "has already been used");
}
auto def = std::make_shared<CompoundDef>(&startTok, name, type);
return def;
} else {
try {
auto& begTok = tokens_.peek();
auto member = parseCompleteType();
if (member.second.size() == 0) {
errors_.add(Error(&tokens_.peek(),
"an identifier is needed in data member declaration"));
}
auto inserted = members.insert(member.second, member.first, &begTok);
// auto inserted = type->members().insert(member.second, member.first, &begTok);
if (!inserted) {
// duplicate
errors_.add(Error(&begTok,
std::string("variable ") + member.second + " is already a data member"));
}
if (tokens_.peek().type() == Token::Semicolon) {
tokens_.next();
} else {
errors_.add(Error(&tokens_.peek(), "miss ; after data member definition"));
}
} catch (Error& err) {
skipUntil(Token::Semicolon);
while (tokens_.peek().type() == Token::Semicolon) {
tokens_.next();
}
errors_.add(err);
}
}
}
}
// when no name, string is ""
std::pair<std::shared_ptr<Type>, std::string>
Parser::parseCompleteType()
{
auto head = parseTypeHead();
return parseTypeRest(head);
}
std::pair<std::shared_ptr<Type>, std::string>
Parser::parseTypeRest(std::shared_ptr<Type> typeHead)
{
// helper class
struct Emptyable
{
int val;
bool empty;
Emptyable(bool e, int a) : empty(e), val(a)
{}
};
auto& tokens = tokens_;
auto getDimensions = [&tokens]() -> std::stack<Emptyable> {
std::stack<Emptyable> dims;
assert(tokens.peek().type() == Token::LBracket);
do {
tokens.next();
if (tokens.peek().type() == Token::IntLiteral) {
dims.push(Emptyable(false, tokens.peek().intLiteral()));
tokens.next();
if (tokens.peek().type() == Token::RBracket) {
tokens.next();
} else {
// miss ']'
throw Error(&tokens.peek(), "miss ] in array declaration");
}
} else if (tokens.peek().type() == Token::RBracket) {
// sth like int arr[]
dims.push(Emptyable{true, 0});
tokens.next();
} else {
throw Error(&tokens.peek(), "incompatible subscript type in array declaration");
}
} while (tokens.peek().type() == Token::LBracket);
return dims;
};
auto& startTok = tokens_.peek();
std::string name;
std::shared_ptr<Type> ret = std::move(typeHead);
if (tokens_.peek().type() == Token::Name) {
name = tokens_.peek().name();
tokens_.next();
// TODO ...
}
if (tokens_.peek().type() == Token::LBracket) {
// parse array
auto dims = getDimensions();
while (!dims.empty()) {
Emptyable dim = dims.top();
dims.pop();
if (!dim.empty) {
if (dim.val <= 0) {
errors_.add(Error(&startTok, "array dimension should not be 0 or negative"));
}
ret = std::make_shared<ArrayType>(ret, dim.val, 0);
} else {
if (dims.empty()) {
// first dimension
ret = std::make_shared<PointerType>(ret, 0);
} else {
throw Error(&startTok, "array dimension should not be empty");
}
}
}
// return { ret, name };
} else if (tokens_.peek().type() == Token::LParen) {
// int (*a)[2];
tokens_.next();
if (tokens_.peek().type() == Token::Operator
&& tokens_.peek().getOperator() == Token::Mult) {
tokens_.next();
if (tokens_.peek().type() == Token::Name) {
name = tokens_.peek().name();
tokens_.next();
}
if (tokens_.peek().type() != Token::RParen) {
throw Error(&tokens_.peek(), "miss ')'");
} else
tokens_.next();
if (tokens_.peek().type() != Token::LBracket) {
throw Error(&tokens_.peek(), "complex type decl is not supported");
}
auto dims = getDimensions();
while (!dims.empty()) {
auto dim = dims.top();
dims.pop();
if (!dim.empty) {
if (dim.val <= 0) {
errors_.add(Error(&startTok, "array dimension should not be 0 or negative"));
}
ret = std::make_shared<ArrayType>(ret, dim.val);
} else {
throw Error(&startTok, "array dimension should not be empty");
}
}
ret = std::make_shared<PointerType>(ret, 0);
// return {ret, name};
} else {
throw Error(&startTok, "array dimension should not be empty");
}
}
// auto& currTok = tokens_.peek();
// if (currTok.type() != Token::Semicolon || currTok.type() != Token::Comma) {
// throw Error(&currTok, "cannot parse token after type declaration");
// }
return {ret, name};
}
std::shared_ptr<Type> Parser::parseTypeHead()
{
// type that is not array/function/...
// bool isStatic = false; // WARNING : will not support static
auto& p = tokens_.peek();
if (p.type() == Token::Keyword && p.keyword() == Token::Static) {
// isStatic = true;
tokens_.next();
}
std::shared_ptr<Type> baseType = parseBasicType();
// now for pointers
std::shared_ptr<Type> ret = baseType;
while (tokens_.peek().type() == Token::Operator
&& tokens_.peek().getOperator() == Token::Mult) {
Type::QualifierHolder qh = 0;
tokens_.next();
if (tokens_.peek().type() == Token::Keyword
&& tokens_.peek().keyword() == Token::Const) {
tokens_.next();
qh |= Type::Const;
}
ret = std::make_shared<PointerType>(ret, qh);
}
return ret;
}
std::shared_ptr<Type> Parser::parseBasicType()
{
// type that is not pointer/array/... and not static
Type::QualifierHolder qh = 0;
BuiltInType::SpecifierHolder sh = 0;
std::shared_ptr<Type> baseType;
auto& tmpTok = tokens_.peek();
while (tokens_.peek().type() == Token::Keyword
&& tokens_.peek().keyword() == Token::Const) {
qh |= Type::Const;
tokens_.next();
}
if (isTypeSpecifier(tokens_.peek())) {
sh |= parseSpecifierList(); // something like unsigned long int
// sth like char const
while (tokens_.peek().type() == Token::Keyword
&& tokens_.peek().keyword() == Token::Const) {
qh |= Type::Const;
tokens_.next();
}
auto ty = BuiltInType::make(sh, qh); // factor
if (!ty) {
throw Error(&tmpTok, "Invalid type specification");
}
baseType = ty;
} else if (tokens_.peek().type() == Token::Name) {
auto& tok = tokens_.peek();
auto ent = currScope().find(tok.name());
if (ent && isUserDefinedType(ent->type->tag())) {
// type name
tokens_.next();
if (tokens_.peek().type() == Token::Keyword
&& tokens_.peek().keyword() == Token::Const) {
qh |= Type::Const;
tokens_.next();
}
SymbolTable* whereDefined;
if (ent->type->tag() == Type::Incomplete) {
whereDefined = static_cast<IncompleteType*>(ent->type.get())->whereDefined();
} else if (ent->type->tag() == Type::Compound) {
whereDefined = static_cast<CompoundType*>(ent->type.get())->whereDefined();
} else assert(false);
baseType = std::make_shared<UserDefinedTypeRef>(tok.name(),
whereDefined, qh, ent->type->width());
} else {
throw Error(&tok, "Invalid type specification");
}
} else {
throw Error(&tmpTok, "Invalid type specification");
}
return baseType;
}
BuiltInType::SpecifierHolder Parser::parseSpecifierList()
{
static constexpr BuiltInType::BuiltInSpecifier kwdToSpec[8] = {
BuiltInType::BI_Unsigned, BuiltInType::BI_Long, BuiltInType::BI_Short,
BuiltInType::BI_Int, BuiltInType::BI_Char, BuiltInType::BI_Double,
BuiltInType::BI_Float, BuiltInType::BI_VOID
};
BuiltInType::SpecifierHolder sh = 0;
while (tokens_.hasNext()) {
auto& tok = tokens_.next();
if (tok.type() == Token::Keyword) {
auto kwd = tok.keyword();
if ((int) kwd <= (int) Token::Void) {
sh |= kwdToSpec[(int) kwd];
} else {
tokens_.putBack();
break;
}
} else {
tokens_.putBack();
break;
}
}
return sh;
}
std::pair<std::shared_ptr<FuncType>, std::vector<std::string>>
Parser::parseFuncHead(std::shared_ptr<Type> retType)
{
// assume that return type has already been parsed
assert(tokens_.peek().type() == Token::Name);
std::string funcName = tokens_.next().name();
auto& tmpTok = tokens_.peek();
auto funcType = std::make_shared<FuncType>(funcName, retType);
std::vector<std::string> names;
// parse parameter list
assert(tokens_.peek().type() == Token::LParen);
tokens_.next();
if (tokens_.peek().type() == Token::RParen) {
tokens_.next();
} else if (tokens_.peek().type() == Token::VarArgs) {
funcType->hasVarArgs(true);
tokens_.next();
if (tokens_.peek().type() != Token::RParen) {
throw Error(&tokens_.peek(), "the varargs indicator should be the last param");
} else {
tokens_.next();
}
} else if (isAboutType(tokens_.peek())) {
auto param = parseCompleteType();
funcType->addParam(param.first);
names.push_back(param.second);
while (true) {
if (tokens_.peek().type() == Token::RParen) {
tokens_.next();
break;
} else if (tokens_.peek().type() == Token::Comma) {
tokens_.next();
if (tokens_.peek().type() == Token::VarArgs) {
funcType->hasVarArgs(true);
tokens_.next();
if (tokens_.peek().type() != Token::RParen) {
throw Error(&tokens_.peek(), "the varargs indicator should be the last param");
} else {
tokens_.next();
break;
}
} else {
auto param = parseCompleteType();
funcType->addParam(param.first);
names.push_back(param.second);
}
} else {
throw Error(&tokens_.peek(), "expect ',' or ')'");
}
}
} else {
throw Error(&tokens_.peek(), "expect empty or parameter list");
}
return {funcType, names};
}
std::shared_ptr<FuncDef> Parser::parseFuncDef(
std::pair<std::shared_ptr<FuncType>, std::vector<std::string>>& headInfo,
const Token* startTok)
{
assert(tokens_.peek().type() == Token::LBrace);
auto& type = headInfo.first;
auto& paramVec = headInfo.second;
auto& funcName = type->name();
assert(paramVec.size() == type->paramCount());
auto nameIt = paramVec.begin();
auto nameEnd = paramVec.end();
auto typeIt = type->begin();
auto typeEnd = type->end();
ListSymtab params(&currScope()); // outer scope
for (; nameIt != nameEnd; ++nameIt, ++typeIt) {
if (!params.insert(*nameIt, *typeIt, nullptr)) { // function arg. nullptr is ok
errors_.add(Error(startTok, "duplicate parameter name"));
}
}
type->defined(true);
auto def = std::make_shared<FuncDef>(startTok, funcName, type, std::move(params));
auto funcBody = parseBlock(&def->params(), true);
// TODO : baocuo
def->body(funcBody);
// refresh symbol table
auto status = currScope().insertOrConditionalAssign(
funcName, type, startTok, [&type](Type& ty) -> bool {
if (ty.tag() == Type::Func) {
auto p = static_cast<FuncType*>(&ty);
return p->equal(type);
} else return false;
});
if (!status) {
throw Error(startTok, std::string("function name ") + funcName + " has already been used");
}
return def;
}
std::shared_ptr<ASTNode> Parser::parseFuncDeclOrDef(std::shared_ptr<Type> retType)
{
// assume return type has been parsed.
auto& tok = tokens_.peek();
auto headInfo = parseFuncHead(std::move(retType));
if (tokens_.peek().type() == Token::Semicolon) {
// func decl
auto& type = headInfo.first;
if (tokens_.peek().type() == Token::Semicolon) {
tokens_.next();
auto inserted = currScope().insert(type->name(), type, &tok);
if (!inserted) {
errors_.add(Error(&tok, std::string("name ") + type->name() + " has already been used"));
}
} else {
errors_.add(Error(&tokens_.peek(), "miss ';' after function declaration"));
}
auto decl = std::make_shared<FuncDecl>(&tok, type->name(), type);
return decl;
} else if (tokens_.peek().type() == Token::LBrace) {
// function def {
return parseFuncDef(headInfo, &tok);
} else {
throw Error(&tokens_.peek(), "unexpected character after function head");
}
}
std::shared_ptr<Block> Parser::parseBlock(SymbolTable* outer, bool isFuncBody)
{
// block : a new scope
auto& startTok = tokens_.peek();
assert(startTok.type() == Token::LBrace); // {
tokens_.next();
std::shared_ptr<Block> block = std::make_shared<Block>(&startTok, outer, isFuncBody);
scopeStack_.push(&block->scope());
while (tokens_.peek().type() == Token::Semicolon)
tokens_.next();
while (tokens_.peek().type() != Token::Eof &&
tokens_.peek().type() != Token::RBrace) {
// skip unnecessary ';'s
try {
auto curr = tokens_.curr();
if (curr->type() == Token::Keyword &&
(curr->keyword() == Token::Struct ||
curr->keyword() == Token::Union ||
curr->keyword() == Token::Enum ||
curr->keyword() == Token::Typedef)) {
// this branch matches struct/union declaration and definition
block->add(parseTypeDeclOrDef());
} else if (isAboutType(*curr)) {
auto typeHead = parseTypeHead();
// if success then continue else exception
auto p2peek = tokens_.curr();
if (p2peek->type() == Token::Name
&& (p2peek + 1)->type() == Token::LParen) {
// function declaration or definition
block->add(parseFuncDeclOrDef(typeHead));
errors_.add(Error(&(*p2peek),
"function decl or def is not allowed in a local scope"));
} else {
// var, array, pointer to array
block->add(parseVarDef(typeHead));
}
} else {
block->add(parseStmt());
}
} catch (Error& err) {
errors_.add(err);
skipErrorParts();
} // end catch
while (tokens_.peek().type() == Token::Semicolon)
tokens_.next();
} // end while
if (tokens_.peek().type() == Token::RBrace) {
tokens_.next();
} else {
throw Error(&tokens_.peek(), "miss '}' after block statements");
}
scopeStack_.pop();
return block;
}
std::shared_ptr<Expr> Parser::parseExpr()
{
// semicolon is processed in function parseBlock
return parseAssignment();
}
std::shared_ptr<Expr> Parser::parsePostfix(std::shared_ptr<Expr> prev)
{
std::shared_ptr<Expr> ret;
if (tokens_.peek().type() == Token::LParen) {
// func call
auto callOpTok = &tokens_.peek();
if (prev->tag() != ExprTag::Var) {
throw Error(&tokens_.peek(), "callable object except function is not implemented");
}
std::vector<std::shared_ptr<Expr>> args;
tokens_.next();
while (true) {
if (tokens_.peek().type() == Token::RParen) {
tokens_.next();
break;
} else if (tokens_.peek().type() == Token::Comma) {
tokens_.next();
} else {
args.emplace_back(parseExpr());
}
}
/// need recursion: func().a;
ret = std::make_shared<FuncCallExpr>(callOpTok,
static_cast<VarExpr*>(prev.get())->varName(),
std::move(args));
return parsePostfix(ret);
} else if (tokens_.peek().type() == Token::LBracket) {
// a[2][3]
ret = prev;
while (tokens_.peek().type() == Token::LBracket) {
auto bracketTok = &tokens_.peek();
tokens_.next();
ret = std::make_shared<ArrayRefExpr>(bracketTok, std::move(ret), parseExpr());
if (tokens_.peek().type() != Token::RBracket) {
throw Error(&tokens_.peek(), "miss ']' in array reference");
}
tokens_.next();
}
} else if (tokens_.peek().type() == Token::Operator &&
(tokens_.peek().getOperator() == Token::Dot ||
tokens_.peek().getOperator() == Token::Arrow)) {
ret = parseMemberExtract(prev, &tokens_.peek());
} else {
/// recursion base
return prev;
}
return parsePostfix(ret);
}
std::shared_ptr<Expr> Parser::parsePrimary()
{
auto& tok = tokens_.peek();
if ((int)tok.type() >= (int)Token::IntLiteral
&& (int)tok.type() <= (int)Token::UnsignedLongLongLiteral) {
// literal
// unsigned long long not supported though
tokens_.next();
return std::make_shared<LiteralExpr>(&tok);
} else if (tok.type() == Token::Name) {
// may be variable
auto nameExpr = std::make_shared<VarExpr>(&tok, tok.name());
tokens_.next();
return parsePostfix(nameExpr);
} else if (tok.type() == Token::LParen) {
// (expr)
tokens_.next();
auto inside = parseExpr();
if (tokens_.peek().type() != Token::RParen) {
throw Error(&tokens_.peek(), "miss ')' in expression");
}
tokens_.next();
return parsePostfix(inside);
} else {
throw Error(&tok, "unrecognized primary expression");
}
}
std::shared_ptr<MemberExpr>
Parser::parseMemberExtract(std::shared_ptr<Expr> suffix, Token const* first)
{
assert(tokens_.peek().type() == Token::Operator);
std::shared_ptr<MemberExpr> ret;
if (tokens_.peek().getOperator() == Token::Dot) {
tokens_.next();
if (tokens_.peek().type() == Token::Name) {
ret = std::make_shared<MemberExpr>(first, suffix, tokens_.peek().name());
tokens_.next();
} else {
throw Error(&tokens_.peek(), "expect an identifier in member extract");
}
} else {
assert(tokens_.peek().getOperator() == Token::Arrow);
// foo->x to (*foo).x
tokens_.next();
if (tokens_.peek().type() == Token::Name) {
auto data = std::make_shared<UnaryOpExpr>(first, suffix, Token::OperatorType::Mult);
ret = std::make_shared<MemberExpr>(first, data, tokens_.peek().name());
tokens_.next();
} else {
throw Error(&tokens_.peek(), "expect an identifier in member extract");
}
}
auto& peek = tokens_.peek();
if (peek.type() == Token::Operator &&
(peek.getOperator() == Token::Dot || peek.getOperator() == Token::Arrow)) {
ret = parseMemberExtract(ret, first);
}
return ret;
}
std::shared_ptr<Expr> Parser::parsePrefix()
{
auto& startTok = tokens_.peek();
if (startTok.type() == Token::Operator) {
auto op = startTok.getOperator();
switch(op) {
case Token::Add:
case Token::Sub:
case Token::Not:
case Token::BitInv: /* ~ */
case Token::Mult:
case Token::BitAnd: /* &, address of */
tokens_.next();
return std::make_shared<UnaryOpExpr>(&startTok, /** recursive */ parsePrefix(), op);
break;
default:
throw Error(&startTok, "not a unary operator");
break;
}
} else if (startTok.type() == Token::LParen) {
// (type cast)
auto next = tokens_.curr() + 1;
if (isAboutType(*next)) {
tokens_.next(); // skip (
auto ty = parseTypeHead();
if (tokens_.peek().type() != Token::RParen) {
throw Error(&tokens_.peek(), "miss ')' in type cast");
}
tokens_.next();
return std::make_shared<CastExpr>(&startTok, ty, /** recursive */ parsePrefix());
} else {
return parsePrimary();
}
} else if (startTok.type() == Token::Keyword &&
startTok.keyword() == Token::Sizeof) {
tokens_.next();
if (tokens_.peek().type() != Token::LParen) {
throw Error(&tokens_.peek(), "miss '(' after sizeof");
}
tokens_.next();
auto ty_nm = parseCompleteType();
if (!ty_nm.second.empty()) {
throw Error(&startTok, "complete variable definition is not allowed in sizeof expr");
}
if (tokens_.peek().type() != Token::RParen) {
throw Error(&tokens_.peek(), "miss ')' in sizeof expression");
}
return std::make_shared<SizeofExpr>(&startTok, ty_nm.first);
} else {
return parsePrimary();
}
}
std::shared_ptr<Expr> Parser::parseMultiplicative()
{
auto lhs = parsePrefix();
auto peek = &tokens_.peek();
while (peek->type() == Token::Operator &&
(peek->getOperator() == Token::Mult
|| peek->getOperator() == Token::Div
|| peek->getOperator() == Token::Mod)) {
auto op = peek->getOperator();
tokens_.next();
auto rhs = parsePrefix();
lhs = std::make_shared<BinaryOpExpr>(peek, lhs, rhs, op);
peek = &tokens_.peek();
}
return lhs;
}
std::shared_ptr<Expr> Parser::parseAdditive()
{
auto lhs = parseMultiplicative();
auto peek = &tokens_.peek();
while (peek->type() == Token::Operator &&
(peek->getOperator() == Token::Add
|| peek->getOperator() == Token::Sub)) {
auto op = peek->getOperator();
tokens_.next();
auto rhs = parseMultiplicative();
lhs = std::make_shared<BinaryOpExpr>(peek, lhs, rhs, op);
peek = &tokens_.peek();
}
return lhs;
}
std::shared_ptr<Expr> Parser::parseShift()
{
auto lhs = parseAdditive();
auto peek = &tokens_.peek();
while (peek->type() == Token::Operator &&
(peek->getOperator() == Token::SftL
|| peek->getOperator() == Token::SftR)) {
auto op = peek->getOperator();
tokens_.next();
auto rhs = parseAdditive();
lhs = std::make_shared<BinaryOpExpr>(peek, lhs, rhs, op);
peek = &tokens_.peek();
}
return lhs;
}
std::shared_ptr<Expr> Parser::parseRelational()
{
auto lhs = parseShift();
auto peek = &tokens_.peek();
while (peek->type() == Token::Operator &&
(peek->getOperator() == Token::Smlr
|| peek->getOperator() == Token::Grtr
|| peek->getOperator() == Token::Se
|| peek->getOperator() == Token::Ge)) {
auto op = peek->getOperator();
tokens_.next();
auto rhs = parseShift();
lhs = std::make_shared<BinaryOpExpr>(peek, lhs, rhs, op);
peek = &tokens_.peek();