This repository was archived by the owner on Nov 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathParseStmt.cpp
2276 lines (1957 loc) · 76.3 KB
/
ParseStmt.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
//===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Statement and Block portions of the Parser
// interface.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/Attributes.h"
#include "clang/Basic/PrettyStackTrace.h"
#include "clang/Parse/Parser.h"
#include "clang/Parse/RAIIObjectsForParser.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/LoopHint.h"
#include "clang/Sema/PrettyDeclStackTrace.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/TypoCorrection.h"
using namespace clang;
//===----------------------------------------------------------------------===//
// C99 6.8: Statements and Blocks.
//===----------------------------------------------------------------------===//
/// \brief Parse a standalone statement (for instance, as the body of an 'if',
/// 'while', or 'for').
StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc,
bool AllowOpenMPStandalone) {
StmtResult Res;
// We may get back a null statement if we found a #pragma. Keep going until
// we get an actual statement.
do {
StmtVector Stmts;
Res = ParseStatementOrDeclaration(
Stmts, AllowOpenMPStandalone ? ACK_StatementsOpenMPAnyExecutable
: ACK_StatementsOpenMPNonStandalone,
TrailingElseLoc);
} while (!Res.isInvalid() && !Res.get());
return Res;
}
/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
/// StatementOrDeclaration:
/// statement
/// declaration
///
/// statement:
/// labeled-statement
/// compound-statement
/// expression-statement
/// selection-statement
/// iteration-statement
/// jump-statement
/// [C++] declaration-statement
/// [C++] try-block
/// [MS] seh-try-block
/// [OBC] objc-throw-statement
/// [OBC] objc-try-catch-statement
/// [OBC] objc-synchronized-statement
/// [GNU] asm-statement
/// [OMP] openmp-construct [TODO]
///
/// labeled-statement:
/// identifier ':' statement
/// 'case' constant-expression ':' statement
/// 'default' ':' statement
///
/// selection-statement:
/// if-statement
/// switch-statement
///
/// iteration-statement:
/// while-statement
/// do-statement
/// for-statement
///
/// expression-statement:
/// expression[opt] ';'
///
/// jump-statement:
/// 'goto' identifier ';'
/// 'continue' ';'
/// 'break' ';'
/// 'return' expression[opt] ';'
/// [GNU] 'goto' '*' expression ';'
///
/// [OBC] objc-throw-statement:
/// [OBC] '@' 'throw' expression ';'
/// [OBC] '@' 'throw' ';'
///
StmtResult
Parser::ParseStatementOrDeclaration(StmtVector &Stmts,
AllowedConstructsKind Allowed,
SourceLocation *TrailingElseLoc) {
ParenBraceBracketBalancer BalancerRAIIObj(*this);
ParsedAttributesWithRange Attrs(AttrFactory);
MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
if (!MaybeParseOpenCLUnrollHintAttribute(Attrs))
return StmtError();
StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
Stmts, Allowed, TrailingElseLoc, Attrs);
assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
"attributes on empty statement");
if (Attrs.empty() || Res.isInvalid())
return Res;
return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
}
namespace {
class StatementFilterCCC : public CorrectionCandidateCallback {
public:
StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
WantTypeSpecifiers = nextTok.isOneOf(tok::l_paren, tok::less, tok::l_square,
tok::identifier, tok::star, tok::amp);
WantExpressionKeywords =
nextTok.isOneOf(tok::l_paren, tok::identifier, tok::arrow, tok::period);
WantRemainingKeywords =
nextTok.isOneOf(tok::l_paren, tok::semi, tok::identifier, tok::l_brace);
WantCXXNamedCasts = false;
}
bool ValidateCandidate(const TypoCorrection &candidate) override {
if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
if (NextToken.is(tok::equal))
return candidate.getCorrectionDeclAs<VarDecl>();
if (NextToken.is(tok::period) &&
candidate.getCorrectionDeclAs<NamespaceDecl>())
return false;
return CorrectionCandidateCallback::ValidateCandidate(candidate);
}
private:
Token NextToken;
};
}
StmtResult
Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
AllowedConstructsKind Allowed, SourceLocation *TrailingElseLoc,
ParsedAttributesWithRange &Attrs) {
const char *SemiError = nullptr;
StmtResult Res;
// Cases in this switch statement should fall through if the parser expects
// the token to end in a semicolon (in which case SemiError should be set),
// or they directly 'return;' if not.
Retry:
tok::TokenKind Kind = Tok.getKind();
SourceLocation AtLoc;
switch (Kind) {
case tok::at: // May be a @try or @throw statement
{
ProhibitAttributes(Attrs); // TODO: is it correct?
AtLoc = ConsumeToken(); // consume @
return ParseObjCAtStatement(AtLoc);
}
case tok::code_completion:
Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
cutOffParsing();
return StmtError();
case tok::identifier: {
Token Next = NextToken();
if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
// identifier ':' statement
return ParseLabeledStatement(Attrs);
}
// Look up the identifier, and typo-correct it to a keyword if it's not
// found.
if (Next.isNot(tok::coloncolon)) {
// Try to limit which sets of keywords should be included in typo
// correction based on what the next token is.
if (TryAnnotateName(/*IsAddressOfOperand*/ false,
llvm::make_unique<StatementFilterCCC>(Next)) ==
ANK_Error) {
// Handle errors here by skipping up to the next semicolon or '}', and
// eat the semicolon if that's what stopped us.
SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
if (Tok.is(tok::semi))
ConsumeToken();
return StmtError();
}
// If the identifier was typo-corrected, try again.
if (Tok.isNot(tok::identifier))
goto Retry;
}
// Fall through
LLVM_FALLTHROUGH;
}
default: {
if ((getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt ||
Allowed == ACK_Any) &&
isDeclarationStatement()) {
SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
DeclGroupPtrTy Decl = ParseDeclaration(Declarator::BlockContext,
DeclEnd, Attrs);
return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
}
if (Tok.is(tok::r_brace)) {
Diag(Tok, diag::err_expected_statement);
return StmtError();
}
return ParseExprStatement();
}
case tok::kw_case: // C99 6.8.1: labeled-statement
return ParseCaseStatement();
case tok::kw_default: // C99 6.8.1: labeled-statement
return ParseDefaultStatement();
case tok::l_brace: // C99 6.8.2: compound-statement
return ParseCompoundStatement();
case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
}
case tok::kw_if: // C99 6.8.4.1: if-statement
return ParseIfStatement(TrailingElseLoc);
case tok::kw_switch: // C99 6.8.4.2: switch-statement
return ParseSwitchStatement(TrailingElseLoc);
case tok::kw_while: // C99 6.8.5.1: while-statement
return ParseWhileStatement(TrailingElseLoc);
case tok::kw_do: // C99 6.8.5.2: do-statement
Res = ParseDoStatement();
SemiError = "do/while";
break;
case tok::kw_for: // C99 6.8.5.3: for-statement
return ParseForStatement(TrailingElseLoc);
case tok::kw_goto: // C99 6.8.6.1: goto-statement
Res = ParseGotoStatement();
SemiError = "goto";
break;
case tok::kw_continue: // C99 6.8.6.2: continue-statement
Res = ParseContinueStatement();
SemiError = "continue";
break;
case tok::kw_break: // C99 6.8.6.3: break-statement
Res = ParseBreakStatement();
SemiError = "break";
break;
case tok::kw_return: // C99 6.8.6.4: return-statement
Res = ParseReturnStatement();
SemiError = "return";
break;
case tok::kw_co_return: // C++ Coroutines: co_return statement
Res = ParseReturnStatement();
SemiError = "co_return";
break;
case tok::kw_asm: {
ProhibitAttributes(Attrs);
bool msAsm = false;
Res = ParseAsmStatement(msAsm);
Res = Actions.ActOnFinishFullStmt(Res.get());
if (msAsm) return Res;
SemiError = "asm";
break;
}
case tok::kw___if_exists:
case tok::kw___if_not_exists:
ProhibitAttributes(Attrs);
ParseMicrosoftIfExistsStatement(Stmts);
// An __if_exists block is like a compound statement, but it doesn't create
// a new scope.
return StmtEmpty();
case tok::kw_try: // C++ 15: try-block
return ParseCXXTryBlock();
case tok::kw___try:
ProhibitAttributes(Attrs); // TODO: is it correct?
return ParseSEHTryBlock();
case tok::kw___leave:
Res = ParseSEHLeaveStatement();
SemiError = "__leave";
break;
case tok::annot_pragma_vis:
ProhibitAttributes(Attrs);
HandlePragmaVisibility();
return StmtEmpty();
case tok::annot_pragma_pack:
ProhibitAttributes(Attrs);
HandlePragmaPack();
return StmtEmpty();
case tok::annot_pragma_msstruct:
ProhibitAttributes(Attrs);
HandlePragmaMSStruct();
return StmtEmpty();
case tok::annot_pragma_align:
ProhibitAttributes(Attrs);
HandlePragmaAlign();
return StmtEmpty();
case tok::annot_pragma_weak:
ProhibitAttributes(Attrs);
HandlePragmaWeak();
return StmtEmpty();
case tok::annot_pragma_weakalias:
ProhibitAttributes(Attrs);
HandlePragmaWeakAlias();
return StmtEmpty();
case tok::annot_pragma_redefine_extname:
ProhibitAttributes(Attrs);
HandlePragmaRedefineExtname();
return StmtEmpty();
case tok::annot_pragma_fp_contract:
ProhibitAttributes(Attrs);
Diag(Tok, diag::err_pragma_fp_contract_scope);
ConsumeAnnotationToken();
return StmtError();
case tok::annot_pragma_fp:
ProhibitAttributes(Attrs);
Diag(Tok, diag::err_pragma_fp_scope);
ConsumeAnnotationToken();
return StmtError();
case tok::annot_pragma_opencl_extension:
ProhibitAttributes(Attrs);
HandlePragmaOpenCLExtension();
return StmtEmpty();
case tok::annot_pragma_captured:
ProhibitAttributes(Attrs);
return HandlePragmaCaptured();
case tok::annot_pragma_openmp:
ProhibitAttributes(Attrs);
return ParseOpenMPDeclarativeOrExecutableDirective(Allowed);
case tok::annot_pragma_ms_pointers_to_members:
ProhibitAttributes(Attrs);
HandlePragmaMSPointersToMembers();
return StmtEmpty();
case tok::annot_pragma_ms_pragma:
ProhibitAttributes(Attrs);
HandlePragmaMSPragma();
return StmtEmpty();
case tok::annot_pragma_ms_vtordisp:
ProhibitAttributes(Attrs);
HandlePragmaMSVtorDisp();
return StmtEmpty();
case tok::annot_pragma_loop_hint:
ProhibitAttributes(Attrs);
return ParsePragmaLoopHint(Stmts, Allowed, TrailingElseLoc, Attrs);
case tok::annot_pragma_dump:
HandlePragmaDump();
return StmtEmpty();
case tok::annot_pragma_attribute:
HandlePragmaAttribute();
return StmtEmpty();
}
// If we reached this code, the statement must end in a semicolon.
if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
// If the result was valid, then we do want to diagnose this. Use
// ExpectAndConsume to emit the diagnostic, even though we know it won't
// succeed.
ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
// Skip until we see a } or ;, but don't eat it.
SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
}
return Res;
}
/// \brief Parse an expression statement.
StmtResult Parser::ParseExprStatement() {
// If a case keyword is missing, this is where it should be inserted.
Token OldToken = Tok;
ExprStatementTokLoc = Tok.getLocation();
// expression[opt] ';'
ExprResult Expr(ParseExpression());
if (Expr.isInvalid()) {
// If the expression is invalid, skip ahead to the next semicolon or '}'.
// Not doing this opens us up to the possibility of infinite loops if
// ParseExpression does not consume any tokens.
SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
if (Tok.is(tok::semi))
ConsumeToken();
return Actions.ActOnExprStmtError();
}
if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
Actions.CheckCaseExpression(Expr.get())) {
// If a constant expression is followed by a colon inside a switch block,
// suggest a missing case keyword.
Diag(OldToken, diag::err_expected_case_before_expression)
<< FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
// Recover parsing as a case statement.
return ParseCaseStatement(/*MissingCase=*/true, Expr);
}
// Otherwise, eat the semicolon.
ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
return Actions.ActOnExprStmt(Expr);
}
/// ParseSEHTryBlockCommon
///
/// seh-try-block:
/// '__try' compound-statement seh-handler
///
/// seh-handler:
/// seh-except-block
/// seh-finally-block
///
StmtResult Parser::ParseSEHTryBlock() {
assert(Tok.is(tok::kw___try) && "Expected '__try'");
SourceLocation TryLoc = ConsumeToken();
if (Tok.isNot(tok::l_brace))
return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
StmtResult TryBlock(ParseCompoundStatement(
/*isStmtExpr=*/false,
Scope::DeclScope | Scope::CompoundStmtScope | Scope::SEHTryScope));
if (TryBlock.isInvalid())
return TryBlock;
StmtResult Handler;
if (Tok.is(tok::identifier) &&
Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
SourceLocation Loc = ConsumeToken();
Handler = ParseSEHExceptBlock(Loc);
} else if (Tok.is(tok::kw___finally)) {
SourceLocation Loc = ConsumeToken();
Handler = ParseSEHFinallyBlock(Loc);
} else {
return StmtError(Diag(Tok, diag::err_seh_expected_handler));
}
if(Handler.isInvalid())
return Handler;
return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
TryLoc,
TryBlock.get(),
Handler.get());
}
/// ParseSEHExceptBlock - Handle __except
///
/// seh-except-block:
/// '__except' '(' seh-filter-expression ')' compound-statement
///
StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
raii2(Ident___exception_code, false),
raii3(Ident_GetExceptionCode, false);
if (ExpectAndConsume(tok::l_paren))
return StmtError();
ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
Scope::SEHExceptScope);
if (getLangOpts().Borland) {
Ident__exception_info->setIsPoisoned(false);
Ident___exception_info->setIsPoisoned(false);
Ident_GetExceptionInfo->setIsPoisoned(false);
}
ExprResult FilterExpr;
{
ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
Scope::SEHFilterScope);
FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
}
if (getLangOpts().Borland) {
Ident__exception_info->setIsPoisoned(true);
Ident___exception_info->setIsPoisoned(true);
Ident_GetExceptionInfo->setIsPoisoned(true);
}
if(FilterExpr.isInvalid())
return StmtError();
if (ExpectAndConsume(tok::r_paren))
return StmtError();
if (Tok.isNot(tok::l_brace))
return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
StmtResult Block(ParseCompoundStatement());
if(Block.isInvalid())
return Block;
return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
}
/// ParseSEHFinallyBlock - Handle __finally
///
/// seh-finally-block:
/// '__finally' compound-statement
///
StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
raii2(Ident___abnormal_termination, false),
raii3(Ident_AbnormalTermination, false);
if (Tok.isNot(tok::l_brace))
return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
ParseScope FinallyScope(this, 0);
Actions.ActOnStartSEHFinallyBlock();
StmtResult Block(ParseCompoundStatement());
if(Block.isInvalid()) {
Actions.ActOnAbortSEHFinallyBlock();
return Block;
}
return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
}
/// Handle __leave
///
/// seh-leave-statement:
/// '__leave' ';'
///
StmtResult Parser::ParseSEHLeaveStatement() {
SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
}
/// ParseLabeledStatement - We have an identifier and a ':' after it.
///
/// labeled-statement:
/// identifier ':' statement
/// [GNU] identifier ':' attributes[opt] statement
///
StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
"Not an identifier!");
Token IdentTok = Tok; // Save the whole token.
ConsumeToken(); // eat the identifier.
assert(Tok.is(tok::colon) && "Not a label!");
// identifier ':' statement
SourceLocation ColonLoc = ConsumeToken();
// Read label attributes, if present.
StmtResult SubStmt;
if (Tok.is(tok::kw___attribute)) {
ParsedAttributesWithRange TempAttrs(AttrFactory);
ParseGNUAttributes(TempAttrs);
// In C++, GNU attributes only apply to the label if they are followed by a
// semicolon, to disambiguate label attributes from attributes on a labeled
// declaration.
//
// This doesn't quite match what GCC does; if the attribute list is empty
// and followed by a semicolon, GCC will reject (it appears to parse the
// attributes as part of a statement in that case). That looks like a bug.
if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
attrs.takeAllFrom(TempAttrs);
else if (isDeclarationStatement()) {
StmtVector Stmts;
// FIXME: We should do this whether or not we have a declaration
// statement, but that doesn't work correctly (because ProhibitAttributes
// can't handle GNU attributes), so only call it in the one case where
// GNU attributes are allowed.
SubStmt = ParseStatementOrDeclarationAfterAttributes(
Stmts, /*Allowed=*/ACK_StatementsOpenMPNonStandalone, nullptr,
TempAttrs);
if (!TempAttrs.empty() && !SubStmt.isInvalid())
SubStmt = Actions.ProcessStmtAttributes(
SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
} else {
Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
}
}
// If we've not parsed a statement yet, parse one now.
if (!SubStmt.isInvalid() && !SubStmt.isUsable())
SubStmt = ParseStatement();
// Broken substmt shouldn't prevent the label from being added to the AST.
if (SubStmt.isInvalid())
SubStmt = Actions.ActOnNullStmt(ColonLoc);
LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
IdentTok.getLocation());
if (AttributeList *Attrs = attrs.getList()) {
Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
attrs.clear();
}
return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
SubStmt.get());
}
/// ParseCaseStatement
/// labeled-statement:
/// 'case' constant-expression ':' statement
/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
///
StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
// It is very very common for code to contain many case statements recursively
// nested, as in (but usually without indentation):
// case 1:
// case 2:
// case 3:
// case 4:
// case 5: etc.
//
// Parsing this naively works, but is both inefficient and can cause us to run
// out of stack space in our recursive descent parser. As a special case,
// flatten this recursion into an iterative loop. This is complex and gross,
// but all the grossness is constrained to ParseCaseStatement (and some
// weirdness in the actions), so this is just local grossness :).
// TopLevelCase - This is the highest level we have parsed. 'case 1' in the
// example above.
StmtResult TopLevelCase(true);
// DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
// gets updated each time a new case is parsed, and whose body is unset so
// far. When parsing 'case 4', this is the 'case 3' node.
Stmt *DeepestParsedCaseStmt = nullptr;
// While we have case statements, eat and stack them.
SourceLocation ColonLoc;
do {
SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
ConsumeToken(); // eat the 'case'.
ColonLoc = SourceLocation();
if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteCase(getCurScope());
cutOffParsing();
return StmtError();
}
/// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
/// Disable this form of error recovery while we're parsing the case
/// expression.
ColonProtectionRAIIObject ColonProtection(*this);
ExprResult LHS;
if (!MissingCase) {
LHS = ParseConstantExpression();
if (!getLangOpts().CPlusPlus11) {
LHS = Actions.CorrectDelayedTyposInExpr(LHS, [this](class Expr *E) {
return Actions.VerifyIntegerConstantExpression(E);
});
}
if (LHS.isInvalid()) {
// If constant-expression is parsed unsuccessfully, recover by skipping
// current case statement (moving to the colon that ends it).
if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
TryConsumeToken(tok::colon, ColonLoc);
continue;
}
return StmtError();
}
} else {
LHS = Expr;
MissingCase = false;
}
// GNU case range extension.
SourceLocation DotDotDotLoc;
ExprResult RHS;
if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
Diag(DotDotDotLoc, diag::ext_gnu_case_range);
RHS = ParseConstantExpression();
if (RHS.isInvalid()) {
if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
TryConsumeToken(tok::colon, ColonLoc);
continue;
}
return StmtError();
}
}
ColonProtection.restore();
if (TryConsumeToken(tok::colon, ColonLoc)) {
} else if (TryConsumeToken(tok::semi, ColonLoc) ||
TryConsumeToken(tok::coloncolon, ColonLoc)) {
// Treat "case blah;" or "case blah::" as a typo for "case blah:".
Diag(ColonLoc, diag::err_expected_after)
<< "'case'" << tok::colon
<< FixItHint::CreateReplacement(ColonLoc, ":");
} else {
SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Diag(ExpectedLoc, diag::err_expected_after)
<< "'case'" << tok::colon
<< FixItHint::CreateInsertion(ExpectedLoc, ":");
ColonLoc = ExpectedLoc;
}
StmtResult Case =
Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
RHS.get(), ColonLoc);
// If we had a sema error parsing this case, then just ignore it and
// continue parsing the sub-stmt.
if (Case.isInvalid()) {
if (TopLevelCase.isInvalid()) // No parsed case stmts.
return ParseStatement(/*TrailingElseLoc=*/nullptr,
/*AllowOpenMPStandalone=*/true);
// Otherwise, just don't add it as a nested case.
} else {
// If this is the first case statement we parsed, it becomes TopLevelCase.
// Otherwise we link it into the current chain.
Stmt *NextDeepest = Case.get();
if (TopLevelCase.isInvalid())
TopLevelCase = Case;
else
Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
DeepestParsedCaseStmt = NextDeepest;
}
// Handle all case statements.
} while (Tok.is(tok::kw_case));
// If we found a non-case statement, start by parsing it.
StmtResult SubStmt;
if (Tok.isNot(tok::r_brace)) {
SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
/*AllowOpenMPStandalone=*/true);
} else {
// Nicely diagnose the common error "switch (X) { case 4: }", which is
// not valid. If ColonLoc doesn't point to a valid text location, there was
// another parsing error, so avoid producing extra diagnostics.
if (ColonLoc.isValid()) {
SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
<< FixItHint::CreateInsertion(AfterColonLoc, " ;");
}
SubStmt = StmtError();
}
// Install the body into the most deeply-nested case.
if (DeepestParsedCaseStmt) {
// Broken sub-stmt shouldn't prevent forming the case statement properly.
if (SubStmt.isInvalid())
SubStmt = Actions.ActOnNullStmt(SourceLocation());
Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
}
// Return the top level parsed statement tree.
return TopLevelCase;
}
/// ParseDefaultStatement
/// labeled-statement:
/// 'default' ':' statement
/// Note that this does not parse the 'statement' at the end.
///
StmtResult Parser::ParseDefaultStatement() {
assert(Tok.is(tok::kw_default) && "Not a default stmt!");
SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
SourceLocation ColonLoc;
if (TryConsumeToken(tok::colon, ColonLoc)) {
} else if (TryConsumeToken(tok::semi, ColonLoc)) {
// Treat "default;" as a typo for "default:".
Diag(ColonLoc, diag::err_expected_after)
<< "'default'" << tok::colon
<< FixItHint::CreateReplacement(ColonLoc, ":");
} else {
SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Diag(ExpectedLoc, diag::err_expected_after)
<< "'default'" << tok::colon
<< FixItHint::CreateInsertion(ExpectedLoc, ":");
ColonLoc = ExpectedLoc;
}
StmtResult SubStmt;
if (Tok.isNot(tok::r_brace)) {
SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
/*AllowOpenMPStandalone=*/true);
} else {
// Diagnose the common error "switch (X) {... default: }", which is
// not valid.
SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
<< FixItHint::CreateInsertion(AfterColonLoc, " ;");
SubStmt = true;
}
// Broken sub-stmt shouldn't prevent forming the case statement properly.
if (SubStmt.isInvalid())
SubStmt = Actions.ActOnNullStmt(ColonLoc);
return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
SubStmt.get(), getCurScope());
}
StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
return ParseCompoundStatement(isStmtExpr,
Scope::DeclScope | Scope::CompoundStmtScope);
}
/// ParseCompoundStatement - Parse a "{}" block.
///
/// compound-statement: [C99 6.8.2]
/// { block-item-list[opt] }
/// [GNU] { label-declarations block-item-list } [TODO]
///
/// block-item-list:
/// block-item
/// block-item-list block-item
///
/// block-item:
/// declaration
/// [GNU] '__extension__' declaration
/// statement
///
/// [GNU] label-declarations:
/// [GNU] label-declaration
/// [GNU] label-declarations label-declaration
///
/// [GNU] label-declaration:
/// [GNU] '__label__' identifier-list ';'
///
StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
unsigned ScopeFlags) {
assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
// Enter a scope to hold everything within the compound stmt. Compound
// statements can always hold declarations.
ParseScope CompoundScope(this, ScopeFlags);
// Parse the statements in the body.
return ParseCompoundStatementBody(isStmtExpr);
}
/// Parse any pragmas at the start of the compound expression. We handle these
/// separately since some pragmas (FP_CONTRACT) must appear before any C
/// statement in the compound, but may be intermingled with other pragmas.
void Parser::ParseCompoundStatementLeadingPragmas() {
bool checkForPragmas = true;
while (checkForPragmas) {
switch (Tok.getKind()) {
case tok::annot_pragma_vis:
HandlePragmaVisibility();
break;
case tok::annot_pragma_pack:
HandlePragmaPack();
break;
case tok::annot_pragma_msstruct:
HandlePragmaMSStruct();
break;
case tok::annot_pragma_align:
HandlePragmaAlign();
break;
case tok::annot_pragma_weak:
HandlePragmaWeak();
break;
case tok::annot_pragma_weakalias:
HandlePragmaWeakAlias();
break;
case tok::annot_pragma_redefine_extname:
HandlePragmaRedefineExtname();
break;
case tok::annot_pragma_opencl_extension:
HandlePragmaOpenCLExtension();
break;
case tok::annot_pragma_fp_contract:
HandlePragmaFPContract();
break;
case tok::annot_pragma_fp:
HandlePragmaFP();
break;
case tok::annot_pragma_ms_pointers_to_members:
HandlePragmaMSPointersToMembers();
break;
case tok::annot_pragma_ms_pragma:
HandlePragmaMSPragma();
break;
case tok::annot_pragma_ms_vtordisp:
HandlePragmaMSVtorDisp();
break;
case tok::annot_pragma_dump:
HandlePragmaDump();
break;
default:
checkForPragmas = false;
break;
}
}
}
/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
/// consume the '}' at the end of the block. It does not manipulate the scope
/// stack.
StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Tok.getLocation(),
"in compound statement ('{}')");
// Record the state of the FP_CONTRACT pragma, restore on leaving the
// compound statement.
Sema::FPContractStateRAII SaveFPContractState(Actions);
InMessageExpressionRAIIObject InMessage(*this, false);
BalancedDelimiterTracker T(*this, tok::l_brace);
if (T.consumeOpen())
return StmtError();
Sema::CompoundScopeRAII CompoundScope(Actions);
// Parse any pragmas at the beginning of the compound statement.
ParseCompoundStatementLeadingPragmas();
StmtVector Stmts;
// "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
// only allowed at the start of a compound stmt regardless of the language.
while (Tok.is(tok::kw___label__)) {
SourceLocation LabelLoc = ConsumeToken();
SmallVector<Decl *, 8> DeclsInGroup;
while (1) {
if (Tok.isNot(tok::identifier)) {
Diag(Tok, diag::err_expected) << tok::identifier;
break;
}
IdentifierInfo *II = Tok.getIdentifierInfo();
SourceLocation IdLoc = ConsumeToken();
DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
if (!TryConsumeToken(tok::comma))
break;
}
DeclSpec DS(AttrFactory);
DeclGroupPtrTy Res =
Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
if (R.isUsable())
Stmts.push_back(R.get());
}
while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
Tok.isNot(tok::eof)) {
if (Tok.is(tok::annot_pragma_unused)) {
HandlePragmaUnused();
continue;
}