#include "clang/Parse/Parser.h"
#include "RAIIObjectsForParser.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/Parse/ParseDiagnostic.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/ParsedTemplate.h"
#include "clang/Sema/Scope.h"
#include "llvm/Support/raw_ostream.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;
}
};
class DestroyTemplateIdAnnotationsRAIIObj {
SmallVectorImpl<TemplateIdAnnotation *> &Container;
public:
DestroyTemplateIdAnnotationsRAIIObj(
SmallVectorImpl<TemplateIdAnnotation *> &Container)
: Container(Container) {}
~DestroyTemplateIdAnnotationsRAIIObj() {
for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I =
Container.begin(),
E = Container.end();
I != E; ++I)
(*I)->Destroy();
Container.clear();
}
};
}
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), 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;
ParenCount = BracketCount = BraceCount = 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) {
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);
}
void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned 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((DeclSpec::TST)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));
}
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 (1) {
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_pragma_openmp_end:
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::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::string_literal:
case tok::wide_string_literal:
case tok::utf8_string_literal:
case tok::utf16_string_literal:
case tok::utf32_string_literal:
ConsumeStringToken();
break;
case tok::semi:
if (HasFlagsSet(Flags, StopAtSemi))
return false;
default:
ConsumeToken();
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();
if (getLangOpts().DelayedTemplateParsing &&
!PP.isIncrementalProcessingEnabled() && !TemplateIds.empty()) {
DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
}
assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
}
void Parser::Initialize() {
assert(getCurScope() == nullptr && "A scope is already active?");
EnterScope(Scope::DeclScope);
Actions.ActOnTranslationUnitScope(getCurScope());
if (getLangOpts().ObjC1) {
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_override = nullptr;
Ident_super = &PP.getIdentifierTable().get("super");
Ident_vector = nullptr;
Ident_bool = nullptr;
Ident_pixel = nullptr;
if (getLangOpts().AltiVec || getLangOpts().ZVector) {
Ident_vector = &PP.getIdentifierTable().get("vector");
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__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);
}
Actions.Initialize();
ConsumeToken();
}
void Parser::LateTemplateParserCleanupCallback(void *P) {
DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(((Parser *)P)->TemplateIds);
}
bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
ConsumeToken();
Result = nullptr;
switch (Tok.getKind()) {
case tok::annot_pragma_unused:
HandlePragmaUnused();
return false;
case tok::annot_module_include:
Actions.ActOnModuleInclude(Tok.getLocation(),
reinterpret_cast<Module *>(
Tok.getAnnotationValue()));
ConsumeToken();
return false;
case tok::annot_module_begin:
Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast<Module *>(
Tok.getAnnotationValue()));
ConsumeToken();
return false;
case tok::annot_module_end:
Actions.ActOnModuleEnd(Tok.getLocation(), reinterpret_cast<Module *>(
Tok.getAnnotationValue()));
ConsumeToken();
return false;
case tok::eof:
if (getLangOpts().DelayedTemplateParsing)
Actions.SetLateTemplateParser(LateTemplateParserCallback,
PP.isIncrementalProcessingEnabled() ?
LateTemplateParserCleanupCallback : nullptr,
this);
if (!PP.isIncrementalProcessingEnabled())
Actions.ActOnEndOfTranslationUnit();
return true;
default:
break;
}
ParsedAttributesWithRange attrs(AttrFactory);
MaybeParseCXX11Attributes(attrs);
MaybeParseMicrosoftAttributes(attrs);
Result = ParseExternalDeclaration(attrs);
return false;
}
Parser::DeclGroupPtrTy
Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
ParsingDeclSpec *DS) {
DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
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_opencl_extension:
HandlePragmaOpenCLExtension();
return nullptr;
case tok::annot_pragma_openmp:
return ParseOpenMPDeclarativeDirective();
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::semi:
SingleDecl = Actions.ActOnEmptyDeclaration(getCurScope(),
attrs.getList(),
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(&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();
case tok::minus:
case tok::plus:
if (!getLangOpts().ObjC1) {
Diag(Tok, diag::err_expected_external_declaration);
ConsumeToken();
return nullptr;
}
SingleDecl = ParseObjCMethodDefinition();
break;
case tok::code_completion:
Actions.CodeCompleteOrdinaryName(getCurScope(),
CurParsedObjCImpl? Sema::PCC_ObjCImplementation
: Sema::PCC_Namespace);
cutOffParsing();
return nullptr;
case tok::kw_using:
case tok::kw_namespace:
case tok::kw_typedef:
case tok::kw_template:
case tok::kw_export: case tok::kw_static_assert:
case tok::kw__Static_assert:
{
SourceLocation DeclEnd;
return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
}
case tok::kw_static:
if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
<< 0;
SourceLocation DeclEnd;
return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
}
goto dont_know;
case tok::kw_inline:
if (getLangOpts().CPlusPlus) {
tok::TokenKind NextKind = NextToken().getKind();
if (NextKind == tok::kw_namespace) {
SourceLocation DeclEnd;
return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
}
if (NextKind == tok::kw_template) {
Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
<< 1;
SourceLocation DeclEnd;
return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
}
}
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(Declarator::FileContext,
ExternLoc, TemplateLoc, DeclEnd));
}
goto dont_know;
case tok::kw___if_exists:
case tok::kw___if_not_exists:
ParseMicrosoftIfExistsExternalDeclaration();
return nullptr;
default:
dont_know:
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(ParsedAttributesWithRange &attrs,
ParsingDeclSpec &DS,
AccessSpecifier AS) {
ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
if (DS.hasTagDefinition() &&
DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_top_level))
return nullptr;
if (Tok.is(tok::semi)) {
ProhibitAttributes(attrs);
ConsumeToken();
Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
DS.complete(TheDecl);
return Actions.ConvertDeclToDeclGroup(TheDecl);
}
DS.takeAttributesFrom(attrs);
if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
SourceLocation AtLoc = ConsumeToken(); if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
!Tok.isObjCAtKeyword(tok::objc_protocol)) {
Diag(Tok, diag::err_objc_unexpected_attr);
SkipUntil(tok::semi); return nullptr;
}
DS.abort();
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());
return Actions.ConvertDeclToDeclGroup(
ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
}
if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
return Actions.ConvertDeclToDeclGroup(TheDecl);
}
return ParseDeclGroup(DS, Declarator::FileContext);
}
Parser::DeclGroupPtrTy
Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &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();
if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
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)) {
AttributeList *DtorAttrs = D.getAttributes();
while (DtorAttrs) {
if (DtorAttrs->isKnownToGCC() &&
!DtorAttrs->isCXX11Attribute()) {
Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
<< DtorAttrs->getName();
}
DtorAttrs = DtorAttrs->getNext();
}
}
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 *ParentScope = getCurScope()->getParent();
D.setFunctionDefinitionKind(FDK_Definition);
Decl *DP = Actions.HandleDeclarator(ParentScope, D,
TemplateParameterLists);
D.complete(DP);
D.getMutableDeclSpec().abort();
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 *ParentScope = getCurScope()->getParent();
D.setFunctionDefinitionKind(FDK_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);
Sema::SkipBodyInfo SkipBody;
Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
TemplateInfo.TemplateParams
? *TemplateInfo.TemplateParams
: MultiTemplateParamsArg(),
&SkipBody);
if (SkipBody.ShouldSkip) {
SkipFunctionBody();
return Res;
}
D.complete(Res);
D.getMutableDeclSpec().abort();
if (TryConsumeToken(tok::equal)) {
assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
bool Delete = false;
SourceLocation KWLoc;
if (TryConsumeToken(tok::kw_delete, KWLoc)) {
Diag(KWLoc, getLangOpts().CPlusPlus11
? diag::warn_cxx98_compat_defaulted_deleted_function
: diag::ext_defaulted_deleted_function)
<< 1 ;
Actions.SetDeclDeleted(Res, KWLoc);
Delete = true;
} else if (TryConsumeToken(tok::kw_default, KWLoc)) {
Diag(KWLoc, getLangOpts().CPlusPlus11
? diag::warn_cxx98_compat_defaulted_deleted_function
: diag::ext_defaulted_deleted_function)
<< 0 ;
Actions.SetDeclDefaulted(Res, KWLoc);
} else {
llvm_unreachable("function definition after = not 'delete' or 'default'");
}
if (Tok.is(tok::comma)) {
Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
<< Delete;
SkipUntil(tok::semi);
} else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
Delete ? "delete" : "default")) {
SkipUntil(tok::semi);
}
Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
return Res;
}
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, Declarator::KNRTypeListContext);
ParseDeclarator(ParmDeclarator);
while (1) {
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() {
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->isAscii()) {
Diag(Tok, diag::err_asm_operand_wide_string_literal)
<< SL->isWide()
<< SL->getSourceRange();
return ExprError();
}
}
return AsmString;
}
ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
assert(Tok.is(tok::kw_asm) && "Not an asm!");
SourceLocation Loc = ConsumeToken();
if (Tok.is(tok::kw_volatile)) {
SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
PP.getLocForEndOfToken(Tok.getLocation()));
Diag(Tok, diag::warn_file_asm_volatile)
<< 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());
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);
Tok.setKind(tok::annot_cxxscope);
Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
Tok.setAnnotationRange(SS.getRange());
if (IsNewAnnotation)
PP.AnnotateCachedTokens(Tok);
}
Parser::AnnotatedNameKind
Parser::TryAnnotateName(bool IsAddressOfOperand,
std::unique_ptr<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, EnteringContext))
return ANK_Error;
if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
!WasScopeAnnotation))
return ANK_Error;
return ANK_Unresolved;
}
IdentifierInfo *Name = Tok.getIdentifierInfo();
SourceLocation NameLoc = Tok.getLocation();
if (isTentativelyDeclared(Name)) {
if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, 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, IsAddressOfOperand,
SS.isEmpty() ? std::move(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: {
SourceLocation BeginLoc = NameLoc;
if (SS.isNotEmpty())
BeginLoc = SS.getBeginLoc();
ParsedType Ty = Classification.getType();
if (getLangOpts().ObjC1 && 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();
}
Tok.setKind(tok::annot_typename);
setTypeAnnotation(Tok, Ty);
Tok.setAnnotationEndLoc(Tok.getLocation());
Tok.setLocation(BeginLoc);
PP.AnnotateCachedTokens(Tok);
return ANK_Success;
}
case Sema::NC_Expression:
Tok.setKind(tok::annot_primary_expr);
setExprAnnotation(Tok, Classification.getExpression());
Tok.setAnnotationEndLoc(NameLoc);
if (SS.isNotEmpty())
Tok.setLocation(SS.getBeginLoc());
PP.AnnotateCachedTokens(Tok);
return ANK_Success;
case Sema::NC_TypeTemplate:
if (Next.isNot(tok::less)) {
if (SS.isNotEmpty())
AnnotateScopeToken(SS, !WasScopeAnnotation);
return ANK_TemplateName;
}
case Sema::NC_VarTemplate:
case Sema::NC_FunctionTemplate: {
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_NestedNameSpecifier:
llvm_unreachable("already parsed nested name specifier");
}
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(bool EnteringContext, bool NeedType) {
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(EnteringContext, NeedType);
PP.EnterToken(Tok);
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, nullptr,
true))
return true;
if (!SS.isSet()) {
if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
Tok.is(tok::annot_decltype)) {
if (Tok.is(tok::annot_decltype) ||
(!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) &&
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;
}
}
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->Kind != TNK_Type_template &&
TemplateId->Kind != TNK_Dependent_template_name) {
Diag(Tok, diag::err_typename_refers_to_non_type_template)
<< Tok.getAnnotationRange();
return true;
}
ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
TemplateId->NumArgs);
Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
TemplateId->TemplateKWLoc,
TemplateId->Template,
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.isInvalid() ? nullptr : Ty.get());
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, EnteringContext))
return true;
return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType,
SS, !WasScopeAnnotation);
}
bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
bool NeedType,
CXXScopeSpec &SS,
bool IsNewScope) {
if (Tok.is(tok::identifier)) {
IdentifierInfo *CorrectedII = nullptr;
if (ParsedType Ty = Actions.getTypeName(
*Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
false, NextToken().is(tok::period), nullptr,
false,
true,
NeedType ? &CorrectedII : nullptr)) {
if (CorrectedII)
Tok.setIdentifierInfo(CorrectedII);
SourceLocation BeginLoc = Tok.getLocation();
if (SS.isNotEmpty()) BeginLoc = SS.getBeginLoc();
if (getLangOpts().ObjC1 && 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();
}
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, EnteringContext,
Template, MemberOfUnknownSpecialization)) {
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();
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((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
(Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super)) &&
"Cannot be a type or scope token!");
CXXScopeSpec SS;
if (ParseOptionalCXXScopeSpecifier(SS, nullptr, 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()), "=");
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->getFlags() & Scope::FnScope) {
Actions.CodeCompleteOrdinaryName(getCurScope(),
Sema::PCC_RecoveryInFunction);
cutOffParsing();
return PrevTokLocation;
}
if (S->getFlags() & Scope::ClassScope) {
Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
cutOffParsing();
return PrevTokLocation;
}
}
Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
cutOffParsing();
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::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);
if (Result.SS.isInvalid()) {
T.skipToEnd();
return true;
}
SourceLocation TemplateKWLoc; if (ParseUnqualifiedId(Result.SS, false, true, true, nullptr, 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()) {
ParsedAttributesWithRange attrs(AttrFactory);
MaybeParseCXX11Attributes(attrs);
MaybeParseMicrosoftAttributes(attrs);
DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
if (Result && !getCurScope()->getParent())
Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
}
Braces.consumeClose();
}
Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
assert(Tok.isObjCAtKeyword(tok::objc_import) &&
"Improper start to module import");
SourceLocation ImportLoc = ConsumeToken();
SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
do {
if (!Tok.is(tok::identifier)) {
if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteModuleImport(ImportLoc, Path);
cutOffParsing();
return nullptr;
}
Diag(Tok, diag::err_module_expected_ident);
SkipUntil(tok::semi);
return nullptr;
}
Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
ConsumeToken();
if (Tok.is(tok::period)) {
ConsumeToken();
continue;
}
break;
} while (true);
if (PP.hadModuleLoaderFatalFailure()) {
cutOffParsing();
return nullptr;
}
DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
ExpectAndConsumeSemi(diag::err_module_expected_semi);
if (Import.isInvalid())
return nullptr;
return Actions.ConvertDeclToDeclGroup(Import.get());
}
bool Parser::parseMisplacedModuleImport() {
while (true) {
switch (Tok.getKind()) {
case tok::annot_module_end:
return true;
case tok::annot_module_begin:
Actions.diagnoseMisplacedModuleImport(reinterpret_cast<Module *>(
Tok.getAnnotationValue()), Tok.getLocation());
return true;
case tok::annot_module_include:
Actions.ActOnModuleInclude(Tok.getLocation(),
reinterpret_cast<Module *>(
Tok.getAnnotationValue()));
ConsumeToken();
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() < MaxDepth)
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();
}