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