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