#include "clang/AST/PrettyDeclStackTrace.h"
#include "clang/Basic/Attributes.h"
#include "clang/Basic/PrettyStackTrace.h"
#include "clang/Parse/LoopHint.h"
#include "clang/Parse/Parser.h"
#include "clang/Parse/RAIIObjectsForParser.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/TypoCorrection.h"
#include "llvm/ADT/STLExtras.h"
using namespace clang;
StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc,
ParsedStmtContext StmtCtx) {
StmtResult Res;
do {
StmtVector Stmts;
Res = ParseStatementOrDeclaration(Stmts, StmtCtx, TrailingElseLoc);
} while (!Res.isInvalid() && !Res.get());
return Res;
}
StmtResult
Parser::ParseStatementOrDeclaration(StmtVector &Stmts,
ParsedStmtContext StmtCtx,
SourceLocation *TrailingElseLoc) {
ParenBraceBracketBalancer BalancerRAIIObj(*this);
ParsedAttributes CXX11Attrs(AttrFactory);
MaybeParseCXX11Attributes(CXX11Attrs, true);
ParsedAttributes GNUAttrs(AttrFactory);
if (getLangOpts().OpenCL)
MaybeParseGNUAttributes(GNUAttrs);
StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
Stmts, StmtCtx, TrailingElseLoc, CXX11Attrs, GNUAttrs);
MaybeDestroyTemplateIds();
ParsedAttributes Attrs(AttrFactory);
takeAndConcatenateAttrs(CXX11Attrs, GNUAttrs, Attrs);
assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
"attributes on empty statement");
if (Attrs.empty() || Res.isInvalid())
return Res;
return Actions.ActOnAttributedStmt(Attrs, Res.get());
}
namespace {
class StatementFilterCCC final : public CorrectionCandidateCallback {
public:
StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
WantTypeSpecifiers = nextTok.isOneOf(tok::l_paren, tok::less, tok::l_square,
tok::identifier, tok::star, tok::amp);
WantExpressionKeywords =
nextTok.isOneOf(tok::l_paren, tok::identifier, tok::arrow, tok::period);
WantRemainingKeywords =
nextTok.isOneOf(tok::l_paren, tok::semi, tok::identifier, tok::l_brace);
WantCXXNamedCasts = false;
}
bool ValidateCandidate(const TypoCorrection &candidate) override {
if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
if (NextToken.is(tok::equal))
return candidate.getCorrectionDeclAs<VarDecl>();
if (NextToken.is(tok::period) &&
candidate.getCorrectionDeclAs<NamespaceDecl>())
return false;
return CorrectionCandidateCallback::ValidateCandidate(candidate);
}
std::unique_ptr<CorrectionCandidateCallback> clone() override {
return std::make_unique<StatementFilterCCC>(*this);
}
private:
Token NextToken;
};
}
StmtResult Parser::ParseStatementOrDeclarationAfterAttributes(
StmtVector &Stmts, ParsedStmtContext StmtCtx,
SourceLocation *TrailingElseLoc, ParsedAttributes &CXX11Attrs,
ParsedAttributes &GNUAttrs) {
const char *SemiError = nullptr;
StmtResult Res;
SourceLocation GNUAttributeLoc;
Retry:
tok::TokenKind Kind = Tok.getKind();
SourceLocation AtLoc;
switch (Kind) {
case tok::at: {
AtLoc = ConsumeToken(); return ParseObjCAtStatement(AtLoc, StmtCtx);
}
case tok::code_completion:
cutOffParsing();
Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
return StmtError();
case tok::identifier: {
Token Next = NextToken();
if (Next.is(tok::colon)) { ParsedAttributes Attrs(AttrFactory);
takeAndConcatenateAttrs(CXX11Attrs, GNUAttrs, Attrs);
return ParseLabeledStatement(Attrs, StmtCtx);
}
if (Next.isNot(tok::coloncolon)) {
StatementFilterCCC CCC(Next);
if (TryAnnotateName(&CCC) == ANK_Error) {
SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
if (Tok.is(tok::semi))
ConsumeToken();
return StmtError();
}
if (Tok.isNot(tok::identifier))
goto Retry;
}
LLVM_FALLTHROUGH;
}
default: {
bool HaveAttrs = !CXX11Attrs.empty() || !GNUAttrs.empty();
auto IsStmtAttr = [](ParsedAttr &Attr) { return Attr.isStmtAttr(); };
bool AllAttrsAreStmtAttrs = llvm::all_of(CXX11Attrs, IsStmtAttr) &&
llvm::all_of(GNUAttrs, IsStmtAttr);
if ((getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt ||
(StmtCtx & ParsedStmtContext::AllowDeclarationsInC) !=
ParsedStmtContext()) &&
((GNUAttributeLoc.isValid() && !(HaveAttrs && AllAttrsAreStmtAttrs)) ||
isDeclarationStatement())) {
SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
DeclGroupPtrTy Decl;
if (GNUAttributeLoc.isValid()) {
DeclStart = GNUAttributeLoc;
Decl = ParseDeclaration(DeclaratorContext::Block, DeclEnd, CXX11Attrs,
GNUAttrs, &GNUAttributeLoc);
} else {
Decl = ParseDeclaration(DeclaratorContext::Block, DeclEnd, CXX11Attrs,
GNUAttrs);
}
if (CXX11Attrs.Range.getBegin().isValid()) {
assert(GNUAttrs.Range.getBegin().isInvalid() ||
GNUAttrs.Range.getBegin() > CXX11Attrs.Range.getBegin());
DeclStart = CXX11Attrs.Range.getBegin();
} else if (GNUAttrs.Range.getBegin().isValid())
DeclStart = GNUAttrs.Range.getBegin();
return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
}
if (Tok.is(tok::r_brace)) {
Diag(Tok, diag::err_expected_statement);
return StmtError();
}
return ParseExprStatement(StmtCtx);
}
case tok::kw___attribute: {
GNUAttributeLoc = Tok.getLocation();
ParseGNUAttributes(GNUAttrs);
goto Retry;
}
case tok::kw_case: return ParseCaseStatement(StmtCtx);
case tok::kw_default: return ParseDefaultStatement(StmtCtx);
case tok::l_brace: return ParseCompoundStatement();
case tok::semi: { bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
}
case tok::kw_if: return ParseIfStatement(TrailingElseLoc);
case tok::kw_switch: return ParseSwitchStatement(TrailingElseLoc);
case tok::kw_while: return ParseWhileStatement(TrailingElseLoc);
case tok::kw_do: Res = ParseDoStatement();
SemiError = "do/while";
break;
case tok::kw_for: return ParseForStatement(TrailingElseLoc);
case tok::kw_goto: Res = ParseGotoStatement();
SemiError = "goto";
break;
case tok::kw_continue: Res = ParseContinueStatement();
SemiError = "continue";
break;
case tok::kw_break: Res = ParseBreakStatement();
SemiError = "break";
break;
case tok::kw_return: Res = ParseReturnStatement();
SemiError = "return";
break;
case tok::kw_co_return: Res = ParseReturnStatement();
SemiError = "co_return";
break;
case tok::kw_asm: {
for (const ParsedAttr &AL : CXX11Attrs)
Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
CXX11Attrs.clear();
ProhibitAttributes(GNUAttrs);
bool msAsm = false;
Res = ParseAsmStatement(msAsm);
if (msAsm) return Res;
SemiError = "asm";
break;
}
case tok::kw___if_exists:
case tok::kw___if_not_exists:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
ParseMicrosoftIfExistsStatement(Stmts);
return StmtEmpty();
case tok::kw_try: return ParseCXXTryBlock();
case tok::kw___try:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
return ParseSEHTryBlock();
case tok::kw___leave:
Res = ParseSEHLeaveStatement();
SemiError = "__leave";
break;
case tok::annot_pragma_vis:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
HandlePragmaVisibility();
return StmtEmpty();
case tok::annot_pragma_pack:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
HandlePragmaPack();
return StmtEmpty();
case tok::annot_pragma_msstruct:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
HandlePragmaMSStruct();
return StmtEmpty();
case tok::annot_pragma_align:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
HandlePragmaAlign();
return StmtEmpty();
case tok::annot_pragma_weak:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
HandlePragmaWeak();
return StmtEmpty();
case tok::annot_pragma_weakalias:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
HandlePragmaWeakAlias();
return StmtEmpty();
case tok::annot_pragma_redefine_extname:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
HandlePragmaRedefineExtname();
return StmtEmpty();
case tok::annot_pragma_fp_contract:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
Diag(Tok, diag::err_pragma_file_or_compound_scope) << "fp_contract";
ConsumeAnnotationToken();
return StmtError();
case tok::annot_pragma_fp:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
Diag(Tok, diag::err_pragma_file_or_compound_scope) << "clang fp";
ConsumeAnnotationToken();
return StmtError();
case tok::annot_pragma_fenv_access:
case tok::annot_pragma_fenv_access_ms:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
Diag(Tok, diag::err_pragma_file_or_compound_scope)
<< (Kind == tok::annot_pragma_fenv_access ? "STDC FENV_ACCESS"
: "fenv_access");
ConsumeAnnotationToken();
return StmtEmpty();
case tok::annot_pragma_fenv_round:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
Diag(Tok, diag::err_pragma_file_or_compound_scope) << "STDC FENV_ROUND";
ConsumeAnnotationToken();
return StmtError();
case tok::annot_pragma_float_control:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
Diag(Tok, diag::err_pragma_file_or_compound_scope) << "float_control";
ConsumeAnnotationToken();
return StmtError();
case tok::annot_pragma_opencl_extension:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
HandlePragmaOpenCLExtension();
return StmtEmpty();
case tok::annot_pragma_captured:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
return HandlePragmaCaptured();
case tok::annot_pragma_openmp:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
LLVM_FALLTHROUGH;
case tok::annot_attr_openmp:
return ParseOpenMPDeclarativeOrExecutableDirective(StmtCtx);
case tok::annot_pragma_ms_pointers_to_members:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
HandlePragmaMSPointersToMembers();
return StmtEmpty();
case tok::annot_pragma_ms_pragma:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
HandlePragmaMSPragma();
return StmtEmpty();
case tok::annot_pragma_ms_vtordisp:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
HandlePragmaMSVtorDisp();
return StmtEmpty();
case tok::annot_pragma_loop_hint:
ProhibitAttributes(CXX11Attrs);
ProhibitAttributes(GNUAttrs);
return ParsePragmaLoopHint(Stmts, StmtCtx, TrailingElseLoc, CXX11Attrs);
case tok::annot_pragma_dump:
HandlePragmaDump();
return StmtEmpty();
case tok::annot_pragma_attribute:
HandlePragmaAttribute();
return StmtEmpty();
}
if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
}
return Res;
}
StmtResult Parser::ParseExprStatement(ParsedStmtContext StmtCtx) {
Token OldToken = Tok;
ExprStatementTokLoc = Tok.getLocation();
ExprResult Expr(ParseExpression());
if (Expr.isInvalid()) {
SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
if (Tok.is(tok::semi))
ConsumeToken();
return Actions.ActOnExprStmtError();
}
if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
Actions.CheckCaseExpression(Expr.get())) {
Diag(OldToken, diag::err_expected_case_before_expression)
<< FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
return ParseCaseStatement(StmtCtx, true, Expr);
}
ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
return handleExprStmt(Expr, StmtCtx);
}
StmtResult Parser::ParseSEHTryBlock() {
assert(Tok.is(tok::kw___try) && "Expected '__try'");
SourceLocation TryLoc = ConsumeToken();
if (Tok.isNot(tok::l_brace))
return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
StmtResult TryBlock(ParseCompoundStatement(
false,
Scope::DeclScope | Scope::CompoundStmtScope | Scope::SEHTryScope));
if (TryBlock.isInvalid())
return TryBlock;
StmtResult Handler;
if (Tok.is(tok::identifier) &&
Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
SourceLocation Loc = ConsumeToken();
Handler = ParseSEHExceptBlock(Loc);
} else if (Tok.is(tok::kw___finally)) {
SourceLocation Loc = ConsumeToken();
Handler = ParseSEHFinallyBlock(Loc);
} else {
return StmtError(Diag(Tok, diag::err_seh_expected_handler));
}
if(Handler.isInvalid())
return Handler;
return Actions.ActOnSEHTryBlock(false ,
TryLoc,
TryBlock.get(),
Handler.get());
}
StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
raii2(Ident___exception_code, false),
raii3(Ident_GetExceptionCode, false);
if (ExpectAndConsume(tok::l_paren))
return StmtError();
ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
Scope::SEHExceptScope);
if (getLangOpts().Borland) {
Ident__exception_info->setIsPoisoned(false);
Ident___exception_info->setIsPoisoned(false);
Ident_GetExceptionInfo->setIsPoisoned(false);
}
ExprResult FilterExpr;
{
ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
Scope::SEHFilterScope);
FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
}
if (getLangOpts().Borland) {
Ident__exception_info->setIsPoisoned(true);
Ident___exception_info->setIsPoisoned(true);
Ident_GetExceptionInfo->setIsPoisoned(true);
}
if(FilterExpr.isInvalid())
return StmtError();
if (ExpectAndConsume(tok::r_paren))
return StmtError();
if (Tok.isNot(tok::l_brace))
return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
StmtResult Block(ParseCompoundStatement());
if(Block.isInvalid())
return Block;
return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
}
StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
raii2(Ident___abnormal_termination, false),
raii3(Ident_AbnormalTermination, false);
if (Tok.isNot(tok::l_brace))
return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
ParseScope FinallyScope(this, 0);
Actions.ActOnStartSEHFinallyBlock();
StmtResult Block(ParseCompoundStatement());
if(Block.isInvalid()) {
Actions.ActOnAbortSEHFinallyBlock();
return Block;
}
return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
}
StmtResult Parser::ParseSEHLeaveStatement() {
SourceLocation LeaveLoc = ConsumeToken(); return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
}
StmtResult Parser::ParseLabeledStatement(ParsedAttributes &Attrs,
ParsedStmtContext StmtCtx) {
assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
"Not an identifier!");
StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
Token IdentTok = Tok; ConsumeToken();
assert(Tok.is(tok::colon) && "Not a label!");
SourceLocation ColonLoc = ConsumeToken();
StmtResult SubStmt;
if (Tok.is(tok::kw___attribute)) {
ParsedAttributes TempAttrs(AttrFactory);
ParseGNUAttributes(TempAttrs);
if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
Attrs.takeAllFrom(TempAttrs);
else {
StmtVector Stmts;
ParsedAttributes EmptyCXX11Attrs(AttrFactory);
SubStmt = ParseStatementOrDeclarationAfterAttributes(
Stmts, StmtCtx, nullptr, EmptyCXX11Attrs, TempAttrs);
if (!TempAttrs.empty() && !SubStmt.isInvalid())
SubStmt = Actions.ActOnAttributedStmt(TempAttrs, SubStmt.get());
}
}
if (!SubStmt.isInvalid() && !SubStmt.isUsable())
SubStmt = ParseStatement(nullptr, StmtCtx);
if (SubStmt.isInvalid())
SubStmt = Actions.ActOnNullStmt(ColonLoc);
LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
IdentTok.getLocation());
Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Attrs.clear();
return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
SubStmt.get());
}
StmtResult Parser::ParseCaseStatement(ParsedStmtContext StmtCtx,
bool MissingCase, ExprResult Expr) {
assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
StmtResult TopLevelCase(true);
Stmt *DeepestParsedCaseStmt = nullptr;
SourceLocation ColonLoc;
do {
SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
ConsumeToken(); ColonLoc = SourceLocation();
if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompleteCase(getCurScope());
return StmtError();
}
ColonProtectionRAIIObject ColonProtection(*this);
ExprResult LHS;
if (!MissingCase) {
LHS = ParseCaseExpression(CaseLoc);
if (LHS.isInvalid()) {
if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
return StmtError();
}
} else {
LHS = Expr;
MissingCase = false;
}
SourceLocation DotDotDotLoc;
ExprResult RHS;
if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
Diag(DotDotDotLoc, diag::ext_gnu_case_range);
RHS = ParseCaseExpression(CaseLoc);
if (RHS.isInvalid()) {
if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
return StmtError();
}
}
ColonProtection.restore();
if (TryConsumeToken(tok::colon, ColonLoc)) {
} else if (TryConsumeToken(tok::semi, ColonLoc) ||
TryConsumeToken(tok::coloncolon, ColonLoc)) {
Diag(ColonLoc, diag::err_expected_after)
<< "'case'" << tok::colon
<< FixItHint::CreateReplacement(ColonLoc, ":");
} else {
SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Diag(ExpectedLoc, diag::err_expected_after)
<< "'case'" << tok::colon
<< FixItHint::CreateInsertion(ExpectedLoc, ":");
ColonLoc = ExpectedLoc;
}
StmtResult Case =
Actions.ActOnCaseStmt(CaseLoc, LHS, DotDotDotLoc, RHS, ColonLoc);
if (Case.isInvalid()) {
if (TopLevelCase.isInvalid()) return ParseStatement(nullptr, StmtCtx);
} else {
Stmt *NextDeepest = Case.get();
if (TopLevelCase.isInvalid())
TopLevelCase = Case;
else
Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
DeepestParsedCaseStmt = NextDeepest;
}
} while (Tok.is(tok::kw_case));
StmtResult SubStmt;
if (Tok.isNot(tok::r_brace)) {
SubStmt = ParseStatement(nullptr, StmtCtx);
} else {
if (ColonLoc.isValid()) {
SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
<< FixItHint::CreateInsertion(AfterColonLoc, " ;");
}
SubStmt = StmtError();
}
if (DeepestParsedCaseStmt) {
if (SubStmt.isInvalid())
SubStmt = Actions.ActOnNullStmt(SourceLocation());
Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
}
return TopLevelCase;
}
StmtResult Parser::ParseDefaultStatement(ParsedStmtContext StmtCtx) {
assert(Tok.is(tok::kw_default) && "Not a default stmt!");
StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
SourceLocation DefaultLoc = ConsumeToken();
SourceLocation ColonLoc;
if (TryConsumeToken(tok::colon, ColonLoc)) {
} else if (TryConsumeToken(tok::semi, ColonLoc)) {
Diag(ColonLoc, diag::err_expected_after)
<< "'default'" << tok::colon
<< FixItHint::CreateReplacement(ColonLoc, ":");
} else {
SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Diag(ExpectedLoc, diag::err_expected_after)
<< "'default'" << tok::colon
<< FixItHint::CreateInsertion(ExpectedLoc, ":");
ColonLoc = ExpectedLoc;
}
StmtResult SubStmt;
if (Tok.isNot(tok::r_brace)) {
SubStmt = ParseStatement(nullptr, StmtCtx);
} else {
SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
<< FixItHint::CreateInsertion(AfterColonLoc, " ;");
SubStmt = true;
}
if (SubStmt.isInvalid())
SubStmt = Actions.ActOnNullStmt(ColonLoc);
return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
SubStmt.get(), getCurScope());
}
StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
return ParseCompoundStatement(isStmtExpr,
Scope::DeclScope | Scope::CompoundStmtScope);
}
StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
unsigned ScopeFlags) {
assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
ParseScope CompoundScope(this, ScopeFlags);
return ParseCompoundStatementBody(isStmtExpr);
}
void Parser::ParseCompoundStatementLeadingPragmas() {
bool checkForPragmas = true;
while (checkForPragmas) {
switch (Tok.getKind()) {
case tok::annot_pragma_vis:
HandlePragmaVisibility();
break;
case tok::annot_pragma_pack:
HandlePragmaPack();
break;
case tok::annot_pragma_msstruct:
HandlePragmaMSStruct();
break;
case tok::annot_pragma_align:
HandlePragmaAlign();
break;
case tok::annot_pragma_weak:
HandlePragmaWeak();
break;
case tok::annot_pragma_weakalias:
HandlePragmaWeakAlias();
break;
case tok::annot_pragma_redefine_extname:
HandlePragmaRedefineExtname();
break;
case tok::annot_pragma_opencl_extension:
HandlePragmaOpenCLExtension();
break;
case tok::annot_pragma_fp_contract:
HandlePragmaFPContract();
break;
case tok::annot_pragma_fp:
HandlePragmaFP();
break;
case tok::annot_pragma_fenv_access:
case tok::annot_pragma_fenv_access_ms:
HandlePragmaFEnvAccess();
break;
case tok::annot_pragma_fenv_round:
HandlePragmaFEnvRound();
break;
case tok::annot_pragma_float_control:
HandlePragmaFloatControl();
break;
case tok::annot_pragma_ms_pointers_to_members:
HandlePragmaMSPointersToMembers();
break;
case tok::annot_pragma_ms_pragma:
HandlePragmaMSPragma();
break;
case tok::annot_pragma_ms_vtordisp:
HandlePragmaMSVtorDisp();
break;
case tok::annot_pragma_dump:
HandlePragmaDump();
break;
default:
checkForPragmas = false;
break;
}
}
}
bool Parser::ConsumeNullStmt(StmtVector &Stmts) {
if (!Tok.is(tok::semi))
return false;
SourceLocation StartLoc = Tok.getLocation();
SourceLocation EndLoc;
while (Tok.is(tok::semi) && !Tok.hasLeadingEmptyMacro() &&
Tok.getLocation().isValid() && !Tok.getLocation().isMacroID()) {
EndLoc = Tok.getLocation();
StmtResult R =
ParseStatementOrDeclaration(Stmts, ParsedStmtContext::SubStmt);
if (R.isUsable())
Stmts.push_back(R.get());
}
if (EndLoc.isInvalid())
return false;
Diag(StartLoc, diag::warn_null_statement)
<< FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
return true;
}
StmtResult Parser::handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx) {
bool IsStmtExprResult = false;
if ((StmtCtx & ParsedStmtContext::InStmtExpr) != ParsedStmtContext()) {
unsigned LookAhead = 0;
while (GetLookAheadToken(LookAhead).is(tok::semi)) {
++LookAhead;
}
IsStmtExprResult = GetLookAheadToken(LookAhead).is(tok::r_brace) &&
GetLookAheadToken(LookAhead + 1).is(tok::r_paren);
}
if (IsStmtExprResult)
E = Actions.ActOnStmtExprResult(E);
return Actions.ActOnExprStmt(E, !IsStmtExprResult);
}
StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Tok.getLocation(),
"in compound statement ('{}')");
Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
InMessageExpressionRAIIObject InMessage(*this, false);
BalancedDelimiterTracker T(*this, tok::l_brace);
if (T.consumeOpen())
return StmtError();
Sema::CompoundScopeRAII CompoundScope(Actions, isStmtExpr);
ParseCompoundStatementLeadingPragmas();
Actions.ActOnAfterCompoundStatementLeadingPragmas();
StmtVector Stmts;
while (Tok.is(tok::kw___label__)) {
SourceLocation LabelLoc = ConsumeToken();
SmallVector<Decl *, 8> DeclsInGroup;
while (true) {
if (Tok.isNot(tok::identifier)) {
Diag(Tok, diag::err_expected) << tok::identifier;
break;
}
IdentifierInfo *II = Tok.getIdentifierInfo();
SourceLocation IdLoc = ConsumeToken();
DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
if (!TryConsumeToken(tok::comma))
break;
}
DeclSpec DS(AttrFactory);
DeclGroupPtrTy Res =
Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
if (R.isUsable())
Stmts.push_back(R.get());
}
ParsedStmtContext SubStmtCtx =
ParsedStmtContext::Compound |
(isStmtExpr ? ParsedStmtContext::InStmtExpr : ParsedStmtContext());
while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
Tok.isNot(tok::eof)) {
if (Tok.is(tok::annot_pragma_unused)) {
HandlePragmaUnused();
continue;
}
if (ConsumeNullStmt(Stmts))
continue;
StmtResult R;
if (Tok.isNot(tok::kw___extension__)) {
R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
} else {
SourceLocation ExtLoc = ConsumeToken();
while (Tok.is(tok::kw___extension__))
ConsumeToken();
ParsedAttributes attrs(AttrFactory);
MaybeParseCXX11Attributes(attrs, true);
if (isDeclarationStatement()) {
ExtensionRAIIObject O(Diags);
SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
ParsedAttributes DeclSpecAttrs(AttrFactory);
DeclGroupPtrTy Res = ParseDeclaration(DeclaratorContext::Block, DeclEnd,
attrs, DeclSpecAttrs);
R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
} else {
ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
if (Res.isInvalid()) {
SkipUntil(tok::semi);
continue;
}
ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
R = handleExprStmt(Res, SubStmtCtx);
if (R.isUsable())
R = Actions.ActOnAttributedStmt(attrs, R.get());
}
}
if (R.isUsable())
Stmts.push_back(R.get());
}
if (!PP.getTargetInfo().supportSourceEvalMethod() &&
(PP.getLastFPEvalPragmaLocation().isValid() ||
PP.getCurrentFPEvalMethod() ==
LangOptions::FPEvalMethodKind::FEM_Source))
Diag(Tok.getLocation(),
diag::warn_no_support_for_eval_method_source_on_m32);
SourceLocation CloseLoc = Tok.getLocation();
if (!T.consumeClose()) {
if (isStmtExpr && Tok.is(tok::r_paren))
checkCompoundToken(CloseLoc, tok::r_brace, CompoundToken::StmtExprEnd);
} else {
}
if (T.getCloseLocation().isValid())
CloseLoc = T.getCloseLocation();
return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Stmts, isStmtExpr);
}
bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
Sema::ConditionResult &Cond,
SourceLocation Loc,
Sema::ConditionKind CK, bool MissingOK,
SourceLocation *LParenLoc,
SourceLocation *RParenLoc) {
BalancedDelimiterTracker T(*this, tok::l_paren);
T.consumeOpen();
SourceLocation Start = Tok.getLocation();
if (getLangOpts().CPlusPlus) {
Cond = ParseCXXCondition(InitStmt, Loc, CK, MissingOK);
} else {
ExprResult CondExpr = ParseExpression();
if (CondExpr.isInvalid())
Cond = Sema::ConditionError();
else
Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK,
MissingOK);
}
if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) {
SkipUntil(tok::semi);
if (Tok.isNot(tok::r_paren))
return true;
}
if (Cond.isInvalid()) {
ExprResult CondExpr = Actions.CreateRecoveryExpr(
Start, Tok.getLocation() == Start ? Start : PrevTokLocation, {},
Actions.PreferredConditionType(CK));
if (!CondExpr.isInvalid())
Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK,
MissingOK);
}
T.consumeClose();
if (LParenLoc != nullptr) {
*LParenLoc = T.getOpenLocation();
}
if (RParenLoc != nullptr) {
*RParenLoc = T.getCloseLocation();
}
while (Tok.is(tok::r_paren)) {
Diag(Tok, diag::err_extraneous_rparen_in_condition)
<< FixItHint::CreateRemoval(Tok.getLocation());
ConsumeParen();
}
return false;
}
namespace {
enum MisleadingStatementKind { MSK_if, MSK_else, MSK_for, MSK_while };
struct MisleadingIndentationChecker {
Parser &P;
SourceLocation StmtLoc;
SourceLocation PrevLoc;
unsigned NumDirectives;
MisleadingStatementKind Kind;
bool ShouldSkip;
MisleadingIndentationChecker(Parser &P, MisleadingStatementKind K,
SourceLocation SL)
: P(P), StmtLoc(SL), PrevLoc(P.getCurToken().getLocation()),
NumDirectives(P.getPreprocessor().getNumDirectives()), Kind(K),
ShouldSkip(P.getCurToken().is(tok::l_brace)) {
if (!P.MisleadingIndentationElseLoc.isInvalid()) {
StmtLoc = P.MisleadingIndentationElseLoc;
P.MisleadingIndentationElseLoc = SourceLocation();
}
if (Kind == MSK_else && !ShouldSkip)
P.MisleadingIndentationElseLoc = SL;
}
static unsigned getVisualIndentation(SourceManager &SM, SourceLocation Loc) {
unsigned TabStop = SM.getDiagnostics().getDiagnosticOptions().TabStop;
unsigned ColNo = SM.getSpellingColumnNumber(Loc);
if (ColNo == 0 || TabStop == 1)
return ColNo;
std::pair<FileID, unsigned> FIDAndOffset = SM.getDecomposedLoc(Loc);
bool Invalid;
StringRef BufData = SM.getBufferData(FIDAndOffset.first, &Invalid);
if (Invalid)
return 0;
const char *EndPos = BufData.data() + FIDAndOffset.second;
assert(FIDAndOffset.second + 1 >= ColNo &&
"Column number smaller than file offset?");
unsigned VisualColumn = 0; for (const char *CurPos = EndPos - (ColNo - 1); CurPos != EndPos;
++CurPos) {
if (*CurPos == '\t')
VisualColumn += (TabStop - VisualColumn % TabStop);
else
VisualColumn++;
}
return VisualColumn + 1;
}
void Check() {
Token Tok = P.getCurToken();
if (P.getActions().getDiagnostics().isIgnored(
diag::warn_misleading_indentation, Tok.getLocation()) ||
ShouldSkip || NumDirectives != P.getPreprocessor().getNumDirectives() ||
Tok.isOneOf(tok::semi, tok::r_brace) || Tok.isAnnotation() ||
Tok.getLocation().isMacroID() || PrevLoc.isMacroID() ||
StmtLoc.isMacroID() ||
(Kind == MSK_else && P.MisleadingIndentationElseLoc.isInvalid())) {
P.MisleadingIndentationElseLoc = SourceLocation();
return;
}
if (Kind == MSK_else)
P.MisleadingIndentationElseLoc = SourceLocation();
SourceManager &SM = P.getPreprocessor().getSourceManager();
unsigned PrevColNum = getVisualIndentation(SM, PrevLoc);
unsigned CurColNum = getVisualIndentation(SM, Tok.getLocation());
unsigned StmtColNum = getVisualIndentation(SM, StmtLoc);
if (PrevColNum != 0 && CurColNum != 0 && StmtColNum != 0 &&
((PrevColNum > StmtColNum && PrevColNum == CurColNum) ||
!Tok.isAtStartOfLine()) &&
SM.getPresumedLineNumber(StmtLoc) !=
SM.getPresumedLineNumber(Tok.getLocation()) &&
(Tok.isNot(tok::identifier) ||
P.getPreprocessor().LookAhead(0).isNot(tok::colon))) {
P.Diag(Tok.getLocation(), diag::warn_misleading_indentation) << Kind;
P.Diag(StmtLoc, diag::note_previous_statement);
}
}
};
}
StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
assert(Tok.is(tok::kw_if) && "Not an if stmt!");
SourceLocation IfLoc = ConsumeToken();
bool IsConstexpr = false;
bool IsConsteval = false;
SourceLocation NotLocation;
SourceLocation ConstevalLoc;
if (Tok.is(tok::kw_constexpr)) {
Diag(Tok, getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_constexpr_if
: diag::ext_constexpr_if);
IsConstexpr = true;
ConsumeToken();
} else {
if (Tok.is(tok::exclaim)) {
NotLocation = ConsumeToken();
}
if (Tok.is(tok::kw_consteval)) {
Diag(Tok, getLangOpts().CPlusPlus2b ? diag::warn_cxx20_compat_consteval_if
: diag::ext_consteval_if);
IsConsteval = true;
ConstevalLoc = ConsumeToken();
}
}
if (!IsConsteval && (NotLocation.isValid() || Tok.isNot(tok::l_paren))) {
Diag(Tok, diag::err_expected_lparen_after) << "if";
SkipUntil(tok::semi);
return StmtError();
}
bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
StmtResult InitStmt;
Sema::ConditionResult Cond;
SourceLocation LParen;
SourceLocation RParen;
llvm::Optional<bool> ConstexprCondition;
if (!IsConsteval) {
if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
IsConstexpr ? Sema::ConditionKind::ConstexprIf
: Sema::ConditionKind::Boolean,
false, &LParen, &RParen))
return StmtError();
if (IsConstexpr)
ConstexprCondition = Cond.getKnownValue();
}
bool IsBracedThen = Tok.is(tok::l_brace);
ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, IsBracedThen);
MisleadingIndentationChecker MIChecker(*this, MSK_if, IfLoc);
SourceLocation ThenStmtLoc = Tok.getLocation();
SourceLocation InnerStatementTrailingElseLoc;
StmtResult ThenStmt;
{
bool ShouldEnter = ConstexprCondition && !*ConstexprCondition;
Sema::ExpressionEvaluationContext Context =
Sema::ExpressionEvaluationContext::DiscardedStatement;
if (NotLocation.isInvalid() && IsConsteval) {
Context = Sema::ExpressionEvaluationContext::ImmediateFunctionContext;
ShouldEnter = true;
}
EnterExpressionEvaluationContext PotentiallyDiscarded(
Actions, Context, nullptr,
Sema::ExpressionEvaluationContextRecord::EK_Other, ShouldEnter);
ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
}
if (Tok.isNot(tok::kw_else))
MIChecker.Check();
InnerScope.Exit();
SourceLocation ElseLoc;
SourceLocation ElseStmtLoc;
StmtResult ElseStmt;
if (Tok.is(tok::kw_else)) {
if (TrailingElseLoc)
*TrailingElseLoc = Tok.getLocation();
ElseLoc = ConsumeToken();
ElseStmtLoc = Tok.getLocation();
ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
Tok.is(tok::l_brace));
MisleadingIndentationChecker MIChecker(*this, MSK_else, ElseLoc);
bool ShouldEnter = ConstexprCondition && *ConstexprCondition;
Sema::ExpressionEvaluationContext Context =
Sema::ExpressionEvaluationContext::DiscardedStatement;
if (NotLocation.isValid() && IsConsteval) {
Context = Sema::ExpressionEvaluationContext::ImmediateFunctionContext;
ShouldEnter = true;
}
EnterExpressionEvaluationContext PotentiallyDiscarded(
Actions, Context, nullptr,
Sema::ExpressionEvaluationContextRecord::EK_Other, ShouldEnter);
ElseStmt = ParseStatement();
if (ElseStmt.isUsable())
MIChecker.Check();
InnerScope.Exit();
} else if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompleteAfterIf(getCurScope(), IsBracedThen);
return StmtError();
} else if (InnerStatementTrailingElseLoc.isValid()) {
Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
}
IfScope.Exit();
if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
(ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
(ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
return StmtError();
}
if (IsConsteval) {
auto IsCompoundStatement = [](const Stmt *S) {
if (const auto *Outer = dyn_cast_or_null<AttributedStmt>(S))
S = Outer->getSubStmt();
return isa_and_nonnull<clang::CompoundStmt>(S);
};
if (!IsCompoundStatement(ThenStmt.get())) {
Diag(ConstevalLoc, diag::err_expected_after) << "consteval"
<< "{";
return StmtError();
}
if (!ElseStmt.isUnset() && !IsCompoundStatement(ElseStmt.get())) {
Diag(ElseLoc, diag::err_expected_after) << "else"
<< "{";
return StmtError();
}
}
if (ThenStmt.isInvalid())
ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
if (ElseStmt.isInvalid())
ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
IfStatementKind Kind = IfStatementKind::Ordinary;
if (IsConstexpr)
Kind = IfStatementKind::Constexpr;
else if (IsConsteval)
Kind = NotLocation.isValid() ? IfStatementKind::ConstevalNegated
: IfStatementKind::ConstevalNonNegated;
return Actions.ActOnIfStmt(IfLoc, Kind, LParen, InitStmt.get(), Cond, RParen,
ThenStmt.get(), ElseLoc, ElseStmt.get());
}
StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
SourceLocation SwitchLoc = ConsumeToken();
if (Tok.isNot(tok::l_paren)) {
Diag(Tok, diag::err_expected_lparen_after) << "switch";
SkipUntil(tok::semi);
return StmtError();
}
bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
unsigned ScopeFlags = Scope::SwitchScope;
if (C99orCXX)
ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
ParseScope SwitchScope(this, ScopeFlags);
StmtResult InitStmt;
Sema::ConditionResult Cond;
SourceLocation LParen;
SourceLocation RParen;
if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
Sema::ConditionKind::Switch,
false, &LParen, &RParen))
return StmtError();
StmtResult Switch = Actions.ActOnStartOfSwitchStmt(
SwitchLoc, LParen, InitStmt.get(), Cond, RParen);
if (Switch.isInvalid()) {
if (Tok.is(tok::l_brace)) {
ConsumeBrace();
SkipUntil(tok::r_brace);
} else
SkipUntil(tok::semi);
return Switch;
}
getCurScope()->AddFlags(Scope::BreakScope);
ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
if (C99orCXX)
getCurScope()->decrementMSManglingNumber();
StmtResult Body(ParseStatement(TrailingElseLoc));
InnerScope.Exit();
SwitchScope.Exit();
return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
}
StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
assert(Tok.is(tok::kw_while) && "Not a while stmt!");
SourceLocation WhileLoc = Tok.getLocation();
ConsumeToken();
if (Tok.isNot(tok::l_paren)) {
Diag(Tok, diag::err_expected_lparen_after) << "while";
SkipUntil(tok::semi);
return StmtError();
}
bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
unsigned ScopeFlags;
if (C99orCXX)
ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
Scope::DeclScope | Scope::ControlScope;
else
ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
ParseScope WhileScope(this, ScopeFlags);
Sema::ConditionResult Cond;
SourceLocation LParen;
SourceLocation RParen;
if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
Sema::ConditionKind::Boolean,
false, &LParen, &RParen))
return StmtError();
ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
MisleadingIndentationChecker MIChecker(*this, MSK_while, WhileLoc);
StmtResult Body(ParseStatement(TrailingElseLoc));
if (Body.isUsable())
MIChecker.Check();
InnerScope.Exit();
WhileScope.Exit();
if (Cond.isInvalid() || Body.isInvalid())
return StmtError();
return Actions.ActOnWhileStmt(WhileLoc, LParen, Cond, RParen, Body.get());
}
StmtResult Parser::ParseDoStatement() {
assert(Tok.is(tok::kw_do) && "Not a do stmt!");
SourceLocation DoLoc = ConsumeToken();
unsigned ScopeFlags;
if (getLangOpts().C99)
ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
else
ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
ParseScope DoScope(this, ScopeFlags);
bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
StmtResult Body(ParseStatement());
InnerScope.Exit();
if (Tok.isNot(tok::kw_while)) {
if (!Body.isInvalid()) {
Diag(Tok, diag::err_expected_while);
Diag(DoLoc, diag::note_matching) << "'do'";
SkipUntil(tok::semi, StopBeforeMatch);
}
return StmtError();
}
SourceLocation WhileLoc = ConsumeToken();
if (Tok.isNot(tok::l_paren)) {
Diag(Tok, diag::err_expected_lparen_after) << "do/while";
SkipUntil(tok::semi, StopBeforeMatch);
return StmtError();
}
BalancedDelimiterTracker T(*this, tok::l_paren);
T.consumeOpen();
DiagnoseAndSkipCXX11Attributes();
SourceLocation Start = Tok.getLocation();
ExprResult Cond = ParseExpression();
if (Cond.isUsable())
Cond = Actions.CorrectDelayedTyposInExpr(Cond);
else {
if (!Tok.isOneOf(tok::r_paren, tok::r_square, tok::r_brace))
SkipUntil(tok::semi);
Cond = Actions.CreateRecoveryExpr(
Start, Start == Tok.getLocation() ? Start : PrevTokLocation, {},
Actions.getASTContext().BoolTy);
}
T.consumeClose();
DoScope.Exit();
if (Cond.isInvalid() || Body.isInvalid())
return StmtError();
return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
Cond.get(), T.getCloseLocation());
}
bool Parser::isForRangeIdentifier() {
assert(Tok.is(tok::identifier));
const Token &Next = NextToken();
if (Next.is(tok::colon))
return true;
if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
TentativeParsingAction PA(*this);
ConsumeToken();
SkipCXX11Attributes();
bool Result = Tok.is(tok::colon);
PA.Revert();
return Result;
}
return false;
}
StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
assert(Tok.is(tok::kw_for) && "Not a for stmt!");
SourceLocation ForLoc = ConsumeToken();
SourceLocation CoawaitLoc;
if (Tok.is(tok::kw_co_await))
CoawaitLoc = ConsumeToken();
if (Tok.isNot(tok::l_paren)) {
Diag(Tok, diag::err_expected_lparen_after) << "for";
SkipUntil(tok::semi);
return StmtError();
}
bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
getLangOpts().ObjC;
unsigned ScopeFlags = 0;
if (C99orCXXorObjC)
ScopeFlags = Scope::DeclScope | Scope::ControlScope;
ParseScope ForScope(this, ScopeFlags);
BalancedDelimiterTracker T(*this, tok::l_paren);
T.consumeOpen();
ExprResult Value;
bool ForEach = false;
StmtResult FirstPart;
Sema::ConditionResult SecondPart;
ExprResult Collection;
ForRangeInfo ForRangeInfo;
FullExprArg ThirdPart(Actions);
if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompleteOrdinaryName(getCurScope(),
C99orCXXorObjC? Sema::PCC_ForInit
: Sema::PCC_Expression);
return StmtError();
}
ParsedAttributes attrs(AttrFactory);
MaybeParseCXX11Attributes(attrs);
SourceLocation EmptyInitStmtSemiLoc;
if (Tok.is(tok::semi)) { ProhibitAttributes(attrs);
SourceLocation SemiLoc = Tok.getLocation();
if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID())
EmptyInitStmtSemiLoc = SemiLoc;
ConsumeToken();
} else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
isForRangeIdentifier()) {
ProhibitAttributes(attrs);
IdentifierInfo *Name = Tok.getIdentifierInfo();
SourceLocation Loc = ConsumeToken();
MaybeParseCXX11Attributes(attrs);
ForRangeInfo.ColonLoc = ConsumeToken();
if (Tok.is(tok::l_brace))
ForRangeInfo.RangeExpr = ParseBraceInitializer();
else
ForRangeInfo.RangeExpr = ParseExpression();
Diag(Loc, diag::err_for_range_identifier)
<< ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17)
? FixItHint::CreateInsertion(Loc, "auto &&")
: FixItHint());
ForRangeInfo.LoopVar =
Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name, attrs);
} else if (isForInitDeclaration()) { ParenBraceBracketBalancer BalancerRAIIObj(*this);
if (!C99orCXXorObjC) { Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Diag(Tok, diag::warn_gcc_variable_decl_in_for_loop);
}
DeclGroupPtrTy DG;
if (Tok.is(tok::kw_using)) {
DG = ParseAliasDeclarationInInitStatement(DeclaratorContext::ForInit,
attrs);
} else {
bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
ParsedAttributes DeclSpecAttrs(AttrFactory);
DG = ParseSimpleDeclaration(
DeclaratorContext::ForInit, DeclEnd, attrs, DeclSpecAttrs, false,
MightBeForRangeStmt ? &ForRangeInfo : nullptr);
FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
if (ForRangeInfo.ParsedForRangeDecl()) {
Diag(ForRangeInfo.ColonLoc, getLangOpts().CPlusPlus11
? diag::warn_cxx98_compat_for_range
: diag::ext_for_range);
ForRangeInfo.LoopVar = FirstPart;
FirstPart = StmtResult();
} else if (Tok.is(tok::semi)) { ConsumeToken();
} else if ((ForEach = isTokIdentifier_in())) {
Actions.ActOnForEachDeclStmt(DG);
ConsumeToken();
if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
return StmtError();
}
Collection = ParseExpression();
} else {
Diag(Tok, diag::err_expected_semi_for);
}
}
} else {
ProhibitAttributes(attrs);
Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
ForEach = isTokIdentifier_in();
if (!Value.isInvalid()) {
if (ForEach)
FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
else {
bool IsRangeBasedFor =
getLangOpts().CPlusPlus11 && !ForEach && Tok.is(tok::colon);
FirstPart = Actions.ActOnExprStmt(Value, !IsRangeBasedFor);
}
}
if (Tok.is(tok::semi)) {
ConsumeToken();
} else if (ForEach) {
ConsumeToken();
if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr);
return StmtError();
}
Collection = ParseExpression();
} else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Diag(Tok, diag::err_for_range_expected_decl)
<< FirstPart.get()->getSourceRange();
SkipUntil(tok::r_paren, StopBeforeMatch);
SecondPart = Sema::ConditionError();
} else {
if (!Value.isInvalid()) {
Diag(Tok, diag::err_expected_semi_for);
} else {
SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
if (Tok.is(tok::semi))
ConsumeToken();
}
}
}
if (!ForEach && !ForRangeInfo.ParsedForRangeDecl() &&
!SecondPart.isInvalid()) {
if (Tok.is(tok::semi)) { } else if (Tok.is(tok::r_paren)) {
} else {
if (getLangOpts().CPlusPlus) {
bool MightBeForRangeStmt = !ForRangeInfo.ParsedForRangeDecl();
ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
SecondPart = ParseCXXCondition(
nullptr, ForLoc, Sema::ConditionKind::Boolean,
true, MightBeForRangeStmt ? &ForRangeInfo : nullptr,
true);
if (ForRangeInfo.ParsedForRangeDecl()) {
Diag(FirstPart.get() ? FirstPart.get()->getBeginLoc()
: ForRangeInfo.ColonLoc,
getLangOpts().CPlusPlus20
? diag::warn_cxx17_compat_for_range_init_stmt
: diag::ext_for_range_init_stmt)
<< (FirstPart.get() ? FirstPart.get()->getSourceRange()
: SourceRange());
if (EmptyInitStmtSemiLoc.isValid()) {
Diag(EmptyInitStmtSemiLoc, diag::warn_empty_init_statement)
<< 2
<< FixItHint::CreateRemoval(EmptyInitStmtSemiLoc);
}
}
} else {
getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
ExprResult SecondExpr = ParseExpression();
if (SecondExpr.isInvalid())
SecondPart = Sema::ConditionError();
else
SecondPart = Actions.ActOnCondition(
getCurScope(), ForLoc, SecondExpr.get(),
Sema::ConditionKind::Boolean, true);
}
}
}
if (!getCurScope()->isContinueScope())
getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
if (!ForEach && !ForRangeInfo.ParsedForRangeDecl()) {
if (Tok.isNot(tok::semi)) {
if (!SecondPart.isInvalid())
Diag(Tok, diag::err_expected_semi_for);
else
SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
}
if (Tok.is(tok::semi)) {
ConsumeToken();
}
if (Tok.isNot(tok::r_paren)) { ExprResult Third = ParseExpression();
ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
}
}
T.consumeClose();
if (CoawaitLoc.isValid() && !ForRangeInfo.ParsedForRangeDecl()) {
Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
CoawaitLoc = SourceLocation();
}
if (CoawaitLoc.isValid() && getLangOpts().CPlusPlus20)
Diag(CoawaitLoc, diag::warn_deprecated_for_co_await);
StmtResult ForRangeStmt;
StmtResult ForEachStmt;
if (ForRangeInfo.ParsedForRangeDecl()) {
ExprResult CorrectedRange =
Actions.CorrectDelayedTyposInExpr(ForRangeInfo.RangeExpr.get());
ForRangeStmt = Actions.ActOnCXXForRangeStmt(
getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
ForRangeInfo.LoopVar.get(), ForRangeInfo.ColonLoc, CorrectedRange.get(),
T.getCloseLocation(), Sema::BFRK_Build);
} else if (ForEach) {
ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
FirstPart.get(),
Collection.get(),
T.getCloseLocation());
} else {
if (getLangOpts().OpenMP && FirstPart.isUsable()) {
Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
}
}
ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
Tok.is(tok::l_brace));
if (C99orCXXorObjC)
getCurScope()->decrementMSManglingNumber();
MisleadingIndentationChecker MIChecker(*this, MSK_for, ForLoc);
StmtResult Body(ParseStatement(TrailingElseLoc));
if (Body.isUsable())
MIChecker.Check();
InnerScope.Exit();
ForScope.Exit();
if (Body.isInvalid())
return StmtError();
if (ForEach)
return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
Body.get());
if (ForRangeInfo.ParsedForRangeDecl())
return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
SecondPart, ThirdPart, T.getCloseLocation(),
Body.get());
}
StmtResult Parser::ParseGotoStatement() {
assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
SourceLocation GotoLoc = ConsumeToken();
StmtResult Res;
if (Tok.is(tok::identifier)) {
LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
Tok.getLocation());
Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
ConsumeToken();
} else if (Tok.is(tok::star)) {
Diag(Tok, diag::ext_gnu_indirect_goto);
SourceLocation StarLoc = ConsumeToken();
ExprResult R(ParseExpression());
if (R.isInvalid()) { SkipUntil(tok::semi, StopBeforeMatch);
return StmtError();
}
Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
} else {
Diag(Tok, diag::err_expected) << tok::identifier;
return StmtError();
}
return Res;
}
StmtResult Parser::ParseContinueStatement() {
SourceLocation ContinueLoc = ConsumeToken(); return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
}
StmtResult Parser::ParseBreakStatement() {
SourceLocation BreakLoc = ConsumeToken(); return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
}
StmtResult Parser::ParseReturnStatement() {
assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
"Not a return stmt!");
bool IsCoreturn = Tok.is(tok::kw_co_return);
SourceLocation ReturnLoc = ConsumeToken();
ExprResult R;
if (Tok.isNot(tok::semi)) {
if (!IsCoreturn)
PreferredType.enterReturn(Actions, Tok.getLocation());
if (Tok.is(tok::code_completion) && !IsCoreturn) {
cutOffParsing();
Actions.CodeCompleteExpression(getCurScope(),
PreferredType.get(Tok.getLocation()));
return StmtError();
}
if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
R = ParseInitializer();
if (R.isUsable())
Diag(R.get()->getBeginLoc(),
getLangOpts().CPlusPlus11
? diag::warn_cxx98_compat_generalized_initializer_lists
: diag::ext_generalized_initializer_lists)
<< R.get()->getSourceRange();
} else
R = ParseExpression();
if (R.isInvalid()) {
SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
return StmtError();
}
}
if (IsCoreturn)
return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get());
return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
}
StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
ParsedStmtContext StmtCtx,
SourceLocation *TrailingElseLoc,
ParsedAttributes &Attrs) {
ParsedAttributes TempAttrs(AttrFactory);
SourceLocation StartLoc = Tok.getLocation();
while (Tok.is(tok::annot_pragma_loop_hint)) {
LoopHint Hint;
if (!HandlePragmaLoopHint(Hint))
continue;
ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
ArgsUnion(Hint.ValueExpr)};
TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
Hint.PragmaNameLoc->Loc, ArgHints, 4,
ParsedAttr::AS_Pragma);
}
MaybeParseCXX11Attributes(Attrs);
ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
StmtResult S = ParseStatementOrDeclarationAfterAttributes(
Stmts, StmtCtx, TrailingElseLoc, Attrs, EmptyDeclSpecAttrs);
Attrs.takeAllFrom(TempAttrs);
if (Attrs.Range.getBegin().isInvalid())
Attrs.Range.setBegin(StartLoc);
return S;
}
Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
assert(Tok.is(tok::l_brace));
SourceLocation LBraceLoc = Tok.getLocation();
PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, LBraceLoc,
"parsing function body");
bool IsCXXMethod =
getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
Sema::PragmaStackSentinelRAII
PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
StmtResult FnBody(ParseCompoundStatementBody());
if (FnBody.isInvalid()) {
Sema::CompoundScopeRAII CompoundScope(Actions);
FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
}
BodyScope.Exit();
return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
}
Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
assert(Tok.is(tok::kw_try) && "Expected 'try'");
SourceLocation TryLoc = ConsumeToken();
PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, TryLoc,
"parsing function try block");
if (Tok.is(tok::colon))
ParseConstructorInitializer(Decl);
else
Actions.ActOnDefaultCtorInitializers(Decl);
bool IsCXXMethod =
getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
Sema::PragmaStackSentinelRAII
PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
SourceLocation LBraceLoc = Tok.getLocation();
StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, true));
if (FnBody.isInvalid()) {
Sema::CompoundScopeRAII CompoundScope(Actions);
FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
}
BodyScope.Exit();
return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
}
bool Parser::trySkippingFunctionBody() {
assert(SkipFunctionBodies &&
"Should only be called when SkipFunctionBodies is enabled");
if (!PP.isCodeCompletionEnabled()) {
SkipFunctionBody();
return true;
}
TentativeParsingAction PA(*this);
bool IsTryCatch = Tok.is(tok::kw_try);
CachedTokens Toks;
bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
if (llvm::any_of(Toks, [](const Token &Tok) {
return Tok.is(tok::code_completion);
})) {
PA.Revert();
return false;
}
if (ErrorInPrologue) {
PA.Commit();
SkipMalformedDecl();
return true;
}
if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
PA.Revert();
return false;
}
while (IsTryCatch && Tok.is(tok::kw_catch)) {
if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
PA.Revert();
return false;
}
}
PA.Commit();
return true;
}
StmtResult Parser::ParseCXXTryBlock() {
assert(Tok.is(tok::kw_try) && "Expected 'try'");
SourceLocation TryLoc = ConsumeToken();
return ParseCXXTryBlockCommon(TryLoc);
}
StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
if (Tok.isNot(tok::l_brace))
return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
StmtResult TryBlock(ParseCompoundStatement(
false, Scope::DeclScope | Scope::TryScope |
Scope::CompoundStmtScope |
(FnTry ? Scope::FnTryCatchScope : 0)));
if (TryBlock.isInvalid())
return TryBlock;
if ((Tok.is(tok::identifier) &&
Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
Tok.is(tok::kw___finally)) {
StmtResult Handler;
if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
SourceLocation Loc = ConsumeToken();
Handler = ParseSEHExceptBlock(Loc);
}
else {
SourceLocation Loc = ConsumeToken();
Handler = ParseSEHFinallyBlock(Loc);
}
if(Handler.isInvalid())
return Handler;
return Actions.ActOnSEHTryBlock(true ,
TryLoc,
TryBlock.get(),
Handler.get());
}
else {
StmtVector Handlers;
DiagnoseAndSkipCXX11Attributes();
if (Tok.isNot(tok::kw_catch))
return StmtError(Diag(Tok, diag::err_expected_catch));
while (Tok.is(tok::kw_catch)) {
StmtResult Handler(ParseCXXCatchBlock(FnTry));
if (!Handler.isInvalid())
Handlers.push_back(Handler.get());
}
if (Handlers.empty())
return StmtError();
return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
}
}
StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
SourceLocation CatchLoc = ConsumeToken();
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.expectAndConsume())
return StmtError();
ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
Scope::CatchScope |
(FnCatch ? Scope::FnTryCatchScope : 0));
Decl *ExceptionDecl = nullptr;
if (Tok.isNot(tok::ellipsis)) {
ParsedAttributes Attributes(AttrFactory);
MaybeParseCXX11Attributes(Attributes);
DeclSpec DS(AttrFactory);
if (ParseCXXTypeSpecifierSeq(DS))
return StmtError();
Declarator ExDecl(DS, Attributes, DeclaratorContext::CXXCatch);
ParseDeclarator(ExDecl);
ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
} else
ConsumeToken();
T.consumeClose();
if (T.getCloseLocation().isInvalid())
return StmtError();
if (Tok.isNot(tok::l_brace))
return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
StmtResult Block(ParseCompoundStatement());
if (Block.isInvalid())
return Block;
return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
}
void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
IfExistsCondition Result;
if (ParseMicrosoftIfExistsCondition(Result))
return;
if (Result.Behavior == IEB_Dependent) {
if (!Tok.is(tok::l_brace)) {
Diag(Tok, diag::err_expected) << tok::l_brace;
return;
}
StmtResult Compound = ParseCompoundStatement();
if (Compound.isInvalid())
return;
StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
Result.IsIfExists,
Result.SS,
Result.Name,
Compound.get());
if (DepResult.isUsable())
Stmts.push_back(DepResult.get());
return;
}
BalancedDelimiterTracker Braces(*this, tok::l_brace);
if (Braces.consumeOpen()) {
Diag(Tok, diag::err_expected) << tok::l_brace;
return;
}
switch (Result.Behavior) {
case IEB_Parse:
break;
case IEB_Dependent:
llvm_unreachable("Dependent case handled above");
case IEB_Skip:
Braces.skipToEnd();
return;
}
while (Tok.isNot(tok::r_brace)) {
StmtResult R =
ParseStatementOrDeclaration(Stmts, ParsedStmtContext::Compound);
if (R.isUsable())
Stmts.push_back(R.get());
}
Braces.consumeClose();
}