]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Parse/ParseStmt.cpp
MFV r306669:
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Parse / ParseStmt.cpp
1 //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Statement and Block portions of the Parser
11 // interface.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "clang/Parse/Parser.h"
16 #include "RAIIObjectsForParser.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/Basic/Attributes.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Basic/PrettyStackTrace.h"
21 #include "clang/Sema/DeclSpec.h"
22 #include "clang/Sema/LoopHint.h"
23 #include "clang/Sema/PrettyDeclStackTrace.h"
24 #include "clang/Sema/Scope.h"
25 #include "clang/Sema/TypoCorrection.h"
26 #include "llvm/ADT/SmallString.h"
27 using namespace clang;
28
29 //===----------------------------------------------------------------------===//
30 // C99 6.8: Statements and Blocks.
31 //===----------------------------------------------------------------------===//
32
33 /// \brief Parse a standalone statement (for instance, as the body of an 'if',
34 /// 'while', or 'for').
35 StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc,
36                                   bool AllowOpenMPStandalone) {
37   StmtResult Res;
38
39   // We may get back a null statement if we found a #pragma. Keep going until
40   // we get an actual statement.
41   do {
42     StmtVector Stmts;
43     Res = ParseStatementOrDeclaration(
44         Stmts, AllowOpenMPStandalone ? ACK_StatementsOpenMPAnyExecutable
45                                      : ACK_StatementsOpenMPNonStandalone,
46         TrailingElseLoc);
47   } while (!Res.isInvalid() && !Res.get());
48
49   return Res;
50 }
51
52 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
53 ///       StatementOrDeclaration:
54 ///         statement
55 ///         declaration
56 ///
57 ///       statement:
58 ///         labeled-statement
59 ///         compound-statement
60 ///         expression-statement
61 ///         selection-statement
62 ///         iteration-statement
63 ///         jump-statement
64 /// [C++]   declaration-statement
65 /// [C++]   try-block
66 /// [MS]    seh-try-block
67 /// [OBC]   objc-throw-statement
68 /// [OBC]   objc-try-catch-statement
69 /// [OBC]   objc-synchronized-statement
70 /// [GNU]   asm-statement
71 /// [OMP]   openmp-construct             [TODO]
72 ///
73 ///       labeled-statement:
74 ///         identifier ':' statement
75 ///         'case' constant-expression ':' statement
76 ///         'default' ':' statement
77 ///
78 ///       selection-statement:
79 ///         if-statement
80 ///         switch-statement
81 ///
82 ///       iteration-statement:
83 ///         while-statement
84 ///         do-statement
85 ///         for-statement
86 ///
87 ///       expression-statement:
88 ///         expression[opt] ';'
89 ///
90 ///       jump-statement:
91 ///         'goto' identifier ';'
92 ///         'continue' ';'
93 ///         'break' ';'
94 ///         'return' expression[opt] ';'
95 /// [GNU]   'goto' '*' expression ';'
96 ///
97 /// [OBC] objc-throw-statement:
98 /// [OBC]   '@' 'throw' expression ';'
99 /// [OBC]   '@' 'throw' ';'
100 ///
101 StmtResult
102 Parser::ParseStatementOrDeclaration(StmtVector &Stmts,
103                                     AllowedContsructsKind Allowed,
104                                     SourceLocation *TrailingElseLoc) {
105
106   ParenBraceBracketBalancer BalancerRAIIObj(*this);
107
108   ParsedAttributesWithRange Attrs(AttrFactory);
109   MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
110
111   StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
112       Stmts, Allowed, TrailingElseLoc, Attrs);
113
114   assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
115          "attributes on empty statement");
116
117   if (Attrs.empty() || Res.isInvalid())
118     return Res;
119
120   return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
121 }
122
123 namespace {
124 class StatementFilterCCC : public CorrectionCandidateCallback {
125 public:
126   StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
127     WantTypeSpecifiers = nextTok.isOneOf(tok::l_paren, tok::less, tok::l_square,
128                                          tok::identifier, tok::star, tok::amp);
129     WantExpressionKeywords =
130         nextTok.isOneOf(tok::l_paren, tok::identifier, tok::arrow, tok::period);
131     WantRemainingKeywords =
132         nextTok.isOneOf(tok::l_paren, tok::semi, tok::identifier, tok::l_brace);
133     WantCXXNamedCasts = false;
134   }
135
136   bool ValidateCandidate(const TypoCorrection &candidate) override {
137     if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
138       return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
139     if (NextToken.is(tok::equal))
140       return candidate.getCorrectionDeclAs<VarDecl>();
141     if (NextToken.is(tok::period) &&
142         candidate.getCorrectionDeclAs<NamespaceDecl>())
143       return false;
144     return CorrectionCandidateCallback::ValidateCandidate(candidate);
145   }
146
147 private:
148   Token NextToken;
149 };
150 }
151
152 StmtResult
153 Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
154           AllowedContsructsKind Allowed, SourceLocation *TrailingElseLoc,
155           ParsedAttributesWithRange &Attrs) {
156   const char *SemiError = nullptr;
157   StmtResult Res;
158
159   // Cases in this switch statement should fall through if the parser expects
160   // the token to end in a semicolon (in which case SemiError should be set),
161   // or they directly 'return;' if not.
162 Retry:
163   tok::TokenKind Kind  = Tok.getKind();
164   SourceLocation AtLoc;
165   switch (Kind) {
166   case tok::at: // May be a @try or @throw statement
167     {
168       ProhibitAttributes(Attrs); // TODO: is it correct?
169       AtLoc = ConsumeToken();  // consume @
170       return ParseObjCAtStatement(AtLoc);
171     }
172
173   case tok::code_completion:
174     Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
175     cutOffParsing();
176     return StmtError();
177
178   case tok::identifier: {
179     Token Next = NextToken();
180     if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
181       // identifier ':' statement
182       return ParseLabeledStatement(Attrs);
183     }
184
185     // Look up the identifier, and typo-correct it to a keyword if it's not
186     // found.
187     if (Next.isNot(tok::coloncolon)) {
188       // Try to limit which sets of keywords should be included in typo
189       // correction based on what the next token is.
190       if (TryAnnotateName(/*IsAddressOfOperand*/ false,
191                           llvm::make_unique<StatementFilterCCC>(Next)) ==
192           ANK_Error) {
193         // Handle errors here by skipping up to the next semicolon or '}', and
194         // eat the semicolon if that's what stopped us.
195         SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
196         if (Tok.is(tok::semi))
197           ConsumeToken();
198         return StmtError();
199       }
200
201       // If the identifier was typo-corrected, try again.
202       if (Tok.isNot(tok::identifier))
203         goto Retry;
204     }
205
206     // Fall through
207   }
208
209   default: {
210     if ((getLangOpts().CPlusPlus || Allowed == ACK_Any) &&
211         isDeclarationStatement()) {
212       SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
213       DeclGroupPtrTy Decl = ParseDeclaration(Declarator::BlockContext,
214                                              DeclEnd, Attrs);
215       return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
216     }
217
218     if (Tok.is(tok::r_brace)) {
219       Diag(Tok, diag::err_expected_statement);
220       return StmtError();
221     }
222
223     return ParseExprStatement();
224   }
225
226   case tok::kw_case:                // C99 6.8.1: labeled-statement
227     return ParseCaseStatement();
228   case tok::kw_default:             // C99 6.8.1: labeled-statement
229     return ParseDefaultStatement();
230
231   case tok::l_brace:                // C99 6.8.2: compound-statement
232     return ParseCompoundStatement();
233   case tok::semi: {                 // C99 6.8.3p3: expression[opt] ';'
234     bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
235     return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
236   }
237
238   case tok::kw_if:                  // C99 6.8.4.1: if-statement
239     return ParseIfStatement(TrailingElseLoc);
240   case tok::kw_switch:              // C99 6.8.4.2: switch-statement
241     return ParseSwitchStatement(TrailingElseLoc);
242
243   case tok::kw_while:               // C99 6.8.5.1: while-statement
244     return ParseWhileStatement(TrailingElseLoc);
245   case tok::kw_do:                  // C99 6.8.5.2: do-statement
246     Res = ParseDoStatement();
247     SemiError = "do/while";
248     break;
249   case tok::kw_for:                 // C99 6.8.5.3: for-statement
250     return ParseForStatement(TrailingElseLoc);
251
252   case tok::kw_goto:                // C99 6.8.6.1: goto-statement
253     Res = ParseGotoStatement();
254     SemiError = "goto";
255     break;
256   case tok::kw_continue:            // C99 6.8.6.2: continue-statement
257     Res = ParseContinueStatement();
258     SemiError = "continue";
259     break;
260   case tok::kw_break:               // C99 6.8.6.3: break-statement
261     Res = ParseBreakStatement();
262     SemiError = "break";
263     break;
264   case tok::kw_return:              // C99 6.8.6.4: return-statement
265     Res = ParseReturnStatement();
266     SemiError = "return";
267     break;
268   case tok::kw_co_return:            // C++ Coroutines: co_return statement
269     Res = ParseReturnStatement();
270     SemiError = "co_return";
271     break;
272
273   case tok::kw_asm: {
274     ProhibitAttributes(Attrs);
275     bool msAsm = false;
276     Res = ParseAsmStatement(msAsm);
277     Res = Actions.ActOnFinishFullStmt(Res.get());
278     if (msAsm) return Res;
279     SemiError = "asm";
280     break;
281   }
282
283   case tok::kw___if_exists:
284   case tok::kw___if_not_exists:
285     ProhibitAttributes(Attrs);
286     ParseMicrosoftIfExistsStatement(Stmts);
287     // An __if_exists block is like a compound statement, but it doesn't create
288     // a new scope.
289     return StmtEmpty();
290
291   case tok::kw_try:                 // C++ 15: try-block
292     return ParseCXXTryBlock();
293
294   case tok::kw___try:
295     ProhibitAttributes(Attrs); // TODO: is it correct?
296     return ParseSEHTryBlock();
297
298   case tok::kw___leave:
299     Res = ParseSEHLeaveStatement();
300     SemiError = "__leave";
301     break;
302
303   case tok::annot_pragma_vis:
304     ProhibitAttributes(Attrs);
305     HandlePragmaVisibility();
306     return StmtEmpty();
307
308   case tok::annot_pragma_pack:
309     ProhibitAttributes(Attrs);
310     HandlePragmaPack();
311     return StmtEmpty();
312
313   case tok::annot_pragma_msstruct:
314     ProhibitAttributes(Attrs);
315     HandlePragmaMSStruct();
316     return StmtEmpty();
317
318   case tok::annot_pragma_align:
319     ProhibitAttributes(Attrs);
320     HandlePragmaAlign();
321     return StmtEmpty();
322
323   case tok::annot_pragma_weak:
324     ProhibitAttributes(Attrs);
325     HandlePragmaWeak();
326     return StmtEmpty();
327
328   case tok::annot_pragma_weakalias:
329     ProhibitAttributes(Attrs);
330     HandlePragmaWeakAlias();
331     return StmtEmpty();
332
333   case tok::annot_pragma_redefine_extname:
334     ProhibitAttributes(Attrs);
335     HandlePragmaRedefineExtname();
336     return StmtEmpty();
337
338   case tok::annot_pragma_fp_contract:
339     ProhibitAttributes(Attrs);
340     Diag(Tok, diag::err_pragma_fp_contract_scope);
341     ConsumeToken();
342     return StmtError();
343
344   case tok::annot_pragma_opencl_extension:
345     ProhibitAttributes(Attrs);
346     HandlePragmaOpenCLExtension();
347     return StmtEmpty();
348
349   case tok::annot_pragma_captured:
350     ProhibitAttributes(Attrs);
351     return HandlePragmaCaptured();
352
353   case tok::annot_pragma_openmp:
354     ProhibitAttributes(Attrs);
355     return ParseOpenMPDeclarativeOrExecutableDirective(Allowed);
356
357   case tok::annot_pragma_ms_pointers_to_members:
358     ProhibitAttributes(Attrs);
359     HandlePragmaMSPointersToMembers();
360     return StmtEmpty();
361
362   case tok::annot_pragma_ms_pragma:
363     ProhibitAttributes(Attrs);
364     HandlePragmaMSPragma();
365     return StmtEmpty();
366
367   case tok::annot_pragma_ms_vtordisp:
368     ProhibitAttributes(Attrs);
369     HandlePragmaMSVtorDisp();
370     return StmtEmpty();
371
372   case tok::annot_pragma_loop_hint:
373     ProhibitAttributes(Attrs);
374     return ParsePragmaLoopHint(Stmts, Allowed, TrailingElseLoc, Attrs);
375
376   case tok::annot_pragma_dump:
377     HandlePragmaDump();
378     return StmtEmpty();
379   }
380
381   // If we reached this code, the statement must end in a semicolon.
382   if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
383     // If the result was valid, then we do want to diagnose this.  Use
384     // ExpectAndConsume to emit the diagnostic, even though we know it won't
385     // succeed.
386     ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
387     // Skip until we see a } or ;, but don't eat it.
388     SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
389   }
390
391   return Res;
392 }
393
394 /// \brief Parse an expression statement.
395 StmtResult Parser::ParseExprStatement() {
396   // If a case keyword is missing, this is where it should be inserted.
397   Token OldToken = Tok;
398
399   // expression[opt] ';'
400   ExprResult Expr(ParseExpression());
401   if (Expr.isInvalid()) {
402     // If the expression is invalid, skip ahead to the next semicolon or '}'.
403     // Not doing this opens us up to the possibility of infinite loops if
404     // ParseExpression does not consume any tokens.
405     SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
406     if (Tok.is(tok::semi))
407       ConsumeToken();
408     return Actions.ActOnExprStmtError();
409   }
410
411   if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
412       Actions.CheckCaseExpression(Expr.get())) {
413     // If a constant expression is followed by a colon inside a switch block,
414     // suggest a missing case keyword.
415     Diag(OldToken, diag::err_expected_case_before_expression)
416       << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
417
418     // Recover parsing as a case statement.
419     return ParseCaseStatement(/*MissingCase=*/true, Expr);
420   }
421
422   // Otherwise, eat the semicolon.
423   ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
424   return Actions.ActOnExprStmt(Expr);
425 }
426
427 /// ParseSEHTryBlockCommon
428 ///
429 /// seh-try-block:
430 ///   '__try' compound-statement seh-handler
431 ///
432 /// seh-handler:
433 ///   seh-except-block
434 ///   seh-finally-block
435 ///
436 StmtResult Parser::ParseSEHTryBlock() {
437   assert(Tok.is(tok::kw___try) && "Expected '__try'");
438   SourceLocation TryLoc = ConsumeToken();
439
440   if (Tok.isNot(tok::l_brace))
441     return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
442
443   StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
444                       Scope::DeclScope | Scope::SEHTryScope));
445   if(TryBlock.isInvalid())
446     return TryBlock;
447
448   StmtResult Handler;
449   if (Tok.is(tok::identifier) &&
450       Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
451     SourceLocation Loc = ConsumeToken();
452     Handler = ParseSEHExceptBlock(Loc);
453   } else if (Tok.is(tok::kw___finally)) {
454     SourceLocation Loc = ConsumeToken();
455     Handler = ParseSEHFinallyBlock(Loc);
456   } else {
457     return StmtError(Diag(Tok, diag::err_seh_expected_handler));
458   }
459
460   if(Handler.isInvalid())
461     return Handler;
462
463   return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
464                                   TryLoc,
465                                   TryBlock.get(),
466                                   Handler.get());
467 }
468
469 /// ParseSEHExceptBlock - Handle __except
470 ///
471 /// seh-except-block:
472 ///   '__except' '(' seh-filter-expression ')' compound-statement
473 ///
474 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
475   PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
476     raii2(Ident___exception_code, false),
477     raii3(Ident_GetExceptionCode, false);
478
479   if (ExpectAndConsume(tok::l_paren))
480     return StmtError();
481
482   ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
483                                    Scope::SEHExceptScope);
484
485   if (getLangOpts().Borland) {
486     Ident__exception_info->setIsPoisoned(false);
487     Ident___exception_info->setIsPoisoned(false);
488     Ident_GetExceptionInfo->setIsPoisoned(false);
489   }
490
491   ExprResult FilterExpr;
492   {
493     ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
494                                           Scope::SEHFilterScope);
495     FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
496   }
497
498   if (getLangOpts().Borland) {
499     Ident__exception_info->setIsPoisoned(true);
500     Ident___exception_info->setIsPoisoned(true);
501     Ident_GetExceptionInfo->setIsPoisoned(true);
502   }
503
504   if(FilterExpr.isInvalid())
505     return StmtError();
506
507   if (ExpectAndConsume(tok::r_paren))
508     return StmtError();
509
510   if (Tok.isNot(tok::l_brace))
511     return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
512
513   StmtResult Block(ParseCompoundStatement());
514
515   if(Block.isInvalid())
516     return Block;
517
518   return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
519 }
520
521 /// ParseSEHFinallyBlock - Handle __finally
522 ///
523 /// seh-finally-block:
524 ///   '__finally' compound-statement
525 ///
526 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
527   PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
528     raii2(Ident___abnormal_termination, false),
529     raii3(Ident_AbnormalTermination, false);
530
531   if (Tok.isNot(tok::l_brace))
532     return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
533
534   ParseScope FinallyScope(this, 0);
535   Actions.ActOnStartSEHFinallyBlock();
536
537   StmtResult Block(ParseCompoundStatement());
538   if(Block.isInvalid()) {
539     Actions.ActOnAbortSEHFinallyBlock();
540     return Block;
541   }
542
543   return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
544 }
545
546 /// Handle __leave
547 ///
548 /// seh-leave-statement:
549 ///   '__leave' ';'
550 ///
551 StmtResult Parser::ParseSEHLeaveStatement() {
552   SourceLocation LeaveLoc = ConsumeToken();  // eat the '__leave'.
553   return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
554 }
555
556 /// ParseLabeledStatement - We have an identifier and a ':' after it.
557 ///
558 ///       labeled-statement:
559 ///         identifier ':' statement
560 /// [GNU]   identifier ':' attributes[opt] statement
561 ///
562 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
563   assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
564          "Not an identifier!");
565
566   Token IdentTok = Tok;  // Save the whole token.
567   ConsumeToken();  // eat the identifier.
568
569   assert(Tok.is(tok::colon) && "Not a label!");
570
571   // identifier ':' statement
572   SourceLocation ColonLoc = ConsumeToken();
573
574   // Read label attributes, if present.
575   StmtResult SubStmt;
576   if (Tok.is(tok::kw___attribute)) {
577     ParsedAttributesWithRange TempAttrs(AttrFactory);
578     ParseGNUAttributes(TempAttrs);
579
580     // In C++, GNU attributes only apply to the label if they are followed by a
581     // semicolon, to disambiguate label attributes from attributes on a labeled
582     // declaration.
583     //
584     // This doesn't quite match what GCC does; if the attribute list is empty
585     // and followed by a semicolon, GCC will reject (it appears to parse the
586     // attributes as part of a statement in that case). That looks like a bug.
587     if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
588       attrs.takeAllFrom(TempAttrs);
589     else if (isDeclarationStatement()) {
590       StmtVector Stmts;
591       // FIXME: We should do this whether or not we have a declaration
592       // statement, but that doesn't work correctly (because ProhibitAttributes
593       // can't handle GNU attributes), so only call it in the one case where
594       // GNU attributes are allowed.
595       SubStmt = ParseStatementOrDeclarationAfterAttributes(
596           Stmts, /*Allowed=*/ACK_StatementsOpenMPNonStandalone, nullptr,
597           TempAttrs);
598       if (!TempAttrs.empty() && !SubStmt.isInvalid())
599         SubStmt = Actions.ProcessStmtAttributes(
600             SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
601     } else {
602       Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
603     }
604   }
605
606   // If we've not parsed a statement yet, parse one now.
607   if (!SubStmt.isInvalid() && !SubStmt.isUsable())
608     SubStmt = ParseStatement();
609
610   // Broken substmt shouldn't prevent the label from being added to the AST.
611   if (SubStmt.isInvalid())
612     SubStmt = Actions.ActOnNullStmt(ColonLoc);
613
614   LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
615                                               IdentTok.getLocation());
616   if (AttributeList *Attrs = attrs.getList()) {
617     Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
618     attrs.clear();
619   }
620
621   return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
622                                 SubStmt.get());
623 }
624
625 /// ParseCaseStatement
626 ///       labeled-statement:
627 ///         'case' constant-expression ':' statement
628 /// [GNU]   'case' constant-expression '...' constant-expression ':' statement
629 ///
630 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
631   assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
632
633   // It is very very common for code to contain many case statements recursively
634   // nested, as in (but usually without indentation):
635   //  case 1:
636   //    case 2:
637   //      case 3:
638   //         case 4:
639   //           case 5: etc.
640   //
641   // Parsing this naively works, but is both inefficient and can cause us to run
642   // out of stack space in our recursive descent parser.  As a special case,
643   // flatten this recursion into an iterative loop.  This is complex and gross,
644   // but all the grossness is constrained to ParseCaseStatement (and some
645   // weirdness in the actions), so this is just local grossness :).
646
647   // TopLevelCase - This is the highest level we have parsed.  'case 1' in the
648   // example above.
649   StmtResult TopLevelCase(true);
650
651   // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
652   // gets updated each time a new case is parsed, and whose body is unset so
653   // far.  When parsing 'case 4', this is the 'case 3' node.
654   Stmt *DeepestParsedCaseStmt = nullptr;
655
656   // While we have case statements, eat and stack them.
657   SourceLocation ColonLoc;
658   do {
659     SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
660                                            ConsumeToken();  // eat the 'case'.
661     ColonLoc = SourceLocation();
662
663     if (Tok.is(tok::code_completion)) {
664       Actions.CodeCompleteCase(getCurScope());
665       cutOffParsing();
666       return StmtError();
667     }
668
669     /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
670     /// Disable this form of error recovery while we're parsing the case
671     /// expression.
672     ColonProtectionRAIIObject ColonProtection(*this);
673
674     ExprResult LHS;
675     if (!MissingCase) {
676       LHS = ParseConstantExpression();
677       if (!getLangOpts().CPlusPlus11) {
678         LHS = Actions.CorrectDelayedTyposInExpr(LHS, [this](class Expr *E) {
679           return Actions.VerifyIntegerConstantExpression(E);
680         });
681       }
682       if (LHS.isInvalid()) {
683         // If constant-expression is parsed unsuccessfully, recover by skipping
684         // current case statement (moving to the colon that ends it).
685         if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
686           TryConsumeToken(tok::colon, ColonLoc);
687           continue;
688         }
689         return StmtError();
690       }
691     } else {
692       LHS = Expr;
693       MissingCase = false;
694     }
695
696     // GNU case range extension.
697     SourceLocation DotDotDotLoc;
698     ExprResult RHS;
699     if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
700       Diag(DotDotDotLoc, diag::ext_gnu_case_range);
701       RHS = ParseConstantExpression();
702       if (RHS.isInvalid()) {
703         if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
704           TryConsumeToken(tok::colon, ColonLoc);
705           continue;
706         }
707         return StmtError();
708       }
709     }
710
711     ColonProtection.restore();
712
713     if (TryConsumeToken(tok::colon, ColonLoc)) {
714     } else if (TryConsumeToken(tok::semi, ColonLoc) ||
715                TryConsumeToken(tok::coloncolon, ColonLoc)) {
716       // Treat "case blah;" or "case blah::" as a typo for "case blah:".
717       Diag(ColonLoc, diag::err_expected_after)
718           << "'case'" << tok::colon
719           << FixItHint::CreateReplacement(ColonLoc, ":");
720     } else {
721       SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
722       Diag(ExpectedLoc, diag::err_expected_after)
723           << "'case'" << tok::colon
724           << FixItHint::CreateInsertion(ExpectedLoc, ":");
725       ColonLoc = ExpectedLoc;
726     }
727
728     StmtResult Case =
729       Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
730                             RHS.get(), ColonLoc);
731
732     // If we had a sema error parsing this case, then just ignore it and
733     // continue parsing the sub-stmt.
734     if (Case.isInvalid()) {
735       if (TopLevelCase.isInvalid())  // No parsed case stmts.
736         return ParseStatement(/*TrailingElseLoc=*/nullptr,
737                               /*AllowOpenMPStandalone=*/true);
738       // Otherwise, just don't add it as a nested case.
739     } else {
740       // If this is the first case statement we parsed, it becomes TopLevelCase.
741       // Otherwise we link it into the current chain.
742       Stmt *NextDeepest = Case.get();
743       if (TopLevelCase.isInvalid())
744         TopLevelCase = Case;
745       else
746         Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
747       DeepestParsedCaseStmt = NextDeepest;
748     }
749
750     // Handle all case statements.
751   } while (Tok.is(tok::kw_case));
752
753   // If we found a non-case statement, start by parsing it.
754   StmtResult SubStmt;
755
756   if (Tok.isNot(tok::r_brace)) {
757     SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
758                              /*AllowOpenMPStandalone=*/true);
759   } else {
760     // Nicely diagnose the common error "switch (X) { case 4: }", which is
761     // not valid.  If ColonLoc doesn't point to a valid text location, there was
762     // another parsing error, so avoid producing extra diagnostics.
763     if (ColonLoc.isValid()) {
764       SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
765       Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
766         << FixItHint::CreateInsertion(AfterColonLoc, " ;");
767     }
768     SubStmt = StmtError();
769   }
770
771   // Install the body into the most deeply-nested case.
772   if (DeepestParsedCaseStmt) {
773     // Broken sub-stmt shouldn't prevent forming the case statement properly.
774     if (SubStmt.isInvalid())
775       SubStmt = Actions.ActOnNullStmt(SourceLocation());
776     Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
777   }
778
779   // Return the top level parsed statement tree.
780   return TopLevelCase;
781 }
782
783 /// ParseDefaultStatement
784 ///       labeled-statement:
785 ///         'default' ':' statement
786 /// Note that this does not parse the 'statement' at the end.
787 ///
788 StmtResult Parser::ParseDefaultStatement() {
789   assert(Tok.is(tok::kw_default) && "Not a default stmt!");
790   SourceLocation DefaultLoc = ConsumeToken();  // eat the 'default'.
791
792   SourceLocation ColonLoc;
793   if (TryConsumeToken(tok::colon, ColonLoc)) {
794   } else if (TryConsumeToken(tok::semi, ColonLoc)) {
795     // Treat "default;" as a typo for "default:".
796     Diag(ColonLoc, diag::err_expected_after)
797         << "'default'" << tok::colon
798         << FixItHint::CreateReplacement(ColonLoc, ":");
799   } else {
800     SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
801     Diag(ExpectedLoc, diag::err_expected_after)
802         << "'default'" << tok::colon
803         << FixItHint::CreateInsertion(ExpectedLoc, ":");
804     ColonLoc = ExpectedLoc;
805   }
806
807   StmtResult SubStmt;
808
809   if (Tok.isNot(tok::r_brace)) {
810     SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
811                              /*AllowOpenMPStandalone=*/true);
812   } else {
813     // Diagnose the common error "switch (X) {... default: }", which is
814     // not valid.
815     SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
816     Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
817       << FixItHint::CreateInsertion(AfterColonLoc, " ;");
818     SubStmt = true;
819   }
820
821   // Broken sub-stmt shouldn't prevent forming the case statement properly.
822   if (SubStmt.isInvalid())
823     SubStmt = Actions.ActOnNullStmt(ColonLoc);
824
825   return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
826                                   SubStmt.get(), getCurScope());
827 }
828
829 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
830   return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
831 }
832
833 /// ParseCompoundStatement - Parse a "{}" block.
834 ///
835 ///       compound-statement: [C99 6.8.2]
836 ///         { block-item-list[opt] }
837 /// [GNU]   { label-declarations block-item-list } [TODO]
838 ///
839 ///       block-item-list:
840 ///         block-item
841 ///         block-item-list block-item
842 ///
843 ///       block-item:
844 ///         declaration
845 /// [GNU]   '__extension__' declaration
846 ///         statement
847 ///
848 /// [GNU] label-declarations:
849 /// [GNU]   label-declaration
850 /// [GNU]   label-declarations label-declaration
851 ///
852 /// [GNU] label-declaration:
853 /// [GNU]   '__label__' identifier-list ';'
854 ///
855 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
856                                           unsigned ScopeFlags) {
857   assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
858
859   // Enter a scope to hold everything within the compound stmt.  Compound
860   // statements can always hold declarations.
861   ParseScope CompoundScope(this, ScopeFlags);
862
863   // Parse the statements in the body.
864   return ParseCompoundStatementBody(isStmtExpr);
865 }
866
867 /// Parse any pragmas at the start of the compound expression. We handle these
868 /// separately since some pragmas (FP_CONTRACT) must appear before any C
869 /// statement in the compound, but may be intermingled with other pragmas.
870 void Parser::ParseCompoundStatementLeadingPragmas() {
871   bool checkForPragmas = true;
872   while (checkForPragmas) {
873     switch (Tok.getKind()) {
874     case tok::annot_pragma_vis:
875       HandlePragmaVisibility();
876       break;
877     case tok::annot_pragma_pack:
878       HandlePragmaPack();
879       break;
880     case tok::annot_pragma_msstruct:
881       HandlePragmaMSStruct();
882       break;
883     case tok::annot_pragma_align:
884       HandlePragmaAlign();
885       break;
886     case tok::annot_pragma_weak:
887       HandlePragmaWeak();
888       break;
889     case tok::annot_pragma_weakalias:
890       HandlePragmaWeakAlias();
891       break;
892     case tok::annot_pragma_redefine_extname:
893       HandlePragmaRedefineExtname();
894       break;
895     case tok::annot_pragma_opencl_extension:
896       HandlePragmaOpenCLExtension();
897       break;
898     case tok::annot_pragma_fp_contract:
899       HandlePragmaFPContract();
900       break;
901     case tok::annot_pragma_ms_pointers_to_members:
902       HandlePragmaMSPointersToMembers();
903       break;
904     case tok::annot_pragma_ms_pragma:
905       HandlePragmaMSPragma();
906       break;
907     case tok::annot_pragma_ms_vtordisp:
908       HandlePragmaMSVtorDisp();
909       break;
910     case tok::annot_pragma_dump:
911       HandlePragmaDump();
912       break;
913     default:
914       checkForPragmas = false;
915       break;
916     }
917   }
918
919 }
920
921 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
922 /// ActOnCompoundStmt action.  This expects the '{' to be the current token, and
923 /// consume the '}' at the end of the block.  It does not manipulate the scope
924 /// stack.
925 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
926   PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
927                                 Tok.getLocation(),
928                                 "in compound statement ('{}')");
929
930   // Record the state of the FP_CONTRACT pragma, restore on leaving the
931   // compound statement.
932   Sema::FPContractStateRAII SaveFPContractState(Actions);
933
934   InMessageExpressionRAIIObject InMessage(*this, false);
935   BalancedDelimiterTracker T(*this, tok::l_brace);
936   if (T.consumeOpen())
937     return StmtError();
938
939   Sema::CompoundScopeRAII CompoundScope(Actions);
940
941   // Parse any pragmas at the beginning of the compound statement.
942   ParseCompoundStatementLeadingPragmas();
943
944   StmtVector Stmts;
945
946   // "__label__ X, Y, Z;" is the GNU "Local Label" extension.  These are
947   // only allowed at the start of a compound stmt regardless of the language.
948   while (Tok.is(tok::kw___label__)) {
949     SourceLocation LabelLoc = ConsumeToken();
950
951     SmallVector<Decl *, 8> DeclsInGroup;
952     while (1) {
953       if (Tok.isNot(tok::identifier)) {
954         Diag(Tok, diag::err_expected) << tok::identifier;
955         break;
956       }
957
958       IdentifierInfo *II = Tok.getIdentifierInfo();
959       SourceLocation IdLoc = ConsumeToken();
960       DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
961
962       if (!TryConsumeToken(tok::comma))
963         break;
964     }
965
966     DeclSpec DS(AttrFactory);
967     DeclGroupPtrTy Res =
968         Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
969     StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
970
971     ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
972     if (R.isUsable())
973       Stmts.push_back(R.get());
974   }
975
976   while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
977          Tok.isNot(tok::eof)) {
978     if (Tok.is(tok::annot_pragma_unused)) {
979       HandlePragmaUnused();
980       continue;
981     }
982
983     StmtResult R;
984     if (Tok.isNot(tok::kw___extension__)) {
985       R = ParseStatementOrDeclaration(Stmts, ACK_Any);
986     } else {
987       // __extension__ can start declarations and it can also be a unary
988       // operator for expressions.  Consume multiple __extension__ markers here
989       // until we can determine which is which.
990       // FIXME: This loses extension expressions in the AST!
991       SourceLocation ExtLoc = ConsumeToken();
992       while (Tok.is(tok::kw___extension__))
993         ConsumeToken();
994
995       ParsedAttributesWithRange attrs(AttrFactory);
996       MaybeParseCXX11Attributes(attrs, nullptr,
997                                 /*MightBeObjCMessageSend*/ true);
998
999       // If this is the start of a declaration, parse it as such.
1000       if (isDeclarationStatement()) {
1001         // __extension__ silences extension warnings in the subdeclaration.
1002         // FIXME: Save the __extension__ on the decl as a node somehow?
1003         ExtensionRAIIObject O(Diags);
1004
1005         SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1006         DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd,
1007                                               attrs);
1008         R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
1009       } else {
1010         // Otherwise this was a unary __extension__ marker.
1011         ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1012
1013         if (Res.isInvalid()) {
1014           SkipUntil(tok::semi);
1015           continue;
1016         }
1017
1018         // FIXME: Use attributes?
1019         // Eat the semicolon at the end of stmt and convert the expr into a
1020         // statement.
1021         ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1022         R = Actions.ActOnExprStmt(Res);
1023       }
1024     }
1025
1026     if (R.isUsable())
1027       Stmts.push_back(R.get());
1028   }
1029
1030   SourceLocation CloseLoc = Tok.getLocation();
1031
1032   // We broke out of the while loop because we found a '}' or EOF.
1033   if (!T.consumeClose())
1034     // Recover by creating a compound statement with what we parsed so far,
1035     // instead of dropping everything and returning StmtError();
1036     CloseLoc = T.getCloseLocation();
1037
1038   return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
1039                                    Stmts, isStmtExpr);
1040 }
1041
1042 /// ParseParenExprOrCondition:
1043 /// [C  ]     '(' expression ')'
1044 /// [C++]     '(' condition ')'       [not allowed if OnlyAllowCondition=true]
1045 ///
1046 /// This function parses and performs error recovery on the specified condition
1047 /// or expression (depending on whether we're in C++ or C mode).  This function
1048 /// goes out of its way to recover well.  It returns true if there was a parser
1049 /// error (the right paren couldn't be found), which indicates that the caller
1050 /// should try to recover harder.  It returns false if the condition is
1051 /// successfully parsed.  Note that a successful parse can still have semantic
1052 /// errors in the condition.
1053 bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
1054                                        Decl *&DeclResult,
1055                                        SourceLocation Loc,
1056                                        bool ConvertToBoolean) {
1057   BalancedDelimiterTracker T(*this, tok::l_paren);
1058   T.consumeOpen();
1059
1060   if (getLangOpts().CPlusPlus)
1061     ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
1062   else {
1063     ExprResult = ParseExpression();
1064     DeclResult = nullptr;
1065
1066     // If required, convert to a boolean value.
1067     if (!ExprResult.isInvalid() && ConvertToBoolean)
1068       ExprResult
1069         = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
1070   }
1071
1072   // If the parser was confused by the condition and we don't have a ')', try to
1073   // recover by skipping ahead to a semi and bailing out.  If condexp is
1074   // semantically invalid but we have well formed code, keep going.
1075   if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
1076     SkipUntil(tok::semi);
1077     // Skipping may have stopped if it found the containing ')'.  If so, we can
1078     // continue parsing the if statement.
1079     if (Tok.isNot(tok::r_paren))
1080       return true;
1081   }
1082
1083   // Otherwise the condition is valid or the rparen is present.
1084   T.consumeClose();
1085
1086   // Check for extraneous ')'s to catch things like "if (foo())) {".  We know
1087   // that all callers are looking for a statement after the condition, so ")"
1088   // isn't valid.
1089   while (Tok.is(tok::r_paren)) {
1090     Diag(Tok, diag::err_extraneous_rparen_in_condition)
1091       << FixItHint::CreateRemoval(Tok.getLocation());
1092     ConsumeParen();
1093   }
1094
1095   return false;
1096 }
1097
1098
1099 /// ParseIfStatement
1100 ///       if-statement: [C99 6.8.4.1]
1101 ///         'if' '(' expression ')' statement
1102 ///         'if' '(' expression ')' statement 'else' statement
1103 /// [C++]   'if' '(' condition ')' statement
1104 /// [C++]   'if' '(' condition ')' statement 'else' statement
1105 ///
1106 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1107   assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1108   SourceLocation IfLoc = ConsumeToken();  // eat the 'if'.
1109
1110   if (Tok.isNot(tok::l_paren)) {
1111     Diag(Tok, diag::err_expected_lparen_after) << "if";
1112     SkipUntil(tok::semi);
1113     return StmtError();
1114   }
1115
1116   bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1117
1118   // C99 6.8.4p3 - In C99, the if statement is a block.  This is not
1119   // the case for C90.
1120   //
1121   // C++ 6.4p3:
1122   // A name introduced by a declaration in a condition is in scope from its
1123   // point of declaration until the end of the substatements controlled by the
1124   // condition.
1125   // C++ 3.3.2p4:
1126   // Names declared in the for-init-statement, and in the condition of if,
1127   // while, for, and switch statements are local to the if, while, for, or
1128   // switch statement (including the controlled statement).
1129   //
1130   ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1131
1132   // Parse the condition.
1133   ExprResult CondExp;
1134   Decl *CondVar = nullptr;
1135   if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
1136     return StmtError();
1137
1138   FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
1139
1140   // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1141   // there is no compound stmt.  C90 does not have this clause.  We only do this
1142   // if the body isn't a compound statement to avoid push/pop in common cases.
1143   //
1144   // C++ 6.4p1:
1145   // The substatement in a selection-statement (each substatement, in the else
1146   // form of the if statement) implicitly defines a local scope.
1147   //
1148   // For C++ we create a scope for the condition and a new scope for
1149   // substatements because:
1150   // -When the 'then' scope exits, we want the condition declaration to still be
1151   //    active for the 'else' scope too.
1152   // -Sema will detect name clashes by considering declarations of a
1153   //    'ControlScope' as part of its direct subscope.
1154   // -If we wanted the condition and substatement to be in the same scope, we
1155   //    would have to notify ParseStatement not to create a new scope. It's
1156   //    simpler to let it create a new scope.
1157   //
1158   ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1159
1160   // Read the 'then' stmt.
1161   SourceLocation ThenStmtLoc = Tok.getLocation();
1162
1163   SourceLocation InnerStatementTrailingElseLoc;
1164   StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
1165
1166   // Pop the 'if' scope if needed.
1167   InnerScope.Exit();
1168
1169   // If it has an else, parse it.
1170   SourceLocation ElseLoc;
1171   SourceLocation ElseStmtLoc;
1172   StmtResult ElseStmt;
1173
1174   if (Tok.is(tok::kw_else)) {
1175     if (TrailingElseLoc)
1176       *TrailingElseLoc = Tok.getLocation();
1177
1178     ElseLoc = ConsumeToken();
1179     ElseStmtLoc = Tok.getLocation();
1180
1181     // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1182     // there is no compound stmt.  C90 does not have this clause.  We only do
1183     // this if the body isn't a compound statement to avoid push/pop in common
1184     // cases.
1185     //
1186     // C++ 6.4p1:
1187     // The substatement in a selection-statement (each substatement, in the else
1188     // form of the if statement) implicitly defines a local scope.
1189     //
1190     ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1191
1192     ElseStmt = ParseStatement();
1193
1194     // Pop the 'else' scope if needed.
1195     InnerScope.Exit();
1196   } else if (Tok.is(tok::code_completion)) {
1197     Actions.CodeCompleteAfterIf(getCurScope());
1198     cutOffParsing();
1199     return StmtError();
1200   } else if (InnerStatementTrailingElseLoc.isValid()) {
1201     Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1202   }
1203
1204   IfScope.Exit();
1205
1206   // If the then or else stmt is invalid and the other is valid (and present),
1207   // make turn the invalid one into a null stmt to avoid dropping the other
1208   // part.  If both are invalid, return error.
1209   if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1210       (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1211       (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
1212     // Both invalid, or one is invalid and other is non-present: return error.
1213     return StmtError();
1214   }
1215
1216   // Now if either are invalid, replace with a ';'.
1217   if (ThenStmt.isInvalid())
1218     ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1219   if (ElseStmt.isInvalid())
1220     ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1221
1222   return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
1223                              ElseLoc, ElseStmt.get());
1224 }
1225
1226 /// ParseSwitchStatement
1227 ///       switch-statement:
1228 ///         'switch' '(' expression ')' statement
1229 /// [C++]   'switch' '(' condition ')' statement
1230 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1231   assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1232   SourceLocation SwitchLoc = ConsumeToken();  // eat the 'switch'.
1233
1234   if (Tok.isNot(tok::l_paren)) {
1235     Diag(Tok, diag::err_expected_lparen_after) << "switch";
1236     SkipUntil(tok::semi);
1237     return StmtError();
1238   }
1239
1240   bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1241
1242   // C99 6.8.4p3 - In C99, the switch statement is a block.  This is
1243   // not the case for C90.  Start the switch scope.
1244   //
1245   // C++ 6.4p3:
1246   // A name introduced by a declaration in a condition is in scope from its
1247   // point of declaration until the end of the substatements controlled by the
1248   // condition.
1249   // C++ 3.3.2p4:
1250   // Names declared in the for-init-statement, and in the condition of if,
1251   // while, for, and switch statements are local to the if, while, for, or
1252   // switch statement (including the controlled statement).
1253   //
1254   unsigned ScopeFlags = Scope::SwitchScope;
1255   if (C99orCXX)
1256     ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1257   ParseScope SwitchScope(this, ScopeFlags);
1258
1259   // Parse the condition.
1260   ExprResult Cond;
1261   Decl *CondVar = nullptr;
1262   if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
1263     return StmtError();
1264
1265   StmtResult Switch
1266     = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
1267
1268   if (Switch.isInvalid()) {
1269     // Skip the switch body.
1270     // FIXME: This is not optimal recovery, but parsing the body is more
1271     // dangerous due to the presence of case and default statements, which
1272     // will have no place to connect back with the switch.
1273     if (Tok.is(tok::l_brace)) {
1274       ConsumeBrace();
1275       SkipUntil(tok::r_brace);
1276     } else
1277       SkipUntil(tok::semi);
1278     return Switch;
1279   }
1280
1281   // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1282   // there is no compound stmt.  C90 does not have this clause.  We only do this
1283   // if the body isn't a compound statement to avoid push/pop in common cases.
1284   //
1285   // C++ 6.4p1:
1286   // The substatement in a selection-statement (each substatement, in the else
1287   // form of the if statement) implicitly defines a local scope.
1288   //
1289   // See comments in ParseIfStatement for why we create a scope for the
1290   // condition and a new scope for substatement in C++.
1291   //
1292   getCurScope()->AddFlags(Scope::BreakScope);
1293   ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1294
1295   // We have incremented the mangling number for the SwitchScope and the
1296   // InnerScope, which is one too many.
1297   if (C99orCXX)
1298     getCurScope()->decrementMSManglingNumber();
1299
1300   // Read the body statement.
1301   StmtResult Body(ParseStatement(TrailingElseLoc));
1302
1303   // Pop the scopes.
1304   InnerScope.Exit();
1305   SwitchScope.Exit();
1306
1307   return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1308 }
1309
1310 /// ParseWhileStatement
1311 ///       while-statement: [C99 6.8.5.1]
1312 ///         'while' '(' expression ')' statement
1313 /// [C++]   'while' '(' condition ')' statement
1314 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1315   assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1316   SourceLocation WhileLoc = Tok.getLocation();
1317   ConsumeToken();  // eat the 'while'.
1318
1319   if (Tok.isNot(tok::l_paren)) {
1320     Diag(Tok, diag::err_expected_lparen_after) << "while";
1321     SkipUntil(tok::semi);
1322     return StmtError();
1323   }
1324
1325   bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1326
1327   // C99 6.8.5p5 - In C99, the while statement is a block.  This is not
1328   // the case for C90.  Start the loop scope.
1329   //
1330   // C++ 6.4p3:
1331   // A name introduced by a declaration in a condition is in scope from its
1332   // point of declaration until the end of the substatements controlled by the
1333   // condition.
1334   // C++ 3.3.2p4:
1335   // Names declared in the for-init-statement, and in the condition of if,
1336   // while, for, and switch statements are local to the if, while, for, or
1337   // switch statement (including the controlled statement).
1338   //
1339   unsigned ScopeFlags;
1340   if (C99orCXX)
1341     ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1342                  Scope::DeclScope  | Scope::ControlScope;
1343   else
1344     ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1345   ParseScope WhileScope(this, ScopeFlags);
1346
1347   // Parse the condition.
1348   ExprResult Cond;
1349   Decl *CondVar = nullptr;
1350   if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
1351     return StmtError();
1352
1353   FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
1354
1355   // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1356   // there is no compound stmt.  C90 does not have this clause.  We only do this
1357   // if the body isn't a compound statement to avoid push/pop in common cases.
1358   //
1359   // C++ 6.5p2:
1360   // The substatement in an iteration-statement implicitly defines a local scope
1361   // which is entered and exited each time through the loop.
1362   //
1363   // See comments in ParseIfStatement for why we create a scope for the
1364   // condition and a new scope for substatement in C++.
1365   //
1366   ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1367
1368   // Read the body statement.
1369   StmtResult Body(ParseStatement(TrailingElseLoc));
1370
1371   // Pop the body scope if needed.
1372   InnerScope.Exit();
1373   WhileScope.Exit();
1374
1375   if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
1376     return StmtError();
1377
1378   return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
1379 }
1380
1381 /// ParseDoStatement
1382 ///       do-statement: [C99 6.8.5.2]
1383 ///         'do' statement 'while' '(' expression ')' ';'
1384 /// Note: this lets the caller parse the end ';'.
1385 StmtResult Parser::ParseDoStatement() {
1386   assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1387   SourceLocation DoLoc = ConsumeToken();  // eat the 'do'.
1388
1389   // C99 6.8.5p5 - In C99, the do statement is a block.  This is not
1390   // the case for C90.  Start the loop scope.
1391   unsigned ScopeFlags;
1392   if (getLangOpts().C99)
1393     ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1394   else
1395     ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1396
1397   ParseScope DoScope(this, ScopeFlags);
1398
1399   // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1400   // there is no compound stmt.  C90 does not have this clause. We only do this
1401   // if the body isn't a compound statement to avoid push/pop in common cases.
1402   //
1403   // C++ 6.5p2:
1404   // The substatement in an iteration-statement implicitly defines a local scope
1405   // which is entered and exited each time through the loop.
1406   //
1407   bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1408   ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1409
1410   // Read the body statement.
1411   StmtResult Body(ParseStatement());
1412
1413   // Pop the body scope if needed.
1414   InnerScope.Exit();
1415
1416   if (Tok.isNot(tok::kw_while)) {
1417     if (!Body.isInvalid()) {
1418       Diag(Tok, diag::err_expected_while);
1419       Diag(DoLoc, diag::note_matching) << "'do'";
1420       SkipUntil(tok::semi, StopBeforeMatch);
1421     }
1422     return StmtError();
1423   }
1424   SourceLocation WhileLoc = ConsumeToken();
1425
1426   if (Tok.isNot(tok::l_paren)) {
1427     Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1428     SkipUntil(tok::semi, StopBeforeMatch);
1429     return StmtError();
1430   }
1431
1432   // Parse the parenthesized expression.
1433   BalancedDelimiterTracker T(*this, tok::l_paren);
1434   T.consumeOpen();
1435
1436   // A do-while expression is not a condition, so can't have attributes.
1437   DiagnoseAndSkipCXX11Attributes();
1438
1439   ExprResult Cond = ParseExpression();
1440   T.consumeClose();
1441   DoScope.Exit();
1442
1443   if (Cond.isInvalid() || Body.isInvalid())
1444     return StmtError();
1445
1446   return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1447                              Cond.get(), T.getCloseLocation());
1448 }
1449
1450 bool Parser::isForRangeIdentifier() {
1451   assert(Tok.is(tok::identifier));
1452
1453   const Token &Next = NextToken();
1454   if (Next.is(tok::colon))
1455     return true;
1456
1457   if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1458     TentativeParsingAction PA(*this);
1459     ConsumeToken();
1460     SkipCXX11Attributes();
1461     bool Result = Tok.is(tok::colon);
1462     PA.Revert();
1463     return Result;
1464   }
1465
1466   return false;
1467 }
1468
1469 /// ParseForStatement
1470 ///       for-statement: [C99 6.8.5.3]
1471 ///         'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1472 ///         'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1473 /// [C++]   'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1474 /// [C++]       statement
1475 /// [C++0x] 'for'
1476 ///             'co_await'[opt]    [Coroutines]
1477 ///             '(' for-range-declaration ':' for-range-initializer ')'
1478 ///             statement
1479 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1480 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1481 ///
1482 /// [C++] for-init-statement:
1483 /// [C++]   expression-statement
1484 /// [C++]   simple-declaration
1485 ///
1486 /// [C++0x] for-range-declaration:
1487 /// [C++0x]   attribute-specifier-seq[opt] type-specifier-seq declarator
1488 /// [C++0x] for-range-initializer:
1489 /// [C++0x]   expression
1490 /// [C++0x]   braced-init-list            [TODO]
1491 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1492   assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1493   SourceLocation ForLoc = ConsumeToken();  // eat the 'for'.
1494
1495   SourceLocation CoawaitLoc;
1496   if (Tok.is(tok::kw_co_await))
1497     CoawaitLoc = ConsumeToken();
1498
1499   if (Tok.isNot(tok::l_paren)) {
1500     Diag(Tok, diag::err_expected_lparen_after) << "for";
1501     SkipUntil(tok::semi);
1502     return StmtError();
1503   }
1504
1505   bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1506     getLangOpts().ObjC1;
1507
1508   // C99 6.8.5p5 - In C99, the for statement is a block.  This is not
1509   // the case for C90.  Start the loop scope.
1510   //
1511   // C++ 6.4p3:
1512   // A name introduced by a declaration in a condition is in scope from its
1513   // point of declaration until the end of the substatements controlled by the
1514   // condition.
1515   // C++ 3.3.2p4:
1516   // Names declared in the for-init-statement, and in the condition of if,
1517   // while, for, and switch statements are local to the if, while, for, or
1518   // switch statement (including the controlled statement).
1519   // C++ 6.5.3p1:
1520   // Names declared in the for-init-statement are in the same declarative-region
1521   // as those declared in the condition.
1522   //
1523   unsigned ScopeFlags = 0;
1524   if (C99orCXXorObjC)
1525     ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1526
1527   ParseScope ForScope(this, ScopeFlags);
1528
1529   BalancedDelimiterTracker T(*this, tok::l_paren);
1530   T.consumeOpen();
1531
1532   ExprResult Value;
1533
1534   bool ForEach = false, ForRange = false;
1535   StmtResult FirstPart;
1536   bool SecondPartIsInvalid = false;
1537   FullExprArg SecondPart(Actions);
1538   ExprResult Collection;
1539   ForRangeInit ForRangeInit;
1540   FullExprArg ThirdPart(Actions);
1541   Decl *SecondVar = nullptr;
1542
1543   if (Tok.is(tok::code_completion)) {
1544     Actions.CodeCompleteOrdinaryName(getCurScope(),
1545                                      C99orCXXorObjC? Sema::PCC_ForInit
1546                                                    : Sema::PCC_Expression);
1547     cutOffParsing();
1548     return StmtError();
1549   }
1550
1551   ParsedAttributesWithRange attrs(AttrFactory);
1552   MaybeParseCXX11Attributes(attrs);
1553
1554   // Parse the first part of the for specifier.
1555   if (Tok.is(tok::semi)) {  // for (;
1556     ProhibitAttributes(attrs);
1557     // no first part, eat the ';'.
1558     ConsumeToken();
1559   } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1560              isForRangeIdentifier()) {
1561     ProhibitAttributes(attrs);
1562     IdentifierInfo *Name = Tok.getIdentifierInfo();
1563     SourceLocation Loc = ConsumeToken();
1564     MaybeParseCXX11Attributes(attrs);
1565
1566     ForRangeInit.ColonLoc = ConsumeToken();
1567     if (Tok.is(tok::l_brace))
1568       ForRangeInit.RangeExpr = ParseBraceInitializer();
1569     else
1570       ForRangeInit.RangeExpr = ParseExpression();
1571
1572     Diag(Loc, diag::err_for_range_identifier)
1573       << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus1z)
1574               ? FixItHint::CreateInsertion(Loc, "auto &&")
1575               : FixItHint());
1576
1577     FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name,
1578                                                    attrs, attrs.Range.getEnd());
1579     ForRange = true;
1580   } else if (isForInitDeclaration()) {  // for (int X = 4;
1581     // Parse declaration, which eats the ';'.
1582     if (!C99orCXXorObjC)   // Use of C99-style for loops in C90 mode?
1583       Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1584
1585     // In C++0x, "for (T NS:a" might not be a typo for ::
1586     bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1587     ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1588
1589     SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1590     DeclGroupPtrTy DG = ParseSimpleDeclaration(
1591         Declarator::ForContext, DeclEnd, attrs, false,
1592         MightBeForRangeStmt ? &ForRangeInit : nullptr);
1593     FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1594     if (ForRangeInit.ParsedForRangeDecl()) {
1595       Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
1596            diag::warn_cxx98_compat_for_range : diag::ext_for_range);
1597
1598       ForRange = true;
1599     } else if (Tok.is(tok::semi)) {  // for (int x = 4;
1600       ConsumeToken();
1601     } else if ((ForEach = isTokIdentifier_in())) {
1602       Actions.ActOnForEachDeclStmt(DG);
1603       // ObjC: for (id x in expr)
1604       ConsumeToken(); // consume 'in'
1605
1606       if (Tok.is(tok::code_completion)) {
1607         Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1608         cutOffParsing();
1609         return StmtError();
1610       }
1611       Collection = ParseExpression();
1612     } else {
1613       Diag(Tok, diag::err_expected_semi_for);
1614     }
1615   } else {
1616     ProhibitAttributes(attrs);
1617     Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
1618
1619     ForEach = isTokIdentifier_in();
1620
1621     // Turn the expression into a stmt.
1622     if (!Value.isInvalid()) {
1623       if (ForEach)
1624         FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1625       else
1626         FirstPart = Actions.ActOnExprStmt(Value);
1627     }
1628
1629     if (Tok.is(tok::semi)) {
1630       ConsumeToken();
1631     } else if (ForEach) {
1632       ConsumeToken(); // consume 'in'
1633
1634       if (Tok.is(tok::code_completion)) {
1635         Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
1636         cutOffParsing();
1637         return StmtError();
1638       }
1639       Collection = ParseExpression();
1640     } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
1641       // User tried to write the reasonable, but ill-formed, for-range-statement
1642       //   for (expr : expr) { ... }
1643       Diag(Tok, diag::err_for_range_expected_decl)
1644         << FirstPart.get()->getSourceRange();
1645       SkipUntil(tok::r_paren, StopBeforeMatch);
1646       SecondPartIsInvalid = true;
1647     } else {
1648       if (!Value.isInvalid()) {
1649         Diag(Tok, diag::err_expected_semi_for);
1650       } else {
1651         // Skip until semicolon or rparen, don't consume it.
1652         SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1653         if (Tok.is(tok::semi))
1654           ConsumeToken();
1655       }
1656     }
1657   }
1658
1659   // Parse the second part of the for specifier.
1660   getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
1661   if (!ForEach && !ForRange) {
1662     assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
1663     // Parse the second part of the for specifier.
1664     if (Tok.is(tok::semi)) {  // for (...;;
1665       // no second part.
1666     } else if (Tok.is(tok::r_paren)) {
1667       // missing both semicolons.
1668     } else {
1669       ExprResult Second;
1670       if (getLangOpts().CPlusPlus)
1671         ParseCXXCondition(Second, SecondVar, ForLoc, true);
1672       else {
1673         Second = ParseExpression();
1674         if (!Second.isInvalid())
1675           Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
1676                                                  Second.get());
1677       }
1678       SecondPartIsInvalid = Second.isInvalid();
1679       SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
1680     }
1681
1682     if (Tok.isNot(tok::semi)) {
1683       if (!SecondPartIsInvalid || SecondVar)
1684         Diag(Tok, diag::err_expected_semi_for);
1685       else
1686         // Skip until semicolon or rparen, don't consume it.
1687         SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1688     }
1689
1690     if (Tok.is(tok::semi)) {
1691       ConsumeToken();
1692     }
1693
1694     // Parse the third part of the for specifier.
1695     if (Tok.isNot(tok::r_paren)) {   // for (...;...;)
1696       ExprResult Third = ParseExpression();
1697       // FIXME: The C++11 standard doesn't actually say that this is a
1698       // discarded-value expression, but it clearly should be.
1699       ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
1700     }
1701   }
1702   // Match the ')'.
1703   T.consumeClose();
1704
1705   // C++ Coroutines [stmt.iter]:
1706   //   'co_await' can only be used for a range-based for statement.
1707   if (CoawaitLoc.isValid() && !ForRange) {
1708     Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
1709     CoawaitLoc = SourceLocation();
1710   }
1711
1712   // We need to perform most of the semantic analysis for a C++0x for-range
1713   // statememt before parsing the body, in order to be able to deduce the type
1714   // of an auto-typed loop variable.
1715   StmtResult ForRangeStmt;
1716   StmtResult ForEachStmt;
1717
1718   if (ForRange) {
1719     ForRangeStmt = Actions.ActOnCXXForRangeStmt(
1720         getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
1721         ForRangeInit.ColonLoc, ForRangeInit.RangeExpr.get(),
1722         T.getCloseLocation(), Sema::BFRK_Build);
1723
1724   // Similarly, we need to do the semantic analysis for a for-range
1725   // statement immediately in order to close over temporaries correctly.
1726   } else if (ForEach) {
1727     ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
1728                                                      FirstPart.get(),
1729                                                      Collection.get(),
1730                                                      T.getCloseLocation());
1731   } else {
1732     // In OpenMP loop region loop control variable must be captured and be
1733     // private. Perform analysis of first part (if any).
1734     if (getLangOpts().OpenMP && FirstPart.isUsable()) {
1735       Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
1736     }
1737   }
1738
1739   // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
1740   // there is no compound stmt.  C90 does not have this clause.  We only do this
1741   // if the body isn't a compound statement to avoid push/pop in common cases.
1742   //
1743   // C++ 6.5p2:
1744   // The substatement in an iteration-statement implicitly defines a local scope
1745   // which is entered and exited each time through the loop.
1746   //
1747   // See comments in ParseIfStatement for why we create a scope for
1748   // for-init-statement/condition and a new scope for substatement in C++.
1749   //
1750   ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1751                         Tok.is(tok::l_brace));
1752
1753   // The body of the for loop has the same local mangling number as the
1754   // for-init-statement.
1755   // It will only be incremented if the body contains other things that would
1756   // normally increment the mangling number (like a compound statement).
1757   if (C99orCXXorObjC)
1758     getCurScope()->decrementMSManglingNumber();
1759
1760   // Read the body statement.
1761   StmtResult Body(ParseStatement(TrailingElseLoc));
1762
1763   // Pop the body scope if needed.
1764   InnerScope.Exit();
1765
1766   // Leave the for-scope.
1767   ForScope.Exit();
1768
1769   if (Body.isInvalid())
1770     return StmtError();
1771
1772   if (ForEach)
1773    return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1774                                               Body.get());
1775
1776   if (ForRange)
1777     return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
1778
1779   return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
1780                               SecondPart, SecondVar, ThirdPart,
1781                               T.getCloseLocation(), Body.get());
1782 }
1783
1784 /// ParseGotoStatement
1785 ///       jump-statement:
1786 ///         'goto' identifier ';'
1787 /// [GNU]   'goto' '*' expression ';'
1788 ///
1789 /// Note: this lets the caller parse the end ';'.
1790 ///
1791 StmtResult Parser::ParseGotoStatement() {
1792   assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1793   SourceLocation GotoLoc = ConsumeToken();  // eat the 'goto'.
1794
1795   StmtResult Res;
1796   if (Tok.is(tok::identifier)) {
1797     LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1798                                                 Tok.getLocation());
1799     Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1800     ConsumeToken();
1801   } else if (Tok.is(tok::star)) {
1802     // GNU indirect goto extension.
1803     Diag(Tok, diag::ext_gnu_indirect_goto);
1804     SourceLocation StarLoc = ConsumeToken();
1805     ExprResult R(ParseExpression());
1806     if (R.isInvalid()) {  // Skip to the semicolon, but don't consume it.
1807       SkipUntil(tok::semi, StopBeforeMatch);
1808       return StmtError();
1809     }
1810     Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
1811   } else {
1812     Diag(Tok, diag::err_expected) << tok::identifier;
1813     return StmtError();
1814   }
1815
1816   return Res;
1817 }
1818
1819 /// ParseContinueStatement
1820 ///       jump-statement:
1821 ///         'continue' ';'
1822 ///
1823 /// Note: this lets the caller parse the end ';'.
1824 ///
1825 StmtResult Parser::ParseContinueStatement() {
1826   SourceLocation ContinueLoc = ConsumeToken();  // eat the 'continue'.
1827   return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1828 }
1829
1830 /// ParseBreakStatement
1831 ///       jump-statement:
1832 ///         'break' ';'
1833 ///
1834 /// Note: this lets the caller parse the end ';'.
1835 ///
1836 StmtResult Parser::ParseBreakStatement() {
1837   SourceLocation BreakLoc = ConsumeToken();  // eat the 'break'.
1838   return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1839 }
1840
1841 /// ParseReturnStatement
1842 ///       jump-statement:
1843 ///         'return' expression[opt] ';'
1844 ///         'return' braced-init-list ';'
1845 ///         'co_return' expression[opt] ';'
1846 ///         'co_return' braced-init-list ';'
1847 StmtResult Parser::ParseReturnStatement() {
1848   assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
1849          "Not a return stmt!");
1850   bool IsCoreturn = Tok.is(tok::kw_co_return);
1851   SourceLocation ReturnLoc = ConsumeToken();  // eat the 'return'.
1852
1853   ExprResult R;
1854   if (Tok.isNot(tok::semi)) {
1855     // FIXME: Code completion for co_return.
1856     if (Tok.is(tok::code_completion) && !IsCoreturn) {
1857       Actions.CodeCompleteReturn(getCurScope());
1858       cutOffParsing();
1859       return StmtError();
1860     }
1861
1862     if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
1863       R = ParseInitializer();
1864       if (R.isUsable())
1865         Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
1866              diag::warn_cxx98_compat_generalized_initializer_lists :
1867              diag::ext_generalized_initializer_lists)
1868           << R.get()->getSourceRange();
1869     } else
1870       R = ParseExpression();
1871     if (R.isInvalid()) {
1872       SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1873       return StmtError();
1874     }
1875   }
1876   if (IsCoreturn)
1877     return Actions.ActOnCoreturnStmt(ReturnLoc, R.get());
1878   return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
1879 }
1880
1881 StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
1882                                        AllowedContsructsKind Allowed,
1883                                        SourceLocation *TrailingElseLoc,
1884                                        ParsedAttributesWithRange &Attrs) {
1885   // Create temporary attribute list.
1886   ParsedAttributesWithRange TempAttrs(AttrFactory);
1887
1888   // Get loop hints and consume annotated token.
1889   while (Tok.is(tok::annot_pragma_loop_hint)) {
1890     LoopHint Hint;
1891     if (!HandlePragmaLoopHint(Hint))
1892       continue;
1893
1894     ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
1895                             ArgsUnion(Hint.ValueExpr)};
1896     TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
1897                      Hint.PragmaNameLoc->Loc, ArgHints, 4,
1898                      AttributeList::AS_Pragma);
1899   }
1900
1901   // Get the next statement.
1902   MaybeParseCXX11Attributes(Attrs);
1903
1904   StmtResult S = ParseStatementOrDeclarationAfterAttributes(
1905       Stmts, Allowed, TrailingElseLoc, Attrs);
1906
1907   Attrs.takeAllFrom(TempAttrs);
1908   return S;
1909 }
1910
1911 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
1912   assert(Tok.is(tok::l_brace));
1913   SourceLocation LBraceLoc = Tok.getLocation();
1914
1915   if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
1916       trySkippingFunctionBody()) {
1917     BodyScope.Exit();
1918     return Actions.ActOnSkippedFunctionBody(Decl);
1919   }
1920
1921   PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1922                                       "parsing function body");
1923
1924   // Save and reset current vtordisp stack if we have entered a C++ method body.
1925   bool IsCXXMethod =
1926       getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1927   Sema::VtorDispStackRAII SavedVtorDispStack(Actions, IsCXXMethod);
1928
1929   // Do not enter a scope for the brace, as the arguments are in the same scope
1930   // (the function body) as the body itself.  Instead, just read the statement
1931   // list and put it into a CompoundStmt for safe keeping.
1932   StmtResult FnBody(ParseCompoundStatementBody());
1933
1934   // If the function body could not be parsed, make a bogus compoundstmt.
1935   if (FnBody.isInvalid()) {
1936     Sema::CompoundScopeRAII CompoundScope(Actions);
1937     FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
1938   }
1939
1940   BodyScope.Exit();
1941   return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
1942 }
1943
1944 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1945 ///
1946 ///       function-try-block:
1947 ///         'try' ctor-initializer[opt] compound-statement handler-seq
1948 ///
1949 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
1950   assert(Tok.is(tok::kw_try) && "Expected 'try'");
1951   SourceLocation TryLoc = ConsumeToken();
1952
1953   PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1954                                       "parsing function try block");
1955
1956   // Constructor initializer list?
1957   if (Tok.is(tok::colon))
1958     ParseConstructorInitializer(Decl);
1959   else
1960     Actions.ActOnDefaultCtorInitializers(Decl);
1961
1962   if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
1963       trySkippingFunctionBody()) {
1964     BodyScope.Exit();
1965     return Actions.ActOnSkippedFunctionBody(Decl);
1966   }
1967
1968   // Save and reset current vtordisp stack if we have entered a C++ method body.
1969   bool IsCXXMethod =
1970       getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1971   Sema::VtorDispStackRAII SavedVtorDispStack(Actions, IsCXXMethod);
1972
1973   SourceLocation LBraceLoc = Tok.getLocation();
1974   StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
1975   // If we failed to parse the try-catch, we just give the function an empty
1976   // compound statement as the body.
1977   if (FnBody.isInvalid()) {
1978     Sema::CompoundScopeRAII CompoundScope(Actions);
1979     FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
1980   }
1981
1982   BodyScope.Exit();
1983   return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
1984 }
1985
1986 bool Parser::trySkippingFunctionBody() {
1987   assert(Tok.is(tok::l_brace));
1988   assert(SkipFunctionBodies &&
1989          "Should only be called when SkipFunctionBodies is enabled");
1990
1991   if (!PP.isCodeCompletionEnabled()) {
1992     ConsumeBrace();
1993     SkipUntil(tok::r_brace);
1994     return true;
1995   }
1996
1997   // We're in code-completion mode. Skip parsing for all function bodies unless
1998   // the body contains the code-completion point.
1999   TentativeParsingAction PA(*this);
2000   ConsumeBrace();
2001   if (SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2002     PA.Commit();
2003     return true;
2004   }
2005
2006   PA.Revert();
2007   return false;
2008 }
2009
2010 /// ParseCXXTryBlock - Parse a C++ try-block.
2011 ///
2012 ///       try-block:
2013 ///         'try' compound-statement handler-seq
2014 ///
2015 StmtResult Parser::ParseCXXTryBlock() {
2016   assert(Tok.is(tok::kw_try) && "Expected 'try'");
2017
2018   SourceLocation TryLoc = ConsumeToken();
2019   return ParseCXXTryBlockCommon(TryLoc);
2020 }
2021
2022 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2023 /// function-try-block.
2024 ///
2025 ///       try-block:
2026 ///         'try' compound-statement handler-seq
2027 ///
2028 ///       function-try-block:
2029 ///         'try' ctor-initializer[opt] compound-statement handler-seq
2030 ///
2031 ///       handler-seq:
2032 ///         handler handler-seq[opt]
2033 ///
2034 ///       [Borland] try-block:
2035 ///         'try' compound-statement seh-except-block
2036 ///         'try' compound-statement seh-finally-block
2037 ///
2038 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2039   if (Tok.isNot(tok::l_brace))
2040     return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2041
2042   StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
2043                       Scope::DeclScope | Scope::TryScope |
2044                         (FnTry ? Scope::FnTryCatchScope : 0)));
2045   if (TryBlock.isInvalid())
2046     return TryBlock;
2047
2048   // Borland allows SEH-handlers with 'try'
2049
2050   if ((Tok.is(tok::identifier) &&
2051        Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2052       Tok.is(tok::kw___finally)) {
2053     // TODO: Factor into common return ParseSEHHandlerCommon(...)
2054     StmtResult Handler;
2055     if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2056       SourceLocation Loc = ConsumeToken();
2057       Handler = ParseSEHExceptBlock(Loc);
2058     }
2059     else {
2060       SourceLocation Loc = ConsumeToken();
2061       Handler = ParseSEHFinallyBlock(Loc);
2062     }
2063     if(Handler.isInvalid())
2064       return Handler;
2065
2066     return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2067                                     TryLoc,
2068                                     TryBlock.get(),
2069                                     Handler.get());
2070   }
2071   else {
2072     StmtVector Handlers;
2073
2074     // C++11 attributes can't appear here, despite this context seeming
2075     // statement-like.
2076     DiagnoseAndSkipCXX11Attributes();
2077
2078     if (Tok.isNot(tok::kw_catch))
2079       return StmtError(Diag(Tok, diag::err_expected_catch));
2080     while (Tok.is(tok::kw_catch)) {
2081       StmtResult Handler(ParseCXXCatchBlock(FnTry));
2082       if (!Handler.isInvalid())
2083         Handlers.push_back(Handler.get());
2084     }
2085     // Don't bother creating the full statement if we don't have any usable
2086     // handlers.
2087     if (Handlers.empty())
2088       return StmtError();
2089
2090     return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2091   }
2092 }
2093
2094 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2095 ///
2096 ///   handler:
2097 ///     'catch' '(' exception-declaration ')' compound-statement
2098 ///
2099 ///   exception-declaration:
2100 ///     attribute-specifier-seq[opt] type-specifier-seq declarator
2101 ///     attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2102 ///     '...'
2103 ///
2104 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2105   assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2106
2107   SourceLocation CatchLoc = ConsumeToken();
2108
2109   BalancedDelimiterTracker T(*this, tok::l_paren);
2110   if (T.expectAndConsume())
2111     return StmtError();
2112
2113   // C++ 3.3.2p3:
2114   // The name in a catch exception-declaration is local to the handler and
2115   // shall not be redeclared in the outermost block of the handler.
2116   ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2117                           (FnCatch ? Scope::FnTryCatchScope : 0));
2118
2119   // exception-declaration is equivalent to '...' or a parameter-declaration
2120   // without default arguments.
2121   Decl *ExceptionDecl = nullptr;
2122   if (Tok.isNot(tok::ellipsis)) {
2123     ParsedAttributesWithRange Attributes(AttrFactory);
2124     MaybeParseCXX11Attributes(Attributes);
2125
2126     DeclSpec DS(AttrFactory);
2127     DS.takeAttributesFrom(Attributes);
2128
2129     if (ParseCXXTypeSpecifierSeq(DS))
2130       return StmtError();
2131
2132     Declarator ExDecl(DS, Declarator::CXXCatchContext);
2133     ParseDeclarator(ExDecl);
2134     ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2135   } else
2136     ConsumeToken();
2137
2138   T.consumeClose();
2139   if (T.getCloseLocation().isInvalid())
2140     return StmtError();
2141
2142   if (Tok.isNot(tok::l_brace))
2143     return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2144
2145   // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2146   StmtResult Block(ParseCompoundStatement());
2147   if (Block.isInvalid())
2148     return Block;
2149
2150   return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2151 }
2152
2153 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2154   IfExistsCondition Result;
2155   if (ParseMicrosoftIfExistsCondition(Result))
2156     return;
2157
2158   // Handle dependent statements by parsing the braces as a compound statement.
2159   // This is not the same behavior as Visual C++, which don't treat this as a
2160   // compound statement, but for Clang's type checking we can't have anything
2161   // inside these braces escaping to the surrounding code.
2162   if (Result.Behavior == IEB_Dependent) {
2163     if (!Tok.is(tok::l_brace)) {
2164       Diag(Tok, diag::err_expected) << tok::l_brace;
2165       return;
2166     }
2167
2168     StmtResult Compound = ParseCompoundStatement();
2169     if (Compound.isInvalid())
2170       return;
2171
2172     StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2173                                                               Result.IsIfExists,
2174                                                               Result.SS,
2175                                                               Result.Name,
2176                                                               Compound.get());
2177     if (DepResult.isUsable())
2178       Stmts.push_back(DepResult.get());
2179     return;
2180   }
2181
2182   BalancedDelimiterTracker Braces(*this, tok::l_brace);
2183   if (Braces.consumeOpen()) {
2184     Diag(Tok, diag::err_expected) << tok::l_brace;
2185     return;
2186   }
2187
2188   switch (Result.Behavior) {
2189   case IEB_Parse:
2190     // Parse the statements below.
2191     break;
2192
2193   case IEB_Dependent:
2194     llvm_unreachable("Dependent case handled above");
2195
2196   case IEB_Skip:
2197     Braces.skipToEnd();
2198     return;
2199   }
2200
2201   // Condition is true, parse the statements.
2202   while (Tok.isNot(tok::r_brace)) {
2203     StmtResult R = ParseStatementOrDeclaration(Stmts, ACK_Any);
2204     if (R.isUsable())
2205       Stmts.push_back(R.get());
2206   }
2207   Braces.consumeClose();
2208 }