clang API Documentation

ParseStmt.cpp
Go to the documentation of this file.
00001 //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Statement and Block portions of the Parser
00011 // interface.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Parse/Parser.h"
00016 #include "RAIIObjectsForParser.h"
00017 #include "clang/Sema/DeclSpec.h"
00018 #include "clang/Sema/PrettyDeclStackTrace.h"
00019 #include "clang/Sema/Scope.h"
00020 #include "clang/Basic/Diagnostic.h"
00021 #include "clang/Basic/PrettyStackTrace.h"
00022 #include "clang/Basic/SourceManager.h"
00023 using namespace clang;
00024 
00025 //===----------------------------------------------------------------------===//
00026 // C99 6.8: Statements and Blocks.
00027 //===----------------------------------------------------------------------===//
00028 
00029 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
00030 ///       StatementOrDeclaration:
00031 ///         statement
00032 ///         declaration
00033 ///
00034 ///       statement:
00035 ///         labeled-statement
00036 ///         compound-statement
00037 ///         expression-statement
00038 ///         selection-statement
00039 ///         iteration-statement
00040 ///         jump-statement
00041 /// [C++]   declaration-statement
00042 /// [C++]   try-block
00043 /// [MS]    seh-try-block
00044 /// [OBC]   objc-throw-statement
00045 /// [OBC]   objc-try-catch-statement
00046 /// [OBC]   objc-synchronized-statement
00047 /// [GNU]   asm-statement
00048 /// [OMP]   openmp-construct             [TODO]
00049 ///
00050 ///       labeled-statement:
00051 ///         identifier ':' statement
00052 ///         'case' constant-expression ':' statement
00053 ///         'default' ':' statement
00054 ///
00055 ///       selection-statement:
00056 ///         if-statement
00057 ///         switch-statement
00058 ///
00059 ///       iteration-statement:
00060 ///         while-statement
00061 ///         do-statement
00062 ///         for-statement
00063 ///
00064 ///       expression-statement:
00065 ///         expression[opt] ';'
00066 ///
00067 ///       jump-statement:
00068 ///         'goto' identifier ';'
00069 ///         'continue' ';'
00070 ///         'break' ';'
00071 ///         'return' expression[opt] ';'
00072 /// [GNU]   'goto' '*' expression ';'
00073 ///
00074 /// [OBC] objc-throw-statement:
00075 /// [OBC]   '@' 'throw' expression ';'
00076 /// [OBC]   '@' 'throw' ';'
00077 ///
00078 StmtResult
00079 Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
00080                                     SourceLocation *TrailingElseLoc) {
00081 
00082   ParenBraceBracketBalancer BalancerRAIIObj(*this);
00083 
00084   ParsedAttributesWithRange Attrs(AttrFactory);
00085   MaybeParseCXX0XAttributes(Attrs, 0, /*MightBeObjCMessageSend*/ true);
00086 
00087   StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts,
00088                                  OnlyStatement, TrailingElseLoc, Attrs);
00089 
00090   assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
00091          "attributes on empty statement");
00092 
00093   if (Attrs.empty() || Res.isInvalid())
00094     return Res;
00095 
00096   return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
00097 }
00098 
00099 StmtResult
00100 Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
00101           bool OnlyStatement, SourceLocation *TrailingElseLoc,
00102           ParsedAttributesWithRange &Attrs) {
00103   const char *SemiError = 0;
00104   StmtResult Res;
00105 
00106   // Cases in this switch statement should fall through if the parser expects
00107   // the token to end in a semicolon (in which case SemiError should be set),
00108   // or they directly 'return;' if not.
00109 Retry:
00110   tok::TokenKind Kind  = Tok.getKind();
00111   SourceLocation AtLoc;
00112   switch (Kind) {
00113   case tok::at: // May be a @try or @throw statement
00114     {
00115       ProhibitAttributes(Attrs); // TODO: is it correct?
00116       AtLoc = ConsumeToken();  // consume @
00117       return ParseObjCAtStatement(AtLoc);
00118     }
00119 
00120   case tok::code_completion:
00121     Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
00122     cutOffParsing();
00123     return StmtError();
00124 
00125   case tok::identifier: {
00126     Token Next = NextToken();
00127     if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
00128       // identifier ':' statement
00129       return ParseLabeledStatement(Attrs);
00130     }
00131 
00132     if (Next.isNot(tok::coloncolon)) {
00133       CXXScopeSpec SS;
00134       IdentifierInfo *Name = Tok.getIdentifierInfo();
00135       SourceLocation NameLoc = Tok.getLocation();
00136 
00137       if (getLangOpts().CPlusPlus)
00138         CheckForTemplateAndDigraph(Next, ParsedType(),
00139                                    /*EnteringContext=*/false, *Name, SS);
00140 
00141       Sema::NameClassification Classification
00142         = Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next);
00143       switch (Classification.getKind()) {
00144       case Sema::NC_Keyword:
00145         // The identifier was corrected to a keyword. Update the token
00146         // to this keyword, and try again.
00147         if (Name->getTokenID() != tok::identifier) {
00148           Tok.setIdentifierInfo(Name);
00149           Tok.setKind(Name->getTokenID());
00150           goto Retry;
00151         }
00152 
00153         // Fall through via the normal error path.
00154         // FIXME: This seems like it could only happen for context-sensitive
00155         // keywords.
00156 
00157       case Sema::NC_Error:
00158         // Handle errors here by skipping up to the next semicolon or '}', and
00159         // eat the semicolon if that's what stopped us.
00160         SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
00161         if (Tok.is(tok::semi))
00162           ConsumeToken();
00163         return StmtError();
00164 
00165       case Sema::NC_Unknown:
00166         // Either we don't know anything about this identifier, or we know that
00167         // we're in a syntactic context we haven't handled yet.
00168         break;
00169 
00170       case Sema::NC_Type:
00171         Tok.setKind(tok::annot_typename);
00172         setTypeAnnotation(Tok, Classification.getType());
00173         Tok.setAnnotationEndLoc(NameLoc);
00174         PP.AnnotateCachedTokens(Tok);
00175         break;
00176 
00177       case Sema::NC_Expression:
00178         Tok.setKind(tok::annot_primary_expr);
00179         setExprAnnotation(Tok, Classification.getExpression());
00180         Tok.setAnnotationEndLoc(NameLoc);
00181         PP.AnnotateCachedTokens(Tok);
00182         break;
00183 
00184       case Sema::NC_TypeTemplate:
00185       case Sema::NC_FunctionTemplate: {
00186         ConsumeToken(); // the identifier
00187         UnqualifiedId Id;
00188         Id.setIdentifier(Name, NameLoc);
00189         if (AnnotateTemplateIdToken(
00190                             TemplateTy::make(Classification.getTemplateName()),
00191                                     Classification.getTemplateNameKind(),
00192                                     SS, SourceLocation(), Id,
00193                                     /*AllowTypeAnnotation=*/false)) {
00194           // Handle errors here by skipping up to the next semicolon or '}', and
00195           // eat the semicolon if that's what stopped us.
00196           SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
00197           if (Tok.is(tok::semi))
00198             ConsumeToken();
00199           return StmtError();
00200         }
00201 
00202         // If the next token is '::', jump right into parsing a
00203         // nested-name-specifier. We don't want to leave the template-id
00204         // hanging.
00205         if (NextToken().is(tok::coloncolon) && TryAnnotateCXXScopeToken(false)){
00206           // Handle errors here by skipping up to the next semicolon or '}', and
00207           // eat the semicolon if that's what stopped us.
00208           SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
00209           if (Tok.is(tok::semi))
00210             ConsumeToken();
00211           return StmtError();
00212         }
00213 
00214         // We've annotated a template-id, so try again now.
00215         goto Retry;
00216       }
00217 
00218       case Sema::NC_NestedNameSpecifier:
00219         // FIXME: Implement this!
00220         break;
00221       }
00222     }
00223 
00224     // Fall through
00225   }
00226 
00227   default: {
00228     if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
00229       SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
00230       DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
00231                                              DeclEnd, Attrs);
00232       return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
00233     }
00234 
00235     if (Tok.is(tok::r_brace)) {
00236       Diag(Tok, diag::err_expected_statement);
00237       return StmtError();
00238     }
00239 
00240     return ParseExprStatement();
00241   }
00242 
00243   case tok::kw_case:                // C99 6.8.1: labeled-statement
00244     return ParseCaseStatement();
00245   case tok::kw_default:             // C99 6.8.1: labeled-statement
00246     return ParseDefaultStatement();
00247 
00248   case tok::l_brace:                // C99 6.8.2: compound-statement
00249     return ParseCompoundStatement();
00250   case tok::semi: {                 // C99 6.8.3p3: expression[opt] ';'
00251     bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
00252     return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
00253   }
00254 
00255   case tok::kw_if:                  // C99 6.8.4.1: if-statement
00256     return ParseIfStatement(TrailingElseLoc);
00257   case tok::kw_switch:              // C99 6.8.4.2: switch-statement
00258     return ParseSwitchStatement(TrailingElseLoc);
00259 
00260   case tok::kw_while:               // C99 6.8.5.1: while-statement
00261     return ParseWhileStatement(TrailingElseLoc);
00262   case tok::kw_do:                  // C99 6.8.5.2: do-statement
00263     Res = ParseDoStatement();
00264     SemiError = "do/while";
00265     break;
00266   case tok::kw_for:                 // C99 6.8.5.3: for-statement
00267     return ParseForStatement(TrailingElseLoc);
00268 
00269   case tok::kw_goto:                // C99 6.8.6.1: goto-statement
00270     Res = ParseGotoStatement();
00271     SemiError = "goto";
00272     break;
00273   case tok::kw_continue:            // C99 6.8.6.2: continue-statement
00274     Res = ParseContinueStatement();
00275     SemiError = "continue";
00276     break;
00277   case tok::kw_break:               // C99 6.8.6.3: break-statement
00278     Res = ParseBreakStatement();
00279     SemiError = "break";
00280     break;
00281   case tok::kw_return:              // C99 6.8.6.4: return-statement
00282     Res = ParseReturnStatement();
00283     SemiError = "return";
00284     break;
00285 
00286   case tok::kw_asm: {
00287     ProhibitAttributes(Attrs);
00288     bool msAsm = false;
00289     Res = ParseAsmStatement(msAsm);
00290     Res = Actions.ActOnFinishFullStmt(Res.get());
00291     if (msAsm) return move(Res);
00292     SemiError = "asm";
00293     break;
00294   }
00295 
00296   case tok::kw_try:                 // C++ 15: try-block
00297     return ParseCXXTryBlock();
00298 
00299   case tok::kw___try:
00300     ProhibitAttributes(Attrs); // TODO: is it correct?
00301     return ParseSEHTryBlock();
00302 
00303   case tok::annot_pragma_vis:
00304     ProhibitAttributes(Attrs);
00305     HandlePragmaVisibility();
00306     return StmtEmpty();
00307 
00308   case tok::annot_pragma_pack:
00309     ProhibitAttributes(Attrs);
00310     HandlePragmaPack();
00311     return StmtEmpty();
00312   }
00313 
00314   // If we reached this code, the statement must end in a semicolon.
00315   if (Tok.is(tok::semi)) {
00316     ConsumeToken();
00317   } else if (!Res.isInvalid()) {
00318     // If the result was valid, then we do want to diagnose this.  Use
00319     // ExpectAndConsume to emit the diagnostic, even though we know it won't
00320     // succeed.
00321     ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
00322     // Skip until we see a } or ;, but don't eat it.
00323     SkipUntil(tok::r_brace, true, true);
00324   }
00325 
00326   return move(Res);
00327 }
00328 
00329 /// \brief Parse an expression statement.
00330 StmtResult Parser::ParseExprStatement() {
00331   // If a case keyword is missing, this is where it should be inserted.
00332   Token OldToken = Tok;
00333 
00334   // expression[opt] ';'
00335   ExprResult Expr(ParseExpression());
00336   if (Expr.isInvalid()) {
00337     // If the expression is invalid, skip ahead to the next semicolon or '}'.
00338     // Not doing this opens us up to the possibility of infinite loops if
00339     // ParseExpression does not consume any tokens.
00340     SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
00341     if (Tok.is(tok::semi))
00342       ConsumeToken();
00343     return StmtError();
00344   }
00345 
00346   if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
00347       Actions.CheckCaseExpression(Expr.get())) {
00348     // If a constant expression is followed by a colon inside a switch block,
00349     // suggest a missing case keyword.
00350     Diag(OldToken, diag::err_expected_case_before_expression)
00351       << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
00352 
00353     // Recover parsing as a case statement.
00354     return ParseCaseStatement(/*MissingCase=*/true, Expr);
00355   }
00356 
00357   // Otherwise, eat the semicolon.
00358   ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
00359   return Actions.ActOnExprStmt(Actions.MakeFullExpr(Expr.get()));
00360 }
00361 
00362 StmtResult Parser::ParseSEHTryBlock() {
00363   assert(Tok.is(tok::kw___try) && "Expected '__try'");
00364   SourceLocation Loc = ConsumeToken();
00365   return ParseSEHTryBlockCommon(Loc);
00366 }
00367 
00368 /// ParseSEHTryBlockCommon
00369 ///
00370 /// seh-try-block:
00371 ///   '__try' compound-statement seh-handler
00372 ///
00373 /// seh-handler:
00374 ///   seh-except-block
00375 ///   seh-finally-block
00376 ///
00377 StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
00378   if(Tok.isNot(tok::l_brace))
00379     return StmtError(Diag(Tok,diag::err_expected_lbrace));
00380 
00381   StmtResult TryBlock(ParseCompoundStatement());
00382   if(TryBlock.isInvalid())
00383     return move(TryBlock);
00384 
00385   StmtResult Handler;
00386   if (Tok.is(tok::identifier) &&
00387       Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
00388     SourceLocation Loc = ConsumeToken();
00389     Handler = ParseSEHExceptBlock(Loc);
00390   } else if (Tok.is(tok::kw___finally)) {
00391     SourceLocation Loc = ConsumeToken();
00392     Handler = ParseSEHFinallyBlock(Loc);
00393   } else {
00394     return StmtError(Diag(Tok,diag::err_seh_expected_handler));
00395   }
00396 
00397   if(Handler.isInvalid())
00398     return move(Handler);
00399 
00400   return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
00401                                   TryLoc,
00402                                   TryBlock.take(),
00403                                   Handler.take());
00404 }
00405 
00406 /// ParseSEHExceptBlock - Handle __except
00407 ///
00408 /// seh-except-block:
00409 ///   '__except' '(' seh-filter-expression ')' compound-statement
00410 ///
00411 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
00412   PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
00413     raii2(Ident___exception_code, false),
00414     raii3(Ident_GetExceptionCode, false);
00415 
00416   if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
00417     return StmtError();
00418 
00419   ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
00420 
00421   if (getLangOpts().Borland) {
00422     Ident__exception_info->setIsPoisoned(false);
00423     Ident___exception_info->setIsPoisoned(false);
00424     Ident_GetExceptionInfo->setIsPoisoned(false);
00425   }
00426   ExprResult FilterExpr(ParseExpression());
00427 
00428   if (getLangOpts().Borland) {
00429     Ident__exception_info->setIsPoisoned(true);
00430     Ident___exception_info->setIsPoisoned(true);
00431     Ident_GetExceptionInfo->setIsPoisoned(true);
00432   }
00433 
00434   if(FilterExpr.isInvalid())
00435     return StmtError();
00436 
00437   if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
00438     return StmtError();
00439 
00440   StmtResult Block(ParseCompoundStatement());
00441 
00442   if(Block.isInvalid())
00443     return move(Block);
00444 
00445   return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
00446 }
00447 
00448 /// ParseSEHFinallyBlock - Handle __finally
00449 ///
00450 /// seh-finally-block:
00451 ///   '__finally' compound-statement
00452 ///
00453 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
00454   PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
00455     raii2(Ident___abnormal_termination, false),
00456     raii3(Ident_AbnormalTermination, false);
00457 
00458   StmtResult Block(ParseCompoundStatement());
00459   if(Block.isInvalid())
00460     return move(Block);
00461 
00462   return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
00463 }
00464 
00465 /// ParseLabeledStatement - We have an identifier and a ':' after it.
00466 ///
00467 ///       labeled-statement:
00468 ///         identifier ':' statement
00469 /// [GNU]   identifier ':' attributes[opt] statement
00470 ///
00471 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
00472   assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
00473          "Not an identifier!");
00474 
00475   Token IdentTok = Tok;  // Save the whole token.
00476   ConsumeToken();  // eat the identifier.
00477 
00478   assert(Tok.is(tok::colon) && "Not a label!");
00479 
00480   // identifier ':' statement
00481   SourceLocation ColonLoc = ConsumeToken();
00482 
00483   // Read label attributes, if present. attrs will contain both C++11 and GNU
00484   // attributes (if present) after this point.
00485   MaybeParseGNUAttributes(attrs);
00486 
00487   StmtResult SubStmt(ParseStatement());
00488 
00489   // Broken substmt shouldn't prevent the label from being added to the AST.
00490   if (SubStmt.isInvalid())
00491     SubStmt = Actions.ActOnNullStmt(ColonLoc);
00492 
00493   LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
00494                                               IdentTok.getLocation());
00495   if (AttributeList *Attrs = attrs.getList()) {
00496     Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
00497     attrs.clear();
00498   }
00499 
00500   return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
00501                                 SubStmt.get());
00502 }
00503 
00504 /// ParseCaseStatement
00505 ///       labeled-statement:
00506 ///         'case' constant-expression ':' statement
00507 /// [GNU]   'case' constant-expression '...' constant-expression ':' statement
00508 ///
00509 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
00510   assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
00511 
00512   // It is very very common for code to contain many case statements recursively
00513   // nested, as in (but usually without indentation):
00514   //  case 1:
00515   //    case 2:
00516   //      case 3:
00517   //         case 4:
00518   //           case 5: etc.
00519   //
00520   // Parsing this naively works, but is both inefficient and can cause us to run
00521   // out of stack space in our recursive descent parser.  As a special case,
00522   // flatten this recursion into an iterative loop.  This is complex and gross,
00523   // but all the grossness is constrained to ParseCaseStatement (and some
00524   // wierdness in the actions), so this is just local grossness :).
00525 
00526   // TopLevelCase - This is the highest level we have parsed.  'case 1' in the
00527   // example above.
00528   StmtResult TopLevelCase(true);
00529 
00530   // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
00531   // gets updated each time a new case is parsed, and whose body is unset so
00532   // far.  When parsing 'case 4', this is the 'case 3' node.
00533   Stmt *DeepestParsedCaseStmt = 0;
00534 
00535   // While we have case statements, eat and stack them.
00536   SourceLocation ColonLoc;
00537   do {
00538     SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
00539                                            ConsumeToken();  // eat the 'case'.
00540 
00541     if (Tok.is(tok::code_completion)) {
00542       Actions.CodeCompleteCase(getCurScope());
00543       cutOffParsing();
00544       return StmtError();
00545     }
00546 
00547     /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
00548     /// Disable this form of error recovery while we're parsing the case
00549     /// expression.
00550     ColonProtectionRAIIObject ColonProtection(*this);
00551 
00552     ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
00553     MissingCase = false;
00554     if (LHS.isInvalid()) {
00555       SkipUntil(tok::colon);
00556       return StmtError();
00557     }
00558 
00559     // GNU case range extension.
00560     SourceLocation DotDotDotLoc;
00561     ExprResult RHS;
00562     if (Tok.is(tok::ellipsis)) {
00563       Diag(Tok, diag::ext_gnu_case_range);
00564       DotDotDotLoc = ConsumeToken();
00565 
00566       RHS = ParseConstantExpression();
00567       if (RHS.isInvalid()) {
00568         SkipUntil(tok::colon);
00569         return StmtError();
00570       }
00571     }
00572 
00573     ColonProtection.restore();
00574 
00575     if (Tok.is(tok::colon)) {
00576       ColonLoc = ConsumeToken();
00577 
00578     // Treat "case blah;" as a typo for "case blah:".
00579     } else if (Tok.is(tok::semi)) {
00580       ColonLoc = ConsumeToken();
00581       Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
00582         << FixItHint::CreateReplacement(ColonLoc, ":");
00583     } else {
00584       SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
00585       Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
00586         << FixItHint::CreateInsertion(ExpectedLoc, ":");
00587       ColonLoc = ExpectedLoc;
00588     }
00589 
00590     StmtResult Case =
00591       Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
00592                             RHS.get(), ColonLoc);
00593 
00594     // If we had a sema error parsing this case, then just ignore it and
00595     // continue parsing the sub-stmt.
00596     if (Case.isInvalid()) {
00597       if (TopLevelCase.isInvalid())  // No parsed case stmts.
00598         return ParseStatement();
00599       // Otherwise, just don't add it as a nested case.
00600     } else {
00601       // If this is the first case statement we parsed, it becomes TopLevelCase.
00602       // Otherwise we link it into the current chain.
00603       Stmt *NextDeepest = Case.get();
00604       if (TopLevelCase.isInvalid())
00605         TopLevelCase = move(Case);
00606       else
00607         Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
00608       DeepestParsedCaseStmt = NextDeepest;
00609     }
00610 
00611     // Handle all case statements.
00612   } while (Tok.is(tok::kw_case));
00613 
00614   assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
00615 
00616   // If we found a non-case statement, start by parsing it.
00617   StmtResult SubStmt;
00618 
00619   if (Tok.isNot(tok::r_brace)) {
00620     SubStmt = ParseStatement();
00621   } else {
00622     // Nicely diagnose the common error "switch (X) { case 4: }", which is
00623     // not valid.
00624     SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
00625     Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
00626       << FixItHint::CreateInsertion(AfterColonLoc, " ;");
00627     SubStmt = true;
00628   }
00629 
00630   // Broken sub-stmt shouldn't prevent forming the case statement properly.
00631   if (SubStmt.isInvalid())
00632     SubStmt = Actions.ActOnNullStmt(SourceLocation());
00633 
00634   // Install the body into the most deeply-nested case.
00635   Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
00636 
00637   // Return the top level parsed statement tree.
00638   return move(TopLevelCase);
00639 }
00640 
00641 /// ParseDefaultStatement
00642 ///       labeled-statement:
00643 ///         'default' ':' statement
00644 /// Note that this does not parse the 'statement' at the end.
00645 ///
00646 StmtResult Parser::ParseDefaultStatement() {
00647   assert(Tok.is(tok::kw_default) && "Not a default stmt!");
00648   SourceLocation DefaultLoc = ConsumeToken();  // eat the 'default'.
00649 
00650   SourceLocation ColonLoc;
00651   if (Tok.is(tok::colon)) {
00652     ColonLoc = ConsumeToken();
00653 
00654   // Treat "default;" as a typo for "default:".
00655   } else if (Tok.is(tok::semi)) {
00656     ColonLoc = ConsumeToken();
00657     Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
00658       << FixItHint::CreateReplacement(ColonLoc, ":");
00659   } else {
00660     SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
00661     Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
00662       << FixItHint::CreateInsertion(ExpectedLoc, ":");
00663     ColonLoc = ExpectedLoc;
00664   }
00665 
00666   StmtResult SubStmt;
00667 
00668   if (Tok.isNot(tok::r_brace)) {
00669     SubStmt = ParseStatement();
00670   } else {
00671     // Diagnose the common error "switch (X) {... default: }", which is
00672     // not valid.
00673     SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
00674     Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
00675       << FixItHint::CreateInsertion(AfterColonLoc, " ;");
00676     SubStmt = true;
00677   }
00678 
00679   // Broken sub-stmt shouldn't prevent forming the case statement properly.
00680   if (SubStmt.isInvalid())
00681     SubStmt = Actions.ActOnNullStmt(ColonLoc);
00682 
00683   return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
00684                                   SubStmt.get(), getCurScope());
00685 }
00686 
00687 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
00688   return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
00689 }
00690 
00691 /// ParseCompoundStatement - Parse a "{}" block.
00692 ///
00693 ///       compound-statement: [C99 6.8.2]
00694 ///         { block-item-list[opt] }
00695 /// [GNU]   { label-declarations block-item-list } [TODO]
00696 ///
00697 ///       block-item-list:
00698 ///         block-item
00699 ///         block-item-list block-item
00700 ///
00701 ///       block-item:
00702 ///         declaration
00703 /// [GNU]   '__extension__' declaration
00704 ///         statement
00705 /// [OMP]   openmp-directive            [TODO]
00706 ///
00707 /// [GNU] label-declarations:
00708 /// [GNU]   label-declaration
00709 /// [GNU]   label-declarations label-declaration
00710 ///
00711 /// [GNU] label-declaration:
00712 /// [GNU]   '__label__' identifier-list ';'
00713 ///
00714 /// [OMP] openmp-directive:             [TODO]
00715 /// [OMP]   barrier-directive
00716 /// [OMP]   flush-directive
00717 ///
00718 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
00719                                           unsigned ScopeFlags) {
00720   assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
00721 
00722   // Enter a scope to hold everything within the compound stmt.  Compound
00723   // statements can always hold declarations.
00724   ParseScope CompoundScope(this, ScopeFlags);
00725 
00726   // Parse the statements in the body.
00727   return ParseCompoundStatementBody(isStmtExpr);
00728 }
00729 
00730 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
00731 /// ActOnCompoundStmt action.  This expects the '{' to be the current token, and
00732 /// consume the '}' at the end of the block.  It does not manipulate the scope
00733 /// stack.
00734 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
00735   PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
00736                                 Tok.getLocation(),
00737                                 "in compound statement ('{}')");
00738   InMessageExpressionRAIIObject InMessage(*this, false);
00739   BalancedDelimiterTracker T(*this, tok::l_brace);
00740   if (T.consumeOpen())
00741     return StmtError();
00742 
00743   Sema::CompoundScopeRAII CompoundScope(Actions);
00744 
00745   StmtVector Stmts(Actions);
00746 
00747   // "__label__ X, Y, Z;" is the GNU "Local Label" extension.  These are
00748   // only allowed at the start of a compound stmt regardless of the language.
00749   while (Tok.is(tok::kw___label__)) {
00750     SourceLocation LabelLoc = ConsumeToken();
00751     Diag(LabelLoc, diag::ext_gnu_local_label);
00752 
00753     SmallVector<Decl *, 8> DeclsInGroup;
00754     while (1) {
00755       if (Tok.isNot(tok::identifier)) {
00756         Diag(Tok, diag::err_expected_ident);
00757         break;
00758       }
00759 
00760       IdentifierInfo *II = Tok.getIdentifierInfo();
00761       SourceLocation IdLoc = ConsumeToken();
00762       DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
00763 
00764       if (!Tok.is(tok::comma))
00765         break;
00766       ConsumeToken();
00767     }
00768 
00769     DeclSpec DS(AttrFactory);
00770     DeclGroupPtrTy Res = Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
00771                                       DeclsInGroup.data(), DeclsInGroup.size());
00772     StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
00773 
00774     ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
00775     if (R.isUsable())
00776       Stmts.push_back(R.release());
00777   }
00778 
00779   while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
00780     if (Tok.is(tok::annot_pragma_unused)) {
00781       HandlePragmaUnused();
00782       continue;
00783     }
00784 
00785     if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
00786         Tok.is(tok::kw___if_not_exists))) {
00787       ParseMicrosoftIfExistsStatement(Stmts);
00788       continue;
00789     }
00790 
00791     StmtResult R;
00792     if (Tok.isNot(tok::kw___extension__)) {
00793       R = ParseStatementOrDeclaration(Stmts, false);
00794     } else {
00795       // __extension__ can start declarations and it can also be a unary
00796       // operator for expressions.  Consume multiple __extension__ markers here
00797       // until we can determine which is which.
00798       // FIXME: This loses extension expressions in the AST!
00799       SourceLocation ExtLoc = ConsumeToken();
00800       while (Tok.is(tok::kw___extension__))
00801         ConsumeToken();
00802 
00803       ParsedAttributesWithRange attrs(AttrFactory);
00804       MaybeParseCXX0XAttributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
00805 
00806       // If this is the start of a declaration, parse it as such.
00807       if (isDeclarationStatement()) {
00808         // __extension__ silences extension warnings in the subdeclaration.
00809         // FIXME: Save the __extension__ on the decl as a node somehow?
00810         ExtensionRAIIObject O(Diags);
00811 
00812         SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
00813         DeclGroupPtrTy Res = ParseDeclaration(Stmts,
00814                                               Declarator::BlockContext, DeclEnd,
00815                                               attrs);
00816         R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
00817       } else {
00818         // Otherwise this was a unary __extension__ marker.
00819         ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
00820 
00821         if (Res.isInvalid()) {
00822           SkipUntil(tok::semi);
00823           continue;
00824         }
00825 
00826         // FIXME: Use attributes?
00827         // Eat the semicolon at the end of stmt and convert the expr into a
00828         // statement.
00829         ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
00830         R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.get()));
00831       }
00832     }
00833 
00834     if (R.isUsable())
00835       Stmts.push_back(R.release());
00836   }
00837 
00838   SourceLocation CloseLoc = Tok.getLocation();
00839 
00840   // We broke out of the while loop because we found a '}' or EOF.
00841   if (Tok.isNot(tok::r_brace)) {
00842     Diag(Tok, diag::err_expected_rbrace);
00843     Diag(T.getOpenLocation(), diag::note_matching) << "{";
00844     // Recover by creating a compound statement with what we parsed so far,
00845     // instead of dropping everything and returning StmtError();
00846   } else {
00847     if (!T.consumeClose())
00848       CloseLoc = T.getCloseLocation();
00849   }
00850 
00851   return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
00852                                    move_arg(Stmts), isStmtExpr);
00853 }
00854 
00855 /// ParseParenExprOrCondition:
00856 /// [C  ]     '(' expression ')'
00857 /// [C++]     '(' condition ')'       [not allowed if OnlyAllowCondition=true]
00858 ///
00859 /// This function parses and performs error recovery on the specified condition
00860 /// or expression (depending on whether we're in C++ or C mode).  This function
00861 /// goes out of its way to recover well.  It returns true if there was a parser
00862 /// error (the right paren couldn't be found), which indicates that the caller
00863 /// should try to recover harder.  It returns false if the condition is
00864 /// successfully parsed.  Note that a successful parse can still have semantic
00865 /// errors in the condition.
00866 bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
00867                                        Decl *&DeclResult,
00868                                        SourceLocation Loc,
00869                                        bool ConvertToBoolean) {
00870   BalancedDelimiterTracker T(*this, tok::l_paren);
00871   T.consumeOpen();
00872 
00873   if (getLangOpts().CPlusPlus)
00874     ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
00875   else {
00876     ExprResult = ParseExpression();
00877     DeclResult = 0;
00878 
00879     // If required, convert to a boolean value.
00880     if (!ExprResult.isInvalid() && ConvertToBoolean)
00881       ExprResult
00882         = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
00883   }
00884 
00885   // If the parser was confused by the condition and we don't have a ')', try to
00886   // recover by skipping ahead to a semi and bailing out.  If condexp is
00887   // semantically invalid but we have well formed code, keep going.
00888   if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
00889     SkipUntil(tok::semi);
00890     // Skipping may have stopped if it found the containing ')'.  If so, we can
00891     // continue parsing the if statement.
00892     if (Tok.isNot(tok::r_paren))
00893       return true;
00894   }
00895 
00896   // Otherwise the condition is valid or the rparen is present.
00897   T.consumeClose();
00898   
00899   // Check for extraneous ')'s to catch things like "if (foo())) {".  We know
00900   // that all callers are looking for a statement after the condition, so ")"
00901   // isn't valid.
00902   while (Tok.is(tok::r_paren)) {
00903     Diag(Tok, diag::err_extraneous_rparen_in_condition)
00904       << FixItHint::CreateRemoval(Tok.getLocation());
00905     ConsumeParen();
00906   }
00907   
00908   return false;
00909 }
00910 
00911 
00912 /// ParseIfStatement
00913 ///       if-statement: [C99 6.8.4.1]
00914 ///         'if' '(' expression ')' statement
00915 ///         'if' '(' expression ')' statement 'else' statement
00916 /// [C++]   'if' '(' condition ')' statement
00917 /// [C++]   'if' '(' condition ')' statement 'else' statement
00918 ///
00919 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
00920   assert(Tok.is(tok::kw_if) && "Not an if stmt!");
00921   SourceLocation IfLoc = ConsumeToken();  // eat the 'if'.
00922 
00923   if (Tok.isNot(tok::l_paren)) {
00924     Diag(Tok, diag::err_expected_lparen_after) << "if";
00925     SkipUntil(tok::semi);
00926     return StmtError();
00927   }
00928 
00929   bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
00930 
00931   // C99 6.8.4p3 - In C99, the if statement is a block.  This is not
00932   // the case for C90.
00933   //
00934   // C++ 6.4p3:
00935   // A name introduced by a declaration in a condition is in scope from its
00936   // point of declaration until the end of the substatements controlled by the
00937   // condition.
00938   // C++ 3.3.2p4:
00939   // Names declared in the for-init-statement, and in the condition of if,
00940   // while, for, and switch statements are local to the if, while, for, or
00941   // switch statement (including the controlled statement).
00942   //
00943   ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
00944 
00945   // Parse the condition.
00946   ExprResult CondExp;
00947   Decl *CondVar = 0;
00948   if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
00949     return StmtError();
00950 
00951   FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
00952 
00953   // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
00954   // there is no compound stmt.  C90 does not have this clause.  We only do this
00955   // if the body isn't a compound statement to avoid push/pop in common cases.
00956   //
00957   // C++ 6.4p1:
00958   // The substatement in a selection-statement (each substatement, in the else
00959   // form of the if statement) implicitly defines a local scope.
00960   //
00961   // For C++ we create a scope for the condition and a new scope for
00962   // substatements because:
00963   // -When the 'then' scope exits, we want the condition declaration to still be
00964   //    active for the 'else' scope too.
00965   // -Sema will detect name clashes by considering declarations of a
00966   //    'ControlScope' as part of its direct subscope.
00967   // -If we wanted the condition and substatement to be in the same scope, we
00968   //    would have to notify ParseStatement not to create a new scope. It's
00969   //    simpler to let it create a new scope.
00970   //
00971   ParseScope InnerScope(this, Scope::DeclScope,
00972                         C99orCXX && Tok.isNot(tok::l_brace));
00973 
00974   // Read the 'then' stmt.
00975   SourceLocation ThenStmtLoc = Tok.getLocation();
00976 
00977   SourceLocation InnerStatementTrailingElseLoc;
00978   StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
00979 
00980   // Pop the 'if' scope if needed.
00981   InnerScope.Exit();
00982 
00983   // If it has an else, parse it.
00984   SourceLocation ElseLoc;
00985   SourceLocation ElseStmtLoc;
00986   StmtResult ElseStmt;
00987 
00988   if (Tok.is(tok::kw_else)) {
00989     if (TrailingElseLoc)
00990       *TrailingElseLoc = Tok.getLocation();
00991 
00992     ElseLoc = ConsumeToken();
00993     ElseStmtLoc = Tok.getLocation();
00994 
00995     // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
00996     // there is no compound stmt.  C90 does not have this clause.  We only do
00997     // this if the body isn't a compound statement to avoid push/pop in common
00998     // cases.
00999     //
01000     // C++ 6.4p1:
01001     // The substatement in a selection-statement (each substatement, in the else
01002     // form of the if statement) implicitly defines a local scope.
01003     //
01004     ParseScope InnerScope(this, Scope::DeclScope,
01005                           C99orCXX && Tok.isNot(tok::l_brace));
01006 
01007     ElseStmt = ParseStatement();
01008 
01009     // Pop the 'else' scope if needed.
01010     InnerScope.Exit();
01011   } else if (Tok.is(tok::code_completion)) {
01012     Actions.CodeCompleteAfterIf(getCurScope());
01013     cutOffParsing();
01014     return StmtError();
01015   } else if (InnerStatementTrailingElseLoc.isValid()) {
01016     Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
01017   }
01018 
01019   IfScope.Exit();
01020 
01021   // If the condition was invalid, discard the if statement.  We could recover
01022   // better by replacing it with a valid expr, but don't do that yet.
01023   if (CondExp.isInvalid() && !CondVar)
01024     return StmtError();
01025 
01026   // If the then or else stmt is invalid and the other is valid (and present),
01027   // make turn the invalid one into a null stmt to avoid dropping the other
01028   // part.  If both are invalid, return error.
01029   if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
01030       (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
01031       (ThenStmt.get() == 0  && ElseStmt.isInvalid())) {
01032     // Both invalid, or one is invalid and other is non-present: return error.
01033     return StmtError();
01034   }
01035 
01036   // Now if either are invalid, replace with a ';'.
01037   if (ThenStmt.isInvalid())
01038     ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
01039   if (ElseStmt.isInvalid())
01040     ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
01041 
01042   return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
01043                              ElseLoc, ElseStmt.get());
01044 }
01045 
01046 /// ParseSwitchStatement
01047 ///       switch-statement:
01048 ///         'switch' '(' expression ')' statement
01049 /// [C++]   'switch' '(' condition ')' statement
01050 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
01051   assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
01052   SourceLocation SwitchLoc = ConsumeToken();  // eat the 'switch'.
01053 
01054   if (Tok.isNot(tok::l_paren)) {
01055     Diag(Tok, diag::err_expected_lparen_after) << "switch";
01056     SkipUntil(tok::semi);
01057     return StmtError();
01058   }
01059 
01060   bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
01061 
01062   // C99 6.8.4p3 - In C99, the switch statement is a block.  This is
01063   // not the case for C90.  Start the switch scope.
01064   //
01065   // C++ 6.4p3:
01066   // A name introduced by a declaration in a condition is in scope from its
01067   // point of declaration until the end of the substatements controlled by the
01068   // condition.
01069   // C++ 3.3.2p4:
01070   // Names declared in the for-init-statement, and in the condition of if,
01071   // while, for, and switch statements are local to the if, while, for, or
01072   // switch statement (including the controlled statement).
01073   //
01074   unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
01075   if (C99orCXX)
01076     ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
01077   ParseScope SwitchScope(this, ScopeFlags);
01078 
01079   // Parse the condition.
01080   ExprResult Cond;
01081   Decl *CondVar = 0;
01082   if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
01083     return StmtError();
01084 
01085   StmtResult Switch
01086     = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
01087 
01088   if (Switch.isInvalid()) {
01089     // Skip the switch body.
01090     // FIXME: This is not optimal recovery, but parsing the body is more
01091     // dangerous due to the presence of case and default statements, which
01092     // will have no place to connect back with the switch.
01093     if (Tok.is(tok::l_brace)) {
01094       ConsumeBrace();
01095       SkipUntil(tok::r_brace, false, false);
01096     } else
01097       SkipUntil(tok::semi);
01098     return move(Switch);
01099   }
01100 
01101   // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
01102   // there is no compound stmt.  C90 does not have this clause.  We only do this
01103   // if the body isn't a compound statement to avoid push/pop in common cases.
01104   //
01105   // C++ 6.4p1:
01106   // The substatement in a selection-statement (each substatement, in the else
01107   // form of the if statement) implicitly defines a local scope.
01108   //
01109   // See comments in ParseIfStatement for why we create a scope for the
01110   // condition and a new scope for substatement in C++.
01111   //
01112   ParseScope InnerScope(this, Scope::DeclScope,
01113                         C99orCXX && Tok.isNot(tok::l_brace));
01114 
01115   // Read the body statement.
01116   StmtResult Body(ParseStatement(TrailingElseLoc));
01117 
01118   // Pop the scopes.
01119   InnerScope.Exit();
01120   SwitchScope.Exit();
01121 
01122   if (Body.isInvalid()) {
01123     // FIXME: Remove the case statement list from the Switch statement.
01124 
01125     // Put the synthesized null statement on the same line as the end of switch
01126     // condition.
01127     SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
01128     Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
01129   }
01130 
01131   return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
01132 }
01133 
01134 /// ParseWhileStatement
01135 ///       while-statement: [C99 6.8.5.1]
01136 ///         'while' '(' expression ')' statement
01137 /// [C++]   'while' '(' condition ')' statement
01138 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
01139   assert(Tok.is(tok::kw_while) && "Not a while stmt!");
01140   SourceLocation WhileLoc = Tok.getLocation();
01141   ConsumeToken();  // eat the 'while'.
01142 
01143   if (Tok.isNot(tok::l_paren)) {
01144     Diag(Tok, diag::err_expected_lparen_after) << "while";
01145     SkipUntil(tok::semi);
01146     return StmtError();
01147   }
01148 
01149   bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
01150 
01151   // C99 6.8.5p5 - In C99, the while statement is a block.  This is not
01152   // the case for C90.  Start the loop scope.
01153   //
01154   // C++ 6.4p3:
01155   // A name introduced by a declaration in a condition is in scope from its
01156   // point of declaration until the end of the substatements controlled by the
01157   // condition.
01158   // C++ 3.3.2p4:
01159   // Names declared in the for-init-statement, and in the condition of if,
01160   // while, for, and switch statements are local to the if, while, for, or
01161   // switch statement (including the controlled statement).
01162   //
01163   unsigned ScopeFlags;
01164   if (C99orCXX)
01165     ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
01166                  Scope::DeclScope  | Scope::ControlScope;
01167   else
01168     ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
01169   ParseScope WhileScope(this, ScopeFlags);
01170 
01171   // Parse the condition.
01172   ExprResult Cond;
01173   Decl *CondVar = 0;
01174   if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
01175     return StmtError();
01176 
01177   FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
01178 
01179   // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
01180   // there is no compound stmt.  C90 does not have this clause.  We only do this
01181   // if the body isn't a compound statement to avoid push/pop in common cases.
01182   //
01183   // C++ 6.5p2:
01184   // The substatement in an iteration-statement implicitly defines a local scope
01185   // which is entered and exited each time through the loop.
01186   //
01187   // See comments in ParseIfStatement for why we create a scope for the
01188   // condition and a new scope for substatement in C++.
01189   //
01190   ParseScope InnerScope(this, Scope::DeclScope,
01191                         C99orCXX && Tok.isNot(tok::l_brace));
01192 
01193   // Read the body statement.
01194   StmtResult Body(ParseStatement(TrailingElseLoc));
01195 
01196   // Pop the body scope if needed.
01197   InnerScope.Exit();
01198   WhileScope.Exit();
01199 
01200   if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
01201     return StmtError();
01202 
01203   return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
01204 }
01205 
01206 /// ParseDoStatement
01207 ///       do-statement: [C99 6.8.5.2]
01208 ///         'do' statement 'while' '(' expression ')' ';'
01209 /// Note: this lets the caller parse the end ';'.
01210 StmtResult Parser::ParseDoStatement() {
01211   assert(Tok.is(tok::kw_do) && "Not a do stmt!");
01212   SourceLocation DoLoc = ConsumeToken();  // eat the 'do'.
01213 
01214   // C99 6.8.5p5 - In C99, the do statement is a block.  This is not
01215   // the case for C90.  Start the loop scope.
01216   unsigned ScopeFlags;
01217   if (getLangOpts().C99)
01218     ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
01219   else
01220     ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
01221 
01222   ParseScope DoScope(this, ScopeFlags);
01223 
01224   // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
01225   // there is no compound stmt.  C90 does not have this clause. We only do this
01226   // if the body isn't a compound statement to avoid push/pop in common cases.
01227   //
01228   // C++ 6.5p2:
01229   // The substatement in an iteration-statement implicitly defines a local scope
01230   // which is entered and exited each time through the loop.
01231   //
01232   ParseScope InnerScope(this, Scope::DeclScope,
01233                         (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
01234                         Tok.isNot(tok::l_brace));
01235 
01236   // Read the body statement.
01237   StmtResult Body(ParseStatement());
01238 
01239   // Pop the body scope if needed.
01240   InnerScope.Exit();
01241 
01242   if (Tok.isNot(tok::kw_while)) {
01243     if (!Body.isInvalid()) {
01244       Diag(Tok, diag::err_expected_while);
01245       Diag(DoLoc, diag::note_matching) << "do";
01246       SkipUntil(tok::semi, false, true);
01247     }
01248     return StmtError();
01249   }
01250   SourceLocation WhileLoc = ConsumeToken();
01251 
01252   if (Tok.isNot(tok::l_paren)) {
01253     Diag(Tok, diag::err_expected_lparen_after) << "do/while";
01254     SkipUntil(tok::semi, false, true);
01255     return StmtError();
01256   }
01257 
01258   // Parse the parenthesized condition.
01259   BalancedDelimiterTracker T(*this, tok::l_paren);
01260   T.consumeOpen();
01261   ExprResult Cond = ParseExpression();
01262   T.consumeClose();
01263   DoScope.Exit();
01264 
01265   if (Cond.isInvalid() || Body.isInvalid())
01266     return StmtError();
01267 
01268   return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
01269                              Cond.get(), T.getCloseLocation());
01270 }
01271 
01272 /// ParseForStatement
01273 ///       for-statement: [C99 6.8.5.3]
01274 ///         'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
01275 ///         'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
01276 /// [C++]   'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
01277 /// [C++]       statement
01278 /// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
01279 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
01280 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
01281 ///
01282 /// [C++] for-init-statement:
01283 /// [C++]   expression-statement
01284 /// [C++]   simple-declaration
01285 ///
01286 /// [C++0x] for-range-declaration:
01287 /// [C++0x]   attribute-specifier-seq[opt] type-specifier-seq declarator
01288 /// [C++0x] for-range-initializer:
01289 /// [C++0x]   expression
01290 /// [C++0x]   braced-init-list            [TODO]
01291 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
01292   assert(Tok.is(tok::kw_for) && "Not a for stmt!");
01293   SourceLocation ForLoc = ConsumeToken();  // eat the 'for'.
01294 
01295   if (Tok.isNot(tok::l_paren)) {
01296     Diag(Tok, diag::err_expected_lparen_after) << "for";
01297     SkipUntil(tok::semi);
01298     return StmtError();
01299   }
01300 
01301   bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus || getLangOpts().ObjC1;
01302 
01303   // C99 6.8.5p5 - In C99, the for statement is a block.  This is not
01304   // the case for C90.  Start the loop scope.
01305   //
01306   // C++ 6.4p3:
01307   // A name introduced by a declaration in a condition is in scope from its
01308   // point of declaration until the end of the substatements controlled by the
01309   // condition.
01310   // C++ 3.3.2p4:
01311   // Names declared in the for-init-statement, and in the condition of if,
01312   // while, for, and switch statements are local to the if, while, for, or
01313   // switch statement (including the controlled statement).
01314   // C++ 6.5.3p1:
01315   // Names declared in the for-init-statement are in the same declarative-region
01316   // as those declared in the condition.
01317   //
01318   unsigned ScopeFlags;
01319   if (C99orCXXorObjC)
01320     ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
01321                  Scope::DeclScope  | Scope::ControlScope;
01322   else
01323     ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
01324 
01325   ParseScope ForScope(this, ScopeFlags);
01326 
01327   BalancedDelimiterTracker T(*this, tok::l_paren);
01328   T.consumeOpen();
01329 
01330   ExprResult Value;
01331 
01332   bool ForEach = false, ForRange = false;
01333   StmtResult FirstPart;
01334   bool SecondPartIsInvalid = false;
01335   FullExprArg SecondPart(Actions);
01336   ExprResult Collection;
01337   ForRangeInit ForRangeInit;
01338   FullExprArg ThirdPart(Actions);
01339   Decl *SecondVar = 0;
01340 
01341   if (Tok.is(tok::code_completion)) {
01342     Actions.CodeCompleteOrdinaryName(getCurScope(),
01343                                      C99orCXXorObjC? Sema::PCC_ForInit
01344                                                    : Sema::PCC_Expression);
01345     cutOffParsing();
01346     return StmtError();
01347   }
01348 
01349   // Parse the first part of the for specifier.
01350   if (Tok.is(tok::semi)) {  // for (;
01351     // no first part, eat the ';'.
01352     ConsumeToken();
01353   } else if (isForInitDeclaration()) {  // for (int X = 4;
01354     // Parse declaration, which eats the ';'.
01355     if (!C99orCXXorObjC)   // Use of C99-style for loops in C90 mode?
01356       Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
01357 
01358     ParsedAttributesWithRange attrs(AttrFactory);
01359     MaybeParseCXX0XAttributes(attrs);
01360 
01361     // In C++0x, "for (T NS:a" might not be a typo for ::
01362     bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
01363     ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
01364 
01365     SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
01366     StmtVector Stmts(Actions);
01367     DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
01368                                                DeclEnd, attrs, false,
01369                                                MightBeForRangeStmt ?
01370                                                  &ForRangeInit : 0);
01371     FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
01372 
01373     if (ForRangeInit.ParsedForRangeDecl()) {
01374       Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus0x ?
01375            diag::warn_cxx98_compat_for_range : diag::ext_for_range);
01376 
01377       ForRange = true;
01378     } else if (Tok.is(tok::semi)) {  // for (int x = 4;
01379       ConsumeToken();
01380     } else if ((ForEach = isTokIdentifier_in())) {
01381       Actions.ActOnForEachDeclStmt(DG);
01382       // ObjC: for (id x in expr)
01383       ConsumeToken(); // consume 'in'
01384 
01385       if (Tok.is(tok::code_completion)) {
01386         Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
01387         cutOffParsing();
01388         return StmtError();
01389       }
01390       Collection = ParseExpression();
01391     } else {
01392       Diag(Tok, diag::err_expected_semi_for);
01393     }
01394   } else {
01395     Value = ParseExpression();
01396 
01397     ForEach = isTokIdentifier_in();
01398 
01399     // Turn the expression into a stmt.
01400     if (!Value.isInvalid()) {
01401       if (ForEach)
01402         FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
01403       else
01404         FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value.get()));
01405     }
01406 
01407     if (Tok.is(tok::semi)) {
01408       ConsumeToken();
01409     } else if (ForEach) {
01410       ConsumeToken(); // consume 'in'
01411 
01412       if (Tok.is(tok::code_completion)) {
01413         Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
01414         cutOffParsing();
01415         return StmtError();
01416       }
01417       Collection = ParseExpression();
01418     } else if (getLangOpts().CPlusPlus0x && Tok.is(tok::colon) && FirstPart.get()) {
01419       // User tried to write the reasonable, but ill-formed, for-range-statement
01420       //   for (expr : expr) { ... }
01421       Diag(Tok, diag::err_for_range_expected_decl)
01422         << FirstPart.get()->getSourceRange();
01423       SkipUntil(tok::r_paren, false, true);
01424       SecondPartIsInvalid = true;
01425     } else {
01426       if (!Value.isInvalid()) {
01427         Diag(Tok, diag::err_expected_semi_for);
01428       } else {
01429         // Skip until semicolon or rparen, don't consume it.
01430         SkipUntil(tok::r_paren, true, true);
01431         if (Tok.is(tok::semi))
01432           ConsumeToken();
01433       }
01434     }
01435   }
01436   if (!ForEach && !ForRange) {
01437     assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
01438     // Parse the second part of the for specifier.
01439     if (Tok.is(tok::semi)) {  // for (...;;
01440       // no second part.
01441     } else if (Tok.is(tok::r_paren)) {
01442       // missing both semicolons.
01443     } else {
01444       ExprResult Second;
01445       if (getLangOpts().CPlusPlus)
01446         ParseCXXCondition(Second, SecondVar, ForLoc, true);
01447       else {
01448         Second = ParseExpression();
01449         if (!Second.isInvalid())
01450           Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
01451                                                  Second.get());
01452       }
01453       SecondPartIsInvalid = Second.isInvalid();
01454       SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
01455     }
01456 
01457     if (Tok.isNot(tok::semi)) {
01458       if (!SecondPartIsInvalid || SecondVar)
01459         Diag(Tok, diag::err_expected_semi_for);
01460       else
01461         // Skip until semicolon or rparen, don't consume it.
01462         SkipUntil(tok::r_paren, true, true);
01463     }
01464 
01465     if (Tok.is(tok::semi)) {
01466       ConsumeToken();
01467     }
01468 
01469     // Parse the third part of the for specifier.
01470     if (Tok.isNot(tok::r_paren)) {   // for (...;...;)
01471       ExprResult Third = ParseExpression();
01472       ThirdPart = Actions.MakeFullExpr(Third.take());
01473     }
01474   }
01475   // Match the ')'.
01476   T.consumeClose();
01477 
01478   // We need to perform most of the semantic analysis for a C++0x for-range
01479   // statememt before parsing the body, in order to be able to deduce the type
01480   // of an auto-typed loop variable.
01481   StmtResult ForRangeStmt;
01482   if (ForRange) {
01483     ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, T.getOpenLocation(),
01484                                                 FirstPart.take(),
01485                                                 ForRangeInit.ColonLoc,
01486                                                 ForRangeInit.RangeExpr.get(),
01487                                                 T.getCloseLocation());
01488 
01489 
01490   // Similarly, we need to do the semantic analysis for a for-range
01491   // statement immediately in order to close over temporaries correctly.
01492   } else if (ForEach) {
01493     if (!Collection.isInvalid())
01494       Collection =
01495         Actions.ActOnObjCForCollectionOperand(ForLoc, Collection.take());
01496   }
01497 
01498   // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
01499   // there is no compound stmt.  C90 does not have this clause.  We only do this
01500   // if the body isn't a compound statement to avoid push/pop in common cases.
01501   //
01502   // C++ 6.5p2:
01503   // The substatement in an iteration-statement implicitly defines a local scope
01504   // which is entered and exited each time through the loop.
01505   //
01506   // See comments in ParseIfStatement for why we create a scope for
01507   // for-init-statement/condition and a new scope for substatement in C++.
01508   //
01509   ParseScope InnerScope(this, Scope::DeclScope,
01510                         C99orCXXorObjC && Tok.isNot(tok::l_brace));
01511 
01512   // Read the body statement.
01513   StmtResult Body(ParseStatement(TrailingElseLoc));
01514 
01515   // Pop the body scope if needed.
01516   InnerScope.Exit();
01517 
01518   // Leave the for-scope.
01519   ForScope.Exit();
01520 
01521   if (Body.isInvalid())
01522     return StmtError();
01523 
01524   if (ForEach)
01525    return Actions.ActOnObjCForCollectionStmt(ForLoc, T.getOpenLocation(),
01526                                              FirstPart.take(),
01527                                              Collection.take(), 
01528                                              T.getCloseLocation(),
01529                                              Body.take());
01530 
01531   if (ForRange)
01532     return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
01533 
01534   return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
01535                               SecondPart, SecondVar, ThirdPart,
01536                               T.getCloseLocation(), Body.take());
01537 }
01538 
01539 /// ParseGotoStatement
01540 ///       jump-statement:
01541 ///         'goto' identifier ';'
01542 /// [GNU]   'goto' '*' expression ';'
01543 ///
01544 /// Note: this lets the caller parse the end ';'.
01545 ///
01546 StmtResult Parser::ParseGotoStatement() {
01547   assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
01548   SourceLocation GotoLoc = ConsumeToken();  // eat the 'goto'.
01549 
01550   StmtResult Res;
01551   if (Tok.is(tok::identifier)) {
01552     LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
01553                                                 Tok.getLocation());
01554     Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
01555     ConsumeToken();
01556   } else if (Tok.is(tok::star)) {
01557     // GNU indirect goto extension.
01558     Diag(Tok, diag::ext_gnu_indirect_goto);
01559     SourceLocation StarLoc = ConsumeToken();
01560     ExprResult R(ParseExpression());
01561     if (R.isInvalid()) {  // Skip to the semicolon, but don't consume it.
01562       SkipUntil(tok::semi, false, true);
01563       return StmtError();
01564     }
01565     Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
01566   } else {
01567     Diag(Tok, diag::err_expected_ident);
01568     return StmtError();
01569   }
01570 
01571   return move(Res);
01572 }
01573 
01574 /// ParseContinueStatement
01575 ///       jump-statement:
01576 ///         'continue' ';'
01577 ///
01578 /// Note: this lets the caller parse the end ';'.
01579 ///
01580 StmtResult Parser::ParseContinueStatement() {
01581   SourceLocation ContinueLoc = ConsumeToken();  // eat the 'continue'.
01582   return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
01583 }
01584 
01585 /// ParseBreakStatement
01586 ///       jump-statement:
01587 ///         'break' ';'
01588 ///
01589 /// Note: this lets the caller parse the end ';'.
01590 ///
01591 StmtResult Parser::ParseBreakStatement() {
01592   SourceLocation BreakLoc = ConsumeToken();  // eat the 'break'.
01593   return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
01594 }
01595 
01596 /// ParseReturnStatement
01597 ///       jump-statement:
01598 ///         'return' expression[opt] ';'
01599 StmtResult Parser::ParseReturnStatement() {
01600   assert(Tok.is(tok::kw_return) && "Not a return stmt!");
01601   SourceLocation ReturnLoc = ConsumeToken();  // eat the 'return'.
01602 
01603   ExprResult R;
01604   if (Tok.isNot(tok::semi)) {
01605     if (Tok.is(tok::code_completion)) {
01606       Actions.CodeCompleteReturn(getCurScope());
01607       cutOffParsing();
01608       return StmtError();
01609     }
01610 
01611     if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
01612       R = ParseInitializer();
01613       if (R.isUsable())
01614         Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus0x ?
01615              diag::warn_cxx98_compat_generalized_initializer_lists :
01616              diag::ext_generalized_initializer_lists)
01617           << R.get()->getSourceRange();
01618     } else
01619         R = ParseExpression();
01620     if (R.isInvalid()) {  // Skip to the semicolon, but don't consume it.
01621       SkipUntil(tok::semi, false, true);
01622       return StmtError();
01623     }
01624   }
01625   return Actions.ActOnReturnStmt(ReturnLoc, R.take());
01626 }
01627 
01628 /// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
01629 /// this routine is called to collect the tokens for an MS asm statement.
01630 StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
01631   SourceManager &SrcMgr = PP.getSourceManager();
01632   SourceLocation EndLoc = AsmLoc;
01633   do {
01634     bool InBraces = false;
01635     unsigned short savedBraceCount = 0;
01636     bool InAsmComment = false;
01637     FileID FID;
01638     unsigned LineNo = 0;
01639     unsigned NumTokensRead = 0;
01640     SourceLocation LBraceLoc;
01641 
01642     if (Tok.is(tok::l_brace)) {
01643       // Braced inline asm: consume the opening brace.
01644       InBraces = true;
01645       savedBraceCount = BraceCount;
01646       EndLoc = LBraceLoc = ConsumeBrace();
01647       ++NumTokensRead;
01648     } else {
01649       // Single-line inline asm; compute which line it is on.
01650       std::pair<FileID, unsigned> ExpAsmLoc =
01651           SrcMgr.getDecomposedExpansionLoc(EndLoc);
01652       FID = ExpAsmLoc.first;
01653       LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
01654     }
01655 
01656     SourceLocation TokLoc = Tok.getLocation();
01657     do {
01658       // If we hit EOF, we're done, period.
01659       if (Tok.is(tok::eof))
01660         break;
01661       // When we consume the closing brace, we're done.
01662       if (InBraces && BraceCount == savedBraceCount)
01663         break;
01664 
01665       if (!InAsmComment && Tok.is(tok::semi)) {
01666         // A semicolon in an asm is the start of a comment.
01667         InAsmComment = true;
01668         if (InBraces) {
01669           // Compute which line the comment is on.
01670           std::pair<FileID, unsigned> ExpSemiLoc =
01671               SrcMgr.getDecomposedExpansionLoc(TokLoc);
01672           FID = ExpSemiLoc.first;
01673           LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
01674         }
01675       } else if (!InBraces || InAsmComment) {
01676         // If end-of-line is significant, check whether this token is on a
01677         // new line.
01678         std::pair<FileID, unsigned> ExpLoc =
01679             SrcMgr.getDecomposedExpansionLoc(TokLoc);
01680         if (ExpLoc.first != FID ||
01681             SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
01682           // If this is a single-line __asm, we're done.
01683           if (!InBraces)
01684             break;
01685           // We're no longer in a comment.
01686           InAsmComment = false;
01687         } else if (!InAsmComment && Tok.is(tok::r_brace)) {
01688           // Single-line asm always ends when a closing brace is seen.
01689           // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
01690           // does MSVC do here?
01691           break;
01692         }
01693       }
01694 
01695       // Consume the next token; make sure we don't modify the brace count etc.
01696       // if we are in a comment.
01697       EndLoc = TokLoc;
01698       if (InAsmComment)
01699         PP.Lex(Tok);
01700       else
01701         ConsumeAnyToken();
01702       TokLoc = Tok.getLocation();
01703       ++NumTokensRead;
01704     } while (1);
01705 
01706     if (InBraces && BraceCount != savedBraceCount) {
01707       // __asm without closing brace (this can happen at EOF).
01708       Diag(Tok, diag::err_expected_rbrace);
01709       Diag(LBraceLoc, diag::note_matching) << "{";
01710       return StmtError();
01711     } else if (NumTokensRead == 0) {
01712       // Empty __asm.
01713       Diag(Tok, diag::err_expected_lbrace);
01714       return StmtError();
01715     }
01716     // Multiple adjacent asm's form together into a single asm statement
01717     // in the AST.
01718     if (!Tok.is(tok::kw_asm))
01719       break;
01720     EndLoc = ConsumeToken();
01721   } while (1);
01722   // FIXME: Need to actually grab the data and pass it on to Sema.  Ideally,
01723   // what Sema wants is a string of the entire inline asm, with one instruction
01724   // per line and all the __asm keywords stripped out, and a way of mapping
01725   // from any character of that string to its location in the original source
01726   // code. I'm not entirely sure how to go about that, though.
01727   Token t;
01728   t.setKind(tok::string_literal);
01729   t.setLiteralData("\"/*FIXME: not done*/\"");
01730   t.clearFlag(Token::NeedsCleaning);
01731   t.setLength(21);
01732   ExprResult AsmString(Actions.ActOnStringLiteral(&t, 1));
01733   ExprVector Constraints(Actions);
01734   ExprVector Exprs(Actions);
01735   ExprVector Clobbers(Actions);
01736   return Actions.ActOnAsmStmt(AsmLoc, true, true, 0, 0, 0,
01737                               move_arg(Constraints), move_arg(Exprs),
01738                               AsmString.take(), move_arg(Clobbers),
01739                               EndLoc, true);
01740 }
01741 
01742 /// ParseAsmStatement - Parse a GNU extended asm statement.
01743 ///       asm-statement:
01744 ///         gnu-asm-statement
01745 ///         ms-asm-statement
01746 ///
01747 /// [GNU] gnu-asm-statement:
01748 ///         'asm' type-qualifier[opt] '(' asm-argument ')' ';'
01749 ///
01750 /// [GNU] asm-argument:
01751 ///         asm-string-literal
01752 ///         asm-string-literal ':' asm-operands[opt]
01753 ///         asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
01754 ///         asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
01755 ///                 ':' asm-clobbers
01756 ///
01757 /// [GNU] asm-clobbers:
01758 ///         asm-string-literal
01759 ///         asm-clobbers ',' asm-string-literal
01760 ///
01761 /// [MS]  ms-asm-statement:
01762 ///         ms-asm-block
01763 ///         ms-asm-block ms-asm-statement
01764 ///
01765 /// [MS]  ms-asm-block:
01766 ///         '__asm' ms-asm-line '\n'
01767 ///         '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
01768 ///
01769 /// [MS]  ms-asm-instruction-block
01770 ///         ms-asm-line
01771 ///         ms-asm-line '\n' ms-asm-instruction-block
01772 ///
01773 StmtResult Parser::ParseAsmStatement(bool &msAsm) {
01774   assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
01775   SourceLocation AsmLoc = ConsumeToken();
01776 
01777   if (getLangOpts().MicrosoftExt && Tok.isNot(tok::l_paren) && !isTypeQualifier()) {
01778     msAsm = true;
01779     return ParseMicrosoftAsmStatement(AsmLoc);
01780   }
01781   DeclSpec DS(AttrFactory);
01782   SourceLocation Loc = Tok.getLocation();
01783   ParseTypeQualifierListOpt(DS, true, false);
01784 
01785   // GNU asms accept, but warn, about type-qualifiers other than volatile.
01786   if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
01787     Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
01788   if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
01789     Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
01790 
01791   // Remember if this was a volatile asm.
01792   bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
01793   if (Tok.isNot(tok::l_paren)) {
01794     Diag(Tok, diag::err_expected_lparen_after) << "asm";
01795     SkipUntil(tok::r_paren);
01796     return StmtError();
01797   }
01798   BalancedDelimiterTracker T(*this, tok::l_paren);
01799   T.consumeOpen();
01800 
01801   ExprResult AsmString(ParseAsmStringLiteral());
01802   if (AsmString.isInvalid()) {
01803     // Consume up to and including the closing paren.
01804     T.skipToEnd();
01805     return StmtError();
01806   }
01807 
01808   SmallVector<IdentifierInfo *, 4> Names;
01809   ExprVector Constraints(Actions);
01810   ExprVector Exprs(Actions);
01811   ExprVector Clobbers(Actions);
01812 
01813   if (Tok.is(tok::r_paren)) {
01814     // We have a simple asm expression like 'asm("foo")'.
01815     T.consumeClose();
01816     return Actions.ActOnAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
01817                                 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
01818                                 move_arg(Constraints), move_arg(Exprs),
01819                                 AsmString.take(), move_arg(Clobbers),
01820                                 T.getCloseLocation());
01821   }
01822 
01823   // Parse Outputs, if present.
01824   bool AteExtraColon = false;
01825   if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
01826     // In C++ mode, parse "::" like ": :".
01827     AteExtraColon = Tok.is(tok::coloncolon);
01828     ConsumeToken();
01829 
01830     if (!AteExtraColon &&
01831         ParseAsmOperandsOpt(Names, Constraints, Exprs))
01832       return StmtError();
01833   }
01834 
01835   unsigned NumOutputs = Names.size();
01836 
01837   // Parse Inputs, if present.
01838   if (AteExtraColon ||
01839       Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
01840     // In C++ mode, parse "::" like ": :".
01841     if (AteExtraColon)
01842       AteExtraColon = false;
01843     else {
01844       AteExtraColon = Tok.is(tok::coloncolon);
01845       ConsumeToken();
01846     }
01847 
01848     if (!AteExtraColon &&
01849         ParseAsmOperandsOpt(Names, Constraints, Exprs))
01850       return StmtError();
01851   }
01852 
01853   assert(Names.size() == Constraints.size() &&
01854          Constraints.size() == Exprs.size() &&
01855          "Input operand size mismatch!");
01856 
01857   unsigned NumInputs = Names.size() - NumOutputs;
01858 
01859   // Parse the clobbers, if present.
01860   if (AteExtraColon || Tok.is(tok::colon)) {
01861     if (!AteExtraColon)
01862       ConsumeToken();
01863 
01864     // Parse the asm-string list for clobbers if present.
01865     if (Tok.isNot(tok::r_paren)) {
01866       while (1) {
01867         ExprResult Clobber(ParseAsmStringLiteral());
01868 
01869         if (Clobber.isInvalid())
01870           break;
01871 
01872         Clobbers.push_back(Clobber.release());
01873 
01874         if (Tok.isNot(tok::comma)) break;
01875         ConsumeToken();
01876       }
01877     }
01878   }
01879 
01880   T.consumeClose();
01881   return Actions.ActOnAsmStmt(AsmLoc, false, isVolatile,
01882                               NumOutputs, NumInputs, Names.data(),
01883                               move_arg(Constraints), move_arg(Exprs),
01884                               AsmString.take(), move_arg(Clobbers),
01885                               T.getCloseLocation());
01886 }
01887 
01888 /// ParseAsmOperands - Parse the asm-operands production as used by
01889 /// asm-statement, assuming the leading ':' token was eaten.
01890 ///
01891 /// [GNU] asm-operands:
01892 ///         asm-operand
01893 ///         asm-operands ',' asm-operand
01894 ///
01895 /// [GNU] asm-operand:
01896 ///         asm-string-literal '(' expression ')'
01897 ///         '[' identifier ']' asm-string-literal '(' expression ')'
01898 ///
01899 //
01900 // FIXME: Avoid unnecessary std::string trashing.
01901 bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
01902                                  SmallVectorImpl<Expr *> &Constraints,
01903                                  SmallVectorImpl<Expr *> &Exprs) {
01904   // 'asm-operands' isn't present?
01905   if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
01906     return false;
01907 
01908   while (1) {
01909     // Read the [id] if present.
01910     if (Tok.is(tok::l_square)) {
01911       BalancedDelimiterTracker T(*this, tok::l_square);
01912       T.consumeOpen();
01913 
01914       if (Tok.isNot(tok::identifier)) {
01915         Diag(Tok, diag::err_expected_ident);
01916         SkipUntil(tok::r_paren);
01917         return true;
01918       }
01919 
01920       IdentifierInfo *II = Tok.getIdentifierInfo();
01921       ConsumeToken();
01922 
01923       Names.push_back(II);
01924       T.consumeClose();
01925     } else
01926       Names.push_back(0);
01927 
01928     ExprResult Constraint(ParseAsmStringLiteral());
01929     if (Constraint.isInvalid()) {
01930         SkipUntil(tok::r_paren);
01931         return true;
01932     }
01933     Constraints.push_back(Constraint.release());
01934 
01935     if (Tok.isNot(tok::l_paren)) {
01936       Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
01937       SkipUntil(tok::r_paren);
01938       return true;
01939     }
01940 
01941     // Read the parenthesized expression.
01942     BalancedDelimiterTracker T(*this, tok::l_paren);
01943     T.consumeOpen();
01944     ExprResult Res(ParseExpression());
01945     T.consumeClose();
01946     if (Res.isInvalid()) {
01947       SkipUntil(tok::r_paren);
01948       return true;
01949     }
01950     Exprs.push_back(Res.release());
01951     // Eat the comma and continue parsing if it exists.
01952     if (Tok.isNot(tok::comma)) return false;
01953     ConsumeToken();
01954   }
01955 }
01956 
01957 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
01958   assert(Tok.is(tok::l_brace));
01959   SourceLocation LBraceLoc = Tok.getLocation();
01960 
01961   if (SkipFunctionBodies && trySkippingFunctionBody()) {
01962     BodyScope.Exit();
01963     return Actions.ActOnFinishFunctionBody(Decl, 0);
01964   }
01965 
01966   PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
01967                                       "parsing function body");
01968 
01969   // Do not enter a scope for the brace, as the arguments are in the same scope
01970   // (the function body) as the body itself.  Instead, just read the statement
01971   // list and put it into a CompoundStmt for safe keeping.
01972   StmtResult FnBody(ParseCompoundStatementBody());
01973 
01974   // If the function body could not be parsed, make a bogus compoundstmt.
01975   if (FnBody.isInvalid()) {
01976     Sema::CompoundScopeRAII CompoundScope(Actions);
01977     FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
01978                                        MultiStmtArg(Actions), false);
01979   }
01980 
01981   BodyScope.Exit();
01982   return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
01983 }
01984 
01985 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
01986 ///
01987 ///       function-try-block:
01988 ///         'try' ctor-initializer[opt] compound-statement handler-seq
01989 ///
01990 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
01991   assert(Tok.is(tok::kw_try) && "Expected 'try'");
01992   SourceLocation TryLoc = ConsumeToken();
01993 
01994   PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
01995                                       "parsing function try block");
01996 
01997   // Constructor initializer list?
01998   if (Tok.is(tok::colon))
01999     ParseConstructorInitializer(Decl);
02000   else
02001     Actions.ActOnDefaultCtorInitializers(Decl);
02002 
02003   if (SkipFunctionBodies && trySkippingFunctionBody()) {
02004     BodyScope.Exit();
02005     return Actions.ActOnFinishFunctionBody(Decl, 0);
02006   }
02007 
02008   SourceLocation LBraceLoc = Tok.getLocation();
02009   StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc));
02010   // If we failed to parse the try-catch, we just give the function an empty
02011   // compound statement as the body.
02012   if (FnBody.isInvalid()) {
02013     Sema::CompoundScopeRAII CompoundScope(Actions);
02014     FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
02015                                        MultiStmtArg(Actions), false);
02016   }
02017 
02018   BodyScope.Exit();
02019   return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
02020 }
02021 
02022 bool Parser::trySkippingFunctionBody() {
02023   assert(Tok.is(tok::l_brace));
02024   assert(SkipFunctionBodies &&
02025          "Should only be called when SkipFunctionBodies is enabled");
02026 
02027   // We're in code-completion mode. Skip parsing for all function bodies unless
02028   // the body contains the code-completion point.
02029   TentativeParsingAction PA(*this);
02030   ConsumeBrace();
02031   if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
02032                 /*StopAtCodeCompletion=*/PP.isCodeCompletionEnabled())) {
02033     PA.Commit();
02034     return true;
02035   }
02036 
02037   PA.Revert();
02038   return false;
02039 }
02040 
02041 /// ParseCXXTryBlock - Parse a C++ try-block.
02042 ///
02043 ///       try-block:
02044 ///         'try' compound-statement handler-seq
02045 ///
02046 StmtResult Parser::ParseCXXTryBlock() {
02047   assert(Tok.is(tok::kw_try) && "Expected 'try'");
02048 
02049   SourceLocation TryLoc = ConsumeToken();
02050   return ParseCXXTryBlockCommon(TryLoc);
02051 }
02052 
02053 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
02054 /// function-try-block.
02055 ///
02056 ///       try-block:
02057 ///         'try' compound-statement handler-seq
02058 ///
02059 ///       function-try-block:
02060 ///         'try' ctor-initializer[opt] compound-statement handler-seq
02061 ///
02062 ///       handler-seq:
02063 ///         handler handler-seq[opt]
02064 ///
02065 ///       [Borland] try-block:
02066 ///         'try' compound-statement seh-except-block
02067 ///         'try' compound-statment  seh-finally-block
02068 ///
02069 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc) {
02070   if (Tok.isNot(tok::l_brace))
02071     return StmtError(Diag(Tok, diag::err_expected_lbrace));
02072   // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
02073 
02074   StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
02075                                              Scope::DeclScope|Scope::TryScope));
02076   if (TryBlock.isInvalid())
02077     return move(TryBlock);
02078 
02079   // Borland allows SEH-handlers with 'try'
02080   
02081   if ((Tok.is(tok::identifier) &&
02082        Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
02083       Tok.is(tok::kw___finally)) {
02084     // TODO: Factor into common return ParseSEHHandlerCommon(...)
02085     StmtResult Handler;
02086     if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
02087       SourceLocation Loc = ConsumeToken();
02088       Handler = ParseSEHExceptBlock(Loc);
02089     }
02090     else {
02091       SourceLocation Loc = ConsumeToken();
02092       Handler = ParseSEHFinallyBlock(Loc);
02093     }
02094     if(Handler.isInvalid())
02095       return move(Handler);
02096 
02097     return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
02098                                     TryLoc,
02099                                     TryBlock.take(),
02100                                     Handler.take());
02101   }
02102   else {
02103     StmtVector Handlers(Actions);
02104     ParsedAttributesWithRange attrs(AttrFactory);
02105     MaybeParseCXX0XAttributes(attrs);
02106     ProhibitAttributes(attrs);
02107 
02108     if (Tok.isNot(tok::kw_catch))
02109       return StmtError(Diag(Tok, diag::err_expected_catch));
02110     while (Tok.is(tok::kw_catch)) {
02111       StmtResult Handler(ParseCXXCatchBlock());
02112       if (!Handler.isInvalid())
02113         Handlers.push_back(Handler.release());
02114     }
02115     // Don't bother creating the full statement if we don't have any usable
02116     // handlers.
02117     if (Handlers.empty())
02118       return StmtError();
02119 
02120     return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), move_arg(Handlers));
02121   }
02122 }
02123 
02124 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
02125 ///
02126 ///       handler:
02127 ///         'catch' '(' exception-declaration ')' compound-statement
02128 ///
02129 ///       exception-declaration:
02130 ///         type-specifier-seq declarator
02131 ///         type-specifier-seq abstract-declarator
02132 ///         type-specifier-seq
02133 ///         '...'
02134 ///
02135 StmtResult Parser::ParseCXXCatchBlock() {
02136   assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
02137 
02138   SourceLocation CatchLoc = ConsumeToken();
02139 
02140   BalancedDelimiterTracker T(*this, tok::l_paren);
02141   if (T.expectAndConsume(diag::err_expected_lparen))
02142     return StmtError();
02143 
02144   // C++ 3.3.2p3:
02145   // The name in a catch exception-declaration is local to the handler and
02146   // shall not be redeclared in the outermost block of the handler.
02147   ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope);
02148 
02149   // exception-declaration is equivalent to '...' or a parameter-declaration
02150   // without default arguments.
02151   Decl *ExceptionDecl = 0;
02152   if (Tok.isNot(tok::ellipsis)) {
02153     DeclSpec DS(AttrFactory);
02154     if (ParseCXXTypeSpecifierSeq(DS))
02155       return StmtError();
02156     Declarator ExDecl(DS, Declarator::CXXCatchContext);
02157     ParseDeclarator(ExDecl);
02158     ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
02159   } else
02160     ConsumeToken();
02161 
02162   T.consumeClose();
02163   if (T.getCloseLocation().isInvalid())
02164     return StmtError();
02165 
02166   if (Tok.isNot(tok::l_brace))
02167     return StmtError(Diag(Tok, diag::err_expected_lbrace));
02168 
02169   // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
02170   StmtResult Block(ParseCompoundStatement());
02171   if (Block.isInvalid())
02172     return move(Block);
02173 
02174   return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
02175 }
02176 
02177 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
02178   IfExistsCondition Result;
02179   if (ParseMicrosoftIfExistsCondition(Result))
02180     return;
02181 
02182   // Handle dependent statements by parsing the braces as a compound statement.
02183   // This is not the same behavior as Visual C++, which don't treat this as a
02184   // compound statement, but for Clang's type checking we can't have anything
02185   // inside these braces escaping to the surrounding code.
02186   if (Result.Behavior == IEB_Dependent) {
02187     if (!Tok.is(tok::l_brace)) {
02188       Diag(Tok, diag::err_expected_lbrace);
02189       return;
02190     }
02191 
02192     StmtResult Compound = ParseCompoundStatement();
02193     if (Compound.isInvalid())
02194       return;
02195 
02196     StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
02197                                                               Result.IsIfExists,
02198                                                               Result.SS,
02199                                                               Result.Name,
02200                                                               Compound.get());
02201     if (DepResult.isUsable())
02202       Stmts.push_back(DepResult.get());
02203     return;
02204   }
02205 
02206   BalancedDelimiterTracker Braces(*this, tok::l_brace);
02207   if (Braces.consumeOpen()) {
02208     Diag(Tok, diag::err_expected_lbrace);
02209     return;
02210   }
02211 
02212   switch (Result.Behavior) {
02213   case IEB_Parse:
02214     // Parse the statements below.
02215     break;
02216       
02217   case IEB_Dependent:
02218     llvm_unreachable("Dependent case handled above");
02219       
02220   case IEB_Skip:
02221     Braces.skipToEnd();
02222     return;
02223   }
02224 
02225   // Condition is true, parse the statements.
02226   while (Tok.isNot(tok::r_brace)) {
02227     StmtResult R = ParseStatementOrDeclaration(Stmts, false);
02228     if (R.isUsable())
02229       Stmts.push_back(R.release());
02230   }
02231   Braces.consumeClose();
02232 }