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