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