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