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