#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"
using namespace clang;
Parser::Parser(Preprocessor &pp, Sema &actions)
: PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
GreaterThanIsOperator(true), ColonIsSacred(false),
InMessageExpression(false), TemplateParameterDepth(0) {
Tok.setKind(tok::eof);
Actions.CurScope = 0;
NumCachedScopes = 0;
ParenCount = BracketCount = BraceCount = 0;
ObjCImpDecl = 0;
AlignHandler.reset(new PragmaAlignHandler(actions));
PP.AddPragmaHandler(AlignHandler.get());
GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler(actions));
PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
OptionsHandler.reset(new PragmaOptionsHandler(actions));
PP.AddPragmaHandler(OptionsHandler.get());
PackHandler.reset(new PragmaPackHandler(actions));
PP.AddPragmaHandler(PackHandler.get());
MSStructHandler.reset(new PragmaMSStructHandler(actions));
PP.AddPragmaHandler(MSStructHandler.get());
UnusedHandler.reset(new PragmaUnusedHandler(actions, *this));
PP.AddPragmaHandler(UnusedHandler.get());
WeakHandler.reset(new PragmaWeakHandler(actions));
PP.AddPragmaHandler(WeakHandler.get());
FPContractHandler.reset(new PragmaFPContractHandler(actions, *this));
PP.AddPragmaHandler("STDC", FPContractHandler.get());
if (getLang().OpenCL) {
OpenCLExtensionHandler.reset(
new PragmaOpenCLExtensionHandler(actions, *this));
PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
}
PP.setCodeCompletionHandler(*this);
}
void PrettyStackTraceParserEntry::print(llvm::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, ")");
}
SourceLocation Parser::MatchRHSPunctuation(tok::TokenKind RHSTok,
SourceLocation LHSLoc) {
if (Tok.is(RHSTok))
return ConsumeAnyToken();
SourceLocation R = Tok.getLocation();
const char *LHSName = "unknown";
diag::kind DID = diag::err_parse_error;
switch (RHSTok) {
default: break;
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;
case tok::greater: LHSName = "<"; DID = diag::err_expected_greater; break;
case tok::greatergreatergreater:
LHSName = "<<<"; DID = diag::err_expected_ggg; break;
}
Diag(Tok, DID);
Diag(LHSLoc, diag::note_matching) << LHSName;
SkipUntil(RHSTok);
return R;
}
static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
switch (ExpectedTok) {
case tok::semi: return Tok.is(tok::colon); 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)) {
ConsumeAnyToken();
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);
}
bool Parser::SkipUntil(const tok::TokenKind *Toks, unsigned NumToks,
bool StopAtSemi, bool DontConsume,
bool StopAtCodeCompletion) {
bool isFirstTokenSkipped = true;
while (1) {
for (unsigned i = 0; 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:
ConsumeStringToken();
break;
case tok::at:
return false;
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::~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();
if (getLang().OpenCL) {
PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
OpenCLExtensionHandler.reset();
PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
}
PP.RemovePragmaHandler("STDC", FPContractHandler.get());
FPContractHandler.reset();
PP.clearCodeCompletionHandler();
}
void Parser::Initialize() {
assert(getCurScope() == 0 && "A scope is already active?");
EnterScope(Scope::DeclScope);
Actions.ActOnTranslationUnitScope(getCurScope());
ConsumeToken();
if (Tok.is(tok::eof) &&
!getLang().CPlusPlus) Diag(Tok, diag::ext_empty_source_file);
if (getLang().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_final = 0;
Ident_override = 0;
Ident_super = &PP.getIdentifierTable().get("super");
if (getLang().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__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(getLang().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);
}
}
bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
while (Tok.is(tok::annot_pragma_unused))
HandlePragmaUnused();
Result = DeclGroupPtrTy();
if (Tok.is(tok::eof)) {
if (getLang().DelayedTemplateParsing)
Actions.SetLateTemplateParser(LateTemplateParserCallback, this);
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) {
ParenBraceBracketBalancer BalancerRAIIObj(*this);
Decl *SingleDecl = 0;
switch (Tok.getKind()) {
case tok::semi:
if (!getLang().CPlusPlus0x)
Diag(Tok, diag::ext_top_level_semi)
<< FixItHint::CreateRemoval(Tok.getLocation());
ConsumeToken();
return DeclGroupPtrTy();
case tok::r_brace:
Diag(Tok, diag::err_expected_external_declaration);
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:
SingleDecl = ParseObjCAtDirectives();
break;
case tok::minus:
case tok::plus:
if (!getLang().ObjC1) {
Diag(Tok, diag::err_expected_external_declaration);
ConsumeToken();
return DeclGroupPtrTy();
}
SingleDecl = ParseObjCMethodDefinition();
break;
case tok::code_completion:
Actions.CodeCompleteOrdinaryName(getCurScope(),
ObjCImpDecl? Sema::PCC_ObjCImplementation
: Sema::PCC_Namespace);
ConsumeCodeCompletionToken();
return ParseExternalDeclaration(attrs);
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(Actions);
return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
}
case tok::kw_static:
if (getLang().CPlusPlus && NextToken().is(tok::kw_template)) {
Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
<< 0;
SourceLocation DeclEnd;
StmtVector Stmts(Actions);
return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
}
goto dont_know;
case tok::kw_inline:
if (getLang().CPlusPlus) {
tok::TokenKind NextKind = NextToken().getKind();
if (NextKind == tok::kw_namespace) {
SourceLocation DeclEnd;
StmtVector Stmts(Actions);
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(Actions);
return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
}
}
goto dont_know;
case tok::kw_extern:
if (getLang().CPlusPlus && NextToken().is(tok::kw_template)) {
SourceLocation ExternLoc = ConsumeToken();
SourceLocation TemplateLoc = ConsumeToken();
SourceLocation DeclEnd;
return Actions.ConvertDeclToDeclGroup(
ParseExplicitInstantiation(ExternLoc, TemplateLoc, DeclEnd));
}
goto dont_know;
default:
dont_know:
if (DS) {
DS->takeAttributesFrom(attrs);
return ParseDeclarationOrFunctionDefinition(*DS);
} else {
return ParseDeclarationOrFunctionDefinition(attrs);
}
}
return Actions.ConvertDeclToDeclGroup(SingleDecl);
}
bool Parser::isDeclarationAfterDeclarator() const {
return Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::semi) || Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute) || (getLang().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 (!getLang().CPlusPlus &&
Declarator.getFunctionTypeInfo().isKNRPrototype())
return isDeclarationSpecifier();
return Tok.is(tok::colon) || Tok.is(tok::kw_try); }
Parser::DeclGroupPtrTy
Parser::ParseDeclarationOrFunctionDefinition(ParsingDeclSpec &DS,
AccessSpecifier AS) {
ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
if (Tok.is(tok::semi)) {
ConsumeToken();
Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
DS.complete(TheDecl);
return Actions.ConvertDeclToDeclGroup(TheDecl);
}
if (getLang().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;
Decl *TheDecl = 0;
if (Tok.isObjCAtKeyword(tok::objc_protocol))
TheDecl = ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
else
TheDecl = ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes());
return Actions.ConvertDeclToDeclGroup(TheDecl);
}
if (Tok.is(tok::string_literal) && getLang().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(ParsedAttributes &attrs,
AccessSpecifier AS) {
ParsingDeclSpec DS(*this);
DS.takeAttributesFrom(attrs);
return ParseDeclarationOrFunctionDefinition(DS, AS);
}
Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
const ParsedTemplateInfo &TemplateInfo) {
PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
if (getLang().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) &&
(!getLang().CPlusPlus ||
(Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try)))) {
Diag(Tok, diag::err_expected_fn_body);
SkipUntil(tok::l_brace, true, true);
if (Tok.isNot(tok::l_brace))
return 0;
}
if (getLang().DelayedTemplateParsing &&
TemplateInfo.Kind == ParsedTemplateInfo::Template) {
MultiTemplateParamsArg TemplateParameterLists(Actions,
TemplateInfo.TemplateParams->data(),
TemplateInfo.TemplateParams->size());
ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
Scope *ParentScope = getCurScope()->getParent();
Decl *DP = Actions.HandleDeclarator(ParentScope, D,
move(TemplateParameterLists),
true);
D.complete(DP);
D.getMutableDeclSpec().abort();
if (DP) {
LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(this, 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;
}
ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
Decl *Res = TemplateInfo.TemplateParams?
Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
MultiTemplateParamsArg(Actions,
TemplateInfo.TemplateParams->data(),
TemplateInfo.TemplateParams->size()),
D)
: Actions.ActOnStartOfFunctionDef(getCurScope(), D);
D.complete(Res);
D.getMutableDeclSpec().abort();
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);
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;
ConsumeToken();
ParmDeclarator.clear();
ParseDeclarator(ParmDeclarator);
}
if (Tok.is(tok::semi)) {
ConsumeToken();
} else {
Diag(Tok, diag::err_parse_error);
SkipUntil(tok::semi, true);
if (Tok.is(tok::semi))
ConsumeToken();
}
}
Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
}
Parser::ExprResult Parser::ParseAsmStringLiteral() {
if (!isTokenStringLiteral()) {
Diag(Tok, diag::err_expected_string_literal);
return ExprError();
}
ExprResult Res(ParseStringLiteralExpression());
if (Res.isInvalid()) return move(Res);
return move(Res);
}
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();
}
if (Tok.isNot(tok::l_paren)) {
Diag(Tok, diag::err_expected_lparen_after) << "asm";
return ExprError();
}
Loc = ConsumeParen();
ExprResult Result(ParseAsmStringLiteral());
if (Result.isInvalid()) {
SkipUntil(tok::r_paren, true, true);
if (EndLoc)
*EndLoc = Tok.getLocation();
ConsumeAnyToken();
} else {
Loc = MatchRHSPunctuation(tok::r_paren, Loc);
if (EndLoc)
*EndLoc = Loc;
}
return move(Result);
}
bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext) {
assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)
|| Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)) &&
"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 (getLang().Microsoft)
Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
else
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
= static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
if (TemplateId->Kind == TNK_Function_template) {
Diag(Tok, diag::err_typename_refers_to_non_type_template)
<< Tok.getAnnotationRange();
return true;
}
ASTTemplateArgsPtr TemplateArgsPtr(Actions,
TemplateId->getTemplateArgs(),
TemplateId->NumArgs);
Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
SourceLocation(),
TemplateId->Template,
TemplateId->TemplateNameLoc,
TemplateId->LAngleLoc,
TemplateArgsPtr,
TemplateId->RAngleLoc);
TemplateId->Destroy();
} 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 (getLang().CPlusPlus)
if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
return true;
if (Tok.is(tok::identifier)) {
if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
Tok.getLocation(), getCurScope(),
&SS, false,
NextToken().is(tok::period),
ParsedType(),
true)) {
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 (!getLang().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, TemplateName)) {
return true;
}
}
}
}
if (Tok.is(tok::annot_template_id)) {
TemplateIdAnnotation *TemplateId
= static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
if (TemplateId->Kind == TNK_Type_template) {
AnnotateTemplateIdTokenAsType();
return false;
}
}
if (SS.isEmpty())
return false;
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 (!wasScopeAnnotation)
PP.AnnotateCachedTokens(Tok);
return false;
}
bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
assert(getLang().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)))&&
"Cannot be a type or scope token!");
CXXScopeSpec SS;
if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
return true;
if (SS.isEmpty())
return false;
if (PP.isBacktrackEnabled())
PP.RevertCachedTokens(1);
else
PP.EnterToken(Tok);
Tok.setKind(tok::annot_cxxscope);
Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
Tok.setAnnotationRange(SS.getRange());
PP.AnnotateCachedTokens(Tok);
return false;
}
bool Parser::isTokenEqualOrMistypedEqualEqual(unsigned DiagID) {
if (Tok.is(tok::equalequal)) {
Diag(Tok, DiagID)
<< FixItHint::CreateReplacement(SourceRange(Tok.getLocation()),
getTokenSimpleSpelling(tok::equal));
return true;
}
return Tok.is(tok::equal);
}
void Parser::CodeCompletionRecovery() {
for (Scope *S = getCurScope(); S; S = S->getParent()) {
if (S->getFlags() & Scope::FnScope) {
Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction);
return;
}
if (S->getFlags() & Scope::ClassScope) {
Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
return;
}
}
Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
}
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();
}