#include "clang/Parse/Parser.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/Basic/FileManager.h"
#include "clang/Parse/ParseDiagnostic.h"
#include "clang/Parse/RAIIObjectsForParser.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/ParsedTemplate.h"
#include "clang/Sema/Scope.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace {
class ActionCommentHandler : public CommentHandler {
Sema &S;
public:
explicit ActionCommentHandler(Sema &S) : S(S) { }
bool HandleComment(Preprocessor &PP, SourceRange Comment) override {
S.ActOnComment(Comment);
return false;
}
};
}
IdentifierInfo *Parser::getSEHExceptKeyword() {
if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
Ident__except = PP.getIdentifierInfo("__except");
return Ident__except;
}
Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
: PP(pp), PreferredType(pp.isCodeCompletionEnabled()), Actions(actions),
Diags(PP.getDiagnostics()), GreaterThanIsOperator(true),
ColonIsSacred(false), InMessageExpression(false),
TemplateParameterDepth(0), ParsingInObjCContainer(false) {
SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
Tok.startToken();
Tok.setKind(tok::eof);
Actions.CurScope = nullptr;
NumCachedScopes = 0;
CurParsedObjCImpl = nullptr;
initializePragmaHandlers();
CommentSemaHandler.reset(new ActionCommentHandler(actions));
PP.addCommentHandler(CommentSemaHandler.get());
PP.setCodeCompletionHandler(*this);
}
DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
return Diags.Report(Loc, DiagID);
}
DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
return Diag(Tok.getLocation(), DiagID);
}
void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
SourceRange ParenRange) {
SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
Diag(Loc, DK);
return;
}
Diag(Loc, DK)
<< FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
<< FixItHint::CreateInsertion(EndLoc, ")");
}
static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
switch (ExpectedTok) {
case tok::semi:
return Tok.is(tok::colon) || Tok.is(tok::comma); default: return false;
}
}
bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
StringRef Msg) {
if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
ConsumeAnyToken();
return false;
}
if (IsCommonTypo(ExpectedTok, Tok)) {
SourceLocation Loc = Tok.getLocation();
{
DiagnosticBuilder DB = Diag(Loc, DiagID);
DB << FixItHint::CreateReplacement(
SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok));
if (DiagID == diag::err_expected)
DB << ExpectedTok;
else if (DiagID == diag::err_expected_after)
DB << Msg << ExpectedTok;
else
DB << Msg;
}
ConsumeAnyToken();
return false;
}
SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
const char *Spelling = nullptr;
if (EndLoc.isValid())
Spelling = tok::getPunctuatorSpelling(ExpectedTok);
DiagnosticBuilder DB =
Spelling
? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling)
: Diag(Tok, DiagID);
if (DiagID == diag::err_expected)
DB << ExpectedTok;
else if (DiagID == diag::err_expected_after)
DB << Msg << ExpectedTok;
else
DB << Msg;
return true;
}
bool Parser::ExpectAndConsumeSemi(unsigned DiagID, StringRef TokenUsed) {
if (TryConsumeToken(tok::semi))
return false;
if (Tok.is(tok::code_completion)) {
handleUnexpectedCodeCompletionToken();
return false;
}
if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
NextToken().is(tok::semi)) {
Diag(Tok, diag::err_extraneous_token_before_semi)
<< PP.getSpelling(Tok)
<< FixItHint::CreateRemoval(Tok.getLocation());
ConsumeAnyToken(); ConsumeToken(); return false;
}
return ExpectAndConsume(tok::semi, DiagID , TokenUsed);
}
void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST TST) {
if (!Tok.is(tok::semi)) return;
bool HadMultipleSemis = false;
SourceLocation StartLoc = Tok.getLocation();
SourceLocation EndLoc = Tok.getLocation();
ConsumeToken();
while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
HadMultipleSemis = true;
EndLoc = Tok.getLocation();
ConsumeToken();
}
if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
if (getLangOpts().CPlusPlus11)
Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
<< FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
else
Diag(StartLoc, diag::ext_extra_semi_cxx11)
<< FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
return;
}
if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
Diag(StartLoc, diag::ext_extra_semi)
<< Kind << DeclSpec::getSpecifierName(TST,
Actions.getASTContext().getPrintingPolicy())
<< FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
else
Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
<< FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
}
bool Parser::expectIdentifier() {
if (Tok.is(tok::identifier))
return false;
if (const auto *II = Tok.getIdentifierInfo()) {
if (II->isCPlusPlusKeyword(getLangOpts())) {
Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
<< tok::identifier << Tok.getIdentifierInfo();
return false;
}
}
Diag(Tok, diag::err_expected) << tok::identifier;
return true;
}
void Parser::checkCompoundToken(SourceLocation FirstTokLoc,
tok::TokenKind FirstTokKind, CompoundToken Op) {
if (FirstTokLoc.isInvalid())
return;
SourceLocation SecondTokLoc = Tok.getLocation();
if ((FirstTokLoc.isMacroID() || SecondTokLoc.isMacroID()) &&
PP.getSourceManager().getFileID(FirstTokLoc) !=
PP.getSourceManager().getFileID(SecondTokLoc)) {
Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro)
<< (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
<< static_cast<int>(Op) << SourceRange(FirstTokLoc);
Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here)
<< (FirstTokKind == Tok.getKind()) << Tok.getKind()
<< SourceRange(SecondTokLoc);
return;
}
if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc);
if (SpaceLoc.isInvalid())
SpaceLoc = FirstTokLoc;
Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace)
<< (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
<< static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);
return;
}
}
static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {
return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
}
bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) {
bool isFirstTokenSkipped = true;
while (true) {
for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
if (Tok.is(Toks[i])) {
if (HasFlagsSet(Flags, StopBeforeMatch)) {
} else {
ConsumeAnyToken();
}
return true;
}
}
if (Toks.size() == 1 && Toks[0] == tok::eof &&
!HasFlagsSet(Flags, StopAtSemi) &&
!HasFlagsSet(Flags, StopAtCodeCompletion)) {
while (Tok.isNot(tok::eof))
ConsumeAnyToken();
return true;
}
switch (Tok.getKind()) {
case tok::eof:
return false;
case tok::annot_pragma_openmp:
case tok::annot_attr_openmp:
case tok::annot_pragma_openmp_end:
if (OpenMPDirectiveParsing)
return false;
ConsumeAnnotationToken();
break;
case tok::annot_module_begin:
case tok::annot_module_end:
case tok::annot_module_include:
return false;
case tok::code_completion:
if (!HasFlagsSet(Flags, StopAtCodeCompletion))
handleUnexpectedCodeCompletionToken();
return false;
case tok::l_paren:
ConsumeParen();
if (HasFlagsSet(Flags, StopAtCodeCompletion))
SkipUntil(tok::r_paren, StopAtCodeCompletion);
else
SkipUntil(tok::r_paren);
break;
case tok::l_square:
ConsumeBracket();
if (HasFlagsSet(Flags, StopAtCodeCompletion))
SkipUntil(tok::r_square, StopAtCodeCompletion);
else
SkipUntil(tok::r_square);
break;
case tok::l_brace:
ConsumeBrace();
if (HasFlagsSet(Flags, StopAtCodeCompletion))
SkipUntil(tok::r_brace, StopAtCodeCompletion);
else
SkipUntil(tok::r_brace);
break;
case tok::question:
ConsumeToken();
SkipUntil(tok::colon,
SkipUntilFlags(unsigned(Flags) &
unsigned(StopAtCodeCompletion | StopAtSemi)));
break;
case tok::r_paren:
if (ParenCount && !isFirstTokenSkipped)
return false; ConsumeParen();
break;
case tok::r_square:
if (BracketCount && !isFirstTokenSkipped)
return false; ConsumeBracket();
break;
case tok::r_brace:
if (BraceCount && !isFirstTokenSkipped)
return false; ConsumeBrace();
break;
case tok::semi:
if (HasFlagsSet(Flags, StopAtSemi))
return false;
LLVM_FALLTHROUGH;
default:
ConsumeAnyToken();
break;
}
isFirstTokenSkipped = false;
}
}
void Parser::EnterScope(unsigned ScopeFlags) {
if (NumCachedScopes) {
Scope *N = ScopeCache[--NumCachedScopes];
N->Init(getCurScope(), ScopeFlags);
Actions.CurScope = N;
} else {
Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
}
}
void Parser::ExitScope() {
assert(getCurScope() && "Scope imbalance!");
Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
Scope *OldScope = getCurScope();
Actions.CurScope = OldScope->getParent();
if (NumCachedScopes == ScopeCacheSize)
delete OldScope;
else
ScopeCache[NumCachedScopes++] = OldScope;
}
Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
bool ManageFlags)
: CurScope(ManageFlags ? Self->getCurScope() : nullptr) {
if (CurScope) {
OldFlags = CurScope->getFlags();
CurScope->setFlags(ScopeFlags);
}
}
Parser::ParseScopeFlags::~ParseScopeFlags() {
if (CurScope)
CurScope->setFlags(OldFlags);
}
Parser::~Parser() {
delete getCurScope();
Actions.CurScope = nullptr;
for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
delete ScopeCache[i];
resetPragmaHandlers();
PP.removeCommentHandler(CommentSemaHandler.get());
PP.clearCodeCompletionHandler();
DestroyTemplateIds();
}
void Parser::Initialize() {
assert(getCurScope() == nullptr && "A scope is already active?");
EnterScope(Scope::DeclScope);
Actions.ActOnTranslationUnitScope(getCurScope());
if (getLangOpts().ObjC) {
ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
ObjCTypeQuals[objc_nonnull] = &PP.getIdentifierTable().get("nonnull");
ObjCTypeQuals[objc_nullable] = &PP.getIdentifierTable().get("nullable");
ObjCTypeQuals[objc_null_unspecified]
= &PP.getIdentifierTable().get("null_unspecified");
}
Ident_instancetype = nullptr;
Ident_final = nullptr;
Ident_sealed = nullptr;
Ident_abstract = nullptr;
Ident_override = nullptr;
Ident_GNU_final = nullptr;
Ident_import = nullptr;
Ident_module = nullptr;
Ident_super = &PP.getIdentifierTable().get("super");
Ident_vector = nullptr;
Ident_bool = nullptr;
Ident_Bool = nullptr;
Ident_pixel = nullptr;
if (getLangOpts().AltiVec || getLangOpts().ZVector) {
Ident_vector = &PP.getIdentifierTable().get("vector");
Ident_bool = &PP.getIdentifierTable().get("bool");
Ident_Bool = &PP.getIdentifierTable().get("_Bool");
}
if (getLangOpts().AltiVec)
Ident_pixel = &PP.getIdentifierTable().get("pixel");
Ident_introduced = nullptr;
Ident_deprecated = nullptr;
Ident_obsoleted = nullptr;
Ident_unavailable = nullptr;
Ident_strict = nullptr;
Ident_replacement = nullptr;
Ident_language = Ident_defined_in = Ident_generated_declaration = nullptr;
Ident__except = nullptr;
Ident__exception_code = Ident__exception_info = nullptr;
Ident__abnormal_termination = Ident___exception_code = nullptr;
Ident___exception_info = Ident___abnormal_termination = nullptr;
Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr;
Ident_AbnormalTermination = nullptr;
if(getLangOpts().Borland) {
Ident__exception_info = PP.getIdentifierInfo("_exception_info");
Ident___exception_info = PP.getIdentifierInfo("__exception_info");
Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation");
Ident__exception_code = PP.getIdentifierInfo("_exception_code");
Ident___exception_code = PP.getIdentifierInfo("__exception_code");
Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode");
Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination");
Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination");
PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
}
if (getLangOpts().CPlusPlusModules) {
Ident_import = PP.getIdentifierInfo("import");
Ident_module = PP.getIdentifierInfo("module");
}
Actions.Initialize();
ConsumeToken();
}
void Parser::DestroyTemplateIds() {
for (TemplateIdAnnotation *Id : TemplateIds)
Id->Destroy();
TemplateIds.clear();
}
bool Parser::ParseFirstTopLevelDecl(DeclGroupPtrTy &Result,
Sema::ModuleImportState &ImportState) {
Actions.ActOnStartOfTranslationUnit();
ImportState = Sema::ModuleImportState::FirstDecl;
bool NoTopLevelDecls = ParseTopLevelDecl(Result, ImportState);
if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
!getLangOpts().CPlusPlus && !getLangOpts().IsHeaderFile)
Diag(diag::ext_empty_translation_unit);
return NoTopLevelDecls;
}
bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result,
Sema::ModuleImportState &ImportState) {
DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
ConsumeToken();
Result = nullptr;
switch (Tok.getKind()) {
case tok::annot_pragma_unused:
HandlePragmaUnused();
return false;
case tok::kw_export:
switch (NextToken().getKind()) {
case tok::kw_module:
goto module_decl;
case tok::identifier: {
IdentifierInfo *II = NextToken().getIdentifierInfo();
if ((II == Ident_module || II == Ident_import) &&
GetLookAheadToken(2).isNot(tok::coloncolon)) {
if (II == Ident_module)
goto module_decl;
else
goto import_decl;
}
break;
}
default:
break;
}
break;
case tok::kw_module:
module_decl:
Result = ParseModuleDecl(ImportState);
return false;
case tok::kw_import:
import_decl: {
Decl *ImportDecl = ParseModuleImport(SourceLocation(), ImportState);
Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
return false;
}
case tok::annot_module_include: {
auto Loc = Tok.getLocation();
Module *Mod = reinterpret_cast<Module *>(Tok.getAnnotationValue());
if (!getLangOpts().CPlusPlusModules || !Mod->isHeaderUnit())
Actions.ActOnModuleInclude(Loc, Mod);
else {
DeclResult Import =
Actions.ActOnModuleImport(Loc, SourceLocation(), Loc, Mod);
Decl *ImportDecl = Import.isInvalid() ? nullptr : Import.get();
Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
}
ConsumeAnnotationToken();
return false;
}
case tok::annot_module_begin:
Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast<Module *>(
Tok.getAnnotationValue()));
ConsumeAnnotationToken();
ImportState = Sema::ModuleImportState::NotACXX20Module;
return false;
case tok::annot_module_end:
Actions.ActOnModuleEnd(Tok.getLocation(), reinterpret_cast<Module *>(
Tok.getAnnotationValue()));
ConsumeAnnotationToken();
ImportState = Sema::ModuleImportState::NotACXX20Module;
return false;
case tok::eof:
if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
<< PP.getTokenCount() << PP.getMaxTokens();
SourceLocation OverrideLoc = PP.getMaxTokensOverrideLoc();
if (OverrideLoc.isValid()) {
PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
}
}
Actions.SetLateTemplateParser(LateTemplateParserCallback, nullptr, this);
if (!PP.isIncrementalProcessingEnabled())
Actions.ActOnEndOfTranslationUnit();
return true;
case tok::identifier:
if ((Tok.getIdentifierInfo() == Ident_module ||
Tok.getIdentifierInfo() == Ident_import) &&
NextToken().isNot(tok::coloncolon)) {
if (Tok.getIdentifierInfo() == Ident_module)
goto module_decl;
else
goto import_decl;
}
break;
default:
break;
}
ParsedAttributes attrs(AttrFactory);
MaybeParseCXX11Attributes(attrs);
Result = ParseExternalDeclaration(attrs);
if (Result) {
if (ImportState == Sema::ModuleImportState::FirstDecl)
ImportState = Sema::ModuleImportState::NotACXX20Module;
else if (ImportState == Sema::ModuleImportState::ImportAllowed)
ImportState = Sema::ModuleImportState::ImportFinished;
}
return false;
}
Parser::DeclGroupPtrTy Parser::ParseExternalDeclaration(ParsedAttributes &Attrs,
ParsingDeclSpec *DS) {
DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
ParenBraceBracketBalancer BalancerRAIIObj(*this);
if (PP.isCodeCompletionReached()) {
cutOffParsing();
return nullptr;
}
Decl *SingleDecl = nullptr;
switch (Tok.getKind()) {
case tok::annot_pragma_vis:
HandlePragmaVisibility();
return nullptr;
case tok::annot_pragma_pack:
HandlePragmaPack();
return nullptr;
case tok::annot_pragma_msstruct:
HandlePragmaMSStruct();
return nullptr;
case tok::annot_pragma_align:
HandlePragmaAlign();
return nullptr;
case tok::annot_pragma_weak:
HandlePragmaWeak();
return nullptr;
case tok::annot_pragma_weakalias:
HandlePragmaWeakAlias();
return nullptr;
case tok::annot_pragma_redefine_extname:
HandlePragmaRedefineExtname();
return nullptr;
case tok::annot_pragma_fp_contract:
HandlePragmaFPContract();
return nullptr;
case tok::annot_pragma_fenv_access:
case tok::annot_pragma_fenv_access_ms:
HandlePragmaFEnvAccess();
return nullptr;
case tok::annot_pragma_fenv_round:
HandlePragmaFEnvRound();
return nullptr;
case tok::annot_pragma_float_control:
HandlePragmaFloatControl();
return nullptr;
case tok::annot_pragma_fp:
HandlePragmaFP();
break;
case tok::annot_pragma_opencl_extension:
HandlePragmaOpenCLExtension();
return nullptr;
case tok::annot_attr_openmp:
case tok::annot_pragma_openmp: {
AccessSpecifier AS = AS_none;
return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
}
case tok::annot_pragma_ms_pointers_to_members:
HandlePragmaMSPointersToMembers();
return nullptr;
case tok::annot_pragma_ms_vtordisp:
HandlePragmaMSVtorDisp();
return nullptr;
case tok::annot_pragma_ms_pragma:
HandlePragmaMSPragma();
return nullptr;
case tok::annot_pragma_dump:
HandlePragmaDump();
return nullptr;
case tok::annot_pragma_attribute:
HandlePragmaAttribute();
return nullptr;
case tok::semi:
SingleDecl =
Actions.ActOnEmptyDeclaration(getCurScope(), Attrs, Tok.getLocation());
ConsumeExtraSemi(OutsideFunction);
break;
case tok::r_brace:
Diag(Tok, diag::err_extraneous_closing_brace);
ConsumeBrace();
return nullptr;
case tok::eof:
Diag(Tok, diag::err_expected_external_declaration);
return nullptr;
case tok::kw___extension__: {
ExtensionRAIIObject O(Diags); ConsumeToken();
return ParseExternalDeclaration(Attrs);
}
case tok::kw_asm: {
ProhibitAttributes(Attrs);
SourceLocation StartLoc = Tok.getLocation();
SourceLocation EndLoc;
ExprResult Result(ParseSimpleAsm( false, &EndLoc));
if (!(getLangOpts().GNUAsm || Result.isInvalid())) {
const auto *SL = cast<StringLiteral>(Result.get());
if (!SL->getString().trim().empty())
Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
}
ExpectAndConsume(tok::semi, diag::err_expected_after,
"top-level asm block");
if (Result.isInvalid())
return nullptr;
SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
break;
}
case tok::at:
return ParseObjCAtDirectives(Attrs);
case tok::minus:
case tok::plus:
if (!getLangOpts().ObjC) {
Diag(Tok, diag::err_expected_external_declaration);
ConsumeToken();
return nullptr;
}
SingleDecl = ParseObjCMethodDefinition();
break;
case tok::code_completion:
cutOffParsing();
if (CurParsedObjCImpl) {
Actions.CodeCompleteObjCMethodDecl(getCurScope(),
None,
nullptr);
}
Actions.CodeCompleteOrdinaryName(
getCurScope(),
CurParsedObjCImpl ? Sema::PCC_ObjCImplementation : Sema::PCC_Namespace);
return nullptr;
case tok::kw_import: {
Sema::ModuleImportState IS = Sema::ModuleImportState::NotACXX20Module;
if (getLangOpts().CPlusPlusModules) {
llvm_unreachable("not expecting a c++20 import here");
ProhibitAttributes(Attrs);
}
SingleDecl = ParseModuleImport(SourceLocation(), IS);
} break;
case tok::kw_export:
if (getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS) {
ProhibitAttributes(Attrs);
SingleDecl = ParseExportDeclaration();
break;
}
LLVM_FALLTHROUGH;
case tok::kw_using:
case tok::kw_namespace:
case tok::kw_typedef:
case tok::kw_template:
case tok::kw_static_assert:
case tok::kw__Static_assert:
{
SourceLocation DeclEnd;
ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
EmptyDeclSpecAttrs);
}
case tok::kw_static:
if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
<< 0;
SourceLocation DeclEnd;
ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
EmptyDeclSpecAttrs);
}
goto dont_know;
case tok::kw_inline:
if (getLangOpts().CPlusPlus) {
tok::TokenKind NextKind = NextToken().getKind();
if (NextKind == tok::kw_namespace) {
SourceLocation DeclEnd;
ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
EmptyDeclSpecAttrs);
}
if (NextKind == tok::kw_template) {
Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
<< 1;
SourceLocation DeclEnd;
ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
EmptyDeclSpecAttrs);
}
}
goto dont_know;
case tok::kw_extern:
if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
SourceLocation ExternLoc = ConsumeToken();
SourceLocation TemplateLoc = ConsumeToken();
Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
diag::warn_cxx98_compat_extern_template :
diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
SourceLocation DeclEnd;
return Actions.ConvertDeclToDeclGroup(ParseExplicitInstantiation(
DeclaratorContext::File, ExternLoc, TemplateLoc, DeclEnd, Attrs));
}
goto dont_know;
case tok::kw___if_exists:
case tok::kw___if_not_exists:
ParseMicrosoftIfExistsExternalDeclaration();
return nullptr;
case tok::kw_module:
Diag(Tok, diag::err_unexpected_module_decl);
SkipUntil(tok::semi);
return nullptr;
default:
dont_know:
if (Tok.isEditorPlaceholder()) {
ConsumeToken();
return nullptr;
}
return ParseDeclarationOrFunctionDefinition(Attrs, DS);
}
return Actions.ConvertDeclToDeclGroup(SingleDecl);
}
bool Parser::isDeclarationAfterDeclarator() {
if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
const Token &KW = NextToken();
if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
return false;
}
return Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::semi) || Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute) || (getLangOpts().CPlusPlus &&
Tok.is(tok::l_paren)); }
bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
if (Tok.is(tok::l_brace)) return true;
if (!getLangOpts().CPlusPlus &&
Declarator.getFunctionTypeInfo().isKNRPrototype())
return isDeclarationSpecifier();
if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
const Token &KW = NextToken();
return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
}
return Tok.is(tok::colon) || Tok.is(tok::kw_try); }
Parser::DeclGroupPtrTy Parser::ParseDeclOrFunctionDefInternal(
ParsedAttributes &Attrs, ParsingDeclSpec &DS, AccessSpecifier AS) {
MaybeParseMicrosoftAttributes(DS.getAttributes());
ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS,
DeclSpecContext::DSC_top_level);
if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(
DS, AS, DeclSpecContext::DSC_top_level))
return nullptr;
if (Tok.is(tok::semi)) {
auto LengthOfTSTToken = [](DeclSpec::TST TKind) {
assert(DeclSpec::isDeclRep(TKind));
switch(TKind) {
case DeclSpec::TST_class:
return 5;
case DeclSpec::TST_struct:
return 6;
case DeclSpec::TST_union:
return 5;
case DeclSpec::TST_enum:
return 4;
case DeclSpec::TST_interface:
return 9;
default:
llvm_unreachable("we only expect to get the length of the class/struct/union/enum");
}
};
SourceLocation CorrectLocationForAttributes =
DeclSpec::isDeclRep(DS.getTypeSpecType())
? DS.getTypeSpecTypeLoc().getLocWithOffset(
LengthOfTSTToken(DS.getTypeSpecType()))
: SourceLocation();
ProhibitAttributes(Attrs, CorrectLocationForAttributes);
ConsumeToken();
RecordDecl *AnonRecord = nullptr;
Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
DS.complete(TheDecl);
if (AnonRecord) {
Decl* decls[] = {AnonRecord, TheDecl};
return Actions.BuildDeclaratorGroup(decls);
}
return Actions.ConvertDeclToDeclGroup(TheDecl);
}
if (getLangOpts().ObjC && Tok.is(tok::at)) {
SourceLocation AtLoc = ConsumeToken(); if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
!Tok.isObjCAtKeyword(tok::objc_protocol) &&
!Tok.isObjCAtKeyword(tok::objc_implementation)) {
Diag(Tok, diag::err_objc_unexpected_attr);
SkipUntil(tok::semi);
return nullptr;
}
DS.abort();
DS.takeAttributesFrom(Attrs);
const char *PrevSpec = nullptr;
unsigned DiagID;
if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
Actions.getASTContext().getPrintingPolicy()))
Diag(AtLoc, DiagID) << PrevSpec;
if (Tok.isObjCAtKeyword(tok::objc_protocol))
return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
if (Tok.isObjCAtKeyword(tok::objc_implementation))
return ParseObjCAtImplementationDeclaration(AtLoc, DS.getAttributes());
return Actions.ConvertDeclToDeclGroup(
ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
}
if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
ProhibitAttributes(Attrs);
Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File);
return Actions.ConvertDeclToDeclGroup(TheDecl);
}
return ParseDeclGroup(DS, DeclaratorContext::File, Attrs);
}
Parser::DeclGroupPtrTy Parser::ParseDeclarationOrFunctionDefinition(
ParsedAttributes &Attrs, ParsingDeclSpec *DS, AccessSpecifier AS) {
if (DS) {
return ParseDeclOrFunctionDefInternal(Attrs, *DS, AS);
} else {
ParsingDeclSpec PDS(*this);
ObjCDeclContextSwitch ObjCDC(*this);
return ParseDeclOrFunctionDefInternal(Attrs, PDS, AS);
}
}
Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
const ParsedTemplateInfo &TemplateInfo,
LateParsedAttrList *LateParsedAttrs) {
PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
if (getLangOpts().isImplicitIntRequired() && D.getDeclSpec().isEmpty()) {
Diag(D.getIdentifierLoc(), diag::warn_missing_type_specifier)
<< D.getDeclSpec().getSourceRange();
const char *PrevSpec;
unsigned DiagID;
const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
D.getIdentifierLoc(),
PrevSpec, DiagID,
Policy);
D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
}
if (FTI.isKNRPrototype())
ParseKNRParamDeclarations(D);
if (Tok.isNot(tok::l_brace) &&
(!getLangOpts().CPlusPlus ||
(Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
Tok.isNot(tok::equal)))) {
Diag(Tok, diag::err_expected_fn_body);
SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
if (Tok.isNot(tok::l_brace))
return nullptr;
}
if (Tok.isNot(tok::equal)) {
for (const ParsedAttr &AL : D.getAttributes())
if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
}
if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
TemplateInfo.Kind == ParsedTemplateInfo::Template &&
Actions.canDelayFunctionBody(D)) {
MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
Scope::CompoundStmtScope);
Scope *ParentScope = getCurScope()->getParent();
D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
Decl *DP = Actions.HandleDeclarator(ParentScope, D,
TemplateParameterLists);
D.complete(DP);
D.getMutableDeclSpec().abort();
if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
trySkippingFunctionBody()) {
BodyScope.Exit();
return Actions.ActOnSkippedFunctionBody(DP);
}
CachedTokens Toks;
LexTemplateFunctionForLateParsing(Toks);
if (DP) {
FunctionDecl *FnD = DP->getAsFunction();
Actions.CheckForFunctionRedefinition(FnD);
Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
}
return DP;
}
else if (CurParsedObjCImpl &&
!TemplateInfo.TemplateParams &&
(Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
Tok.is(tok::colon)) &&
Actions.CurContext->isTranslationUnit()) {
ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
Scope::CompoundStmtScope);
Scope *ParentScope = getCurScope()->getParent();
D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
MultiTemplateParamsArg());
D.complete(FuncDecl);
D.getMutableDeclSpec().abort();
if (FuncDecl) {
StashAwayMethodOrFunctionBodyTokens(FuncDecl);
CurParsedObjCImpl->HasCFunction = true;
return FuncDecl;
}
}
ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
Scope::CompoundStmtScope);
Sema::FnBodyKind BodyKind = Sema::FnBodyKind::Other;
SourceLocation KWLoc;
if (TryConsumeToken(tok::equal)) {
assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
if (TryConsumeToken(tok::kw_delete, KWLoc)) {
Diag(KWLoc, getLangOpts().CPlusPlus11
? diag::warn_cxx98_compat_defaulted_deleted_function
: diag::ext_defaulted_deleted_function)
<< 1 ;
BodyKind = Sema::FnBodyKind::Delete;
} else if (TryConsumeToken(tok::kw_default, KWLoc)) {
Diag(KWLoc, getLangOpts().CPlusPlus11
? diag::warn_cxx98_compat_defaulted_deleted_function
: diag::ext_defaulted_deleted_function)
<< 0 ;
BodyKind = Sema::FnBodyKind::Default;
} else {
llvm_unreachable("function definition after = not 'delete' or 'default'");
}
if (Tok.is(tok::comma)) {
Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
<< (BodyKind == Sema::FnBodyKind::Delete);
SkipUntil(tok::semi);
} else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
BodyKind == Sema::FnBodyKind::Delete
? "delete"
: "default")) {
SkipUntil(tok::semi);
}
}
Sema::SkipBodyInfo SkipBody;
Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
TemplateInfo.TemplateParams
? *TemplateInfo.TemplateParams
: MultiTemplateParamsArg(),
&SkipBody, BodyKind);
if (SkipBody.ShouldSkip) {
if (BodyKind == Sema::FnBodyKind::Other)
SkipFunctionBody();
return Res;
}
D.complete(Res);
D.getMutableDeclSpec().abort();
if (BodyKind != Sema::FnBodyKind::Other) {
Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind);
Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
return Res;
}
if (auto *Template = dyn_cast_or_null<FunctionTemplateDecl>(Res))
if (Template->isAbbreviated() &&
Template->getTemplateParameters()->getParam(0)->isImplicit())
CurTemplateDepthTracker.addDepth(1);
if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
trySkippingFunctionBody()) {
BodyScope.Exit();
Actions.ActOnSkippedFunctionBody(Res);
return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
}
if (Tok.is(tok::kw_try))
return ParseFunctionTryBlock(Res, BodyScope);
if (Tok.is(tok::colon)) {
ParseConstructorInitializer(Res);
if (!Tok.is(tok::l_brace)) {
BodyScope.Exit();
Actions.ActOnFinishFunctionBody(Res, nullptr);
return Res;
}
} else
Actions.ActOnDefaultCtorInitializers(Res);
if (LateParsedAttrs)
ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
return ParseFunctionStatementBody(Res, BodyScope);
}
void Parser::SkipFunctionBody() {
if (Tok.is(tok::equal)) {
SkipUntil(tok::semi);
return;
}
bool IsFunctionTryBlock = Tok.is(tok::kw_try);
if (IsFunctionTryBlock)
ConsumeToken();
CachedTokens Skipped;
if (ConsumeAndStoreFunctionPrologue(Skipped))
SkipMalformedDecl();
else {
SkipUntil(tok::r_brace);
while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
SkipUntil(tok::l_brace);
SkipUntil(tok::r_brace);
}
}
}
void Parser::ParseKNRParamDeclarations(Declarator &D) {
DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
Scope::FunctionDeclarationScope | Scope::DeclScope);
while (isDeclarationSpecifier()) {
SourceLocation DSStart = Tok.getLocation();
DeclSpec DS(AttrFactory);
ParseDeclarationSpecifiers(DS);
if (TryConsumeToken(tok::semi)) {
Diag(DSStart, diag::err_declaration_does_not_declare_param);
continue;
}
if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
DS.getStorageClassSpec() != DeclSpec::SCS_register) {
Diag(DS.getStorageClassSpecLoc(),
diag::err_invalid_storage_class_in_func_decl);
DS.ClearStorageClassSpecs();
}
if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
Diag(DS.getThreadStorageClassSpecLoc(),
diag::err_invalid_storage_class_in_func_decl);
DS.ClearStorageClassSpecs();
}
Declarator ParmDeclarator(DS, ParsedAttributesView::none(),
DeclaratorContext::KNRTypeList);
ParseDeclarator(ParmDeclarator);
while (true) {
MaybeParseGNUAttributes(ParmDeclarator);
Decl *Param =
Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
if (Param &&
ParmDeclarator.getIdentifier()) {
for (unsigned i = 0; ; ++i) {
if (i == FTI.NumParams) {
Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
<< ParmDeclarator.getIdentifier();
break;
}
if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
if (FTI.Params[i].Param) {
Diag(ParmDeclarator.getIdentifierLoc(),
diag::err_param_redefinition)
<< ParmDeclarator.getIdentifier();
} else {
FTI.Params[i].Param = Param;
}
break;
}
}
}
if (Tok.isNot(tok::comma))
break;
ParmDeclarator.clear();
ParmDeclarator.setCommaLoc(ConsumeToken());
ParseDeclarator(ParmDeclarator);
}
if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
continue;
if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
break;
TryConsumeToken(tok::semi);
}
Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
}
ExprResult Parser::ParseAsmStringLiteral(bool ForAsmLabel) {
if (!isTokenStringLiteral()) {
Diag(Tok, diag::err_expected_string_literal)
<< 0 << "'asm'";
return ExprError();
}
ExprResult AsmString(ParseStringLiteralExpression());
if (!AsmString.isInvalid()) {
const auto *SL = cast<StringLiteral>(AsmString.get());
if (!SL->isOrdinary()) {
Diag(Tok, diag::err_asm_operand_wide_string_literal)
<< SL->isWide()
<< SL->getSourceRange();
return ExprError();
}
if (ForAsmLabel && SL->getString().empty()) {
Diag(Tok, diag::err_asm_operand_wide_string_literal)
<< 2 << SL->getSourceRange();
return ExprError();
}
}
return AsmString;
}
ExprResult Parser::ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc) {
assert(Tok.is(tok::kw_asm) && "Not an asm!");
SourceLocation Loc = ConsumeToken();
if (isGNUAsmQualifier(Tok)) {
SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
PP.getLocForEndOfToken(Tok.getLocation()));
Diag(Tok, diag::err_global_asm_qualifier_ignored)
<< GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
<< FixItHint::CreateRemoval(RemovalRange);
ConsumeToken();
}
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.consumeOpen()) {
Diag(Tok, diag::err_expected_lparen_after) << "asm";
return ExprError();
}
ExprResult Result(ParseAsmStringLiteral(ForAsmLabel));
if (!Result.isInvalid()) {
T.consumeClose();
if (EndLoc)
*EndLoc = T.getCloseLocation();
} else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
if (EndLoc)
*EndLoc = Tok.getLocation();
ConsumeParen();
}
return Result;
}
TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
assert(tok.is(tok::annot_template_id) && "Expected template-id token");
TemplateIdAnnotation *
Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
return Id;
}
void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
if (PP.isBacktrackEnabled())
PP.RevertCachedTokens(1);
else
PP.EnterToken(Tok, true);
Tok.setKind(tok::annot_cxxscope);
Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
Tok.setAnnotationRange(SS.getRange());
if (IsNewAnnotation)
PP.AnnotateCachedTokens(Tok);
}
Parser::AnnotatedNameKind
Parser::TryAnnotateName(CorrectionCandidateCallback *CCC) {
assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
const bool EnteringContext = false;
const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
CXXScopeSpec SS;
if (getLangOpts().CPlusPlus &&
ParseOptionalCXXScopeSpecifier(SS, nullptr,
false,
EnteringContext))
return ANK_Error;
if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation))
return ANK_Error;
return ANK_Unresolved;
}
IdentifierInfo *Name = Tok.getIdentifierInfo();
SourceLocation NameLoc = Tok.getLocation();
if (isTentativelyDeclared(Name)) {
if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation))
return ANK_Error;
return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
}
Token Next = NextToken();
Sema::NameClassification Classification = Actions.ClassifyName(
getCurScope(), SS, Name, NameLoc, Next, SS.isEmpty() ? CCC : nullptr);
if (Classification.getKind() == Sema::NC_UndeclaredTemplate &&
isTemplateArgumentList(1) == TPResult::False) {
Token FakeNext = Next;
FakeNext.setKind(tok::unknown);
Classification =
Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext,
SS.isEmpty() ? CCC : nullptr);
}
switch (Classification.getKind()) {
case Sema::NC_Error:
return ANK_Error;
case Sema::NC_Keyword:
Tok.setIdentifierInfo(Name);
Tok.setKind(Name->getTokenID());
PP.TypoCorrectToken(Tok);
if (SS.isNotEmpty())
AnnotateScopeToken(SS, !WasScopeAnnotation);
return ANK_Success;
case Sema::NC_Unknown:
break;
case Sema::NC_Type: {
if (TryAltiVecVectorToken())
break;
SourceLocation BeginLoc = NameLoc;
if (SS.isNotEmpty())
BeginLoc = SS.getBeginLoc();
ParsedType Ty = Classification.getType();
if (getLangOpts().ObjC && NextToken().is(tok::less) &&
(Ty.get()->isObjCObjectType() ||
Ty.get()->isObjCObjectPointerType())) {
SourceLocation IdentifierLoc = ConsumeToken();
SourceLocation NewEndLoc;
TypeResult NewType
= parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
false,
NewEndLoc);
if (NewType.isUsable())
Ty = NewType.get();
else if (Tok.is(tok::eof)) return ANK_Error;
}
Tok.setKind(tok::annot_typename);
setTypeAnnotation(Tok, Ty);
Tok.setAnnotationEndLoc(Tok.getLocation());
Tok.setLocation(BeginLoc);
PP.AnnotateCachedTokens(Tok);
return ANK_Success;
}
case Sema::NC_OverloadSet:
Tok.setKind(tok::annot_overload_set);
setExprAnnotation(Tok, Classification.getExpression());
Tok.setAnnotationEndLoc(NameLoc);
if (SS.isNotEmpty())
Tok.setLocation(SS.getBeginLoc());
PP.AnnotateCachedTokens(Tok);
return ANK_Success;
case Sema::NC_NonType:
if (TryAltiVecVectorToken())
break;
Tok.setKind(tok::annot_non_type);
setNonTypeAnnotation(Tok, Classification.getNonTypeDecl());
Tok.setLocation(NameLoc);
Tok.setAnnotationEndLoc(NameLoc);
PP.AnnotateCachedTokens(Tok);
if (SS.isNotEmpty())
AnnotateScopeToken(SS, !WasScopeAnnotation);
return ANK_Success;
case Sema::NC_UndeclaredNonType:
case Sema::NC_DependentNonType:
Tok.setKind(Classification.getKind() == Sema::NC_UndeclaredNonType
? tok::annot_non_type_undeclared
: tok::annot_non_type_dependent);
setIdentifierAnnotation(Tok, Name);
Tok.setLocation(NameLoc);
Tok.setAnnotationEndLoc(NameLoc);
PP.AnnotateCachedTokens(Tok);
if (SS.isNotEmpty())
AnnotateScopeToken(SS, !WasScopeAnnotation);
return ANK_Success;
case Sema::NC_TypeTemplate:
if (Next.isNot(tok::less)) {
if (SS.isNotEmpty())
AnnotateScopeToken(SS, !WasScopeAnnotation);
return ANK_TemplateName;
}
LLVM_FALLTHROUGH;
case Sema::NC_VarTemplate:
case Sema::NC_FunctionTemplate:
case Sema::NC_UndeclaredTemplate: {
ConsumeToken();
UnqualifiedId Id;
Id.setIdentifier(Name, NameLoc);
if (AnnotateTemplateIdToken(
TemplateTy::make(Classification.getTemplateName()),
Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
return ANK_Error;
return ANK_Success;
}
case Sema::NC_Concept: {
UnqualifiedId Id;
Id.setIdentifier(Name, NameLoc);
if (Next.is(tok::less))
ConsumeToken();
if (AnnotateTemplateIdToken(
TemplateTy::make(Classification.getTemplateName()),
Classification.getTemplateNameKind(), SS, SourceLocation(), Id,
false, true))
return ANK_Error;
return ANK_Success;
}
}
if (SS.isNotEmpty())
AnnotateScopeToken(SS, !WasScopeAnnotation);
return ANK_Unresolved;
}
bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
assert(Tok.isNot(tok::identifier));
Diag(Tok, diag::ext_keyword_as_ident)
<< PP.getSpelling(Tok)
<< DisableKeyword;
if (DisableKeyword)
Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
Tok.setKind(tok::identifier);
return true;
}
bool Parser::TryAnnotateTypeOrScopeToken() {
assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
Tok.is(tok::kw___super)) &&
"Cannot be a type or scope token!");
if (Tok.is(tok::kw_typename)) {
if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
Token TypedefToken;
PP.Lex(TypedefToken);
bool Result = TryAnnotateTypeOrScopeToken();
PP.EnterToken(Tok, true);
Tok = TypedefToken;
if (!Result)
Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
return Result;
}
SourceLocation TypenameLoc = ConsumeToken();
CXXScopeSpec SS;
if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
false,
false, nullptr,
true))
return true;
if (SS.isEmpty()) {
if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
Tok.is(tok::annot_decltype)) {
if (Tok.is(tok::annot_decltype) ||
(!TryAnnotateTypeOrScopeToken() && Tok.isAnnotation())) {
unsigned DiagID = diag::err_expected_qualified_after_typename;
if (getLangOpts().MicrosoftExt)
DiagID = diag::warn_expected_qualified_after_typename;
Diag(Tok.getLocation(), DiagID);
return false;
}
}
if (Tok.isEditorPlaceholder())
return true;
Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
return true;
}
TypeResult Ty;
if (Tok.is(tok::identifier)) {
Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
*Tok.getIdentifierInfo(),
Tok.getLocation());
} else if (Tok.is(tok::annot_template_id)) {
TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
if (!TemplateId->mightBeType()) {
Diag(Tok, diag::err_typename_refers_to_non_type_template)
<< Tok.getAnnotationRange();
return true;
}
ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
TemplateId->NumArgs);
Ty = TemplateId->isInvalid()
? TypeError()
: Actions.ActOnTypenameType(
getCurScope(), TypenameLoc, SS, TemplateId->TemplateKWLoc,
TemplateId->Template, TemplateId->Name,
TemplateId->TemplateNameLoc, TemplateId->LAngleLoc,
TemplateArgsPtr, TemplateId->RAngleLoc);
} else {
Diag(Tok, diag::err_expected_type_name_after_typename)
<< SS.getRange();
return true;
}
SourceLocation EndLoc = Tok.getLastLoc();
Tok.setKind(tok::annot_typename);
setTypeAnnotation(Tok, Ty);
Tok.setAnnotationEndLoc(EndLoc);
Tok.setLocation(TypenameLoc);
PP.AnnotateCachedTokens(Tok);
return false;
}
bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
CXXScopeSpec SS;
if (getLangOpts().CPlusPlus)
if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
false,
false))
return true;
return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation);
}
bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
bool IsNewScope) {
if (Tok.is(tok::identifier)) {
if (ParsedType Ty = Actions.getTypeName(
*Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
false, NextToken().is(tok::period), nullptr,
false,
true,
true)) {
SourceLocation BeginLoc = Tok.getLocation();
if (SS.isNotEmpty()) BeginLoc = SS.getBeginLoc();
if (getLangOpts().ObjC && NextToken().is(tok::less) &&
(Ty.get()->isObjCObjectType() ||
Ty.get()->isObjCObjectPointerType())) {
SourceLocation IdentifierLoc = ConsumeToken();
SourceLocation NewEndLoc;
TypeResult NewType
= parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
false,
NewEndLoc);
if (NewType.isUsable())
Ty = NewType.get();
else if (Tok.is(tok::eof)) return false;
}
Tok.setKind(tok::annot_typename);
setTypeAnnotation(Tok, Ty);
Tok.setAnnotationEndLoc(Tok.getLocation());
Tok.setLocation(BeginLoc);
PP.AnnotateCachedTokens(Tok);
return false;
}
if (!getLangOpts().CPlusPlus) {
return false;
}
if (NextToken().is(tok::less)) {
TemplateTy Template;
UnqualifiedId TemplateName;
TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
bool MemberOfUnknownSpecialization;
if (TemplateNameKind TNK = Actions.isTemplateName(
getCurScope(), SS,
false, TemplateName,
nullptr, false, Template,
MemberOfUnknownSpecialization)) {
if (TNK != TNK_Undeclared_template ||
isTemplateArgumentList(1) != TPResult::False) {
ConsumeToken();
if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
TemplateName)) {
return true;
}
}
}
}
}
if (Tok.is(tok::annot_template_id)) {
TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
if (TemplateId->Kind == TNK_Type_template) {
AnnotateTemplateIdTokenAsType(SS);
return false;
}
}
if (SS.isEmpty())
return false;
AnnotateScopeToken(SS, IsNewScope);
return false;
}
bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
assert(getLangOpts().CPlusPlus &&
"Call sites of this function should be guarded by checking for C++");
assert(MightBeCXXScopeToken() && "Cannot be a type or scope token!");
CXXScopeSpec SS;
if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
false,
EnteringContext))
return true;
if (SS.isEmpty())
return false;
AnnotateScopeToken(SS, true);
return false;
}
bool Parser::isTokenEqualOrEqualTypo() {
tok::TokenKind Kind = Tok.getKind();
switch (Kind) {
default:
return false;
case tok::ampequal: case tok::starequal: case tok::plusequal: case tok::minusequal: case tok::exclaimequal: case tok::slashequal: case tok::percentequal: case tok::lessequal: case tok::lesslessequal: case tok::greaterequal: case tok::greatergreaterequal: case tok::caretequal: case tok::pipeequal: case tok::equalequal: Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
<< Kind
<< FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
LLVM_FALLTHROUGH;
case tok::equal:
return true;
}
}
SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
assert(Tok.is(tok::code_completion));
PrevTokLocation = Tok.getLocation();
for (Scope *S = getCurScope(); S; S = S->getParent()) {
if (S->isFunctionScope()) {
cutOffParsing();
Actions.CodeCompleteOrdinaryName(getCurScope(),
Sema::PCC_RecoveryInFunction);
return PrevTokLocation;
}
if (S->isClassScope()) {
cutOffParsing();
Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
return PrevTokLocation;
}
}
cutOffParsing();
Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
return PrevTokLocation;
}
void Parser::CodeCompleteDirective(bool InConditional) {
Actions.CodeCompletePreprocessorDirective(InConditional);
}
void Parser::CodeCompleteInConditionalExclusion() {
Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
}
void Parser::CodeCompleteMacroName(bool IsDefinition) {
Actions.CodeCompletePreprocessorMacroName(IsDefinition);
}
void Parser::CodeCompletePreprocessorExpression() {
Actions.CodeCompletePreprocessorExpression();
}
void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
MacroInfo *MacroInfo,
unsigned ArgumentIndex) {
Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
ArgumentIndex);
}
void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) {
Actions.CodeCompleteIncludedFile(Dir, IsAngled);
}
void Parser::CodeCompleteNaturalLanguage() {
Actions.CodeCompleteNaturalLanguage();
}
bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
"Expected '__if_exists' or '__if_not_exists'");
Result.IsIfExists = Tok.is(tok::kw___if_exists);
Result.KeywordLoc = ConsumeToken();
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.consumeOpen()) {
Diag(Tok, diag::err_expected_lparen_after)
<< (Result.IsIfExists? "__if_exists" : "__if_not_exists");
return true;
}
if (getLangOpts().CPlusPlus)
ParseOptionalCXXScopeSpecifier(Result.SS, nullptr,
false,
false);
if (Result.SS.isInvalid()) {
T.skipToEnd();
return true;
}
SourceLocation TemplateKWLoc; if (ParseUnqualifiedId(Result.SS, nullptr,
false, false,
true,
true,
false, &TemplateKWLoc,
Result.Name)) {
T.skipToEnd();
return true;
}
if (T.consumeClose())
return true;
switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
Result.IsIfExists, Result.SS,
Result.Name)) {
case Sema::IER_Exists:
Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
break;
case Sema::IER_DoesNotExist:
Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
break;
case Sema::IER_Dependent:
Result.Behavior = IEB_Dependent;
break;
case Sema::IER_Error:
return true;
}
return false;
}
void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
IfExistsCondition Result;
if (ParseMicrosoftIfExistsCondition(Result))
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("Cannot have a dependent external declaration");
case IEB_Skip:
Braces.skipToEnd();
return;
}
while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
ParsedAttributes Attrs(AttrFactory);
MaybeParseCXX11Attributes(Attrs);
DeclGroupPtrTy Result = ParseExternalDeclaration(Attrs);
if (Result && !getCurScope()->getParent())
Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
}
Braces.consumeClose();
}
Parser::DeclGroupPtrTy
Parser::ParseModuleDecl(Sema::ModuleImportState &ImportState) {
SourceLocation StartLoc = Tok.getLocation();
Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export)
? Sema::ModuleDeclKind::Interface
: Sema::ModuleDeclKind::Implementation;
assert(
(Tok.is(tok::kw_module) ||
(Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) &&
"not a module declaration");
SourceLocation ModuleLoc = ConsumeToken();
DiagnoseAndSkipCXX11Attributes();
if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
SourceLocation SemiLoc = ConsumeToken();
if (ImportState != Sema::ModuleImportState::FirstDecl) {
Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
<< SourceRange(StartLoc, SemiLoc);
return nullptr;
}
if (MDK == Sema::ModuleDeclKind::Interface) {
Diag(StartLoc, diag::err_module_fragment_exported)
<< 0 << FixItHint::CreateRemoval(StartLoc);
}
ImportState = Sema::ModuleImportState::GlobalFragment;
return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
}
if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
NextToken().is(tok::kw_private)) {
if (MDK == Sema::ModuleDeclKind::Interface) {
Diag(StartLoc, diag::err_module_fragment_exported)
<< 1 << FixItHint::CreateRemoval(StartLoc);
}
ConsumeToken();
SourceLocation PrivateLoc = ConsumeToken();
DiagnoseAndSkipCXX11Attributes();
ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
ImportState = Sema::ModuleImportState::PrivateFragment;
return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
}
SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
if (ParseModuleName(ModuleLoc, Path, false))
return nullptr;
SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Partition;
if (Tok.is(tok::colon)) {
SourceLocation ColonLoc = ConsumeToken();
if (!getLangOpts().CPlusPlusModules)
Diag(ColonLoc, diag::err_unsupported_module_partition)
<< SourceRange(ColonLoc, Partition.back().second);
else if (ParseModuleName(ModuleLoc, Partition, false))
return nullptr;
}
ParsedAttributes Attrs(AttrFactory);
MaybeParseCXX11Attributes(Attrs);
ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
false,
true);
ExpectAndConsumeSemi(diag::err_module_expected_semi);
return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
ImportState);
}
Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
Sema::ModuleImportState &ImportState) {
SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc;
SourceLocation ExportLoc;
TryConsumeToken(tok::kw_export, ExportLoc);
assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier)
: Tok.isObjCAtKeyword(tok::objc_import)) &&
"Improper start to module import");
bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
SourceLocation ImportLoc = ConsumeToken();
SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
bool IsPartition = false;
Module *HeaderUnit = nullptr;
if (Tok.is(tok::header_name)) {
ConsumeToken();
} else if (Tok.is(tok::annot_header_unit)) {
HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue());
ConsumeAnnotationToken();
} else if (Tok.is(tok::colon)) {
SourceLocation ColonLoc = ConsumeToken();
if (!getLangOpts().CPlusPlusModules)
Diag(ColonLoc, diag::err_unsupported_module_partition)
<< SourceRange(ColonLoc, Path.back().second);
else if (ParseModuleName(ColonLoc, Path, true))
return nullptr;
else
IsPartition = true;
} else {
if (ParseModuleName(ImportLoc, Path, true))
return nullptr;
}
ParsedAttributes Attrs(AttrFactory);
MaybeParseCXX11Attributes(Attrs);
ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
false,
true);
if (PP.hadModuleLoaderFatalFailure()) {
cutOffParsing();
return nullptr;
}
bool SeenError = true;
switch (ImportState) {
case Sema::ModuleImportState::ImportAllowed:
SeenError = false;
break;
case Sema::ModuleImportState::FirstDecl:
case Sema::ModuleImportState::NotACXX20Module:
if (IsPartition)
Diag(ImportLoc, diag::err_partition_import_outside_module);
else
SeenError = false;
break;
case Sema::ModuleImportState::GlobalFragment:
if (!HeaderUnit || HeaderUnit->Kind != Module::ModuleKind::ModuleHeaderUnit)
Diag(ImportLoc, diag::err_import_in_wrong_fragment) << IsPartition << 0;
else
SeenError = false;
break;
case Sema::ModuleImportState::ImportFinished:
if (getLangOpts().CPlusPlusModules)
Diag(ImportLoc, diag::err_import_not_allowed_here);
else
SeenError = false;
break;
case Sema::ModuleImportState::PrivateFragment:
Diag(ImportLoc, diag::err_import_in_wrong_fragment) << IsPartition << 1;
break;
}
if (SeenError) {
ExpectAndConsumeSemi(diag::err_module_expected_semi);
return nullptr;
}
DeclResult Import;
if (HeaderUnit)
Import =
Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
else if (!Path.empty())
Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
IsPartition);
ExpectAndConsumeSemi(diag::err_module_expected_semi);
if (Import.isInvalid())
return nullptr;
if (IsObjCAtImport && AtLoc.isValid()) {
auto &SrcMgr = PP.getSourceManager();
auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
.endswith(".framework"))
Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
}
return Import.get();
}
bool Parser::ParseModuleName(
SourceLocation UseLoc,
SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
bool IsImport) {
while (true) {
if (!Tok.is(tok::identifier)) {
if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompleteModuleImport(UseLoc, Path);
return true;
}
Diag(Tok, diag::err_module_expected_ident) << IsImport;
SkipUntil(tok::semi);
return true;
}
Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
ConsumeToken();
if (Tok.isNot(tok::period))
return false;
ConsumeToken();
}
}
bool Parser::parseMisplacedModuleImport() {
while (true) {
switch (Tok.getKind()) {
case tok::annot_module_end:
if (MisplacedModuleBeginCount) {
--MisplacedModuleBeginCount;
Actions.ActOnModuleEnd(Tok.getLocation(),
reinterpret_cast<Module *>(
Tok.getAnnotationValue()));
ConsumeAnnotationToken();
continue;
}
return true;
case tok::annot_module_begin:
Actions.ActOnModuleBegin(Tok.getLocation(),
reinterpret_cast<Module *>(
Tok.getAnnotationValue()));
ConsumeAnnotationToken();
++MisplacedModuleBeginCount;
continue;
case tok::annot_module_include:
Actions.ActOnModuleInclude(Tok.getLocation(),
reinterpret_cast<Module *>(
Tok.getAnnotationValue()));
ConsumeAnnotationToken();
continue;
default:
return false;
}
}
return false;
}
bool BalancedDelimiterTracker::diagnoseOverflow() {
P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
<< P.getLangOpts().BracketDepth;
P.Diag(P.Tok, diag::note_bracket_depth);
P.cutOffParsing();
return true;
}
bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
const char *Msg,
tok::TokenKind SkipToTok) {
LOpen = P.Tok.getLocation();
if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
if (SkipToTok != tok::unknown)
P.SkipUntil(SkipToTok, Parser::StopAtSemi);
return true;
}
if (getDepth() < P.getLangOpts().BracketDepth)
return false;
return diagnoseOverflow();
}
bool BalancedDelimiterTracker::diagnoseMissingClose() {
assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
if (P.Tok.is(tok::annot_module_end))
P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
else
P.Diag(P.Tok, diag::err_expected) << Close;
P.Diag(LOpen, diag::note_matching) << Kind;
if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
P.Tok.isNot(tok::r_square) &&
P.SkipUntil(Close, FinalToken,
Parser::StopAtSemi | Parser::StopBeforeMatch) &&
P.Tok.is(Close))
LClose = P.ConsumeAnyToken();
return true;
}
void BalancedDelimiterTracker::skipToEnd() {
P.SkipUntil(Close, Parser::StopBeforeMatch);
consumeClose();
}