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