Path: blob/main/contrib/llvm-project/clang/lib/Parse/ParseStmt.cpp
35233 views
//===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the Statement and Block portions of the Parser9// interface.10//11//===----------------------------------------------------------------------===//1213#include "clang/AST/PrettyDeclStackTrace.h"14#include "clang/Basic/Attributes.h"15#include "clang/Basic/PrettyStackTrace.h"16#include "clang/Basic/TargetInfo.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/SemaCodeCompletion.h"25#include "clang/Sema/SemaObjC.h"26#include "clang/Sema/SemaOpenMP.h"27#include "clang/Sema/TypoCorrection.h"28#include "llvm/ADT/STLExtras.h"29#include <optional>3031using namespace clang;3233//===----------------------------------------------------------------------===//34// C99 6.8: Statements and Blocks.35//===----------------------------------------------------------------------===//3637/// Parse a standalone statement (for instance, as the body of an 'if',38/// 'while', or 'for').39StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc,40ParsedStmtContext StmtCtx) {41StmtResult Res;4243// We may get back a null statement if we found a #pragma. Keep going until44// we get an actual statement.45StmtVector Stmts;46do {47Res = ParseStatementOrDeclaration(Stmts, StmtCtx, TrailingElseLoc);48} while (!Res.isInvalid() && !Res.get());4950return Res;51}5253/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.54/// StatementOrDeclaration:55/// statement56/// declaration57///58/// statement:59/// labeled-statement60/// compound-statement61/// expression-statement62/// selection-statement63/// iteration-statement64/// jump-statement65/// [C++] declaration-statement66/// [C++] try-block67/// [MS] seh-try-block68/// [OBC] objc-throw-statement69/// [OBC] objc-try-catch-statement70/// [OBC] objc-synchronized-statement71/// [GNU] asm-statement72/// [OMP] openmp-construct [TODO]73///74/// labeled-statement:75/// identifier ':' statement76/// 'case' constant-expression ':' statement77/// 'default' ':' statement78///79/// selection-statement:80/// if-statement81/// switch-statement82///83/// iteration-statement:84/// while-statement85/// do-statement86/// for-statement87///88/// expression-statement:89/// expression[opt] ';'90///91/// jump-statement:92/// 'goto' identifier ';'93/// 'continue' ';'94/// 'break' ';'95/// 'return' expression[opt] ';'96/// [GNU] 'goto' '*' expression ';'97///98/// [OBC] objc-throw-statement:99/// [OBC] '@' 'throw' expression ';'100/// [OBC] '@' 'throw' ';'101///102StmtResult103Parser::ParseStatementOrDeclaration(StmtVector &Stmts,104ParsedStmtContext StmtCtx,105SourceLocation *TrailingElseLoc) {106107ParenBraceBracketBalancer BalancerRAIIObj(*this);108109// Because we're parsing either a statement or a declaration, the order of110// attribute parsing is important. [[]] attributes at the start of a111// statement are different from [[]] attributes that follow an __attribute__112// at the start of the statement. Thus, we're not using MaybeParseAttributes113// here because we don't want to allow arbitrary orderings.114ParsedAttributes CXX11Attrs(AttrFactory);115MaybeParseCXX11Attributes(CXX11Attrs, /*MightBeObjCMessageSend*/ true);116ParsedAttributes GNUOrMSAttrs(AttrFactory);117if (getLangOpts().OpenCL)118MaybeParseGNUAttributes(GNUOrMSAttrs);119120if (getLangOpts().HLSL)121MaybeParseMicrosoftAttributes(GNUOrMSAttrs);122123StmtResult Res = ParseStatementOrDeclarationAfterAttributes(124Stmts, StmtCtx, TrailingElseLoc, CXX11Attrs, GNUOrMSAttrs);125MaybeDestroyTemplateIds();126127// Attributes that are left should all go on the statement, so concatenate the128// two lists.129ParsedAttributes Attrs(AttrFactory);130takeAndConcatenateAttrs(CXX11Attrs, GNUOrMSAttrs, Attrs);131132assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&133"attributes on empty statement");134135if (Attrs.empty() || Res.isInvalid())136return Res;137138return Actions.ActOnAttributedStmt(Attrs, Res.get());139}140141namespace {142class StatementFilterCCC final : public CorrectionCandidateCallback {143public:144StatementFilterCCC(Token nextTok) : NextToken(nextTok) {145WantTypeSpecifiers = nextTok.isOneOf(tok::l_paren, tok::less, tok::l_square,146tok::identifier, tok::star, tok::amp);147WantExpressionKeywords =148nextTok.isOneOf(tok::l_paren, tok::identifier, tok::arrow, tok::period);149WantRemainingKeywords =150nextTok.isOneOf(tok::l_paren, tok::semi, tok::identifier, tok::l_brace);151WantCXXNamedCasts = false;152}153154bool ValidateCandidate(const TypoCorrection &candidate) override {155if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())156return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);157if (NextToken.is(tok::equal))158return candidate.getCorrectionDeclAs<VarDecl>();159if (NextToken.is(tok::period) &&160candidate.getCorrectionDeclAs<NamespaceDecl>())161return false;162return CorrectionCandidateCallback::ValidateCandidate(candidate);163}164165std::unique_ptr<CorrectionCandidateCallback> clone() override {166return std::make_unique<StatementFilterCCC>(*this);167}168169private:170Token NextToken;171};172}173174StmtResult Parser::ParseStatementOrDeclarationAfterAttributes(175StmtVector &Stmts, ParsedStmtContext StmtCtx,176SourceLocation *TrailingElseLoc, ParsedAttributes &CXX11Attrs,177ParsedAttributes &GNUAttrs) {178const char *SemiError = nullptr;179StmtResult Res;180SourceLocation GNUAttributeLoc;181182// Cases in this switch statement should fall through if the parser expects183// the token to end in a semicolon (in which case SemiError should be set),184// or they directly 'return;' if not.185Retry:186tok::TokenKind Kind = Tok.getKind();187SourceLocation AtLoc;188switch (Kind) {189case tok::at: // May be a @try or @throw statement190{191AtLoc = ConsumeToken(); // consume @192return ParseObjCAtStatement(AtLoc, StmtCtx);193}194195case tok::code_completion:196cutOffParsing();197Actions.CodeCompletion().CodeCompleteOrdinaryName(198getCurScope(), SemaCodeCompletion::PCC_Statement);199return StmtError();200201case tok::identifier:202ParseIdentifier: {203Token Next = NextToken();204if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement205// Both C++11 and GNU attributes preceding the label appertain to the206// label, so put them in a single list to pass on to207// ParseLabeledStatement().208ParsedAttributes Attrs(AttrFactory);209takeAndConcatenateAttrs(CXX11Attrs, GNUAttrs, Attrs);210211// identifier ':' statement212return ParseLabeledStatement(Attrs, StmtCtx);213}214215// Look up the identifier, and typo-correct it to a keyword if it's not216// found.217if (Next.isNot(tok::coloncolon)) {218// Try to limit which sets of keywords should be included in typo219// correction based on what the next token is.220StatementFilterCCC CCC(Next);221if (TryAnnotateName(&CCC) == ANK_Error) {222// Handle errors here by skipping up to the next semicolon or '}', and223// eat the semicolon if that's what stopped us.224SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);225if (Tok.is(tok::semi))226ConsumeToken();227return StmtError();228}229230// If the identifier was typo-corrected, try again.231if (Tok.isNot(tok::identifier))232goto Retry;233}234235// Fall through236[[fallthrough]];237}238239default: {240bool HaveAttrs = !CXX11Attrs.empty() || !GNUAttrs.empty();241auto IsStmtAttr = [](ParsedAttr &Attr) { return Attr.isStmtAttr(); };242bool AllAttrsAreStmtAttrs = llvm::all_of(CXX11Attrs, IsStmtAttr) &&243llvm::all_of(GNUAttrs, IsStmtAttr);244// In C, the grammar production for statement (C23 6.8.1p1) does not allow245// for declarations, which is different from C++ (C++23 [stmt.pre]p1). So246// in C++, we always allow a declaration, but in C we need to check whether247// we're in a statement context that allows declarations. e.g., in C, the248// following is invalid: if (1) int x;249if ((getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt ||250(StmtCtx & ParsedStmtContext::AllowDeclarationsInC) !=251ParsedStmtContext()) &&252((GNUAttributeLoc.isValid() && !(HaveAttrs && AllAttrsAreStmtAttrs)) ||253isDeclarationStatement())) {254SourceLocation DeclStart = Tok.getLocation(), DeclEnd;255DeclGroupPtrTy Decl;256if (GNUAttributeLoc.isValid()) {257DeclStart = GNUAttributeLoc;258Decl = ParseDeclaration(DeclaratorContext::Block, DeclEnd, CXX11Attrs,259GNUAttrs, &GNUAttributeLoc);260} else {261Decl = ParseDeclaration(DeclaratorContext::Block, DeclEnd, CXX11Attrs,262GNUAttrs);263}264if (CXX11Attrs.Range.getBegin().isValid()) {265// The caller must guarantee that the CXX11Attrs appear before the266// GNUAttrs, and we rely on that here.267assert(GNUAttrs.Range.getBegin().isInvalid() ||268GNUAttrs.Range.getBegin() > CXX11Attrs.Range.getBegin());269DeclStart = CXX11Attrs.Range.getBegin();270} else if (GNUAttrs.Range.getBegin().isValid())271DeclStart = GNUAttrs.Range.getBegin();272return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);273}274275if (Tok.is(tok::r_brace)) {276Diag(Tok, diag::err_expected_statement);277return StmtError();278}279280switch (Tok.getKind()) {281#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:282#include "clang/Basic/TransformTypeTraits.def"283if (NextToken().is(tok::less)) {284Tok.setKind(tok::identifier);285Diag(Tok, diag::ext_keyword_as_ident)286<< Tok.getIdentifierInfo()->getName() << 0;287goto ParseIdentifier;288}289[[fallthrough]];290default:291return ParseExprStatement(StmtCtx);292}293}294295case tok::kw___attribute: {296GNUAttributeLoc = Tok.getLocation();297ParseGNUAttributes(GNUAttrs);298goto Retry;299}300301case tok::kw_case: // C99 6.8.1: labeled-statement302return ParseCaseStatement(StmtCtx);303case tok::kw_default: // C99 6.8.1: labeled-statement304return ParseDefaultStatement(StmtCtx);305306case tok::l_brace: // C99 6.8.2: compound-statement307return ParseCompoundStatement();308case tok::semi: { // C99 6.8.3p3: expression[opt] ';'309bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();310return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);311}312313case tok::kw_if: // C99 6.8.4.1: if-statement314return ParseIfStatement(TrailingElseLoc);315case tok::kw_switch: // C99 6.8.4.2: switch-statement316return ParseSwitchStatement(TrailingElseLoc);317318case tok::kw_while: // C99 6.8.5.1: while-statement319return ParseWhileStatement(TrailingElseLoc);320case tok::kw_do: // C99 6.8.5.2: do-statement321Res = ParseDoStatement();322SemiError = "do/while";323break;324case tok::kw_for: // C99 6.8.5.3: for-statement325return ParseForStatement(TrailingElseLoc);326327case tok::kw_goto: // C99 6.8.6.1: goto-statement328Res = ParseGotoStatement();329SemiError = "goto";330break;331case tok::kw_continue: // C99 6.8.6.2: continue-statement332Res = ParseContinueStatement();333SemiError = "continue";334break;335case tok::kw_break: // C99 6.8.6.3: break-statement336Res = ParseBreakStatement();337SemiError = "break";338break;339case tok::kw_return: // C99 6.8.6.4: return-statement340Res = ParseReturnStatement();341SemiError = "return";342break;343case tok::kw_co_return: // C++ Coroutines: co_return statement344Res = ParseReturnStatement();345SemiError = "co_return";346break;347348case tok::kw_asm: {349for (const ParsedAttr &AL : CXX11Attrs)350// Could be relaxed if asm-related regular keyword attributes are351// added later.352(AL.isRegularKeywordAttribute()353? Diag(AL.getRange().getBegin(), diag::err_keyword_not_allowed)354: Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored))355<< AL;356// Prevent these from being interpreted as statement attributes later on.357CXX11Attrs.clear();358ProhibitAttributes(GNUAttrs);359bool msAsm = false;360Res = ParseAsmStatement(msAsm);361if (msAsm) return Res;362SemiError = "asm";363break;364}365366case tok::kw___if_exists:367case tok::kw___if_not_exists:368ProhibitAttributes(CXX11Attrs);369ProhibitAttributes(GNUAttrs);370ParseMicrosoftIfExistsStatement(Stmts);371// An __if_exists block is like a compound statement, but it doesn't create372// a new scope.373return StmtEmpty();374375case tok::kw_try: // C++ 15: try-block376return ParseCXXTryBlock();377378case tok::kw___try:379ProhibitAttributes(CXX11Attrs);380ProhibitAttributes(GNUAttrs);381return ParseSEHTryBlock();382383case tok::kw___leave:384Res = ParseSEHLeaveStatement();385SemiError = "__leave";386break;387388case tok::annot_pragma_vis:389ProhibitAttributes(CXX11Attrs);390ProhibitAttributes(GNUAttrs);391HandlePragmaVisibility();392return StmtEmpty();393394case tok::annot_pragma_pack:395ProhibitAttributes(CXX11Attrs);396ProhibitAttributes(GNUAttrs);397HandlePragmaPack();398return StmtEmpty();399400case tok::annot_pragma_msstruct:401ProhibitAttributes(CXX11Attrs);402ProhibitAttributes(GNUAttrs);403HandlePragmaMSStruct();404return StmtEmpty();405406case tok::annot_pragma_align:407ProhibitAttributes(CXX11Attrs);408ProhibitAttributes(GNUAttrs);409HandlePragmaAlign();410return StmtEmpty();411412case tok::annot_pragma_weak:413ProhibitAttributes(CXX11Attrs);414ProhibitAttributes(GNUAttrs);415HandlePragmaWeak();416return StmtEmpty();417418case tok::annot_pragma_weakalias:419ProhibitAttributes(CXX11Attrs);420ProhibitAttributes(GNUAttrs);421HandlePragmaWeakAlias();422return StmtEmpty();423424case tok::annot_pragma_redefine_extname:425ProhibitAttributes(CXX11Attrs);426ProhibitAttributes(GNUAttrs);427HandlePragmaRedefineExtname();428return StmtEmpty();429430case tok::annot_pragma_fp_contract:431ProhibitAttributes(CXX11Attrs);432ProhibitAttributes(GNUAttrs);433Diag(Tok, diag::err_pragma_file_or_compound_scope) << "fp_contract";434ConsumeAnnotationToken();435return StmtError();436437case tok::annot_pragma_fp:438ProhibitAttributes(CXX11Attrs);439ProhibitAttributes(GNUAttrs);440Diag(Tok, diag::err_pragma_file_or_compound_scope) << "clang fp";441ConsumeAnnotationToken();442return StmtError();443444case tok::annot_pragma_fenv_access:445case tok::annot_pragma_fenv_access_ms:446ProhibitAttributes(CXX11Attrs);447ProhibitAttributes(GNUAttrs);448Diag(Tok, diag::err_pragma_file_or_compound_scope)449<< (Kind == tok::annot_pragma_fenv_access ? "STDC FENV_ACCESS"450: "fenv_access");451ConsumeAnnotationToken();452return StmtEmpty();453454case tok::annot_pragma_fenv_round:455ProhibitAttributes(CXX11Attrs);456ProhibitAttributes(GNUAttrs);457Diag(Tok, diag::err_pragma_file_or_compound_scope) << "STDC FENV_ROUND";458ConsumeAnnotationToken();459return StmtError();460461case tok::annot_pragma_cx_limited_range:462ProhibitAttributes(CXX11Attrs);463ProhibitAttributes(GNUAttrs);464Diag(Tok, diag::err_pragma_file_or_compound_scope)465<< "STDC CX_LIMITED_RANGE";466ConsumeAnnotationToken();467return StmtError();468469case tok::annot_pragma_float_control:470ProhibitAttributes(CXX11Attrs);471ProhibitAttributes(GNUAttrs);472Diag(Tok, diag::err_pragma_file_or_compound_scope) << "float_control";473ConsumeAnnotationToken();474return StmtError();475476case tok::annot_pragma_opencl_extension:477ProhibitAttributes(CXX11Attrs);478ProhibitAttributes(GNUAttrs);479HandlePragmaOpenCLExtension();480return StmtEmpty();481482case tok::annot_pragma_captured:483ProhibitAttributes(CXX11Attrs);484ProhibitAttributes(GNUAttrs);485return HandlePragmaCaptured();486487case tok::annot_pragma_openmp:488// Prohibit attributes that are not OpenMP attributes, but only before489// processing a #pragma omp clause.490ProhibitAttributes(CXX11Attrs);491ProhibitAttributes(GNUAttrs);492[[fallthrough]];493case tok::annot_attr_openmp:494// Do not prohibit attributes if they were OpenMP attributes.495return ParseOpenMPDeclarativeOrExecutableDirective(StmtCtx);496497case tok::annot_pragma_openacc:498return ParseOpenACCDirectiveStmt();499500case tok::annot_pragma_ms_pointers_to_members:501ProhibitAttributes(CXX11Attrs);502ProhibitAttributes(GNUAttrs);503HandlePragmaMSPointersToMembers();504return StmtEmpty();505506case tok::annot_pragma_ms_pragma:507ProhibitAttributes(CXX11Attrs);508ProhibitAttributes(GNUAttrs);509HandlePragmaMSPragma();510return StmtEmpty();511512case tok::annot_pragma_ms_vtordisp:513ProhibitAttributes(CXX11Attrs);514ProhibitAttributes(GNUAttrs);515HandlePragmaMSVtorDisp();516return StmtEmpty();517518case tok::annot_pragma_loop_hint:519ProhibitAttributes(CXX11Attrs);520ProhibitAttributes(GNUAttrs);521return ParsePragmaLoopHint(Stmts, StmtCtx, TrailingElseLoc, CXX11Attrs);522523case tok::annot_pragma_dump:524HandlePragmaDump();525return StmtEmpty();526527case tok::annot_pragma_attribute:528HandlePragmaAttribute();529return StmtEmpty();530}531532// If we reached this code, the statement must end in a semicolon.533if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {534// If the result was valid, then we do want to diagnose this. Use535// ExpectAndConsume to emit the diagnostic, even though we know it won't536// succeed.537ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);538// Skip until we see a } or ;, but don't eat it.539SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);540}541542return Res;543}544545/// Parse an expression statement.546StmtResult Parser::ParseExprStatement(ParsedStmtContext StmtCtx) {547// If a case keyword is missing, this is where it should be inserted.548Token OldToken = Tok;549550ExprStatementTokLoc = Tok.getLocation();551552// expression[opt] ';'553ExprResult Expr(ParseExpression());554if (Expr.isInvalid()) {555// If the expression is invalid, skip ahead to the next semicolon or '}'.556// Not doing this opens us up to the possibility of infinite loops if557// ParseExpression does not consume any tokens.558SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);559if (Tok.is(tok::semi))560ConsumeToken();561return Actions.ActOnExprStmtError();562}563564if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&565Actions.CheckCaseExpression(Expr.get())) {566// If a constant expression is followed by a colon inside a switch block,567// suggest a missing case keyword.568Diag(OldToken, diag::err_expected_case_before_expression)569<< FixItHint::CreateInsertion(OldToken.getLocation(), "case ");570571// Recover parsing as a case statement.572return ParseCaseStatement(StmtCtx, /*MissingCase=*/true, Expr);573}574575Token *CurTok = nullptr;576// Note we shouldn't eat the token since the callback needs it.577if (Tok.is(tok::annot_repl_input_end))578CurTok = &Tok;579else580// Otherwise, eat the semicolon.581ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);582583StmtResult R = handleExprStmt(Expr, StmtCtx);584if (CurTok && !R.isInvalid())585CurTok->setAnnotationValue(R.get());586587return R;588}589590/// ParseSEHTryBlockCommon591///592/// seh-try-block:593/// '__try' compound-statement seh-handler594///595/// seh-handler:596/// seh-except-block597/// seh-finally-block598///599StmtResult Parser::ParseSEHTryBlock() {600assert(Tok.is(tok::kw___try) && "Expected '__try'");601SourceLocation TryLoc = ConsumeToken();602603if (Tok.isNot(tok::l_brace))604return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);605606StmtResult TryBlock(ParseCompoundStatement(607/*isStmtExpr=*/false,608Scope::DeclScope | Scope::CompoundStmtScope | Scope::SEHTryScope));609if (TryBlock.isInvalid())610return TryBlock;611612StmtResult Handler;613if (Tok.is(tok::identifier) &&614Tok.getIdentifierInfo() == getSEHExceptKeyword()) {615SourceLocation Loc = ConsumeToken();616Handler = ParseSEHExceptBlock(Loc);617} else if (Tok.is(tok::kw___finally)) {618SourceLocation Loc = ConsumeToken();619Handler = ParseSEHFinallyBlock(Loc);620} else {621return StmtError(Diag(Tok, diag::err_seh_expected_handler));622}623624if(Handler.isInvalid())625return Handler;626627return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,628TryLoc,629TryBlock.get(),630Handler.get());631}632633/// ParseSEHExceptBlock - Handle __except634///635/// seh-except-block:636/// '__except' '(' seh-filter-expression ')' compound-statement637///638StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {639PoisonIdentifierRAIIObject raii(Ident__exception_code, false),640raii2(Ident___exception_code, false),641raii3(Ident_GetExceptionCode, false);642643if (ExpectAndConsume(tok::l_paren))644return StmtError();645646ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |647Scope::SEHExceptScope);648649if (getLangOpts().Borland) {650Ident__exception_info->setIsPoisoned(false);651Ident___exception_info->setIsPoisoned(false);652Ident_GetExceptionInfo->setIsPoisoned(false);653}654655ExprResult FilterExpr;656{657ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |658Scope::SEHFilterScope);659FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());660}661662if (getLangOpts().Borland) {663Ident__exception_info->setIsPoisoned(true);664Ident___exception_info->setIsPoisoned(true);665Ident_GetExceptionInfo->setIsPoisoned(true);666}667668if(FilterExpr.isInvalid())669return StmtError();670671if (ExpectAndConsume(tok::r_paren))672return StmtError();673674if (Tok.isNot(tok::l_brace))675return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);676677StmtResult Block(ParseCompoundStatement());678679if(Block.isInvalid())680return Block;681682return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());683}684685/// ParseSEHFinallyBlock - Handle __finally686///687/// seh-finally-block:688/// '__finally' compound-statement689///690StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {691PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),692raii2(Ident___abnormal_termination, false),693raii3(Ident_AbnormalTermination, false);694695if (Tok.isNot(tok::l_brace))696return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);697698ParseScope FinallyScope(this, 0);699Actions.ActOnStartSEHFinallyBlock();700701StmtResult Block(ParseCompoundStatement());702if(Block.isInvalid()) {703Actions.ActOnAbortSEHFinallyBlock();704return Block;705}706707return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());708}709710/// Handle __leave711///712/// seh-leave-statement:713/// '__leave' ';'714///715StmtResult Parser::ParseSEHLeaveStatement() {716SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.717return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());718}719720static void DiagnoseLabelFollowedByDecl(Parser &P, const Stmt *SubStmt) {721// When in C mode (but not Microsoft extensions mode), diagnose use of a722// label that is followed by a declaration rather than a statement.723if (!P.getLangOpts().CPlusPlus && !P.getLangOpts().MicrosoftExt &&724isa<DeclStmt>(SubStmt)) {725P.Diag(SubStmt->getBeginLoc(),726P.getLangOpts().C23727? diag::warn_c23_compat_label_followed_by_declaration728: diag::ext_c_label_followed_by_declaration);729}730}731732/// ParseLabeledStatement - We have an identifier and a ':' after it.733///734/// label:735/// identifier ':'736/// [GNU] identifier ':' attributes[opt]737///738/// labeled-statement:739/// label statement740///741StmtResult Parser::ParseLabeledStatement(ParsedAttributes &Attrs,742ParsedStmtContext StmtCtx) {743assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&744"Not an identifier!");745746// [OpenMP 5.1] 2.1.3: A stand-alone directive may not be used in place of a747// substatement in a selection statement, in place of the loop body in an748// iteration statement, or in place of the statement that follows a label.749StmtCtx &= ~ParsedStmtContext::AllowStandaloneOpenMPDirectives;750751Token IdentTok = Tok; // Save the whole token.752ConsumeToken(); // eat the identifier.753754assert(Tok.is(tok::colon) && "Not a label!");755756// identifier ':' statement757SourceLocation ColonLoc = ConsumeToken();758759// Read label attributes, if present.760StmtResult SubStmt;761if (Tok.is(tok::kw___attribute)) {762ParsedAttributes TempAttrs(AttrFactory);763ParseGNUAttributes(TempAttrs);764765// In C++, GNU attributes only apply to the label if they are followed by a766// semicolon, to disambiguate label attributes from attributes on a labeled767// declaration.768//769// This doesn't quite match what GCC does; if the attribute list is empty770// and followed by a semicolon, GCC will reject (it appears to parse the771// attributes as part of a statement in that case). That looks like a bug.772if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))773Attrs.takeAllFrom(TempAttrs);774else {775StmtVector Stmts;776ParsedAttributes EmptyCXX11Attrs(AttrFactory);777SubStmt = ParseStatementOrDeclarationAfterAttributes(778Stmts, StmtCtx, nullptr, EmptyCXX11Attrs, TempAttrs);779if (!TempAttrs.empty() && !SubStmt.isInvalid())780SubStmt = Actions.ActOnAttributedStmt(TempAttrs, SubStmt.get());781}782}783784// The label may have no statement following it785if (SubStmt.isUnset() && Tok.is(tok::r_brace)) {786DiagnoseLabelAtEndOfCompoundStatement();787SubStmt = Actions.ActOnNullStmt(ColonLoc);788}789790// If we've not parsed a statement yet, parse one now.791if (!SubStmt.isInvalid() && !SubStmt.isUsable())792SubStmt = ParseStatement(nullptr, StmtCtx);793794// Broken substmt shouldn't prevent the label from being added to the AST.795if (SubStmt.isInvalid())796SubStmt = Actions.ActOnNullStmt(ColonLoc);797798DiagnoseLabelFollowedByDecl(*this, SubStmt.get());799800LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),801IdentTok.getLocation());802Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);803Attrs.clear();804805return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,806SubStmt.get());807}808809/// ParseCaseStatement810/// labeled-statement:811/// 'case' constant-expression ':' statement812/// [GNU] 'case' constant-expression '...' constant-expression ':' statement813///814StmtResult Parser::ParseCaseStatement(ParsedStmtContext StmtCtx,815bool MissingCase, ExprResult Expr) {816assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");817818// [OpenMP 5.1] 2.1.3: A stand-alone directive may not be used in place of a819// substatement in a selection statement, in place of the loop body in an820// iteration statement, or in place of the statement that follows a label.821StmtCtx &= ~ParsedStmtContext::AllowStandaloneOpenMPDirectives;822823// It is very common for code to contain many case statements recursively824// nested, as in (but usually without indentation):825// case 1:826// case 2:827// case 3:828// case 4:829// case 5: etc.830//831// Parsing this naively works, but is both inefficient and can cause us to run832// out of stack space in our recursive descent parser. As a special case,833// flatten this recursion into an iterative loop. This is complex and gross,834// but all the grossness is constrained to ParseCaseStatement (and some835// weirdness in the actions), so this is just local grossness :).836837// TopLevelCase - This is the highest level we have parsed. 'case 1' in the838// example above.839StmtResult TopLevelCase(true);840841// DeepestParsedCaseStmt - This is the deepest statement we have parsed, which842// gets updated each time a new case is parsed, and whose body is unset so843// far. When parsing 'case 4', this is the 'case 3' node.844Stmt *DeepestParsedCaseStmt = nullptr;845846// While we have case statements, eat and stack them.847SourceLocation ColonLoc;848do {849SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :850ConsumeToken(); // eat the 'case'.851ColonLoc = SourceLocation();852853if (Tok.is(tok::code_completion)) {854cutOffParsing();855Actions.CodeCompletion().CodeCompleteCase(getCurScope());856return StmtError();857}858859/// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.860/// Disable this form of error recovery while we're parsing the case861/// expression.862ColonProtectionRAIIObject ColonProtection(*this);863864ExprResult LHS;865if (!MissingCase) {866LHS = ParseCaseExpression(CaseLoc);867if (LHS.isInvalid()) {868// If constant-expression is parsed unsuccessfully, recover by skipping869// current case statement (moving to the colon that ends it).870if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))871return StmtError();872}873} else {874LHS = Expr;875MissingCase = false;876}877878// GNU case range extension.879SourceLocation DotDotDotLoc;880ExprResult RHS;881if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {882Diag(DotDotDotLoc, diag::ext_gnu_case_range);883RHS = ParseCaseExpression(CaseLoc);884if (RHS.isInvalid()) {885if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))886return StmtError();887}888}889890ColonProtection.restore();891892if (TryConsumeToken(tok::colon, ColonLoc)) {893} else if (TryConsumeToken(tok::semi, ColonLoc) ||894TryConsumeToken(tok::coloncolon, ColonLoc)) {895// Treat "case blah;" or "case blah::" as a typo for "case blah:".896Diag(ColonLoc, diag::err_expected_after)897<< "'case'" << tok::colon898<< FixItHint::CreateReplacement(ColonLoc, ":");899} else {900SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);901Diag(ExpectedLoc, diag::err_expected_after)902<< "'case'" << tok::colon903<< FixItHint::CreateInsertion(ExpectedLoc, ":");904ColonLoc = ExpectedLoc;905}906907StmtResult Case =908Actions.ActOnCaseStmt(CaseLoc, LHS, DotDotDotLoc, RHS, ColonLoc);909910// If we had a sema error parsing this case, then just ignore it and911// continue parsing the sub-stmt.912if (Case.isInvalid()) {913if (TopLevelCase.isInvalid()) // No parsed case stmts.914return ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);915// Otherwise, just don't add it as a nested case.916} else {917// If this is the first case statement we parsed, it becomes TopLevelCase.918// Otherwise we link it into the current chain.919Stmt *NextDeepest = Case.get();920if (TopLevelCase.isInvalid())921TopLevelCase = Case;922else923Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());924DeepestParsedCaseStmt = NextDeepest;925}926927// Handle all case statements.928} while (Tok.is(tok::kw_case));929930// If we found a non-case statement, start by parsing it.931StmtResult SubStmt;932933if (Tok.is(tok::r_brace)) {934// "switch (X) { case 4: }", is valid and is treated as if label was935// followed by a null statement.936DiagnoseLabelAtEndOfCompoundStatement();937SubStmt = Actions.ActOnNullStmt(ColonLoc);938} else {939SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);940}941942// Install the body into the most deeply-nested case.943if (DeepestParsedCaseStmt) {944// Broken sub-stmt shouldn't prevent forming the case statement properly.945if (SubStmt.isInvalid())946SubStmt = Actions.ActOnNullStmt(SourceLocation());947DiagnoseLabelFollowedByDecl(*this, SubStmt.get());948Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());949}950951// Return the top level parsed statement tree.952return TopLevelCase;953}954955/// ParseDefaultStatement956/// labeled-statement:957/// 'default' ':' statement958/// Note that this does not parse the 'statement' at the end.959///960StmtResult Parser::ParseDefaultStatement(ParsedStmtContext StmtCtx) {961assert(Tok.is(tok::kw_default) && "Not a default stmt!");962963// [OpenMP 5.1] 2.1.3: A stand-alone directive may not be used in place of a964// substatement in a selection statement, in place of the loop body in an965// iteration statement, or in place of the statement that follows a label.966StmtCtx &= ~ParsedStmtContext::AllowStandaloneOpenMPDirectives;967968SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.969970SourceLocation ColonLoc;971if (TryConsumeToken(tok::colon, ColonLoc)) {972} else if (TryConsumeToken(tok::semi, ColonLoc)) {973// Treat "default;" as a typo for "default:".974Diag(ColonLoc, diag::err_expected_after)975<< "'default'" << tok::colon976<< FixItHint::CreateReplacement(ColonLoc, ":");977} else {978SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);979Diag(ExpectedLoc, diag::err_expected_after)980<< "'default'" << tok::colon981<< FixItHint::CreateInsertion(ExpectedLoc, ":");982ColonLoc = ExpectedLoc;983}984985StmtResult SubStmt;986987if (Tok.is(tok::r_brace)) {988// "switch (X) {... default: }", is valid and is treated as if label was989// followed by a null statement.990DiagnoseLabelAtEndOfCompoundStatement();991SubStmt = Actions.ActOnNullStmt(ColonLoc);992} else {993SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);994}995996// Broken sub-stmt shouldn't prevent forming the case statement properly.997if (SubStmt.isInvalid())998SubStmt = Actions.ActOnNullStmt(ColonLoc);9991000DiagnoseLabelFollowedByDecl(*this, SubStmt.get());1001return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,1002SubStmt.get(), getCurScope());1003}10041005StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {1006return ParseCompoundStatement(isStmtExpr,1007Scope::DeclScope | Scope::CompoundStmtScope);1008}10091010/// ParseCompoundStatement - Parse a "{}" block.1011///1012/// compound-statement: [C99 6.8.2]1013/// { block-item-list[opt] }1014/// [GNU] { label-declarations block-item-list } [TODO]1015///1016/// block-item-list:1017/// block-item1018/// block-item-list block-item1019///1020/// block-item:1021/// declaration1022/// [GNU] '__extension__' declaration1023/// statement1024///1025/// [GNU] label-declarations:1026/// [GNU] label-declaration1027/// [GNU] label-declarations label-declaration1028///1029/// [GNU] label-declaration:1030/// [GNU] '__label__' identifier-list ';'1031///1032StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,1033unsigned ScopeFlags) {1034assert(Tok.is(tok::l_brace) && "Not a compound stmt!");10351036// Enter a scope to hold everything within the compound stmt. Compound1037// statements can always hold declarations.1038ParseScope CompoundScope(this, ScopeFlags);10391040// Parse the statements in the body.1041return ParseCompoundStatementBody(isStmtExpr);1042}10431044/// Parse any pragmas at the start of the compound expression. We handle these1045/// separately since some pragmas (FP_CONTRACT) must appear before any C1046/// statement in the compound, but may be intermingled with other pragmas.1047void Parser::ParseCompoundStatementLeadingPragmas() {1048bool checkForPragmas = true;1049while (checkForPragmas) {1050switch (Tok.getKind()) {1051case tok::annot_pragma_vis:1052HandlePragmaVisibility();1053break;1054case tok::annot_pragma_pack:1055HandlePragmaPack();1056break;1057case tok::annot_pragma_msstruct:1058HandlePragmaMSStruct();1059break;1060case tok::annot_pragma_align:1061HandlePragmaAlign();1062break;1063case tok::annot_pragma_weak:1064HandlePragmaWeak();1065break;1066case tok::annot_pragma_weakalias:1067HandlePragmaWeakAlias();1068break;1069case tok::annot_pragma_redefine_extname:1070HandlePragmaRedefineExtname();1071break;1072case tok::annot_pragma_opencl_extension:1073HandlePragmaOpenCLExtension();1074break;1075case tok::annot_pragma_fp_contract:1076HandlePragmaFPContract();1077break;1078case tok::annot_pragma_fp:1079HandlePragmaFP();1080break;1081case tok::annot_pragma_fenv_access:1082case tok::annot_pragma_fenv_access_ms:1083HandlePragmaFEnvAccess();1084break;1085case tok::annot_pragma_fenv_round:1086HandlePragmaFEnvRound();1087break;1088case tok::annot_pragma_cx_limited_range:1089HandlePragmaCXLimitedRange();1090break;1091case tok::annot_pragma_float_control:1092HandlePragmaFloatControl();1093break;1094case tok::annot_pragma_ms_pointers_to_members:1095HandlePragmaMSPointersToMembers();1096break;1097case tok::annot_pragma_ms_pragma:1098HandlePragmaMSPragma();1099break;1100case tok::annot_pragma_ms_vtordisp:1101HandlePragmaMSVtorDisp();1102break;1103case tok::annot_pragma_dump:1104HandlePragmaDump();1105break;1106default:1107checkForPragmas = false;1108break;1109}1110}11111112}11131114void Parser::DiagnoseLabelAtEndOfCompoundStatement() {1115if (getLangOpts().CPlusPlus) {1116Diag(Tok, getLangOpts().CPlusPlus231117? diag::warn_cxx20_compat_label_end_of_compound_statement1118: diag::ext_cxx_label_end_of_compound_statement);1119} else {1120Diag(Tok, getLangOpts().C231121? diag::warn_c23_compat_label_end_of_compound_statement1122: diag::ext_c_label_end_of_compound_statement);1123}1124}11251126/// Consume any extra semi-colons resulting in null statements,1127/// returning true if any tok::semi were consumed.1128bool Parser::ConsumeNullStmt(StmtVector &Stmts) {1129if (!Tok.is(tok::semi))1130return false;11311132SourceLocation StartLoc = Tok.getLocation();1133SourceLocation EndLoc;11341135while (Tok.is(tok::semi) && !Tok.hasLeadingEmptyMacro() &&1136Tok.getLocation().isValid() && !Tok.getLocation().isMacroID()) {1137EndLoc = Tok.getLocation();11381139// Don't just ConsumeToken() this tok::semi, do store it in AST.1140StmtResult R =1141ParseStatementOrDeclaration(Stmts, ParsedStmtContext::SubStmt);1142if (R.isUsable())1143Stmts.push_back(R.get());1144}11451146// Did not consume any extra semi.1147if (EndLoc.isInvalid())1148return false;11491150Diag(StartLoc, diag::warn_null_statement)1151<< FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));1152return true;1153}11541155StmtResult Parser::handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx) {1156bool IsStmtExprResult = false;1157if ((StmtCtx & ParsedStmtContext::InStmtExpr) != ParsedStmtContext()) {1158// For GCC compatibility we skip past NullStmts.1159unsigned LookAhead = 0;1160while (GetLookAheadToken(LookAhead).is(tok::semi)) {1161++LookAhead;1162}1163// Then look to see if the next two tokens close the statement expression;1164// if so, this expression statement is the last statement in a statement1165// expression.1166IsStmtExprResult = GetLookAheadToken(LookAhead).is(tok::r_brace) &&1167GetLookAheadToken(LookAhead + 1).is(tok::r_paren);1168}11691170if (IsStmtExprResult)1171E = Actions.ActOnStmtExprResult(E);1172return Actions.ActOnExprStmt(E, /*DiscardedValue=*/!IsStmtExprResult);1173}11741175/// ParseCompoundStatementBody - Parse a sequence of statements optionally1176/// followed by a label and invoke the ActOnCompoundStmt action. This expects1177/// the '{' to be the current token, and consume the '}' at the end of the1178/// block. It does not manipulate the scope stack.1179StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {1180PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),1181Tok.getLocation(),1182"in compound statement ('{}')");11831184// Record the current FPFeatures, restore on leaving the1185// compound statement.1186Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);11871188InMessageExpressionRAIIObject InMessage(*this, false);1189BalancedDelimiterTracker T(*this, tok::l_brace);1190if (T.consumeOpen())1191return StmtError();11921193Sema::CompoundScopeRAII CompoundScope(Actions, isStmtExpr);11941195// Parse any pragmas at the beginning of the compound statement.1196ParseCompoundStatementLeadingPragmas();1197Actions.ActOnAfterCompoundStatementLeadingPragmas();11981199StmtVector Stmts;12001201// "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are1202// only allowed at the start of a compound stmt regardless of the language.1203while (Tok.is(tok::kw___label__)) {1204SourceLocation LabelLoc = ConsumeToken();12051206SmallVector<Decl *, 8> DeclsInGroup;1207while (true) {1208if (Tok.isNot(tok::identifier)) {1209Diag(Tok, diag::err_expected) << tok::identifier;1210break;1211}12121213IdentifierInfo *II = Tok.getIdentifierInfo();1214SourceLocation IdLoc = ConsumeToken();1215DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));12161217if (!TryConsumeToken(tok::comma))1218break;1219}12201221DeclSpec DS(AttrFactory);1222DeclGroupPtrTy Res =1223Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);1224StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());12251226ExpectAndConsumeSemi(diag::err_expected_semi_declaration);1227if (R.isUsable())1228Stmts.push_back(R.get());1229}12301231ParsedStmtContext SubStmtCtx =1232ParsedStmtContext::Compound |1233(isStmtExpr ? ParsedStmtContext::InStmtExpr : ParsedStmtContext());12341235while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&1236Tok.isNot(tok::eof)) {1237if (Tok.is(tok::annot_pragma_unused)) {1238HandlePragmaUnused();1239continue;1240}12411242if (ConsumeNullStmt(Stmts))1243continue;12441245StmtResult R;1246if (Tok.isNot(tok::kw___extension__)) {1247R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);1248} else {1249// __extension__ can start declarations and it can also be a unary1250// operator for expressions. Consume multiple __extension__ markers here1251// until we can determine which is which.1252// FIXME: This loses extension expressions in the AST!1253SourceLocation ExtLoc = ConsumeToken();1254while (Tok.is(tok::kw___extension__))1255ConsumeToken();12561257ParsedAttributes attrs(AttrFactory);1258MaybeParseCXX11Attributes(attrs, /*MightBeObjCMessageSend*/ true);12591260// If this is the start of a declaration, parse it as such.1261if (isDeclarationStatement()) {1262// __extension__ silences extension warnings in the subdeclaration.1263// FIXME: Save the __extension__ on the decl as a node somehow?1264ExtensionRAIIObject O(Diags);12651266SourceLocation DeclStart = Tok.getLocation(), DeclEnd;1267ParsedAttributes DeclSpecAttrs(AttrFactory);1268DeclGroupPtrTy Res = ParseDeclaration(DeclaratorContext::Block, DeclEnd,1269attrs, DeclSpecAttrs);1270R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);1271} else {1272// Otherwise this was a unary __extension__ marker.1273ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));12741275if (Res.isInvalid()) {1276SkipUntil(tok::semi);1277continue;1278}12791280// Eat the semicolon at the end of stmt and convert the expr into a1281// statement.1282ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);1283R = handleExprStmt(Res, SubStmtCtx);1284if (R.isUsable())1285R = Actions.ActOnAttributedStmt(attrs, R.get());1286}1287}12881289if (R.isUsable())1290Stmts.push_back(R.get());1291}1292// Warn the user that using option `-ffp-eval-method=source` on a1293// 32-bit target and feature `sse` disabled, or using1294// `pragma clang fp eval_method=source` and feature `sse` disabled, is not1295// supported.1296if (!PP.getTargetInfo().supportSourceEvalMethod() &&1297(PP.getLastFPEvalPragmaLocation().isValid() ||1298PP.getCurrentFPEvalMethod() ==1299LangOptions::FPEvalMethodKind::FEM_Source))1300Diag(Tok.getLocation(),1301diag::warn_no_support_for_eval_method_source_on_m32);13021303SourceLocation CloseLoc = Tok.getLocation();13041305// We broke out of the while loop because we found a '}' or EOF.1306if (!T.consumeClose()) {1307// If this is the '})' of a statement expression, check that it's written1308// in a sensible way.1309if (isStmtExpr && Tok.is(tok::r_paren))1310checkCompoundToken(CloseLoc, tok::r_brace, CompoundToken::StmtExprEnd);1311} else {1312// Recover by creating a compound statement with what we parsed so far,1313// instead of dropping everything and returning StmtError().1314}13151316if (T.getCloseLocation().isValid())1317CloseLoc = T.getCloseLocation();13181319return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,1320Stmts, isStmtExpr);1321}13221323/// ParseParenExprOrCondition:1324/// [C ] '(' expression ')'1325/// [C++] '(' condition ')'1326/// [C++1z] '(' init-statement[opt] condition ')'1327///1328/// This function parses and performs error recovery on the specified condition1329/// or expression (depending on whether we're in C++ or C mode). This function1330/// goes out of its way to recover well. It returns true if there was a parser1331/// error (the right paren couldn't be found), which indicates that the caller1332/// should try to recover harder. It returns false if the condition is1333/// successfully parsed. Note that a successful parse can still have semantic1334/// errors in the condition.1335/// Additionally, it will assign the location of the outer-most '(' and ')',1336/// to LParenLoc and RParenLoc, respectively.1337bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,1338Sema::ConditionResult &Cond,1339SourceLocation Loc,1340Sema::ConditionKind CK,1341SourceLocation &LParenLoc,1342SourceLocation &RParenLoc) {1343BalancedDelimiterTracker T(*this, tok::l_paren);1344T.consumeOpen();1345SourceLocation Start = Tok.getLocation();13461347if (getLangOpts().CPlusPlus) {1348Cond = ParseCXXCondition(InitStmt, Loc, CK, false);1349} else {1350ExprResult CondExpr = ParseExpression();13511352// If required, convert to a boolean value.1353if (CondExpr.isInvalid())1354Cond = Sema::ConditionError();1355else1356Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK,1357/*MissingOK=*/false);1358}13591360// If the parser was confused by the condition and we don't have a ')', try to1361// recover by skipping ahead to a semi and bailing out. If condexp is1362// semantically invalid but we have well formed code, keep going.1363if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) {1364SkipUntil(tok::semi);1365// Skipping may have stopped if it found the containing ')'. If so, we can1366// continue parsing the if statement.1367if (Tok.isNot(tok::r_paren))1368return true;1369}13701371if (Cond.isInvalid()) {1372ExprResult CondExpr = Actions.CreateRecoveryExpr(1373Start, Tok.getLocation() == Start ? Start : PrevTokLocation, {},1374Actions.PreferredConditionType(CK));1375if (!CondExpr.isInvalid())1376Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK,1377/*MissingOK=*/false);1378}13791380// Either the condition is valid or the rparen is present.1381T.consumeClose();1382LParenLoc = T.getOpenLocation();1383RParenLoc = T.getCloseLocation();13841385// Check for extraneous ')'s to catch things like "if (foo())) {". We know1386// that all callers are looking for a statement after the condition, so ")"1387// isn't valid.1388while (Tok.is(tok::r_paren)) {1389Diag(Tok, diag::err_extraneous_rparen_in_condition)1390<< FixItHint::CreateRemoval(Tok.getLocation());1391ConsumeParen();1392}13931394return false;1395}13961397namespace {13981399enum MisleadingStatementKind { MSK_if, MSK_else, MSK_for, MSK_while };14001401struct MisleadingIndentationChecker {1402Parser &P;1403SourceLocation StmtLoc;1404SourceLocation PrevLoc;1405unsigned NumDirectives;1406MisleadingStatementKind Kind;1407bool ShouldSkip;1408MisleadingIndentationChecker(Parser &P, MisleadingStatementKind K,1409SourceLocation SL)1410: P(P), StmtLoc(SL), PrevLoc(P.getCurToken().getLocation()),1411NumDirectives(P.getPreprocessor().getNumDirectives()), Kind(K),1412ShouldSkip(P.getCurToken().is(tok::l_brace)) {1413if (!P.MisleadingIndentationElseLoc.isInvalid()) {1414StmtLoc = P.MisleadingIndentationElseLoc;1415P.MisleadingIndentationElseLoc = SourceLocation();1416}1417if (Kind == MSK_else && !ShouldSkip)1418P.MisleadingIndentationElseLoc = SL;1419}14201421/// Compute the column number will aligning tabs on TabStop (-ftabstop), this1422/// gives the visual indentation of the SourceLocation.1423static unsigned getVisualIndentation(SourceManager &SM, SourceLocation Loc) {1424unsigned TabStop = SM.getDiagnostics().getDiagnosticOptions().TabStop;14251426unsigned ColNo = SM.getSpellingColumnNumber(Loc);1427if (ColNo == 0 || TabStop == 1)1428return ColNo;14291430std::pair<FileID, unsigned> FIDAndOffset = SM.getDecomposedLoc(Loc);14311432bool Invalid;1433StringRef BufData = SM.getBufferData(FIDAndOffset.first, &Invalid);1434if (Invalid)1435return 0;14361437const char *EndPos = BufData.data() + FIDAndOffset.second;1438// FileOffset are 0-based and Column numbers are 1-based1439assert(FIDAndOffset.second + 1 >= ColNo &&1440"Column number smaller than file offset?");14411442unsigned VisualColumn = 0; // Stored as 0-based column, here.1443// Loop from beginning of line up to Loc's file position, counting columns,1444// expanding tabs.1445for (const char *CurPos = EndPos - (ColNo - 1); CurPos != EndPos;1446++CurPos) {1447if (*CurPos == '\t')1448// Advance visual column to next tabstop.1449VisualColumn += (TabStop - VisualColumn % TabStop);1450else1451VisualColumn++;1452}1453return VisualColumn + 1;1454}14551456void Check() {1457Token Tok = P.getCurToken();1458if (P.getActions().getDiagnostics().isIgnored(1459diag::warn_misleading_indentation, Tok.getLocation()) ||1460ShouldSkip || NumDirectives != P.getPreprocessor().getNumDirectives() ||1461Tok.isOneOf(tok::semi, tok::r_brace) || Tok.isAnnotation() ||1462Tok.getLocation().isMacroID() || PrevLoc.isMacroID() ||1463StmtLoc.isMacroID() ||1464(Kind == MSK_else && P.MisleadingIndentationElseLoc.isInvalid())) {1465P.MisleadingIndentationElseLoc = SourceLocation();1466return;1467}1468if (Kind == MSK_else)1469P.MisleadingIndentationElseLoc = SourceLocation();14701471SourceManager &SM = P.getPreprocessor().getSourceManager();1472unsigned PrevColNum = getVisualIndentation(SM, PrevLoc);1473unsigned CurColNum = getVisualIndentation(SM, Tok.getLocation());1474unsigned StmtColNum = getVisualIndentation(SM, StmtLoc);14751476if (PrevColNum != 0 && CurColNum != 0 && StmtColNum != 0 &&1477((PrevColNum > StmtColNum && PrevColNum == CurColNum) ||1478!Tok.isAtStartOfLine()) &&1479SM.getPresumedLineNumber(StmtLoc) !=1480SM.getPresumedLineNumber(Tok.getLocation()) &&1481(Tok.isNot(tok::identifier) ||1482P.getPreprocessor().LookAhead(0).isNot(tok::colon))) {1483P.Diag(Tok.getLocation(), diag::warn_misleading_indentation) << Kind;1484P.Diag(StmtLoc, diag::note_previous_statement);1485}1486}1487};14881489}14901491/// ParseIfStatement1492/// if-statement: [C99 6.8.4.1]1493/// 'if' '(' expression ')' statement1494/// 'if' '(' expression ')' statement 'else' statement1495/// [C++] 'if' '(' condition ')' statement1496/// [C++] 'if' '(' condition ')' statement 'else' statement1497/// [C++23] 'if' '!' [opt] consteval compound-statement1498/// [C++23] 'if' '!' [opt] consteval compound-statement 'else' statement1499///1500StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {1501assert(Tok.is(tok::kw_if) && "Not an if stmt!");1502SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.15031504bool IsConstexpr = false;1505bool IsConsteval = false;1506SourceLocation NotLocation;1507SourceLocation ConstevalLoc;15081509if (Tok.is(tok::kw_constexpr)) {1510// C23 supports constexpr keyword, but only for object definitions.1511if (getLangOpts().CPlusPlus) {1512Diag(Tok, getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_constexpr_if1513: diag::ext_constexpr_if);1514IsConstexpr = true;1515ConsumeToken();1516}1517} else {1518if (Tok.is(tok::exclaim)) {1519NotLocation = ConsumeToken();1520}15211522if (Tok.is(tok::kw_consteval)) {1523Diag(Tok, getLangOpts().CPlusPlus23 ? diag::warn_cxx20_compat_consteval_if1524: diag::ext_consteval_if);1525IsConsteval = true;1526ConstevalLoc = ConsumeToken();1527}1528}1529if (!IsConsteval && (NotLocation.isValid() || Tok.isNot(tok::l_paren))) {1530Diag(Tok, diag::err_expected_lparen_after) << "if";1531SkipUntil(tok::semi);1532return StmtError();1533}15341535bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;15361537// C99 6.8.4p3 - In C99, the if statement is a block. This is not1538// the case for C90.1539//1540// C++ 6.4p3:1541// A name introduced by a declaration in a condition is in scope from its1542// point of declaration until the end of the substatements controlled by the1543// condition.1544// C++ 3.3.2p4:1545// Names declared in the for-init-statement, and in the condition of if,1546// while, for, and switch statements are local to the if, while, for, or1547// switch statement (including the controlled statement).1548//1549ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);15501551// Parse the condition.1552StmtResult InitStmt;1553Sema::ConditionResult Cond;1554SourceLocation LParen;1555SourceLocation RParen;1556std::optional<bool> ConstexprCondition;1557if (!IsConsteval) {15581559if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,1560IsConstexpr ? Sema::ConditionKind::ConstexprIf1561: Sema::ConditionKind::Boolean,1562LParen, RParen))1563return StmtError();15641565if (IsConstexpr)1566ConstexprCondition = Cond.getKnownValue();1567}15681569bool IsBracedThen = Tok.is(tok::l_brace);15701571// C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if1572// there is no compound stmt. C90 does not have this clause. We only do this1573// if the body isn't a compound statement to avoid push/pop in common cases.1574//1575// C++ 6.4p1:1576// The substatement in a selection-statement (each substatement, in the else1577// form of the if statement) implicitly defines a local scope.1578//1579// For C++ we create a scope for the condition and a new scope for1580// substatements because:1581// -When the 'then' scope exits, we want the condition declaration to still be1582// active for the 'else' scope too.1583// -Sema will detect name clashes by considering declarations of a1584// 'ControlScope' as part of its direct subscope.1585// -If we wanted the condition and substatement to be in the same scope, we1586// would have to notify ParseStatement not to create a new scope. It's1587// simpler to let it create a new scope.1588//1589ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, IsBracedThen);15901591MisleadingIndentationChecker MIChecker(*this, MSK_if, IfLoc);15921593// Read the 'then' stmt.1594SourceLocation ThenStmtLoc = Tok.getLocation();15951596SourceLocation InnerStatementTrailingElseLoc;1597StmtResult ThenStmt;1598{1599bool ShouldEnter = ConstexprCondition && !*ConstexprCondition;1600Sema::ExpressionEvaluationContext Context =1601Sema::ExpressionEvaluationContext::DiscardedStatement;1602if (NotLocation.isInvalid() && IsConsteval) {1603Context = Sema::ExpressionEvaluationContext::ImmediateFunctionContext;1604ShouldEnter = true;1605}16061607EnterExpressionEvaluationContext PotentiallyDiscarded(1608Actions, Context, nullptr,1609Sema::ExpressionEvaluationContextRecord::EK_Other, ShouldEnter);1610ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);1611}16121613if (Tok.isNot(tok::kw_else))1614MIChecker.Check();16151616// Pop the 'if' scope if needed.1617InnerScope.Exit();16181619// If it has an else, parse it.1620SourceLocation ElseLoc;1621SourceLocation ElseStmtLoc;1622StmtResult ElseStmt;16231624if (Tok.is(tok::kw_else)) {1625if (TrailingElseLoc)1626*TrailingElseLoc = Tok.getLocation();16271628ElseLoc = ConsumeToken();1629ElseStmtLoc = Tok.getLocation();16301631// C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if1632// there is no compound stmt. C90 does not have this clause. We only do1633// this if the body isn't a compound statement to avoid push/pop in common1634// cases.1635//1636// C++ 6.4p1:1637// The substatement in a selection-statement (each substatement, in the else1638// form of the if statement) implicitly defines a local scope.1639//1640ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,1641Tok.is(tok::l_brace));16421643MisleadingIndentationChecker MIChecker(*this, MSK_else, ElseLoc);1644bool ShouldEnter = ConstexprCondition && *ConstexprCondition;1645Sema::ExpressionEvaluationContext Context =1646Sema::ExpressionEvaluationContext::DiscardedStatement;1647if (NotLocation.isValid() && IsConsteval) {1648Context = Sema::ExpressionEvaluationContext::ImmediateFunctionContext;1649ShouldEnter = true;1650}16511652EnterExpressionEvaluationContext PotentiallyDiscarded(1653Actions, Context, nullptr,1654Sema::ExpressionEvaluationContextRecord::EK_Other, ShouldEnter);1655ElseStmt = ParseStatement();16561657if (ElseStmt.isUsable())1658MIChecker.Check();16591660// Pop the 'else' scope if needed.1661InnerScope.Exit();1662} else if (Tok.is(tok::code_completion)) {1663cutOffParsing();1664Actions.CodeCompletion().CodeCompleteAfterIf(getCurScope(), IsBracedThen);1665return StmtError();1666} else if (InnerStatementTrailingElseLoc.isValid()) {1667Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);1668}16691670IfScope.Exit();16711672// If the then or else stmt is invalid and the other is valid (and present),1673// turn the invalid one into a null stmt to avoid dropping the other1674// part. If both are invalid, return error.1675if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||1676(ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||1677(ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {1678// Both invalid, or one is invalid and other is non-present: return error.1679return StmtError();1680}16811682if (IsConsteval) {1683auto IsCompoundStatement = [](const Stmt *S) {1684if (const auto *Outer = dyn_cast_if_present<AttributedStmt>(S))1685S = Outer->getSubStmt();1686return isa_and_nonnull<clang::CompoundStmt>(S);1687};16881689if (!IsCompoundStatement(ThenStmt.get())) {1690Diag(ConstevalLoc, diag::err_expected_after) << "consteval"1691<< "{";1692return StmtError();1693}1694if (!ElseStmt.isUnset() && !IsCompoundStatement(ElseStmt.get())) {1695Diag(ElseLoc, diag::err_expected_after) << "else"1696<< "{";1697return StmtError();1698}1699}17001701// Now if either are invalid, replace with a ';'.1702if (ThenStmt.isInvalid())1703ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);1704if (ElseStmt.isInvalid())1705ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);17061707IfStatementKind Kind = IfStatementKind::Ordinary;1708if (IsConstexpr)1709Kind = IfStatementKind::Constexpr;1710else if (IsConsteval)1711Kind = NotLocation.isValid() ? IfStatementKind::ConstevalNegated1712: IfStatementKind::ConstevalNonNegated;17131714return Actions.ActOnIfStmt(IfLoc, Kind, LParen, InitStmt.get(), Cond, RParen,1715ThenStmt.get(), ElseLoc, ElseStmt.get());1716}17171718/// ParseSwitchStatement1719/// switch-statement:1720/// 'switch' '(' expression ')' statement1721/// [C++] 'switch' '(' condition ')' statement1722StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {1723assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");1724SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.17251726if (Tok.isNot(tok::l_paren)) {1727Diag(Tok, diag::err_expected_lparen_after) << "switch";1728SkipUntil(tok::semi);1729return StmtError();1730}17311732bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;17331734// C99 6.8.4p3 - In C99, the switch statement is a block. This is1735// not the case for C90. Start the switch scope.1736//1737// C++ 6.4p3:1738// A name introduced by a declaration in a condition is in scope from its1739// point of declaration until the end of the substatements controlled by the1740// condition.1741// C++ 3.3.2p4:1742// Names declared in the for-init-statement, and in the condition of if,1743// while, for, and switch statements are local to the if, while, for, or1744// switch statement (including the controlled statement).1745//1746unsigned ScopeFlags = Scope::SwitchScope;1747if (C99orCXX)1748ScopeFlags |= Scope::DeclScope | Scope::ControlScope;1749ParseScope SwitchScope(this, ScopeFlags);17501751// Parse the condition.1752StmtResult InitStmt;1753Sema::ConditionResult Cond;1754SourceLocation LParen;1755SourceLocation RParen;1756if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,1757Sema::ConditionKind::Switch, LParen, RParen))1758return StmtError();17591760StmtResult Switch = Actions.ActOnStartOfSwitchStmt(1761SwitchLoc, LParen, InitStmt.get(), Cond, RParen);17621763if (Switch.isInvalid()) {1764// Skip the switch body.1765// FIXME: This is not optimal recovery, but parsing the body is more1766// dangerous due to the presence of case and default statements, which1767// will have no place to connect back with the switch.1768if (Tok.is(tok::l_brace)) {1769ConsumeBrace();1770SkipUntil(tok::r_brace);1771} else1772SkipUntil(tok::semi);1773return Switch;1774}17751776// C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if1777// there is no compound stmt. C90 does not have this clause. We only do this1778// if the body isn't a compound statement to avoid push/pop in common cases.1779//1780// C++ 6.4p1:1781// The substatement in a selection-statement (each substatement, in the else1782// form of the if statement) implicitly defines a local scope.1783//1784// See comments in ParseIfStatement for why we create a scope for the1785// condition and a new scope for substatement in C++.1786//1787getCurScope()->AddFlags(Scope::BreakScope);1788ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));17891790// We have incremented the mangling number for the SwitchScope and the1791// InnerScope, which is one too many.1792if (C99orCXX)1793getCurScope()->decrementMSManglingNumber();17941795// Read the body statement.1796StmtResult Body(ParseStatement(TrailingElseLoc));17971798// Pop the scopes.1799InnerScope.Exit();1800SwitchScope.Exit();18011802return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());1803}18041805/// ParseWhileStatement1806/// while-statement: [C99 6.8.5.1]1807/// 'while' '(' expression ')' statement1808/// [C++] 'while' '(' condition ')' statement1809StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {1810assert(Tok.is(tok::kw_while) && "Not a while stmt!");1811SourceLocation WhileLoc = Tok.getLocation();1812ConsumeToken(); // eat the 'while'.18131814if (Tok.isNot(tok::l_paren)) {1815Diag(Tok, diag::err_expected_lparen_after) << "while";1816SkipUntil(tok::semi);1817return StmtError();1818}18191820bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;18211822// C99 6.8.5p5 - In C99, the while statement is a block. This is not1823// the case for C90. Start the loop scope.1824//1825// C++ 6.4p3:1826// A name introduced by a declaration in a condition is in scope from its1827// point of declaration until the end of the substatements controlled by the1828// condition.1829// C++ 3.3.2p4:1830// Names declared in the for-init-statement, and in the condition of if,1831// while, for, and switch statements are local to the if, while, for, or1832// switch statement (including the controlled statement).1833//1834unsigned ScopeFlags;1835if (C99orCXX)1836ScopeFlags = Scope::BreakScope | Scope::ContinueScope |1837Scope::DeclScope | Scope::ControlScope;1838else1839ScopeFlags = Scope::BreakScope | Scope::ContinueScope;1840ParseScope WhileScope(this, ScopeFlags);18411842// Parse the condition.1843Sema::ConditionResult Cond;1844SourceLocation LParen;1845SourceLocation RParen;1846if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,1847Sema::ConditionKind::Boolean, LParen, RParen))1848return StmtError();18491850// C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if1851// there is no compound stmt. C90 does not have this clause. We only do this1852// if the body isn't a compound statement to avoid push/pop in common cases.1853//1854// C++ 6.5p2:1855// The substatement in an iteration-statement implicitly defines a local scope1856// which is entered and exited each time through the loop.1857//1858// See comments in ParseIfStatement for why we create a scope for the1859// condition and a new scope for substatement in C++.1860//1861ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));18621863MisleadingIndentationChecker MIChecker(*this, MSK_while, WhileLoc);18641865// Read the body statement.1866StmtResult Body(ParseStatement(TrailingElseLoc));18671868if (Body.isUsable())1869MIChecker.Check();1870// Pop the body scope if needed.1871InnerScope.Exit();1872WhileScope.Exit();18731874if (Cond.isInvalid() || Body.isInvalid())1875return StmtError();18761877return Actions.ActOnWhileStmt(WhileLoc, LParen, Cond, RParen, Body.get());1878}18791880/// ParseDoStatement1881/// do-statement: [C99 6.8.5.2]1882/// 'do' statement 'while' '(' expression ')' ';'1883/// Note: this lets the caller parse the end ';'.1884StmtResult Parser::ParseDoStatement() {1885assert(Tok.is(tok::kw_do) && "Not a do stmt!");1886SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.18871888// C99 6.8.5p5 - In C99, the do statement is a block. This is not1889// the case for C90. Start the loop scope.1890unsigned ScopeFlags;1891if (getLangOpts().C99)1892ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;1893else1894ScopeFlags = Scope::BreakScope | Scope::ContinueScope;18951896ParseScope DoScope(this, ScopeFlags);18971898// C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if1899// there is no compound stmt. C90 does not have this clause. We only do this1900// if the body isn't a compound statement to avoid push/pop in common cases.1901//1902// C++ 6.5p2:1903// The substatement in an iteration-statement implicitly defines a local scope1904// which is entered and exited each time through the loop.1905//1906bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;1907ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));19081909// Read the body statement.1910StmtResult Body(ParseStatement());19111912// Pop the body scope if needed.1913InnerScope.Exit();19141915if (Tok.isNot(tok::kw_while)) {1916if (!Body.isInvalid()) {1917Diag(Tok, diag::err_expected_while);1918Diag(DoLoc, diag::note_matching) << "'do'";1919SkipUntil(tok::semi, StopBeforeMatch);1920}1921return StmtError();1922}1923SourceLocation WhileLoc = ConsumeToken();19241925if (Tok.isNot(tok::l_paren)) {1926Diag(Tok, diag::err_expected_lparen_after) << "do/while";1927SkipUntil(tok::semi, StopBeforeMatch);1928return StmtError();1929}19301931// Parse the parenthesized expression.1932BalancedDelimiterTracker T(*this, tok::l_paren);1933T.consumeOpen();19341935// A do-while expression is not a condition, so can't have attributes.1936DiagnoseAndSkipCXX11Attributes();19371938SourceLocation Start = Tok.getLocation();1939ExprResult Cond = ParseExpression();1940// Correct the typos in condition before closing the scope.1941if (Cond.isUsable())1942Cond = Actions.CorrectDelayedTyposInExpr(Cond, /*InitDecl=*/nullptr,1943/*RecoverUncorrectedTypos=*/true);1944else {1945if (!Tok.isOneOf(tok::r_paren, tok::r_square, tok::r_brace))1946SkipUntil(tok::semi);1947Cond = Actions.CreateRecoveryExpr(1948Start, Start == Tok.getLocation() ? Start : PrevTokLocation, {},1949Actions.getASTContext().BoolTy);1950}1951T.consumeClose();1952DoScope.Exit();19531954if (Cond.isInvalid() || Body.isInvalid())1955return StmtError();19561957return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),1958Cond.get(), T.getCloseLocation());1959}19601961bool Parser::isForRangeIdentifier() {1962assert(Tok.is(tok::identifier));19631964const Token &Next = NextToken();1965if (Next.is(tok::colon))1966return true;19671968if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {1969TentativeParsingAction PA(*this);1970ConsumeToken();1971SkipCXX11Attributes();1972bool Result = Tok.is(tok::colon);1973PA.Revert();1974return Result;1975}19761977return false;1978}19791980/// ParseForStatement1981/// for-statement: [C99 6.8.5.3]1982/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement1983/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement1984/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'1985/// [C++] statement1986/// [C++0x] 'for'1987/// 'co_await'[opt] [Coroutines]1988/// '(' for-range-declaration ':' for-range-initializer ')'1989/// statement1990/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement1991/// [OBJC2] 'for' '(' expr 'in' expr ')' statement1992///1993/// [C++] for-init-statement:1994/// [C++] expression-statement1995/// [C++] simple-declaration1996/// [C++23] alias-declaration1997///1998/// [C++0x] for-range-declaration:1999/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator2000/// [C++0x] for-range-initializer:2001/// [C++0x] expression2002/// [C++0x] braced-init-list [TODO]2003StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {2004assert(Tok.is(tok::kw_for) && "Not a for stmt!");2005SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.20062007SourceLocation CoawaitLoc;2008if (Tok.is(tok::kw_co_await))2009CoawaitLoc = ConsumeToken();20102011if (Tok.isNot(tok::l_paren)) {2012Diag(Tok, diag::err_expected_lparen_after) << "for";2013SkipUntil(tok::semi);2014return StmtError();2015}20162017bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||2018getLangOpts().ObjC;20192020// C99 6.8.5p5 - In C99, the for statement is a block. This is not2021// the case for C90. Start the loop scope.2022//2023// C++ 6.4p3:2024// A name introduced by a declaration in a condition is in scope from its2025// point of declaration until the end of the substatements controlled by the2026// condition.2027// C++ 3.3.2p4:2028// Names declared in the for-init-statement, and in the condition of if,2029// while, for, and switch statements are local to the if, while, for, or2030// switch statement (including the controlled statement).2031// C++ 6.5.3p1:2032// Names declared in the for-init-statement are in the same declarative-region2033// as those declared in the condition.2034//2035unsigned ScopeFlags = 0;2036if (C99orCXXorObjC)2037ScopeFlags = Scope::DeclScope | Scope::ControlScope;20382039ParseScope ForScope(this, ScopeFlags);20402041BalancedDelimiterTracker T(*this, tok::l_paren);2042T.consumeOpen();20432044ExprResult Value;20452046bool ForEach = false;2047StmtResult FirstPart;2048Sema::ConditionResult SecondPart;2049ExprResult Collection;2050ForRangeInfo ForRangeInfo;2051FullExprArg ThirdPart(Actions);20522053if (Tok.is(tok::code_completion)) {2054cutOffParsing();2055Actions.CodeCompletion().CodeCompleteOrdinaryName(2056getCurScope(), C99orCXXorObjC ? SemaCodeCompletion::PCC_ForInit2057: SemaCodeCompletion::PCC_Expression);2058return StmtError();2059}20602061ParsedAttributes attrs(AttrFactory);2062MaybeParseCXX11Attributes(attrs);20632064SourceLocation EmptyInitStmtSemiLoc;20652066// Parse the first part of the for specifier.2067if (Tok.is(tok::semi)) { // for (;2068ProhibitAttributes(attrs);2069// no first part, eat the ';'.2070SourceLocation SemiLoc = Tok.getLocation();2071if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID())2072EmptyInitStmtSemiLoc = SemiLoc;2073ConsumeToken();2074} else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&2075isForRangeIdentifier()) {2076ProhibitAttributes(attrs);2077IdentifierInfo *Name = Tok.getIdentifierInfo();2078SourceLocation Loc = ConsumeToken();2079MaybeParseCXX11Attributes(attrs);20802081ForRangeInfo.ColonLoc = ConsumeToken();2082if (Tok.is(tok::l_brace))2083ForRangeInfo.RangeExpr = ParseBraceInitializer();2084else2085ForRangeInfo.RangeExpr = ParseExpression();20862087Diag(Loc, diag::err_for_range_identifier)2088<< ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17)2089? FixItHint::CreateInsertion(Loc, "auto &&")2090: FixItHint());20912092ForRangeInfo.LoopVar =2093Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name, attrs);2094} else if (isForInitDeclaration()) { // for (int X = 4;2095ParenBraceBracketBalancer BalancerRAIIObj(*this);20962097// Parse declaration, which eats the ';'.2098if (!C99orCXXorObjC) { // Use of C99-style for loops in C90 mode?2099Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);2100Diag(Tok, diag::warn_gcc_variable_decl_in_for_loop);2101}2102DeclGroupPtrTy DG;2103SourceLocation DeclStart = Tok.getLocation(), DeclEnd;2104if (Tok.is(tok::kw_using)) {2105DG = ParseAliasDeclarationInInitStatement(DeclaratorContext::ForInit,2106attrs);2107FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());2108} else {2109// In C++0x, "for (T NS:a" might not be a typo for ::2110bool MightBeForRangeStmt = getLangOpts().CPlusPlus;2111ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);2112ParsedAttributes DeclSpecAttrs(AttrFactory);2113DG = ParseSimpleDeclaration(2114DeclaratorContext::ForInit, DeclEnd, attrs, DeclSpecAttrs, false,2115MightBeForRangeStmt ? &ForRangeInfo : nullptr);2116FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());2117if (ForRangeInfo.ParsedForRangeDecl()) {2118Diag(ForRangeInfo.ColonLoc, getLangOpts().CPlusPlus112119? diag::warn_cxx98_compat_for_range2120: diag::ext_for_range);2121ForRangeInfo.LoopVar = FirstPart;2122FirstPart = StmtResult();2123} else if (Tok.is(tok::semi)) { // for (int x = 4;2124ConsumeToken();2125} else if ((ForEach = isTokIdentifier_in())) {2126Actions.ActOnForEachDeclStmt(DG);2127// ObjC: for (id x in expr)2128ConsumeToken(); // consume 'in'21292130if (Tok.is(tok::code_completion)) {2131cutOffParsing();2132Actions.CodeCompletion().CodeCompleteObjCForCollection(getCurScope(),2133DG);2134return StmtError();2135}2136Collection = ParseExpression();2137} else {2138Diag(Tok, diag::err_expected_semi_for);2139}2140}2141} else {2142ProhibitAttributes(attrs);2143Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());21442145ForEach = isTokIdentifier_in();21462147// Turn the expression into a stmt.2148if (!Value.isInvalid()) {2149if (ForEach)2150FirstPart = Actions.ActOnForEachLValueExpr(Value.get());2151else {2152// We already know this is not an init-statement within a for loop, so2153// if we are parsing a C++11 range-based for loop, we should treat this2154// expression statement as being a discarded value expression because2155// we will err below. This way we do not warn on an unused expression2156// that was an error in the first place, like with: for (expr : expr);2157bool IsRangeBasedFor =2158getLangOpts().CPlusPlus11 && !ForEach && Tok.is(tok::colon);2159FirstPart = Actions.ActOnExprStmt(Value, !IsRangeBasedFor);2160}2161}21622163if (Tok.is(tok::semi)) {2164ConsumeToken();2165} else if (ForEach) {2166ConsumeToken(); // consume 'in'21672168if (Tok.is(tok::code_completion)) {2169cutOffParsing();2170Actions.CodeCompletion().CodeCompleteObjCForCollection(getCurScope(),2171nullptr);2172return StmtError();2173}2174Collection = ParseExpression();2175} else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {2176// User tried to write the reasonable, but ill-formed, for-range-statement2177// for (expr : expr) { ... }2178Diag(Tok, diag::err_for_range_expected_decl)2179<< FirstPart.get()->getSourceRange();2180SkipUntil(tok::r_paren, StopBeforeMatch);2181SecondPart = Sema::ConditionError();2182} else {2183if (!Value.isInvalid()) {2184Diag(Tok, diag::err_expected_semi_for);2185} else {2186// Skip until semicolon or rparen, don't consume it.2187SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);2188if (Tok.is(tok::semi))2189ConsumeToken();2190}2191}2192}21932194// Parse the second part of the for specifier.2195if (!ForEach && !ForRangeInfo.ParsedForRangeDecl() &&2196!SecondPart.isInvalid()) {2197// Parse the second part of the for specifier.2198if (Tok.is(tok::semi)) { // for (...;;2199// no second part.2200} else if (Tok.is(tok::r_paren)) {2201// missing both semicolons.2202} else {2203if (getLangOpts().CPlusPlus) {2204// C++2a: We've parsed an init-statement; we might have a2205// for-range-declaration next.2206bool MightBeForRangeStmt = !ForRangeInfo.ParsedForRangeDecl();2207ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);2208SourceLocation SecondPartStart = Tok.getLocation();2209Sema::ConditionKind CK = Sema::ConditionKind::Boolean;2210SecondPart = ParseCXXCondition(2211/*InitStmt=*/nullptr, ForLoc, CK,2212// FIXME: recovery if we don't see another semi!2213/*MissingOK=*/true, MightBeForRangeStmt ? &ForRangeInfo : nullptr,2214/*EnterForConditionScope=*/true);22152216if (ForRangeInfo.ParsedForRangeDecl()) {2217Diag(FirstPart.get() ? FirstPart.get()->getBeginLoc()2218: ForRangeInfo.ColonLoc,2219getLangOpts().CPlusPlus202220? diag::warn_cxx17_compat_for_range_init_stmt2221: diag::ext_for_range_init_stmt)2222<< (FirstPart.get() ? FirstPart.get()->getSourceRange()2223: SourceRange());2224if (EmptyInitStmtSemiLoc.isValid()) {2225Diag(EmptyInitStmtSemiLoc, diag::warn_empty_init_statement)2226<< /*for-loop*/ 22227<< FixItHint::CreateRemoval(EmptyInitStmtSemiLoc);2228}2229}22302231if (SecondPart.isInvalid()) {2232ExprResult CondExpr = Actions.CreateRecoveryExpr(2233SecondPartStart,2234Tok.getLocation() == SecondPartStart ? SecondPartStart2235: PrevTokLocation,2236{}, Actions.PreferredConditionType(CK));2237if (!CondExpr.isInvalid())2238SecondPart = Actions.ActOnCondition(getCurScope(), ForLoc,2239CondExpr.get(), CK,2240/*MissingOK=*/false);2241}22422243} else {2244// We permit 'continue' and 'break' in the condition of a for loop.2245getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);22462247ExprResult SecondExpr = ParseExpression();2248if (SecondExpr.isInvalid())2249SecondPart = Sema::ConditionError();2250else2251SecondPart = Actions.ActOnCondition(2252getCurScope(), ForLoc, SecondExpr.get(),2253Sema::ConditionKind::Boolean, /*MissingOK=*/true);2254}2255}2256}22572258// Enter a break / continue scope, if we didn't already enter one while2259// parsing the second part.2260if (!getCurScope()->isContinueScope())2261getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);22622263// Parse the third part of the for statement.2264if (!ForEach && !ForRangeInfo.ParsedForRangeDecl()) {2265if (Tok.isNot(tok::semi)) {2266if (!SecondPart.isInvalid())2267Diag(Tok, diag::err_expected_semi_for);2268SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);2269}22702271if (Tok.is(tok::semi)) {2272ConsumeToken();2273}22742275if (Tok.isNot(tok::r_paren)) { // for (...;...;)2276ExprResult Third = ParseExpression();2277// FIXME: The C++11 standard doesn't actually say that this is a2278// discarded-value expression, but it clearly should be.2279ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());2280}2281}2282// Match the ')'.2283T.consumeClose();22842285// C++ Coroutines [stmt.iter]:2286// 'co_await' can only be used for a range-based for statement.2287if (CoawaitLoc.isValid() && !ForRangeInfo.ParsedForRangeDecl()) {2288Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);2289CoawaitLoc = SourceLocation();2290}22912292if (CoawaitLoc.isValid() && getLangOpts().CPlusPlus20)2293Diag(CoawaitLoc, diag::warn_deprecated_for_co_await);22942295// We need to perform most of the semantic analysis for a C++0x for-range2296// statememt before parsing the body, in order to be able to deduce the type2297// of an auto-typed loop variable.2298StmtResult ForRangeStmt;2299StmtResult ForEachStmt;23002301if (ForRangeInfo.ParsedForRangeDecl()) {2302ExprResult CorrectedRange =2303Actions.CorrectDelayedTyposInExpr(ForRangeInfo.RangeExpr.get());2304ForRangeStmt = Actions.ActOnCXXForRangeStmt(2305getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),2306ForRangeInfo.LoopVar.get(), ForRangeInfo.ColonLoc, CorrectedRange.get(),2307T.getCloseLocation(), Sema::BFRK_Build,2308ForRangeInfo.LifetimeExtendTemps);2309} else if (ForEach) {2310// Similarly, we need to do the semantic analysis for a for-range2311// statement immediately in order to close over temporaries correctly.2312ForEachStmt = Actions.ObjC().ActOnObjCForCollectionStmt(2313ForLoc, FirstPart.get(), Collection.get(), T.getCloseLocation());2314} else {2315// In OpenMP loop region loop control variable must be captured and be2316// private. Perform analysis of first part (if any).2317if (getLangOpts().OpenMP && FirstPart.isUsable()) {2318Actions.OpenMP().ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());2319}2320}23212322// C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if2323// there is no compound stmt. C90 does not have this clause. We only do this2324// if the body isn't a compound statement to avoid push/pop in common cases.2325//2326// C++ 6.5p2:2327// The substatement in an iteration-statement implicitly defines a local scope2328// which is entered and exited each time through the loop.2329//2330// See comments in ParseIfStatement for why we create a scope for2331// for-init-statement/condition and a new scope for substatement in C++.2332//2333ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,2334Tok.is(tok::l_brace));23352336// The body of the for loop has the same local mangling number as the2337// for-init-statement.2338// It will only be incremented if the body contains other things that would2339// normally increment the mangling number (like a compound statement).2340if (C99orCXXorObjC)2341getCurScope()->decrementMSManglingNumber();23422343MisleadingIndentationChecker MIChecker(*this, MSK_for, ForLoc);23442345// Read the body statement.2346StmtResult Body(ParseStatement(TrailingElseLoc));23472348if (Body.isUsable())2349MIChecker.Check();23502351// Pop the body scope if needed.2352InnerScope.Exit();23532354// Leave the for-scope.2355ForScope.Exit();23562357if (Body.isInvalid())2358return StmtError();23592360if (ForEach)2361return Actions.ObjC().FinishObjCForCollectionStmt(ForEachStmt.get(),2362Body.get());23632364if (ForRangeInfo.ParsedForRangeDecl())2365return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());23662367return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),2368SecondPart, ThirdPart, T.getCloseLocation(),2369Body.get());2370}23712372/// ParseGotoStatement2373/// jump-statement:2374/// 'goto' identifier ';'2375/// [GNU] 'goto' '*' expression ';'2376///2377/// Note: this lets the caller parse the end ';'.2378///2379StmtResult Parser::ParseGotoStatement() {2380assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");2381SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.23822383StmtResult Res;2384if (Tok.is(tok::identifier)) {2385LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),2386Tok.getLocation());2387Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);2388ConsumeToken();2389} else if (Tok.is(tok::star)) {2390// GNU indirect goto extension.2391Diag(Tok, diag::ext_gnu_indirect_goto);2392SourceLocation StarLoc = ConsumeToken();2393ExprResult R(ParseExpression());2394if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.2395SkipUntil(tok::semi, StopBeforeMatch);2396return StmtError();2397}2398Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());2399} else {2400Diag(Tok, diag::err_expected) << tok::identifier;2401return StmtError();2402}24032404return Res;2405}24062407/// ParseContinueStatement2408/// jump-statement:2409/// 'continue' ';'2410///2411/// Note: this lets the caller parse the end ';'.2412///2413StmtResult Parser::ParseContinueStatement() {2414SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.2415return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());2416}24172418/// ParseBreakStatement2419/// jump-statement:2420/// 'break' ';'2421///2422/// Note: this lets the caller parse the end ';'.2423///2424StmtResult Parser::ParseBreakStatement() {2425SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.2426return Actions.ActOnBreakStmt(BreakLoc, getCurScope());2427}24282429/// ParseReturnStatement2430/// jump-statement:2431/// 'return' expression[opt] ';'2432/// 'return' braced-init-list ';'2433/// 'co_return' expression[opt] ';'2434/// 'co_return' braced-init-list ';'2435StmtResult Parser::ParseReturnStatement() {2436assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&2437"Not a return stmt!");2438bool IsCoreturn = Tok.is(tok::kw_co_return);2439SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.24402441ExprResult R;2442if (Tok.isNot(tok::semi)) {2443if (!IsCoreturn)2444PreferredType.enterReturn(Actions, Tok.getLocation());2445// FIXME: Code completion for co_return.2446if (Tok.is(tok::code_completion) && !IsCoreturn) {2447cutOffParsing();2448Actions.CodeCompletion().CodeCompleteExpression(2449getCurScope(), PreferredType.get(Tok.getLocation()));2450return StmtError();2451}24522453if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {2454R = ParseInitializer();2455if (R.isUsable())2456Diag(R.get()->getBeginLoc(),2457getLangOpts().CPlusPlus112458? diag::warn_cxx98_compat_generalized_initializer_lists2459: diag::ext_generalized_initializer_lists)2460<< R.get()->getSourceRange();2461} else2462R = ParseExpression();2463if (R.isInvalid()) {2464SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);2465return StmtError();2466}2467}2468if (IsCoreturn)2469return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get());2470return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());2471}24722473StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,2474ParsedStmtContext StmtCtx,2475SourceLocation *TrailingElseLoc,2476ParsedAttributes &Attrs) {2477// Create temporary attribute list.2478ParsedAttributes TempAttrs(AttrFactory);24792480SourceLocation StartLoc = Tok.getLocation();24812482// Get loop hints and consume annotated token.2483while (Tok.is(tok::annot_pragma_loop_hint)) {2484LoopHint Hint;2485if (!HandlePragmaLoopHint(Hint))2486continue;24872488ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,2489ArgsUnion(Hint.ValueExpr)};2490TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,2491Hint.PragmaNameLoc->Loc, ArgHints, 4,2492ParsedAttr::Form::Pragma());2493}24942495// Get the next statement.2496MaybeParseCXX11Attributes(Attrs);24972498ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);2499StmtResult S = ParseStatementOrDeclarationAfterAttributes(2500Stmts, StmtCtx, TrailingElseLoc, Attrs, EmptyDeclSpecAttrs);25012502Attrs.takeAllFrom(TempAttrs);25032504// Start of attribute range may already be set for some invalid input.2505// See PR46336.2506if (Attrs.Range.getBegin().isInvalid())2507Attrs.Range.setBegin(StartLoc);25082509return S;2510}25112512Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {2513assert(Tok.is(tok::l_brace));2514SourceLocation LBraceLoc = Tok.getLocation();25152516PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, LBraceLoc,2517"parsing function body");25182519// Save and reset current vtordisp stack if we have entered a C++ method body.2520bool IsCXXMethod =2521getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);2522Sema::PragmaStackSentinelRAII2523PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);25242525// Do not enter a scope for the brace, as the arguments are in the same scope2526// (the function body) as the body itself. Instead, just read the statement2527// list and put it into a CompoundStmt for safe keeping.2528StmtResult FnBody(ParseCompoundStatementBody());25292530// If the function body could not be parsed, make a bogus compoundstmt.2531if (FnBody.isInvalid()) {2532Sema::CompoundScopeRAII CompoundScope(Actions);2533FnBody =2534Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, std::nullopt, false);2535}25362537BodyScope.Exit();2538return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());2539}25402541/// ParseFunctionTryBlock - Parse a C++ function-try-block.2542///2543/// function-try-block:2544/// 'try' ctor-initializer[opt] compound-statement handler-seq2545///2546Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {2547assert(Tok.is(tok::kw_try) && "Expected 'try'");2548SourceLocation TryLoc = ConsumeToken();25492550PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, TryLoc,2551"parsing function try block");25522553// Constructor initializer list?2554if (Tok.is(tok::colon))2555ParseConstructorInitializer(Decl);2556else2557Actions.ActOnDefaultCtorInitializers(Decl);25582559// Save and reset current vtordisp stack if we have entered a C++ method body.2560bool IsCXXMethod =2561getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);2562Sema::PragmaStackSentinelRAII2563PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);25642565SourceLocation LBraceLoc = Tok.getLocation();2566StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));2567// If we failed to parse the try-catch, we just give the function an empty2568// compound statement as the body.2569if (FnBody.isInvalid()) {2570Sema::CompoundScopeRAII CompoundScope(Actions);2571FnBody =2572Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, std::nullopt, false);2573}25742575BodyScope.Exit();2576return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());2577}25782579bool Parser::trySkippingFunctionBody() {2580assert(SkipFunctionBodies &&2581"Should only be called when SkipFunctionBodies is enabled");2582if (!PP.isCodeCompletionEnabled()) {2583SkipFunctionBody();2584return true;2585}25862587// We're in code-completion mode. Skip parsing for all function bodies unless2588// the body contains the code-completion point.2589TentativeParsingAction PA(*this);2590bool IsTryCatch = Tok.is(tok::kw_try);2591CachedTokens Toks;2592bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);2593if (llvm::any_of(Toks, [](const Token &Tok) {2594return Tok.is(tok::code_completion);2595})) {2596PA.Revert();2597return false;2598}2599if (ErrorInPrologue) {2600PA.Commit();2601SkipMalformedDecl();2602return true;2603}2604if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {2605PA.Revert();2606return false;2607}2608while (IsTryCatch && Tok.is(tok::kw_catch)) {2609if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||2610!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {2611PA.Revert();2612return false;2613}2614}2615PA.Commit();2616return true;2617}26182619/// ParseCXXTryBlock - Parse a C++ try-block.2620///2621/// try-block:2622/// 'try' compound-statement handler-seq2623///2624StmtResult Parser::ParseCXXTryBlock() {2625assert(Tok.is(tok::kw_try) && "Expected 'try'");26262627SourceLocation TryLoc = ConsumeToken();2628return ParseCXXTryBlockCommon(TryLoc);2629}26302631/// ParseCXXTryBlockCommon - Parse the common part of try-block and2632/// function-try-block.2633///2634/// try-block:2635/// 'try' compound-statement handler-seq2636///2637/// function-try-block:2638/// 'try' ctor-initializer[opt] compound-statement handler-seq2639///2640/// handler-seq:2641/// handler handler-seq[opt]2642///2643/// [Borland] try-block:2644/// 'try' compound-statement seh-except-block2645/// 'try' compound-statement seh-finally-block2646///2647StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {2648if (Tok.isNot(tok::l_brace))2649return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);26502651StmtResult TryBlock(ParseCompoundStatement(2652/*isStmtExpr=*/false, Scope::DeclScope | Scope::TryScope |2653Scope::CompoundStmtScope |2654(FnTry ? Scope::FnTryCatchScope : 0)));2655if (TryBlock.isInvalid())2656return TryBlock;26572658// Borland allows SEH-handlers with 'try'26592660if ((Tok.is(tok::identifier) &&2661Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||2662Tok.is(tok::kw___finally)) {2663// TODO: Factor into common return ParseSEHHandlerCommon(...)2664StmtResult Handler;2665if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {2666SourceLocation Loc = ConsumeToken();2667Handler = ParseSEHExceptBlock(Loc);2668}2669else {2670SourceLocation Loc = ConsumeToken();2671Handler = ParseSEHFinallyBlock(Loc);2672}2673if(Handler.isInvalid())2674return Handler;26752676return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,2677TryLoc,2678TryBlock.get(),2679Handler.get());2680}2681else {2682StmtVector Handlers;26832684// C++11 attributes can't appear here, despite this context seeming2685// statement-like.2686DiagnoseAndSkipCXX11Attributes();26872688if (Tok.isNot(tok::kw_catch))2689return StmtError(Diag(Tok, diag::err_expected_catch));2690while (Tok.is(tok::kw_catch)) {2691StmtResult Handler(ParseCXXCatchBlock(FnTry));2692if (!Handler.isInvalid())2693Handlers.push_back(Handler.get());2694}2695// Don't bother creating the full statement if we don't have any usable2696// handlers.2697if (Handlers.empty())2698return StmtError();26992700return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);2701}2702}27032704/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard2705///2706/// handler:2707/// 'catch' '(' exception-declaration ')' compound-statement2708///2709/// exception-declaration:2710/// attribute-specifier-seq[opt] type-specifier-seq declarator2711/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]2712/// '...'2713///2714StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {2715assert(Tok.is(tok::kw_catch) && "Expected 'catch'");27162717SourceLocation CatchLoc = ConsumeToken();27182719BalancedDelimiterTracker T(*this, tok::l_paren);2720if (T.expectAndConsume())2721return StmtError();27222723// C++ 3.3.2p3:2724// The name in a catch exception-declaration is local to the handler and2725// shall not be redeclared in the outermost block of the handler.2726ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |2727Scope::CatchScope |2728(FnCatch ? Scope::FnTryCatchScope : 0));27292730// exception-declaration is equivalent to '...' or a parameter-declaration2731// without default arguments.2732Decl *ExceptionDecl = nullptr;2733if (Tok.isNot(tok::ellipsis)) {2734ParsedAttributes Attributes(AttrFactory);2735MaybeParseCXX11Attributes(Attributes);27362737DeclSpec DS(AttrFactory);27382739if (ParseCXXTypeSpecifierSeq(DS))2740return StmtError();27412742Declarator ExDecl(DS, Attributes, DeclaratorContext::CXXCatch);2743ParseDeclarator(ExDecl);2744ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);2745} else2746ConsumeToken();27472748T.consumeClose();2749if (T.getCloseLocation().isInvalid())2750return StmtError();27512752if (Tok.isNot(tok::l_brace))2753return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);27542755// FIXME: Possible draft standard bug: attribute-specifier should be allowed?2756StmtResult Block(ParseCompoundStatement());2757if (Block.isInvalid())2758return Block;27592760return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());2761}27622763void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {2764IfExistsCondition Result;2765if (ParseMicrosoftIfExistsCondition(Result))2766return;27672768// Handle dependent statements by parsing the braces as a compound statement.2769// This is not the same behavior as Visual C++, which don't treat this as a2770// compound statement, but for Clang's type checking we can't have anything2771// inside these braces escaping to the surrounding code.2772if (Result.Behavior == IEB_Dependent) {2773if (!Tok.is(tok::l_brace)) {2774Diag(Tok, diag::err_expected) << tok::l_brace;2775return;2776}27772778StmtResult Compound = ParseCompoundStatement();2779if (Compound.isInvalid())2780return;27812782StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,2783Result.IsIfExists,2784Result.SS,2785Result.Name,2786Compound.get());2787if (DepResult.isUsable())2788Stmts.push_back(DepResult.get());2789return;2790}27912792BalancedDelimiterTracker Braces(*this, tok::l_brace);2793if (Braces.consumeOpen()) {2794Diag(Tok, diag::err_expected) << tok::l_brace;2795return;2796}27972798switch (Result.Behavior) {2799case IEB_Parse:2800// Parse the statements below.2801break;28022803case IEB_Dependent:2804llvm_unreachable("Dependent case handled above");28052806case IEB_Skip:2807Braces.skipToEnd();2808return;2809}28102811// Condition is true, parse the statements.2812while (Tok.isNot(tok::r_brace)) {2813StmtResult R =2814ParseStatementOrDeclaration(Stmts, ParsedStmtContext::Compound);2815if (R.isUsable())2816Stmts.push_back(R.get());2817}2818Braces.consumeClose();2819}282028212822