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