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