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