#include "clang/Parse/Parser.h"
#include "clang/Parse/ParseDiagnostic.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ParsedTemplate.h"
#include "llvm/Support/raw_ostream.h"
#include "RAIIObjectsForParser.h"
#include "ParsePragma.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/ASTConsumer.h"
using namespace clang;
namespace {
class ActionCommentHandler : public CommentHandler {
Sema &S;
public:
explicit ActionCommentHandler(Sema &S) : S(S) { }
virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) {
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), Actions(actions), Diags(PP.getDiagnostics()),
GreaterThanIsOperator(true), ColonIsSacred(false),
InMessageExpression(false), TemplateParameterDepth(0),
ParsingInObjCContainer(false), SkipFunctionBodies(SkipFunctionBodies) {
Tok.setKind(tok::eof);
Actions.CurScope = 0;
NumCachedScopes = 0;
ParenCount = BracketCount = BraceCount = 0;
CurParsedObjCImpl = 0;
AlignHandler.reset(new PragmaAlignHandler());
PP.AddPragmaHandler(AlignHandler.get());
GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler());
PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
OptionsHandler.reset(new PragmaOptionsHandler());
PP.AddPragmaHandler(OptionsHandler.get());
PackHandler.reset(new PragmaPackHandler());
PP.AddPragmaHandler(PackHandler.get());
MSStructHandler.reset(new PragmaMSStructHandler());
PP.AddPragmaHandler(MSStructHandler.get());
UnusedHandler.reset(new PragmaUnusedHandler());
PP.AddPragmaHandler(UnusedHandler.get());
WeakHandler.reset(new PragmaWeakHandler());
PP.AddPragmaHandler(WeakHandler.get());
RedefineExtnameHandler.reset(new PragmaRedefineExtnameHandler());
PP.AddPragmaHandler(RedefineExtnameHandler.get());
FPContractHandler.reset(new PragmaFPContractHandler());
PP.AddPragmaHandler("STDC", FPContractHandler.get());
if (getLangOpts().OpenCL) {
OpenCLExtensionHandler.reset(new PragmaOpenCLExtensionHandler());
PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
}
CommentSemaHandler.reset(new ActionCommentHandler(actions));
PP.addCommentHandler(CommentSemaHandler.get());
PP.setCodeCompletionHandler(*this);
}
void PrettyStackTraceParserEntry::print(raw_ostream &OS) const {
const Token &Tok = P.getCurToken();
if (Tok.is(tok::eof)) {
OS << "<eof> parser at end of file\n";
return;
}
if (Tok.getLocation().isInvalid()) {
OS << "<unknown> parser at unknown location\n";
return;
}
const Preprocessor &PP = P.getPreprocessor();
Tok.getLocation().print(OS, PP.getSourceManager());
if (Tok.isAnnotation())
OS << ": at annotation token \n";
else
OS << ": current parser token '" << PP.getSpelling(Tok) << "'\n";
}
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,
const char *Msg, tok::TokenKind SkipToTok) {
if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
ConsumeAnyToken();
return false;
}
if (IsCommonTypo(ExpectedTok, Tok)) {
SourceLocation Loc = Tok.getLocation();
Diag(Loc, DiagID)
<< Msg
<< FixItHint::CreateReplacement(SourceRange(Loc),
getTokenSimpleSpelling(ExpectedTok));
ConsumeAnyToken();
return false;
}
const char *Spelling = 0;
SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
if (EndLoc.isValid() &&
(Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) {
Diag(EndLoc, DiagID)
<< Msg
<< FixItHint::CreateInsertion(EndLoc, Spelling);
} else
Diag(Tok, DiagID) << Msg;
if (SkipToTok != tok::unknown)
SkipUntil(SkipToTok);
return true;
}
bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
if (Tok.is(tok::semi) || Tok.is(tok::code_completion)) {
ConsumeToken();
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().CPlusPlus0x)
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)
<< FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
else
Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
<< FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
}
bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, bool StopAtSemi,
bool DontConsume, bool StopAtCodeCompletion) {
bool isFirstTokenSkipped = true;
while (1) {
for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
if (Tok.is(Toks[i])) {
if (DontConsume) {
} else {
ConsumeAnyToken();
}
return true;
}
}
switch (Tok.getKind()) {
case tok::eof:
return false;
case tok::code_completion:
if (!StopAtCodeCompletion)
ConsumeToken();
return false;
case tok::l_paren:
ConsumeParen();
SkipUntil(tok::r_paren, false, false, StopAtCodeCompletion);
break;
case tok::l_square:
ConsumeBracket();
SkipUntil(tok::r_square, false, false, StopAtCodeCompletion);
break;
case tok::l_brace:
ConsumeBrace();
SkipUntil(tok::r_brace, false, false, StopAtCodeCompletion);
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 (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!");
if (!getCurScope()->decl_empty())
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() : 0) {
if (CurScope) {
OldFlags = CurScope->getFlags();
CurScope->setFlags(ScopeFlags);
}
}
Parser::ParseScopeFlags::~ParseScopeFlags() {
if (CurScope)
CurScope->setFlags(OldFlags);
}
Parser::~Parser() {
delete getCurScope();
Actions.CurScope = 0;
for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
delete ScopeCache[i];
for (LateParsedTemplateMapT::iterator it = LateParsedTemplateMap.begin();
it != LateParsedTemplateMap.end(); ++it)
delete it->second;
PP.RemovePragmaHandler(AlignHandler.get());
AlignHandler.reset();
PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
GCCVisibilityHandler.reset();
PP.RemovePragmaHandler(OptionsHandler.get());
OptionsHandler.reset();
PP.RemovePragmaHandler(PackHandler.get());
PackHandler.reset();
PP.RemovePragmaHandler(MSStructHandler.get());
MSStructHandler.reset();
PP.RemovePragmaHandler(UnusedHandler.get());
UnusedHandler.reset();
PP.RemovePragmaHandler(WeakHandler.get());
WeakHandler.reset();
PP.RemovePragmaHandler(RedefineExtnameHandler.get());
RedefineExtnameHandler.reset();
if (getLangOpts().OpenCL) {
PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
OpenCLExtensionHandler.reset();
PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
}
PP.RemovePragmaHandler("STDC", FPContractHandler.get());
FPContractHandler.reset();
PP.removeCommentHandler(CommentSemaHandler.get());
PP.clearCodeCompletionHandler();
assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
}
void Parser::Initialize() {
assert(getCurScope() == 0 && "A scope is already active?");
EnterScope(Scope::DeclScope);
Actions.ActOnTranslationUnitScope(getCurScope());
ConsumeToken();
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");
}
Ident_instancetype = 0;
Ident_final = 0;
Ident_override = 0;
Ident_super = &PP.getIdentifierTable().get("super");
if (getLangOpts().AltiVec) {
Ident_vector = &PP.getIdentifierTable().get("vector");
Ident_pixel = &PP.getIdentifierTable().get("pixel");
}
Ident_introduced = 0;
Ident_deprecated = 0;
Ident_obsoleted = 0;
Ident_unavailable = 0;
Ident__except = 0;
Ident__exception_code = Ident__exception_info = Ident__abnormal_termination = 0;
Ident___exception_code = Ident___exception_info = Ident___abnormal_termination = 0;
Ident_GetExceptionCode = Ident_GetExceptionInfo = Ident_AbnormalTermination = 0;
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);
}
}
namespace {
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();
}
};
}
bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
ConsumeToken();
while (Tok.is(tok::annot_pragma_unused))
HandlePragmaUnused();
Result = DeclGroupPtrTy();
if (Tok.is(tok::eof)) {
if (getLangOpts().DelayedTemplateParsing)
Actions.SetLateTemplateParser(LateTemplateParserCallback, this);
if (!PP.isIncrementalProcessingEnabled())
Actions.ActOnEndOfTranslationUnit();
return true;
}
ParsedAttributesWithRange attrs(AttrFactory);
MaybeParseCXX0XAttributes(attrs);
MaybeParseMicrosoftAttributes(attrs);
Result = ParseExternalDeclaration(attrs);
return false;
}
void Parser::ParseTranslationUnit() {
Initialize();
DeclGroupPtrTy Res;
while (!ParseTopLevelDecl(Res))
;
ExitScope();
assert(getCurScope() == 0 && "Scope imbalance!");
}
Parser::DeclGroupPtrTy
Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
ParsingDeclSpec *DS) {
DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
ParenBraceBracketBalancer BalancerRAIIObj(*this);
if (PP.isCodeCompletionReached()) {
cutOffParsing();
return DeclGroupPtrTy();
}
Decl *SingleDecl = 0;
switch (Tok.getKind()) {
case tok::annot_pragma_vis:
HandlePragmaVisibility();
return DeclGroupPtrTy();
case tok::annot_pragma_pack:
HandlePragmaPack();
return DeclGroupPtrTy();
case tok::annot_pragma_msstruct:
HandlePragmaMSStruct();
return DeclGroupPtrTy();
case tok::annot_pragma_align:
HandlePragmaAlign();
return DeclGroupPtrTy();
case tok::annot_pragma_weak:
HandlePragmaWeak();
return DeclGroupPtrTy();
case tok::annot_pragma_weakalias:
HandlePragmaWeakAlias();
return DeclGroupPtrTy();
case tok::annot_pragma_redefine_extname:
HandlePragmaRedefineExtname();
return DeclGroupPtrTy();
case tok::annot_pragma_fp_contract:
HandlePragmaFPContract();
return DeclGroupPtrTy();
case tok::annot_pragma_opencl_extension:
HandlePragmaOpenCLExtension();
return DeclGroupPtrTy();
case tok::semi:
ConsumeExtraSemi(OutsideFunction);
return DeclGroupPtrTy();
case tok::r_brace:
Diag(Tok, diag::err_extraneous_closing_brace);
ConsumeBrace();
return DeclGroupPtrTy();
case tok::eof:
Diag(Tok, diag::err_expected_external_declaration);
return DeclGroupPtrTy();
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));
ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
"top-level asm block");
if (Result.isInvalid())
return DeclGroupPtrTy();
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 DeclGroupPtrTy();
}
SingleDecl = ParseObjCMethodDefinition();
break;
case tok::code_completion:
Actions.CodeCompleteOrdinaryName(getCurScope(),
CurParsedObjCImpl? Sema::PCC_ObjCImplementation
: Sema::PCC_Namespace);
cutOffParsing();
return DeclGroupPtrTy();
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;
StmtVector Stmts;
return ParseDeclaration(Stmts, 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;
StmtVector Stmts;
return ParseDeclaration(Stmts, 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;
StmtVector Stmts;
return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
}
if (NextKind == tok::kw_template) {
Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
<< 1;
SourceLocation DeclEnd;
StmtVector Stmts;
return ParseDeclaration(Stmts, 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().CPlusPlus0x ?
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 DeclGroupPtrTy();
default:
dont_know:
if (DS) {
return ParseDeclarationOrFunctionDefinition(attrs, DS);
} else {
return ParseDeclarationOrFunctionDefinition(attrs);
}
}
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 (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 DeclGroupPtrTy();
}
DS.abort();
const char *PrevSpec = 0;
unsigned DiagID;
if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID))
Diag(AtLoc, DiagID) << PrevSpec;
if (Tok.isObjCAtKeyword(tok::objc_protocol))
return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
return Actions.ConvertDeclToDeclGroup(
ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
}
if (Tok.is(tok::string_literal) && getLangOpts().CPlusPlus &&
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, true);
}
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;
D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
D.getIdentifierLoc(),
PrevSpec, DiagID);
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, true, true);
if (Tok.isNot(tok::l_brace))
return 0;
}
if (Tok.isNot(tok::equal)) {
AttributeList *DtorAttrs = D.getAttributes();
while (DtorAttrs) {
if (!IsThreadSafetyAttribute(DtorAttrs->getName()->getName())) {
Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
<< DtorAttrs->getName()->getName();
}
DtorAttrs = DtorAttrs->getNext();
}
}
if (getLangOpts().DelayedTemplateParsing &&
Tok.isNot(tok::equal) &&
TemplateInfo.Kind == ParsedTemplateInfo::Template) {
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();
if (DP) {
LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(DP);
FunctionDecl *FnD = 0;
if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(DP))
FnD = FunTmpl->getTemplatedDecl();
else
FnD = cast<FunctionDecl>(DP);
Actions.CheckForFunctionRedefinition(FnD);
LateParsedTemplateMap[FnD] = LPT;
Actions.MarkAsLateParsedTemplate(FnD);
LexTemplateFunctionForLateParsing(LPT->Toks);
} else {
CachedTokens Toks;
LexTemplateFunctionForLateParsing(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);
Decl *Res = TemplateInfo.TemplateParams?
Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
*TemplateInfo.TemplateParams, D)
: Actions.ActOnStartOfFunctionDef(getCurScope(), D);
D.complete(Res);
D.getMutableDeclSpec().abort();
if (Tok.is(tok::equal)) {
assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
ConsumeToken();
Actions.ActOnFinishFunctionBody(Res, 0, false);
bool Delete = false;
SourceLocation KWLoc;
if (Tok.is(tok::kw_delete)) {
Diag(Tok, getLangOpts().CPlusPlus0x ?
diag::warn_cxx98_compat_deleted_function :
diag::ext_deleted_function);
KWLoc = ConsumeToken();
Actions.SetDeclDeleted(Res, KWLoc);
Delete = true;
} else if (Tok.is(tok::kw_default)) {
Diag(Tok, getLangOpts().CPlusPlus0x ?
diag::warn_cxx98_compat_defaulted_function :
diag::ext_defaulted_function);
KWLoc = ConsumeToken();
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 {
ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
Delete ? "delete" : "default", tok::semi);
}
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, 0);
return Res;
}
} else
Actions.ActOnDefaultCtorInitializers(Res);
if (LateParsedAttrs)
ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
return ParseFunctionStatementBody(Res, BodyScope);
}
void Parser::ParseKNRParamDeclarations(Declarator &D) {
DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope);
while (isDeclarationSpecifier()) {
SourceLocation DSStart = Tok.getLocation();
DeclSpec DS(AttrFactory);
ParseDeclarationSpecifiers(DS);
if (Tok.is(tok::semi)) {
Diag(DSStart, diag::err_declaration_does_not_declare_param);
ConsumeToken();
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.isThreadSpecified()) {
Diag(DS.getThreadSpecLoc(),
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.NumArgs) {
Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
<< ParmDeclarator.getIdentifier();
break;
}
if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
if (FTI.ArgInfo[i].Param) {
Diag(ParmDeclarator.getIdentifierLoc(),
diag::err_param_redefinition)
<< ParmDeclarator.getIdentifier();
} else {
FTI.ArgInfo[i].Param = Param;
}
break;
}
}
}
if (Tok.isNot(tok::comma))
break;
ParmDeclarator.clear();
ParmDeclarator.setCommaLoc(ConsumeToken());
ParseDeclarator(ParmDeclarator);
}
if (ExpectAndConsumeSemi(diag::err_expected_semi_declaration)) {
SkipUntil(tok::semi, true);
if (Tok.is(tok::semi))
ConsumeToken();
}
}
Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
}
Parser::ExprResult Parser::ParseAsmStringLiteral() {
switch (Tok.getKind()) {
case tok::string_literal:
break;
case tok::utf8_string_literal:
case tok::utf16_string_literal:
case tok::utf32_string_literal:
case tok::wide_string_literal: {
SourceLocation L = Tok.getLocation();
Diag(Tok, diag::err_asm_operand_wide_string_literal)
<< (Tok.getKind() == tok::wide_string_literal)
<< SourceRange(L, L);
return ExprError();
}
default:
Diag(Tok, diag::err_expected_string_literal);
return ExprError();
}
return ParseStringLiteralExpression();
}
Parser::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()) {
SkipUntil(tok::r_paren, true, true);
if (EndLoc)
*EndLoc = Tok.getLocation();
ConsumeAnyToken();
} else {
T.consumeClose();
if (EndLoc)
*EndLoc = T.getCloseLocation();
}
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,
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, ParsedType(), 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() ? CCC : 0);
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:
Tok.setKind(tok::annot_typename);
setTypeAnnotation(Tok, Classification.getType());
Tok.setAnnotationEndLoc(NameLoc);
if (SS.isNotEmpty())
Tok.setLocation(SS.getBeginLoc());
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_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::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))
&& "Cannot be a type or scope token!");
if (Tok.is(tok::kw_typename)) {
SourceLocation TypenameLoc = ConsumeToken();
CXXScopeSpec SS;
if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
false,
0, 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_Function_template) {
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() ? ParsedType() : 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, ParsedType(), 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 = 0;
if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
Tok.getLocation(), getCurScope(),
&SS, false,
NextToken().is(tok::period),
ParsedType(),
false,
true,
NeedType ? &CorrectedII : NULL)) {
if (CorrectedII)
Tok.setIdentifierInfo(CorrectedII);
Tok.setKind(tok::annot_typename);
setTypeAnnotation(Tok, Ty);
Tok.setAnnotationEndLoc(Tok.getLocation());
if (SS.isNotEmpty()) Tok.setLocation(SS.getBeginLoc());
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,
ParsedType(),
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)) && "Cannot be a type or scope token!");
CXXScopeSpec SS;
if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 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)
<< getTokenSimpleSpelling(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::FieldCallback::_anchor() {
}
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;
}
ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(),
false);
if (Result.SS.isInvalid()) {
T.skipToEnd();
return true;
}
SourceLocation TemplateKWLoc; if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
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_lbrace);
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) && Tok.isNot(tok::eof)) {
ParsedAttributesWithRange attrs(AttrFactory);
MaybeParseCXX0XAttributes(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___experimental_modules_import) &&
"Improper start to module import");
SourceLocation ImportLoc = ConsumeToken();
llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
do {
if (!Tok.is(tok::identifier)) {
if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteModuleImport(ImportLoc, Path);
ConsumeCodeCompletionToken();
SkipUntil(tok::semi);
return DeclGroupPtrTy();
}
Diag(Tok, diag::err_module_expected_ident);
SkipUntil(tok::semi);
return DeclGroupPtrTy();
}
Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
ConsumeToken();
if (Tok.is(tok::period)) {
ConsumeToken();
continue;
}
break;
} while (true);
DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
ExpectAndConsumeSemi(diag::err_module_expected_semi);
if (Import.isInvalid())
return DeclGroupPtrTy();
return Actions.ConvertDeclToDeclGroup(Import.get());
}
bool BalancedDelimiterTracker::diagnoseOverflow() {
P.Diag(P.Tok, diag::err_parser_impl_limit_overflow);
P.SkipUntil(tok::eof);
return true;
}
bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
const char *Msg,
tok::TokenKind SkipToToc ) {
LOpen = P.Tok.getLocation();
if (P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc))
return true;
if (getDepth() < MaxDepth)
return false;
return diagnoseOverflow();
}
bool BalancedDelimiterTracker::diagnoseMissingClose() {
assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
const char *LHSName = "unknown";
diag::kind DID;
switch (Close) {
default: llvm_unreachable("Unexpected balanced token");
case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
}
P.Diag(P.Tok, DID);
P.Diag(LOpen, diag::note_matching) << LHSName;
if (P.SkipUntil(Close))
LClose = P.Tok.getLocation();
return true;
}
void BalancedDelimiterTracker::skipToEnd() {
P.SkipUntil(Close, false);
}