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