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