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