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