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