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