#include "clang/Parse/Parser.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/Parse/ParseDiagnostic.h"
#include "clang/Parse/RAIIObjectsForParser.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Scope.h"
using namespace clang;
NamedDecl *Parser::ParseCXXInlineMethodDef(
AccessSpecifier AS, const ParsedAttributesView &AccessAttrs,
ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo,
const VirtSpecifiers &VS, SourceLocation PureSpecLoc) {
assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try, tok::equal) &&
"Current token not a '{', ':', '=', or 'try'!");
MultiTemplateParamsArg TemplateParams(
TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data()
: nullptr,
TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
NamedDecl *FnD;
if (D.getDeclSpec().isFriendSpecified())
FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
TemplateParams);
else {
FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
TemplateParams, nullptr,
VS, ICIS_NoInit);
if (FnD) {
Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
if (PureSpecLoc.isValid())
Actions.ActOnPureSpecifier(FnD, PureSpecLoc);
}
}
if (FnD)
HandleMemberFunctionDeclDelays(D, FnD);
D.complete(FnD);
if (TryConsumeToken(tok::equal)) {
if (!FnD) {
SkipUntil(tok::semi);
return nullptr;
}
bool Delete = false;
SourceLocation KWLoc;
SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1);
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(FnD, KWLoc);
Delete = true;
if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
DeclAsFunction->setRangeEnd(KWEndLoc);
}
} 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(FnD, KWLoc);
if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
DeclAsFunction->setRangeEnd(KWEndLoc);
}
} 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);
}
return FnD;
}
if (SkipFunctionBodies && (!FnD || Actions.canSkipFunctionBody(FnD)) &&
trySkippingFunctionBody()) {
Actions.ActOnSkippedFunctionBody(FnD);
return FnD;
}
if (getLangOpts().DelayedTemplateParsing &&
D.getFunctionDefinitionKind() == FunctionDefinitionKind::Definition &&
!D.getDeclSpec().hasConstexprSpecifier() &&
!(FnD && FnD->getAsFunction() &&
FnD->getAsFunction()->getReturnType()->getContainedAutoType()) &&
((Actions.CurContext->isDependentContext() ||
(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
!Actions.IsInsideALocalClassWithinATemplateFunction())) {
CachedTokens Toks;
LexTemplateFunctionForLateParsing(Toks);
if (FnD) {
FunctionDecl *FD = FnD->getAsFunction();
Actions.CheckForFunctionRedefinition(FD);
Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
}
return FnD;
}
LexedMethod* LM = new LexedMethod(this, FnD);
getCurrentClass().LateParsedDeclarations.push_back(LM);
CachedTokens &Toks = LM->Toks;
tok::TokenKind kind = Tok.getKind();
if (ConsumeAndStoreFunctionPrologue(Toks)) {
if (PP.isCodeCompletionEnabled() &&
llvm::any_of(Toks, [](const Token &Tok) {
return Tok.is(tok::code_completion);
})) {
return FnD;
}
SkipMalformedDecl();
delete getCurrentClass().LateParsedDeclarations.back();
getCurrentClass().LateParsedDeclarations.pop_back();
return FnD;
} else {
ConsumeAndStoreUntil(tok::r_brace, Toks, false);
}
if (kind == tok::kw_try) {
while (Tok.is(tok::kw_catch)) {
ConsumeAndStoreUntil(tok::l_brace, Toks, false);
ConsumeAndStoreUntil(tok::r_brace, Toks, false);
}
}
if (FnD) {
FunctionDecl *FD = FnD->getAsFunction();
Actions.CheckForFunctionRedefinition(FD);
FD->setWillHaveBody(true);
} else {
delete getCurrentClass().LateParsedDeclarations.back();
getCurrentClass().LateParsedDeclarations.pop_back();
}
return FnD;
}
void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
assert(Tok.isOneOf(tok::l_brace, tok::equal) &&
"Current token not a '{' or '='!");
LateParsedMemberInitializer *MI =
new LateParsedMemberInitializer(this, VarD);
getCurrentClass().LateParsedDeclarations.push_back(MI);
CachedTokens &Toks = MI->Toks;
tok::TokenKind kind = Tok.getKind();
if (kind == tok::equal) {
Toks.push_back(Tok);
ConsumeToken();
}
if (kind == tok::l_brace) {
Toks.push_back(Tok);
ConsumeBrace();
ConsumeAndStoreUntil(tok::r_brace, Toks, true);
} else {
ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
}
Token Eof;
Eof.startToken();
Eof.setKind(tok::eof);
Eof.setLocation(Tok.getLocation());
Eof.setEofData(VarD);
Toks.push_back(Eof);
}
Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
void Parser::LateParsedDeclaration::ParseLexedPragmas() {}
Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
: Self(P), Class(C) {}
Parser::LateParsedClass::~LateParsedClass() {
Self->DeallocateParsedClasses(Class);
}
void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
Self->ParseLexedMethodDeclarations(*Class);
}
void Parser::LateParsedClass::ParseLexedMemberInitializers() {
Self->ParseLexedMemberInitializers(*Class);
}
void Parser::LateParsedClass::ParseLexedMethodDefs() {
Self->ParseLexedMethodDefs(*Class);
}
void Parser::LateParsedClass::ParseLexedAttributes() {
Self->ParseLexedAttributes(*Class);
}
void Parser::LateParsedClass::ParseLexedPragmas() {
Self->ParseLexedPragmas(*Class);
}
void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
Self->ParseLexedMethodDeclaration(*this);
}
void Parser::LexedMethod::ParseLexedMethodDefs() {
Self->ParseLexedMethodDef(*this);
}
void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
Self->ParseLexedMemberInitializer(*this);
}
void Parser::LateParsedAttribute::ParseLexedAttributes() {
Self->ParseLexedAttribute(*this, true, false);
}
void Parser::LateParsedPragma::ParseLexedPragmas() {
Self->ParseLexedPragma(*this);
}
struct Parser::ReenterTemplateScopeRAII {
Parser &P;
MultiParseScope Scopes;
TemplateParameterDepthRAII CurTemplateDepthTracker;
ReenterTemplateScopeRAII(Parser &P, Decl *MaybeTemplated, bool Enter = true)
: P(P), Scopes(P), CurTemplateDepthTracker(P.TemplateParameterDepth) {
if (Enter) {
CurTemplateDepthTracker.addDepth(
P.ReenterTemplateScopes(Scopes, MaybeTemplated));
}
}
};
struct Parser::ReenterClassScopeRAII : ReenterTemplateScopeRAII {
ParsingClass &Class;
ReenterClassScopeRAII(Parser &P, ParsingClass &Class)
: ReenterTemplateScopeRAII(P, Class.TagOrTemplate,
!Class.TopLevelClass),
Class(Class) {
if (Class.TopLevelClass)
return;
Scopes.Enter(Scope::ClassScope|Scope::DeclScope);
P.Actions.ActOnStartDelayedMemberDeclarations(P.getCurScope(),
Class.TagOrTemplate);
}
~ReenterClassScopeRAII() {
if (Class.TopLevelClass)
return;
P.Actions.ActOnFinishDelayedMemberDeclarations(P.getCurScope(),
Class.TagOrTemplate);
}
};
void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
ReenterClassScopeRAII InClassScope(*this, Class);
for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations)
LateD->ParseLexedMethodDeclarations();
}
void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
ReenterTemplateScopeRAII InFunctionTemplateScope(*this, LM.Method);
Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
InFunctionTemplateScope.Scopes.Enter(Scope::FunctionPrototypeScope |
Scope::FunctionDeclarationScope |
Scope::DeclScope);
for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
bool HasUnparsed = Param->hasUnparsedDefaultArg();
Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param);
std::unique_ptr<CachedTokens> Toks = std::move(LM.DefaultArgs[I].Toks);
if (Toks) {
ParenBraceBracketBalancer BalancerRAIIObj(*this);
Token LastDefaultArgToken = Toks->back();
Token DefArgEnd;
DefArgEnd.startToken();
DefArgEnd.setKind(tok::eof);
DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
DefArgEnd.setEofData(Param);
Toks->push_back(DefArgEnd);
Toks->push_back(Tok); PP.EnterTokenStream(*Toks, true, true);
ConsumeAnyToken();
assert(Tok.is(tok::equal) && "Default argument not starting with '='");
SourceLocation EqualLoc = ConsumeToken();
EnterExpressionEvaluationContext Eval(
Actions,
Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, Param);
ExprResult DefArgResult;
if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
DefArgResult = ParseBraceInitializer();
} else
DefArgResult = ParseAssignmentExpression();
DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
if (DefArgResult.isInvalid()) {
Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
} else {
if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
assert(Toks->size() >= 3 && "expected a token in default arg");
Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
<< SourceRange(Tok.getLocation(),
(*Toks)[Toks->size() - 3].getLocation());
}
Actions.ActOnParamDefaultArgument(Param, EqualLoc,
DefArgResult.get());
}
while (Tok.isNot(tok::eof))
ConsumeAnyToken();
if (Tok.is(tok::eof) && Tok.getEofData() == Param)
ConsumeAnyToken();
} else if (HasUnparsed) {
assert(Param->hasInheritedDefaultArg());
const FunctionDecl *Old;
if (const auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(LM.Method))
Old =
cast<FunctionDecl>(FunTmpl->getTemplatedDecl())->getPreviousDecl();
else
Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
if (Old) {
ParmVarDecl *OldParam = const_cast<ParmVarDecl*>(Old->getParamDecl(I));
assert(!OldParam->hasUnparsedDefaultArg());
if (OldParam->hasUninstantiatedDefaultArg())
Param->setUninstantiatedDefaultArg(
OldParam->getUninstantiatedDefaultArg());
else
Param->setDefaultArg(OldParam->getInit());
}
}
}
if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
ParenBraceBracketBalancer BalancerRAIIObj(*this);
Token LastExceptionSpecToken = Toks->back();
Token ExceptionSpecEnd;
ExceptionSpecEnd.startToken();
ExceptionSpecEnd.setKind(tok::eof);
ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
ExceptionSpecEnd.setEofData(LM.Method);
Toks->push_back(ExceptionSpecEnd);
Toks->push_back(Tok); PP.EnterTokenStream(*Toks, true, true);
ConsumeAnyToken();
CXXMethodDecl *Method;
if (FunctionTemplateDecl *FunTmpl
= dyn_cast<FunctionTemplateDecl>(LM.Method))
Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
else
Method = dyn_cast<CXXMethodDecl>(LM.Method);
Sema::CXXThisScopeRAII ThisScope(
Actions, Method ? Method->getParent() : nullptr,
Method ? Method->getMethodQualifiers() : Qualifiers{},
Method && getLangOpts().CPlusPlus11);
SourceRange SpecificationRange;
SmallVector<ParsedType, 4> DynamicExceptions;
SmallVector<SourceRange, 4> DynamicExceptionRanges;
ExprResult NoexceptExpr;
CachedTokens *ExceptionSpecTokens;
ExceptionSpecificationType EST
= tryParseExceptionSpecification(false, SpecificationRange,
DynamicExceptions,
DynamicExceptionRanges, NoexceptExpr,
ExceptionSpecTokens);
if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
SpecificationRange,
DynamicExceptions,
DynamicExceptionRanges,
NoexceptExpr.isUsable()?
NoexceptExpr.get() : nullptr);
while (Tok.isNot(tok::eof))
ConsumeAnyToken();
if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
ConsumeAnyToken();
delete Toks;
LM.ExceptionSpecTokens = nullptr;
}
InFunctionTemplateScope.Scopes.Exit();
Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
}
void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
ReenterClassScopeRAII InClassScope(*this, Class);
for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
D->ParseLexedMethodDefs();
}
void Parser::ParseLexedMethodDef(LexedMethod &LM) {
ReenterTemplateScopeRAII InFunctionTemplateScope(*this, LM.D);
ParenBraceBracketBalancer BalancerRAIIObj(*this);
assert(!LM.Toks.empty() && "Empty body!");
Token LastBodyToken = LM.Toks.back();
Token BodyEnd;
BodyEnd.startToken();
BodyEnd.setKind(tok::eof);
BodyEnd.setLocation(LastBodyToken.getEndLoc());
BodyEnd.setEofData(LM.D);
LM.Toks.push_back(BodyEnd);
LM.Toks.push_back(Tok);
PP.EnterTokenStream(LM.Toks, true, true);
ConsumeAnyToken(true);
assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)
&& "Inline method not starting with '{', ':' or 'try'");
ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
Scope::CompoundStmtScope);
Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
if (Tok.is(tok::kw_try)) {
ParseFunctionTryBlock(LM.D, FnScope);
while (Tok.isNot(tok::eof))
ConsumeAnyToken();
if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
ConsumeAnyToken();
return;
}
if (Tok.is(tok::colon)) {
ParseConstructorInitializer(LM.D);
if (!Tok.is(tok::l_brace)) {
FnScope.Exit();
Actions.ActOnFinishFunctionBody(LM.D, nullptr);
while (Tok.isNot(tok::eof))
ConsumeAnyToken();
if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
ConsumeAnyToken();
return;
}
} else
Actions.ActOnDefaultCtorInitializers(LM.D);
assert((Actions.getDiagnostics().hasErrorOccurred() ||
!isa<FunctionTemplateDecl>(LM.D) ||
cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
< TemplateParameterDepth) &&
"TemplateParameterDepth should be greater than the depth of "
"current template being instantiated!");
ParseFunctionStatementBody(LM.D, FnScope);
while (Tok.isNot(tok::eof))
ConsumeAnyToken();
if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
ConsumeAnyToken();
if (auto *FD = dyn_cast_or_null<FunctionDecl>(LM.D))
if (isa<CXXMethodDecl>(FD) ||
FD->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend))
Actions.ActOnFinishInlineFunctionDef(FD);
}
void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
ReenterClassScopeRAII InClassScope(*this, Class);
if (!Class.LateParsedDeclarations.empty()) {
Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
Qualifiers());
for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
D->ParseLexedMemberInitializers();
}
Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
}
void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
if (!MI.Field || MI.Field->isInvalidDecl())
return;
ParenBraceBracketBalancer BalancerRAIIObj(*this);
MI.Toks.push_back(Tok);
PP.EnterTokenStream(MI.Toks, true, true);
ConsumeAnyToken(true);
SourceLocation EqualLoc;
Actions.ActOnStartCXXInClassMemberInitializer();
ExprResult Init = ParseCXXMemberInitializer(MI.Field, false,
EqualLoc);
Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
Init.get());
if (Tok.isNot(tok::eof)) {
if (!Init.isInvalid()) {
SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
if (!EndLoc.isValid())
EndLoc = Tok.getLocation();
Diag(EndLoc, diag::err_expected_semi_decl_list);
}
while (Tok.isNot(tok::eof))
ConsumeAnyToken();
}
if (Tok.getEofData() == MI.Field)
ConsumeAnyToken();
}
void Parser::ParseLexedAttributes(ParsingClass &Class) {
ReenterClassScopeRAII InClassScope(*this, Class);
for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations)
LateD->ParseLexedAttributes();
}
void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
bool EnterScope, bool OnDefinition) {
assert(LAs.parseSoon() &&
"Attribute list should be marked for immediate parsing.");
for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
if (D)
LAs[i]->addDecl(D);
ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
delete LAs[i];
}
LAs.clear();
}
void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
bool EnterScope, bool OnDefinition) {
Token AttrEnd;
AttrEnd.startToken();
AttrEnd.setKind(tok::eof);
AttrEnd.setLocation(Tok.getLocation());
AttrEnd.setEofData(LA.Toks.data());
LA.Toks.push_back(AttrEnd);
LA.Toks.push_back(Tok);
PP.EnterTokenStream(LA.Toks, true, true);
ConsumeAnyToken(true);
ParsedAttributes Attrs(AttrFactory);
if (LA.Decls.size() > 0) {
Decl *D = LA.Decls[0];
NamedDecl *ND = dyn_cast<NamedDecl>(D);
RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
ND && ND->isCXXInstanceMember());
if (LA.Decls.size() == 1) {
ReenterTemplateScopeRAII InDeclScope(*this, D, EnterScope);
bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
if (HasFunScope) {
InDeclScope.Scopes.Enter(Scope::FnScope | Scope::DeclScope |
Scope::CompoundStmtScope);
Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
}
ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, nullptr,
nullptr, SourceLocation(), ParsedAttr::AS_GNU,
nullptr);
if (HasFunScope)
Actions.ActOnExitFunctionContext();
} else {
ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, nullptr,
nullptr, SourceLocation(), ParsedAttr::AS_GNU,
nullptr);
}
} else {
Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
}
if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
Attrs.begin()->isKnownToGCC())
Diag(Tok, diag::warn_attribute_on_function_definition)
<< &LA.AttrName;
for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
while (Tok.isNot(tok::eof))
ConsumeAnyToken();
if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
ConsumeAnyToken();
}
void Parser::ParseLexedPragmas(ParsingClass &Class) {
ReenterClassScopeRAII InClassScope(*this, Class);
for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
D->ParseLexedPragmas();
}
void Parser::ParseLexedPragma(LateParsedPragma &LP) {
PP.EnterToken(Tok, true);
PP.EnterTokenStream(LP.toks(), true,
true);
ConsumeAnyToken(true);
assert(Tok.isAnnotation() && "Expected annotation token.");
switch (Tok.getKind()) {
case tok::annot_attr_openmp:
case tok::annot_pragma_openmp: {
AccessSpecifier AS = LP.getAccessSpecifier();
ParsedAttributes Attrs(AttrFactory);
(void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
break;
}
default:
llvm_unreachable("Unexpected token.");
}
}
bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
CachedTokens &Toks,
bool StopAtSemi, bool ConsumeFinalToken) {
bool isFirstTokenConsumed = true;
while (true) {
if (Tok.is(T1) || Tok.is(T2)) {
if (ConsumeFinalToken) {
Toks.push_back(Tok);
ConsumeAnyToken();
}
return true;
}
switch (Tok.getKind()) {
case tok::eof:
case tok::annot_module_begin:
case tok::annot_module_end:
case tok::annot_module_include:
return false;
case tok::l_paren:
Toks.push_back(Tok);
ConsumeParen();
ConsumeAndStoreUntil(tok::r_paren, Toks, false);
break;
case tok::l_square:
Toks.push_back(Tok);
ConsumeBracket();
ConsumeAndStoreUntil(tok::r_square, Toks, false);
break;
case tok::l_brace:
Toks.push_back(Tok);
ConsumeBrace();
ConsumeAndStoreUntil(tok::r_brace, Toks, false);
break;
case tok::r_paren:
if (ParenCount && !isFirstTokenConsumed)
return false; Toks.push_back(Tok);
ConsumeParen();
break;
case tok::r_square:
if (BracketCount && !isFirstTokenConsumed)
return false; Toks.push_back(Tok);
ConsumeBracket();
break;
case tok::r_brace:
if (BraceCount && !isFirstTokenConsumed)
return false; Toks.push_back(Tok);
ConsumeBrace();
break;
case tok::semi:
if (StopAtSemi)
return false;
LLVM_FALLTHROUGH;
default:
Toks.push_back(Tok);
ConsumeAnyToken(true);
break;
}
isFirstTokenConsumed = false;
}
}
bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
if (Tok.is(tok::kw_try)) {
Toks.push_back(Tok);
ConsumeToken();
}
if (Tok.isNot(tok::colon)) {
ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
true,
false);
if (Tok.isNot(tok::l_brace))
return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Toks.push_back(Tok);
ConsumeBrace();
return false;
}
Toks.push_back(Tok);
ConsumeToken();
bool MightBeTemplateArgument = false;
while (true) {
if (Tok.is(tok::kw_decltype)) {
Toks.push_back(Tok);
SourceLocation OpenLoc = ConsumeToken();
if (Tok.isNot(tok::l_paren))
return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
<< "decltype";
Toks.push_back(Tok);
ConsumeParen();
if (!ConsumeAndStoreUntil(tok::r_paren, Toks, true)) {
Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
Diag(OpenLoc, diag::note_matching) << tok::l_paren;
return true;
}
}
do {
if (Tok.is(tok::coloncolon)) {
Toks.push_back(Tok);
ConsumeToken();
if (Tok.is(tok::kw_template)) {
Toks.push_back(Tok);
ConsumeToken();
}
}
if (Tok.is(tok::identifier)) {
Toks.push_back(Tok);
ConsumeToken();
} else {
break;
}
} while (Tok.is(tok::coloncolon));
if (Tok.is(tok::code_completion)) {
Toks.push_back(Tok);
ConsumeCodeCompletionToken();
if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype)) {
continue;
}
}
if (Tok.is(tok::comma)) {
Toks.push_back(Tok);
ConsumeToken();
continue;
}
if (Tok.is(tok::less))
MightBeTemplateArgument = true;
if (MightBeTemplateArgument) {
if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
true,
false)) {
return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
}
} else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
if (getLangOpts().CPlusPlus11)
return Diag(Tok.getLocation(), diag::err_expected_either)
<< tok::l_paren << tok::l_brace;
else
return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
}
tok::TokenKind kind = Tok.getKind();
Toks.push_back(Tok);
bool IsLParen = (kind == tok::l_paren);
SourceLocation OpenLoc = Tok.getLocation();
if (IsLParen) {
ConsumeParen();
} else {
assert(kind == tok::l_brace && "Must be left paren or brace here.");
ConsumeBrace();
if (!getLangOpts().CPlusPlus11)
return false;
const Token &PreviousToken = Toks[Toks.size() - 2];
if (!MightBeTemplateArgument &&
!PreviousToken.isOneOf(tok::identifier, tok::greater,
tok::greatergreater)) {
TentativeParsingAction PA(*this);
if (SkipUntil(tok::r_brace) &&
!Tok.isOneOf(tok::comma, tok::ellipsis, tok::l_brace)) {
PA.Revert();
return false;
}
PA.Revert();
}
}
tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
if (!ConsumeAndStoreUntil(CloseKind, Toks, true)) {
Diag(Tok, diag::err_expected) << CloseKind;
Diag(OpenLoc, diag::note_matching) << kind;
return true;
}
if (Tok.is(tok::ellipsis)) {
Toks.push_back(Tok);
ConsumeToken();
}
if (Tok.is(tok::comma)) {
Toks.push_back(Tok);
ConsumeToken();
} else if (Tok.is(tok::l_brace)) {
Toks.push_back(Tok);
ConsumeBrace();
return false;
} else if (!MightBeTemplateArgument) {
return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
<< tok::comma;
}
}
}
bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
assert(Tok.is(tok::question));
Toks.push_back(Tok);
ConsumeToken();
while (Tok.isNot(tok::colon)) {
if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
true,
false))
return false;
if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
return false;
}
Toks.push_back(Tok);
ConsumeToken();
return true;
}
class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
public:
explicit UnannotatedTentativeParsingAction(Parser &Self,
tok::TokenKind EndKind)
: TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
TentativeParsingAction Inner(Self);
Self.ConsumeAndStoreUntil(EndKind, Toks, true, false);
Inner.Revert();
}
void RevertAnnotations() {
Revert();
Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
if (Toks.size()) {
auto Buffer = std::make_unique<Token[]>(Toks.size());
std::copy(Toks.begin() + 1, Toks.end(), Buffer.get());
Buffer[Toks.size() - 1] = Self.Tok;
Self.PP.EnterTokenStream(std::move(Buffer), Toks.size(), true,
true);
Self.Tok = Toks.front();
}
}
private:
Parser &Self;
CachedTokens Toks;
tok::TokenKind EndKind;
};
bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
CachedInitKind CIK) {
bool IsFirstToken = true;
unsigned AngleCount = 0;
unsigned KnownTemplateCount = 0;
while (true) {
switch (Tok.getKind()) {
case tok::comma:
if (!AngleCount)
return true;
if (KnownTemplateCount)
goto consume_token;
{
UnannotatedTentativeParsingAction PA(*this,
CIK == CIK_DefaultInitializer
? tok::semi : tok::r_paren);
Sema::TentativeAnalysisScope Scope(Actions);
TPResult Result = TPResult::Error;
ConsumeToken();
switch (CIK) {
case CIK_DefaultInitializer:
Result = TryParseInitDeclaratorList();
if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
Result = TPResult::False;
break;
case CIK_DefaultArgument:
bool InvalidAsDeclaration = false;
Result = TryParseParameterDeclarationClause(
&InvalidAsDeclaration, true);
if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
Result = TPResult::False;
break;
}
PA.RevertAnnotations();
if (Result != TPResult::False && Result != TPResult::Error)
return true;
}
++KnownTemplateCount;
goto consume_token;
case tok::eof:
case tok::annot_module_begin:
case tok::annot_module_end:
case tok::annot_module_include:
return false;
case tok::less:
++AngleCount;
goto consume_token;
case tok::question:
if (!ConsumeAndStoreConditional(Toks))
return false;
break;
case tok::greatergreatergreater:
if (!getLangOpts().CPlusPlus11)
goto consume_token;
if (AngleCount) --AngleCount;
if (KnownTemplateCount) --KnownTemplateCount;
LLVM_FALLTHROUGH;
case tok::greatergreater:
if (!getLangOpts().CPlusPlus11)
goto consume_token;
if (AngleCount) --AngleCount;
if (KnownTemplateCount) --KnownTemplateCount;
LLVM_FALLTHROUGH;
case tok::greater:
if (AngleCount) --AngleCount;
if (KnownTemplateCount) --KnownTemplateCount;
goto consume_token;
case tok::kw_template:
Toks.push_back(Tok);
ConsumeToken();
if (Tok.is(tok::identifier)) {
Toks.push_back(Tok);
ConsumeToken();
if (Tok.is(tok::less)) {
++AngleCount;
++KnownTemplateCount;
Toks.push_back(Tok);
ConsumeToken();
}
}
break;
case tok::kw_operator:
Toks.push_back(Tok);
ConsumeToken();
switch (Tok.getKind()) {
case tok::comma:
case tok::greatergreatergreater:
case tok::greatergreater:
case tok::greater:
case tok::less:
Toks.push_back(Tok);
ConsumeToken();
break;
default:
break;
}
break;
case tok::l_paren:
Toks.push_back(Tok);
ConsumeParen();
ConsumeAndStoreUntil(tok::r_paren, Toks, false);
break;
case tok::l_square:
Toks.push_back(Tok);
ConsumeBracket();
ConsumeAndStoreUntil(tok::r_square, Toks, false);
break;
case tok::l_brace:
Toks.push_back(Tok);
ConsumeBrace();
ConsumeAndStoreUntil(tok::r_brace, Toks, false);
break;
case tok::r_paren:
if (CIK == CIK_DefaultArgument)
return true; if (ParenCount && !IsFirstToken)
return false;
Toks.push_back(Tok);
ConsumeParen();
continue;
case tok::r_square:
if (BracketCount && !IsFirstToken)
return false;
Toks.push_back(Tok);
ConsumeBracket();
continue;
case tok::r_brace:
if (BraceCount && !IsFirstToken)
return false;
Toks.push_back(Tok);
ConsumeBrace();
continue;
case tok::code_completion:
Toks.push_back(Tok);
ConsumeCodeCompletionToken();
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:
Toks.push_back(Tok);
ConsumeStringToken();
break;
case tok::semi:
if (CIK == CIK_DefaultInitializer)
return true; LLVM_FALLTHROUGH;
default:
consume_token:
Toks.push_back(Tok);
ConsumeToken();
break;
}
IsFirstToken = false;
}
}