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 ParsedAttributesWithRange Attrs(AttrFactory); 109 MaybeParseCXX11Attributes(Attrs, nullptr, /*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, ParsedAttributesWithRange &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(ParsedAttributesWithRange &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 ParsedAttributesWithRange 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 (1) { 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 ParsedAttributesWithRange attrs(AttrFactory); 1122 MaybeParseCXX11Attributes(attrs, nullptr, 1123 /*MightBeObjCMessageSend*/ true); 1124 1125 // If this is the start of a declaration, parse it as such. 1126 if (isDeclarationStatement()) { 1127 // __extension__ silences extension warnings in the subdeclaration. 1128 // FIXME: Save the __extension__ on the decl as a node somehow? 1129 ExtensionRAIIObject O(Diags); 1130 1131 SourceLocation DeclStart = Tok.getLocation(), DeclEnd; 1132 DeclGroupPtrTy Res = 1133 ParseDeclaration(DeclaratorContext::Block, DeclEnd, attrs); 1134 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd); 1135 } else { 1136 // Otherwise this was a unary __extension__ marker. 1137 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc)); 1138 1139 if (Res.isInvalid()) { 1140 SkipUntil(tok::semi); 1141 continue; 1142 } 1143 1144 // Eat the semicolon at the end of stmt and convert the expr into a 1145 // statement. 1146 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr); 1147 R = handleExprStmt(Res, SubStmtCtx); 1148 if (R.isUsable()) 1149 R = Actions.ActOnAttributedStmt(attrs, R.get()); 1150 } 1151 } 1152 1153 if (R.isUsable()) 1154 Stmts.push_back(R.get()); 1155 } 1156 1157 SourceLocation CloseLoc = Tok.getLocation(); 1158 1159 // We broke out of the while loop because we found a '}' or EOF. 1160 if (!T.consumeClose()) { 1161 // If this is the '})' of a statement expression, check that it's written 1162 // in a sensible way. 1163 if (isStmtExpr && Tok.is(tok::r_paren)) 1164 checkCompoundToken(CloseLoc, tok::r_brace, CompoundToken::StmtExprEnd); 1165 } else { 1166 // Recover by creating a compound statement with what we parsed so far, 1167 // instead of dropping everything and returning StmtError(). 1168 } 1169 1170 if (T.getCloseLocation().isValid()) 1171 CloseLoc = T.getCloseLocation(); 1172 1173 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc, 1174 Stmts, isStmtExpr); 1175 } 1176 1177 /// ParseParenExprOrCondition: 1178 /// [C ] '(' expression ')' 1179 /// [C++] '(' condition ')' 1180 /// [C++1z] '(' init-statement[opt] condition ')' 1181 /// 1182 /// This function parses and performs error recovery on the specified condition 1183 /// or expression (depending on whether we're in C++ or C mode). This function 1184 /// goes out of its way to recover well. It returns true if there was a parser 1185 /// error (the right paren couldn't be found), which indicates that the caller 1186 /// should try to recover harder. It returns false if the condition is 1187 /// successfully parsed. Note that a successful parse can still have semantic 1188 /// errors in the condition. 1189 /// Additionally, if LParenLoc and RParenLoc are non-null, it will assign 1190 /// the location of the outer-most '(' and ')', respectively, to them. 1191 bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt, 1192 Sema::ConditionResult &Cond, 1193 SourceLocation Loc, 1194 Sema::ConditionKind CK, 1195 SourceLocation *LParenLoc, 1196 SourceLocation *RParenLoc) { 1197 BalancedDelimiterTracker T(*this, tok::l_paren); 1198 T.consumeOpen(); 1199 1200 if (getLangOpts().CPlusPlus) 1201 Cond = ParseCXXCondition(InitStmt, Loc, CK); 1202 else { 1203 ExprResult CondExpr = ParseExpression(); 1204 1205 // If required, convert to a boolean value. 1206 if (CondExpr.isInvalid()) 1207 Cond = Sema::ConditionError(); 1208 else 1209 Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK); 1210 } 1211 1212 // If the parser was confused by the condition and we don't have a ')', try to 1213 // recover by skipping ahead to a semi and bailing out. If condexp is 1214 // semantically invalid but we have well formed code, keep going. 1215 if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) { 1216 SkipUntil(tok::semi); 1217 // Skipping may have stopped if it found the containing ')'. If so, we can 1218 // continue parsing the if statement. 1219 if (Tok.isNot(tok::r_paren)) 1220 return true; 1221 } 1222 1223 // Otherwise the condition is valid or the rparen is present. 1224 T.consumeClose(); 1225 1226 if (LParenLoc != nullptr) { 1227 *LParenLoc = T.getOpenLocation(); 1228 } 1229 if (RParenLoc != nullptr) { 1230 *RParenLoc = T.getCloseLocation(); 1231 } 1232 1233 // Check for extraneous ')'s to catch things like "if (foo())) {". We know 1234 // that all callers are looking for a statement after the condition, so ")" 1235 // isn't valid. 1236 while (Tok.is(tok::r_paren)) { 1237 Diag(Tok, diag::err_extraneous_rparen_in_condition) 1238 << FixItHint::CreateRemoval(Tok.getLocation()); 1239 ConsumeParen(); 1240 } 1241 1242 return false; 1243 } 1244 1245 namespace { 1246 1247 enum MisleadingStatementKind { MSK_if, MSK_else, MSK_for, MSK_while }; 1248 1249 struct MisleadingIndentationChecker { 1250 Parser &P; 1251 SourceLocation StmtLoc; 1252 SourceLocation PrevLoc; 1253 unsigned NumDirectives; 1254 MisleadingStatementKind Kind; 1255 bool ShouldSkip; 1256 MisleadingIndentationChecker(Parser &P, MisleadingStatementKind K, 1257 SourceLocation SL) 1258 : P(P), StmtLoc(SL), PrevLoc(P.getCurToken().getLocation()), 1259 NumDirectives(P.getPreprocessor().getNumDirectives()), Kind(K), 1260 ShouldSkip(P.getCurToken().is(tok::l_brace)) { 1261 if (!P.MisleadingIndentationElseLoc.isInvalid()) { 1262 StmtLoc = P.MisleadingIndentationElseLoc; 1263 P.MisleadingIndentationElseLoc = SourceLocation(); 1264 } 1265 if (Kind == MSK_else && !ShouldSkip) 1266 P.MisleadingIndentationElseLoc = SL; 1267 } 1268 1269 /// Compute the column number will aligning tabs on TabStop (-ftabstop), this 1270 /// gives the visual indentation of the SourceLocation. 1271 static unsigned getVisualIndentation(SourceManager &SM, SourceLocation Loc) { 1272 unsigned TabStop = SM.getDiagnostics().getDiagnosticOptions().TabStop; 1273 1274 unsigned ColNo = SM.getSpellingColumnNumber(Loc); 1275 if (ColNo == 0 || TabStop == 1) 1276 return ColNo; 1277 1278 std::pair<FileID, unsigned> FIDAndOffset = SM.getDecomposedLoc(Loc); 1279 1280 bool Invalid; 1281 StringRef BufData = SM.getBufferData(FIDAndOffset.first, &Invalid); 1282 if (Invalid) 1283 return 0; 1284 1285 const char *EndPos = BufData.data() + FIDAndOffset.second; 1286 // FileOffset are 0-based and Column numbers are 1-based 1287 assert(FIDAndOffset.second + 1 >= ColNo && 1288 "Column number smaller than file offset?"); 1289 1290 unsigned VisualColumn = 0; // Stored as 0-based column, here. 1291 // Loop from beginning of line up to Loc's file position, counting columns, 1292 // expanding tabs. 1293 for (const char *CurPos = EndPos - (ColNo - 1); CurPos != EndPos; 1294 ++CurPos) { 1295 if (*CurPos == '\t') 1296 // Advance visual column to next tabstop. 1297 VisualColumn += (TabStop - VisualColumn % TabStop); 1298 else 1299 VisualColumn++; 1300 } 1301 return VisualColumn + 1; 1302 } 1303 1304 void Check() { 1305 Token Tok = P.getCurToken(); 1306 if (P.getActions().getDiagnostics().isIgnored( 1307 diag::warn_misleading_indentation, Tok.getLocation()) || 1308 ShouldSkip || NumDirectives != P.getPreprocessor().getNumDirectives() || 1309 Tok.isOneOf(tok::semi, tok::r_brace) || Tok.isAnnotation() || 1310 Tok.getLocation().isMacroID() || PrevLoc.isMacroID() || 1311 StmtLoc.isMacroID() || 1312 (Kind == MSK_else && P.MisleadingIndentationElseLoc.isInvalid())) { 1313 P.MisleadingIndentationElseLoc = SourceLocation(); 1314 return; 1315 } 1316 if (Kind == MSK_else) 1317 P.MisleadingIndentationElseLoc = SourceLocation(); 1318 1319 SourceManager &SM = P.getPreprocessor().getSourceManager(); 1320 unsigned PrevColNum = getVisualIndentation(SM, PrevLoc); 1321 unsigned CurColNum = getVisualIndentation(SM, Tok.getLocation()); 1322 unsigned StmtColNum = getVisualIndentation(SM, StmtLoc); 1323 1324 if (PrevColNum != 0 && CurColNum != 0 && StmtColNum != 0 && 1325 ((PrevColNum > StmtColNum && PrevColNum == CurColNum) || 1326 !Tok.isAtStartOfLine()) && 1327 SM.getPresumedLineNumber(StmtLoc) != 1328 SM.getPresumedLineNumber(Tok.getLocation()) && 1329 (Tok.isNot(tok::identifier) || 1330 P.getPreprocessor().LookAhead(0).isNot(tok::colon))) { 1331 P.Diag(Tok.getLocation(), diag::warn_misleading_indentation) << Kind; 1332 P.Diag(StmtLoc, diag::note_previous_statement); 1333 } 1334 } 1335 }; 1336 1337 } 1338 1339 /// ParseIfStatement 1340 /// if-statement: [C99 6.8.4.1] 1341 /// 'if' '(' expression ')' statement 1342 /// 'if' '(' expression ')' statement 'else' statement 1343 /// [C++] 'if' '(' condition ')' statement 1344 /// [C++] 'if' '(' condition ')' statement 'else' statement 1345 /// [C++23] 'if' '!' [opt] consteval compound-statement 1346 /// [C++23] 'if' '!' [opt] consteval compound-statement 'else' statement 1347 /// 1348 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) { 1349 assert(Tok.is(tok::kw_if) && "Not an if stmt!"); 1350 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'. 1351 1352 bool IsConstexpr = false; 1353 bool IsConsteval = false; 1354 SourceLocation NotLocation; 1355 SourceLocation ConstevalLoc; 1356 1357 if (Tok.is(tok::kw_constexpr)) { 1358 Diag(Tok, getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_constexpr_if 1359 : diag::ext_constexpr_if); 1360 IsConstexpr = true; 1361 ConsumeToken(); 1362 } else { 1363 if (Tok.is(tok::exclaim)) { 1364 NotLocation = ConsumeToken(); 1365 } 1366 1367 if (Tok.is(tok::kw_consteval)) { 1368 Diag(Tok, getLangOpts().CPlusPlus2b ? diag::warn_cxx20_compat_consteval_if 1369 : diag::ext_consteval_if); 1370 IsConsteval = true; 1371 ConstevalLoc = ConsumeToken(); 1372 } 1373 } 1374 if (!IsConsteval && (NotLocation.isValid() || Tok.isNot(tok::l_paren))) { 1375 Diag(Tok, diag::err_expected_lparen_after) << "if"; 1376 SkipUntil(tok::semi); 1377 return StmtError(); 1378 } 1379 1380 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus; 1381 1382 // C99 6.8.4p3 - In C99, the if statement is a block. This is not 1383 // the case for C90. 1384 // 1385 // C++ 6.4p3: 1386 // A name introduced by a declaration in a condition is in scope from its 1387 // point of declaration until the end of the substatements controlled by the 1388 // condition. 1389 // C++ 3.3.2p4: 1390 // Names declared in the for-init-statement, and in the condition of if, 1391 // while, for, and switch statements are local to the if, while, for, or 1392 // switch statement (including the controlled statement). 1393 // 1394 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX); 1395 1396 // Parse the condition. 1397 StmtResult InitStmt; 1398 Sema::ConditionResult Cond; 1399 SourceLocation LParen; 1400 SourceLocation RParen; 1401 llvm::Optional<bool> ConstexprCondition; 1402 if (!IsConsteval) { 1403 1404 if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc, 1405 IsConstexpr ? Sema::ConditionKind::ConstexprIf 1406 : Sema::ConditionKind::Boolean, 1407 &LParen, &RParen)) 1408 return StmtError(); 1409 1410 if (IsConstexpr) 1411 ConstexprCondition = Cond.getKnownValue(); 1412 } 1413 1414 bool IsBracedThen = Tok.is(tok::l_brace); 1415 1416 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if 1417 // there is no compound stmt. C90 does not have this clause. We only do this 1418 // if the body isn't a compound statement to avoid push/pop in common cases. 1419 // 1420 // C++ 6.4p1: 1421 // The substatement in a selection-statement (each substatement, in the else 1422 // form of the if statement) implicitly defines a local scope. 1423 // 1424 // For C++ we create a scope for the condition and a new scope for 1425 // substatements because: 1426 // -When the 'then' scope exits, we want the condition declaration to still be 1427 // active for the 'else' scope too. 1428 // -Sema will detect name clashes by considering declarations of a 1429 // 'ControlScope' as part of its direct subscope. 1430 // -If we wanted the condition and substatement to be in the same scope, we 1431 // would have to notify ParseStatement not to create a new scope. It's 1432 // simpler to let it create a new scope. 1433 // 1434 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, IsBracedThen); 1435 1436 MisleadingIndentationChecker MIChecker(*this, MSK_if, IfLoc); 1437 1438 // Read the 'then' stmt. 1439 SourceLocation ThenStmtLoc = Tok.getLocation(); 1440 1441 SourceLocation InnerStatementTrailingElseLoc; 1442 StmtResult ThenStmt; 1443 { 1444 bool ShouldEnter = ConstexprCondition && !*ConstexprCondition; 1445 Sema::ExpressionEvaluationContext Context = 1446 Sema::ExpressionEvaluationContext::DiscardedStatement; 1447 if (NotLocation.isInvalid() && IsConsteval) { 1448 Context = Sema::ExpressionEvaluationContext::ImmediateFunctionContext; 1449 ShouldEnter = true; 1450 } 1451 1452 EnterExpressionEvaluationContext PotentiallyDiscarded( 1453 Actions, Context, nullptr, 1454 Sema::ExpressionEvaluationContextRecord::EK_Other, ShouldEnter); 1455 ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc); 1456 } 1457 1458 if (Tok.isNot(tok::kw_else)) 1459 MIChecker.Check(); 1460 1461 // Pop the 'if' scope if needed. 1462 InnerScope.Exit(); 1463 1464 // If it has an else, parse it. 1465 SourceLocation ElseLoc; 1466 SourceLocation ElseStmtLoc; 1467 StmtResult ElseStmt; 1468 1469 if (Tok.is(tok::kw_else)) { 1470 if (TrailingElseLoc) 1471 *TrailingElseLoc = Tok.getLocation(); 1472 1473 ElseLoc = ConsumeToken(); 1474 ElseStmtLoc = Tok.getLocation(); 1475 1476 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if 1477 // there is no compound stmt. C90 does not have this clause. We only do 1478 // this if the body isn't a compound statement to avoid push/pop in common 1479 // cases. 1480 // 1481 // C++ 6.4p1: 1482 // The substatement in a selection-statement (each substatement, in the else 1483 // form of the if statement) implicitly defines a local scope. 1484 // 1485 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, 1486 Tok.is(tok::l_brace)); 1487 1488 MisleadingIndentationChecker MIChecker(*this, MSK_else, ElseLoc); 1489 bool ShouldEnter = ConstexprCondition && *ConstexprCondition; 1490 Sema::ExpressionEvaluationContext Context = 1491 Sema::ExpressionEvaluationContext::DiscardedStatement; 1492 if (NotLocation.isValid() && IsConsteval) { 1493 Context = Sema::ExpressionEvaluationContext::ImmediateFunctionContext; 1494 ShouldEnter = true; 1495 } 1496 1497 EnterExpressionEvaluationContext PotentiallyDiscarded( 1498 Actions, Context, nullptr, 1499 Sema::ExpressionEvaluationContextRecord::EK_Other, ShouldEnter); 1500 ElseStmt = ParseStatement(); 1501 1502 if (ElseStmt.isUsable()) 1503 MIChecker.Check(); 1504 1505 // Pop the 'else' scope if needed. 1506 InnerScope.Exit(); 1507 } else if (Tok.is(tok::code_completion)) { 1508 cutOffParsing(); 1509 Actions.CodeCompleteAfterIf(getCurScope(), IsBracedThen); 1510 return StmtError(); 1511 } else if (InnerStatementTrailingElseLoc.isValid()) { 1512 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else); 1513 } 1514 1515 IfScope.Exit(); 1516 1517 // If the then or else stmt is invalid and the other is valid (and present), 1518 // make turn the invalid one into a null stmt to avoid dropping the other 1519 // part. If both are invalid, return error. 1520 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) || 1521 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) || 1522 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) { 1523 // Both invalid, or one is invalid and other is non-present: return error. 1524 return StmtError(); 1525 } 1526 1527 if (IsConsteval) { 1528 auto IsCompoundStatement = [](const Stmt *S) { 1529 if (const auto *Outer = dyn_cast_or_null<AttributedStmt>(S)) 1530 S = Outer->getSubStmt(); 1531 return isa_and_nonnull<clang::CompoundStmt>(S); 1532 }; 1533 1534 if (!IsCompoundStatement(ThenStmt.get())) { 1535 Diag(ConstevalLoc, diag::err_expected_after) << "consteval" 1536 << "{"; 1537 return StmtError(); 1538 } 1539 if (!ElseStmt.isUnset() && !IsCompoundStatement(ElseStmt.get())) { 1540 Diag(ElseLoc, diag::err_expected_after) << "else" 1541 << "{"; 1542 return StmtError(); 1543 } 1544 } 1545 1546 // Now if either are invalid, replace with a ';'. 1547 if (ThenStmt.isInvalid()) 1548 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc); 1549 if (ElseStmt.isInvalid()) 1550 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc); 1551 1552 IfStatementKind Kind = IfStatementKind::Ordinary; 1553 if (IsConstexpr) 1554 Kind = IfStatementKind::Constexpr; 1555 else if (IsConsteval) 1556 Kind = NotLocation.isValid() ? IfStatementKind::ConstevalNegated 1557 : IfStatementKind::ConstevalNonNegated; 1558 1559 return Actions.ActOnIfStmt(IfLoc, Kind, LParen, InitStmt.get(), Cond, RParen, 1560 ThenStmt.get(), ElseLoc, ElseStmt.get()); 1561 } 1562 1563 /// ParseSwitchStatement 1564 /// switch-statement: 1565 /// 'switch' '(' expression ')' statement 1566 /// [C++] 'switch' '(' condition ')' statement 1567 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) { 1568 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!"); 1569 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'. 1570 1571 if (Tok.isNot(tok::l_paren)) { 1572 Diag(Tok, diag::err_expected_lparen_after) << "switch"; 1573 SkipUntil(tok::semi); 1574 return StmtError(); 1575 } 1576 1577 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus; 1578 1579 // C99 6.8.4p3 - In C99, the switch statement is a block. This is 1580 // not the case for C90. Start the switch scope. 1581 // 1582 // C++ 6.4p3: 1583 // A name introduced by a declaration in a condition is in scope from its 1584 // point of declaration until the end of the substatements controlled by the 1585 // condition. 1586 // C++ 3.3.2p4: 1587 // Names declared in the for-init-statement, and in the condition of if, 1588 // while, for, and switch statements are local to the if, while, for, or 1589 // switch statement (including the controlled statement). 1590 // 1591 unsigned ScopeFlags = Scope::SwitchScope; 1592 if (C99orCXX) 1593 ScopeFlags |= Scope::DeclScope | Scope::ControlScope; 1594 ParseScope SwitchScope(this, ScopeFlags); 1595 1596 // Parse the condition. 1597 StmtResult InitStmt; 1598 Sema::ConditionResult Cond; 1599 SourceLocation LParen; 1600 SourceLocation RParen; 1601 if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc, 1602 Sema::ConditionKind::Switch, &LParen, &RParen)) 1603 return StmtError(); 1604 1605 StmtResult Switch = Actions.ActOnStartOfSwitchStmt( 1606 SwitchLoc, LParen, InitStmt.get(), Cond, RParen); 1607 1608 if (Switch.isInvalid()) { 1609 // Skip the switch body. 1610 // FIXME: This is not optimal recovery, but parsing the body is more 1611 // dangerous due to the presence of case and default statements, which 1612 // will have no place to connect back with the switch. 1613 if (Tok.is(tok::l_brace)) { 1614 ConsumeBrace(); 1615 SkipUntil(tok::r_brace); 1616 } else 1617 SkipUntil(tok::semi); 1618 return Switch; 1619 } 1620 1621 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if 1622 // there is no compound stmt. C90 does not have this clause. We only do this 1623 // if the body isn't a compound statement to avoid push/pop in common cases. 1624 // 1625 // C++ 6.4p1: 1626 // The substatement in a selection-statement (each substatement, in the else 1627 // form of the if statement) implicitly defines a local scope. 1628 // 1629 // See comments in ParseIfStatement for why we create a scope for the 1630 // condition and a new scope for substatement in C++. 1631 // 1632 getCurScope()->AddFlags(Scope::BreakScope); 1633 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace)); 1634 1635 // We have incremented the mangling number for the SwitchScope and the 1636 // InnerScope, which is one too many. 1637 if (C99orCXX) 1638 getCurScope()->decrementMSManglingNumber(); 1639 1640 // Read the body statement. 1641 StmtResult Body(ParseStatement(TrailingElseLoc)); 1642 1643 // Pop the scopes. 1644 InnerScope.Exit(); 1645 SwitchScope.Exit(); 1646 1647 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get()); 1648 } 1649 1650 /// ParseWhileStatement 1651 /// while-statement: [C99 6.8.5.1] 1652 /// 'while' '(' expression ')' statement 1653 /// [C++] 'while' '(' condition ')' statement 1654 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) { 1655 assert(Tok.is(tok::kw_while) && "Not a while stmt!"); 1656 SourceLocation WhileLoc = Tok.getLocation(); 1657 ConsumeToken(); // eat the 'while'. 1658 1659 if (Tok.isNot(tok::l_paren)) { 1660 Diag(Tok, diag::err_expected_lparen_after) << "while"; 1661 SkipUntil(tok::semi); 1662 return StmtError(); 1663 } 1664 1665 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus; 1666 1667 // C99 6.8.5p5 - In C99, the while statement is a block. This is not 1668 // the case for C90. Start the loop scope. 1669 // 1670 // C++ 6.4p3: 1671 // A name introduced by a declaration in a condition is in scope from its 1672 // point of declaration until the end of the substatements controlled by the 1673 // condition. 1674 // C++ 3.3.2p4: 1675 // Names declared in the for-init-statement, and in the condition of if, 1676 // while, for, and switch statements are local to the if, while, for, or 1677 // switch statement (including the controlled statement). 1678 // 1679 unsigned ScopeFlags; 1680 if (C99orCXX) 1681 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | 1682 Scope::DeclScope | Scope::ControlScope; 1683 else 1684 ScopeFlags = Scope::BreakScope | Scope::ContinueScope; 1685 ParseScope WhileScope(this, ScopeFlags); 1686 1687 // Parse the condition. 1688 Sema::ConditionResult Cond; 1689 SourceLocation LParen; 1690 SourceLocation RParen; 1691 if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc, 1692 Sema::ConditionKind::Boolean, &LParen, &RParen)) 1693 return StmtError(); 1694 1695 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if 1696 // there is no compound stmt. C90 does not have this clause. We only do this 1697 // if the body isn't a compound statement to avoid push/pop in common cases. 1698 // 1699 // C++ 6.5p2: 1700 // The substatement in an iteration-statement implicitly defines a local scope 1701 // which is entered and exited each time through the loop. 1702 // 1703 // See comments in ParseIfStatement for why we create a scope for the 1704 // condition and a new scope for substatement in C++. 1705 // 1706 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace)); 1707 1708 MisleadingIndentationChecker MIChecker(*this, MSK_while, WhileLoc); 1709 1710 // Read the body statement. 1711 StmtResult Body(ParseStatement(TrailingElseLoc)); 1712 1713 if (Body.isUsable()) 1714 MIChecker.Check(); 1715 // Pop the body scope if needed. 1716 InnerScope.Exit(); 1717 WhileScope.Exit(); 1718 1719 if (Cond.isInvalid() || Body.isInvalid()) 1720 return StmtError(); 1721 1722 return Actions.ActOnWhileStmt(WhileLoc, LParen, Cond, RParen, Body.get()); 1723 } 1724 1725 /// ParseDoStatement 1726 /// do-statement: [C99 6.8.5.2] 1727 /// 'do' statement 'while' '(' expression ')' ';' 1728 /// Note: this lets the caller parse the end ';'. 1729 StmtResult Parser::ParseDoStatement() { 1730 assert(Tok.is(tok::kw_do) && "Not a do stmt!"); 1731 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'. 1732 1733 // C99 6.8.5p5 - In C99, the do statement is a block. This is not 1734 // the case for C90. Start the loop scope. 1735 unsigned ScopeFlags; 1736 if (getLangOpts().C99) 1737 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope; 1738 else 1739 ScopeFlags = Scope::BreakScope | Scope::ContinueScope; 1740 1741 ParseScope DoScope(this, ScopeFlags); 1742 1743 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if 1744 // there is no compound stmt. C90 does not have this clause. We only do this 1745 // if the body isn't a compound statement to avoid push/pop in common cases. 1746 // 1747 // C++ 6.5p2: 1748 // The substatement in an iteration-statement implicitly defines a local scope 1749 // which is entered and exited each time through the loop. 1750 // 1751 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus; 1752 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace)); 1753 1754 // Read the body statement. 1755 StmtResult Body(ParseStatement()); 1756 1757 // Pop the body scope if needed. 1758 InnerScope.Exit(); 1759 1760 if (Tok.isNot(tok::kw_while)) { 1761 if (!Body.isInvalid()) { 1762 Diag(Tok, diag::err_expected_while); 1763 Diag(DoLoc, diag::note_matching) << "'do'"; 1764 SkipUntil(tok::semi, StopBeforeMatch); 1765 } 1766 return StmtError(); 1767 } 1768 SourceLocation WhileLoc = ConsumeToken(); 1769 1770 if (Tok.isNot(tok::l_paren)) { 1771 Diag(Tok, diag::err_expected_lparen_after) << "do/while"; 1772 SkipUntil(tok::semi, StopBeforeMatch); 1773 return StmtError(); 1774 } 1775 1776 // Parse the parenthesized expression. 1777 BalancedDelimiterTracker T(*this, tok::l_paren); 1778 T.consumeOpen(); 1779 1780 // A do-while expression is not a condition, so can't have attributes. 1781 DiagnoseAndSkipCXX11Attributes(); 1782 1783 ExprResult Cond = ParseExpression(); 1784 // Correct the typos in condition before closing the scope. 1785 if (Cond.isUsable()) 1786 Cond = Actions.CorrectDelayedTyposInExpr(Cond); 1787 T.consumeClose(); 1788 DoScope.Exit(); 1789 1790 if (Cond.isInvalid() || Body.isInvalid()) 1791 return StmtError(); 1792 1793 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(), 1794 Cond.get(), T.getCloseLocation()); 1795 } 1796 1797 bool Parser::isForRangeIdentifier() { 1798 assert(Tok.is(tok::identifier)); 1799 1800 const Token &Next = NextToken(); 1801 if (Next.is(tok::colon)) 1802 return true; 1803 1804 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) { 1805 TentativeParsingAction PA(*this); 1806 ConsumeToken(); 1807 SkipCXX11Attributes(); 1808 bool Result = Tok.is(tok::colon); 1809 PA.Revert(); 1810 return Result; 1811 } 1812 1813 return false; 1814 } 1815 1816 /// ParseForStatement 1817 /// for-statement: [C99 6.8.5.3] 1818 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement 1819 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement 1820 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')' 1821 /// [C++] statement 1822 /// [C++0x] 'for' 1823 /// 'co_await'[opt] [Coroutines] 1824 /// '(' for-range-declaration ':' for-range-initializer ')' 1825 /// statement 1826 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement 1827 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement 1828 /// 1829 /// [C++] for-init-statement: 1830 /// [C++] expression-statement 1831 /// [C++] simple-declaration 1832 /// [C++2b] alias-declaration 1833 /// 1834 /// [C++0x] for-range-declaration: 1835 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator 1836 /// [C++0x] for-range-initializer: 1837 /// [C++0x] expression 1838 /// [C++0x] braced-init-list [TODO] 1839 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) { 1840 assert(Tok.is(tok::kw_for) && "Not a for stmt!"); 1841 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'. 1842 1843 SourceLocation CoawaitLoc; 1844 if (Tok.is(tok::kw_co_await)) 1845 CoawaitLoc = ConsumeToken(); 1846 1847 if (Tok.isNot(tok::l_paren)) { 1848 Diag(Tok, diag::err_expected_lparen_after) << "for"; 1849 SkipUntil(tok::semi); 1850 return StmtError(); 1851 } 1852 1853 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus || 1854 getLangOpts().ObjC; 1855 1856 // C99 6.8.5p5 - In C99, the for statement is a block. This is not 1857 // the case for C90. Start the loop scope. 1858 // 1859 // C++ 6.4p3: 1860 // A name introduced by a declaration in a condition is in scope from its 1861 // point of declaration until the end of the substatements controlled by the 1862 // condition. 1863 // C++ 3.3.2p4: 1864 // Names declared in the for-init-statement, and in the condition of if, 1865 // while, for, and switch statements are local to the if, while, for, or 1866 // switch statement (including the controlled statement). 1867 // C++ 6.5.3p1: 1868 // Names declared in the for-init-statement are in the same declarative-region 1869 // as those declared in the condition. 1870 // 1871 unsigned ScopeFlags = 0; 1872 if (C99orCXXorObjC) 1873 ScopeFlags = Scope::DeclScope | Scope::ControlScope; 1874 1875 ParseScope ForScope(this, ScopeFlags); 1876 1877 BalancedDelimiterTracker T(*this, tok::l_paren); 1878 T.consumeOpen(); 1879 1880 ExprResult Value; 1881 1882 bool ForEach = false; 1883 StmtResult FirstPart; 1884 Sema::ConditionResult SecondPart; 1885 ExprResult Collection; 1886 ForRangeInfo ForRangeInfo; 1887 FullExprArg ThirdPart(Actions); 1888 1889 if (Tok.is(tok::code_completion)) { 1890 cutOffParsing(); 1891 Actions.CodeCompleteOrdinaryName(getCurScope(), 1892 C99orCXXorObjC? Sema::PCC_ForInit 1893 : Sema::PCC_Expression); 1894 return StmtError(); 1895 } 1896 1897 ParsedAttributesWithRange attrs(AttrFactory); 1898 MaybeParseCXX11Attributes(attrs); 1899 1900 SourceLocation EmptyInitStmtSemiLoc; 1901 1902 // Parse the first part of the for specifier. 1903 if (Tok.is(tok::semi)) { // for (; 1904 ProhibitAttributes(attrs); 1905 // no first part, eat the ';'. 1906 SourceLocation SemiLoc = Tok.getLocation(); 1907 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) 1908 EmptyInitStmtSemiLoc = SemiLoc; 1909 ConsumeToken(); 1910 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) && 1911 isForRangeIdentifier()) { 1912 ProhibitAttributes(attrs); 1913 IdentifierInfo *Name = Tok.getIdentifierInfo(); 1914 SourceLocation Loc = ConsumeToken(); 1915 MaybeParseCXX11Attributes(attrs); 1916 1917 ForRangeInfo.ColonLoc = ConsumeToken(); 1918 if (Tok.is(tok::l_brace)) 1919 ForRangeInfo.RangeExpr = ParseBraceInitializer(); 1920 else 1921 ForRangeInfo.RangeExpr = ParseExpression(); 1922 1923 Diag(Loc, diag::err_for_range_identifier) 1924 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17) 1925 ? FixItHint::CreateInsertion(Loc, "auto &&") 1926 : FixItHint()); 1927 1928 ForRangeInfo.LoopVar = Actions.ActOnCXXForRangeIdentifier( 1929 getCurScope(), Loc, Name, attrs, attrs.Range.getEnd()); 1930 } else if (isForInitDeclaration()) { // for (int X = 4; 1931 ParenBraceBracketBalancer BalancerRAIIObj(*this); 1932 1933 // Parse declaration, which eats the ';'. 1934 if (!C99orCXXorObjC) { // Use of C99-style for loops in C90 mode? 1935 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop); 1936 Diag(Tok, diag::warn_gcc_variable_decl_in_for_loop); 1937 } 1938 DeclGroupPtrTy DG; 1939 if (Tok.is(tok::kw_using)) { 1940 DG = ParseAliasDeclarationInInitStatement(DeclaratorContext::ForInit, 1941 attrs); 1942 } else { 1943 // In C++0x, "for (T NS:a" might not be a typo for :: 1944 bool MightBeForRangeStmt = getLangOpts().CPlusPlus; 1945 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt); 1946 1947 SourceLocation DeclStart = Tok.getLocation(), DeclEnd; 1948 DG = ParseSimpleDeclaration( 1949 DeclaratorContext::ForInit, DeclEnd, attrs, false, 1950 MightBeForRangeStmt ? &ForRangeInfo : nullptr); 1951 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation()); 1952 if (ForRangeInfo.ParsedForRangeDecl()) { 1953 Diag(ForRangeInfo.ColonLoc, getLangOpts().CPlusPlus11 1954 ? diag::warn_cxx98_compat_for_range 1955 : diag::ext_for_range); 1956 ForRangeInfo.LoopVar = FirstPart; 1957 FirstPart = StmtResult(); 1958 } else if (Tok.is(tok::semi)) { // for (int x = 4; 1959 ConsumeToken(); 1960 } else if ((ForEach = isTokIdentifier_in())) { 1961 Actions.ActOnForEachDeclStmt(DG); 1962 // ObjC: for (id x in expr) 1963 ConsumeToken(); // consume 'in' 1964 1965 if (Tok.is(tok::code_completion)) { 1966 cutOffParsing(); 1967 Actions.CodeCompleteObjCForCollection(getCurScope(), DG); 1968 return StmtError(); 1969 } 1970 Collection = ParseExpression(); 1971 } else { 1972 Diag(Tok, diag::err_expected_semi_for); 1973 } 1974 } 1975 } else { 1976 ProhibitAttributes(attrs); 1977 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression()); 1978 1979 ForEach = isTokIdentifier_in(); 1980 1981 // Turn the expression into a stmt. 1982 if (!Value.isInvalid()) { 1983 if (ForEach) 1984 FirstPart = Actions.ActOnForEachLValueExpr(Value.get()); 1985 else { 1986 // We already know this is not an init-statement within a for loop, so 1987 // if we are parsing a C++11 range-based for loop, we should treat this 1988 // expression statement as being a discarded value expression because 1989 // we will err below. This way we do not warn on an unused expression 1990 // that was an error in the first place, like with: for (expr : expr); 1991 bool IsRangeBasedFor = 1992 getLangOpts().CPlusPlus11 && !ForEach && Tok.is(tok::colon); 1993 FirstPart = Actions.ActOnExprStmt(Value, !IsRangeBasedFor); 1994 } 1995 } 1996 1997 if (Tok.is(tok::semi)) { 1998 ConsumeToken(); 1999 } else if (ForEach) { 2000 ConsumeToken(); // consume 'in' 2001 2002 if (Tok.is(tok::code_completion)) { 2003 cutOffParsing(); 2004 Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr); 2005 return StmtError(); 2006 } 2007 Collection = ParseExpression(); 2008 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) { 2009 // User tried to write the reasonable, but ill-formed, for-range-statement 2010 // for (expr : expr) { ... } 2011 Diag(Tok, diag::err_for_range_expected_decl) 2012 << FirstPart.get()->getSourceRange(); 2013 SkipUntil(tok::r_paren, StopBeforeMatch); 2014 SecondPart = Sema::ConditionError(); 2015 } else { 2016 if (!Value.isInvalid()) { 2017 Diag(Tok, diag::err_expected_semi_for); 2018 } else { 2019 // Skip until semicolon or rparen, don't consume it. 2020 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch); 2021 if (Tok.is(tok::semi)) 2022 ConsumeToken(); 2023 } 2024 } 2025 } 2026 2027 // Parse the second part of the for specifier. 2028 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl() && 2029 !SecondPart.isInvalid()) { 2030 // Parse the second part of the for specifier. 2031 if (Tok.is(tok::semi)) { // for (...;; 2032 // no second part. 2033 } else if (Tok.is(tok::r_paren)) { 2034 // missing both semicolons. 2035 } else { 2036 if (getLangOpts().CPlusPlus) { 2037 // C++2a: We've parsed an init-statement; we might have a 2038 // for-range-declaration next. 2039 bool MightBeForRangeStmt = !ForRangeInfo.ParsedForRangeDecl(); 2040 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt); 2041 SecondPart = 2042 ParseCXXCondition(nullptr, ForLoc, Sema::ConditionKind::Boolean, 2043 MightBeForRangeStmt ? &ForRangeInfo : nullptr, 2044 /*EnterForConditionScope*/ true); 2045 2046 if (ForRangeInfo.ParsedForRangeDecl()) { 2047 Diag(FirstPart.get() ? FirstPart.get()->getBeginLoc() 2048 : ForRangeInfo.ColonLoc, 2049 getLangOpts().CPlusPlus20 2050 ? diag::warn_cxx17_compat_for_range_init_stmt 2051 : diag::ext_for_range_init_stmt) 2052 << (FirstPart.get() ? FirstPart.get()->getSourceRange() 2053 : SourceRange()); 2054 if (EmptyInitStmtSemiLoc.isValid()) { 2055 Diag(EmptyInitStmtSemiLoc, diag::warn_empty_init_statement) 2056 << /*for-loop*/ 2 2057 << FixItHint::CreateRemoval(EmptyInitStmtSemiLoc); 2058 } 2059 } 2060 } else { 2061 // We permit 'continue' and 'break' in the condition of a for loop. 2062 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope); 2063 2064 ExprResult SecondExpr = ParseExpression(); 2065 if (SecondExpr.isInvalid()) 2066 SecondPart = Sema::ConditionError(); 2067 else 2068 SecondPart = 2069 Actions.ActOnCondition(getCurScope(), ForLoc, SecondExpr.get(), 2070 Sema::ConditionKind::Boolean); 2071 } 2072 } 2073 } 2074 2075 // Enter a break / continue scope, if we didn't already enter one while 2076 // parsing the second part. 2077 if (!(getCurScope()->getFlags() & Scope::ContinueScope)) 2078 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope); 2079 2080 // Parse the third part of the for statement. 2081 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl()) { 2082 if (Tok.isNot(tok::semi)) { 2083 if (!SecondPart.isInvalid()) 2084 Diag(Tok, diag::err_expected_semi_for); 2085 else 2086 // Skip until semicolon or rparen, don't consume it. 2087 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch); 2088 } 2089 2090 if (Tok.is(tok::semi)) { 2091 ConsumeToken(); 2092 } 2093 2094 if (Tok.isNot(tok::r_paren)) { // for (...;...;) 2095 ExprResult Third = ParseExpression(); 2096 // FIXME: The C++11 standard doesn't actually say that this is a 2097 // discarded-value expression, but it clearly should be. 2098 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get()); 2099 } 2100 } 2101 // Match the ')'. 2102 T.consumeClose(); 2103 2104 // C++ Coroutines [stmt.iter]: 2105 // 'co_await' can only be used for a range-based for statement. 2106 if (CoawaitLoc.isValid() && !ForRangeInfo.ParsedForRangeDecl()) { 2107 Diag(CoawaitLoc, diag::err_for_co_await_not_range_for); 2108 CoawaitLoc = SourceLocation(); 2109 } 2110 2111 // We need to perform most of the semantic analysis for a C++0x for-range 2112 // statememt before parsing the body, in order to be able to deduce the type 2113 // of an auto-typed loop variable. 2114 StmtResult ForRangeStmt; 2115 StmtResult ForEachStmt; 2116 2117 if (ForRangeInfo.ParsedForRangeDecl()) { 2118 ExprResult CorrectedRange = 2119 Actions.CorrectDelayedTyposInExpr(ForRangeInfo.RangeExpr.get()); 2120 ForRangeStmt = Actions.ActOnCXXForRangeStmt( 2121 getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(), 2122 ForRangeInfo.LoopVar.get(), ForRangeInfo.ColonLoc, CorrectedRange.get(), 2123 T.getCloseLocation(), Sema::BFRK_Build); 2124 2125 // Similarly, we need to do the semantic analysis for a for-range 2126 // statement immediately in order to close over temporaries correctly. 2127 } else if (ForEach) { 2128 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc, 2129 FirstPart.get(), 2130 Collection.get(), 2131 T.getCloseLocation()); 2132 } else { 2133 // In OpenMP loop region loop control variable must be captured and be 2134 // private. Perform analysis of first part (if any). 2135 if (getLangOpts().OpenMP && FirstPart.isUsable()) { 2136 Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get()); 2137 } 2138 } 2139 2140 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if 2141 // there is no compound stmt. C90 does not have this clause. We only do this 2142 // if the body isn't a compound statement to avoid push/pop in common cases. 2143 // 2144 // C++ 6.5p2: 2145 // The substatement in an iteration-statement implicitly defines a local scope 2146 // which is entered and exited each time through the loop. 2147 // 2148 // See comments in ParseIfStatement for why we create a scope for 2149 // for-init-statement/condition and a new scope for substatement in C++. 2150 // 2151 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC, 2152 Tok.is(tok::l_brace)); 2153 2154 // The body of the for loop has the same local mangling number as the 2155 // for-init-statement. 2156 // It will only be incremented if the body contains other things that would 2157 // normally increment the mangling number (like a compound statement). 2158 if (C99orCXXorObjC) 2159 getCurScope()->decrementMSManglingNumber(); 2160 2161 MisleadingIndentationChecker MIChecker(*this, MSK_for, ForLoc); 2162 2163 // Read the body statement. 2164 StmtResult Body(ParseStatement(TrailingElseLoc)); 2165 2166 if (Body.isUsable()) 2167 MIChecker.Check(); 2168 2169 // Pop the body scope if needed. 2170 InnerScope.Exit(); 2171 2172 // Leave the for-scope. 2173 ForScope.Exit(); 2174 2175 if (Body.isInvalid()) 2176 return StmtError(); 2177 2178 if (ForEach) 2179 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(), 2180 Body.get()); 2181 2182 if (ForRangeInfo.ParsedForRangeDecl()) 2183 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get()); 2184 2185 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(), 2186 SecondPart, ThirdPart, T.getCloseLocation(), 2187 Body.get()); 2188 } 2189 2190 /// ParseGotoStatement 2191 /// jump-statement: 2192 /// 'goto' identifier ';' 2193 /// [GNU] 'goto' '*' expression ';' 2194 /// 2195 /// Note: this lets the caller parse the end ';'. 2196 /// 2197 StmtResult Parser::ParseGotoStatement() { 2198 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!"); 2199 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'. 2200 2201 StmtResult Res; 2202 if (Tok.is(tok::identifier)) { 2203 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(), 2204 Tok.getLocation()); 2205 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD); 2206 ConsumeToken(); 2207 } else if (Tok.is(tok::star)) { 2208 // GNU indirect goto extension. 2209 Diag(Tok, diag::ext_gnu_indirect_goto); 2210 SourceLocation StarLoc = ConsumeToken(); 2211 ExprResult R(ParseExpression()); 2212 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it. 2213 SkipUntil(tok::semi, StopBeforeMatch); 2214 return StmtError(); 2215 } 2216 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get()); 2217 } else { 2218 Diag(Tok, diag::err_expected) << tok::identifier; 2219 return StmtError(); 2220 } 2221 2222 return Res; 2223 } 2224 2225 /// ParseContinueStatement 2226 /// jump-statement: 2227 /// 'continue' ';' 2228 /// 2229 /// Note: this lets the caller parse the end ';'. 2230 /// 2231 StmtResult Parser::ParseContinueStatement() { 2232 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'. 2233 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope()); 2234 } 2235 2236 /// ParseBreakStatement 2237 /// jump-statement: 2238 /// 'break' ';' 2239 /// 2240 /// Note: this lets the caller parse the end ';'. 2241 /// 2242 StmtResult Parser::ParseBreakStatement() { 2243 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'. 2244 return Actions.ActOnBreakStmt(BreakLoc, getCurScope()); 2245 } 2246 2247 /// ParseReturnStatement 2248 /// jump-statement: 2249 /// 'return' expression[opt] ';' 2250 /// 'return' braced-init-list ';' 2251 /// 'co_return' expression[opt] ';' 2252 /// 'co_return' braced-init-list ';' 2253 StmtResult Parser::ParseReturnStatement() { 2254 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) && 2255 "Not a return stmt!"); 2256 bool IsCoreturn = Tok.is(tok::kw_co_return); 2257 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'. 2258 2259 ExprResult R; 2260 if (Tok.isNot(tok::semi)) { 2261 if (!IsCoreturn) 2262 PreferredType.enterReturn(Actions, Tok.getLocation()); 2263 // FIXME: Code completion for co_return. 2264 if (Tok.is(tok::code_completion) && !IsCoreturn) { 2265 cutOffParsing(); 2266 Actions.CodeCompleteExpression(getCurScope(), 2267 PreferredType.get(Tok.getLocation())); 2268 return StmtError(); 2269 } 2270 2271 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) { 2272 R = ParseInitializer(); 2273 if (R.isUsable()) 2274 Diag(R.get()->getBeginLoc(), 2275 getLangOpts().CPlusPlus11 2276 ? diag::warn_cxx98_compat_generalized_initializer_lists 2277 : diag::ext_generalized_initializer_lists) 2278 << R.get()->getSourceRange(); 2279 } else 2280 R = ParseExpression(); 2281 if (R.isInvalid()) { 2282 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 2283 return StmtError(); 2284 } 2285 } 2286 if (IsCoreturn) 2287 return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get()); 2288 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope()); 2289 } 2290 2291 StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts, 2292 ParsedStmtContext StmtCtx, 2293 SourceLocation *TrailingElseLoc, 2294 ParsedAttributesWithRange &Attrs) { 2295 // Create temporary attribute list. 2296 ParsedAttributesWithRange TempAttrs(AttrFactory); 2297 2298 SourceLocation StartLoc = Tok.getLocation(); 2299 2300 // Get loop hints and consume annotated token. 2301 while (Tok.is(tok::annot_pragma_loop_hint)) { 2302 LoopHint Hint; 2303 if (!HandlePragmaLoopHint(Hint)) 2304 continue; 2305 2306 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc, 2307 ArgsUnion(Hint.ValueExpr)}; 2308 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr, 2309 Hint.PragmaNameLoc->Loc, ArgHints, 4, 2310 ParsedAttr::AS_Pragma); 2311 } 2312 2313 // Get the next statement. 2314 MaybeParseCXX11Attributes(Attrs); 2315 2316 StmtResult S = ParseStatementOrDeclarationAfterAttributes( 2317 Stmts, StmtCtx, TrailingElseLoc, Attrs); 2318 2319 Attrs.takeAllFrom(TempAttrs); 2320 2321 // Start of attribute range may already be set for some invalid input. 2322 // See PR46336. 2323 if (Attrs.Range.getBegin().isInvalid()) 2324 Attrs.Range.setBegin(StartLoc); 2325 2326 return S; 2327 } 2328 2329 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) { 2330 assert(Tok.is(tok::l_brace)); 2331 SourceLocation LBraceLoc = Tok.getLocation(); 2332 2333 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, LBraceLoc, 2334 "parsing function body"); 2335 2336 // Save and reset current vtordisp stack if we have entered a C++ method body. 2337 bool IsCXXMethod = 2338 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl); 2339 Sema::PragmaStackSentinelRAII 2340 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod); 2341 2342 // Do not enter a scope for the brace, as the arguments are in the same scope 2343 // (the function body) as the body itself. Instead, just read the statement 2344 // list and put it into a CompoundStmt for safe keeping. 2345 StmtResult FnBody(ParseCompoundStatementBody()); 2346 2347 // If the function body could not be parsed, make a bogus compoundstmt. 2348 if (FnBody.isInvalid()) { 2349 Sema::CompoundScopeRAII CompoundScope(Actions); 2350 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false); 2351 } 2352 2353 BodyScope.Exit(); 2354 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get()); 2355 } 2356 2357 /// ParseFunctionTryBlock - Parse a C++ function-try-block. 2358 /// 2359 /// function-try-block: 2360 /// 'try' ctor-initializer[opt] compound-statement handler-seq 2361 /// 2362 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) { 2363 assert(Tok.is(tok::kw_try) && "Expected 'try'"); 2364 SourceLocation TryLoc = ConsumeToken(); 2365 2366 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, TryLoc, 2367 "parsing function try block"); 2368 2369 // Constructor initializer list? 2370 if (Tok.is(tok::colon)) 2371 ParseConstructorInitializer(Decl); 2372 else 2373 Actions.ActOnDefaultCtorInitializers(Decl); 2374 2375 // Save and reset current vtordisp stack if we have entered a C++ method body. 2376 bool IsCXXMethod = 2377 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl); 2378 Sema::PragmaStackSentinelRAII 2379 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod); 2380 2381 SourceLocation LBraceLoc = Tok.getLocation(); 2382 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true)); 2383 // If we failed to parse the try-catch, we just give the function an empty 2384 // compound statement as the body. 2385 if (FnBody.isInvalid()) { 2386 Sema::CompoundScopeRAII CompoundScope(Actions); 2387 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false); 2388 } 2389 2390 BodyScope.Exit(); 2391 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get()); 2392 } 2393 2394 bool Parser::trySkippingFunctionBody() { 2395 assert(SkipFunctionBodies && 2396 "Should only be called when SkipFunctionBodies is enabled"); 2397 if (!PP.isCodeCompletionEnabled()) { 2398 SkipFunctionBody(); 2399 return true; 2400 } 2401 2402 // We're in code-completion mode. Skip parsing for all function bodies unless 2403 // the body contains the code-completion point. 2404 TentativeParsingAction PA(*this); 2405 bool IsTryCatch = Tok.is(tok::kw_try); 2406 CachedTokens Toks; 2407 bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks); 2408 if (llvm::any_of(Toks, [](const Token &Tok) { 2409 return Tok.is(tok::code_completion); 2410 })) { 2411 PA.Revert(); 2412 return false; 2413 } 2414 if (ErrorInPrologue) { 2415 PA.Commit(); 2416 SkipMalformedDecl(); 2417 return true; 2418 } 2419 if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) { 2420 PA.Revert(); 2421 return false; 2422 } 2423 while (IsTryCatch && Tok.is(tok::kw_catch)) { 2424 if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) || 2425 !SkipUntil(tok::r_brace, StopAtCodeCompletion)) { 2426 PA.Revert(); 2427 return false; 2428 } 2429 } 2430 PA.Commit(); 2431 return true; 2432 } 2433 2434 /// ParseCXXTryBlock - Parse a C++ try-block. 2435 /// 2436 /// try-block: 2437 /// 'try' compound-statement handler-seq 2438 /// 2439 StmtResult Parser::ParseCXXTryBlock() { 2440 assert(Tok.is(tok::kw_try) && "Expected 'try'"); 2441 2442 SourceLocation TryLoc = ConsumeToken(); 2443 return ParseCXXTryBlockCommon(TryLoc); 2444 } 2445 2446 /// ParseCXXTryBlockCommon - Parse the common part of try-block and 2447 /// function-try-block. 2448 /// 2449 /// try-block: 2450 /// 'try' compound-statement handler-seq 2451 /// 2452 /// function-try-block: 2453 /// 'try' ctor-initializer[opt] compound-statement handler-seq 2454 /// 2455 /// handler-seq: 2456 /// handler handler-seq[opt] 2457 /// 2458 /// [Borland] try-block: 2459 /// 'try' compound-statement seh-except-block 2460 /// 'try' compound-statement seh-finally-block 2461 /// 2462 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) { 2463 if (Tok.isNot(tok::l_brace)) 2464 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace); 2465 2466 StmtResult TryBlock(ParseCompoundStatement( 2467 /*isStmtExpr=*/false, Scope::DeclScope | Scope::TryScope | 2468 Scope::CompoundStmtScope | 2469 (FnTry ? Scope::FnTryCatchScope : 0))); 2470 if (TryBlock.isInvalid()) 2471 return TryBlock; 2472 2473 // Borland allows SEH-handlers with 'try' 2474 2475 if ((Tok.is(tok::identifier) && 2476 Tok.getIdentifierInfo() == getSEHExceptKeyword()) || 2477 Tok.is(tok::kw___finally)) { 2478 // TODO: Factor into common return ParseSEHHandlerCommon(...) 2479 StmtResult Handler; 2480 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) { 2481 SourceLocation Loc = ConsumeToken(); 2482 Handler = ParseSEHExceptBlock(Loc); 2483 } 2484 else { 2485 SourceLocation Loc = ConsumeToken(); 2486 Handler = ParseSEHFinallyBlock(Loc); 2487 } 2488 if(Handler.isInvalid()) 2489 return Handler; 2490 2491 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */, 2492 TryLoc, 2493 TryBlock.get(), 2494 Handler.get()); 2495 } 2496 else { 2497 StmtVector Handlers; 2498 2499 // C++11 attributes can't appear here, despite this context seeming 2500 // statement-like. 2501 DiagnoseAndSkipCXX11Attributes(); 2502 2503 if (Tok.isNot(tok::kw_catch)) 2504 return StmtError(Diag(Tok, diag::err_expected_catch)); 2505 while (Tok.is(tok::kw_catch)) { 2506 StmtResult Handler(ParseCXXCatchBlock(FnTry)); 2507 if (!Handler.isInvalid()) 2508 Handlers.push_back(Handler.get()); 2509 } 2510 // Don't bother creating the full statement if we don't have any usable 2511 // handlers. 2512 if (Handlers.empty()) 2513 return StmtError(); 2514 2515 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers); 2516 } 2517 } 2518 2519 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard 2520 /// 2521 /// handler: 2522 /// 'catch' '(' exception-declaration ')' compound-statement 2523 /// 2524 /// exception-declaration: 2525 /// attribute-specifier-seq[opt] type-specifier-seq declarator 2526 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt] 2527 /// '...' 2528 /// 2529 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) { 2530 assert(Tok.is(tok::kw_catch) && "Expected 'catch'"); 2531 2532 SourceLocation CatchLoc = ConsumeToken(); 2533 2534 BalancedDelimiterTracker T(*this, tok::l_paren); 2535 if (T.expectAndConsume()) 2536 return StmtError(); 2537 2538 // C++ 3.3.2p3: 2539 // The name in a catch exception-declaration is local to the handler and 2540 // shall not be redeclared in the outermost block of the handler. 2541 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope | 2542 Scope::CatchScope | 2543 (FnCatch ? Scope::FnTryCatchScope : 0)); 2544 2545 // exception-declaration is equivalent to '...' or a parameter-declaration 2546 // without default arguments. 2547 Decl *ExceptionDecl = nullptr; 2548 if (Tok.isNot(tok::ellipsis)) { 2549 ParsedAttributesWithRange Attributes(AttrFactory); 2550 MaybeParseCXX11Attributes(Attributes); 2551 2552 DeclSpec DS(AttrFactory); 2553 DS.takeAttributesFrom(Attributes); 2554 2555 if (ParseCXXTypeSpecifierSeq(DS)) 2556 return StmtError(); 2557 2558 Declarator ExDecl(DS, DeclaratorContext::CXXCatch); 2559 ParseDeclarator(ExDecl); 2560 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl); 2561 } else 2562 ConsumeToken(); 2563 2564 T.consumeClose(); 2565 if (T.getCloseLocation().isInvalid()) 2566 return StmtError(); 2567 2568 if (Tok.isNot(tok::l_brace)) 2569 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace); 2570 2571 // FIXME: Possible draft standard bug: attribute-specifier should be allowed? 2572 StmtResult Block(ParseCompoundStatement()); 2573 if (Block.isInvalid()) 2574 return Block; 2575 2576 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get()); 2577 } 2578 2579 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) { 2580 IfExistsCondition Result; 2581 if (ParseMicrosoftIfExistsCondition(Result)) 2582 return; 2583 2584 // Handle dependent statements by parsing the braces as a compound statement. 2585 // This is not the same behavior as Visual C++, which don't treat this as a 2586 // compound statement, but for Clang's type checking we can't have anything 2587 // inside these braces escaping to the surrounding code. 2588 if (Result.Behavior == IEB_Dependent) { 2589 if (!Tok.is(tok::l_brace)) { 2590 Diag(Tok, diag::err_expected) << tok::l_brace; 2591 return; 2592 } 2593 2594 StmtResult Compound = ParseCompoundStatement(); 2595 if (Compound.isInvalid()) 2596 return; 2597 2598 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc, 2599 Result.IsIfExists, 2600 Result.SS, 2601 Result.Name, 2602 Compound.get()); 2603 if (DepResult.isUsable()) 2604 Stmts.push_back(DepResult.get()); 2605 return; 2606 } 2607 2608 BalancedDelimiterTracker Braces(*this, tok::l_brace); 2609 if (Braces.consumeOpen()) { 2610 Diag(Tok, diag::err_expected) << tok::l_brace; 2611 return; 2612 } 2613 2614 switch (Result.Behavior) { 2615 case IEB_Parse: 2616 // Parse the statements below. 2617 break; 2618 2619 case IEB_Dependent: 2620 llvm_unreachable("Dependent case handled above"); 2621 2622 case IEB_Skip: 2623 Braces.skipToEnd(); 2624 return; 2625 } 2626 2627 // Condition is true, parse the statements. 2628 while (Tok.isNot(tok::r_brace)) { 2629 StmtResult R = 2630 ParseStatementOrDeclaration(Stmts, ParsedStmtContext::Compound); 2631 if (R.isUsable()) 2632 Stmts.push_back(R.get()); 2633 } 2634 Braces.consumeClose(); 2635 } 2636