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