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