ParseStmt.cpp revision 218893
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/Sema/DeclSpec.h"
18#include "clang/Sema/PrettyDeclStackTrace.h"
19#include "clang/Sema/Scope.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/PrettyStackTrace.h"
22#include "clang/Basic/SourceManager.h"
23using namespace clang;
24
25//===----------------------------------------------------------------------===//
26// C99 6.8: Statements and Blocks.
27//===----------------------------------------------------------------------===//
28
29/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
30///       StatementOrDeclaration:
31///         statement
32///         declaration
33///
34///       statement:
35///         labeled-statement
36///         compound-statement
37///         expression-statement
38///         selection-statement
39///         iteration-statement
40///         jump-statement
41/// [C++]   declaration-statement
42/// [C++]   try-block
43/// [OBC]   objc-throw-statement
44/// [OBC]   objc-try-catch-statement
45/// [OBC]   objc-synchronized-statement
46/// [GNU]   asm-statement
47/// [OMP]   openmp-construct             [TODO]
48///
49///       labeled-statement:
50///         identifier ':' statement
51///         'case' constant-expression ':' statement
52///         'default' ':' statement
53///
54///       selection-statement:
55///         if-statement
56///         switch-statement
57///
58///       iteration-statement:
59///         while-statement
60///         do-statement
61///         for-statement
62///
63///       expression-statement:
64///         expression[opt] ';'
65///
66///       jump-statement:
67///         'goto' identifier ';'
68///         'continue' ';'
69///         'break' ';'
70///         'return' expression[opt] ';'
71/// [GNU]   'goto' '*' expression ';'
72///
73/// [OBC] objc-throw-statement:
74/// [OBC]   '@' 'throw' expression ';'
75/// [OBC]   '@' 'throw' ';'
76///
77StmtResult
78Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement) {
79  const char *SemiError = 0;
80  StmtResult Res;
81
82  ParenBraceBracketBalancer BalancerRAIIObj(*this);
83
84  ParsedAttributesWithRange attrs;
85  MaybeParseCXX0XAttributes(attrs);
86
87  // Cases in this switch statement should fall through if the parser expects
88  // the token to end in a semicolon (in which case SemiError should be set),
89  // or they directly 'return;' if not.
90  tok::TokenKind Kind  = Tok.getKind();
91  SourceLocation AtLoc;
92  switch (Kind) {
93  case tok::at: // May be a @try or @throw statement
94    {
95      AtLoc = ConsumeToken();  // consume @
96      return ParseObjCAtStatement(AtLoc);
97    }
98
99  case tok::code_completion:
100    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
101    ConsumeCodeCompletionToken();
102    return ParseStatementOrDeclaration(Stmts, OnlyStatement);
103
104  case tok::identifier:
105    if (NextToken().is(tok::colon)) { // C99 6.8.1: labeled-statement
106      // identifier ':' statement
107      return ParseLabeledStatement(attrs);
108    }
109    // PASS THROUGH.
110
111  default: {
112    if ((getLang().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
113      SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
114      DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
115                                             DeclEnd, attrs);
116      return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
117    }
118
119    if (Tok.is(tok::r_brace)) {
120      Diag(Tok, diag::err_expected_statement);
121      return StmtError();
122    }
123
124    // FIXME: Use the attributes
125    // expression[opt] ';'
126    ExprResult Expr(ParseExpression());
127    if (Expr.isInvalid()) {
128      // If the expression is invalid, skip ahead to the next semicolon or '}'.
129      // Not doing this opens us up to the possibility of infinite loops if
130      // ParseExpression does not consume any tokens.
131      SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
132      if (Tok.is(tok::semi))
133        ConsumeToken();
134      return StmtError();
135    }
136    // Otherwise, eat the semicolon.
137    ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
138    return Actions.ActOnExprStmt(Actions.MakeFullExpr(Expr.get()));
139  }
140
141  case tok::kw_case:                // C99 6.8.1: labeled-statement
142    return ParseCaseStatement(attrs);
143  case tok::kw_default:             // C99 6.8.1: labeled-statement
144    return ParseDefaultStatement(attrs);
145
146  case tok::l_brace:                // C99 6.8.2: compound-statement
147    return ParseCompoundStatement(attrs);
148  case tok::semi: {                 // C99 6.8.3p3: expression[opt] ';'
149    bool LeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
150    return Actions.ActOnNullStmt(ConsumeToken(), LeadingEmptyMacro);
151  }
152
153  case tok::kw_if:                  // C99 6.8.4.1: if-statement
154    return ParseIfStatement(attrs);
155  case tok::kw_switch:              // C99 6.8.4.2: switch-statement
156    return ParseSwitchStatement(attrs);
157
158  case tok::kw_while:               // C99 6.8.5.1: while-statement
159    return ParseWhileStatement(attrs);
160  case tok::kw_do:                  // C99 6.8.5.2: do-statement
161    Res = ParseDoStatement(attrs);
162    SemiError = "do/while";
163    break;
164  case tok::kw_for:                 // C99 6.8.5.3: for-statement
165    return ParseForStatement(attrs);
166
167  case tok::kw_goto:                // C99 6.8.6.1: goto-statement
168    Res = ParseGotoStatement(attrs);
169    SemiError = "goto";
170    break;
171  case tok::kw_continue:            // C99 6.8.6.2: continue-statement
172    Res = ParseContinueStatement(attrs);
173    SemiError = "continue";
174    break;
175  case tok::kw_break:               // C99 6.8.6.3: break-statement
176    Res = ParseBreakStatement(attrs);
177    SemiError = "break";
178    break;
179  case tok::kw_return:              // C99 6.8.6.4: return-statement
180    Res = ParseReturnStatement(attrs);
181    SemiError = "return";
182    break;
183
184  case tok::kw_asm: {
185    ProhibitAttributes(attrs);
186    bool msAsm = false;
187    Res = ParseAsmStatement(msAsm);
188    Res = Actions.ActOnFinishFullStmt(Res.get());
189    if (msAsm) return move(Res);
190    SemiError = "asm";
191    break;
192  }
193
194  case tok::kw_try:                 // C++ 15: try-block
195    return ParseCXXTryBlock(attrs);
196  }
197
198  // If we reached this code, the statement must end in a semicolon.
199  if (Tok.is(tok::semi)) {
200    ConsumeToken();
201  } else if (!Res.isInvalid()) {
202    // If the result was valid, then we do want to diagnose this.  Use
203    // ExpectAndConsume to emit the diagnostic, even though we know it won't
204    // succeed.
205    ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
206    // Skip until we see a } or ;, but don't eat it.
207    SkipUntil(tok::r_brace, true, true);
208  }
209
210  return move(Res);
211}
212
213/// ParseLabeledStatement - We have an identifier and a ':' after it.
214///
215///       labeled-statement:
216///         identifier ':' statement
217/// [GNU]   identifier ':' attributes[opt] statement
218///
219StmtResult Parser::ParseLabeledStatement(ParsedAttributes &attrs) {
220  assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
221         "Not an identifier!");
222
223  Token IdentTok = Tok;  // Save the whole token.
224  ConsumeToken();  // eat the identifier.
225
226  assert(Tok.is(tok::colon) && "Not a label!");
227
228  // identifier ':' statement
229  SourceLocation ColonLoc = ConsumeToken();
230
231  // Read label attributes, if present.
232  MaybeParseGNUAttributes(attrs);
233
234  StmtResult SubStmt(ParseStatement());
235
236  // Broken substmt shouldn't prevent the label from being added to the AST.
237  if (SubStmt.isInvalid())
238    SubStmt = Actions.ActOnNullStmt(ColonLoc);
239
240  LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
241                                              IdentTok.getLocation());
242  if (AttributeList *Attrs = attrs.getList())
243    Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
244
245  return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
246                                SubStmt.get());
247}
248
249/// ParseCaseStatement
250///       labeled-statement:
251///         'case' constant-expression ':' statement
252/// [GNU]   'case' constant-expression '...' constant-expression ':' statement
253///
254StmtResult Parser::ParseCaseStatement(ParsedAttributes &attrs) {
255  assert(Tok.is(tok::kw_case) && "Not a case stmt!");
256  // FIXME: Use attributes?
257
258  // It is very very common for code to contain many case statements recursively
259  // nested, as in (but usually without indentation):
260  //  case 1:
261  //    case 2:
262  //      case 3:
263  //         case 4:
264  //           case 5: etc.
265  //
266  // Parsing this naively works, but is both inefficient and can cause us to run
267  // out of stack space in our recursive descent parser.  As a special case,
268  // flatten this recursion into an iterative loop.  This is complex and gross,
269  // but all the grossness is constrained to ParseCaseStatement (and some
270  // wierdness in the actions), so this is just local grossness :).
271
272  // TopLevelCase - This is the highest level we have parsed.  'case 1' in the
273  // example above.
274  StmtResult TopLevelCase(true);
275
276  // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
277  // gets updated each time a new case is parsed, and whose body is unset so
278  // far.  When parsing 'case 4', this is the 'case 3' node.
279  StmtTy *DeepestParsedCaseStmt = 0;
280
281  // While we have case statements, eat and stack them.
282  do {
283    SourceLocation CaseLoc = ConsumeToken();  // eat the 'case'.
284
285    if (Tok.is(tok::code_completion)) {
286      Actions.CodeCompleteCase(getCurScope());
287      ConsumeCodeCompletionToken();
288    }
289
290    /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
291    /// Disable this form of error recovery while we're parsing the case
292    /// expression.
293    ColonProtectionRAIIObject ColonProtection(*this);
294
295    ExprResult LHS(ParseConstantExpression());
296    if (LHS.isInvalid()) {
297      SkipUntil(tok::colon);
298      return StmtError();
299    }
300
301    // GNU case range extension.
302    SourceLocation DotDotDotLoc;
303    ExprResult RHS;
304    if (Tok.is(tok::ellipsis)) {
305      Diag(Tok, diag::ext_gnu_case_range);
306      DotDotDotLoc = ConsumeToken();
307
308      RHS = ParseConstantExpression();
309      if (RHS.isInvalid()) {
310        SkipUntil(tok::colon);
311        return StmtError();
312      }
313    }
314
315    ColonProtection.restore();
316
317    SourceLocation ColonLoc;
318    if (Tok.is(tok::colon)) {
319      ColonLoc = ConsumeToken();
320
321    // Treat "case blah;" as a typo for "case blah:".
322    } else if (Tok.is(tok::semi)) {
323      ColonLoc = ConsumeToken();
324      Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
325        << FixItHint::CreateReplacement(ColonLoc, ":");
326    } else {
327      SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
328      Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
329        << FixItHint::CreateInsertion(ExpectedLoc, ":");
330      ColonLoc = ExpectedLoc;
331    }
332
333    StmtResult Case =
334      Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
335                            RHS.get(), ColonLoc);
336
337    // If we had a sema error parsing this case, then just ignore it and
338    // continue parsing the sub-stmt.
339    if (Case.isInvalid()) {
340      if (TopLevelCase.isInvalid())  // No parsed case stmts.
341        return ParseStatement();
342      // Otherwise, just don't add it as a nested case.
343    } else {
344      // If this is the first case statement we parsed, it becomes TopLevelCase.
345      // Otherwise we link it into the current chain.
346      Stmt *NextDeepest = Case.get();
347      if (TopLevelCase.isInvalid())
348        TopLevelCase = move(Case);
349      else
350        Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
351      DeepestParsedCaseStmt = NextDeepest;
352    }
353
354    // Handle all case statements.
355  } while (Tok.is(tok::kw_case));
356
357  assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
358
359  // If we found a non-case statement, start by parsing it.
360  StmtResult SubStmt;
361
362  if (Tok.isNot(tok::r_brace)) {
363    SubStmt = ParseStatement();
364  } else {
365    // Nicely diagnose the common error "switch (X) { case 4: }", which is
366    // not valid.
367    // FIXME: add insertion hint.
368    Diag(Tok, diag::err_label_end_of_compound_statement);
369    SubStmt = true;
370  }
371
372  // Broken sub-stmt shouldn't prevent forming the case statement properly.
373  if (SubStmt.isInvalid())
374    SubStmt = Actions.ActOnNullStmt(SourceLocation());
375
376  // Install the body into the most deeply-nested case.
377  Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
378
379  // Return the top level parsed statement tree.
380  return move(TopLevelCase);
381}
382
383/// ParseDefaultStatement
384///       labeled-statement:
385///         'default' ':' statement
386/// Note that this does not parse the 'statement' at the end.
387///
388StmtResult Parser::ParseDefaultStatement(ParsedAttributes &attrs) {
389  //FIXME: Use attributes?
390
391  assert(Tok.is(tok::kw_default) && "Not a default stmt!");
392  SourceLocation DefaultLoc = ConsumeToken();  // eat the 'default'.
393
394  SourceLocation ColonLoc;
395  if (Tok.is(tok::colon)) {
396    ColonLoc = ConsumeToken();
397
398  // Treat "default;" as a typo for "default:".
399  } else if (Tok.is(tok::semi)) {
400    ColonLoc = ConsumeToken();
401    Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
402      << FixItHint::CreateReplacement(ColonLoc, ":");
403  } else {
404    SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
405    Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
406      << FixItHint::CreateInsertion(ExpectedLoc, ":");
407    ColonLoc = ExpectedLoc;
408  }
409
410  // Diagnose the common error "switch (X) {... default: }", which is not valid.
411  if (Tok.is(tok::r_brace)) {
412    Diag(Tok, diag::err_label_end_of_compound_statement);
413    return StmtError();
414  }
415
416  StmtResult SubStmt(ParseStatement());
417  if (SubStmt.isInvalid())
418    return StmtError();
419
420  return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
421                                  SubStmt.get(), getCurScope());
422}
423
424
425/// ParseCompoundStatement - Parse a "{}" block.
426///
427///       compound-statement: [C99 6.8.2]
428///         { block-item-list[opt] }
429/// [GNU]   { label-declarations block-item-list } [TODO]
430///
431///       block-item-list:
432///         block-item
433///         block-item-list block-item
434///
435///       block-item:
436///         declaration
437/// [GNU]   '__extension__' declaration
438///         statement
439/// [OMP]   openmp-directive            [TODO]
440///
441/// [GNU] label-declarations:
442/// [GNU]   label-declaration
443/// [GNU]   label-declarations label-declaration
444///
445/// [GNU] label-declaration:
446/// [GNU]   '__label__' identifier-list ';'
447///
448/// [OMP] openmp-directive:             [TODO]
449/// [OMP]   barrier-directive
450/// [OMP]   flush-directive
451///
452StmtResult Parser::ParseCompoundStatement(ParsedAttributes &attrs,
453                                                        bool isStmtExpr) {
454  //FIXME: Use attributes?
455
456  assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
457
458  // Enter a scope to hold everything within the compound stmt.  Compound
459  // statements can always hold declarations.
460  ParseScope CompoundScope(this, Scope::DeclScope);
461
462  // Parse the statements in the body.
463  return ParseCompoundStatementBody(isStmtExpr);
464}
465
466
467/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
468/// ActOnCompoundStmt action.  This expects the '{' to be the current token, and
469/// consume the '}' at the end of the block.  It does not manipulate the scope
470/// stack.
471StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
472  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
473                                Tok.getLocation(),
474                                "in compound statement ('{}')");
475  InMessageExpressionRAIIObject InMessage(*this, false);
476
477  SourceLocation LBraceLoc = ConsumeBrace();  // eat the '{'.
478
479  StmtVector Stmts(Actions);
480
481  // "__label__ X, Y, Z;" is the GNU "Local Label" extension.  These are
482  // only allowed at the start of a compound stmt regardless of the language.
483  while (Tok.is(tok::kw___label__)) {
484    SourceLocation LabelLoc = ConsumeToken();
485    Diag(LabelLoc, diag::ext_gnu_local_label);
486
487    llvm::SmallVector<Decl *, 8> DeclsInGroup;
488    while (1) {
489      if (Tok.isNot(tok::identifier)) {
490        Diag(Tok, diag::err_expected_ident);
491        break;
492      }
493
494      IdentifierInfo *II = Tok.getIdentifierInfo();
495      SourceLocation IdLoc = ConsumeToken();
496      DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, true));
497
498      if (!Tok.is(tok::comma))
499        break;
500      ConsumeToken();
501    }
502
503    DeclSpec DS;
504    DeclGroupPtrTy Res = Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
505                                      DeclsInGroup.data(), DeclsInGroup.size());
506    StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
507
508    ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
509    if (R.isUsable())
510      Stmts.push_back(R.release());
511  }
512
513  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
514    if (Tok.is(tok::annot_pragma_unused)) {
515      HandlePragmaUnused();
516      continue;
517    }
518
519    StmtResult R;
520    if (Tok.isNot(tok::kw___extension__)) {
521      R = ParseStatementOrDeclaration(Stmts, false);
522    } else {
523      // __extension__ can start declarations and it can also be a unary
524      // operator for expressions.  Consume multiple __extension__ markers here
525      // until we can determine which is which.
526      // FIXME: This loses extension expressions in the AST!
527      SourceLocation ExtLoc = ConsumeToken();
528      while (Tok.is(tok::kw___extension__))
529        ConsumeToken();
530
531      ParsedAttributesWithRange attrs;
532      MaybeParseCXX0XAttributes(attrs);
533
534      // If this is the start of a declaration, parse it as such.
535      if (isDeclarationStatement()) {
536        // __extension__ silences extension warnings in the subdeclaration.
537        // FIXME: Save the __extension__ on the decl as a node somehow?
538        ExtensionRAIIObject O(Diags);
539
540        SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
541        DeclGroupPtrTy Res = ParseDeclaration(Stmts,
542                                              Declarator::BlockContext, DeclEnd,
543                                              attrs);
544        R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
545      } else {
546        // Otherwise this was a unary __extension__ marker.
547        ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
548
549        if (Res.isInvalid()) {
550          SkipUntil(tok::semi);
551          continue;
552        }
553
554        // FIXME: Use attributes?
555        // Eat the semicolon at the end of stmt and convert the expr into a
556        // statement.
557        ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
558        R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.get()));
559      }
560    }
561
562    if (R.isUsable())
563      Stmts.push_back(R.release());
564  }
565
566  // We broke out of the while loop because we found a '}' or EOF.
567  if (Tok.isNot(tok::r_brace)) {
568    Diag(Tok, diag::err_expected_rbrace);
569    Diag(LBraceLoc, diag::note_matching) << "{";
570    return StmtError();
571  }
572
573  SourceLocation RBraceLoc = ConsumeBrace();
574  return Actions.ActOnCompoundStmt(LBraceLoc, RBraceLoc, move_arg(Stmts),
575                                   isStmtExpr);
576}
577
578/// ParseParenExprOrCondition:
579/// [C  ]     '(' expression ')'
580/// [C++]     '(' condition ')'       [not allowed if OnlyAllowCondition=true]
581///
582/// This function parses and performs error recovery on the specified condition
583/// or expression (depending on whether we're in C++ or C mode).  This function
584/// goes out of its way to recover well.  It returns true if there was a parser
585/// error (the right paren couldn't be found), which indicates that the caller
586/// should try to recover harder.  It returns false if the condition is
587/// successfully parsed.  Note that a successful parse can still have semantic
588/// errors in the condition.
589bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
590                                       Decl *&DeclResult,
591                                       SourceLocation Loc,
592                                       bool ConvertToBoolean) {
593  SourceLocation LParenLoc = ConsumeParen();
594  if (getLang().CPlusPlus)
595    ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
596  else {
597    ExprResult = ParseExpression();
598    DeclResult = 0;
599
600    // If required, convert to a boolean value.
601    if (!ExprResult.isInvalid() && ConvertToBoolean)
602      ExprResult
603        = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
604  }
605
606  // If the parser was confused by the condition and we don't have a ')', try to
607  // recover by skipping ahead to a semi and bailing out.  If condexp is
608  // semantically invalid but we have well formed code, keep going.
609  if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
610    SkipUntil(tok::semi);
611    // Skipping may have stopped if it found the containing ')'.  If so, we can
612    // continue parsing the if statement.
613    if (Tok.isNot(tok::r_paren))
614      return true;
615  }
616
617  // Otherwise the condition is valid or the rparen is present.
618  MatchRHSPunctuation(tok::r_paren, LParenLoc);
619  return false;
620}
621
622
623/// ParseIfStatement
624///       if-statement: [C99 6.8.4.1]
625///         'if' '(' expression ')' statement
626///         'if' '(' expression ')' statement 'else' statement
627/// [C++]   'if' '(' condition ')' statement
628/// [C++]   'if' '(' condition ')' statement 'else' statement
629///
630StmtResult Parser::ParseIfStatement(ParsedAttributes &attrs) {
631  // FIXME: Use attributes?
632
633  assert(Tok.is(tok::kw_if) && "Not an if stmt!");
634  SourceLocation IfLoc = ConsumeToken();  // eat the 'if'.
635
636  if (Tok.isNot(tok::l_paren)) {
637    Diag(Tok, diag::err_expected_lparen_after) << "if";
638    SkipUntil(tok::semi);
639    return StmtError();
640  }
641
642  bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
643
644  // C99 6.8.4p3 - In C99, the if statement is a block.  This is not
645  // the case for C90.
646  //
647  // C++ 6.4p3:
648  // A name introduced by a declaration in a condition is in scope from its
649  // point of declaration until the end of the substatements controlled by the
650  // condition.
651  // C++ 3.3.2p4:
652  // Names declared in the for-init-statement, and in the condition of if,
653  // while, for, and switch statements are local to the if, while, for, or
654  // switch statement (including the controlled statement).
655  //
656  ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
657
658  // Parse the condition.
659  ExprResult CondExp;
660  Decl *CondVar = 0;
661  if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
662    return StmtError();
663
664  FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get()));
665
666  // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
667  // there is no compound stmt.  C90 does not have this clause.  We only do this
668  // if the body isn't a compound statement to avoid push/pop in common cases.
669  //
670  // C++ 6.4p1:
671  // The substatement in a selection-statement (each substatement, in the else
672  // form of the if statement) implicitly defines a local scope.
673  //
674  // For C++ we create a scope for the condition and a new scope for
675  // substatements because:
676  // -When the 'then' scope exits, we want the condition declaration to still be
677  //    active for the 'else' scope too.
678  // -Sema will detect name clashes by considering declarations of a
679  //    'ControlScope' as part of its direct subscope.
680  // -If we wanted the condition and substatement to be in the same scope, we
681  //    would have to notify ParseStatement not to create a new scope. It's
682  //    simpler to let it create a new scope.
683  //
684  ParseScope InnerScope(this, Scope::DeclScope,
685                        C99orCXX && Tok.isNot(tok::l_brace));
686
687  // Read the 'then' stmt.
688  SourceLocation ThenStmtLoc = Tok.getLocation();
689  StmtResult ThenStmt(ParseStatement());
690
691  // Pop the 'if' scope if needed.
692  InnerScope.Exit();
693
694  // If it has an else, parse it.
695  SourceLocation ElseLoc;
696  SourceLocation ElseStmtLoc;
697  StmtResult ElseStmt;
698
699  if (Tok.is(tok::kw_else)) {
700    ElseLoc = ConsumeToken();
701    ElseStmtLoc = Tok.getLocation();
702
703    // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
704    // there is no compound stmt.  C90 does not have this clause.  We only do
705    // this if the body isn't a compound statement to avoid push/pop in common
706    // cases.
707    //
708    // C++ 6.4p1:
709    // The substatement in a selection-statement (each substatement, in the else
710    // form of the if statement) implicitly defines a local scope.
711    //
712    ParseScope InnerScope(this, Scope::DeclScope,
713                          C99orCXX && Tok.isNot(tok::l_brace));
714
715    ElseStmt = ParseStatement();
716
717    // Pop the 'else' scope if needed.
718    InnerScope.Exit();
719  }
720
721  IfScope.Exit();
722
723  // If the condition was invalid, discard the if statement.  We could recover
724  // better by replacing it with a valid expr, but don't do that yet.
725  if (CondExp.isInvalid() && !CondVar)
726    return StmtError();
727
728  // If the then or else stmt is invalid and the other is valid (and present),
729  // make turn the invalid one into a null stmt to avoid dropping the other
730  // part.  If both are invalid, return error.
731  if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
732      (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
733      (ThenStmt.get() == 0  && ElseStmt.isInvalid())) {
734    // Both invalid, or one is invalid and other is non-present: return error.
735    return StmtError();
736  }
737
738  // Now if either are invalid, replace with a ';'.
739  if (ThenStmt.isInvalid())
740    ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
741  if (ElseStmt.isInvalid())
742    ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
743
744  return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
745                             ElseLoc, ElseStmt.get());
746}
747
748/// ParseSwitchStatement
749///       switch-statement:
750///         'switch' '(' expression ')' statement
751/// [C++]   'switch' '(' condition ')' statement
752StmtResult Parser::ParseSwitchStatement(ParsedAttributes &attrs) {
753  // FIXME: Use attributes?
754
755  assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
756  SourceLocation SwitchLoc = ConsumeToken();  // eat the 'switch'.
757
758  if (Tok.isNot(tok::l_paren)) {
759    Diag(Tok, diag::err_expected_lparen_after) << "switch";
760    SkipUntil(tok::semi);
761    return StmtError();
762  }
763
764  bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
765
766  // C99 6.8.4p3 - In C99, the switch statement is a block.  This is
767  // not the case for C90.  Start the switch scope.
768  //
769  // C++ 6.4p3:
770  // A name introduced by a declaration in a condition is in scope from its
771  // point of declaration until the end of the substatements controlled by the
772  // condition.
773  // C++ 3.3.2p4:
774  // Names declared in the for-init-statement, and in the condition of if,
775  // while, for, and switch statements are local to the if, while, for, or
776  // switch statement (including the controlled statement).
777  //
778  unsigned ScopeFlags = Scope::BreakScope;
779  if (C99orCXX)
780    ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
781  ParseScope SwitchScope(this, ScopeFlags);
782
783  // Parse the condition.
784  ExprResult Cond;
785  Decl *CondVar = 0;
786  if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
787    return StmtError();
788
789  StmtResult Switch
790    = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
791
792  if (Switch.isInvalid()) {
793    // Skip the switch body.
794    // FIXME: This is not optimal recovery, but parsing the body is more
795    // dangerous due to the presence of case and default statements, which
796    // will have no place to connect back with the switch.
797    if (Tok.is(tok::l_brace)) {
798      ConsumeBrace();
799      SkipUntil(tok::r_brace, false, false);
800    } else
801      SkipUntil(tok::semi);
802    return move(Switch);
803  }
804
805  // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
806  // there is no compound stmt.  C90 does not have this clause.  We only do this
807  // if the body isn't a compound statement to avoid push/pop in common cases.
808  //
809  // C++ 6.4p1:
810  // The substatement in a selection-statement (each substatement, in the else
811  // form of the if statement) implicitly defines a local scope.
812  //
813  // See comments in ParseIfStatement for why we create a scope for the
814  // condition and a new scope for substatement in C++.
815  //
816  ParseScope InnerScope(this, Scope::DeclScope,
817                        C99orCXX && Tok.isNot(tok::l_brace));
818
819  // Read the body statement.
820  StmtResult Body(ParseStatement());
821
822  // Pop the scopes.
823  InnerScope.Exit();
824  SwitchScope.Exit();
825
826  if (Body.isInvalid())
827    // FIXME: Remove the case statement list from the Switch statement.
828    Body = Actions.ActOnNullStmt(Tok.getLocation());
829
830  return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
831}
832
833/// ParseWhileStatement
834///       while-statement: [C99 6.8.5.1]
835///         'while' '(' expression ')' statement
836/// [C++]   'while' '(' condition ')' statement
837StmtResult Parser::ParseWhileStatement(ParsedAttributes &attrs) {
838  // FIXME: Use attributes?
839
840  assert(Tok.is(tok::kw_while) && "Not a while stmt!");
841  SourceLocation WhileLoc = Tok.getLocation();
842  ConsumeToken();  // eat the 'while'.
843
844  if (Tok.isNot(tok::l_paren)) {
845    Diag(Tok, diag::err_expected_lparen_after) << "while";
846    SkipUntil(tok::semi);
847    return StmtError();
848  }
849
850  bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
851
852  // C99 6.8.5p5 - In C99, the while statement is a block.  This is not
853  // the case for C90.  Start the loop scope.
854  //
855  // C++ 6.4p3:
856  // A name introduced by a declaration in a condition is in scope from its
857  // point of declaration until the end of the substatements controlled by the
858  // condition.
859  // C++ 3.3.2p4:
860  // Names declared in the for-init-statement, and in the condition of if,
861  // while, for, and switch statements are local to the if, while, for, or
862  // switch statement (including the controlled statement).
863  //
864  unsigned ScopeFlags;
865  if (C99orCXX)
866    ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
867                 Scope::DeclScope  | Scope::ControlScope;
868  else
869    ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
870  ParseScope WhileScope(this, ScopeFlags);
871
872  // Parse the condition.
873  ExprResult Cond;
874  Decl *CondVar = 0;
875  if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
876    return StmtError();
877
878  FullExprArg FullCond(Actions.MakeFullExpr(Cond.get()));
879
880  // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
881  // there is no compound stmt.  C90 does not have this clause.  We only do this
882  // if the body isn't a compound statement to avoid push/pop in common cases.
883  //
884  // C++ 6.5p2:
885  // The substatement in an iteration-statement implicitly defines a local scope
886  // which is entered and exited each time through the loop.
887  //
888  // See comments in ParseIfStatement for why we create a scope for the
889  // condition and a new scope for substatement in C++.
890  //
891  ParseScope InnerScope(this, Scope::DeclScope,
892                        C99orCXX && Tok.isNot(tok::l_brace));
893
894  // Read the body statement.
895  StmtResult Body(ParseStatement());
896
897  // Pop the body scope if needed.
898  InnerScope.Exit();
899  WhileScope.Exit();
900
901  if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
902    return StmtError();
903
904  return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
905}
906
907/// ParseDoStatement
908///       do-statement: [C99 6.8.5.2]
909///         'do' statement 'while' '(' expression ')' ';'
910/// Note: this lets the caller parse the end ';'.
911StmtResult Parser::ParseDoStatement(ParsedAttributes &attrs) {
912  // FIXME: Use attributes?
913
914  assert(Tok.is(tok::kw_do) && "Not a do stmt!");
915  SourceLocation DoLoc = ConsumeToken();  // eat the 'do'.
916
917  // C99 6.8.5p5 - In C99, the do statement is a block.  This is not
918  // the case for C90.  Start the loop scope.
919  unsigned ScopeFlags;
920  if (getLang().C99)
921    ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
922  else
923    ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
924
925  ParseScope DoScope(this, ScopeFlags);
926
927  // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
928  // there is no compound stmt.  C90 does not have this clause. We only do this
929  // if the body isn't a compound statement to avoid push/pop in common cases.
930  //
931  // C++ 6.5p2:
932  // The substatement in an iteration-statement implicitly defines a local scope
933  // which is entered and exited each time through the loop.
934  //
935  ParseScope InnerScope(this, Scope::DeclScope,
936                        (getLang().C99 || getLang().CPlusPlus) &&
937                        Tok.isNot(tok::l_brace));
938
939  // Read the body statement.
940  StmtResult Body(ParseStatement());
941
942  // Pop the body scope if needed.
943  InnerScope.Exit();
944
945  if (Tok.isNot(tok::kw_while)) {
946    if (!Body.isInvalid()) {
947      Diag(Tok, diag::err_expected_while);
948      Diag(DoLoc, diag::note_matching) << "do";
949      SkipUntil(tok::semi, false, true);
950    }
951    return StmtError();
952  }
953  SourceLocation WhileLoc = ConsumeToken();
954
955  if (Tok.isNot(tok::l_paren)) {
956    Diag(Tok, diag::err_expected_lparen_after) << "do/while";
957    SkipUntil(tok::semi, false, true);
958    return StmtError();
959  }
960
961  // Parse the parenthesized condition.
962  SourceLocation LPLoc = ConsumeParen();
963  ExprResult Cond = ParseExpression();
964  SourceLocation RPLoc = MatchRHSPunctuation(tok::r_paren, LPLoc);
965  DoScope.Exit();
966
967  if (Cond.isInvalid() || Body.isInvalid())
968    return StmtError();
969
970  return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, LPLoc,
971                             Cond.get(), RPLoc);
972}
973
974/// ParseForStatement
975///       for-statement: [C99 6.8.5.3]
976///         'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
977///         'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
978/// [C++]   'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
979/// [C++]       statement
980/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
981/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
982///
983/// [C++] for-init-statement:
984/// [C++]   expression-statement
985/// [C++]   simple-declaration
986///
987StmtResult Parser::ParseForStatement(ParsedAttributes &attrs) {
988  // FIXME: Use attributes?
989
990  assert(Tok.is(tok::kw_for) && "Not a for stmt!");
991  SourceLocation ForLoc = ConsumeToken();  // eat the 'for'.
992
993  if (Tok.isNot(tok::l_paren)) {
994    Diag(Tok, diag::err_expected_lparen_after) << "for";
995    SkipUntil(tok::semi);
996    return StmtError();
997  }
998
999  bool C99orCXXorObjC = getLang().C99 || getLang().CPlusPlus || getLang().ObjC1;
1000
1001  // C99 6.8.5p5 - In C99, the for statement is a block.  This is not
1002  // the case for C90.  Start the loop scope.
1003  //
1004  // C++ 6.4p3:
1005  // A name introduced by a declaration in a condition is in scope from its
1006  // point of declaration until the end of the substatements controlled by the
1007  // condition.
1008  // C++ 3.3.2p4:
1009  // Names declared in the for-init-statement, and in the condition of if,
1010  // while, for, and switch statements are local to the if, while, for, or
1011  // switch statement (including the controlled statement).
1012  // C++ 6.5.3p1:
1013  // Names declared in the for-init-statement are in the same declarative-region
1014  // as those declared in the condition.
1015  //
1016  unsigned ScopeFlags;
1017  if (C99orCXXorObjC)
1018    ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1019                 Scope::DeclScope  | Scope::ControlScope;
1020  else
1021    ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1022
1023  ParseScope ForScope(this, ScopeFlags);
1024
1025  SourceLocation LParenLoc = ConsumeParen();
1026  ExprResult Value;
1027
1028  bool ForEach = false;
1029  StmtResult FirstPart;
1030  bool SecondPartIsInvalid = false;
1031  FullExprArg SecondPart(Actions);
1032  ExprResult Collection;
1033  FullExprArg ThirdPart(Actions);
1034  Decl *SecondVar = 0;
1035
1036  if (Tok.is(tok::code_completion)) {
1037    Actions.CodeCompleteOrdinaryName(getCurScope(),
1038                                     C99orCXXorObjC? Sema::PCC_ForInit
1039                                                   : Sema::PCC_Expression);
1040    ConsumeCodeCompletionToken();
1041  }
1042
1043  // Parse the first part of the for specifier.
1044  if (Tok.is(tok::semi)) {  // for (;
1045    // no first part, eat the ';'.
1046    ConsumeToken();
1047  } else if (isSimpleDeclaration()) {  // for (int X = 4;
1048    // Parse declaration, which eats the ';'.
1049    if (!C99orCXXorObjC)   // Use of C99-style for loops in C90 mode?
1050      Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1051
1052    ParsedAttributesWithRange attrs;
1053    MaybeParseCXX0XAttributes(attrs);
1054
1055    SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1056    StmtVector Stmts(Actions);
1057    DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
1058                                               DeclEnd, attrs, false);
1059    FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1060
1061    if (Tok.is(tok::semi)) {  // for (int x = 4;
1062      ConsumeToken();
1063    } else if ((ForEach = isTokIdentifier_in())) {
1064      Actions.ActOnForEachDeclStmt(DG);
1065      // ObjC: for (id x in expr)
1066      ConsumeToken(); // consume 'in'
1067
1068      if (Tok.is(tok::code_completion)) {
1069        Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1070        ConsumeCodeCompletionToken();
1071      }
1072      Collection = ParseExpression();
1073    } else {
1074      Diag(Tok, diag::err_expected_semi_for);
1075    }
1076  } else {
1077    Value = ParseExpression();
1078
1079    ForEach = isTokIdentifier_in();
1080
1081    // Turn the expression into a stmt.
1082    if (!Value.isInvalid()) {
1083      if (ForEach)
1084        FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1085      else
1086        FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value.get()));
1087    }
1088
1089    if (Tok.is(tok::semi)) {
1090      ConsumeToken();
1091    } else if (ForEach) {
1092      ConsumeToken(); // consume 'in'
1093
1094      if (Tok.is(tok::code_completion)) {
1095        Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
1096        ConsumeCodeCompletionToken();
1097      }
1098      Collection = ParseExpression();
1099    } else {
1100      if (!Value.isInvalid()) {
1101        Diag(Tok, diag::err_expected_semi_for);
1102      } else {
1103        // Skip until semicolon or rparen, don't consume it.
1104        SkipUntil(tok::r_paren, true, true);
1105        if (Tok.is(tok::semi))
1106          ConsumeToken();
1107      }
1108    }
1109  }
1110  if (!ForEach) {
1111    assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
1112    // Parse the second part of the for specifier.
1113    if (Tok.is(tok::semi)) {  // for (...;;
1114      // no second part.
1115    } else if (Tok.is(tok::r_paren)) {
1116      // missing both semicolons.
1117    } else {
1118      ExprResult Second;
1119      if (getLang().CPlusPlus)
1120        ParseCXXCondition(Second, SecondVar, ForLoc, true);
1121      else {
1122        Second = ParseExpression();
1123        if (!Second.isInvalid())
1124          Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
1125                                                 Second.get());
1126      }
1127      SecondPartIsInvalid = Second.isInvalid();
1128      SecondPart = Actions.MakeFullExpr(Second.get());
1129    }
1130
1131    if (Tok.isNot(tok::semi)) {
1132      if (!SecondPartIsInvalid || SecondVar)
1133        Diag(Tok, diag::err_expected_semi_for);
1134      else
1135        // Skip until semicolon or rparen, don't consume it.
1136        SkipUntil(tok::r_paren, true, true);
1137    }
1138
1139    if (Tok.is(tok::semi)) {
1140      ConsumeToken();
1141    }
1142
1143    // Parse the third part of the for specifier.
1144    if (Tok.isNot(tok::r_paren)) {   // for (...;...;)
1145      ExprResult Third = ParseExpression();
1146      ThirdPart = Actions.MakeFullExpr(Third.take());
1147    }
1148  }
1149  // Match the ')'.
1150  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1151
1152  // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1153  // there is no compound stmt.  C90 does not have this clause.  We only do this
1154  // if the body isn't a compound statement to avoid push/pop in common cases.
1155  //
1156  // C++ 6.5p2:
1157  // The substatement in an iteration-statement implicitly defines a local scope
1158  // which is entered and exited each time through the loop.
1159  //
1160  // See comments in ParseIfStatement for why we create a scope for
1161  // for-init-statement/condition and a new scope for substatement in C++.
1162  //
1163  ParseScope InnerScope(this, Scope::DeclScope,
1164                        C99orCXXorObjC && Tok.isNot(tok::l_brace));
1165
1166  // Read the body statement.
1167  StmtResult Body(ParseStatement());
1168
1169  // Pop the body scope if needed.
1170  InnerScope.Exit();
1171
1172  // Leave the for-scope.
1173  ForScope.Exit();
1174
1175  if (Body.isInvalid())
1176    return StmtError();
1177
1178  if (!ForEach)
1179    return Actions.ActOnForStmt(ForLoc, LParenLoc, FirstPart.take(), SecondPart,
1180                                SecondVar, ThirdPart, RParenLoc, Body.take());
1181
1182  // FIXME: It isn't clear how to communicate the late destruction of
1183  // C++ temporaries used to create the collection.
1184  return Actions.ActOnObjCForCollectionStmt(ForLoc, LParenLoc, FirstPart.take(),
1185                                            Collection.take(), RParenLoc,
1186                                            Body.take());
1187}
1188
1189/// ParseGotoStatement
1190///       jump-statement:
1191///         'goto' identifier ';'
1192/// [GNU]   'goto' '*' expression ';'
1193///
1194/// Note: this lets the caller parse the end ';'.
1195///
1196StmtResult Parser::ParseGotoStatement(ParsedAttributes &attrs) {
1197  // FIXME: Use attributes?
1198
1199  assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1200  SourceLocation GotoLoc = ConsumeToken();  // eat the 'goto'.
1201
1202  StmtResult Res;
1203  if (Tok.is(tok::identifier)) {
1204    LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1205                                                Tok.getLocation());
1206    Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1207    ConsumeToken();
1208  } else if (Tok.is(tok::star)) {
1209    // GNU indirect goto extension.
1210    Diag(Tok, diag::ext_gnu_indirect_goto);
1211    SourceLocation StarLoc = ConsumeToken();
1212    ExprResult R(ParseExpression());
1213    if (R.isInvalid()) {  // Skip to the semicolon, but don't consume it.
1214      SkipUntil(tok::semi, false, true);
1215      return StmtError();
1216    }
1217    Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
1218  } else {
1219    Diag(Tok, diag::err_expected_ident);
1220    return StmtError();
1221  }
1222
1223  return move(Res);
1224}
1225
1226/// ParseContinueStatement
1227///       jump-statement:
1228///         'continue' ';'
1229///
1230/// Note: this lets the caller parse the end ';'.
1231///
1232StmtResult Parser::ParseContinueStatement(ParsedAttributes &attrs) {
1233  // FIXME: Use attributes?
1234
1235  SourceLocation ContinueLoc = ConsumeToken();  // eat the 'continue'.
1236  return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1237}
1238
1239/// ParseBreakStatement
1240///       jump-statement:
1241///         'break' ';'
1242///
1243/// Note: this lets the caller parse the end ';'.
1244///
1245StmtResult Parser::ParseBreakStatement(ParsedAttributes &attrs) {
1246  // FIXME: Use attributes?
1247
1248  SourceLocation BreakLoc = ConsumeToken();  // eat the 'break'.
1249  return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1250}
1251
1252/// ParseReturnStatement
1253///       jump-statement:
1254///         'return' expression[opt] ';'
1255StmtResult Parser::ParseReturnStatement(ParsedAttributes &attrs) {
1256  // FIXME: Use attributes?
1257
1258  assert(Tok.is(tok::kw_return) && "Not a return stmt!");
1259  SourceLocation ReturnLoc = ConsumeToken();  // eat the 'return'.
1260
1261  ExprResult R;
1262  if (Tok.isNot(tok::semi)) {
1263    if (Tok.is(tok::code_completion)) {
1264      Actions.CodeCompleteReturn(getCurScope());
1265      ConsumeCodeCompletionToken();
1266      SkipUntil(tok::semi, false, true);
1267      return StmtError();
1268    }
1269
1270    R = ParseExpression();
1271    if (R.isInvalid()) {  // Skip to the semicolon, but don't consume it.
1272      SkipUntil(tok::semi, false, true);
1273      return StmtError();
1274    }
1275  }
1276  return Actions.ActOnReturnStmt(ReturnLoc, R.take());
1277}
1278
1279/// FuzzyParseMicrosoftAsmStatement. When -fms-extensions is enabled, this
1280/// routine is called to skip/ignore tokens that comprise the MS asm statement.
1281StmtResult Parser::FuzzyParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
1282  SourceLocation EndLoc;
1283  if (Tok.is(tok::l_brace)) {
1284    unsigned short savedBraceCount = BraceCount;
1285    do {
1286      EndLoc = Tok.getLocation();
1287      ConsumeAnyToken();
1288    } while (BraceCount > savedBraceCount && Tok.isNot(tok::eof));
1289  } else {
1290    // From the MS website: If used without braces, the __asm keyword means
1291    // that the rest of the line is an assembly-language statement.
1292    SourceManager &SrcMgr = PP.getSourceManager();
1293    SourceLocation TokLoc = Tok.getLocation();
1294    unsigned LineNo = SrcMgr.getInstantiationLineNumber(TokLoc);
1295    do {
1296      EndLoc = TokLoc;
1297      ConsumeAnyToken();
1298      TokLoc = Tok.getLocation();
1299    } while ((SrcMgr.getInstantiationLineNumber(TokLoc) == LineNo) &&
1300             Tok.isNot(tok::r_brace) && Tok.isNot(tok::semi) &&
1301             Tok.isNot(tok::eof));
1302  }
1303  Token t;
1304  t.setKind(tok::string_literal);
1305  t.setLiteralData("\"/*FIXME: not done*/\"");
1306  t.clearFlag(Token::NeedsCleaning);
1307  t.setLength(21);
1308  ExprResult AsmString(Actions.ActOnStringLiteral(&t, 1));
1309  ExprVector Constraints(Actions);
1310  ExprVector Exprs(Actions);
1311  ExprVector Clobbers(Actions);
1312  return Actions.ActOnAsmStmt(AsmLoc, true, true, 0, 0, 0,
1313                              move_arg(Constraints), move_arg(Exprs),
1314                              AsmString.take(), move_arg(Clobbers),
1315                              EndLoc, true);
1316}
1317
1318/// ParseAsmStatement - Parse a GNU extended asm statement.
1319///       asm-statement:
1320///         gnu-asm-statement
1321///         ms-asm-statement
1322///
1323/// [GNU] gnu-asm-statement:
1324///         'asm' type-qualifier[opt] '(' asm-argument ')' ';'
1325///
1326/// [GNU] asm-argument:
1327///         asm-string-literal
1328///         asm-string-literal ':' asm-operands[opt]
1329///         asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1330///         asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1331///                 ':' asm-clobbers
1332///
1333/// [GNU] asm-clobbers:
1334///         asm-string-literal
1335///         asm-clobbers ',' asm-string-literal
1336///
1337/// [MS]  ms-asm-statement:
1338///         '__asm' assembly-instruction ';'[opt]
1339///         '__asm' '{' assembly-instruction-list '}' ';'[opt]
1340///
1341/// [MS]  assembly-instruction-list:
1342///         assembly-instruction ';'[opt]
1343///         assembly-instruction-list ';' assembly-instruction ';'[opt]
1344///
1345StmtResult Parser::ParseAsmStatement(bool &msAsm) {
1346  assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
1347  SourceLocation AsmLoc = ConsumeToken();
1348
1349  if (getLang().Microsoft && Tok.isNot(tok::l_paren) && !isTypeQualifier()) {
1350    msAsm = true;
1351    return FuzzyParseMicrosoftAsmStatement(AsmLoc);
1352  }
1353  DeclSpec DS;
1354  SourceLocation Loc = Tok.getLocation();
1355  ParseTypeQualifierListOpt(DS, true, false);
1356
1357  // GNU asms accept, but warn, about type-qualifiers other than volatile.
1358  if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1359    Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
1360  if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
1361    Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
1362
1363  // Remember if this was a volatile asm.
1364  bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
1365  if (Tok.isNot(tok::l_paren)) {
1366    Diag(Tok, diag::err_expected_lparen_after) << "asm";
1367    SkipUntil(tok::r_paren);
1368    return StmtError();
1369  }
1370  Loc = ConsumeParen();
1371
1372  ExprResult AsmString(ParseAsmStringLiteral());
1373  if (AsmString.isInvalid())
1374    return StmtError();
1375
1376  llvm::SmallVector<IdentifierInfo *, 4> Names;
1377  ExprVector Constraints(Actions);
1378  ExprVector Exprs(Actions);
1379  ExprVector Clobbers(Actions);
1380
1381  if (Tok.is(tok::r_paren)) {
1382    // We have a simple asm expression like 'asm("foo")'.
1383    SourceLocation RParenLoc = ConsumeParen();
1384    return Actions.ActOnAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
1385                                /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
1386                                move_arg(Constraints), move_arg(Exprs),
1387                                AsmString.take(), move_arg(Clobbers),
1388                                RParenLoc);
1389  }
1390
1391  // Parse Outputs, if present.
1392  bool AteExtraColon = false;
1393  if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1394    // In C++ mode, parse "::" like ": :".
1395    AteExtraColon = Tok.is(tok::coloncolon);
1396    ConsumeToken();
1397
1398    if (!AteExtraColon &&
1399        ParseAsmOperandsOpt(Names, Constraints, Exprs))
1400      return StmtError();
1401  }
1402
1403  unsigned NumOutputs = Names.size();
1404
1405  // Parse Inputs, if present.
1406  if (AteExtraColon ||
1407      Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1408    // In C++ mode, parse "::" like ": :".
1409    if (AteExtraColon)
1410      AteExtraColon = false;
1411    else {
1412      AteExtraColon = Tok.is(tok::coloncolon);
1413      ConsumeToken();
1414    }
1415
1416    if (!AteExtraColon &&
1417        ParseAsmOperandsOpt(Names, Constraints, Exprs))
1418      return StmtError();
1419  }
1420
1421  assert(Names.size() == Constraints.size() &&
1422         Constraints.size() == Exprs.size() &&
1423         "Input operand size mismatch!");
1424
1425  unsigned NumInputs = Names.size() - NumOutputs;
1426
1427  // Parse the clobbers, if present.
1428  if (AteExtraColon || Tok.is(tok::colon)) {
1429    if (!AteExtraColon)
1430      ConsumeToken();
1431
1432    // Parse the asm-string list for clobbers if present.
1433    if (Tok.isNot(tok::r_paren)) {
1434      while (1) {
1435        ExprResult Clobber(ParseAsmStringLiteral());
1436
1437        if (Clobber.isInvalid())
1438          break;
1439
1440        Clobbers.push_back(Clobber.release());
1441
1442        if (Tok.isNot(tok::comma)) break;
1443        ConsumeToken();
1444      }
1445    }
1446  }
1447
1448  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, Loc);
1449  return Actions.ActOnAsmStmt(AsmLoc, false, isVolatile,
1450                              NumOutputs, NumInputs, Names.data(),
1451                              move_arg(Constraints), move_arg(Exprs),
1452                              AsmString.take(), move_arg(Clobbers),
1453                              RParenLoc);
1454}
1455
1456/// ParseAsmOperands - Parse the asm-operands production as used by
1457/// asm-statement, assuming the leading ':' token was eaten.
1458///
1459/// [GNU] asm-operands:
1460///         asm-operand
1461///         asm-operands ',' asm-operand
1462///
1463/// [GNU] asm-operand:
1464///         asm-string-literal '(' expression ')'
1465///         '[' identifier ']' asm-string-literal '(' expression ')'
1466///
1467//
1468// FIXME: Avoid unnecessary std::string trashing.
1469bool Parser::ParseAsmOperandsOpt(llvm::SmallVectorImpl<IdentifierInfo *> &Names,
1470                                 llvm::SmallVectorImpl<ExprTy *> &Constraints,
1471                                 llvm::SmallVectorImpl<ExprTy *> &Exprs) {
1472  // 'asm-operands' isn't present?
1473  if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
1474    return false;
1475
1476  while (1) {
1477    // Read the [id] if present.
1478    if (Tok.is(tok::l_square)) {
1479      SourceLocation Loc = ConsumeBracket();
1480
1481      if (Tok.isNot(tok::identifier)) {
1482        Diag(Tok, diag::err_expected_ident);
1483        SkipUntil(tok::r_paren);
1484        return true;
1485      }
1486
1487      IdentifierInfo *II = Tok.getIdentifierInfo();
1488      ConsumeToken();
1489
1490      Names.push_back(II);
1491      MatchRHSPunctuation(tok::r_square, Loc);
1492    } else
1493      Names.push_back(0);
1494
1495    ExprResult Constraint(ParseAsmStringLiteral());
1496    if (Constraint.isInvalid()) {
1497        SkipUntil(tok::r_paren);
1498        return true;
1499    }
1500    Constraints.push_back(Constraint.release());
1501
1502    if (Tok.isNot(tok::l_paren)) {
1503      Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
1504      SkipUntil(tok::r_paren);
1505      return true;
1506    }
1507
1508    // Read the parenthesized expression.
1509    SourceLocation OpenLoc = ConsumeParen();
1510    ExprResult Res(ParseExpression());
1511    MatchRHSPunctuation(tok::r_paren, OpenLoc);
1512    if (Res.isInvalid()) {
1513      SkipUntil(tok::r_paren);
1514      return true;
1515    }
1516    Exprs.push_back(Res.release());
1517    // Eat the comma and continue parsing if it exists.
1518    if (Tok.isNot(tok::comma)) return false;
1519    ConsumeToken();
1520  }
1521
1522  return true;
1523}
1524
1525Decl *Parser::ParseFunctionStatementBody(Decl *Decl) {
1526  assert(Tok.is(tok::l_brace));
1527  SourceLocation LBraceLoc = Tok.getLocation();
1528
1529  if (PP.isCodeCompletionEnabled())
1530    if (trySkippingFunctionBodyForCodeCompletion())
1531      return Actions.ActOnFinishFunctionBody(Decl, 0);
1532
1533  PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1534                                      "parsing function body");
1535
1536  // Do not enter a scope for the brace, as the arguments are in the same scope
1537  // (the function body) as the body itself.  Instead, just read the statement
1538  // list and put it into a CompoundStmt for safe keeping.
1539  StmtResult FnBody(ParseCompoundStatementBody());
1540
1541  // If the function body could not be parsed, make a bogus compoundstmt.
1542  if (FnBody.isInvalid())
1543    FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1544                                       MultiStmtArg(Actions), false);
1545
1546  return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
1547}
1548
1549/// ParseFunctionTryBlock - Parse a C++ function-try-block.
1550///
1551///       function-try-block:
1552///         'try' ctor-initializer[opt] compound-statement handler-seq
1553///
1554Decl *Parser::ParseFunctionTryBlock(Decl *Decl) {
1555  assert(Tok.is(tok::kw_try) && "Expected 'try'");
1556  SourceLocation TryLoc = ConsumeToken();
1557
1558  PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1559                                      "parsing function try block");
1560
1561  // Constructor initializer list?
1562  if (Tok.is(tok::colon))
1563    ParseConstructorInitializer(Decl);
1564
1565  if (PP.isCodeCompletionEnabled())
1566    if (trySkippingFunctionBodyForCodeCompletion())
1567      return Actions.ActOnFinishFunctionBody(Decl, 0);
1568
1569  SourceLocation LBraceLoc = Tok.getLocation();
1570  StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc));
1571  // If we failed to parse the try-catch, we just give the function an empty
1572  // compound statement as the body.
1573  if (FnBody.isInvalid())
1574    FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1575                                       MultiStmtArg(Actions), false);
1576
1577  return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
1578}
1579
1580bool Parser::trySkippingFunctionBodyForCodeCompletion() {
1581  assert(Tok.is(tok::l_brace));
1582  assert(PP.isCodeCompletionEnabled() &&
1583         "Should only be called when in code-completion mode");
1584
1585  // We're in code-completion mode. Skip parsing for all function bodies unless
1586  // the body contains the code-completion point.
1587  TentativeParsingAction PA(*this);
1588  ConsumeBrace();
1589  if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
1590                /*StopAtCodeCompletion=*/true)) {
1591    PA.Commit();
1592    return true;
1593  }
1594
1595  PA.Revert();
1596  return false;
1597}
1598
1599/// ParseCXXTryBlock - Parse a C++ try-block.
1600///
1601///       try-block:
1602///         'try' compound-statement handler-seq
1603///
1604StmtResult Parser::ParseCXXTryBlock(ParsedAttributes &attrs) {
1605  // FIXME: Add attributes?
1606
1607  assert(Tok.is(tok::kw_try) && "Expected 'try'");
1608
1609  SourceLocation TryLoc = ConsumeToken();
1610  return ParseCXXTryBlockCommon(TryLoc);
1611}
1612
1613/// ParseCXXTryBlockCommon - Parse the common part of try-block and
1614/// function-try-block.
1615///
1616///       try-block:
1617///         'try' compound-statement handler-seq
1618///
1619///       function-try-block:
1620///         'try' ctor-initializer[opt] compound-statement handler-seq
1621///
1622///       handler-seq:
1623///         handler handler-seq[opt]
1624///
1625StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc) {
1626  if (Tok.isNot(tok::l_brace))
1627    return StmtError(Diag(Tok, diag::err_expected_lbrace));
1628  // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1629  ParsedAttributesWithRange attrs;
1630  StmtResult TryBlock(ParseCompoundStatement(attrs));
1631  if (TryBlock.isInvalid())
1632    return move(TryBlock);
1633
1634  StmtVector Handlers(Actions);
1635  MaybeParseCXX0XAttributes(attrs);
1636  ProhibitAttributes(attrs);
1637
1638  if (Tok.isNot(tok::kw_catch))
1639    return StmtError(Diag(Tok, diag::err_expected_catch));
1640  while (Tok.is(tok::kw_catch)) {
1641    StmtResult Handler(ParseCXXCatchBlock());
1642    if (!Handler.isInvalid())
1643      Handlers.push_back(Handler.release());
1644  }
1645  // Don't bother creating the full statement if we don't have any usable
1646  // handlers.
1647  if (Handlers.empty())
1648    return StmtError();
1649
1650  return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), move_arg(Handlers));
1651}
1652
1653/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
1654///
1655///       handler:
1656///         'catch' '(' exception-declaration ')' compound-statement
1657///
1658///       exception-declaration:
1659///         type-specifier-seq declarator
1660///         type-specifier-seq abstract-declarator
1661///         type-specifier-seq
1662///         '...'
1663///
1664StmtResult Parser::ParseCXXCatchBlock() {
1665  assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
1666
1667  SourceLocation CatchLoc = ConsumeToken();
1668
1669  SourceLocation LParenLoc = Tok.getLocation();
1670  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
1671    return StmtError();
1672
1673  // C++ 3.3.2p3:
1674  // The name in a catch exception-declaration is local to the handler and
1675  // shall not be redeclared in the outermost block of the handler.
1676  ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope);
1677
1678  // exception-declaration is equivalent to '...' or a parameter-declaration
1679  // without default arguments.
1680  Decl *ExceptionDecl = 0;
1681  if (Tok.isNot(tok::ellipsis)) {
1682    DeclSpec DS;
1683    if (ParseCXXTypeSpecifierSeq(DS))
1684      return StmtError();
1685    Declarator ExDecl(DS, Declarator::CXXCatchContext);
1686    ParseDeclarator(ExDecl);
1687    ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
1688  } else
1689    ConsumeToken();
1690
1691  if (MatchRHSPunctuation(tok::r_paren, LParenLoc).isInvalid())
1692    return StmtError();
1693
1694  if (Tok.isNot(tok::l_brace))
1695    return StmtError(Diag(Tok, diag::err_expected_lbrace));
1696
1697  // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1698  ParsedAttributes attrs;
1699  StmtResult Block(ParseCompoundStatement(attrs));
1700  if (Block.isInvalid())
1701    return move(Block);
1702
1703  return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
1704}
1705