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