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