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