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