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