#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/PrettyDeclStackTrace.h"
#include "clang/Basic/AddressSpaces.h"
#include "clang/Basic/AttributeCommonInfo.h"
#include "clang/Basic/Attributes.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Parse/ParseDiagnostic.h"
#include "clang/Parse/Parser.h"
#include "clang/Parse/RAIIObjectsForParser.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/ParsedTemplate.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/SemaDiagnostic.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
using namespace clang;
TypeResult Parser::ParseTypeName(SourceRange *Range, DeclaratorContext Context,
AccessSpecifier AS, Decl **OwnedType,
ParsedAttributes *Attrs) {
DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
if (DSC == DeclSpecContext::DSC_normal)
DSC = DeclSpecContext::DSC_type_specifier;
DeclSpec DS(AttrFactory);
if (Attrs)
DS.addAttributes(*Attrs);
ParseSpecifierQualifierList(DS, AS, DSC);
if (OwnedType)
*OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), Context);
ParseDeclarator(DeclaratorInfo);
if (Range)
*Range = DeclaratorInfo.getSourceRange();
if (DeclaratorInfo.isInvalidType())
return true;
return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
}
static StringRef normalizeAttrName(StringRef Name) {
if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
return Name.drop_front(2).drop_back(2);
return Name;
}
static bool isAttributeLateParsed(const IdentifierInfo &II) {
#define CLANG_ATTR_LATE_PARSED_LIST
return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(false);
#undef CLANG_ATTR_LATE_PARSED_LIST
}
static bool FindLocsWithCommonFileID(Preprocessor &PP, SourceLocation StartLoc,
SourceLocation EndLoc) {
if (!StartLoc.isMacroID() || !EndLoc.isMacroID())
return false;
SourceManager &SM = PP.getSourceManager();
if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
return false;
bool AttrStartIsInMacro =
Lexer::isAtStartOfMacroExpansion(StartLoc, SM, PP.getLangOpts());
bool AttrEndIsInMacro =
Lexer::isAtEndOfMacroExpansion(EndLoc, SM, PP.getLangOpts());
return AttrStartIsInMacro && AttrEndIsInMacro;
}
void Parser::ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
LateParsedAttrList *LateAttrs) {
bool MoreToParse;
do {
MoreToParse = false;
if (WhichAttrKinds & PAKM_CXX11)
MoreToParse |= MaybeParseCXX11Attributes(Attrs);
if (WhichAttrKinds & PAKM_GNU)
MoreToParse |= MaybeParseGNUAttributes(Attrs, LateAttrs);
if (WhichAttrKinds & PAKM_Declspec)
MoreToParse |= MaybeParseMicrosoftDeclSpecs(Attrs);
} while (MoreToParse);
}
void Parser::ParseGNUAttributes(ParsedAttributes &Attrs,
LateParsedAttrList *LateAttrs, Declarator *D) {
assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
SourceLocation StartLoc = Tok.getLocation();
SourceLocation EndLoc = StartLoc;
while (Tok.is(tok::kw___attribute)) {
SourceLocation AttrTokLoc = ConsumeToken();
unsigned OldNumAttrs = Attrs.size();
unsigned OldNumLateAttrs = LateAttrs ? LateAttrs->size() : 0;
if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
"attribute")) {
SkipUntil(tok::r_paren, StopAtSemi); return;
}
if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
SkipUntil(tok::r_paren, StopAtSemi); return;
}
do {
while (TryConsumeToken(tok::comma))
;
if (Tok.isAnnotation())
break;
if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompleteAttribute(AttributeCommonInfo::Syntax::AS_GNU);
break;
}
IdentifierInfo *AttrName = Tok.getIdentifierInfo();
if (!AttrName)
break;
SourceLocation AttrNameLoc = ConsumeToken();
if (Tok.isNot(tok::l_paren)) {
Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
ParsedAttr::AS_GNU);
continue;
}
if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, &EndLoc, nullptr,
SourceLocation(), ParsedAttr::AS_GNU, D);
continue;
}
LateParsedAttribute *LA =
new LateParsedAttribute(this, *AttrName, AttrNameLoc);
LateAttrs->push_back(LA);
if (!ClassStack.empty() && !LateAttrs->parseSoon())
getCurrentClass().LateParsedDeclarations.push_back(LA);
LA->Toks.push_back(Tok);
ConsumeParen();
ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true);
Token Eof;
Eof.startToken();
Eof.setLocation(Tok.getLocation());
LA->Toks.push_back(Eof);
} while (Tok.is(tok::comma));
if (ExpectAndConsume(tok::r_paren))
SkipUntil(tok::r_paren, StopAtSemi);
SourceLocation Loc = Tok.getLocation();
if (ExpectAndConsume(tok::r_paren))
SkipUntil(tok::r_paren, StopAtSemi);
EndLoc = Loc;
auto &SM = PP.getSourceManager();
if (!SM.isWrittenInBuiltinFile(SM.getSpellingLoc(AttrTokLoc)) &&
FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)) {
CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
StringRef FoundName =
Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
for (unsigned i = OldNumAttrs; i < Attrs.size(); ++i)
Attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
if (LateAttrs) {
for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); ++i)
(*LateAttrs)[i]->MacroII = MacroII;
}
}
}
Attrs.Range = SourceRange(StartLoc, EndLoc);
}
static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
#define CLANG_ATTR_IDENTIFIER_ARG_LIST
return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(false);
#undef CLANG_ATTR_IDENTIFIER_ARG_LIST
}
static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II) {
#define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(false);
#undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
}
static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II) {
#define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(false);
#undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
}
static bool attributeAcceptsExprPack(const IdentifierInfo &II) {
#define CLANG_ATTR_ACCEPTS_EXPR_PACK
return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(false);
#undef CLANG_ATTR_ACCEPTS_EXPR_PACK
}
static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
#define CLANG_ATTR_TYPE_ARG_LIST
return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(false);
#undef CLANG_ATTR_TYPE_ARG_LIST
}
static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
#define CLANG_ATTR_ARG_CONTEXT_LIST
return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(false);
#undef CLANG_ATTR_ARG_CONTEXT_LIST
}
IdentifierLoc *Parser::ParseIdentifierLoc() {
assert(Tok.is(tok::identifier) && "expected an identifier");
IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
Tok.getLocation(),
Tok.getIdentifierInfo());
ConsumeToken();
return IL;
}
void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax) {
BalancedDelimiterTracker Parens(*this, tok::l_paren);
Parens.consumeOpen();
TypeResult T;
if (Tok.isNot(tok::r_paren))
T = ParseTypeName();
if (Parens.consumeClose())
return;
if (T.isInvalid())
return;
if (T.isUsable())
Attrs.addNewTypeAttr(&AttrName,
SourceRange(AttrNameLoc, Parens.getCloseLocation()),
ScopeName, ScopeLoc, T.get(), Syntax);
else
Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
ScopeName, ScopeLoc, nullptr, 0, Syntax);
}
unsigned Parser::ParseAttributeArgsCommon(
IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
ConsumeParen();
bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
bool AttributeIsTypeArgAttr = attributeIsTypeArgAttr(*AttrName);
bool AttributeHasVariadicIdentifierArg =
attributeHasVariadicIdentifierArg(*AttrName);
if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
Tok.setKind(tok::identifier);
ArgsVector ArgExprs;
if (Tok.is(tok::identifier)) {
bool IsIdentifierArg = AttributeHasVariadicIdentifierArg ||
attributeHasIdentifierArg(*AttrName);
ParsedAttr::Kind AttrKind =
ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
if (AttrKind == ParsedAttr::UnknownAttribute ||
AttrKind == ParsedAttr::IgnoredAttribute) {
const Token &Next = NextToken();
IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
}
if (IsIdentifierArg)
ArgExprs.push_back(ParseIdentifierLoc());
}
ParsedType TheParsedType;
if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
if (!ArgExprs.empty())
ConsumeToken();
if (AttributeIsTypeArgAttr) {
TypeResult T = ParseTypeName();
if (T.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
return 0;
}
if (T.isUsable())
TheParsedType = T.get();
} else if (AttributeHasVariadicIdentifierArg) {
do {
if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
Tok.setKind(tok::identifier);
ExprResult ArgExpr;
if (Tok.is(tok::identifier)) {
ArgExprs.push_back(ParseIdentifierLoc());
} else {
bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
EnterExpressionEvaluationContext Unevaluated(
Actions,
Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
: Sema::ExpressionEvaluationContext::ConstantEvaluated);
ExprResult ArgExpr(
Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
if (ArgExpr.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
return 0;
}
ArgExprs.push_back(ArgExpr.get());
}
} while (TryConsumeToken(tok::comma));
} else {
bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
EnterExpressionEvaluationContext Unevaluated(
Actions, Uneval
? Sema::ExpressionEvaluationContext::Unevaluated
: Sema::ExpressionEvaluationContext::ConstantEvaluated);
CommaLocsTy CommaLocs;
ExprVector ParsedExprs;
if (ParseExpressionList(ParsedExprs, CommaLocs,
llvm::function_ref<void()>(),
true,
true)) {
SkipUntil(tok::r_paren, StopAtSemi);
return 0;
}
for (size_t I = 0; I < ParsedExprs.size(); ++I) {
if (!isa<PackExpansionExpr>(ParsedExprs[I]))
continue;
if (!attributeAcceptsExprPack(*AttrName)) {
Diag(Tok.getLocation(),
diag::err_attribute_argument_parm_pack_not_supported)
<< AttrName;
SkipUntil(tok::r_paren, StopAtSemi);
return 0;
}
}
ArgExprs.insert(ArgExprs.end(), ParsedExprs.begin(), ParsedExprs.end());
}
}
SourceLocation RParen = Tok.getLocation();
if (!ExpectAndConsume(tok::r_paren)) {
SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
if (AttributeIsTypeArgAttr && !TheParsedType.get().isNull()) {
Attrs.addNewTypeAttr(AttrName, SourceRange(AttrNameLoc, RParen),
ScopeName, ScopeLoc, TheParsedType, Syntax);
} else {
Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
ArgExprs.data(), ArgExprs.size(), Syntax);
}
}
if (EndLoc)
*EndLoc = RParen;
return static_cast<unsigned>(ArgExprs.size() + !TheParsedType.get().isNull());
}
void Parser::ParseGNUAttributeArgs(
IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax, Declarator *D) {
assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
ParsedAttr::Kind AttrKind =
ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
if (AttrKind == ParsedAttr::AT_Availability) {
ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
ScopeLoc, Syntax);
return;
} else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
ScopeName, ScopeLoc, Syntax);
return;
} else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
ScopeName, ScopeLoc, Syntax);
return;
} else if (AttrKind == ParsedAttr::AT_SwiftNewType) {
ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
ScopeLoc, Syntax);
return;
} else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
ScopeName, ScopeLoc, Syntax);
return;
} else if (attributeIsTypeArgAttr(*AttrName)) {
ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, ScopeName,
ScopeLoc, Syntax);
return;
}
llvm::Optional<ParseScope> PrototypeScope;
if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
D && D->isFunctionDeclarator()) {
DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
Scope::FunctionDeclarationScope |
Scope::DeclScope);
for (unsigned i = 0; i != FTI.NumParams; ++i) {
ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
}
}
ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
ScopeLoc, Syntax);
}
unsigned Parser::ParseClangAttributeArgs(
IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
ParsedAttr::Kind AttrKind =
ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
switch (AttrKind) {
default:
return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
ScopeName, ScopeLoc, Syntax);
case ParsedAttr::AT_ExternalSourceSymbol:
ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
ScopeName, ScopeLoc, Syntax);
break;
case ParsedAttr::AT_Availability:
ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
ScopeLoc, Syntax);
break;
case ParsedAttr::AT_ObjCBridgeRelated:
ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
ScopeName, ScopeLoc, Syntax);
break;
case ParsedAttr::AT_SwiftNewType:
ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
ScopeLoc, Syntax);
break;
case ParsedAttr::AT_TypeTagForDatatype:
ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
ScopeName, ScopeLoc, Syntax);
break;
}
return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
}
bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs) {
unsigned ExistingAttrs = Attrs.size();
if (!hasAttribute(AttributeCommonInfo::Syntax::AS_Declspec, nullptr, AttrName,
getTargetInfo(), getLangOpts())) {
ConsumeParen();
SkipUntil(tok::r_paren);
return false;
}
SourceLocation OpenParenLoc = Tok.getLocation();
if (AttrName->getName() == "property") {
BalancedDelimiterTracker T(*this, tok::l_paren);
T.expectAndConsume(diag::err_expected_lparen_after,
AttrName->getNameStart(), tok::r_paren);
enum AccessorKind {
AK_Invalid = -1,
AK_Put = 0,
AK_Get = 1 };
IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
bool HasInvalidAccessor = false;
while (true) {
if (!Tok.is(tok::identifier)) {
if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
AccessorNames[AK_Put] == nullptr &&
AccessorNames[AK_Get] == nullptr) {
Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
break;
}
Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
break;
}
AccessorKind Kind;
SourceLocation KindLoc = Tok.getLocation();
StringRef KindStr = Tok.getIdentifierInfo()->getName();
if (KindStr == "get") {
Kind = AK_Get;
} else if (KindStr == "put") {
Kind = AK_Put;
} else if (KindStr == "set") {
Diag(KindLoc, diag::err_ms_property_has_set_accessor)
<< FixItHint::CreateReplacement(KindLoc, "put");
Kind = AK_Put;
} else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
ConsumeToken();
HasInvalidAccessor = true;
goto next_property_accessor;
} else {
Diag(KindLoc, diag::err_ms_property_unknown_accessor);
HasInvalidAccessor = true;
Kind = AK_Invalid;
if (!NextToken().is(tok::equal))
break;
}
ConsumeToken();
if (!TryConsumeToken(tok::equal)) {
Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
<< KindStr;
break;
}
if (!Tok.is(tok::identifier)) {
Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
break;
}
if (Kind == AK_Invalid) {
} else if (AccessorNames[Kind] != nullptr) {
Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
} else {
AccessorNames[Kind] = Tok.getIdentifierInfo();
}
ConsumeToken();
next_property_accessor:
if (TryConsumeToken(tok::comma))
continue;
if (Tok.is(tok::r_paren))
break;
Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
break;
}
if (!HasInvalidAccessor)
Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
AccessorNames[AK_Get], AccessorNames[AK_Put],
ParsedAttr::AS_Declspec);
T.skipToEnd();
return !HasInvalidAccessor;
}
unsigned NumArgs =
ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
SourceLocation(), ParsedAttr::AS_Declspec);
if (ExistingAttrs < Attrs.size() && Attrs.back().getMaxArgs() && !NumArgs) {
Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
return false;
}
return true;
}
void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs) {
assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
SourceLocation StartLoc = Tok.getLocation();
SourceLocation EndLoc = StartLoc;
while (Tok.is(tok::kw___declspec)) {
ConsumeToken();
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
tok::r_paren))
return;
while (Tok.isNot(tok::r_paren)) {
if (TryConsumeToken(tok::comma))
continue;
if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompleteAttribute(AttributeCommonInfo::AS_Declspec);
return;
}
bool IsString = Tok.getKind() == tok::string_literal;
if (!IsString && Tok.getKind() != tok::identifier &&
Tok.getKind() != tok::kw_restrict) {
Diag(Tok, diag::err_ms_declspec_type);
T.skipToEnd();
return;
}
IdentifierInfo *AttrName;
SourceLocation AttrNameLoc;
if (IsString) {
SmallString<8> StrBuffer;
bool Invalid = false;
StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
if (Invalid) {
T.skipToEnd();
return;
}
AttrName = PP.getIdentifierInfo(Str);
AttrNameLoc = ConsumeStringToken();
} else {
AttrName = Tok.getIdentifierInfo();
AttrNameLoc = ConsumeToken();
}
bool AttrHandled = false;
if (Tok.is(tok::l_paren))
AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
else if (AttrName->getName() == "property")
Diag(Tok.getLocation(), diag::err_expected_lparen_after)
<< AttrName->getName();
if (!AttrHandled)
Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
ParsedAttr::AS_Declspec);
}
T.consumeClose();
EndLoc = T.getCloseLocation();
}
Attrs.Range = SourceRange(StartLoc, EndLoc);
}
void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
while (true) {
switch (Tok.getKind()) {
case tok::kw___fastcall:
case tok::kw___stdcall:
case tok::kw___thiscall:
case tok::kw___regcall:
case tok::kw___cdecl:
case tok::kw___vectorcall:
case tok::kw___ptr64:
case tok::kw___w64:
case tok::kw___ptr32:
case tok::kw___sptr:
case tok::kw___uptr: {
IdentifierInfo *AttrName = Tok.getIdentifierInfo();
SourceLocation AttrNameLoc = ConsumeToken();
attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
ParsedAttr::AS_Keyword);
break;
}
default:
return;
}
}
}
void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
SourceLocation StartLoc = Tok.getLocation();
SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
if (EndLoc.isValid()) {
SourceRange Range(StartLoc, EndLoc);
Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
}
}
SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
SourceLocation EndLoc;
while (true) {
switch (Tok.getKind()) {
case tok::kw_const:
case tok::kw_volatile:
case tok::kw___fastcall:
case tok::kw___stdcall:
case tok::kw___thiscall:
case tok::kw___cdecl:
case tok::kw___vectorcall:
case tok::kw___ptr32:
case tok::kw___ptr64:
case tok::kw___w64:
case tok::kw___unaligned:
case tok::kw___sptr:
case tok::kw___uptr:
EndLoc = ConsumeToken();
break;
default:
return EndLoc;
}
}
}
void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
while (Tok.is(tok::kw___pascal)) {
IdentifierInfo *AttrName = Tok.getIdentifierInfo();
SourceLocation AttrNameLoc = ConsumeToken();
attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
ParsedAttr::AS_Keyword);
}
}
void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
while (Tok.is(tok::kw___kernel)) {
IdentifierInfo *AttrName = Tok.getIdentifierInfo();
SourceLocation AttrNameLoc = ConsumeToken();
attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
ParsedAttr::AS_Keyword);
}
}
void Parser::ParseCUDAFunctionAttributes(ParsedAttributes &attrs) {
while (Tok.is(tok::kw___noinline__)) {
IdentifierInfo *AttrName = Tok.getIdentifierInfo();
SourceLocation AttrNameLoc = ConsumeToken();
attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
ParsedAttr::AS_Keyword);
}
}
void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
IdentifierInfo *AttrName = Tok.getIdentifierInfo();
SourceLocation AttrNameLoc = Tok.getLocation();
Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
ParsedAttr::AS_Keyword);
}
void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
while (true) {
switch (Tok.getKind()) {
case tok::kw__Nonnull:
case tok::kw__Nullable:
case tok::kw__Nullable_result:
case tok::kw__Null_unspecified: {
IdentifierInfo *AttrName = Tok.getIdentifierInfo();
SourceLocation AttrNameLoc = ConsumeToken();
if (!getLangOpts().ObjC)
Diag(AttrNameLoc, diag::ext_nullability)
<< AttrName;
attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
ParsedAttr::AS_Keyword);
break;
}
default:
return;
}
}
}
static bool VersionNumberSeparator(const char Separator) {
return (Separator == '.' || Separator == '_');
}
VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
if (!Tok.is(tok::numeric_constant)) {
Diag(Tok, diag::err_expected_version);
SkipUntil(tok::comma, tok::r_paren,
StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
return VersionTuple();
}
SmallString<512> Buffer;
Buffer.resize(Tok.getLength()+1);
const char *ThisTokBegin = &Buffer[0];
bool Invalid = false;
unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
if (Invalid)
return VersionTuple();
unsigned AfterMajor = 0;
unsigned Major = 0;
while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
++AfterMajor;
}
if (AfterMajor == 0) {
Diag(Tok, diag::err_expected_version);
SkipUntil(tok::comma, tok::r_paren,
StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
return VersionTuple();
}
if (AfterMajor == ActualLength) {
ConsumeToken();
if (Major == 0) {
Diag(Tok, diag::err_zero_version);
return VersionTuple();
}
return VersionTuple(Major);
}
const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
if (!VersionNumberSeparator(AfterMajorSeparator)
|| (AfterMajor + 1 == ActualLength)) {
Diag(Tok, diag::err_expected_version);
SkipUntil(tok::comma, tok::r_paren,
StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
return VersionTuple();
}
unsigned AfterMinor = AfterMajor + 1;
unsigned Minor = 0;
while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
++AfterMinor;
}
if (AfterMinor == ActualLength) {
ConsumeToken();
if (Major == 0 && Minor == 0) {
Diag(Tok, diag::err_zero_version);
return VersionTuple();
}
return VersionTuple(Major, Minor);
}
const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
if (!VersionNumberSeparator(AfterMinorSeparator)) {
Diag(Tok, diag::err_expected_version);
SkipUntil(tok::comma, tok::r_paren,
StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
return VersionTuple();
}
if (AfterMajorSeparator != AfterMinorSeparator)
Diag(Tok, diag::warn_expected_consistent_version_separator);
unsigned AfterSubminor = AfterMinor + 1;
unsigned Subminor = 0;
while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
++AfterSubminor;
}
if (AfterSubminor != ActualLength) {
Diag(Tok, diag::err_expected_version);
SkipUntil(tok::comma, tok::r_paren,
StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
return VersionTuple();
}
ConsumeToken();
return VersionTuple(Major, Minor, Subminor);
}
void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
SourceLocation AvailabilityLoc,
ParsedAttributes &attrs,
SourceLocation *endLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax) {
enum { Introduced, Deprecated, Obsoleted, Unknown };
AvailabilityChange Changes[Unknown];
ExprResult MessageExpr, ReplacementExpr;
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.consumeOpen()) {
Diag(Tok, diag::err_expected) << tok::l_paren;
return;
}
if (Tok.isNot(tok::identifier)) {
Diag(Tok, diag::err_availability_expected_platform);
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
IdentifierLoc *Platform = ParseIdentifierLoc();
if (const IdentifierInfo *const Ident = Platform->Ident) {
if (Ident->getName() == "macosx")
Platform->Ident = PP.getIdentifierInfo("macos");
else if (Ident->getName() == "macosx_app_extension")
Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
else
Platform->Ident = PP.getIdentifierInfo(
AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
}
if (ExpectAndConsume(tok::comma)) {
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
if (!Ident_introduced) {
Ident_introduced = PP.getIdentifierInfo("introduced");
Ident_deprecated = PP.getIdentifierInfo("deprecated");
Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
Ident_unavailable = PP.getIdentifierInfo("unavailable");
Ident_message = PP.getIdentifierInfo("message");
Ident_strict = PP.getIdentifierInfo("strict");
Ident_replacement = PP.getIdentifierInfo("replacement");
}
SourceLocation UnavailableLoc, StrictLoc;
do {
if (Tok.isNot(tok::identifier)) {
Diag(Tok, diag::err_availability_expected_change);
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
IdentifierInfo *Keyword = Tok.getIdentifierInfo();
SourceLocation KeywordLoc = ConsumeToken();
if (Keyword == Ident_strict) {
if (StrictLoc.isValid()) {
Diag(KeywordLoc, diag::err_availability_redundant)
<< Keyword << SourceRange(StrictLoc);
}
StrictLoc = KeywordLoc;
continue;
}
if (Keyword == Ident_unavailable) {
if (UnavailableLoc.isValid()) {
Diag(KeywordLoc, diag::err_availability_redundant)
<< Keyword << SourceRange(UnavailableLoc);
}
UnavailableLoc = KeywordLoc;
continue;
}
if (Keyword == Ident_deprecated && Platform->Ident &&
Platform->Ident->isStr("swift")) {
if (Changes[Deprecated].KeywordLoc.isValid()) {
Diag(KeywordLoc, diag::err_availability_redundant)
<< Keyword
<< SourceRange(Changes[Deprecated].KeywordLoc);
}
Changes[Deprecated].KeywordLoc = KeywordLoc;
Changes[Deprecated].Version = VersionTuple(1);
continue;
}
if (Tok.isNot(tok::equal)) {
Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
ConsumeToken();
if (Keyword == Ident_message || Keyword == Ident_replacement) {
if (Tok.isNot(tok::string_literal)) {
Diag(Tok, diag::err_expected_string_literal)
<< 2;
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
if (Keyword == Ident_message)
MessageExpr = ParseStringLiteralExpression();
else
ReplacementExpr = ParseStringLiteralExpression();
if (StringLiteral *MessageStringLiteral =
cast_or_null<StringLiteral>(MessageExpr.get())) {
if (!MessageStringLiteral->isOrdinary()) {
Diag(MessageStringLiteral->getSourceRange().getBegin(),
diag::err_expected_string_literal)
<< 2;
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
}
if (Keyword == Ident_message)
break;
else
continue;
}
if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
Tok.is(tok::identifier)) {
IdentifierInfo *NA = Tok.getIdentifierInfo();
if (NA->getName() == "NA") {
ConsumeToken();
if (Keyword == Ident_introduced)
UnavailableLoc = KeywordLoc;
continue;
}
}
SourceRange VersionRange;
VersionTuple Version = ParseVersionTuple(VersionRange);
if (Version.empty()) {
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
unsigned Index;
if (Keyword == Ident_introduced)
Index = Introduced;
else if (Keyword == Ident_deprecated)
Index = Deprecated;
else if (Keyword == Ident_obsoleted)
Index = Obsoleted;
else
Index = Unknown;
if (Index < Unknown) {
if (!Changes[Index].KeywordLoc.isInvalid()) {
Diag(KeywordLoc, diag::err_availability_redundant)
<< Keyword
<< SourceRange(Changes[Index].KeywordLoc,
Changes[Index].VersionRange.getEnd());
}
Changes[Index].KeywordLoc = KeywordLoc;
Changes[Index].Version = Version;
Changes[Index].VersionRange = VersionRange;
} else {
Diag(KeywordLoc, diag::err_availability_unknown_change)
<< Keyword << VersionRange;
}
} while (TryConsumeToken(tok::comma));
if (T.consumeClose())
return;
if (endLoc)
*endLoc = T.getCloseLocation();
if (UnavailableLoc.isValid()) {
bool Complained = false;
for (unsigned Index = Introduced; Index != Unknown; ++Index) {
if (Changes[Index].KeywordLoc.isValid()) {
if (!Complained) {
Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
<< SourceRange(Changes[Index].KeywordLoc,
Changes[Index].VersionRange.getEnd());
Complained = true;
}
Changes[Index] = AvailabilityChange();
}
}
}
attrs.addNew(&Availability,
SourceRange(AvailabilityLoc, T.getCloseLocation()),
ScopeName, ScopeLoc,
Platform,
Changes[Introduced],
Changes[Deprecated],
Changes[Obsoleted],
UnavailableLoc, MessageExpr.get(),
Syntax, StrictLoc, ReplacementExpr.get());
}
void Parser::ParseExternalSourceSymbolAttribute(
IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.expectAndConsume())
return;
if (!Ident_language) {
Ident_language = PP.getIdentifierInfo("language");
Ident_defined_in = PP.getIdentifierInfo("defined_in");
Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
}
ExprResult Language;
bool HasLanguage = false;
ExprResult DefinedInExpr;
bool HasDefinedIn = false;
IdentifierLoc *GeneratedDeclaration = nullptr;
do {
if (Tok.isNot(tok::identifier)) {
Diag(Tok, diag::err_external_source_symbol_expected_keyword);
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
SourceLocation KeywordLoc = Tok.getLocation();
IdentifierInfo *Keyword = Tok.getIdentifierInfo();
if (Keyword == Ident_generated_declaration) {
if (GeneratedDeclaration) {
Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
GeneratedDeclaration = ParseIdentifierLoc();
continue;
}
if (Keyword != Ident_language && Keyword != Ident_defined_in) {
Diag(Tok, diag::err_external_source_symbol_expected_keyword);
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
ConsumeToken();
if (ExpectAndConsume(tok::equal, diag::err_expected_after,
Keyword->getName())) {
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
if (Keyword == Ident_language)
HasLanguage = true;
else
HasDefinedIn = true;
if (Tok.isNot(tok::string_literal)) {
Diag(Tok, diag::err_expected_string_literal)
<< 3
<< (Keyword != Ident_language);
SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
continue;
}
if (Keyword == Ident_language) {
if (HadLanguage) {
Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
<< Keyword;
ParseStringLiteralExpression();
continue;
}
Language = ParseStringLiteralExpression();
} else {
assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
if (HadDefinedIn) {
Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
<< Keyword;
ParseStringLiteralExpression();
continue;
}
DefinedInExpr = ParseStringLiteralExpression();
}
} while (TryConsumeToken(tok::comma));
if (T.consumeClose())
return;
if (EndLoc)
*EndLoc = T.getCloseLocation();
ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
GeneratedDeclaration};
Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
}
void Parser::ParseObjCBridgeRelatedAttribute(
IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.consumeOpen()) {
Diag(Tok, diag::err_expected) << tok::l_paren;
return;
}
if (Tok.isNot(tok::identifier)) {
Diag(Tok, diag::err_objcbridge_related_expected_related_class);
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
IdentifierLoc *RelatedClass = ParseIdentifierLoc();
if (ExpectAndConsume(tok::comma)) {
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
IdentifierLoc *ClassMethod = nullptr;
if (Tok.is(tok::identifier)) {
ClassMethod = ParseIdentifierLoc();
if (!TryConsumeToken(tok::colon)) {
Diag(Tok, diag::err_objcbridge_related_selector_name);
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
}
if (!TryConsumeToken(tok::comma)) {
if (Tok.is(tok::colon))
Diag(Tok, diag::err_objcbridge_related_selector_name);
else
Diag(Tok, diag::err_expected) << tok::comma;
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
IdentifierLoc *InstanceMethod = nullptr;
if (Tok.is(tok::identifier))
InstanceMethod = ParseIdentifierLoc();
else if (Tok.isNot(tok::r_paren)) {
Diag(Tok, diag::err_expected) << tok::r_paren;
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
if (T.consumeClose())
return;
if (EndLoc)
*EndLoc = T.getCloseLocation();
Attrs.addNew(&ObjCBridgeRelated,
SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
ScopeName, ScopeLoc, RelatedClass, ClassMethod, InstanceMethod,
Syntax);
}
void Parser::ParseSwiftNewTypeAttribute(
IdentifierInfo &AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.consumeOpen()) {
Diag(Tok, diag::err_expected) << tok::l_paren;
return;
}
if (Tok.is(tok::r_paren)) {
Diag(Tok.getLocation(), diag::err_argument_required_after_attribute);
T.consumeClose();
return;
}
if (Tok.isNot(tok::kw_struct) && Tok.isNot(tok::kw_enum)) {
Diag(Tok, diag::warn_attribute_type_not_supported)
<< &AttrName << Tok.getIdentifierInfo();
if (!isTokenSpecial())
ConsumeToken();
T.consumeClose();
return;
}
auto *SwiftType = IdentifierLoc::create(Actions.Context, Tok.getLocation(),
Tok.getIdentifierInfo());
ConsumeToken();
if (T.consumeClose())
return;
if (EndLoc)
*EndLoc = T.getCloseLocation();
ArgsUnion Args[] = {SwiftType};
Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, T.getCloseLocation()),
ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
}
void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs,
SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax) {
assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
BalancedDelimiterTracker T(*this, tok::l_paren);
T.consumeOpen();
if (Tok.isNot(tok::identifier)) {
Diag(Tok, diag::err_expected) << tok::identifier;
T.skipToEnd();
return;
}
IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
if (ExpectAndConsume(tok::comma)) {
T.skipToEnd();
return;
}
SourceRange MatchingCTypeRange;
TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
if (MatchingCType.isInvalid()) {
T.skipToEnd();
return;
}
bool LayoutCompatible = false;
bool MustBeNull = false;
while (TryConsumeToken(tok::comma)) {
if (Tok.isNot(tok::identifier)) {
Diag(Tok, diag::err_expected) << tok::identifier;
T.skipToEnd();
return;
}
IdentifierInfo *Flag = Tok.getIdentifierInfo();
if (Flag->isStr("layout_compatible"))
LayoutCompatible = true;
else if (Flag->isStr("must_be_null"))
MustBeNull = true;
else {
Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
T.skipToEnd();
return;
}
ConsumeToken(); }
if (!T.consumeClose()) {
Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
ArgumentKind, MatchingCType.get(),
LayoutCompatible, MustBeNull, Syntax);
}
if (EndLoc)
*EndLoc = T.getCloseLocation();
}
bool Parser::DiagnoseProhibitedCXX11Attribute() {
assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
switch (isCXX11AttributeSpecifier(true)) {
case CAK_NotAttributeSpecifier:
return false;
case CAK_InvalidAttributeSpecifier:
Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
return false;
case CAK_AttributeSpecifier:
SourceLocation BeginLoc = ConsumeBracket();
ConsumeBracket();
SkipUntil(tok::r_square);
assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
SourceLocation EndLoc = ConsumeBracket();
Diag(BeginLoc, diag::err_attributes_not_allowed)
<< SourceRange(BeginLoc, EndLoc);
return true;
}
llvm_unreachable("All cases handled above.");
}
void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributes &Attrs,
SourceLocation CorrectLocation) {
assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
Tok.is(tok::kw_alignas));
SourceLocation Loc = Tok.getLocation();
ParseCXX11Attributes(Attrs);
CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
Diag(Loc, diag::err_attributes_not_allowed)
<< FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
<< FixItHint::CreateRemoval(AttrRange);
}
void Parser::DiagnoseProhibitedAttributes(
const SourceRange &Range, const SourceLocation CorrectLocation) {
if (CorrectLocation.isValid()) {
CharSourceRange AttrRange(Range, true);
Diag(CorrectLocation, diag::err_attributes_misplaced)
<< FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
<< FixItHint::CreateRemoval(AttrRange);
} else
Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
}
void Parser::ProhibitCXX11Attributes(ParsedAttributes &Attrs, unsigned DiagID,
bool DiagnoseEmptyAttrs,
bool WarnOnUnknownAttrs) {
if (DiagnoseEmptyAttrs && Attrs.empty() && Attrs.Range.isValid()) {
const auto &LangOpts = getLangOpts();
auto &SM = PP.getSourceManager();
Token FirstLSquare;
Lexer::getRawToken(Attrs.Range.getBegin(), FirstLSquare, SM, LangOpts);
if (FirstLSquare.is(tok::l_square)) {
llvm::Optional<Token> SecondLSquare =
Lexer::findNextToken(FirstLSquare.getLocation(), SM, LangOpts);
if (SecondLSquare && SecondLSquare->is(tok::l_square)) {
Diag(Attrs.Range.getBegin(), DiagID) << Attrs.Range;
return;
}
}
}
for (const ParsedAttr &AL : Attrs) {
if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
continue;
if (AL.getKind() == ParsedAttr::UnknownAttribute) {
if (WarnOnUnknownAttrs)
Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
<< AL << AL.getRange();
} else {
Diag(AL.getLoc(), DiagID) << AL;
AL.setInvalid();
}
}
}
void Parser::DiagnoseCXX11AttributeExtension(ParsedAttributes &Attrs) {
for (const ParsedAttr &PA : Attrs) {
if (PA.isCXX11Attribute() || PA.isC2xAttribute())
Diag(PA.getLoc(), diag::ext_cxx11_attr_placement) << PA << PA.getRange();
}
}
void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs,
DeclSpec &DS,
Sema::TagUseKind TUK) {
if (TUK == Sema::TUK_Reference)
return;
llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
for (ParsedAttr &AL : DS.getAttributes()) {
if ((AL.getKind() == ParsedAttr::AT_Aligned &&
AL.isDeclspecAttribute()) ||
AL.isMicrosoftAttribute())
ToBeMoved.push_back(&AL);
}
for (ParsedAttr *AL : ToBeMoved) {
DS.getAttributes().remove(AL);
Attrs.addAtEnd(AL);
}
}
Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
SourceLocation &DeclEnd,
ParsedAttributes &DeclAttrs,
ParsedAttributes &DeclSpecAttrs,
SourceLocation *DeclSpecStart) {
ParenBraceBracketBalancer BalancerRAIIObj(*this);
ObjCDeclContextSwitch ObjCDC(*this);
Decl *SingleDecl = nullptr;
switch (Tok.getKind()) {
case tok::kw_template:
case tok::kw_export:
ProhibitAttributes(DeclAttrs);
ProhibitAttributes(DeclSpecAttrs);
SingleDecl =
ParseDeclarationStartingWithTemplate(Context, DeclEnd, DeclAttrs);
break;
case tok::kw_inline:
if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
ProhibitAttributes(DeclAttrs);
ProhibitAttributes(DeclSpecAttrs);
SourceLocation InlineLoc = ConsumeToken();
return ParseNamespace(Context, DeclEnd, InlineLoc);
}
return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
true, nullptr, DeclSpecStart);
case tok::kw_namespace:
ProhibitAttributes(DeclAttrs);
ProhibitAttributes(DeclSpecAttrs);
return ParseNamespace(Context, DeclEnd);
case tok::kw_using: {
ParsedAttributes Attrs(AttrFactory);
takeAndConcatenateAttrs(DeclAttrs, DeclSpecAttrs, Attrs);
return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
DeclEnd, Attrs);
}
case tok::kw_static_assert:
case tok::kw__Static_assert:
ProhibitAttributes(DeclAttrs);
ProhibitAttributes(DeclSpecAttrs);
SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
break;
default:
return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
true, nullptr, DeclSpecStart);
}
return Actions.ConvertDeclToDeclGroup(SingleDecl);
}
Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(
DeclaratorContext Context, SourceLocation &DeclEnd,
ParsedAttributes &DeclAttrs, ParsedAttributes &DeclSpecAttrs,
bool RequireSemi, ForRangeInit *FRI, SourceLocation *DeclSpecStart) {
ParsedAttributesView OriginalDeclSpecAttrs;
OriginalDeclSpecAttrs.addAll(DeclSpecAttrs.begin(), DeclSpecAttrs.end());
OriginalDeclSpecAttrs.Range = DeclSpecAttrs.Range;
ParsingDeclSpec DS(*this);
DS.takeAttributesFrom(DeclSpecAttrs);
DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
if (DS.hasTagDefinition() &&
DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
return nullptr;
if (Tok.is(tok::semi)) {
ProhibitAttributes(DeclAttrs);
DeclEnd = Tok.getLocation();
if (RequireSemi) ConsumeToken();
RecordDecl *AnonRecord = nullptr;
Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
DS.complete(TheDecl);
if (AnonRecord) {
Decl* decls[] = {AnonRecord, TheDecl};
return Actions.BuildDeclaratorGroup(decls);
}
return Actions.ConvertDeclToDeclGroup(TheDecl);
}
if (DeclSpecStart)
DS.SetRangeStart(*DeclSpecStart);
return ParseDeclGroup(DS, Context, DeclAttrs, &DeclEnd, FRI);
}
bool Parser::MightBeDeclarator(DeclaratorContext Context) {
switch (Tok.getKind()) {
case tok::annot_cxxscope:
case tok::annot_template_id:
case tok::caret:
case tok::code_completion:
case tok::coloncolon:
case tok::ellipsis:
case tok::kw___attribute:
case tok::kw_operator:
case tok::l_paren:
case tok::star:
return true;
case tok::amp:
case tok::ampamp:
return getLangOpts().CPlusPlus;
case tok::l_square: return Context == DeclaratorContext::Member && getLangOpts().CPlusPlus11 &&
NextToken().is(tok::l_square);
case tok::colon: return Context == DeclaratorContext::Member || getLangOpts().CPlusPlus;
case tok::identifier:
switch (NextToken().getKind()) {
case tok::code_completion:
case tok::coloncolon:
case tok::comma:
case tok::equal:
case tok::equalequal: case tok::kw_alignas:
case tok::kw_asm:
case tok::kw___attribute:
case tok::l_brace:
case tok::l_paren:
case tok::l_square:
case tok::less:
case tok::r_brace:
case tok::r_paren:
case tok::r_square:
case tok::semi:
return true;
case tok::colon:
return Context == DeclaratorContext::Member ||
(getLangOpts().CPlusPlus && Context == DeclaratorContext::File);
case tok::identifier: return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
default:
return false;
}
default:
return false;
}
}
void Parser::SkipMalformedDecl() {
while (true) {
switch (Tok.getKind()) {
case tok::l_brace:
ConsumeBrace();
SkipUntil(tok::r_brace);
if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
continue;
}
TryConsumeToken(tok::semi);
return;
case tok::l_square:
ConsumeBracket();
SkipUntil(tok::r_square);
continue;
case tok::l_paren:
ConsumeParen();
SkipUntil(tok::r_paren);
continue;
case tok::r_brace:
return;
case tok::semi:
ConsumeToken();
return;
case tok::kw_inline:
if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
(!ParsingInObjCContainer || CurParsedObjCImpl))
return;
break;
case tok::kw_namespace:
if (Tok.isAtStartOfLine() &&
(!ParsingInObjCContainer || CurParsedObjCImpl))
return;
break;
case tok::at:
if (NextToken().isObjCAtKeyword(tok::objc_end) &&
ParsingInObjCContainer)
return;
break;
case tok::minus:
case tok::plus:
if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
return;
break;
case tok::eof:
case tok::annot_module_begin:
case tok::annot_module_end:
case tok::annot_module_include:
return;
default:
break;
}
ConsumeAnyToken();
}
}
Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
DeclaratorContext Context,
ParsedAttributes &Attrs,
SourceLocation *DeclEnd,
ForRangeInit *FRI) {
ParsedAttributes LocalAttrs(AttrFactory);
LocalAttrs.takeAllFrom(Attrs);
ParsingDeclarator D(*this, DS, LocalAttrs, Context);
ParseDeclarator(D);
if (!D.hasName() && !D.mayOmitIdentifier()) {
SkipMalformedDecl();
return nullptr;
}
if (Tok.is(tok::kw_requires))
ParseTrailingRequiresClause(D);
LateParsedAttrList LateParsedAttrs(true);
if (D.isFunctionDeclarator()) {
MaybeParseGNUAttributes(D, &LateParsedAttrs);
if (Tok.is(tok::kw__Noreturn)) {
SourceLocation Loc = ConsumeToken();
const char *PrevSpec;
unsigned DiagID;
bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
MaybeParseGNUAttributes(D, &LateParsedAttrs);
Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
Diag(Loc, diag::err_c11_noreturn_misplaced)
<< (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
<< (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
: FixItHint());
}
}
if (D.isFunctionDeclarator()) {
if (Tok.is(tok::equal) && NextToken().is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompleteAfterFunctionEquals(D);
return nullptr;
}
while (auto Specifier = isCXX11VirtSpecifier()) {
Diag(Tok, diag::err_virt_specifier_outside_class)
<< VirtSpecifiers::getSpecifierName(Specifier)
<< FixItHint::CreateRemoval(Tok.getLocation());
ConsumeToken();
}
if (!isDeclarationAfterDeclarator()) {
if (Context == DeclaratorContext::File) {
if (isStartOfFunctionDefinition(D)) {
if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Diag(Tok, diag::err_function_declared_typedef);
DS.ClearStorageClassSpecs();
}
Decl *TheDecl = ParseFunctionDefinition(D, ParsedTemplateInfo(),
&LateParsedAttrs);
return Actions.ConvertDeclToDeclGroup(TheDecl);
}
if (isDeclarationSpecifier()) {
} else {
Diag(Tok, diag::err_expected_fn_body);
SkipUntil(tok::semi);
return nullptr;
}
} else {
if (Tok.is(tok::l_brace)) {
Diag(Tok, diag::err_function_definition_not_allowed);
SkipMalformedDecl();
return nullptr;
}
}
}
}
if (ParseAsmAttributesAfterDeclarator(D))
return nullptr;
if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
bool IsForRangeLoop = false;
if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
IsForRangeLoop = true;
if (getLangOpts().OpenMP)
Actions.startOpenMPCXXRangeFor();
if (Tok.is(tok::l_brace))
FRI->RangeExpr = ParseBraceInitializer();
else
FRI->RangeExpr = ParseExpression();
}
Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
if (IsForRangeLoop) {
Actions.ActOnCXXForRangeDecl(ThisDecl);
} else {
if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
VD->setObjCForDecl(true);
}
Actions.FinalizeDeclaration(ThisDecl);
D.complete(ThisDecl);
return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
}
SmallVector<Decl *, 8> DeclsInGroup;
Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
D, ParsedTemplateInfo(), FRI);
if (LateParsedAttrs.size() > 0)
ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
D.complete(FirstDecl);
if (FirstDecl)
DeclsInGroup.push_back(FirstDecl);
bool ExpectSemi = Context != DeclaratorContext::ForInit;
SourceLocation CommaLoc;
while (TryConsumeToken(tok::comma, CommaLoc)) {
if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
Diag(CommaLoc, diag::err_expected_semi_declaration)
<< FixItHint::CreateReplacement(CommaLoc, ";");
ExpectSemi = false;
break;
}
D.clear();
D.setCommaLoc(CommaLoc);
MaybeParseGNUAttributes(D);
if (getLangOpts().MicrosoftExt)
DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
ParseDeclarator(D);
if (!D.isInvalidType()) {
if (Tok.is(tok::kw_requires))
ParseTrailingRequiresClause(D);
Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
D.complete(ThisDecl);
if (ThisDecl)
DeclsInGroup.push_back(ThisDecl);
}
}
if (DeclEnd)
*DeclEnd = Tok.getLocation();
if (ExpectSemi && ExpectAndConsumeSemi(
Context == DeclaratorContext::File
? diag::err_invalid_token_after_toplevel_declarator
: diag::err_expected_semi_declaration)) {
if (!isDeclarationSpecifier()) {
SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
TryConsumeToken(tok::semi);
}
}
return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
}
bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
if (Tok.is(tok::kw_asm)) {
SourceLocation Loc;
ExprResult AsmLabel(ParseSimpleAsm( true, &Loc));
if (AsmLabel.isInvalid()) {
SkipUntil(tok::semi, StopBeforeMatch);
return true;
}
D.setAsmLabel(AsmLabel.get());
D.SetRangeEnd(Loc);
}
MaybeParseGNUAttributes(D);
return false;
}
Decl *Parser::ParseDeclarationAfterDeclarator(
Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
if (ParseAsmAttributesAfterDeclarator(D))
return nullptr;
return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
}
Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
struct InitializerScopeRAII {
Parser &P;
Declarator &D;
Decl *ThisDecl;
InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
: P(P), D(D), ThisDecl(ThisDecl) {
if (ThisDecl && P.getLangOpts().CPlusPlus) {
Scope *S = nullptr;
if (D.getCXXScopeSpec().isSet()) {
P.EnterScope(0);
S = P.getCurScope();
}
P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
}
}
~InitializerScopeRAII() { pop(); }
void pop() {
if (ThisDecl && P.getLangOpts().CPlusPlus) {
Scope *S = nullptr;
if (D.getCXXScopeSpec().isSet())
S = P.getCurScope();
P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
if (S)
P.ExitScope();
}
ThisDecl = nullptr;
}
};
enum class InitKind { Uninitialized, Equal, CXXDirect, CXXBraced };
InitKind TheInitKind;
if (isTokenEqualOrEqualTypo())
TheInitKind = InitKind::Equal;
else if (Tok.is(tok::l_paren))
TheInitKind = InitKind::CXXDirect;
else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
(!CurParsedObjCImpl || !D.isFunctionDeclarator()))
TheInitKind = InitKind::CXXBraced;
else
TheInitKind = InitKind::Uninitialized;
if (TheInitKind != InitKind::Uninitialized)
D.setHasInitializer();
Decl *ThisDecl = nullptr;
Decl *OuterDecl = nullptr;
switch (TemplateInfo.Kind) {
case ParsedTemplateInfo::NonTemplate:
ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
break;
case ParsedTemplateInfo::Template:
case ParsedTemplateInfo::ExplicitSpecialization: {
ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
*TemplateInfo.TemplateParams,
D);
if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl)) {
ThisDecl = VT->getTemplatedDecl();
OuterDecl = VT;
}
break;
}
case ParsedTemplateInfo::ExplicitInstantiation: {
if (Tok.is(tok::semi)) {
DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
if (ThisRes.isInvalid()) {
SkipUntil(tok::semi, StopBeforeMatch);
return nullptr;
}
ThisDecl = ThisRes.get();
} else {
if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Diag(Tok, diag::err_template_defn_explicit_instantiation)
<< 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
} else {
SourceLocation LAngleLoc =
PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
Diag(D.getIdentifierLoc(),
diag::err_explicit_instantiation_with_definition)
<< SourceRange(TemplateInfo.TemplateLoc)
<< FixItHint::CreateInsertion(LAngleLoc, "<>");
TemplateParameterLists FakedParamLists;
FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
LAngleLoc, nullptr));
ThisDecl =
Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
}
}
break;
}
}
switch (TheInitKind) {
case InitKind::Equal: {
SourceLocation EqualLoc = ConsumeToken();
if (Tok.is(tok::kw_delete)) {
if (D.isFunctionDeclarator())
Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
<< 1 ;
else
Diag(ConsumeToken(), diag::err_deleted_non_function);
} else if (Tok.is(tok::kw_default)) {
if (D.isFunctionDeclarator())
Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
<< 0 ;
else
Diag(ConsumeToken(), diag::err_default_special_members)
<< getLangOpts().CPlusPlus20;
} else {
InitializerScopeRAII InitScope(*this, D, ThisDecl);
if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
Actions.FinalizeDeclaration(ThisDecl);
return nullptr;
}
PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
ExprResult Init = ParseInitializer();
if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
<< FixItHint::CreateReplacement(EqualLoc, ":");
FRI->ColonLoc = EqualLoc;
Init = ExprError();
FRI->RangeExpr = Init;
}
InitScope.pop();
if (Init.isInvalid()) {
SmallVector<tok::TokenKind, 2> StopTokens;
StopTokens.push_back(tok::comma);
if (D.getContext() == DeclaratorContext::ForInit ||
D.getContext() == DeclaratorContext::SelectionInit)
StopTokens.push_back(tok::r_paren);
SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
Actions.ActOnInitializerError(ThisDecl);
} else
Actions.AddInitializerToDecl(ThisDecl, Init.get(),
false);
}
break;
}
case InitKind::CXXDirect: {
BalancedDelimiterTracker T(*this, tok::l_paren);
T.consumeOpen();
ExprVector Exprs;
CommaLocsTy CommaLocs;
InitializerScopeRAII InitScope(*this, D, ThisDecl);
auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
auto RunSignatureHelp = [&]() {
QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
ThisVarDecl->getType()->getCanonicalTypeInternal(),
ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
false);
CalledSignatureHelp = true;
return PreferredType;
};
auto SetPreferredType = [&] {
PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
};
llvm::function_ref<void()> ExpressionStarts;
if (ThisVarDecl) {
ExpressionStarts = SetPreferredType;
}
if (ParseExpressionList(Exprs, CommaLocs, ExpressionStarts)) {
if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
Actions.ProduceConstructorSignatureHelp(
ThisVarDecl->getType()->getCanonicalTypeInternal(),
ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
false);
CalledSignatureHelp = true;
}
Actions.ActOnInitializerError(ThisDecl);
SkipUntil(tok::r_paren, StopAtSemi);
} else {
T.consumeClose();
assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
"Unexpected number of commas!");
InitScope.pop();
ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
T.getCloseLocation(),
Exprs);
Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
true);
}
break;
}
case InitKind::CXXBraced: {
Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
InitializerScopeRAII InitScope(*this, D, ThisDecl);
PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
ExprResult Init(ParseBraceInitializer());
InitScope.pop();
if (Init.isInvalid()) {
Actions.ActOnInitializerError(ThisDecl);
} else
Actions.AddInitializerToDecl(ThisDecl, Init.get(), true);
break;
}
case InitKind::Uninitialized: {
Actions.ActOnUninitializedDecl(ThisDecl);
break;
}
}
Actions.FinalizeDeclaration(ThisDecl);
return OuterDecl ? OuterDecl : ThisDecl;
}
void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
DeclSpecContext DSC) {
ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
unsigned Specs = DS.getParsedSpecifiers();
if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
Diag(Tok, diag::err_expected_type);
DS.SetTypeSpecError();
} else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
Diag(Tok, diag::err_typename_requires_specqual);
if (!DS.hasTypeSpecifier())
DS.SetTypeSpecError();
}
if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
if (DS.getStorageClassSpecLoc().isValid())
Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
else
Diag(DS.getThreadStorageClassSpecLoc(),
diag::err_typename_invalid_storageclass);
DS.ClearStorageClassSpecs();
}
if (Specs & DeclSpec::PQ_FunctionSpecifier) {
if (DS.isInlineSpecified())
Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
if (DS.isVirtualSpecified())
Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
if (DS.hasExplicitSpecifier())
Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
DS.ClearFunctionSpecs();
}
if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
<< static_cast<int>(DS.getConstexprSpecifier());
DS.ClearConstexprSpec();
}
}
static bool isValidAfterIdentifierInDeclarator(const Token &T) {
return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
tok::colon);
}
bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
const ParsedTemplateInfo &TemplateInfo,
AccessSpecifier AS, DeclSpecContext DSC,
ParsedAttributes &Attrs) {
assert(Tok.is(tok::identifier) && "should have identifier");
SourceLocation Loc = Tok.getLocation();
assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
if (!isTypeSpecifier(DSC) && getLangOpts().isImplicitIntAllowed() &&
isValidAfterIdentifierInDeclarator(NextToken())) {
return false;
}
if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
return false;
if (getLangOpts().CPlusPlus &&
DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
if (SS)
AnnotateScopeToken(*SS, false);
return false;
}
if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
getLangOpts().MSVCCompat) {
if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
*Tok.getIdentifierInfo(), Tok.getLocation(),
DSC == DeclSpecContext::DSC_template_type_arg)) {
const char *PrevSpec;
unsigned DiagID;
DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
Actions.getASTContext().getPrintingPolicy());
DS.SetRangeEnd(Tok.getLocation());
ConsumeToken();
return false;
}
}
if (SS == nullptr) {
const char *TagName = nullptr, *FixitTagName = nullptr;
tok::TokenKind TagKind = tok::unknown;
switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
default: break;
case DeclSpec::TST_enum:
TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
case DeclSpec::TST_union:
TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
case DeclSpec::TST_struct:
TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
case DeclSpec::TST_interface:
TagName="__interface"; FixitTagName = "__interface ";
TagKind=tok::kw___interface;break;
case DeclSpec::TST_class:
TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
}
if (TagName) {
IdentifierInfo *TokenName = Tok.getIdentifierInfo();
LookupResult R(Actions, TokenName, SourceLocation(),
Sema::LookupOrdinaryName);
Diag(Loc, diag::err_use_of_tag_name_without_tag)
<< TokenName << TagName << getLangOpts().CPlusPlus
<< FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
if (Actions.LookupParsedName(R, getCurScope(), SS)) {
for (LookupResult::iterator I = R.begin(), IEnd = R.end();
I != IEnd; ++I)
Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
<< TokenName << TagName;
}
if (TagKind == tok::kw_enum)
ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
DeclSpecContext::DSC_normal);
else
ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
false,
DeclSpecContext::DSC_normal, Attrs);
return true;
}
}
if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
DSC == DeclSpecContext::DSC_class)) {
switch (NextToken().getKind()) {
case tok::l_paren: {
TentativeParsingAction PA(*this);
ConsumeToken();
TPResult TPR = TryParseDeclarator(false);
PA.Revert();
if (TPR != TPResult::False) {
break;
}
if (DSC == DeclSpecContext::DSC_class ||
(DSC == DeclSpecContext::DSC_top_level && SS)) {
IdentifierInfo *II = Tok.getIdentifierInfo();
if (Actions.isCurrentClassNameTypo(II, SS)) {
Diag(Loc, diag::err_constructor_bad_name)
<< Tok.getIdentifierInfo() << II
<< FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
Tok.setIdentifierInfo(II);
}
}
LLVM_FALLTHROUGH;
}
case tok::comma:
case tok::equal:
case tok::kw_asm:
case tok::l_brace:
case tok::l_square:
case tok::semi:
if (getCurScope()->isFunctionPrototypeScope())
break;
if (SS)
AnnotateScopeToken(*SS, false);
return false;
default:
break;
}
}
ParsedType T;
IdentifierInfo *II = Tok.getIdentifierInfo();
bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
IsTemplateName);
if (T) {
const char *PrevSpec;
unsigned DiagID;
DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
Actions.getASTContext().getPrintingPolicy());
DS.SetRangeEnd(Tok.getLocation());
ConsumeToken();
return true;
} else if (II != Tok.getIdentifierInfo()) {
Tok.setKind(II->getTokenID());
return true;
}
DS.SetTypeSpecError();
DS.SetRangeEnd(Tok.getLocation());
ConsumeToken();
if (IsTemplateName) {
SourceLocation LAngle, RAngle;
TemplateArgList Args;
ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
}
return true;
}
Parser::DeclSpecContext
Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
if (Context == DeclaratorContext::Member)
return DeclSpecContext::DSC_class;
if (Context == DeclaratorContext::File)
return DeclSpecContext::DSC_top_level;
if (Context == DeclaratorContext::TemplateParam)
return DeclSpecContext::DSC_template_param;
if (Context == DeclaratorContext::TemplateArg ||
Context == DeclaratorContext::TemplateTypeArg)
return DeclSpecContext::DSC_template_type_arg;
if (Context == DeclaratorContext::TrailingReturn ||
Context == DeclaratorContext::TrailingReturnVar)
return DeclSpecContext::DSC_trailing;
if (Context == DeclaratorContext::AliasDecl ||
Context == DeclaratorContext::AliasTemplate)
return DeclSpecContext::DSC_alias_declaration;
if (Context == DeclaratorContext::Association)
return DeclSpecContext::DSC_association;
return DeclSpecContext::DSC_normal;
}
ExprResult Parser::ParseAlignArgument(SourceLocation Start,
SourceLocation &EllipsisLoc) {
ExprResult ER;
if (isTypeIdInParens()) {
SourceLocation TypeLoc = Tok.getLocation();
ParsedType Ty = ParseTypeName().get();
SourceRange TypeRange(Start, Tok.getLocation());
ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
Ty.getAsOpaquePtr(), TypeRange);
} else
ER = ParseConstantExpression();
if (getLangOpts().CPlusPlus11)
TryConsumeToken(tok::ellipsis, EllipsisLoc);
return ER;
}
void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
SourceLocation *EndLoc) {
assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
"Not an alignment-specifier!");
IdentifierInfo *KWName = Tok.getIdentifierInfo();
SourceLocation KWLoc = ConsumeToken();
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.expectAndConsume())
return;
SourceLocation EllipsisLoc;
ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
if (ArgExpr.isInvalid()) {
T.skipToEnd();
return;
}
T.consumeClose();
if (EndLoc)
*EndLoc = T.getCloseLocation();
ArgsVector ArgExprs;
ArgExprs.push_back(ArgExpr.get());
Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
ParsedAttr::AS_Keyword, EllipsisLoc);
}
ExprResult Parser::ParseExtIntegerArgument() {
assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
"Not an extended int type");
ConsumeToken();
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.expectAndConsume())
return ExprError();
ExprResult ER = ParseConstantExpression();
if (ER.isInvalid()) {
T.skipToEnd();
return ExprError();
}
if(T.consumeClose())
return ExprError();
return ER;
}
bool
Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
DeclSpecContext DSContext,
LateParsedAttrList *LateAttrs) {
assert(DS.hasTagDefinition() && "shouldn't call this");
bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
DSContext == DeclSpecContext::DSC_top_level);
if (getLangOpts().CPlusPlus &&
Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
tok::annot_template_id) &&
TryAnnotateCXXScopeToken(EnteringContext)) {
SkipMalformedDecl();
return true;
}
bool HasScope = Tok.is(tok::annot_cxxscope);
Token AfterScope = HasScope ? NextToken() : Tok;
bool MightBeDeclarator = true;
if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
MightBeDeclarator = false;
} else if (AfterScope.is(tok::annot_template_id)) {
TemplateIdAnnotation *Annot =
static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
if (Annot->Kind == TNK_Type_template)
MightBeDeclarator = false;
} else if (AfterScope.is(tok::identifier)) {
const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
tok::annot_cxxscope, tok::coloncolon)) {
MightBeDeclarator = false;
} else if (HasScope) {
CXXScopeSpec SS;
Actions.RestoreNestedNameSpecifierAnnotation(
Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
IdentifierInfo *Name = AfterScope.getIdentifierInfo();
Sema::NameClassification Classification = Actions.ClassifyName(
getCurScope(), SS, Name, AfterScope.getLocation(), Next,
nullptr);
switch (Classification.getKind()) {
case Sema::NC_Error:
SkipMalformedDecl();
return true;
case Sema::NC_Keyword:
llvm_unreachable("typo correction is not possible here");
case Sema::NC_Type:
case Sema::NC_TypeTemplate:
case Sema::NC_UndeclaredNonType:
case Sema::NC_UndeclaredTemplate:
MightBeDeclarator = false;
break;
case Sema::NC_Unknown:
case Sema::NC_NonType:
case Sema::NC_DependentNonType:
case Sema::NC_OverloadSet:
case Sema::NC_VarTemplate:
case Sema::NC_FunctionTemplate:
case Sema::NC_Concept:
break;
}
}
}
if (MightBeDeclarator)
return false;
const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
diag::err_expected_after)
<< DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
DS.ClearTypeSpecType();
ParsedTemplateInfo NotATemplate;
ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
return false;
}
static void SetupFixedPointError(const LangOptions &LangOpts,
const char *&PrevSpec, unsigned &DiagID,
bool &isInvalid) {
assert(!LangOpts.FixedPoint);
DiagID = diag::err_fixed_point_not_enabled;
PrevSpec = ""; isInvalid = true;
}
void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
const ParsedTemplateInfo &TemplateInfo,
AccessSpecifier AS,
DeclSpecContext DSContext,
LateParsedAttrList *LateAttrs) {
if (DS.getSourceRange().isInvalid()) {
DS.SetRangeStart(Tok.getLocation());
DS.SetRangeEnd(SourceLocation());
}
bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
DSContext == DeclSpecContext::DSC_top_level);
bool AttrsLastTime = false;
ParsedAttributes attrs(AttrFactory);
PrintingPolicy Policy = Actions.getPrintingPolicy();
while (true) {
bool isInvalid = false;
bool isStorageClass = false;
const char *PrevSpec = nullptr;
unsigned DiagID = 0;
SourceLocation ConsumedEnd;
if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
!DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
Tok.setKind(tok::identifier);
SourceLocation Loc = Tok.getLocation();
auto handleOpenCLImageKW = [&] (StringRef Ext, TypeSpecifierType ImageTypeSpec) {
if (!StringRef(Ext).empty() && !getActions().getOpenCLOptions().isSupported(Ext, getLangOpts())) {
Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
Tok.setKind(tok::identifier);
return false;
}
isInvalid = DS.SetTypeSpecType(ImageTypeSpec, Loc, PrevSpec, DiagID, Policy);
return true;
};
bool IsTemplateSpecOrInst =
(TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
switch (Tok.getKind()) {
default:
DoneWithDeclSpec:
if (!AttrsLastTime)
ProhibitAttributes(attrs);
else {
for (const ParsedAttr &PA : attrs) {
if (!PA.isCXX11Attribute() && !PA.isC2xAttribute())
continue;
if (PA.getKind() == ParsedAttr::UnknownAttribute)
continue;
if (PA.getKind() == ParsedAttr::AT_VectorSize) {
Diag(PA.getLoc(), diag::warn_attribute_ignored) << PA;
PA.setInvalid();
continue;
}
if (PA.isTypeAttr() && PA.getKind() != ParsedAttr::AT_LifetimeBound &&
PA.getKind() != ParsedAttr::AT_AnyX86NoCfCheck)
continue;
Diag(PA.getLoc(), diag::err_attribute_not_type_attr) << PA;
PA.setInvalid();
}
DS.takeAttributesFrom(attrs);
}
DS.Finish(Actions, Policy);
return;
case tok::l_square:
case tok::kw_alignas:
if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
goto DoneWithDeclSpec;
ProhibitAttributes(attrs);
attrs.clear();
attrs.Range = SourceRange();
ParseCXX11Attributes(attrs);
AttrsLastTime = true;
continue;
case tok::code_completion: {
Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
if (DS.hasTypeSpecifier()) {
bool AllowNonIdentifiers
= (getCurScope()->getFlags() & (Scope::ControlScope |
Scope::BlockScope |
Scope::TemplateParamScope |
Scope::FunctionPrototypeScope |
Scope::AtCatchScope)) == 0;
bool AllowNestedNameSpecifiers
= DSContext == DeclSpecContext::DSC_top_level ||
(DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
cutOffParsing();
Actions.CodeCompleteDeclSpec(getCurScope(), DS,
AllowNonIdentifiers,
AllowNestedNameSpecifiers);
return;
}
if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
CCC = Sema::PCC_LocalDeclarationSpecifiers;
else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
: Sema::PCC_Template;
else if (DSContext == DeclSpecContext::DSC_class)
CCC = Sema::PCC_Class;
else if (CurParsedObjCImpl)
CCC = Sema::PCC_ObjCImplementation;
cutOffParsing();
Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
return;
}
case tok::coloncolon: if (TryAnnotateCXXScopeToken(EnteringContext)) {
if (!DS.hasTypeSpecifier())
DS.SetTypeSpecError();
goto DoneWithDeclSpec;
}
if (Tok.is(tok::coloncolon)) goto DoneWithDeclSpec;
continue;
case tok::annot_cxxscope: {
if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
goto DoneWithDeclSpec;
CXXScopeSpec SS;
Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
Tok.getAnnotationRange(),
SS);
Token Next = NextToken();
TemplateIdAnnotation *TemplateId = Next.is(tok::annot_template_id)
? takeTemplateIdAnnotation(Next)
: nullptr;
if (TemplateId && TemplateId->hasInvalidName()) {
DS.SetTypeSpecError();
ConsumeAnnotationToken();
break;
}
if (TemplateId && TemplateId->Kind == TNK_Type_template) {
if ((DSContext == DeclSpecContext::DSC_top_level ||
DSContext == DeclSpecContext::DSC_class) &&
TemplateId->Name &&
Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
isConstructorDeclarator(false)) {
goto DoneWithDeclSpec;
}
DS.getTypeSpecScope() = SS;
ConsumeAnnotationToken(); assert(Tok.is(tok::annot_template_id) &&
"ParseOptionalCXXScopeSpecifier not working");
AnnotateTemplateIdTokenAsType(SS);
continue;
}
if (TemplateId && TemplateId->Kind == TNK_Concept_template &&
GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype)) {
DS.getTypeSpecScope() = SS;
ConsumeAnnotationToken();
continue;
}
if (Next.is(tok::annot_typename)) {
DS.getTypeSpecScope() = SS;
ConsumeAnnotationToken(); TypeResult T = getTypeAnnotation(Tok);
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
Tok.getAnnotationEndLoc(),
PrevSpec, DiagID, T, Policy);
if (isInvalid)
break;
DS.SetRangeEnd(Tok.getAnnotationEndLoc());
ConsumeAnnotationToken(); }
if (Next.isNot(tok::identifier))
goto DoneWithDeclSpec;
if ((DSContext == DeclSpecContext::DSC_top_level ||
DSContext == DeclSpecContext::DSC_class) &&
Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
&SS) &&
isConstructorDeclarator( false))
goto DoneWithDeclSpec;
SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
ParsedType TypeRep =
Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
getCurScope(), &SS, false, false, nullptr,
false,
true,
isClassTemplateDeductionContext(DSContext));
if (IsTemplateSpecOrInst)
SAC.done();
if (!TypeRep) {
if (TryAnnotateTypeConstraint())
goto DoneWithDeclSpec;
if (Tok.isNot(tok::annot_cxxscope) ||
NextToken().isNot(tok::identifier))
continue;
ConsumeAnnotationToken();
ParsedAttributes Attrs(AttrFactory);
if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
if (!Attrs.empty()) {
AttrsLastTime = true;
attrs.takeAllFrom(Attrs);
}
continue;
}
goto DoneWithDeclSpec;
}
DS.getTypeSpecScope() = SS;
ConsumeAnnotationToken();
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
DiagID, TypeRep, Policy);
if (isInvalid)
break;
DS.SetRangeEnd(Tok.getLocation());
ConsumeToken();
continue;
}
case tok::annot_typename: {
if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
goto DoneWithDeclSpec;
TypeResult T = getTypeAnnotation(Tok);
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
DiagID, T, Policy);
if (isInvalid)
break;
DS.SetRangeEnd(Tok.getAnnotationEndLoc());
ConsumeAnnotationToken();
continue;
}
case tok::kw___is_signed:
if (DS.getTypeSpecType() == TST_bool &&
DS.getTypeQualifiers() == DeclSpec::TQ_const &&
DS.getStorageClassSpec() == DeclSpec::SCS_static)
TryKeywordIdentFallback(true);
goto DoneWithDeclSpec;
case tok::kw___super:
case tok::kw_decltype:
case tok::identifier: {
if (DS.hasTypeSpecifier())
goto DoneWithDeclSpec;
if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
Tok.getIdentifierInfo()->getName().equals("__declspec")) {
Diag(Loc, diag::err_ms_attributes_not_enabled);
if (NextToken().is(tok::l_paren)) {
ConsumeToken();
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.consumeOpen()) {
assert(false && "Not a left paren?");
return;
}
T.skipToEnd();
continue;
}
}
if (getLangOpts().CPlusPlus) {
SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
const bool Success = TryAnnotateCXXScopeToken(EnteringContext);
if (IsTemplateSpecOrInst)
SAC.done();
if (Success) {
if (IsTemplateSpecOrInst)
SAC.redelay();
DS.SetTypeSpecError();
goto DoneWithDeclSpec;
}
if (!Tok.is(tok::identifier))
continue;
}
if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
break;
if (DS.isTypeAltiVecVector())
goto DoneWithDeclSpec;
if (DSContext == DeclSpecContext::DSC_objc_method_result &&
isObjCInstancetype()) {
ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
assert(TypeRep);
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
DiagID, TypeRep, Policy);
if (isInvalid)
break;
DS.SetRangeEnd(Loc);
ConsumeToken();
continue;
}
if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
isConstructorDeclarator(true))
goto DoneWithDeclSpec;
ParsedType TypeRep = Actions.getTypeName(
*Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
false, false, nullptr, false, false,
isClassTemplateDeductionContext(DSContext));
if (!TypeRep) {
if (TryAnnotateTypeConstraint())
goto DoneWithDeclSpec;
if (Tok.isNot(tok::identifier))
continue;
ParsedAttributes Attrs(AttrFactory);
if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
if (!Attrs.empty()) {
AttrsLastTime = true;
attrs.takeAllFrom(Attrs);
}
continue;
}
goto DoneWithDeclSpec;
}
if (getLangOpts().CPlusPlus17 &&
(DSContext == DeclSpecContext::DSC_class ||
DSContext == DeclSpecContext::DSC_top_level) &&
Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
Tok.getLocation()) &&
isConstructorDeclarator( true,
true))
goto DoneWithDeclSpec;
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
DiagID, TypeRep, Policy);
if (isInvalid)
break;
DS.SetRangeEnd(Tok.getLocation());
ConsumeToken();
if (Tok.is(tok::less) && getLangOpts().ObjC) {
SourceLocation NewEndLoc;
TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
Loc, TypeRep, true,
NewEndLoc);
if (NewTypeRep.isUsable()) {
DS.UpdateTypeRep(NewTypeRep.get());
DS.SetRangeEnd(NewEndLoc);
}
}
continue;
}
case tok::annot_template_id: {
TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
if (TemplateId->hasInvalidName()) {
DS.SetTypeSpecError();
break;
}
if (TemplateId->Kind == TNK_Concept_template) {
if (TemplateId->hasInvalidArgs())
TemplateId = nullptr;
if (NextToken().is(tok::identifier)) {
Diag(Loc, diag::err_placeholder_expected_auto_or_decltype_auto)
<< FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
TemplateId, Policy);
break;
}
if (!NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
goto DoneWithDeclSpec;
ConsumeAnnotationToken();
SourceLocation AutoLoc = Tok.getLocation();
if (TryConsumeToken(tok::kw_decltype)) {
BalancedDelimiterTracker Tracker(*this, tok::l_paren);
if (Tracker.consumeOpen()) {
Diag(Tok, diag::err_expected) << tok::l_paren;
} else {
if (!TryConsumeToken(tok::kw_auto)) {
Tracker.skipToEnd();
Diag(Tok, diag::err_placeholder_expected_auto_or_decltype_auto)
<< FixItHint::CreateReplacement(SourceRange(AutoLoc,
Tok.getLocation()),
"auto");
} else {
Tracker.consumeClose();
}
}
ConsumedEnd = Tok.getLocation();
DS.setTypeofParensRange(Tracker.getRange());
isInvalid = DS.SetTypeSpecType(TST_decltype_auto, Loc, PrevSpec,
DiagID, TemplateId, Policy);
} else {
isInvalid = DS.SetTypeSpecType(TST_auto, AutoLoc, PrevSpec, DiagID,
TemplateId, Policy);
}
break;
}
if (TemplateId->Kind != TNK_Type_template &&
TemplateId->Kind != TNK_Undeclared_template) {
goto DoneWithDeclSpec;
}
if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
isConstructorDeclarator(true))
goto DoneWithDeclSpec;
CXXScopeSpec SS;
AnnotateTemplateIdTokenAsType(SS);
continue;
}
case tok::kw___attribute:
case tok::kw___declspec:
ParseAttributes(PAKM_GNU | PAKM_Declspec, DS.getAttributes(), LateAttrs);
continue;
case tok::kw___forceinline: {
isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
IdentifierInfo *AttrName = Tok.getIdentifierInfo();
SourceLocation AttrNameLoc = Tok.getLocation();
DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
nullptr, 0, ParsedAttr::AS_Keyword);
break;
}
case tok::kw___unaligned:
isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
getLangOpts());
break;
case tok::kw___sptr:
case tok::kw___uptr:
case tok::kw___ptr64:
case tok::kw___ptr32:
case tok::kw___w64:
case tok::kw___cdecl:
case tok::kw___stdcall:
case tok::kw___fastcall:
case tok::kw___thiscall:
case tok::kw___regcall:
case tok::kw___vectorcall:
ParseMicrosoftTypeAttributes(DS.getAttributes());
continue;
case tok::kw___pascal:
ParseBorlandTypeAttributes(DS.getAttributes());
continue;
case tok::kw___kernel:
ParseOpenCLKernelAttributes(DS.getAttributes());
continue;
case tok::kw___noinline__:
ParseCUDAFunctionAttributes(DS.getAttributes());
continue;
case tok::kw__Nonnull:
case tok::kw__Nullable:
case tok::kw__Nullable_result:
case tok::kw__Null_unspecified:
ParseNullabilityTypeSpecifiers(DS.getAttributes());
continue;
case tok::kw___kindof:
DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
nullptr, 0, ParsedAttr::AS_Keyword);
(void)ConsumeToken();
continue;
case tok::kw_typedef:
isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
PrevSpec, DiagID, Policy);
isStorageClass = true;
break;
case tok::kw_extern:
if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Diag(Tok, diag::ext_thread_before) << "extern";
isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
PrevSpec, DiagID, Policy);
isStorageClass = true;
break;
case tok::kw___private_extern__:
isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
Loc, PrevSpec, DiagID, Policy);
isStorageClass = true;
break;
case tok::kw_static:
if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Diag(Tok, diag::ext_thread_before) << "static";
isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
PrevSpec, DiagID, Policy);
isStorageClass = true;
break;
case tok::kw_auto:
if (getLangOpts().CPlusPlus11) {
if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
PrevSpec, DiagID, Policy);
if (!isInvalid)
Diag(Tok, diag::ext_auto_storage_class)
<< FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
} else
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
DiagID, Policy);
} else
isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
PrevSpec, DiagID, Policy);
isStorageClass = true;
break;
case tok::kw___auto_type:
Diag(Tok, diag::ext_auto_type);
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw_register:
isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
PrevSpec, DiagID, Policy);
isStorageClass = true;
break;
case tok::kw_mutable:
isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
PrevSpec, DiagID, Policy);
isStorageClass = true;
break;
case tok::kw___thread:
isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
PrevSpec, DiagID);
isStorageClass = true;
break;
case tok::kw_thread_local:
isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
PrevSpec, DiagID);
isStorageClass = true;
break;
case tok::kw__Thread_local:
if (!getLangOpts().C11)
Diag(Tok, diag::ext_c11_feature) << Tok.getName();
isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
Loc, PrevSpec, DiagID);
isStorageClass = true;
break;
case tok::kw_inline:
isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
break;
case tok::kw_virtual:
if (getLangOpts().OpenCLCPlusPlus &&
!getActions().getOpenCLOptions().isAvailableOption(
"__cl_clang_function_pointers", getLangOpts())) {
DiagID = diag::err_openclcxx_virtual_function;
PrevSpec = Tok.getIdentifierInfo()->getNameStart();
isInvalid = true;
} else {
isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
}
break;
case tok::kw_explicit: {
SourceLocation ExplicitLoc = Loc;
SourceLocation CloseParenLoc;
ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
ConsumedEnd = ExplicitLoc;
ConsumeToken(); if (Tok.is(tok::l_paren)) {
if (getLangOpts().CPlusPlus20 || isExplicitBool() == TPResult::True) {
Diag(Tok.getLocation(), getLangOpts().CPlusPlus20
? diag::warn_cxx17_compat_explicit_bool
: diag::ext_explicit_bool);
ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
BalancedDelimiterTracker Tracker(*this, tok::l_paren);
Tracker.consumeOpen();
ExplicitExpr = ParseConstantExpression();
ConsumedEnd = Tok.getLocation();
if (ExplicitExpr.isUsable()) {
CloseParenLoc = Tok.getLocation();
Tracker.consumeClose();
ExplicitSpec =
Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
} else
Tracker.skipToEnd();
} else {
Diag(Tok.getLocation(), diag::warn_cxx20_compat_explicit_bool);
}
}
isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
ExplicitSpec, CloseParenLoc);
break;
}
case tok::kw__Noreturn:
if (!getLangOpts().C11)
Diag(Tok, diag::ext_c11_feature) << Tok.getName();
isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
break;
case tok::kw__Alignas:
if (!getLangOpts().C11)
Diag(Tok, diag::ext_c11_feature) << Tok.getName();
ParseAlignmentSpecifier(DS.getAttributes());
continue;
case tok::kw_friend:
if (DSContext == DeclSpecContext::DSC_class)
isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
else {
PrevSpec = ""; DiagID = diag::err_friend_invalid_in_context;
isInvalid = true;
}
break;
case tok::kw___module_private__:
isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
break;
case tok::kw_constexpr:
isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, Loc,
PrevSpec, DiagID);
break;
case tok::kw_consteval:
isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Consteval, Loc,
PrevSpec, DiagID);
break;
case tok::kw_constinit:
isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Constinit, Loc,
PrevSpec, DiagID);
break;
case tok::kw_short:
isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw_long:
if (DS.getTypeSpecWidth() != TypeSpecifierWidth::Long)
isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec,
DiagID, Policy);
else
isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc,
PrevSpec, DiagID, Policy);
break;
case tok::kw___int64:
isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc,
PrevSpec, DiagID, Policy);
break;
case tok::kw_signed:
isInvalid =
DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
break;
case tok::kw_unsigned:
isInvalid = DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec,
DiagID);
break;
case tok::kw__Complex:
if (!getLangOpts().C99)
Diag(Tok, diag::ext_c99_feature) << Tok.getName();
isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
DiagID);
break;
case tok::kw__Imaginary:
if (!getLangOpts().C99)
Diag(Tok, diag::ext_c99_feature) << Tok.getName();
isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
DiagID);
break;
case tok::kw_void:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw_char:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw_int:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw__ExtInt:
case tok::kw__BitInt: {
DiagnoseBitIntUse(Tok);
ExprResult ER = ParseExtIntegerArgument();
if (ER.isInvalid())
continue;
isInvalid = DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
ConsumedEnd = PrevTokLocation;
break;
}
case tok::kw___int128:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw_half:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw___bf16:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw_float:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw_double:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw__Float16:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw__Accum:
if (!getLangOpts().FixedPoint) {
SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
} else {
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
DiagID, Policy);
}
break;
case tok::kw__Fract:
if (!getLangOpts().FixedPoint) {
SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
} else {
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
DiagID, Policy);
}
break;
case tok::kw__Sat:
if (!getLangOpts().FixedPoint) {
SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
} else {
isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
}
break;
case tok::kw___float128:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw___ibm128:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_ibm128, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw_wchar_t:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw_char8_t:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw_char16_t:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw_char32_t:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw_bool:
case tok::kw__Bool:
if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
Diag(Tok, diag::ext_c99_feature) << Tok.getName();
if (Tok.is(tok::kw_bool) &&
DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
PrevSpec = ""; DiagID = diag::err_bool_redeclaration;
Tok.setKind(tok::identifier);
isInvalid = true;
} else {
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
DiagID, Policy);
}
break;
case tok::kw__Decimal32:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw__Decimal64:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw__Decimal128:
isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
DiagID, Policy);
break;
case tok::kw___vector:
isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
break;
case tok::kw___pixel:
isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
break;
case tok::kw___bool:
isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
break;
case tok::kw_pipe:
if (!getLangOpts().OpenCL ||
getLangOpts().getOpenCLCompatibleVersion() < 200) {
Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
Tok.setKind(tok::identifier);
goto DoneWithDeclSpec;
} else if (!getLangOpts().OpenCLPipes) {
DiagID = diag::err_opencl_unknown_type_specifier;
PrevSpec = Tok.getIdentifierInfo()->getNameStart();
isInvalid = true;
} else
isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
break;
#define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
#define IMAGE_WRITE_TYPE(Type, Id, Ext)
#define IMAGE_READ_TYPE(ImgType, Id, Ext) \
case tok::kw_##ImgType##_t: \
if (!handleOpenCLImageKW(Ext, DeclSpec::TST_##ImgType##_t)) \
goto DoneWithDeclSpec; \
break;
#include "clang/Basic/OpenCLImageTypes.def"
case tok::kw___unknown_anytype:
isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
PrevSpec, DiagID, Policy);
break;
case tok::kw_class:
case tok::kw_struct:
case tok::kw___interface:
case tok::kw_union: {
tok::TokenKind Kind = Tok.getKind();
ConsumeToken();
ParsedAttributes Attributes(AttrFactory);
ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
EnteringContext, DSContext, Attributes);
if (!Attributes.empty()) {
AttrsLastTime = true;
attrs.takeAllFrom(Attributes);
}
continue;
}
case tok::kw_enum:
ConsumeToken();
ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
continue;
case tok::kw_const:
isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
getLangOpts());
break;
case tok::kw_volatile:
isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
getLangOpts());
break;
case tok::kw_restrict:
isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
getLangOpts());
break;
case tok::kw_typename:
if (TryAnnotateTypeOrScopeToken()) {
DS.SetTypeSpecError();
goto DoneWithDeclSpec;
}
if (!Tok.is(tok::kw_typename))
continue;
break;
case tok::kw_typeof:
ParseTypeofSpecifier(DS);
continue;
case tok::annot_decltype:
ParseDecltypeSpecifier(DS);
continue;
case tok::annot_pragma_pack:
HandlePragmaPack();
continue;
case tok::annot_pragma_ms_pragma:
HandlePragmaMSPragma();
continue;
case tok::annot_pragma_ms_vtordisp:
HandlePragmaMSVtorDisp();
continue;
case tok::annot_pragma_ms_pointers_to_members:
HandlePragmaMSPointersToMembers();
continue;
case tok::kw___underlying_type:
ParseUnderlyingTypeSpecifier(DS);
continue;
case tok::kw__Atomic:
if (!getLangOpts().C11)
Diag(Tok, diag::ext_c11_feature) << Tok.getName();
if (NextToken().is(tok::l_paren)) {
ParseAtomicSpecifier(DS);
continue;
}
isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
getLangOpts());
break;
case tok::kw___generic:
if (!Actions.getLangOpts().OpenCLGenericAddressSpace) {
DiagID = diag::err_opencl_unknown_type_specifier;
PrevSpec = Tok.getIdentifierInfo()->getNameStart();
isInvalid = true;
break;
}
LLVM_FALLTHROUGH;
case tok::kw_private:
if (!getLangOpts().OpenCL)
goto DoneWithDeclSpec;
LLVM_FALLTHROUGH;
case tok::kw___private:
case tok::kw___global:
case tok::kw___local:
case tok::kw___constant:
case tok::kw___read_only:
case tok::kw___write_only:
case tok::kw___read_write:
ParseOpenCLQualifiers(DS.getAttributes());
break;
case tok::less:
if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
goto DoneWithDeclSpec;
SourceLocation StartLoc = Tok.getLocation();
SourceLocation EndLoc;
TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
if (Type.isUsable()) {
if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
PrevSpec, DiagID, Type.get(),
Actions.getASTContext().getPrintingPolicy()))
Diag(StartLoc, DiagID) << PrevSpec;
DS.SetRangeEnd(EndLoc);
} else {
DS.SetTypeSpecError();
}
continue;
}
DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
if (isInvalid) {
assert(PrevSpec && "Method did not return previous specifier!");
assert(DiagID);
if (DiagID == diag::ext_duplicate_declspec ||
DiagID == diag::ext_warn_duplicate_declspec ||
DiagID == diag::err_duplicate_declspec)
Diag(Loc, DiagID) << PrevSpec
<< FixItHint::CreateRemoval(
SourceRange(Loc, DS.getEndLoc()));
else if (DiagID == diag::err_opencl_unknown_type_specifier) {
Diag(Loc, DiagID) << getLangOpts().getOpenCLVersionString() << PrevSpec
<< isStorageClass;
} else
Diag(Loc, DiagID) << PrevSpec;
}
if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
ConsumeAnyToken();
AttrsLastTime = false;
}
}
void Parser::ParseStructDeclaration(
ParsingDeclSpec &DS,
llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
if (Tok.is(tok::kw___extension__)) {
ExtensionRAIIObject O(Diags); ConsumeToken();
return ParseStructDeclaration(DS, FieldsCallback);
}
ParsedAttributes Attrs(AttrFactory);
MaybeParseCXX11Attributes(Attrs);
ParseSpecifierQualifierList(DS);
if (Tok.is(tok::semi)) {
ProhibitAttributes(Attrs);
RecordDecl *AnonRecord = nullptr;
Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
assert(!AnonRecord && "Did not expect anonymous struct or union here");
DS.complete(TheDecl);
return;
}
bool FirstDeclarator = true;
SourceLocation CommaLoc;
while (true) {
ParsingFieldDeclarator DeclaratorInfo(*this, DS, Attrs);
DeclaratorInfo.D.setCommaLoc(CommaLoc);
if (!FirstDeclarator) {
DiagnoseAndSkipCXX11Attributes();
MaybeParseGNUAttributes(DeclaratorInfo.D);
DiagnoseAndSkipCXX11Attributes();
}
if (Tok.isNot(tok::colon)) {
ColonProtectionRAIIObject X(*this);
ParseDeclarator(DeclaratorInfo.D);
} else
DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
if (TryConsumeToken(tok::colon)) {
ExprResult Res(ParseConstantExpression());
if (Res.isInvalid())
SkipUntil(tok::semi, StopBeforeMatch);
else
DeclaratorInfo.BitfieldSize = Res.get();
}
MaybeParseGNUAttributes(DeclaratorInfo.D);
FieldsCallback(DeclaratorInfo);
if (!TryConsumeToken(tok::comma, CommaLoc))
return;
FirstDeclarator = false;
}
}
void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
DeclSpec::TST TagType, RecordDecl *TagDecl) {
PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
"parsing struct/union body");
assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
BalancedDelimiterTracker T(*this, tok::l_brace);
if (T.consumeOpen())
return;
ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
Tok.isNot(tok::eof)) {
if (Tok.is(tok::semi)) {
ConsumeExtraSemi(InsideStruct, TagType);
continue;
}
if (Tok.isOneOf(tok::kw__Static_assert, tok::kw_static_assert)) {
SourceLocation DeclEnd;
ParseStaticAssertDeclaration(DeclEnd);
continue;
}
if (Tok.is(tok::annot_pragma_pack)) {
HandlePragmaPack();
continue;
}
if (Tok.is(tok::annot_pragma_align)) {
HandlePragmaAlign();
continue;
}
if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) {
AccessSpecifier AS = AS_none;
ParsedAttributes Attrs(AttrFactory);
(void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
continue;
}
if (tok::isPragmaAnnotation(Tok.getKind())) {
Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
<< DeclSpec::getSpecifierName(
TagType, Actions.getASTContext().getPrintingPolicy());
ConsumeAnnotationToken();
continue;
}
if (!Tok.is(tok::at)) {
auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
Decl *Field =
Actions.ActOnField(getCurScope(), TagDecl,
FD.D.getDeclSpec().getSourceRange().getBegin(),
FD.D, FD.BitfieldSize);
FD.complete(Field);
};
ParsingDeclSpec DS(*this);
ParseStructDeclaration(DS, CFieldCallback);
} else { ConsumeToken();
if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
Diag(Tok, diag::err_unexpected_at);
SkipUntil(tok::semi);
continue;
}
ConsumeToken();
ExpectAndConsume(tok::l_paren);
if (!Tok.is(tok::identifier)) {
Diag(Tok, diag::err_expected) << tok::identifier;
SkipUntil(tok::semi);
continue;
}
SmallVector<Decl *, 16> Fields;
Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
Tok.getIdentifierInfo(), Fields);
ConsumeToken();
ExpectAndConsume(tok::r_paren);
}
if (TryConsumeToken(tok::semi))
continue;
if (Tok.is(tok::r_brace)) {
ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
break;
}
ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
TryConsumeToken(tok::semi);
}
T.consumeClose();
ParsedAttributes attrs(AttrFactory);
MaybeParseGNUAttributes(attrs);
SmallVector<Decl *, 32> FieldDecls(TagDecl->fields());
Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
T.getOpenLocation(), T.getCloseLocation(), attrs);
StructScope.Exit();
Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
}
void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
const ParsedTemplateInfo &TemplateInfo,
AccessSpecifier AS, DeclSpecContext DSC) {
if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
return;
}
ParsedAttributes attrs(AttrFactory);
MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
SourceLocation ScopedEnumKWLoc;
bool IsScopedUsingClassTag = false;
if (Tok.isOneOf(tok::kw_class, tok::kw_struct) && getLangOpts().CPlusPlus) {
Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
: diag::ext_scoped_enum);
IsScopedUsingClassTag = Tok.is(tok::kw_class);
ScopedEnumKWLoc = ConsumeToken();
ProhibitAttributes(attrs);
MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
}
bool shouldDelayDiagsInTag =
(TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
AllowDefiningTypeSpec AllowEnumSpecifier =
isDefiningTypeSpecifierContext(DSC, getLangOpts().CPlusPlus);
bool CanBeOpaqueEnumDeclaration =
DS.isEmpty() && isOpaqueEnumDeclarationContext(DSC);
bool CanHaveEnumBase = (getLangOpts().CPlusPlus11 || getLangOpts().ObjC ||
getLangOpts().MicrosoftExt) &&
(AllowEnumSpecifier == AllowDefiningTypeSpec::Yes ||
CanBeOpaqueEnumDeclaration);
CXXScopeSpec &SS = DS.getTypeSpecScope();
if (getLangOpts().CPlusPlus) {
ColonProtectionRAIIObject X(*this);
CXXScopeSpec Spec;
if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
false,
true))
return;
if (Spec.isSet() && Tok.isNot(tok::identifier)) {
Diag(Tok, diag::err_expected) << tok::identifier;
if (Tok.isNot(tok::l_brace)) {
SkipUntil(tok::comma, StopAtSemi);
return;
}
}
SS = Spec;
}
if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
Tok.isNot(tok::colon)) {
Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
SkipUntil(tok::comma, StopAtSemi);
return;
}
IdentifierInfo *Name = nullptr;
SourceLocation NameLoc;
if (Tok.is(tok::identifier)) {
Name = Tok.getIdentifierInfo();
NameLoc = ConsumeToken();
}
if (!Name && ScopedEnumKWLoc.isValid()) {
Diag(Tok, diag::err_scoped_enum_missing_identifier);
ScopedEnumKWLoc = SourceLocation();
IsScopedUsingClassTag = false;
}
if (shouldDelayDiagsInTag)
diagsFromTag.done();
TypeResult BaseType;
SourceRange BaseRange;
bool CanBeBitfield =
getCurScope()->isClassScope() && ScopedEnumKWLoc.isInvalid() && Name;
if (Tok.is(tok::colon)) {
if (CanBeBitfield && !isEnumBase(CanBeOpaqueEnumDeclaration)) {
if (getLangOpts().CPlusPlus11)
Diag(Tok.getLocation(), diag::err_anonymous_enum_bitfield);
} else if (CanHaveEnumBase || !ColonIsSacred) {
SourceLocation ColonLoc = ConsumeToken();
DeclSpec DS(AttrFactory);
ParseSpecifierQualifierList(DS, AS, DeclSpecContext::DSC_type_specifier);
Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
DeclaratorContext::TypeName);
BaseType = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
BaseRange = SourceRange(ColonLoc, DeclaratorInfo.getSourceRange().getEnd());
if (!getLangOpts().ObjC) {
if (getLangOpts().CPlusPlus11)
Diag(ColonLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type)
<< BaseRange;
else if (getLangOpts().CPlusPlus)
Diag(ColonLoc, diag::ext_cxx11_enum_fixed_underlying_type)
<< BaseRange;
else if (getLangOpts().MicrosoftExt)
Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
<< BaseRange;
else
Diag(ColonLoc, diag::ext_clang_c_enum_fixed_underlying_type)
<< BaseRange;
}
}
}
Sema::TagUseKind TUK;
if (AllowEnumSpecifier == AllowDefiningTypeSpec::No)
TUK = Sema::TUK_Reference;
else if (Tok.is(tok::l_brace)) {
if (DS.isFriendSpecified()) {
Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
<< SourceRange(DS.getFriendSpecLoc());
ConsumeBrace();
SkipUntil(tok::r_brace, StopAtSemi);
attrs.clear();
ScopedEnumKWLoc = SourceLocation();
IsScopedUsingClassTag = false;
BaseType = TypeResult();
TUK = Sema::TUK_Friend;
} else {
TUK = Sema::TUK_Definition;
}
} else if (!isTypeSpecifier(DSC) &&
(Tok.is(tok::semi) ||
(Tok.isAtStartOfLine() &&
!isValidAfterTypeSpecifier(CanBeBitfield)))) {
TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
if (Tok.isNot(tok::semi)) {
ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
PP.EnterToken(Tok, true);
Tok.setKind(tok::semi);
}
} else {
TUK = Sema::TUK_Reference;
}
bool IsElaboratedTypeSpecifier =
TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend;
if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
diagsFromTag.redelay();
}
MultiTemplateParamsArg TParams;
if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
TUK != Sema::TUK_Reference) {
if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
Diag(Tok, diag::err_enum_template);
SkipUntil(tok::comma, StopAtSemi);
return;
}
if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
DS.SetTypeSpecError();
Diag(StartLoc, diag::err_explicit_instantiation_enum);
return;
}
assert(TemplateInfo.TemplateParams && "no template parameters");
TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
TemplateInfo.TemplateParams->size());
}
if (!Name && TUK != Sema::TUK_Definition) {
Diag(Tok, diag::err_enumerator_unnamed_no_def);
SkipUntil(tok::comma, StopAtSemi);
return;
}
if (IsElaboratedTypeSpecifier && !getLangOpts().MicrosoftExt &&
!getLangOpts().ObjC) {
ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
true);
if (BaseType.isUsable())
Diag(BaseRange.getBegin(), diag::ext_enum_base_in_type_specifier)
<< (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes) << BaseRange;
else if (ScopedEnumKWLoc.isValid())
Diag(ScopedEnumKWLoc, diag::ext_elaborated_enum_class)
<< FixItHint::CreateRemoval(ScopedEnumKWLoc) << IsScopedUsingClassTag;
}
stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
Sema::SkipBodyInfo SkipBody;
if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
NextToken().is(tok::identifier))
SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
NextToken().getIdentifierInfo(),
NextToken().getLocation());
bool Owned = false;
bool IsDependent = false;
const char *PrevSpec = nullptr;
unsigned DiagID;
Decl *TagDecl = Actions.ActOnTag(
getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
DSC == DeclSpecContext::DSC_type_specifier,
DSC == DeclSpecContext::DSC_template_param ||
DSC == DeclSpecContext::DSC_template_type_arg,
&SkipBody);
if (SkipBody.ShouldSkip) {
assert(TUK == Sema::TUK_Definition && "can only skip a definition");
BalancedDelimiterTracker T(*this, tok::l_brace);
T.consumeOpen();
T.skipToEnd();
if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
NameLoc.isValid() ? NameLoc : StartLoc,
PrevSpec, DiagID, TagDecl, Owned,
Actions.getASTContext().getPrintingPolicy()))
Diag(StartLoc, DiagID) << PrevSpec;
return;
}
if (IsDependent) {
if (!Name) {
DS.SetTypeSpecError();
Diag(Tok, diag::err_expected_type_name_after_typename);
return;
}
TypeResult Type = Actions.ActOnDependentTag(
getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
if (Type.isInvalid()) {
DS.SetTypeSpecError();
return;
}
if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
NameLoc.isValid() ? NameLoc : StartLoc,
PrevSpec, DiagID, Type.get(),
Actions.getASTContext().getPrintingPolicy()))
Diag(StartLoc, DiagID) << PrevSpec;
return;
}
if (!TagDecl) {
if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
ConsumeBrace();
SkipUntil(tok::r_brace, StopAtSemi);
}
DS.SetTypeSpecError();
return;
}
if (Tok.is(tok::l_brace) && TUK == Sema::TUK_Definition) {
Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
ParseEnumBody(StartLoc, D);
if (SkipBody.CheckSameAsPrevious &&
!Actions.ActOnDuplicateDefinition(TagDecl, SkipBody)) {
DS.SetTypeSpecError();
return;
}
}
if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
NameLoc.isValid() ? NameLoc : StartLoc,
PrevSpec, DiagID, TagDecl, Owned,
Actions.getASTContext().getPrintingPolicy()))
Diag(StartLoc, DiagID) << PrevSpec;
}
void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
BalancedDelimiterTracker T(*this, tok::l_brace);
T.consumeOpen();
if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
Diag(Tok, diag::err_empty_enum);
SmallVector<Decl *, 32> EnumConstantDecls;
SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
Decl *LastEnumConstDecl = nullptr;
while (Tok.isNot(tok::r_brace)) {
if (Tok.isNot(tok::identifier)) {
Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
TryConsumeToken(tok::comma))
continue;
break;
}
IdentifierInfo *Ident = Tok.getIdentifierInfo();
SourceLocation IdentLoc = ConsumeToken();
ParsedAttributes attrs(AttrFactory);
MaybeParseGNUAttributes(attrs);
if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
if (getLangOpts().CPlusPlus)
Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
? diag::warn_cxx14_compat_ns_enum_attribute
: diag::ext_ns_enum_attribute)
<< 1 ;
ParseCXX11Attributes(attrs);
}
SourceLocation EqualLoc;
ExprResult AssignedVal;
EnumAvailabilityDiags.emplace_back(*this);
EnterExpressionEvaluationContext ConstantEvaluated(
Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
if (TryConsumeToken(tok::equal, EqualLoc)) {
AssignedVal = ParseConstantExpressionInExprEvalContext();
if (AssignedVal.isInvalid())
SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
}
Decl *EnumConstDecl = Actions.ActOnEnumConstant(
getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
EqualLoc, AssignedVal.get());
EnumAvailabilityDiags.back().done();
EnumConstantDecls.push_back(EnumConstDecl);
LastEnumConstDecl = EnumConstDecl;
if (Tok.is(tok::identifier)) {
SourceLocation Loc = getEndOfPreviousToken();
Diag(Loc, diag::err_enumerator_list_missing_comma)
<< FixItHint::CreateInsertion(Loc, ", ");
continue;
}
SourceLocation CommaLoc;
if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
if (EqualLoc.isValid())
Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
<< tok::comma;
else
Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
if (TryConsumeToken(tok::comma, CommaLoc))
continue;
} else {
break;
}
}
if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
Diag(CommaLoc, getLangOpts().CPlusPlus ?
diag::ext_enumerator_list_comma_cxx :
diag::ext_enumerator_list_comma_c)
<< FixItHint::CreateRemoval(CommaLoc);
else if (getLangOpts().CPlusPlus11)
Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
<< FixItHint::CreateRemoval(CommaLoc);
break;
}
}
T.consumeClose();
ParsedAttributes attrs(AttrFactory);
MaybeParseGNUAttributes(attrs);
Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
getCurScope(), attrs);
assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
EnumAvailabilityDiags[i].redelay();
PD.complete(EnumConstantDecls[i]);
}
EnumScope.Exit();
Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
bool CanBeBitfield = getCurScope()->isClassScope();
if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
PP.EnterToken(Tok, true);
Tok.setKind(tok::semi);
}
}
bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
switch (Tok.getKind()) {
default: return false;
case tok::kw_short:
case tok::kw_long:
case tok::kw___int64:
case tok::kw___int128:
case tok::kw_signed:
case tok::kw_unsigned:
case tok::kw__Complex:
case tok::kw__Imaginary:
case tok::kw_void:
case tok::kw_char:
case tok::kw_wchar_t:
case tok::kw_char8_t:
case tok::kw_char16_t:
case tok::kw_char32_t:
case tok::kw_int:
case tok::kw__ExtInt:
case tok::kw__BitInt:
case tok::kw___bf16:
case tok::kw_half:
case tok::kw_float:
case tok::kw_double:
case tok::kw__Accum:
case tok::kw__Fract:
case tok::kw__Float16:
case tok::kw___float128:
case tok::kw___ibm128:
case tok::kw_bool:
case tok::kw__Bool:
case tok::kw__Decimal32:
case tok::kw__Decimal64:
case tok::kw__Decimal128:
case tok::kw___vector:
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
#include "clang/Basic/OpenCLImageTypes.def"
case tok::kw_class:
case tok::kw_struct:
case tok::kw___interface:
case tok::kw_union:
case tok::kw_enum:
case tok::annot_typename:
return true;
}
}
bool Parser::isTypeSpecifierQualifier() {
switch (Tok.getKind()) {
default: return false;
case tok::identifier: if (TryAltiVecVectorToken())
return true;
LLVM_FALLTHROUGH;
case tok::kw_typename: if (TryAnnotateTypeOrScopeToken())
return true;
if (Tok.is(tok::identifier))
return false;
return isTypeSpecifierQualifier();
case tok::coloncolon: if (NextToken().is(tok::kw_new) || NextToken().is(tok::kw_delete)) return false;
if (TryAnnotateTypeOrScopeToken())
return true;
return isTypeSpecifierQualifier();
case tok::kw___attribute:
case tok::kw_typeof:
case tok::kw_short:
case tok::kw_long:
case tok::kw___int64:
case tok::kw___int128:
case tok::kw_signed:
case tok::kw_unsigned:
case tok::kw__Complex:
case tok::kw__Imaginary:
case tok::kw_void:
case tok::kw_char:
case tok::kw_wchar_t:
case tok::kw_char8_t:
case tok::kw_char16_t:
case tok::kw_char32_t:
case tok::kw_int:
case tok::kw__ExtInt:
case tok::kw__BitInt:
case tok::kw_half:
case tok::kw___bf16:
case tok::kw_float:
case tok::kw_double:
case tok::kw__Accum:
case tok::kw__Fract:
case tok::kw__Float16:
case tok::kw___float128:
case tok::kw___ibm128:
case tok::kw_bool:
case tok::kw__Bool:
case tok::kw__Decimal32:
case tok::kw__Decimal64:
case tok::kw__Decimal128:
case tok::kw___vector:
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
#include "clang/Basic/OpenCLImageTypes.def"
case tok::kw_class:
case tok::kw_struct:
case tok::kw___interface:
case tok::kw_union:
case tok::kw_enum:
case tok::kw_const:
case tok::kw_volatile:
case tok::kw_restrict:
case tok::kw__Sat:
case tok::kw___unknown_anytype:
case tok::annot_typename:
return true;
case tok::less:
return getLangOpts().ObjC;
case tok::kw___cdecl:
case tok::kw___stdcall:
case tok::kw___fastcall:
case tok::kw___thiscall:
case tok::kw___regcall:
case tok::kw___vectorcall:
case tok::kw___w64:
case tok::kw___ptr64:
case tok::kw___ptr32:
case tok::kw___pascal:
case tok::kw___unaligned:
case tok::kw__Nonnull:
case tok::kw__Nullable:
case tok::kw__Nullable_result:
case tok::kw__Null_unspecified:
case tok::kw___kindof:
case tok::kw___private:
case tok::kw___local:
case tok::kw___global:
case tok::kw___constant:
case tok::kw___generic:
case tok::kw___read_only:
case tok::kw___read_write:
case tok::kw___write_only:
return true;
case tok::kw_private:
return getLangOpts().OpenCL;
case tok::kw__Atomic:
return true;
}
}
bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
switch (Tok.getKind()) {
default: return false;
case tok::kw_pipe:
return getLangOpts().OpenCL &&
getLangOpts().getOpenCLCompatibleVersion() >= 200;
case tok::identifier: if (getLangOpts().ObjC && NextToken().is(tok::period))
return false;
if (TryAltiVecVectorToken())
return true;
LLVM_FALLTHROUGH;
case tok::kw_decltype: case tok::kw_typename: if (TryAnnotateTypeOrScopeToken())
return true;
if (TryAnnotateTypeConstraint())
return true;
if (Tok.is(tok::identifier))
return false;
if (DisambiguatingWithExpression &&
isStartOfObjCClassMessageMissingOpenBracket())
return false;
return isDeclarationSpecifier();
case tok::coloncolon: if (NextToken().is(tok::kw_new) || NextToken().is(tok::kw_delete)) return false;
if (TryAnnotateTypeOrScopeToken())
return true;
return isDeclarationSpecifier();
case tok::kw_typedef:
case tok::kw_extern:
case tok::kw___private_extern__:
case tok::kw_static:
case tok::kw_auto:
case tok::kw___auto_type:
case tok::kw_register:
case tok::kw___thread:
case tok::kw_thread_local:
case tok::kw__Thread_local:
case tok::kw___module_private__:
case tok::kw___unknown_anytype:
case tok::kw_short:
case tok::kw_long:
case tok::kw___int64:
case tok::kw___int128:
case tok::kw_signed:
case tok::kw_unsigned:
case tok::kw__Complex:
case tok::kw__Imaginary:
case tok::kw_void:
case tok::kw_char:
case tok::kw_wchar_t:
case tok::kw_char8_t:
case tok::kw_char16_t:
case tok::kw_char32_t:
case tok::kw_int:
case tok::kw__ExtInt:
case tok::kw__BitInt:
case tok::kw_half:
case tok::kw___bf16:
case tok::kw_float:
case tok::kw_double:
case tok::kw__Accum:
case tok::kw__Fract:
case tok::kw__Float16:
case tok::kw___float128:
case tok::kw___ibm128:
case tok::kw_bool:
case tok::kw__Bool:
case tok::kw__Decimal32:
case tok::kw__Decimal64:
case tok::kw__Decimal128:
case tok::kw___vector:
case tok::kw_class:
case tok::kw_struct:
case tok::kw_union:
case tok::kw___interface:
case tok::kw_enum:
case tok::kw_const:
case tok::kw_volatile:
case tok::kw_restrict:
case tok::kw__Sat:
case tok::kw_inline:
case tok::kw_virtual:
case tok::kw_explicit:
case tok::kw__Noreturn:
case tok::kw__Alignas:
case tok::kw_friend:
case tok::kw_static_assert:
case tok::kw__Static_assert:
case tok::kw_typeof:
case tok::kw___attribute:
case tok::annot_decltype:
case tok::kw_constexpr:
case tok::kw_consteval:
case tok::kw_constinit:
case tok::kw__Atomic:
return true;
case tok::less:
return getLangOpts().ObjC;
case tok::annot_typename:
return !DisambiguatingWithExpression ||
!isStartOfObjCClassMessageMissingOpenBracket();
case tok::annot_template_id: {
TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
if (TemplateId->hasInvalidName())
return true;
return isTypeConstraintAnnotation() &&
(NextToken().is(tok::kw_auto) || NextToken().is(tok::kw_decltype));
}
case tok::annot_cxxscope: {
TemplateIdAnnotation *TemplateId =
NextToken().is(tok::annot_template_id)
? takeTemplateIdAnnotation(NextToken())
: nullptr;
if (TemplateId && TemplateId->hasInvalidName())
return true;
if (NextToken().is(tok::identifier) && TryAnnotateTypeConstraint())
return true;
return isTypeConstraintAnnotation() &&
GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype);
}
case tok::kw___declspec:
case tok::kw___cdecl:
case tok::kw___stdcall:
case tok::kw___fastcall:
case tok::kw___thiscall:
case tok::kw___regcall:
case tok::kw___vectorcall:
case tok::kw___w64:
case tok::kw___sptr:
case tok::kw___uptr:
case tok::kw___ptr64:
case tok::kw___ptr32:
case tok::kw___forceinline:
case tok::kw___pascal:
case tok::kw___unaligned:
case tok::kw__Nonnull:
case tok::kw__Nullable:
case tok::kw__Nullable_result:
case tok::kw__Null_unspecified:
case tok::kw___kindof:
case tok::kw___private:
case tok::kw___local:
case tok::kw___global:
case tok::kw___constant:
case tok::kw___generic:
case tok::kw___read_only:
case tok::kw___read_write:
case tok::kw___write_only:
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
#include "clang/Basic/OpenCLImageTypes.def"
return true;
case tok::kw_private:
return getLangOpts().OpenCL;
}
}
bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
TentativeParsingAction TPA(*this);
CXXScopeSpec SS;
if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
false,
true)) {
TPA.Revert();
return false;
}
if (Tok.is(tok::identifier)) {
ConsumeToken();
} else if (Tok.is(tok::annot_template_id)) {
ConsumeAnnotationToken();
} else {
TPA.Revert();
return false;
}
SkipCXX11Attributes();
if (Tok.isNot(tok::l_paren)) {
TPA.Revert();
return false;
}
ConsumeParen();
if (Tok.is(tok::r_paren) ||
(Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
TPA.Revert();
return true;
}
if (getLangOpts().CPlusPlus11 &&
isCXX11AttributeSpecifier( false,
true)) {
TPA.Revert();
return true;
}
DeclaratorScopeObj DeclScopeObj(*this, SS);
if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
DeclScopeObj.EnterDeclaratorScope();
ParsedAttributes Attrs(AttrFactory);
MaybeParseMicrosoftAttributes(Attrs);
bool IsConstructor = false;
if (isDeclarationSpecifier())
IsConstructor = true;
else if (Tok.is(tok::identifier) ||
(Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
if (Tok.is(tok::annot_cxxscope))
ConsumeAnnotationToken();
ConsumeToken();
switch (Tok.getKind()) {
case tok::l_paren:
case tok::l_square:
case tok::coloncolon:
break;
case tok::r_paren:
ConsumeParen();
SkipCXX11Attributes();
if (DeductionGuide) {
IsConstructor = Tok.is(tok::arrow);
break;
}
if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
IsConstructor = true;
}
if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
IsConstructor = IsUnqualified;
}
break;
default:
IsConstructor = true;
break;
}
}
TPA.Revert();
return IsConstructor;
}
void Parser::ParseTypeQualifierListOpt(
DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
bool IdentifierRequired,
Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
isCXX11AttributeSpecifier()) {
ParsedAttributes Attrs(AttrFactory);
ParseCXX11Attributes(Attrs);
DS.takeAttributesFrom(Attrs);
}
SourceLocation EndLoc;
while (true) {
bool isInvalid = false;
const char *PrevSpec = nullptr;
unsigned DiagID = 0;
SourceLocation Loc = Tok.getLocation();
switch (Tok.getKind()) {
case tok::code_completion:
cutOffParsing();
if (CodeCompletionHandler)
(*CodeCompletionHandler)();
else
Actions.CodeCompleteTypeQualifiers(DS);
return;
case tok::kw_const:
isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
getLangOpts());
break;
case tok::kw_volatile:
isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
getLangOpts());
break;
case tok::kw_restrict:
isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
getLangOpts());
break;
case tok::kw__Atomic:
if (!AtomicAllowed)
goto DoneWithTypeQuals;
if (!getLangOpts().C11)
Diag(Tok, diag::ext_c11_feature) << Tok.getName();
isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
getLangOpts());
break;
case tok::kw_private:
if (!getLangOpts().OpenCL)
goto DoneWithTypeQuals;
LLVM_FALLTHROUGH;
case tok::kw___private:
case tok::kw___global:
case tok::kw___local:
case tok::kw___constant:
case tok::kw___generic:
case tok::kw___read_only:
case tok::kw___write_only:
case tok::kw___read_write:
ParseOpenCLQualifiers(DS.getAttributes());
break;
case tok::kw___unaligned:
isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
getLangOpts());
break;
case tok::kw___uptr:
if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
if (TryKeywordIdentFallback(false))
continue;
}
LLVM_FALLTHROUGH;
case tok::kw___sptr:
case tok::kw___w64:
case tok::kw___ptr64:
case tok::kw___ptr32:
case tok::kw___cdecl:
case tok::kw___stdcall:
case tok::kw___fastcall:
case tok::kw___thiscall:
case tok::kw___regcall:
case tok::kw___vectorcall:
if (AttrReqs & AR_DeclspecAttributesParsed) {
ParseMicrosoftTypeAttributes(DS.getAttributes());
continue;
}
goto DoneWithTypeQuals;
case tok::kw___pascal:
if (AttrReqs & AR_VendorAttributesParsed) {
ParseBorlandTypeAttributes(DS.getAttributes());
continue;
}
goto DoneWithTypeQuals;
case tok::kw__Nonnull:
case tok::kw__Nullable:
case tok::kw__Nullable_result:
case tok::kw__Null_unspecified:
ParseNullabilityTypeSpecifiers(DS.getAttributes());
continue;
case tok::kw___kindof:
DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
nullptr, 0, ParsedAttr::AS_Keyword);
(void)ConsumeToken();
continue;
case tok::kw___attribute:
if (AttrReqs & AR_GNUAttributesParsedAndRejected)
Diag(Tok, diag::err_attributes_not_allowed);
if (AttrReqs & AR_GNUAttributesParsed ||
AttrReqs & AR_GNUAttributesParsedAndRejected) {
ParseGNUAttributes(DS.getAttributes());
continue; }
LLVM_FALLTHROUGH;
default:
DoneWithTypeQuals:
DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
if (EndLoc.isValid())
DS.SetRangeEnd(EndLoc);
return;
}
if (isInvalid) {
assert(PrevSpec && "Method did not return previous specifier!");
Diag(Tok, DiagID) << PrevSpec;
}
EndLoc = ConsumeToken();
}
}
void Parser::ParseDeclarator(Declarator &D) {
Actions.runWithSufficientStackSpace(D.getBeginLoc(), [&] {
ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
});
}
static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
DeclaratorContext TheContext) {
if (Kind == tok::star || Kind == tok::caret)
return true;
if (Kind == tok::kw_pipe && Lang.OpenCL &&
Lang.getOpenCLCompatibleVersion() >= 200)
return true;
if (!Lang.CPlusPlus)
return false;
if (Kind == tok::amp)
return true;
if (Kind == tok::ampamp)
return Lang.CPlusPlus11 || (TheContext != DeclaratorContext::ConversionId &&
TheContext != DeclaratorContext::CXXNew);
return false;
}
static bool isPipeDeclarator(const Declarator &D) {
const unsigned NumTypes = D.getNumTypeObjects();
for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
return true;
return false;
}
void Parser::ParseDeclaratorInternal(Declarator &D,
DirectDeclParseFunction DirectDeclParser) {
if (Diags.hasAllExtensionsSilenced())
D.setExtension();
if (getLangOpts().CPlusPlus &&
(Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
(Tok.is(tok::identifier) &&
(NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
Tok.is(tok::annot_cxxscope))) {
bool EnteringContext = D.getContext() == DeclaratorContext::File ||
D.getContext() == DeclaratorContext::Member;
CXXScopeSpec SS;
ParseOptionalCXXScopeSpecifier(SS, nullptr,
false, EnteringContext);
if (SS.isNotEmpty()) {
if (Tok.isNot(tok::star)) {
if (D.mayHaveIdentifier())
D.getCXXScopeSpec() = SS;
else
AnnotateScopeToken(SS, true);
if (DirectDeclParser)
(this->*DirectDeclParser)(D);
return;
}
if (SS.isValid()) {
checkCompoundToken(SS.getEndLoc(), tok::coloncolon,
CompoundToken::MemberPtr);
}
SourceLocation StarLoc = ConsumeToken();
D.SetRangeEnd(StarLoc);
DeclSpec DS(AttrFactory);
ParseTypeQualifierListOpt(DS);
D.ExtendWithDeclSpec(DS);
Actions.runWithSufficientStackSpace(D.getBeginLoc(), [&] {
ParseDeclaratorInternal(D, DirectDeclParser);
});
D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
SS, DS.getTypeQualifiers(), StarLoc, DS.getEndLoc()),
std::move(DS.getAttributes()),
SourceLocation());
return;
}
}
tok::TokenKind Kind = Tok.getKind();
if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclarator(D)) {
DeclSpec DS(AttrFactory);
ParseTypeQualifierListOpt(DS);
D.AddTypeInfo(
DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
std::move(DS.getAttributes()), SourceLocation());
}
if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
if (DirectDeclParser)
(this->*DirectDeclParser)(D);
return;
}
SourceLocation Loc = ConsumeToken(); D.SetRangeEnd(Loc);
if (Kind == tok::star || Kind == tok::caret) {
DeclSpec DS(AttrFactory);
unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
((D.getContext() != DeclaratorContext::CXXNew)
? AR_GNUAttributesParsed
: AR_GNUAttributesParsedAndRejected);
ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
D.ExtendWithDeclSpec(DS);
Actions.runWithSufficientStackSpace(
D.getBeginLoc(), [&] { ParseDeclaratorInternal(D, DirectDeclParser); });
if (Kind == tok::star)
D.AddTypeInfo(DeclaratorChunk::getPointer(
DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
std::move(DS.getAttributes()), SourceLocation());
else
D.AddTypeInfo(
DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
std::move(DS.getAttributes()), SourceLocation());
} else {
DeclSpec DS(AttrFactory);
if (Kind == tok::ampamp)
Diag(Loc, getLangOpts().CPlusPlus11 ?
diag::warn_cxx98_compat_rvalue_reference :
diag::ext_rvalue_reference);
ParseTypeQualifierListOpt(DS);
D.ExtendWithDeclSpec(DS);
if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Diag(DS.getConstSpecLoc(),
diag::err_invalid_reference_qualifier_application) << "const";
if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Diag(DS.getVolatileSpecLoc(),
diag::err_invalid_reference_qualifier_application) << "volatile";
if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
Diag(DS.getAtomicSpecLoc(),
diag::err_invalid_reference_qualifier_application) << "_Atomic";
}
Actions.runWithSufficientStackSpace(
D.getBeginLoc(), [&] { ParseDeclaratorInternal(D, DirectDeclParser); });
if (D.getNumTypeObjects() > 0) {
DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
if (InnerChunk.Kind == DeclaratorChunk::Reference) {
if (const IdentifierInfo *II = D.getIdentifier())
Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
<< II;
else
Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
<< "type name";
}
}
D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
Kind == tok::amp),
std::move(DS.getAttributes()), SourceLocation());
}
}
static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
SourceLocation Loc) {
if (D.getName().StartLocation.isInvalid() &&
D.getName().EndLocation.isValid())
return D.getName().EndLocation;
return Loc;
}
void Parser::ParseDirectDeclarator(Declarator &D) {
DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
D.getCXXScopeSpec().isEmpty())
return ParseDecompositionDeclarator(D);
ColonProtectionRAIIObject X(
*this, D.getContext() == DeclaratorContext::Member ||
(D.getContext() == DeclaratorContext::ForInit &&
getLangOpts().CPlusPlus11));
if (D.getCXXScopeSpec().isEmpty()) {
bool EnteringContext = D.getContext() == DeclaratorContext::File ||
D.getContext() == DeclaratorContext::Member;
ParseOptionalCXXScopeSpecifier(
D.getCXXScopeSpec(), nullptr,
false, EnteringContext);
}
if (D.getCXXScopeSpec().isValid()) {
if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
D.getCXXScopeSpec()))
DeclScopeObj.EnterDeclaratorScope();
else if (getObjCDeclContext()) {
D.SetIdentifier(nullptr, Tok.getLocation());
D.setInvalidType(true);
ConsumeToken();
goto PastIdentifier;
}
}
if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
!((D.getContext() == DeclaratorContext::Prototype ||
D.getContext() == DeclaratorContext::LambdaExprParameter ||
D.getContext() == DeclaratorContext::BlockLiteral) &&
NextToken().is(tok::r_paren) && !D.hasGroupingParens() &&
!Actions.containsUnexpandedParameterPacks(D) &&
D.getDeclSpec().getTypeSpecType() != TST_auto)) {
SourceLocation EllipsisLoc = ConsumeToken();
if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
ParseDeclarator(D);
if (EllipsisLoc.isValid())
DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
return;
} else
D.setEllipsisLoc(EllipsisLoc);
}
if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
tok::tilde)) {
bool AllowConstructorName;
bool AllowDeductionGuide;
if (D.getDeclSpec().hasTypeSpecifier()) {
AllowConstructorName = false;
AllowDeductionGuide = false;
} else if (D.getCXXScopeSpec().isSet()) {
AllowConstructorName = (D.getContext() == DeclaratorContext::File ||
D.getContext() == DeclaratorContext::Member);
AllowDeductionGuide = false;
} else {
AllowConstructorName = (D.getContext() == DeclaratorContext::Member);
AllowDeductionGuide = (D.getContext() == DeclaratorContext::File ||
D.getContext() == DeclaratorContext::Member);
}
bool HadScope = D.getCXXScopeSpec().isValid();
if (ParseUnqualifiedId(D.getCXXScopeSpec(),
nullptr,
false,
true,
true, AllowConstructorName,
AllowDeductionGuide, nullptr, D.getName()) ||
D.getCXXScopeSpec().isInvalid()) {
D.SetIdentifier(nullptr, Tok.getLocation());
D.setInvalidType(true);
} else {
if (!HadScope && D.getCXXScopeSpec().isValid() &&
Actions.ShouldEnterDeclaratorScope(getCurScope(),
D.getCXXScopeSpec()))
DeclScopeObj.EnterDeclaratorScope();
if (D.getSourceRange().getBegin().isInvalid())
D.SetRangeBegin(D.getName().getSourceRange().getBegin());
D.SetRangeEnd(D.getName().getSourceRange().getEnd());
}
goto PastIdentifier;
}
if (D.getCXXScopeSpec().isNotEmpty()) {
Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
diag::err_expected_unqualified_id)
<< 1;
D.SetIdentifier(nullptr, Tok.getLocation());
goto PastIdentifier;
}
} else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
assert(!getLangOpts().CPlusPlus &&
"There's a C++-specific check for tok::identifier above");
assert(Tok.getIdentifierInfo() && "Not an identifier?");
D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
D.SetRangeEnd(Tok.getLocation());
ConsumeToken();
goto PastIdentifier;
} else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
bool DiagnoseIdentifier = false;
if (D.hasGroupingParens())
DiagnoseIdentifier = true;
else if (D.getContext() == DeclaratorContext::TemplateArg)
DiagnoseIdentifier =
NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
else if (D.getContext() == DeclaratorContext::AliasDecl ||
D.getContext() == DeclaratorContext::AliasTemplate)
DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
else if ((D.getContext() == DeclaratorContext::TrailingReturn ||
D.getContext() == DeclaratorContext::TrailingReturnVar) &&
!isCXX11VirtSpecifier(Tok))
DiagnoseIdentifier = NextToken().isOneOf(
tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
if (DiagnoseIdentifier) {
Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
<< FixItHint::CreateRemoval(Tok.getLocation());
D.SetIdentifier(nullptr, Tok.getLocation());
ConsumeToken();
goto PastIdentifier;
}
}
if (Tok.is(tok::l_paren)) {
if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
RevertingTentativeParsingAction PA(*this);
if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
TPResult::False) {
D.SetIdentifier(nullptr, Tok.getLocation());
goto PastIdentifier;
}
}
ParseParenDeclarator(D);
if (D.getCXXScopeSpec().isSet()) {
if (!D.isInvalidType() &&
Actions.ShouldEnterDeclaratorScope(getCurScope(),
D.getCXXScopeSpec()))
DeclScopeObj.EnterDeclaratorScope();
}
} else if (D.mayOmitIdentifier()) {
D.SetIdentifier(nullptr, Tok.getLocation());
if (D.hasEllipsis() && D.hasGroupingParens())
Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
diag::ext_abstract_pack_declarator_parens);
} else {
if (Tok.getKind() == tok::annot_pragma_parser_crash)
LLVM_BUILTIN_TRAP;
if (Tok.is(tok::l_square))
return ParseMisplacedBracketDeclarator(D);
if (D.getContext() == DeclaratorContext::Member) {
if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
Tok.getIdentifierInfo() &&
Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
diag::err_expected_member_name_or_semi_objcxx_keyword)
<< Tok.getIdentifierInfo()
<< (D.getDeclSpec().isEmpty() ? SourceRange()
: D.getDeclSpec().getSourceRange());
D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
D.SetRangeEnd(Tok.getLocation());
ConsumeToken();
goto PastIdentifier;
}
Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
diag::err_expected_member_name_or_semi)
<< (D.getDeclSpec().isEmpty() ? SourceRange()
: D.getDeclSpec().getSourceRange());
} else {
if (Tok.getKind() == tok::TokenKind::kw_while) {
Diag(Tok, diag::err_while_loop_outside_of_a_function);
} else if (getLangOpts().CPlusPlus) {
if (Tok.isOneOf(tok::period, tok::arrow))
Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
else {
SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
if (Tok.isAtStartOfLine() && Loc.isValid())
Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
<< getLangOpts().CPlusPlus;
else
Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
diag::err_expected_unqualified_id)
<< getLangOpts().CPlusPlus;
}
} else {
Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
diag::err_expected_either)
<< tok::identifier << tok::l_paren;
}
}
D.SetIdentifier(nullptr, Tok.getLocation());
D.setInvalidType(true);
}
PastIdentifier:
assert(D.isPastIdentifier() &&
"Haven't past the location of the identifier yet?");
if (D.hasName() && !D.getNumTypeObjects())
MaybeParseCXX11Attributes(D);
while (true) {
if (Tok.is(tok::l_paren)) {
bool IsFunctionDeclaration = D.isFunctionDeclaratorAFunctionDeclaration();
ParseScope PrototypeScope(this,
Scope::FunctionPrototypeScope|Scope::DeclScope|
(IsFunctionDeclaration
? Scope::FunctionDeclarationScope : 0));
bool IsAmbiguous = false;
if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
TentativelyDeclaredIdentifiers.pop_back();
if (!IsFunctionDecl)
break;
}
ParsedAttributes attrs(AttrFactory);
BalancedDelimiterTracker T(*this, tok::l_paren);
T.consumeOpen();
if (IsFunctionDeclaration)
Actions.ActOnStartFunctionDeclarationDeclarator(D,
TemplateParameterDepth);
ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
if (IsFunctionDeclaration)
Actions.ActOnFinishFunctionDeclarationDeclarator(D);
PrototypeScope.Exit();
} else if (Tok.is(tok::l_square)) {
ParseBracketDeclarator(D);
} else if (Tok.is(tok::kw_requires) && D.hasGroupingParens()) {
Diag(Tok, diag::err_requires_clause_inside_parens);
ConsumeToken();
ExprResult TrailingRequiresClause = Actions.CorrectDelayedTyposInExpr(
ParseConstraintLogicalOrExpression(true));
if (TrailingRequiresClause.isUsable() && D.isFunctionDeclarator() &&
!D.hasTrailingRequiresClause())
D.setTrailingRequiresClause(TrailingRequiresClause.get());
} else {
break;
}
}
}
void Parser::ParseDecompositionDeclarator(Declarator &D) {
assert(Tok.is(tok::l_square));
if (!(NextToken().is(tok::identifier) &&
GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
!(NextToken().is(tok::r_square) &&
GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
return ParseMisplacedBracketDeclarator(D);
BalancedDelimiterTracker T(*this, tok::l_square);
T.consumeOpen();
SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
while (Tok.isNot(tok::r_square)) {
if (!Bindings.empty()) {
if (Tok.is(tok::comma))
ConsumeToken();
else {
if (Tok.is(tok::identifier)) {
SourceLocation EndLoc = getEndOfPreviousToken();
Diag(EndLoc, diag::err_expected)
<< tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
} else {
Diag(Tok, diag::err_expected_comma_or_rsquare);
}
SkipUntil(tok::r_square, tok::comma, tok::identifier,
StopAtSemi | StopBeforeMatch);
if (Tok.is(tok::comma))
ConsumeToken();
else if (Tok.isNot(tok::identifier))
break;
}
}
if (Tok.isNot(tok::identifier)) {
Diag(Tok, diag::err_expected) << tok::identifier;
break;
}
Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
ConsumeToken();
}
if (Tok.isNot(tok::r_square))
T.skipToEnd();
else {
if (Bindings.empty())
Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
T.consumeClose();
}
return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
T.getCloseLocation());
}
void Parser::ParseParenDeclarator(Declarator &D) {
BalancedDelimiterTracker T(*this, tok::l_paren);
T.consumeOpen();
assert(!D.isPastIdentifier() && "Should be called before passing identifier");
ParsedAttributes attrs(AttrFactory);
bool RequiresArg = false;
if (Tok.is(tok::kw___attribute)) {
ParseGNUAttributes(attrs);
RequiresArg = true;
}
ParseMicrosoftTypeAttributes(attrs);
if (Tok.is(tok::kw___pascal))
ParseBorlandTypeAttributes(attrs);
bool isGrouping;
if (!D.mayOmitIdentifier()) {
isGrouping = true;
} else if (Tok.is(tok::r_paren) || (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
NextToken().is(tok::r_paren)) || isDeclarationSpecifier() || isCXX11AttributeSpecifier()) { isGrouping = false;
} else {
isGrouping = true;
}
if (isGrouping) {
SourceLocation EllipsisLoc = D.getEllipsisLoc();
D.setEllipsisLoc(SourceLocation());
bool hadGroupingParens = D.hasGroupingParens();
D.setGroupingParens(true);
ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
T.consumeClose();
D.AddTypeInfo(
DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
std::move(attrs), T.getCloseLocation());
D.setGroupingParens(hadGroupingParens);
if (EllipsisLoc.isValid())
DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
return;
}
D.SetIdentifier(nullptr, Tok.getLocation());
ParseScope PrototypeScope(this,
Scope::FunctionPrototypeScope | Scope::DeclScope |
(D.isFunctionDeclaratorAFunctionDeclaration()
? Scope::FunctionDeclarationScope : 0));
ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
PrototypeScope.Exit();
}
void Parser::InitCXXThisScopeForDeclaratorIfRelevant(
const Declarator &D, const DeclSpec &DS,
llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope) {
bool IsCXX11MemberFunction =
getLangOpts().CPlusPlus11 &&
D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
(D.getContext() == DeclaratorContext::Member
? !D.getDeclSpec().isFriendSpecified()
: D.getContext() == DeclaratorContext::File &&
D.getCXXScopeSpec().isValid() &&
Actions.CurContext->isRecord());
if (!IsCXX11MemberFunction)
return;
Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
if (D.getDeclSpec().hasConstexprSpecifier() && !getLangOpts().CPlusPlus14)
Q.addConst();
if (getLangOpts().OpenCLCPlusPlus) {
for (ParsedAttr &attr : DS.getAttributes()) {
LangAS ASIdx = attr.asOpenCLLangAS();
if (ASIdx != LangAS::Default) {
Q.addAddressSpace(ASIdx);
break;
}
}
}
ThisScope.emplace(Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
IsCXX11MemberFunction);
}
void Parser::ParseFunctionDeclarator(Declarator &D,
ParsedAttributes &FirstArgAttrs,
BalancedDelimiterTracker &Tracker,
bool IsAmbiguous,
bool RequiresArg) {
assert(getCurScope()->isFunctionPrototypeScope() &&
"Should call from a Function scope");
assert(D.isPastIdentifier() && "Should not call before identifier!");
bool HasProto = false;
SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
SourceLocation EllipsisLoc;
DeclSpec DS(AttrFactory);
bool RefQualifierIsLValueRef = true;
SourceLocation RefQualifierLoc;
ExceptionSpecificationType ESpecType = EST_None;
SourceRange ESpecRange;
SmallVector<ParsedType, 2> DynamicExceptions;
SmallVector<SourceRange, 2> DynamicExceptionRanges;
ExprResult NoexceptExpr;
CachedTokens *ExceptionSpecTokens = nullptr;
ParsedAttributes FnAttrs(AttrFactory);
TypeResult TrailingReturnType;
SourceLocation TrailingReturnTypeLoc;
SourceLocation StartLoc, LocalEndLoc, EndLoc;
SourceLocation LParenLoc, RParenLoc;
LParenLoc = Tracker.getOpenLocation();
StartLoc = LParenLoc;
if (isFunctionDeclaratorIdentifierList()) {
if (RequiresArg)
Diag(Tok, diag::err_argument_required_after_attribute);
ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
Tracker.consumeClose();
RParenLoc = Tracker.getCloseLocation();
LocalEndLoc = RParenLoc;
EndLoc = RParenLoc;
MaybeParseCXX11Attributes(FnAttrs);
ProhibitAttributes(FnAttrs);
} else {
if (Tok.isNot(tok::r_paren))
ParseParameterDeclarationClause(D.getContext(), FirstArgAttrs, ParamInfo,
EllipsisLoc);
else if (RequiresArg)
Diag(Tok, diag::err_argument_required_after_attribute);
HasProto = ParamInfo.size() || getLangOpts().requiresStrictPrototypes() ||
getLangOpts().OpenCL;
Tracker.consumeClose();
RParenLoc = Tracker.getCloseLocation();
LocalEndLoc = RParenLoc;
EndLoc = RParenLoc;
if (getLangOpts().CPlusPlus) {
ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
false,
false,
llvm::function_ref<void()>([&]() {
Actions.CodeCompleteFunctionQualifiers(DS, D);
}));
if (!DS.getSourceRange().getEnd().isInvalid()) {
EndLoc = DS.getSourceRange().getEnd();
}
if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
EndLoc = RefQualifierLoc;
llvm::Optional<Sema::CXXThisScopeRAII> ThisScope;
InitCXXThisScopeForDeclaratorIfRelevant(D, DS, ThisScope);
bool Delayed = D.isFirstDeclarationOfMember() &&
D.isFunctionDeclaratorAFunctionDeclaration();
if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
GetLookAheadToken(0).is(tok::kw_noexcept) &&
GetLookAheadToken(1).is(tok::l_paren) &&
GetLookAheadToken(2).is(tok::kw_noexcept) &&
GetLookAheadToken(3).is(tok::l_paren) &&
GetLookAheadToken(4).is(tok::identifier) &&
GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
Delayed = false;
}
ESpecType = tryParseExceptionSpecification(Delayed,
ESpecRange,
DynamicExceptions,
DynamicExceptionRanges,
NoexceptExpr,
ExceptionSpecTokens);
if (ESpecType != EST_None)
EndLoc = ESpecRange.getEnd();
MaybeParseCXX11Attributes(FnAttrs);
LocalEndLoc = EndLoc;
if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
if (D.getDeclSpec().getTypeSpecType() == TST_auto)
StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
LocalEndLoc = Tok.getLocation();
SourceRange Range;
TrailingReturnType =
ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
TrailingReturnTypeLoc = Range.getBegin();
EndLoc = Range.getEnd();
}
} else if (standardAttributesAllowed()) {
MaybeParseCXX11Attributes(FnAttrs);
}
}
SmallVector<NamedDecl *, 0> DeclsInPrototype;
if (getCurScope()->isFunctionDeclarationScope() && !getLangOpts().CPlusPlus) {
for (Decl *D : getCurScope()->decls()) {
NamedDecl *ND = dyn_cast<NamedDecl>(D);
if (!ND || isa<ParmVarDecl>(ND))
continue;
DeclsInPrototype.push_back(ND);
}
}
D.AddTypeInfo(DeclaratorChunk::getFunction(
HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
ParamInfo.size(), EllipsisLoc, RParenLoc,
RefQualifierIsLValueRef, RefQualifierLoc,
SourceLocation(),
ESpecType, ESpecRange, DynamicExceptions.data(),
DynamicExceptionRanges.data(), DynamicExceptions.size(),
NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
ExceptionSpecTokens, DeclsInPrototype, StartLoc,
LocalEndLoc, D, TrailingReturnType, TrailingReturnTypeLoc,
&DS),
std::move(FnAttrs), EndLoc);
}
bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
SourceLocation &RefQualifierLoc) {
if (Tok.isOneOf(tok::amp, tok::ampamp)) {
Diag(Tok, getLangOpts().CPlusPlus11 ?
diag::warn_cxx98_compat_ref_qualifier :
diag::ext_ref_qualifier);
RefQualifierIsLValueRef = Tok.is(tok::amp);
RefQualifierLoc = ConsumeToken();
return true;
}
return false;
}
bool Parser::isFunctionDeclaratorIdentifierList() {
return !getLangOpts().requiresStrictPrototypes()
&& Tok.is(tok::identifier)
&& !TryAltiVecVectorToken()
&& (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
&& (!Tok.is(tok::eof) &&
(NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
}
void Parser::ParseFunctionDeclaratorIdentifierList(
Declarator &D,
SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
assert(!getLangOpts().requiresStrictPrototypes() &&
"Cannot parse an identifier list in C2x or C++");
if (!D.getIdentifier())
Diag(Tok, diag::ext_ident_list_in_param);
llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
do {
if (Tok.isNot(tok::identifier)) {
Diag(Tok, diag::err_expected) << tok::identifier;
SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
ParamInfo.clear();
return;
}
IdentifierInfo *ParmII = Tok.getIdentifierInfo();
if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
if (!ParamsSoFar.insert(ParmII).second) {
Diag(Tok, diag::err_param_redefinition) << ParmII;
} else {
ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
Tok.getLocation(),
nullptr));
}
ConsumeToken();
} while (TryConsumeToken(tok::comma));
}
void Parser::ParseParameterDeclarationClause(
DeclaratorContext DeclaratorCtx, ParsedAttributes &FirstArgAttrs,
SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
SourceLocation &EllipsisLoc) {
if (getCurScope()->getFunctionPrototypeDepth() - 1 >
ParmVarDecl::getMaxFunctionScopeDepth()) {
Diag(Tok.getLocation(), diag::err_function_scope_depth_exceeded)
<< ParmVarDecl::getMaxFunctionScopeDepth();
cutOffParsing();
return;
}
do {
if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
break;
DeclSpec DS(AttrFactory);
ParsedAttributes ArgDeclAttrs(AttrFactory);
ParsedAttributes ArgDeclSpecAttrs(AttrFactory);
if (FirstArgAttrs.Range.isValid()) {
ArgDeclSpecAttrs.takeAllFrom(FirstArgAttrs);
} else {
MaybeParseCXX11Attributes(ArgDeclAttrs);
MaybeParseMicrosoftAttributes(ArgDeclSpecAttrs);
}
SourceLocation DSStart = Tok.getLocation();
ParseDeclarationSpecifiers(DS);
DS.takeAttributesFrom(ArgDeclSpecAttrs);
Declarator ParmDeclarator(DS, ArgDeclAttrs,
DeclaratorCtx == DeclaratorContext::RequiresExpr
? DeclaratorContext::RequiresExpr
: DeclaratorCtx == DeclaratorContext::LambdaExpr
? DeclaratorContext::LambdaExprParameter
: DeclaratorContext::Prototype);
ParseDeclarator(ParmDeclarator);
MaybeParseGNUAttributes(ParmDeclarator);
MaybeParseHLSLSemantics(DS.getAttributes());
if (Tok.is(tok::kw_requires)) {
Diag(Tok,
diag::err_requires_clause_on_declarator_not_declaring_a_function);
ConsumeToken();
Actions.CorrectDelayedTyposInExpr(
ParseConstraintLogicalOrExpression(true));
}
IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
std::unique_ptr<CachedTokens> DefArgToks;
if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
ParmDeclarator.getNumTypeObjects() == 0) {
Diag(DSStart, diag::err_missing_param);
} else {
if (Tok.is(tok::ellipsis) &&
(NextToken().isNot(tok::r_paren) ||
(!ParmDeclarator.getEllipsisLoc().isValid() &&
!Actions.isUnexpandedParameterPackPermitted())) &&
Actions.containsUnexpandedParameterPacks(ParmDeclarator))
DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
if (!ParmDeclarator.isInvalidType() && !ParmDeclarator.hasName() &&
Tok.isNot(tok::raw_identifier) && !Tok.isAnnotation() &&
Tok.getIdentifierInfo() &&
Tok.getIdentifierInfo()->isKeyword(getLangOpts())) {
Diag(Tok, diag::err_keyword_as_parameter) << PP.getSpelling(Tok);
ConsumeToken();
}
Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
if (Tok.is(tok::equal)) {
SourceLocation EqualLoc = Tok.getLocation();
if (DeclaratorCtx == DeclaratorContext::Member) {
DefArgToks.reset(new CachedTokens);
SourceLocation ArgStartLoc = NextToken().getLocation();
if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
DefArgToks.reset();
Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
} else {
Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
ArgStartLoc);
}
} else {
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 {
if (Tok.is(tok::l_paren) && NextToken().is(tok::l_brace)) {
Diag(Tok, diag::err_stmt_expr_in_default_arg) << 0;
Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
SkipUntil(tok::comma, StopBeforeMatch);
continue;
}
DefArgResult = ParseAssignmentExpression();
}
DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
if (DefArgResult.isInvalid()) {
Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
} else {
Actions.ActOnParamDefaultArgument(Param, EqualLoc,
DefArgResult.get());
}
}
}
ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
ParmDeclarator.getIdentifierLoc(),
Param, std::move(DefArgToks)));
}
if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
if (!getLangOpts().CPlusPlus) {
Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
<< FixItHint::CreateInsertion(EllipsisLoc, ", ");
} else if (ParmDeclarator.getEllipsisLoc().isValid() ||
Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
<< ParmEllipsis.isValid() << ParmEllipsis;
if (ParmEllipsis.isValid()) {
Diag(ParmEllipsis,
diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
} else {
Diag(ParmDeclarator.getIdentifierLoc(),
diag::note_misplaced_ellipsis_vararg_add_ellipsis)
<< FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
"...")
<< !ParmDeclarator.hasName();
}
Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
<< FixItHint::CreateInsertion(EllipsisLoc, ", ");
}
break;
}
} while (TryConsumeToken(tok::comma));
}
void Parser::ParseBracketDeclarator(Declarator &D) {
if (CheckProhibitedCXX11Attribute())
return;
BalancedDelimiterTracker T(*this, tok::l_square);
T.consumeOpen();
if (Tok.getKind() == tok::r_square) {
T.consumeClose();
ParsedAttributes attrs(AttrFactory);
MaybeParseCXX11Attributes(attrs);
D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
T.getOpenLocation(),
T.getCloseLocation()),
std::move(attrs), T.getCloseLocation());
return;
} else if (Tok.getKind() == tok::numeric_constant &&
GetLookAheadToken(1).is(tok::r_square)) {
ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
ConsumeToken();
T.consumeClose();
ParsedAttributes attrs(AttrFactory);
MaybeParseCXX11Attributes(attrs);
D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
T.getOpenLocation(),
T.getCloseLocation()),
std::move(attrs), T.getCloseLocation());
return;
} else if (Tok.getKind() == tok::code_completion) {
cutOffParsing();
Actions.CodeCompleteBracketDeclarator(getCurScope());
return;
}
SourceLocation StaticLoc;
TryConsumeToken(tok::kw_static, StaticLoc);
DeclSpec DS(AttrFactory);
ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
if (!StaticLoc.isValid())
TryConsumeToken(tok::kw_static, StaticLoc);
bool isStar = false;
ExprResult NumElements;
if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
ConsumeToken();
if (StaticLoc.isValid()) {
Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
StaticLoc = SourceLocation(); }
isStar = true;
} else if (Tok.isNot(tok::r_square)) {
if (getLangOpts().CPlusPlus) {
NumElements = ParseConstantExpression();
} else {
EnterExpressionEvaluationContext Unevaluated(
Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
NumElements =
Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
}
} else {
if (StaticLoc.isValid()) {
Diag(StaticLoc, diag::err_unspecified_size_with_static);
StaticLoc = SourceLocation(); }
}
if (NumElements.isInvalid()) {
D.setInvalidType(true);
SkipUntil(tok::r_square, StopAtSemi);
return;
}
T.consumeClose();
MaybeParseCXX11Attributes(DS.getAttributes());
D.AddTypeInfo(
DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
isStar, NumElements.get(), T.getOpenLocation(),
T.getCloseLocation()),
std::move(DS.getAttributes()), T.getCloseLocation());
}
void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
assert(Tok.is(tok::l_square) && "Missing opening bracket");
assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
SourceLocation StartBracketLoc = Tok.getLocation();
Declarator TempDeclarator(D.getDeclSpec(), ParsedAttributesView::none(),
D.getContext());
while (Tok.is(tok::l_square)) {
ParseBracketDeclarator(TempDeclarator);
}
if (Tok.is(tok::semi))
D.getName().EndLocation = StartBracketLoc;
SourceLocation SuggestParenLoc = Tok.getLocation();
ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
if (TempDeclarator.getNumTypeObjects() == 0)
return;
bool NeedParens = false;
if (D.getNumTypeObjects() != 0) {
switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
case DeclaratorChunk::Pointer:
case DeclaratorChunk::Reference:
case DeclaratorChunk::BlockPointer:
case DeclaratorChunk::MemberPointer:
case DeclaratorChunk::Pipe:
NeedParens = true;
break;
case DeclaratorChunk::Array:
case DeclaratorChunk::Function:
case DeclaratorChunk::Paren:
break;
}
}
if (NeedParens) {
SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
SourceLocation());
}
for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
D.AddTypeInfo(Chunk, SourceLocation());
}
if (!D.getIdentifier() && !NeedParens)
return;
SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
if (NeedParens) {
Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
<< getLangOpts().CPlusPlus
<< FixItHint::CreateInsertion(SuggestParenLoc, "(")
<< FixItHint::CreateInsertion(EndLoc, ")")
<< FixItHint::CreateInsertionFromRange(
EndLoc, CharSourceRange(BracketRange, true))
<< FixItHint::CreateRemoval(BracketRange);
} else {
Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
<< getLangOpts().CPlusPlus
<< FixItHint::CreateInsertionFromRange(
EndLoc, CharSourceRange(BracketRange, true))
<< FixItHint::CreateRemoval(BracketRange);
}
}
void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
Token OpTok = Tok;
SourceLocation StartLoc = ConsumeToken();
const bool hasParens = Tok.is(tok::l_paren);
EnterExpressionEvaluationContext Unevaluated(
Actions, Sema::ExpressionEvaluationContext::Unevaluated,
Sema::ReuseLambdaContextDecl);
bool isCastExpr;
ParsedType CastTy;
SourceRange CastRange;
ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
if (hasParens)
DS.setTypeofParensRange(CastRange);
if (CastRange.getEnd().isInvalid())
DS.SetRangeEnd(Tok.getLocation());
else
DS.SetRangeEnd(CastRange.getEnd());
if (isCastExpr) {
if (!CastTy) {
DS.SetTypeSpecError();
return;
}
const char *PrevSpec = nullptr;
unsigned DiagID;
if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
DiagID, CastTy,
Actions.getASTContext().getPrintingPolicy()))
Diag(StartLoc, DiagID) << PrevSpec;
return;
}
if (Operand.isInvalid()) {
DS.SetTypeSpecError();
return;
}
Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
if (Operand.isInvalid()) {
DS.SetTypeSpecError();
return;
}
const char *PrevSpec = nullptr;
unsigned DiagID;
if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
DiagID, Operand.get(),
Actions.getASTContext().getPrintingPolicy()))
Diag(StartLoc, DiagID) << PrevSpec;
}
void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
"Not an atomic specifier");
SourceLocation StartLoc = ConsumeToken();
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.consumeOpen())
return;
TypeResult Result = ParseTypeName();
if (Result.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
T.consumeClose();
if (T.getCloseLocation().isInvalid())
return;
DS.setTypeofParensRange(T.getRange());
DS.SetRangeEnd(T.getCloseLocation());
const char *PrevSpec = nullptr;
unsigned DiagID;
if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
DiagID, Result.get(),
Actions.getASTContext().getPrintingPolicy()))
Diag(StartLoc, DiagID) << PrevSpec;
}
bool Parser::TryAltiVecVectorTokenOutOfLine() {
Token Next = NextToken();
switch (Next.getKind()) {
default: return false;
case tok::kw_short:
case tok::kw_long:
case tok::kw_signed:
case tok::kw_unsigned:
case tok::kw_void:
case tok::kw_char:
case tok::kw_int:
case tok::kw_float:
case tok::kw_double:
case tok::kw_bool:
case tok::kw__Bool:
case tok::kw___bool:
case tok::kw___pixel:
Tok.setKind(tok::kw___vector);
return true;
case tok::identifier:
if (Next.getIdentifierInfo() == Ident_pixel) {
Tok.setKind(tok::kw___vector);
return true;
}
if (Next.getIdentifierInfo() == Ident_bool ||
Next.getIdentifierInfo() == Ident_Bool) {
Tok.setKind(tok::kw___vector);
return true;
}
return false;
}
}
bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID,
bool &isInvalid) {
const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
if (Tok.getIdentifierInfo() == Ident_vector) {
Token Next = NextToken();
switch (Next.getKind()) {
case tok::kw_short:
case tok::kw_long:
case tok::kw_signed:
case tok::kw_unsigned:
case tok::kw_void:
case tok::kw_char:
case tok::kw_int:
case tok::kw_float:
case tok::kw_double:
case tok::kw_bool:
case tok::kw__Bool:
case tok::kw___bool:
case tok::kw___pixel:
isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
return true;
case tok::identifier:
if (Next.getIdentifierInfo() == Ident_pixel) {
isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
return true;
}
if (Next.getIdentifierInfo() == Ident_bool ||
Next.getIdentifierInfo() == Ident_Bool) {
isInvalid =
DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
return true;
}
break;
default:
break;
}
} else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
DS.isTypeAltiVecVector()) {
isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
return true;
} else if ((Tok.getIdentifierInfo() == Ident_bool) &&
DS.isTypeAltiVecVector()) {
isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
return true;
}
return false;
}
void Parser::DiagnoseBitIntUse(const Token &Tok) {
assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
"expected either an _ExtInt or _BitInt token!");
SourceLocation Loc = Tok.getLocation();
if (Tok.is(tok::kw__ExtInt)) {
Diag(Loc, diag::warn_ext_int_deprecated)
<< FixItHint::CreateReplacement(Loc, "_BitInt");
} else {
if (getLangOpts().C2x)
Diag(Loc, diag::warn_c17_compat_bit_int);
else
Diag(Loc, diag::ext_bit_int) << getLangOpts().CPlusPlus;
}
}