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