ParseDecl.cpp revision 280031
1168404Spjd//===--- ParseDecl.cpp - Declaration Parsing ------------------------------===// 2168404Spjd// 3168404Spjd// The LLVM Compiler Infrastructure 4168404Spjd// 5168404Spjd// This file is distributed under the University of Illinois Open Source 6168404Spjd// License. See LICENSE.TXT for details. 7168404Spjd// 8168404Spjd//===----------------------------------------------------------------------===// 9168404Spjd// 10168404Spjd// This file implements the Declaration portions of the Parser interfaces. 11168404Spjd// 12168404Spjd//===----------------------------------------------------------------------===// 13168404Spjd 14168404Spjd#include "clang/Parse/Parser.h" 15168404Spjd#include "RAIIObjectsForParser.h" 16168404Spjd#include "clang/AST/ASTContext.h" 17168404Spjd#include "clang/AST/DeclTemplate.h" 18168404Spjd#include "clang/Basic/AddressSpaces.h" 19168404Spjd#include "clang/Basic/Attributes.h" 20168404Spjd#include "clang/Basic/CharInfo.h" 21168404Spjd#include "clang/Basic/TargetInfo.h" 22168404Spjd#include "clang/Parse/ParseDiagnostic.h" 23168404Spjd#include "clang/Sema/Lookup.h" 24168404Spjd#include "clang/Sema/ParsedTemplate.h" 25168404Spjd#include "clang/Sema/PrettyDeclStackTrace.h" 26168404Spjd#include "clang/Sema/Scope.h" 27168404Spjd#include "llvm/ADT/SmallSet.h" 28168404Spjd#include "llvm/ADT/SmallString.h" 29168404Spjd#include "llvm/ADT/StringSwitch.h" 30169303Spjdusing namespace clang; 31168404Spjd 32168404Spjd//===----------------------------------------------------------------------===// 33168404Spjd// C99 6.7: Declarations. 34168404Spjd//===----------------------------------------------------------------------===// 35168404Spjd 36169303Spjd/// ParseTypeName 37168404Spjd/// type-name: [C99 6.7.6] 38168404Spjd/// specifier-qualifier-list abstract-declarator[opt] 39168404Spjd/// 40168404Spjd/// Called type-id in C++. 41168404SpjdTypeResult Parser::ParseTypeName(SourceRange *Range, 42168404Spjd Declarator::TheContext Context, 43168404Spjd AccessSpecifier AS, 44168404Spjd Decl **OwnedType, 45168404Spjd ParsedAttributes *Attrs) { 46168404Spjd DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context); 47168404Spjd if (DSC == DSC_normal) 48168404Spjd DSC = DSC_type_specifier; 49168404Spjd 50168404Spjd // Parse the common declaration-specifiers piece. 51168404Spjd DeclSpec DS(AttrFactory); 52168404Spjd if (Attrs) 53168404Spjd DS.addAttributes(Attrs->getList()); 54168404Spjd ParseSpecifierQualifierList(DS, AS, DSC); 55168404Spjd if (OwnedType) 56168404Spjd *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr; 57168404Spjd 58168404Spjd // Parse the abstract-declarator, if present. 59168404Spjd Declarator DeclaratorInfo(DS, Context); 60168404Spjd ParseDeclarator(DeclaratorInfo); 61168404Spjd if (Range) 62168404Spjd *Range = DeclaratorInfo.getSourceRange(); 63168404Spjd 64168404Spjd if (DeclaratorInfo.isInvalidType()) 65168404Spjd return true; 66168404Spjd 67168404Spjd return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 68168404Spjd} 69168404Spjd 70168404Spjd 71168404Spjd/// isAttributeLateParsed - Return true if the attribute has arguments that 72168404Spjd/// require late parsing. 73168404Spjdstatic bool isAttributeLateParsed(const IdentifierInfo &II) { 74168404Spjd#define CLANG_ATTR_LATE_PARSED_LIST 75168404Spjd return llvm::StringSwitch<bool>(II.getName()) 76168404Spjd#include "clang/Parse/AttrParserStringSwitches.inc" 77168404Spjd .Default(false); 78168404Spjd#undef CLANG_ATTR_LATE_PARSED_LIST 79168404Spjd} 80168404Spjd 81168404Spjd/// ParseGNUAttributes - Parse a non-empty attributes list. 82168404Spjd/// 83168404Spjd/// [GNU] attributes: 84168404Spjd/// attribute 85168404Spjd/// attributes attribute 86168404Spjd/// 87168404Spjd/// [GNU] attribute: 88169303Spjd/// '__attribute__' '(' '(' attribute-list ')' ')' 89169303Spjd/// 90169087Spjd/// [GNU] attribute-list: 91168404Spjd/// attrib 92168404Spjd/// attribute_list ',' attrib 93168404Spjd/// 94168404Spjd/// [GNU] attrib: 95168404Spjd/// empty 96169087Spjd/// attrib-name 97168404Spjd/// attrib-name '(' identifier ')' 98168404Spjd/// attrib-name '(' identifier ',' nonempty-expr-list ')' 99185029Spjd/// attrib-name '(' argument-expression-list [C99 6.5.2] ')' 100185029Spjd/// 101185029Spjd/// [GNU] attrib-name: 102168404Spjd/// identifier 103168404Spjd/// typespec 104168404Spjd/// typequal 105168404Spjd/// storageclass 106168404Spjd/// 107168404Spjd/// Whether an attribute takes an 'identifier' is determined by the 108168404Spjd/// attrib-name. GCC's behavior here is not worth imitating: 109168404Spjd/// 110168404Spjd/// * In C mode, if the attribute argument list starts with an identifier 111168404Spjd/// followed by a ',' or an ')', and the identifier doesn't resolve to 112168404Spjd/// a type, it is parsed as an identifier. If the attribute actually 113168404Spjd/// wanted an expression, it's out of luck (but it turns out that no 114168404Spjd/// attributes work that way, because C constant expressions are very 115169303Spjd/// limited). 116169303Spjd/// * In C++ mode, if the attribute argument list starts with an identifier, 117169303Spjd/// and the attribute *wants* an identifier, it is parsed as an identifier. 118169303Spjd/// At block scope, any additional tokens between the identifier and the 119169303Spjd/// ',' or ')' are ignored, otherwise they produce a parse error. 120168404Spjd/// 121168404Spjd/// We follow the C++ model, but don't allow junk after the identifier. 122168404Spjdvoid Parser::ParseGNUAttributes(ParsedAttributes &attrs, 123168404Spjd SourceLocation *endLoc, 124168404Spjd LateParsedAttrList *LateAttrs, 125168404Spjd Declarator *D) { 126168404Spjd assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!"); 127168404Spjd 128168404Spjd while (Tok.is(tok::kw___attribute)) { 129168404Spjd ConsumeToken(); 130168404Spjd if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 131168404Spjd "attribute")) { 132168404Spjd SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ; 133168404Spjd return; 134168404Spjd } 135168404Spjd if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) { 136168404Spjd SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ; 137168404Spjd return; 138168404Spjd } 139168404Spjd // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") )) 140168404Spjd while (true) { 141168404Spjd // Allow empty/non-empty attributes. ((__vector_size__(16),,,,)) 142168404Spjd if (TryConsumeToken(tok::comma)) 143168404Spjd continue; 144168404Spjd 145168404Spjd // Expect an identifier or declaration specifier (const, int, etc.) 146168404Spjd if (Tok.isAnnotation()) 147168404Spjd break; 148168404Spjd IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 149168404Spjd if (!AttrName) 150168404Spjd break; 151168404Spjd 152168404Spjd SourceLocation AttrNameLoc = ConsumeToken(); 153168404Spjd 154168404Spjd if (Tok.isNot(tok::l_paren)) { 155168404Spjd attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 156168404Spjd AttributeList::AS_GNU); 157168404Spjd continue; 158168404Spjd } 159168404Spjd 160168404Spjd // Handle "parameterized" attributes 161168404Spjd if (!LateAttrs || !isAttributeLateParsed(*AttrName)) { 162168404Spjd ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr, 163168404Spjd SourceLocation(), AttributeList::AS_GNU, D); 164168404Spjd continue; 165168404Spjd } 166168404Spjd 167168404Spjd // Handle attributes with arguments that require late parsing. 168168404Spjd LateParsedAttribute *LA = 169168404Spjd new LateParsedAttribute(this, *AttrName, AttrNameLoc); 170168404Spjd LateAttrs->push_back(LA); 171168404Spjd 172168404Spjd // Attributes in a class are parsed at the end of the class, along 173168404Spjd // with other late-parsed declarations. 174168404Spjd if (!ClassStack.empty() && !LateAttrs->parseSoon()) 175168404Spjd getCurrentClass().LateParsedDeclarations.push_back(LA); 176168404Spjd 177168404Spjd // consume everything up to and including the matching right parens 178168404Spjd ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false); 179168404Spjd 180168404Spjd Token Eof; 181168404Spjd Eof.startToken(); 182168404Spjd Eof.setLocation(Tok.getLocation()); 183168404Spjd LA->Toks.push_back(Eof); 184168404Spjd } 185168404Spjd 186168404Spjd if (ExpectAndConsume(tok::r_paren)) 187168404Spjd SkipUntil(tok::r_paren, StopAtSemi); 188168404Spjd SourceLocation Loc = Tok.getLocation(); 189168404Spjd if (ExpectAndConsume(tok::r_paren)) 190168404Spjd SkipUntil(tok::r_paren, StopAtSemi); 191168404Spjd if (endLoc) 192168404Spjd *endLoc = Loc; 193168404Spjd } 194168404Spjd} 195168404Spjd 196168404Spjd/// \brief Normalizes an attribute name by dropping prefixed and suffixed __. 197168404Spjdstatic StringRef normalizeAttrName(StringRef Name) { 198168404Spjd if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__")) 199168404Spjd Name = Name.drop_front(2).drop_back(2); 200168404Spjd return Name; 201168404Spjd} 202168404Spjd 203168404Spjd/// \brief Determine whether the given attribute has an identifier argument. 204168404Spjdstatic bool attributeHasIdentifierArg(const IdentifierInfo &II) { 205168404Spjd#define CLANG_ATTR_IDENTIFIER_ARG_LIST 206172836Sjulian return llvm::StringSwitch<bool>(normalizeAttrName(II.getName())) 207168404Spjd#include "clang/Parse/AttrParserStringSwitches.inc" 208168404Spjd .Default(false); 209168404Spjd#undef CLANG_ATTR_IDENTIFIER_ARG_LIST 210168404Spjd} 211168404Spjd 212168404Spjd/// \brief Determine whether the given attribute parses a type argument. 213168404Spjdstatic bool attributeIsTypeArgAttr(const IdentifierInfo &II) { 214168404Spjd#define CLANG_ATTR_TYPE_ARG_LIST 215168404Spjd return llvm::StringSwitch<bool>(normalizeAttrName(II.getName())) 216168404Spjd#include "clang/Parse/AttrParserStringSwitches.inc" 217168404Spjd .Default(false); 218168404Spjd#undef CLANG_ATTR_TYPE_ARG_LIST 219168404Spjd} 220168404Spjd 221168404Spjd/// \brief Determine whether the given attribute requires parsing its arguments 222168404Spjd/// in an unevaluated context or not. 223168404Spjdstatic bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) { 224168404Spjd#define CLANG_ATTR_ARG_CONTEXT_LIST 225168404Spjd return llvm::StringSwitch<bool>(normalizeAttrName(II.getName())) 226168404Spjd#include "clang/Parse/AttrParserStringSwitches.inc" 227168404Spjd .Default(false); 228185029Spjd#undef CLANG_ATTR_ARG_CONTEXT_LIST 229168404Spjd} 230168404Spjd 231168404SpjdIdentifierLoc *Parser::ParseIdentifierLoc() { 232185029Spjd assert(Tok.is(tok::identifier) && "expected an identifier"); 233185029Spjd IdentifierLoc *IL = IdentifierLoc::create(Actions.Context, 234185029Spjd Tok.getLocation(), 235185029Spjd Tok.getIdentifierInfo()); 236185029Spjd ConsumeToken(); 237185029Spjd return IL; 238185029Spjd} 239185029Spjd 240185029Spjdvoid Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName, 241185029Spjd SourceLocation AttrNameLoc, 242185029Spjd ParsedAttributes &Attrs, 243185029Spjd SourceLocation *EndLoc, 244185029Spjd IdentifierInfo *ScopeName, 245185029Spjd SourceLocation ScopeLoc, 246185029Spjd AttributeList::Syntax Syntax) { 247185029Spjd BalancedDelimiterTracker Parens(*this, tok::l_paren); 248185029Spjd Parens.consumeOpen(); 249185029Spjd 250185029Spjd TypeResult T; 251185029Spjd if (Tok.isNot(tok::r_paren)) 252185029Spjd T = ParseTypeName(); 253185029Spjd 254185029Spjd if (Parens.consumeClose()) 255185029Spjd return; 256185029Spjd 257185029Spjd if (T.isInvalid()) 258185029Spjd return; 259185029Spjd 260185029Spjd if (T.isUsable()) 261185029Spjd Attrs.addNewTypeAttr(&AttrName, 262185029Spjd SourceRange(AttrNameLoc, Parens.getCloseLocation()), 263185029Spjd ScopeName, ScopeLoc, T.get(), Syntax); 264185029Spjd else 265185029Spjd Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()), 266185029Spjd ScopeName, ScopeLoc, nullptr, 0, Syntax); 267185029Spjd} 268185029Spjd 269185029Spjdunsigned Parser::ParseAttributeArgsCommon( 270185029Spjd IdentifierInfo *AttrName, SourceLocation AttrNameLoc, 271185029Spjd ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, 272185029Spjd SourceLocation ScopeLoc, AttributeList::Syntax Syntax) { 273185029Spjd // Ignore the left paren location for now. 274185029Spjd ConsumeParen(); 275185029Spjd 276185029Spjd ArgsVector ArgExprs; 277185029Spjd if (Tok.is(tok::identifier)) { 278185029Spjd // If this attribute wants an 'identifier' argument, make it so. 279185029Spjd bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName); 280185029Spjd AttributeList::Kind AttrKind = 281185029Spjd AttributeList::getKind(AttrName, ScopeName, Syntax); 282185174Spjd 283185174Spjd // If we don't know how to parse this attribute, but this is the only 284185029Spjd // token in this argument, assume it's meant to be an identifier. 285185029Spjd if (AttrKind == AttributeList::UnknownAttribute || 286185029Spjd AttrKind == AttributeList::IgnoredAttribute) { 287185029Spjd const Token &Next = NextToken(); 288185029Spjd IsIdentifierArg = Next.is(tok::r_paren) || Next.is(tok::comma); 289185029Spjd } 290185029Spjd 291185174Spjd if (IsIdentifierArg) 292185029Spjd ArgExprs.push_back(ParseIdentifierLoc()); 293185029Spjd } 294185029Spjd 295185029Spjd if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) { 296185029Spjd // Eat the comma. 297185029Spjd if (!ArgExprs.empty()) 298185029Spjd ConsumeToken(); 299185029Spjd 300185029Spjd // Parse the non-empty comma-separated list of expressions. 301185029Spjd do { 302185029Spjd std::unique_ptr<EnterExpressionEvaluationContext> Unevaluated; 303185029Spjd if (attributeParsedArgsUnevaluated(*AttrName)) 304185174Spjd Unevaluated.reset( 305185029Spjd new EnterExpressionEvaluationContext(Actions, Sema::Unevaluated)); 306185029Spjd 307185029Spjd ExprResult ArgExpr( 308185174Spjd Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression())); 309185029Spjd if (ArgExpr.isInvalid()) { 310185029Spjd SkipUntil(tok::r_paren, StopAtSemi); 311185029Spjd return 0; 312185029Spjd } 313185029Spjd ArgExprs.push_back(ArgExpr.get()); 314185029Spjd // Eat the comma, move to the next argument 315185029Spjd } while (TryConsumeToken(tok::comma)); 316185029Spjd } 317185029Spjd 318185029Spjd SourceLocation RParen = Tok.getLocation(); 319185029Spjd if (!ExpectAndConsume(tok::r_paren)) { 320185029Spjd SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc; 321185029Spjd Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc, 322185029Spjd ArgExprs.data(), ArgExprs.size(), Syntax); 323185029Spjd } 324185029Spjd 325185174Spjd if (EndLoc) 326185174Spjd *EndLoc = RParen; 327185029Spjd 328185029Spjd return static_cast<unsigned>(ArgExprs.size()); 329185029Spjd} 330185174Spjd 331185174Spjd/// Parse the arguments to a parameterized GNU attribute or 332185174Spjd/// a C++11 attribute in "gnu" namespace. 333185029Spjdvoid Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName, 334185029Spjd SourceLocation AttrNameLoc, 335169303Spjd ParsedAttributes &Attrs, 336185174Spjd SourceLocation *EndLoc, 337169303Spjd IdentifierInfo *ScopeName, 338169303Spjd SourceLocation ScopeLoc, 339169303Spjd AttributeList::Syntax Syntax, 340169303Spjd Declarator *D) { 341169303Spjd 342169303Spjd assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); 343169303Spjd 344169303Spjd AttributeList::Kind AttrKind = 345169303Spjd AttributeList::getKind(AttrName, ScopeName, Syntax); 346169303Spjd 347169303Spjd if (AttrKind == AttributeList::AT_Availability) { 348169303Spjd ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, 349169303Spjd ScopeLoc, Syntax); 350185174Spjd return; 351169303Spjd } else if (AttrKind == AttributeList::AT_ObjCBridgeRelated) { 352169303Spjd ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, 353169303Spjd ScopeName, ScopeLoc, Syntax); 354169303Spjd return; 355169303Spjd } else if (AttrKind == AttributeList::AT_TypeTagForDatatype) { 356169303Spjd ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, 357185174Spjd ScopeName, ScopeLoc, Syntax); 358169303Spjd return; 359169303Spjd } else if (attributeIsTypeArgAttr(*AttrName)) { 360169303Spjd ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, 361169303Spjd ScopeLoc, Syntax); 362169303Spjd return; 363169303Spjd } 364169303Spjd 365169303Spjd // These may refer to the function arguments, but need to be parsed early to 366169303Spjd // participate in determining whether it's a redeclaration. 367169303Spjd std::unique_ptr<ParseScope> PrototypeScope; 368169303Spjd if (AttrName->isStr("enable_if") && D && D->isFunctionDeclarator()) { 369169303Spjd DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo(); 370169303Spjd PrototypeScope.reset(new ParseScope(this, Scope::FunctionPrototypeScope | 371169303Spjd Scope::FunctionDeclarationScope | 372169303Spjd Scope::DeclScope)); 373169303Spjd for (unsigned i = 0; i != FTI.NumParams; ++i) { 374169303Spjd ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 375169303Spjd Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param); 376169303Spjd } 377169303Spjd } 378169303Spjd 379169303Spjd ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, 380169303Spjd ScopeLoc, Syntax); 381169303Spjd} 382169303Spjd 383185174Spjdbool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, 384169303Spjd SourceLocation AttrNameLoc, 385169303Spjd ParsedAttributes &Attrs) { 386169303Spjd // If the attribute isn't known, we will not attempt to parse any 387185174Spjd // arguments. 388169303Spjd if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName, 389169303Spjd getTargetInfo().getTriple(), getLangOpts())) { 390169303Spjd // Eat the left paren, then skip to the ending right paren. 391169303Spjd ConsumeParen(); 392169303Spjd SkipUntil(tok::r_paren); 393169303Spjd return false; 394169303Spjd } 395169303Spjd 396169303Spjd SourceLocation OpenParenLoc = Tok.getLocation(); 397169303Spjd 398169303Spjd if (AttrName->getName() == "property") { 399169303Spjd // The property declspec is more complex in that it can take one or two 400169303Spjd // assignment expressions as a parameter, but the lhs of the assignment 401169303Spjd // must be named get or put. 402169303Spjd 403169303Spjd BalancedDelimiterTracker T(*this, tok::l_paren); 404169303Spjd T.expectAndConsume(diag::err_expected_lparen_after, 405169303Spjd AttrName->getNameStart(), tok::r_paren); 406185174Spjd 407169303Spjd enum AccessorKind { 408169303Spjd AK_Invalid = -1, 409169303Spjd AK_Put = 0, 410169303Spjd AK_Get = 1 // indices into AccessorNames 411169303Spjd }; 412185174Spjd IdentifierInfo *AccessorNames[] = {nullptr, nullptr}; 413169303Spjd bool HasInvalidAccessor = false; 414185174Spjd 415169303Spjd // Parse the accessor specifications. 416169303Spjd while (true) { 417169303Spjd // Stop if this doesn't look like an accessor spec. 418169303Spjd if (!Tok.is(tok::identifier)) { 419169303Spjd // If the user wrote a completely empty list, use a special diagnostic. 420185029Spjd if (Tok.is(tok::r_paren) && !HasInvalidAccessor && 421185174Spjd AccessorNames[AK_Put] == nullptr && 422168404Spjd AccessorNames[AK_Get] == nullptr) { 423185174Spjd Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter); 424185174Spjd break; 425185174Spjd } 426185174Spjd 427185174Spjd Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor); 428185174Spjd break; 429185174Spjd } 430185174Spjd 431185174Spjd AccessorKind Kind; 432185174Spjd SourceLocation KindLoc = Tok.getLocation(); 433185174Spjd StringRef KindStr = Tok.getIdentifierInfo()->getName(); 434185174Spjd if (KindStr == "get") { 435185174Spjd Kind = AK_Get; 436185174Spjd } else if (KindStr == "put") { 437185174Spjd Kind = AK_Put; 438185174Spjd 439185174Spjd // Recover from the common mistake of using 'set' instead of 'put'. 440185174Spjd } else if (KindStr == "set") { 441185174Spjd Diag(KindLoc, diag::err_ms_property_has_set_accessor) 442185174Spjd << FixItHint::CreateReplacement(KindLoc, "put"); 443185174Spjd Kind = AK_Put; 444185174Spjd 445185174Spjd // Handle the mistake of forgetting the accessor kind by skipping 446185174Spjd // this accessor. 447185174Spjd } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) { 448185174Spjd Diag(KindLoc, diag::err_ms_property_missing_accessor_kind); 449185174Spjd ConsumeToken(); 450168404Spjd HasInvalidAccessor = true; 451168404Spjd goto next_property_accessor; 452185174Spjd 453168404Spjd // Otherwise, complain about the unknown accessor kind. 454169303Spjd } else { 455168404Spjd Diag(KindLoc, diag::err_ms_property_unknown_accessor); 456168404Spjd HasInvalidAccessor = true; 457169303Spjd Kind = AK_Invalid; 458169303Spjd 459169303Spjd // Try to keep parsing unless it doesn't look like an accessor spec. 460185174Spjd if (!NextToken().is(tok::equal)) 461169303Spjd break; 462185174Spjd } 463169303Spjd 464185174Spjd // Consume the identifier. 465169303Spjd ConsumeToken(); 466169303Spjd 467185174Spjd // Consume the '='. 468185174Spjd if (!TryConsumeToken(tok::equal)) { 469185174Spjd Diag(Tok.getLocation(), diag::err_ms_property_expected_equal) 470185174Spjd << KindStr; 471185174Spjd break; 472185029Spjd } 473185174Spjd 474169303Spjd // Expect the method name. 475168404Spjd if (!Tok.is(tok::identifier)) { 476168404Spjd Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name); 477169303Spjd break; 478185029Spjd } 479185029Spjd 480169303Spjd if (Kind == AK_Invalid) { 481185029Spjd // Just drop invalid accessors. 482185029Spjd } else if (AccessorNames[Kind] != nullptr) { 483185029Spjd // Complain about the repeated accessor, ignore it, and keep parsing. 484185029Spjd Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr; 485185029Spjd } else { 486185029Spjd AccessorNames[Kind] = Tok.getIdentifierInfo(); 487185029Spjd } 488185029Spjd ConsumeToken(); 489185029Spjd 490185029Spjd next_property_accessor: 491185029Spjd // Keep processing accessors until we run out. 492185029Spjd if (TryConsumeToken(tok::comma)) 493185029Spjd continue; 494185029Spjd 495185029Spjd // If we run into the ')', stop without consuming it. 496185029Spjd if (Tok.is(tok::r_paren)) 497185029Spjd break; 498185029Spjd 499185029Spjd Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen); 500185029Spjd break; 501185174Spjd } 502185029Spjd 503185029Spjd // Only add the property attribute if it was well-formed. 504185174Spjd if (!HasInvalidAccessor) 505185029Spjd Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(), 506185174Spjd AccessorNames[AK_Get], AccessorNames[AK_Put], 507185029Spjd AttributeList::AS_Declspec); 508185174Spjd T.skipToEnd(); 509169303Spjd return !HasInvalidAccessor; 510185174Spjd } 511185174Spjd 512185174Spjd unsigned NumArgs = 513185174Spjd ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr, 514185174Spjd SourceLocation(), AttributeList::AS_Declspec); 515185174Spjd 516185174Spjd // If this attribute's args were parsed, and it was expected to have 517185174Spjd // arguments but none were provided, emit a diagnostic. 518185174Spjd const AttributeList *Attr = Attrs.getList(); 519168404Spjd if (Attr && Attr->getMaxArgs() && !NumArgs) { 520168404Spjd Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName; 521185029Spjd return false; 522185029Spjd } 523185029Spjd return true; 524185029Spjd} 525185029Spjd 526185029Spjd/// [MS] decl-specifier: 527185029Spjd/// __declspec ( extended-decl-modifier-seq ) 528185029Spjd/// 529185029Spjd/// [MS] extended-decl-modifier-seq: 530185029Spjd/// extended-decl-modifier[opt] 531169303Spjd/// extended-decl-modifier extended-decl-modifier-seq 532168404Spjdvoid Parser::ParseMicrosoftDeclSpec(ParsedAttributes &Attrs) { 533185029Spjd assert(Tok.is(tok::kw___declspec) && "Not a declspec!"); 534185029Spjd 535185029Spjd ConsumeToken(); 536168404Spjd BalancedDelimiterTracker T(*this, tok::l_paren); 537168404Spjd if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec", 538168404Spjd tok::r_paren)) 539168404Spjd return; 540168404Spjd 541168404Spjd // An empty declspec is perfectly legal and should not warn. Additionally, 542168404Spjd // you can specify multiple attributes per declspec. 543168404Spjd while (Tok.isNot(tok::r_paren)) { 544168404Spjd // Attribute not present. 545168404Spjd if (TryConsumeToken(tok::comma)) 546168404Spjd continue; 547168404Spjd 548168404Spjd // We expect either a well-known identifier or a generic string. Anything 549168404Spjd // else is a malformed declspec. 550168404Spjd bool IsString = Tok.getKind() == tok::string_literal ? true : false; 551168404Spjd if (!IsString && Tok.getKind() != tok::identifier && 552168404Spjd Tok.getKind() != tok::kw_restrict) { 553168404Spjd Diag(Tok, diag::err_ms_declspec_type); 554168404Spjd T.skipToEnd(); 555168404Spjd return; 556168404Spjd } 557168404Spjd 558168404Spjd IdentifierInfo *AttrName; 559168404Spjd SourceLocation AttrNameLoc; 560168404Spjd if (IsString) { 561168404Spjd SmallString<8> StrBuffer; 562168404Spjd bool Invalid = false; 563168404Spjd StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid); 564168404Spjd if (Invalid) { 565168404Spjd T.skipToEnd(); 566168404Spjd return; 567168404Spjd } 568168404Spjd AttrName = PP.getIdentifierInfo(Str); 569168404Spjd AttrNameLoc = ConsumeStringToken(); 570168404Spjd } else { 571168404Spjd AttrName = Tok.getIdentifierInfo(); 572168404Spjd AttrNameLoc = ConsumeToken(); 573168404Spjd } 574168404Spjd 575168404Spjd bool AttrHandled = false; 576168404Spjd 577168404Spjd // Parse attribute arguments. 578185029Spjd if (Tok.is(tok::l_paren)) 579185029Spjd AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs); 580185029Spjd else if (AttrName->getName() == "property") 581168404Spjd // The property attribute must have an argument list. 582168404Spjd Diag(Tok.getLocation(), diag::err_expected_lparen_after) 583168404Spjd << AttrName->getName(); 584168404Spjd 585168404Spjd if (!AttrHandled) 586168404Spjd Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 587185029Spjd AttributeList::AS_Declspec); 588168404Spjd } 589168404Spjd T.consumeClose(); 590168404Spjd} 591168404Spjd 592168404Spjdvoid Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) { 593168404Spjd // Treat these like attributes 594168404Spjd while (true) { 595168404Spjd switch (Tok.getKind()) { 596168404Spjd case tok::kw___fastcall: 597168404Spjd case tok::kw___stdcall: 598168404Spjd case tok::kw___thiscall: 599168404Spjd case tok::kw___cdecl: 600168404Spjd case tok::kw___vectorcall: 601168404Spjd case tok::kw___ptr64: 602168404Spjd case tok::kw___w64: 603168404Spjd case tok::kw___ptr32: 604168404Spjd case tok::kw___unaligned: 605185029Spjd case tok::kw___sptr: 606168404Spjd case tok::kw___uptr: { 607185029Spjd IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 608168404Spjd SourceLocation AttrNameLoc = ConsumeToken(); 609168404Spjd attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 610168404Spjd AttributeList::AS_Keyword); 611168404Spjd break; 612168404Spjd } 613185029Spjd default: 614185029Spjd return; 615185029Spjd } 616185029Spjd } 617168404Spjd} 618168404Spjd 619168404Spjdvoid Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() { 620168404Spjd SourceLocation StartLoc = Tok.getLocation(); 621168404Spjd SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes(); 622168404Spjd 623168404Spjd if (EndLoc.isValid()) { 624168404Spjd SourceRange Range(StartLoc, EndLoc); 625168404Spjd Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range; 626168404Spjd } 627185029Spjd} 628168404Spjd 629168404SpjdSourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() { 630185029Spjd SourceLocation EndLoc; 631185029Spjd 632185029Spjd while (true) { 633168404Spjd switch (Tok.getKind()) { 634168404Spjd case tok::kw_const: 635168404Spjd case tok::kw_volatile: 636168404Spjd case tok::kw___fastcall: 637168404Spjd case tok::kw___stdcall: 638168404Spjd case tok::kw___thiscall: 639168404Spjd case tok::kw___cdecl: 640168404Spjd case tok::kw___vectorcall: 641168404Spjd case tok::kw___ptr32: 642168404Spjd case tok::kw___ptr64: 643168404Spjd case tok::kw___w64: 644168404Spjd case tok::kw___unaligned: 645168404Spjd case tok::kw___sptr: 646168404Spjd case tok::kw___uptr: 647168404Spjd EndLoc = ConsumeToken(); 648168404Spjd break; 649168404Spjd default: 650168404Spjd return EndLoc; 651168404Spjd } 652168404Spjd } 653168404Spjd} 654185029Spjd 655185029Spjdvoid Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) { 656168404Spjd // Treat these like attributes 657168404Spjd while (Tok.is(tok::kw___pascal)) { 658168404Spjd IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 659168404Spjd SourceLocation AttrNameLoc = ConsumeToken(); 660168404Spjd attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 661168404Spjd AttributeList::AS_Keyword); 662185029Spjd } 663185029Spjd} 664185029Spjd 665185029Spjdvoid Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) { 666185029Spjd // Treat these like attributes 667185029Spjd while (Tok.is(tok::kw___kernel)) { 668185029Spjd IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 669185029Spjd SourceLocation AttrNameLoc = ConsumeToken(); 670185029Spjd attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 671168404Spjd AttributeList::AS_Keyword); 672185029Spjd } 673185029Spjd} 674185029Spjd 675168404Spjdvoid Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) { 676185029Spjd IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 677185029Spjd SourceLocation AttrNameLoc = Tok.getLocation(); 678185029Spjd Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 679185029Spjd AttributeList::AS_Keyword); 680185029Spjd} 681168404Spjd 682168404Spjdstatic bool VersionNumberSeparator(const char Separator) { 683168404Spjd return (Separator == '.' || Separator == '_'); 684168404Spjd} 685168404Spjd 686168404Spjd/// \brief Parse a version number. 687168404Spjd/// 688168404Spjd/// version: 689168404Spjd/// simple-integer 690168404Spjd/// simple-integer ',' simple-integer 691168404Spjd/// simple-integer ',' simple-integer ',' simple-integer 692168404SpjdVersionTuple Parser::ParseVersionTuple(SourceRange &Range) { 693 Range = Tok.getLocation(); 694 695 if (!Tok.is(tok::numeric_constant)) { 696 Diag(Tok, diag::err_expected_version); 697 SkipUntil(tok::comma, tok::r_paren, 698 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); 699 return VersionTuple(); 700 } 701 702 // Parse the major (and possibly minor and subminor) versions, which 703 // are stored in the numeric constant. We utilize a quirk of the 704 // lexer, which is that it handles something like 1.2.3 as a single 705 // numeric constant, rather than two separate tokens. 706 SmallString<512> Buffer; 707 Buffer.resize(Tok.getLength()+1); 708 const char *ThisTokBegin = &Buffer[0]; 709 710 // Get the spelling of the token, which eliminates trigraphs, etc. 711 bool Invalid = false; 712 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid); 713 if (Invalid) 714 return VersionTuple(); 715 716 // Parse the major version. 717 unsigned AfterMajor = 0; 718 unsigned Major = 0; 719 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) { 720 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0'; 721 ++AfterMajor; 722 } 723 724 if (AfterMajor == 0) { 725 Diag(Tok, diag::err_expected_version); 726 SkipUntil(tok::comma, tok::r_paren, 727 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); 728 return VersionTuple(); 729 } 730 731 if (AfterMajor == ActualLength) { 732 ConsumeToken(); 733 734 // We only had a single version component. 735 if (Major == 0) { 736 Diag(Tok, diag::err_zero_version); 737 return VersionTuple(); 738 } 739 740 return VersionTuple(Major); 741 } 742 743 const char AfterMajorSeparator = ThisTokBegin[AfterMajor]; 744 if (!VersionNumberSeparator(AfterMajorSeparator) 745 || (AfterMajor + 1 == ActualLength)) { 746 Diag(Tok, diag::err_expected_version); 747 SkipUntil(tok::comma, tok::r_paren, 748 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); 749 return VersionTuple(); 750 } 751 752 // Parse the minor version. 753 unsigned AfterMinor = AfterMajor + 1; 754 unsigned Minor = 0; 755 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) { 756 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0'; 757 ++AfterMinor; 758 } 759 760 if (AfterMinor == ActualLength) { 761 ConsumeToken(); 762 763 // We had major.minor. 764 if (Major == 0 && Minor == 0) { 765 Diag(Tok, diag::err_zero_version); 766 return VersionTuple(); 767 } 768 769 return VersionTuple(Major, Minor, (AfterMajorSeparator == '_')); 770 } 771 772 const char AfterMinorSeparator = ThisTokBegin[AfterMinor]; 773 // If what follows is not a '.' or '_', we have a problem. 774 if (!VersionNumberSeparator(AfterMinorSeparator)) { 775 Diag(Tok, diag::err_expected_version); 776 SkipUntil(tok::comma, tok::r_paren, 777 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); 778 return VersionTuple(); 779 } 780 781 // Warn if separators, be it '.' or '_', do not match. 782 if (AfterMajorSeparator != AfterMinorSeparator) 783 Diag(Tok, diag::warn_expected_consistent_version_separator); 784 785 // Parse the subminor version. 786 unsigned AfterSubminor = AfterMinor + 1; 787 unsigned Subminor = 0; 788 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) { 789 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0'; 790 ++AfterSubminor; 791 } 792 793 if (AfterSubminor != ActualLength) { 794 Diag(Tok, diag::err_expected_version); 795 SkipUntil(tok::comma, tok::r_paren, 796 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); 797 return VersionTuple(); 798 } 799 ConsumeToken(); 800 return VersionTuple(Major, Minor, Subminor, (AfterMajorSeparator == '_')); 801} 802 803/// \brief Parse the contents of the "availability" attribute. 804/// 805/// availability-attribute: 806/// 'availability' '(' platform ',' version-arg-list, opt-message')' 807/// 808/// platform: 809/// identifier 810/// 811/// version-arg-list: 812/// version-arg 813/// version-arg ',' version-arg-list 814/// 815/// version-arg: 816/// 'introduced' '=' version 817/// 'deprecated' '=' version 818/// 'obsoleted' = version 819/// 'unavailable' 820/// opt-message: 821/// 'message' '=' <string> 822void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability, 823 SourceLocation AvailabilityLoc, 824 ParsedAttributes &attrs, 825 SourceLocation *endLoc, 826 IdentifierInfo *ScopeName, 827 SourceLocation ScopeLoc, 828 AttributeList::Syntax Syntax) { 829 enum { Introduced, Deprecated, Obsoleted, Unknown }; 830 AvailabilityChange Changes[Unknown]; 831 ExprResult MessageExpr; 832 833 // Opening '('. 834 BalancedDelimiterTracker T(*this, tok::l_paren); 835 if (T.consumeOpen()) { 836 Diag(Tok, diag::err_expected) << tok::l_paren; 837 return; 838 } 839 840 // Parse the platform name, 841 if (Tok.isNot(tok::identifier)) { 842 Diag(Tok, diag::err_availability_expected_platform); 843 SkipUntil(tok::r_paren, StopAtSemi); 844 return; 845 } 846 IdentifierLoc *Platform = ParseIdentifierLoc(); 847 848 // Parse the ',' following the platform name. 849 if (ExpectAndConsume(tok::comma)) { 850 SkipUntil(tok::r_paren, StopAtSemi); 851 return; 852 } 853 854 // If we haven't grabbed the pointers for the identifiers 855 // "introduced", "deprecated", and "obsoleted", do so now. 856 if (!Ident_introduced) { 857 Ident_introduced = PP.getIdentifierInfo("introduced"); 858 Ident_deprecated = PP.getIdentifierInfo("deprecated"); 859 Ident_obsoleted = PP.getIdentifierInfo("obsoleted"); 860 Ident_unavailable = PP.getIdentifierInfo("unavailable"); 861 Ident_message = PP.getIdentifierInfo("message"); 862 } 863 864 // Parse the set of introductions/deprecations/removals. 865 SourceLocation UnavailableLoc; 866 do { 867 if (Tok.isNot(tok::identifier)) { 868 Diag(Tok, diag::err_availability_expected_change); 869 SkipUntil(tok::r_paren, StopAtSemi); 870 return; 871 } 872 IdentifierInfo *Keyword = Tok.getIdentifierInfo(); 873 SourceLocation KeywordLoc = ConsumeToken(); 874 875 if (Keyword == Ident_unavailable) { 876 if (UnavailableLoc.isValid()) { 877 Diag(KeywordLoc, diag::err_availability_redundant) 878 << Keyword << SourceRange(UnavailableLoc); 879 } 880 UnavailableLoc = KeywordLoc; 881 continue; 882 } 883 884 if (Tok.isNot(tok::equal)) { 885 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal; 886 SkipUntil(tok::r_paren, StopAtSemi); 887 return; 888 } 889 ConsumeToken(); 890 if (Keyword == Ident_message) { 891 if (Tok.isNot(tok::string_literal)) { 892 Diag(Tok, diag::err_expected_string_literal) 893 << /*Source='availability attribute'*/2; 894 SkipUntil(tok::r_paren, StopAtSemi); 895 return; 896 } 897 MessageExpr = ParseStringLiteralExpression(); 898 // Also reject wide string literals. 899 if (StringLiteral *MessageStringLiteral = 900 cast_or_null<StringLiteral>(MessageExpr.get())) { 901 if (MessageStringLiteral->getCharByteWidth() != 1) { 902 Diag(MessageStringLiteral->getSourceRange().getBegin(), 903 diag::err_expected_string_literal) 904 << /*Source='availability attribute'*/ 2; 905 SkipUntil(tok::r_paren, StopAtSemi); 906 return; 907 } 908 } 909 break; 910 } 911 912 // Special handling of 'NA' only when applied to introduced or 913 // deprecated. 914 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) && 915 Tok.is(tok::identifier)) { 916 IdentifierInfo *NA = Tok.getIdentifierInfo(); 917 if (NA->getName() == "NA") { 918 ConsumeToken(); 919 if (Keyword == Ident_introduced) 920 UnavailableLoc = KeywordLoc; 921 continue; 922 } 923 } 924 925 SourceRange VersionRange; 926 VersionTuple Version = ParseVersionTuple(VersionRange); 927 928 if (Version.empty()) { 929 SkipUntil(tok::r_paren, StopAtSemi); 930 return; 931 } 932 933 unsigned Index; 934 if (Keyword == Ident_introduced) 935 Index = Introduced; 936 else if (Keyword == Ident_deprecated) 937 Index = Deprecated; 938 else if (Keyword == Ident_obsoleted) 939 Index = Obsoleted; 940 else 941 Index = Unknown; 942 943 if (Index < Unknown) { 944 if (!Changes[Index].KeywordLoc.isInvalid()) { 945 Diag(KeywordLoc, diag::err_availability_redundant) 946 << Keyword 947 << SourceRange(Changes[Index].KeywordLoc, 948 Changes[Index].VersionRange.getEnd()); 949 } 950 951 Changes[Index].KeywordLoc = KeywordLoc; 952 Changes[Index].Version = Version; 953 Changes[Index].VersionRange = VersionRange; 954 } else { 955 Diag(KeywordLoc, diag::err_availability_unknown_change) 956 << Keyword << VersionRange; 957 } 958 959 } while (TryConsumeToken(tok::comma)); 960 961 // Closing ')'. 962 if (T.consumeClose()) 963 return; 964 965 if (endLoc) 966 *endLoc = T.getCloseLocation(); 967 968 // The 'unavailable' availability cannot be combined with any other 969 // availability changes. Make sure that hasn't happened. 970 if (UnavailableLoc.isValid()) { 971 bool Complained = false; 972 for (unsigned Index = Introduced; Index != Unknown; ++Index) { 973 if (Changes[Index].KeywordLoc.isValid()) { 974 if (!Complained) { 975 Diag(UnavailableLoc, diag::warn_availability_and_unavailable) 976 << SourceRange(Changes[Index].KeywordLoc, 977 Changes[Index].VersionRange.getEnd()); 978 Complained = true; 979 } 980 981 // Clear out the availability. 982 Changes[Index] = AvailabilityChange(); 983 } 984 } 985 } 986 987 // Record this attribute 988 attrs.addNew(&Availability, 989 SourceRange(AvailabilityLoc, T.getCloseLocation()), 990 ScopeName, ScopeLoc, 991 Platform, 992 Changes[Introduced], 993 Changes[Deprecated], 994 Changes[Obsoleted], 995 UnavailableLoc, MessageExpr.get(), 996 Syntax); 997} 998 999/// \brief Parse the contents of the "objc_bridge_related" attribute. 1000/// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')' 1001/// related_class: 1002/// Identifier 1003/// 1004/// opt-class_method: 1005/// Identifier: | <empty> 1006/// 1007/// opt-instance_method: 1008/// Identifier | <empty> 1009/// 1010void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, 1011 SourceLocation ObjCBridgeRelatedLoc, 1012 ParsedAttributes &attrs, 1013 SourceLocation *endLoc, 1014 IdentifierInfo *ScopeName, 1015 SourceLocation ScopeLoc, 1016 AttributeList::Syntax Syntax) { 1017 // Opening '('. 1018 BalancedDelimiterTracker T(*this, tok::l_paren); 1019 if (T.consumeOpen()) { 1020 Diag(Tok, diag::err_expected) << tok::l_paren; 1021 return; 1022 } 1023 1024 // Parse the related class name. 1025 if (Tok.isNot(tok::identifier)) { 1026 Diag(Tok, diag::err_objcbridge_related_expected_related_class); 1027 SkipUntil(tok::r_paren, StopAtSemi); 1028 return; 1029 } 1030 IdentifierLoc *RelatedClass = ParseIdentifierLoc(); 1031 if (ExpectAndConsume(tok::comma)) { 1032 SkipUntil(tok::r_paren, StopAtSemi); 1033 return; 1034 } 1035 1036 // Parse optional class method name. 1037 IdentifierLoc *ClassMethod = nullptr; 1038 if (Tok.is(tok::identifier)) { 1039 ClassMethod = ParseIdentifierLoc(); 1040 if (!TryConsumeToken(tok::colon)) { 1041 Diag(Tok, diag::err_objcbridge_related_selector_name); 1042 SkipUntil(tok::r_paren, StopAtSemi); 1043 return; 1044 } 1045 } 1046 if (!TryConsumeToken(tok::comma)) { 1047 if (Tok.is(tok::colon)) 1048 Diag(Tok, diag::err_objcbridge_related_selector_name); 1049 else 1050 Diag(Tok, diag::err_expected) << tok::comma; 1051 SkipUntil(tok::r_paren, StopAtSemi); 1052 return; 1053 } 1054 1055 // Parse optional instance method name. 1056 IdentifierLoc *InstanceMethod = nullptr; 1057 if (Tok.is(tok::identifier)) 1058 InstanceMethod = ParseIdentifierLoc(); 1059 else if (Tok.isNot(tok::r_paren)) { 1060 Diag(Tok, diag::err_expected) << tok::r_paren; 1061 SkipUntil(tok::r_paren, StopAtSemi); 1062 return; 1063 } 1064 1065 // Closing ')'. 1066 if (T.consumeClose()) 1067 return; 1068 1069 if (endLoc) 1070 *endLoc = T.getCloseLocation(); 1071 1072 // Record this attribute 1073 attrs.addNew(&ObjCBridgeRelated, 1074 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()), 1075 ScopeName, ScopeLoc, 1076 RelatedClass, 1077 ClassMethod, 1078 InstanceMethod, 1079 Syntax); 1080} 1081 1082// Late Parsed Attributes: 1083// See other examples of late parsing in lib/Parse/ParseCXXInlineMethods 1084 1085void Parser::LateParsedDeclaration::ParseLexedAttributes() {} 1086 1087void Parser::LateParsedClass::ParseLexedAttributes() { 1088 Self->ParseLexedAttributes(*Class); 1089} 1090 1091void Parser::LateParsedAttribute::ParseLexedAttributes() { 1092 Self->ParseLexedAttribute(*this, true, false); 1093} 1094 1095/// Wrapper class which calls ParseLexedAttribute, after setting up the 1096/// scope appropriately. 1097void Parser::ParseLexedAttributes(ParsingClass &Class) { 1098 // Deal with templates 1099 // FIXME: Test cases to make sure this does the right thing for templates. 1100 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope; 1101 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, 1102 HasTemplateScope); 1103 if (HasTemplateScope) 1104 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate); 1105 1106 // Set or update the scope flags. 1107 bool AlreadyHasClassScope = Class.TopLevelClass; 1108 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope; 1109 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope); 1110 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope); 1111 1112 // Enter the scope of nested classes 1113 if (!AlreadyHasClassScope) 1114 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), 1115 Class.TagOrTemplate); 1116 if (!Class.LateParsedDeclarations.empty()) { 1117 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){ 1118 Class.LateParsedDeclarations[i]->ParseLexedAttributes(); 1119 } 1120 } 1121 1122 if (!AlreadyHasClassScope) 1123 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), 1124 Class.TagOrTemplate); 1125} 1126 1127 1128/// \brief Parse all attributes in LAs, and attach them to Decl D. 1129void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, 1130 bool EnterScope, bool OnDefinition) { 1131 assert(LAs.parseSoon() && 1132 "Attribute list should be marked for immediate parsing."); 1133 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) { 1134 if (D) 1135 LAs[i]->addDecl(D); 1136 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition); 1137 delete LAs[i]; 1138 } 1139 LAs.clear(); 1140} 1141 1142 1143/// \brief Finish parsing an attribute for which parsing was delayed. 1144/// This will be called at the end of parsing a class declaration 1145/// for each LateParsedAttribute. We consume the saved tokens and 1146/// create an attribute with the arguments filled in. We add this 1147/// to the Attribute list for the decl. 1148void Parser::ParseLexedAttribute(LateParsedAttribute &LA, 1149 bool EnterScope, bool OnDefinition) { 1150 // Create a fake EOF so that attribute parsing won't go off the end of the 1151 // attribute. 1152 Token AttrEnd; 1153 AttrEnd.startToken(); 1154 AttrEnd.setKind(tok::eof); 1155 AttrEnd.setLocation(Tok.getLocation()); 1156 AttrEnd.setEofData(LA.Toks.data()); 1157 LA.Toks.push_back(AttrEnd); 1158 1159 // Append the current token at the end of the new token stream so that it 1160 // doesn't get lost. 1161 LA.Toks.push_back(Tok); 1162 PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false); 1163 // Consume the previously pushed token. 1164 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 1165 1166 ParsedAttributes Attrs(AttrFactory); 1167 SourceLocation endLoc; 1168 1169 if (LA.Decls.size() > 0) { 1170 Decl *D = LA.Decls[0]; 1171 NamedDecl *ND = dyn_cast<NamedDecl>(D); 1172 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext()); 1173 1174 // Allow 'this' within late-parsed attributes. 1175 Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0, 1176 ND && ND->isCXXInstanceMember()); 1177 1178 if (LA.Decls.size() == 1) { 1179 // If the Decl is templatized, add template parameters to scope. 1180 bool HasTemplateScope = EnterScope && D->isTemplateDecl(); 1181 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope); 1182 if (HasTemplateScope) 1183 Actions.ActOnReenterTemplateScope(Actions.CurScope, D); 1184 1185 // If the Decl is on a function, add function parameters to the scope. 1186 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate(); 1187 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunScope); 1188 if (HasFunScope) 1189 Actions.ActOnReenterFunctionContext(Actions.CurScope, D); 1190 1191 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc, 1192 nullptr, SourceLocation(), AttributeList::AS_GNU, 1193 nullptr); 1194 1195 if (HasFunScope) { 1196 Actions.ActOnExitFunctionContext(); 1197 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver 1198 } 1199 if (HasTemplateScope) { 1200 TempScope.Exit(); 1201 } 1202 } else { 1203 // If there are multiple decls, then the decl cannot be within the 1204 // function scope. 1205 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc, 1206 nullptr, SourceLocation(), AttributeList::AS_GNU, 1207 nullptr); 1208 } 1209 } else { 1210 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName(); 1211 } 1212 1213 const AttributeList *AL = Attrs.getList(); 1214 if (OnDefinition && AL && !AL->isCXX11Attribute() && 1215 AL->isKnownToGCC()) 1216 Diag(Tok, diag::warn_attribute_on_function_definition) 1217 << &LA.AttrName; 1218 1219 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i) 1220 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs); 1221 1222 // Due to a parsing error, we either went over the cached tokens or 1223 // there are still cached tokens left, so we skip the leftover tokens. 1224 while (Tok.isNot(tok::eof)) 1225 ConsumeAnyToken(); 1226 1227 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData()) 1228 ConsumeAnyToken(); 1229} 1230 1231void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, 1232 SourceLocation AttrNameLoc, 1233 ParsedAttributes &Attrs, 1234 SourceLocation *EndLoc, 1235 IdentifierInfo *ScopeName, 1236 SourceLocation ScopeLoc, 1237 AttributeList::Syntax Syntax) { 1238 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); 1239 1240 BalancedDelimiterTracker T(*this, tok::l_paren); 1241 T.consumeOpen(); 1242 1243 if (Tok.isNot(tok::identifier)) { 1244 Diag(Tok, diag::err_expected) << tok::identifier; 1245 T.skipToEnd(); 1246 return; 1247 } 1248 IdentifierLoc *ArgumentKind = ParseIdentifierLoc(); 1249 1250 if (ExpectAndConsume(tok::comma)) { 1251 T.skipToEnd(); 1252 return; 1253 } 1254 1255 SourceRange MatchingCTypeRange; 1256 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange); 1257 if (MatchingCType.isInvalid()) { 1258 T.skipToEnd(); 1259 return; 1260 } 1261 1262 bool LayoutCompatible = false; 1263 bool MustBeNull = false; 1264 while (TryConsumeToken(tok::comma)) { 1265 if (Tok.isNot(tok::identifier)) { 1266 Diag(Tok, diag::err_expected) << tok::identifier; 1267 T.skipToEnd(); 1268 return; 1269 } 1270 IdentifierInfo *Flag = Tok.getIdentifierInfo(); 1271 if (Flag->isStr("layout_compatible")) 1272 LayoutCompatible = true; 1273 else if (Flag->isStr("must_be_null")) 1274 MustBeNull = true; 1275 else { 1276 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag; 1277 T.skipToEnd(); 1278 return; 1279 } 1280 ConsumeToken(); // consume flag 1281 } 1282 1283 if (!T.consumeClose()) { 1284 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc, 1285 ArgumentKind, MatchingCType.get(), 1286 LayoutCompatible, MustBeNull, Syntax); 1287 } 1288 1289 if (EndLoc) 1290 *EndLoc = T.getCloseLocation(); 1291} 1292 1293/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets 1294/// of a C++11 attribute-specifier in a location where an attribute is not 1295/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this 1296/// situation. 1297/// 1298/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if 1299/// this doesn't appear to actually be an attribute-specifier, and the caller 1300/// should try to parse it. 1301bool Parser::DiagnoseProhibitedCXX11Attribute() { 1302 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)); 1303 1304 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) { 1305 case CAK_NotAttributeSpecifier: 1306 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute. 1307 return false; 1308 1309 case CAK_InvalidAttributeSpecifier: 1310 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute); 1311 return false; 1312 1313 case CAK_AttributeSpecifier: 1314 // Parse and discard the attributes. 1315 SourceLocation BeginLoc = ConsumeBracket(); 1316 ConsumeBracket(); 1317 SkipUntil(tok::r_square); 1318 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied"); 1319 SourceLocation EndLoc = ConsumeBracket(); 1320 Diag(BeginLoc, diag::err_attributes_not_allowed) 1321 << SourceRange(BeginLoc, EndLoc); 1322 return true; 1323 } 1324 llvm_unreachable("All cases handled above."); 1325} 1326 1327/// \brief We have found the opening square brackets of a C++11 1328/// attribute-specifier in a location where an attribute is not permitted, but 1329/// we know where the attributes ought to be written. Parse them anyway, and 1330/// provide a fixit moving them to the right place. 1331void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, 1332 SourceLocation CorrectLocation) { 1333 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) || 1334 Tok.is(tok::kw_alignas)); 1335 1336 // Consume the attributes. 1337 SourceLocation Loc = Tok.getLocation(); 1338 ParseCXX11Attributes(Attrs); 1339 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true); 1340 1341 Diag(Loc, diag::err_attributes_not_allowed) 1342 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange) 1343 << FixItHint::CreateRemoval(AttrRange); 1344} 1345 1346void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) { 1347 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed) 1348 << attrs.Range; 1349} 1350 1351void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs) { 1352 AttributeList *AttrList = attrs.getList(); 1353 while (AttrList) { 1354 if (AttrList->isCXX11Attribute()) { 1355 Diag(AttrList->getLoc(), diag::err_attribute_not_type_attr) 1356 << AttrList->getName(); 1357 AttrList->setInvalid(); 1358 } 1359 AttrList = AttrList->getNext(); 1360 } 1361} 1362 1363/// ParseDeclaration - Parse a full 'declaration', which consists of 1364/// declaration-specifiers, some number of declarators, and a semicolon. 1365/// 'Context' should be a Declarator::TheContext value. This returns the 1366/// location of the semicolon in DeclEnd. 1367/// 1368/// declaration: [C99 6.7] 1369/// block-declaration -> 1370/// simple-declaration 1371/// others [FIXME] 1372/// [C++] template-declaration 1373/// [C++] namespace-definition 1374/// [C++] using-directive 1375/// [C++] using-declaration 1376/// [C++11/C11] static_assert-declaration 1377/// others... [FIXME] 1378/// 1379Parser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context, 1380 SourceLocation &DeclEnd, 1381 ParsedAttributesWithRange &attrs) { 1382 ParenBraceBracketBalancer BalancerRAIIObj(*this); 1383 // Must temporarily exit the objective-c container scope for 1384 // parsing c none objective-c decls. 1385 ObjCDeclContextSwitch ObjCDC(*this); 1386 1387 Decl *SingleDecl = nullptr; 1388 Decl *OwnedType = nullptr; 1389 switch (Tok.getKind()) { 1390 case tok::kw_template: 1391 case tok::kw_export: 1392 ProhibitAttributes(attrs); 1393 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd); 1394 break; 1395 case tok::kw_inline: 1396 // Could be the start of an inline namespace. Allowed as an ext in C++03. 1397 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) { 1398 ProhibitAttributes(attrs); 1399 SourceLocation InlineLoc = ConsumeToken(); 1400 SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc); 1401 break; 1402 } 1403 return ParseSimpleDeclaration(Context, DeclEnd, attrs, 1404 true); 1405 case tok::kw_namespace: 1406 ProhibitAttributes(attrs); 1407 SingleDecl = ParseNamespace(Context, DeclEnd); 1408 break; 1409 case tok::kw_using: 1410 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(), 1411 DeclEnd, attrs, &OwnedType); 1412 break; 1413 case tok::kw_static_assert: 1414 case tok::kw__Static_assert: 1415 ProhibitAttributes(attrs); 1416 SingleDecl = ParseStaticAssertDeclaration(DeclEnd); 1417 break; 1418 default: 1419 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true); 1420 } 1421 1422 // This routine returns a DeclGroup, if the thing we parsed only contains a 1423 // single decl, convert it now. Alias declarations can also declare a type; 1424 // include that too if it is present. 1425 return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType); 1426} 1427 1428/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl] 1429/// declaration-specifiers init-declarator-list[opt] ';' 1430/// [C++11] attribute-specifier-seq decl-specifier-seq[opt] 1431/// init-declarator-list ';' 1432///[C90/C++]init-declarator-list ';' [TODO] 1433/// [OMP] threadprivate-directive [TODO] 1434/// 1435/// for-range-declaration: [C++11 6.5p1: stmt.ranged] 1436/// attribute-specifier-seq[opt] type-specifier-seq declarator 1437/// 1438/// If RequireSemi is false, this does not check for a ';' at the end of the 1439/// declaration. If it is true, it checks for and eats it. 1440/// 1441/// If FRI is non-null, we might be parsing a for-range-declaration instead 1442/// of a simple-declaration. If we find that we are, we also parse the 1443/// for-range-initializer, and place it here. 1444Parser::DeclGroupPtrTy 1445Parser::ParseSimpleDeclaration(unsigned Context, 1446 SourceLocation &DeclEnd, 1447 ParsedAttributesWithRange &Attrs, 1448 bool RequireSemi, ForRangeInit *FRI) { 1449 // Parse the common declaration-specifiers piece. 1450 ParsingDeclSpec DS(*this); 1451 1452 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context); 1453 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext); 1454 1455 // If we had a free-standing type definition with a missing semicolon, we 1456 // may get this far before the problem becomes obvious. 1457 if (DS.hasTagDefinition() && 1458 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext)) 1459 return DeclGroupPtrTy(); 1460 1461 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" 1462 // declaration-specifiers init-declarator-list[opt] ';' 1463 if (Tok.is(tok::semi)) { 1464 ProhibitAttributes(Attrs); 1465 DeclEnd = Tok.getLocation(); 1466 if (RequireSemi) ConsumeToken(); 1467 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, 1468 DS); 1469 DS.complete(TheDecl); 1470 return Actions.ConvertDeclToDeclGroup(TheDecl); 1471 } 1472 1473 DS.takeAttributesFrom(Attrs); 1474 return ParseDeclGroup(DS, Context, &DeclEnd, FRI); 1475} 1476 1477/// Returns true if this might be the start of a declarator, or a common typo 1478/// for a declarator. 1479bool Parser::MightBeDeclarator(unsigned Context) { 1480 switch (Tok.getKind()) { 1481 case tok::annot_cxxscope: 1482 case tok::annot_template_id: 1483 case tok::caret: 1484 case tok::code_completion: 1485 case tok::coloncolon: 1486 case tok::ellipsis: 1487 case tok::kw___attribute: 1488 case tok::kw_operator: 1489 case tok::l_paren: 1490 case tok::star: 1491 return true; 1492 1493 case tok::amp: 1494 case tok::ampamp: 1495 return getLangOpts().CPlusPlus; 1496 1497 case tok::l_square: // Might be an attribute on an unnamed bit-field. 1498 return Context == Declarator::MemberContext && getLangOpts().CPlusPlus11 && 1499 NextToken().is(tok::l_square); 1500 1501 case tok::colon: // Might be a typo for '::' or an unnamed bit-field. 1502 return Context == Declarator::MemberContext || getLangOpts().CPlusPlus; 1503 1504 case tok::identifier: 1505 switch (NextToken().getKind()) { 1506 case tok::code_completion: 1507 case tok::coloncolon: 1508 case tok::comma: 1509 case tok::equal: 1510 case tok::equalequal: // Might be a typo for '='. 1511 case tok::kw_alignas: 1512 case tok::kw_asm: 1513 case tok::kw___attribute: 1514 case tok::l_brace: 1515 case tok::l_paren: 1516 case tok::l_square: 1517 case tok::less: 1518 case tok::r_brace: 1519 case tok::r_paren: 1520 case tok::r_square: 1521 case tok::semi: 1522 return true; 1523 1524 case tok::colon: 1525 // At namespace scope, 'identifier:' is probably a typo for 'identifier::' 1526 // and in block scope it's probably a label. Inside a class definition, 1527 // this is a bit-field. 1528 return Context == Declarator::MemberContext || 1529 (getLangOpts().CPlusPlus && Context == Declarator::FileContext); 1530 1531 case tok::identifier: // Possible virt-specifier. 1532 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken()); 1533 1534 default: 1535 return false; 1536 } 1537 1538 default: 1539 return false; 1540 } 1541} 1542 1543/// Skip until we reach something which seems like a sensible place to pick 1544/// up parsing after a malformed declaration. This will sometimes stop sooner 1545/// than SkipUntil(tok::r_brace) would, but will never stop later. 1546void Parser::SkipMalformedDecl() { 1547 while (true) { 1548 switch (Tok.getKind()) { 1549 case tok::l_brace: 1550 // Skip until matching }, then stop. We've probably skipped over 1551 // a malformed class or function definition or similar. 1552 ConsumeBrace(); 1553 SkipUntil(tok::r_brace); 1554 if (Tok.is(tok::comma) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try)) { 1555 // This declaration isn't over yet. Keep skipping. 1556 continue; 1557 } 1558 TryConsumeToken(tok::semi); 1559 return; 1560 1561 case tok::l_square: 1562 ConsumeBracket(); 1563 SkipUntil(tok::r_square); 1564 continue; 1565 1566 case tok::l_paren: 1567 ConsumeParen(); 1568 SkipUntil(tok::r_paren); 1569 continue; 1570 1571 case tok::r_brace: 1572 return; 1573 1574 case tok::semi: 1575 ConsumeToken(); 1576 return; 1577 1578 case tok::kw_inline: 1579 // 'inline namespace' at the start of a line is almost certainly 1580 // a good place to pick back up parsing, except in an Objective-C 1581 // @interface context. 1582 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) && 1583 (!ParsingInObjCContainer || CurParsedObjCImpl)) 1584 return; 1585 break; 1586 1587 case tok::kw_namespace: 1588 // 'namespace' at the start of a line is almost certainly a good 1589 // place to pick back up parsing, except in an Objective-C 1590 // @interface context. 1591 if (Tok.isAtStartOfLine() && 1592 (!ParsingInObjCContainer || CurParsedObjCImpl)) 1593 return; 1594 break; 1595 1596 case tok::at: 1597 // @end is very much like } in Objective-C contexts. 1598 if (NextToken().isObjCAtKeyword(tok::objc_end) && 1599 ParsingInObjCContainer) 1600 return; 1601 break; 1602 1603 case tok::minus: 1604 case tok::plus: 1605 // - and + probably start new method declarations in Objective-C contexts. 1606 if (Tok.isAtStartOfLine() && ParsingInObjCContainer) 1607 return; 1608 break; 1609 1610 case tok::eof: 1611 case tok::annot_module_begin: 1612 case tok::annot_module_end: 1613 case tok::annot_module_include: 1614 return; 1615 1616 default: 1617 break; 1618 } 1619 1620 ConsumeAnyToken(); 1621 } 1622} 1623 1624/// ParseDeclGroup - Having concluded that this is either a function 1625/// definition or a group of object declarations, actually parse the 1626/// result. 1627Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS, 1628 unsigned Context, 1629 SourceLocation *DeclEnd, 1630 ForRangeInit *FRI) { 1631 // Parse the first declarator. 1632 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context)); 1633 ParseDeclarator(D); 1634 1635 // Bail out if the first declarator didn't seem well-formed. 1636 if (!D.hasName() && !D.mayOmitIdentifier()) { 1637 SkipMalformedDecl(); 1638 return DeclGroupPtrTy(); 1639 } 1640 1641 // Save late-parsed attributes for now; they need to be parsed in the 1642 // appropriate function scope after the function Decl has been constructed. 1643 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList. 1644 LateParsedAttrList LateParsedAttrs(true); 1645 if (D.isFunctionDeclarator()) { 1646 MaybeParseGNUAttributes(D, &LateParsedAttrs); 1647 1648 // The _Noreturn keyword can't appear here, unlike the GNU noreturn 1649 // attribute. If we find the keyword here, tell the user to put it 1650 // at the start instead. 1651 if (Tok.is(tok::kw__Noreturn)) { 1652 SourceLocation Loc = ConsumeToken(); 1653 const char *PrevSpec; 1654 unsigned DiagID; 1655 1656 // We can offer a fixit if it's valid to mark this function as _Noreturn 1657 // and we don't have any other declarators in this declaration. 1658 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID); 1659 MaybeParseGNUAttributes(D, &LateParsedAttrs); 1660 Fixit &= Tok.is(tok::semi) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try); 1661 1662 Diag(Loc, diag::err_c11_noreturn_misplaced) 1663 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint()) 1664 << (Fixit ? FixItHint::CreateInsertion(D.getLocStart(), "_Noreturn ") 1665 : FixItHint()); 1666 } 1667 } 1668 1669 // Check to see if we have a function *definition* which must have a body. 1670 if (D.isFunctionDeclarator() && 1671 // Look at the next token to make sure that this isn't a function 1672 // declaration. We have to check this because __attribute__ might be the 1673 // start of a function definition in GCC-extended K&R C. 1674 !isDeclarationAfterDeclarator()) { 1675 1676 // Function definitions are only allowed at file scope and in C++ classes. 1677 // The C++ inline method definition case is handled elsewhere, so we only 1678 // need to handle the file scope definition case. 1679 if (Context == Declarator::FileContext) { 1680 if (isStartOfFunctionDefinition(D)) { 1681 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 1682 Diag(Tok, diag::err_function_declared_typedef); 1683 1684 // Recover by treating the 'typedef' as spurious. 1685 DS.ClearStorageClassSpecs(); 1686 } 1687 1688 Decl *TheDecl = 1689 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs); 1690 return Actions.ConvertDeclToDeclGroup(TheDecl); 1691 } 1692 1693 if (isDeclarationSpecifier()) { 1694 // If there is an invalid declaration specifier right after the function 1695 // prototype, then we must be in a missing semicolon case where this isn't 1696 // actually a body. Just fall through into the code that handles it as a 1697 // prototype, and let the top-level code handle the erroneous declspec 1698 // where it would otherwise expect a comma or semicolon. 1699 } else { 1700 Diag(Tok, diag::err_expected_fn_body); 1701 SkipUntil(tok::semi); 1702 return DeclGroupPtrTy(); 1703 } 1704 } else { 1705 if (Tok.is(tok::l_brace)) { 1706 Diag(Tok, diag::err_function_definition_not_allowed); 1707 SkipMalformedDecl(); 1708 return DeclGroupPtrTy(); 1709 } 1710 } 1711 } 1712 1713 if (ParseAsmAttributesAfterDeclarator(D)) 1714 return DeclGroupPtrTy(); 1715 1716 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we 1717 // must parse and analyze the for-range-initializer before the declaration is 1718 // analyzed. 1719 // 1720 // Handle the Objective-C for-in loop variable similarly, although we 1721 // don't need to parse the container in advance. 1722 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) { 1723 bool IsForRangeLoop = false; 1724 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) { 1725 IsForRangeLoop = true; 1726 if (Tok.is(tok::l_brace)) 1727 FRI->RangeExpr = ParseBraceInitializer(); 1728 else 1729 FRI->RangeExpr = ParseExpression(); 1730 } 1731 1732 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 1733 if (IsForRangeLoop) 1734 Actions.ActOnCXXForRangeDecl(ThisDecl); 1735 Actions.FinalizeDeclaration(ThisDecl); 1736 D.complete(ThisDecl); 1737 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl); 1738 } 1739 1740 SmallVector<Decl *, 8> DeclsInGroup; 1741 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes( 1742 D, ParsedTemplateInfo(), FRI); 1743 if (LateParsedAttrs.size() > 0) 1744 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false); 1745 D.complete(FirstDecl); 1746 if (FirstDecl) 1747 DeclsInGroup.push_back(FirstDecl); 1748 1749 bool ExpectSemi = Context != Declarator::ForContext; 1750 1751 // If we don't have a comma, it is either the end of the list (a ';') or an 1752 // error, bail out. 1753 SourceLocation CommaLoc; 1754 while (TryConsumeToken(tok::comma, CommaLoc)) { 1755 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) { 1756 // This comma was followed by a line-break and something which can't be 1757 // the start of a declarator. The comma was probably a typo for a 1758 // semicolon. 1759 Diag(CommaLoc, diag::err_expected_semi_declaration) 1760 << FixItHint::CreateReplacement(CommaLoc, ";"); 1761 ExpectSemi = false; 1762 break; 1763 } 1764 1765 // Parse the next declarator. 1766 D.clear(); 1767 D.setCommaLoc(CommaLoc); 1768 1769 // Accept attributes in an init-declarator. In the first declarator in a 1770 // declaration, these would be part of the declspec. In subsequent 1771 // declarators, they become part of the declarator itself, so that they 1772 // don't apply to declarators after *this* one. Examples: 1773 // short __attribute__((common)) var; -> declspec 1774 // short var __attribute__((common)); -> declarator 1775 // short x, __attribute__((common)) var; -> declarator 1776 MaybeParseGNUAttributes(D); 1777 1778 // MSVC parses but ignores qualifiers after the comma as an extension. 1779 if (getLangOpts().MicrosoftExt) 1780 DiagnoseAndSkipExtendedMicrosoftTypeAttributes(); 1781 1782 ParseDeclarator(D); 1783 if (!D.isInvalidType()) { 1784 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D); 1785 D.complete(ThisDecl); 1786 if (ThisDecl) 1787 DeclsInGroup.push_back(ThisDecl); 1788 } 1789 } 1790 1791 if (DeclEnd) 1792 *DeclEnd = Tok.getLocation(); 1793 1794 if (ExpectSemi && 1795 ExpectAndConsumeSemi(Context == Declarator::FileContext 1796 ? diag::err_invalid_token_after_toplevel_declarator 1797 : diag::err_expected_semi_declaration)) { 1798 // Okay, there was no semicolon and one was expected. If we see a 1799 // declaration specifier, just assume it was missing and continue parsing. 1800 // Otherwise things are very confused and we skip to recover. 1801 if (!isDeclarationSpecifier()) { 1802 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 1803 TryConsumeToken(tok::semi); 1804 } 1805 } 1806 1807 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup); 1808} 1809 1810/// Parse an optional simple-asm-expr and attributes, and attach them to a 1811/// declarator. Returns true on an error. 1812bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) { 1813 // If a simple-asm-expr is present, parse it. 1814 if (Tok.is(tok::kw_asm)) { 1815 SourceLocation Loc; 1816 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 1817 if (AsmLabel.isInvalid()) { 1818 SkipUntil(tok::semi, StopBeforeMatch); 1819 return true; 1820 } 1821 1822 D.setAsmLabel(AsmLabel.get()); 1823 D.SetRangeEnd(Loc); 1824 } 1825 1826 MaybeParseGNUAttributes(D); 1827 return false; 1828} 1829 1830/// \brief Parse 'declaration' after parsing 'declaration-specifiers 1831/// declarator'. This method parses the remainder of the declaration 1832/// (including any attributes or initializer, among other things) and 1833/// finalizes the declaration. 1834/// 1835/// init-declarator: [C99 6.7] 1836/// declarator 1837/// declarator '=' initializer 1838/// [GNU] declarator simple-asm-expr[opt] attributes[opt] 1839/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer 1840/// [C++] declarator initializer[opt] 1841/// 1842/// [C++] initializer: 1843/// [C++] '=' initializer-clause 1844/// [C++] '(' expression-list ')' 1845/// [C++0x] '=' 'default' [TODO] 1846/// [C++0x] '=' 'delete' 1847/// [C++0x] braced-init-list 1848/// 1849/// According to the standard grammar, =default and =delete are function 1850/// definitions, but that definitely doesn't fit with the parser here. 1851/// 1852Decl *Parser::ParseDeclarationAfterDeclarator( 1853 Declarator &D, const ParsedTemplateInfo &TemplateInfo) { 1854 if (ParseAsmAttributesAfterDeclarator(D)) 1855 return nullptr; 1856 1857 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo); 1858} 1859 1860Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes( 1861 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) { 1862 // Inform the current actions module that we just parsed this declarator. 1863 Decl *ThisDecl = nullptr; 1864 switch (TemplateInfo.Kind) { 1865 case ParsedTemplateInfo::NonTemplate: 1866 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 1867 break; 1868 1869 case ParsedTemplateInfo::Template: 1870 case ParsedTemplateInfo::ExplicitSpecialization: { 1871 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(), 1872 *TemplateInfo.TemplateParams, 1873 D); 1874 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl)) 1875 // Re-direct this decl to refer to the templated decl so that we can 1876 // initialize it. 1877 ThisDecl = VT->getTemplatedDecl(); 1878 break; 1879 } 1880 case ParsedTemplateInfo::ExplicitInstantiation: { 1881 if (Tok.is(tok::semi)) { 1882 DeclResult ThisRes = Actions.ActOnExplicitInstantiation( 1883 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D); 1884 if (ThisRes.isInvalid()) { 1885 SkipUntil(tok::semi, StopBeforeMatch); 1886 return nullptr; 1887 } 1888 ThisDecl = ThisRes.get(); 1889 } else { 1890 // FIXME: This check should be for a variable template instantiation only. 1891 1892 // Check that this is a valid instantiation 1893 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 1894 // If the declarator-id is not a template-id, issue a diagnostic and 1895 // recover by ignoring the 'template' keyword. 1896 Diag(Tok, diag::err_template_defn_explicit_instantiation) 1897 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc); 1898 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 1899 } else { 1900 SourceLocation LAngleLoc = 1901 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); 1902 Diag(D.getIdentifierLoc(), 1903 diag::err_explicit_instantiation_with_definition) 1904 << SourceRange(TemplateInfo.TemplateLoc) 1905 << FixItHint::CreateInsertion(LAngleLoc, "<>"); 1906 1907 // Recover as if it were an explicit specialization. 1908 TemplateParameterLists FakedParamLists; 1909 FakedParamLists.push_back(Actions.ActOnTemplateParameterList( 1910 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr, 1911 0, LAngleLoc)); 1912 1913 ThisDecl = 1914 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D); 1915 } 1916 } 1917 break; 1918 } 1919 } 1920 1921 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType(); 1922 1923 // Parse declarator '=' initializer. 1924 // If a '==' or '+=' is found, suggest a fixit to '='. 1925 if (isTokenEqualOrEqualTypo()) { 1926 SourceLocation EqualLoc = ConsumeToken(); 1927 1928 if (Tok.is(tok::kw_delete)) { 1929 if (D.isFunctionDeclarator()) 1930 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) 1931 << 1 /* delete */; 1932 else 1933 Diag(ConsumeToken(), diag::err_deleted_non_function); 1934 } else if (Tok.is(tok::kw_default)) { 1935 if (D.isFunctionDeclarator()) 1936 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) 1937 << 0 /* default */; 1938 else 1939 Diag(ConsumeToken(), diag::err_default_special_members); 1940 } else { 1941 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 1942 EnterScope(0); 1943 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 1944 } 1945 1946 if (Tok.is(tok::code_completion)) { 1947 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl); 1948 Actions.FinalizeDeclaration(ThisDecl); 1949 cutOffParsing(); 1950 return nullptr; 1951 } 1952 1953 ExprResult Init(ParseInitializer()); 1954 1955 // If this is the only decl in (possibly) range based for statement, 1956 // our best guess is that the user meant ':' instead of '='. 1957 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) { 1958 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range) 1959 << FixItHint::CreateReplacement(EqualLoc, ":"); 1960 // We are trying to stop parser from looking for ';' in this for 1961 // statement, therefore preventing spurious errors to be issued. 1962 FRI->ColonLoc = EqualLoc; 1963 Init = ExprError(); 1964 FRI->RangeExpr = Init; 1965 } 1966 1967 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 1968 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 1969 ExitScope(); 1970 } 1971 1972 if (Init.isInvalid()) { 1973 SmallVector<tok::TokenKind, 2> StopTokens; 1974 StopTokens.push_back(tok::comma); 1975 if (D.getContext() == Declarator::ForContext) 1976 StopTokens.push_back(tok::r_paren); 1977 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch); 1978 Actions.ActOnInitializerError(ThisDecl); 1979 } else 1980 Actions.AddInitializerToDecl(ThisDecl, Init.get(), 1981 /*DirectInit=*/false, TypeContainsAuto); 1982 } 1983 } else if (Tok.is(tok::l_paren)) { 1984 // Parse C++ direct initializer: '(' expression-list ')' 1985 BalancedDelimiterTracker T(*this, tok::l_paren); 1986 T.consumeOpen(); 1987 1988 ExprVector Exprs; 1989 CommaLocsTy CommaLocs; 1990 1991 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 1992 EnterScope(0); 1993 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 1994 } 1995 1996 if (ParseExpressionList(Exprs, CommaLocs)) { 1997 Actions.ActOnInitializerError(ThisDecl); 1998 SkipUntil(tok::r_paren, StopAtSemi); 1999 2000 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 2001 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 2002 ExitScope(); 2003 } 2004 } else { 2005 // Match the ')'. 2006 T.consumeClose(); 2007 2008 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() && 2009 "Unexpected number of commas!"); 2010 2011 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 2012 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 2013 ExitScope(); 2014 } 2015 2016 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(), 2017 T.getCloseLocation(), 2018 Exprs); 2019 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(), 2020 /*DirectInit=*/true, TypeContainsAuto); 2021 } 2022 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) && 2023 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) { 2024 // Parse C++0x braced-init-list. 2025 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 2026 2027 if (D.getCXXScopeSpec().isSet()) { 2028 EnterScope(0); 2029 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 2030 } 2031 2032 ExprResult Init(ParseBraceInitializer()); 2033 2034 if (D.getCXXScopeSpec().isSet()) { 2035 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 2036 ExitScope(); 2037 } 2038 2039 if (Init.isInvalid()) { 2040 Actions.ActOnInitializerError(ThisDecl); 2041 } else 2042 Actions.AddInitializerToDecl(ThisDecl, Init.get(), 2043 /*DirectInit=*/true, TypeContainsAuto); 2044 2045 } else { 2046 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto); 2047 } 2048 2049 Actions.FinalizeDeclaration(ThisDecl); 2050 2051 return ThisDecl; 2052} 2053 2054/// ParseSpecifierQualifierList 2055/// specifier-qualifier-list: 2056/// type-specifier specifier-qualifier-list[opt] 2057/// type-qualifier specifier-qualifier-list[opt] 2058/// [GNU] attributes specifier-qualifier-list[opt] 2059/// 2060void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS, 2061 DeclSpecContext DSC) { 2062 /// specifier-qualifier-list is a subset of declaration-specifiers. Just 2063 /// parse declaration-specifiers and complain about extra stuff. 2064 /// TODO: diagnose attribute-specifiers and alignment-specifiers. 2065 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC); 2066 2067 // Validate declspec for type-name. 2068 unsigned Specs = DS.getParsedSpecifiers(); 2069 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) { 2070 Diag(Tok, diag::err_expected_type); 2071 DS.SetTypeSpecError(); 2072 } else if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() && 2073 !DS.hasAttributes()) { 2074 Diag(Tok, diag::err_typename_requires_specqual); 2075 if (!DS.hasTypeSpecifier()) 2076 DS.SetTypeSpecError(); 2077 } 2078 2079 // Issue diagnostic and remove storage class if present. 2080 if (Specs & DeclSpec::PQ_StorageClassSpecifier) { 2081 if (DS.getStorageClassSpecLoc().isValid()) 2082 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass); 2083 else 2084 Diag(DS.getThreadStorageClassSpecLoc(), 2085 diag::err_typename_invalid_storageclass); 2086 DS.ClearStorageClassSpecs(); 2087 } 2088 2089 // Issue diagnostic and remove function specfier if present. 2090 if (Specs & DeclSpec::PQ_FunctionSpecifier) { 2091 if (DS.isInlineSpecified()) 2092 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec); 2093 if (DS.isVirtualSpecified()) 2094 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec); 2095 if (DS.isExplicitSpecified()) 2096 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec); 2097 DS.ClearFunctionSpecs(); 2098 } 2099 2100 // Issue diagnostic and remove constexpr specfier if present. 2101 if (DS.isConstexprSpecified()) { 2102 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr); 2103 DS.ClearConstexprSpec(); 2104 } 2105} 2106 2107/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the 2108/// specified token is valid after the identifier in a declarator which 2109/// immediately follows the declspec. For example, these things are valid: 2110/// 2111/// int x [ 4]; // direct-declarator 2112/// int x ( int y); // direct-declarator 2113/// int(int x ) // direct-declarator 2114/// int x ; // simple-declaration 2115/// int x = 17; // init-declarator-list 2116/// int x , y; // init-declarator-list 2117/// int x __asm__ ("foo"); // init-declarator-list 2118/// int x : 4; // struct-declarator 2119/// int x { 5}; // C++'0x unified initializers 2120/// 2121/// This is not, because 'x' does not immediately follow the declspec (though 2122/// ')' happens to be valid anyway). 2123/// int (x) 2124/// 2125static bool isValidAfterIdentifierInDeclarator(const Token &T) { 2126 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) || 2127 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) || 2128 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon); 2129} 2130 2131 2132/// ParseImplicitInt - This method is called when we have an non-typename 2133/// identifier in a declspec (which normally terminates the decl spec) when 2134/// the declspec has no type specifier. In this case, the declspec is either 2135/// malformed or is "implicit int" (in K&R and C89). 2136/// 2137/// This method handles diagnosing this prettily and returns false if the 2138/// declspec is done being processed. If it recovers and thinks there may be 2139/// other pieces of declspec after it, it returns true. 2140/// 2141bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, 2142 const ParsedTemplateInfo &TemplateInfo, 2143 AccessSpecifier AS, DeclSpecContext DSC, 2144 ParsedAttributesWithRange &Attrs) { 2145 assert(Tok.is(tok::identifier) && "should have identifier"); 2146 2147 SourceLocation Loc = Tok.getLocation(); 2148 // If we see an identifier that is not a type name, we normally would 2149 // parse it as the identifer being declared. However, when a typename 2150 // is typo'd or the definition is not included, this will incorrectly 2151 // parse the typename as the identifier name and fall over misparsing 2152 // later parts of the diagnostic. 2153 // 2154 // As such, we try to do some look-ahead in cases where this would 2155 // otherwise be an "implicit-int" case to see if this is invalid. For 2156 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as 2157 // an identifier with implicit int, we'd get a parse error because the 2158 // next token is obviously invalid for a type. Parse these as a case 2159 // with an invalid type specifier. 2160 assert(!DS.hasTypeSpecifier() && "Type specifier checked above"); 2161 2162 // Since we know that this either implicit int (which is rare) or an 2163 // error, do lookahead to try to do better recovery. This never applies 2164 // within a type specifier. Outside of C++, we allow this even if the 2165 // language doesn't "officially" support implicit int -- we support 2166 // implicit int as an extension in C99 and C11. 2167 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus && 2168 isValidAfterIdentifierInDeclarator(NextToken())) { 2169 // If this token is valid for implicit int, e.g. "static x = 4", then 2170 // we just avoid eating the identifier, so it will be parsed as the 2171 // identifier in the declarator. 2172 return false; 2173 } 2174 2175 if (getLangOpts().CPlusPlus && 2176 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 2177 // Don't require a type specifier if we have the 'auto' storage class 2178 // specifier in C++98 -- we'll promote it to a type specifier. 2179 if (SS) 2180 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false); 2181 return false; 2182 } 2183 2184 // Otherwise, if we don't consume this token, we are going to emit an 2185 // error anyway. Try to recover from various common problems. Check 2186 // to see if this was a reference to a tag name without a tag specified. 2187 // This is a common problem in C (saying 'foo' instead of 'struct foo'). 2188 // 2189 // C++ doesn't need this, and isTagName doesn't take SS. 2190 if (SS == nullptr) { 2191 const char *TagName = nullptr, *FixitTagName = nullptr; 2192 tok::TokenKind TagKind = tok::unknown; 2193 2194 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) { 2195 default: break; 2196 case DeclSpec::TST_enum: 2197 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break; 2198 case DeclSpec::TST_union: 2199 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break; 2200 case DeclSpec::TST_struct: 2201 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break; 2202 case DeclSpec::TST_interface: 2203 TagName="__interface"; FixitTagName = "__interface "; 2204 TagKind=tok::kw___interface;break; 2205 case DeclSpec::TST_class: 2206 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break; 2207 } 2208 2209 if (TagName) { 2210 IdentifierInfo *TokenName = Tok.getIdentifierInfo(); 2211 LookupResult R(Actions, TokenName, SourceLocation(), 2212 Sema::LookupOrdinaryName); 2213 2214 Diag(Loc, diag::err_use_of_tag_name_without_tag) 2215 << TokenName << TagName << getLangOpts().CPlusPlus 2216 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName); 2217 2218 if (Actions.LookupParsedName(R, getCurScope(), SS)) { 2219 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); 2220 I != IEnd; ++I) 2221 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 2222 << TokenName << TagName; 2223 } 2224 2225 // Parse this as a tag as if the missing tag were present. 2226 if (TagKind == tok::kw_enum) 2227 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal); 2228 else 2229 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS, 2230 /*EnteringContext*/ false, DSC_normal, Attrs); 2231 return true; 2232 } 2233 } 2234 2235 // Determine whether this identifier could plausibly be the name of something 2236 // being declared (with a missing type). 2237 if (!isTypeSpecifier(DSC) && 2238 (!SS || DSC == DSC_top_level || DSC == DSC_class)) { 2239 // Look ahead to the next token to try to figure out what this declaration 2240 // was supposed to be. 2241 switch (NextToken().getKind()) { 2242 case tok::l_paren: { 2243 // static x(4); // 'x' is not a type 2244 // x(int n); // 'x' is not a type 2245 // x (*p)[]; // 'x' is a type 2246 // 2247 // Since we're in an error case, we can afford to perform a tentative 2248 // parse to determine which case we're in. 2249 TentativeParsingAction PA(*this); 2250 ConsumeToken(); 2251 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false); 2252 PA.Revert(); 2253 2254 if (TPR != TPResult::False) { 2255 // The identifier is followed by a parenthesized declarator. 2256 // It's supposed to be a type. 2257 break; 2258 } 2259 2260 // If we're in a context where we could be declaring a constructor, 2261 // check whether this is a constructor declaration with a bogus name. 2262 if (DSC == DSC_class || (DSC == DSC_top_level && SS)) { 2263 IdentifierInfo *II = Tok.getIdentifierInfo(); 2264 if (Actions.isCurrentClassNameTypo(II, SS)) { 2265 Diag(Loc, diag::err_constructor_bad_name) 2266 << Tok.getIdentifierInfo() << II 2267 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName()); 2268 Tok.setIdentifierInfo(II); 2269 } 2270 } 2271 // Fall through. 2272 } 2273 case tok::comma: 2274 case tok::equal: 2275 case tok::kw_asm: 2276 case tok::l_brace: 2277 case tok::l_square: 2278 case tok::semi: 2279 // This looks like a variable or function declaration. The type is 2280 // probably missing. We're done parsing decl-specifiers. 2281 if (SS) 2282 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false); 2283 return false; 2284 2285 default: 2286 // This is probably supposed to be a type. This includes cases like: 2287 // int f(itn); 2288 // struct S { unsinged : 4; }; 2289 break; 2290 } 2291 } 2292 2293 // This is almost certainly an invalid type name. Let Sema emit a diagnostic 2294 // and attempt to recover. 2295 ParsedType T; 2296 IdentifierInfo *II = Tok.getIdentifierInfo(); 2297 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T, 2298 getLangOpts().CPlusPlus && 2299 NextToken().is(tok::less)); 2300 if (T) { 2301 // The action has suggested that the type T could be used. Set that as 2302 // the type in the declaration specifiers, consume the would-be type 2303 // name token, and we're done. 2304 const char *PrevSpec; 2305 unsigned DiagID; 2306 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T, 2307 Actions.getASTContext().getPrintingPolicy()); 2308 DS.SetRangeEnd(Tok.getLocation()); 2309 ConsumeToken(); 2310 // There may be other declaration specifiers after this. 2311 return true; 2312 } else if (II != Tok.getIdentifierInfo()) { 2313 // If no type was suggested, the correction is to a keyword 2314 Tok.setKind(II->getTokenID()); 2315 // There may be other declaration specifiers after this. 2316 return true; 2317 } 2318 2319 // Otherwise, the action had no suggestion for us. Mark this as an error. 2320 DS.SetTypeSpecError(); 2321 DS.SetRangeEnd(Tok.getLocation()); 2322 ConsumeToken(); 2323 2324 // TODO: Could inject an invalid typedef decl in an enclosing scope to 2325 // avoid rippling error messages on subsequent uses of the same type, 2326 // could be useful if #include was forgotten. 2327 return false; 2328} 2329 2330/// \brief Determine the declaration specifier context from the declarator 2331/// context. 2332/// 2333/// \param Context the declarator context, which is one of the 2334/// Declarator::TheContext enumerator values. 2335Parser::DeclSpecContext 2336Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) { 2337 if (Context == Declarator::MemberContext) 2338 return DSC_class; 2339 if (Context == Declarator::FileContext) 2340 return DSC_top_level; 2341 if (Context == Declarator::TemplateTypeArgContext) 2342 return DSC_template_type_arg; 2343 if (Context == Declarator::TrailingReturnContext) 2344 return DSC_trailing; 2345 if (Context == Declarator::AliasDeclContext || 2346 Context == Declarator::AliasTemplateContext) 2347 return DSC_alias_declaration; 2348 return DSC_normal; 2349} 2350 2351/// ParseAlignArgument - Parse the argument to an alignment-specifier. 2352/// 2353/// FIXME: Simply returns an alignof() expression if the argument is a 2354/// type. Ideally, the type should be propagated directly into Sema. 2355/// 2356/// [C11] type-id 2357/// [C11] constant-expression 2358/// [C++0x] type-id ...[opt] 2359/// [C++0x] assignment-expression ...[opt] 2360ExprResult Parser::ParseAlignArgument(SourceLocation Start, 2361 SourceLocation &EllipsisLoc) { 2362 ExprResult ER; 2363 if (isTypeIdInParens()) { 2364 SourceLocation TypeLoc = Tok.getLocation(); 2365 ParsedType Ty = ParseTypeName().get(); 2366 SourceRange TypeRange(Start, Tok.getLocation()); 2367 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true, 2368 Ty.getAsOpaquePtr(), TypeRange); 2369 } else 2370 ER = ParseConstantExpression(); 2371 2372 if (getLangOpts().CPlusPlus11) 2373 TryConsumeToken(tok::ellipsis, EllipsisLoc); 2374 2375 return ER; 2376} 2377 2378/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the 2379/// attribute to Attrs. 2380/// 2381/// alignment-specifier: 2382/// [C11] '_Alignas' '(' type-id ')' 2383/// [C11] '_Alignas' '(' constant-expression ')' 2384/// [C++11] 'alignas' '(' type-id ...[opt] ')' 2385/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')' 2386void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs, 2387 SourceLocation *EndLoc) { 2388 assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) && 2389 "Not an alignment-specifier!"); 2390 2391 IdentifierInfo *KWName = Tok.getIdentifierInfo(); 2392 SourceLocation KWLoc = ConsumeToken(); 2393 2394 BalancedDelimiterTracker T(*this, tok::l_paren); 2395 if (T.expectAndConsume()) 2396 return; 2397 2398 SourceLocation EllipsisLoc; 2399 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc); 2400 if (ArgExpr.isInvalid()) { 2401 T.skipToEnd(); 2402 return; 2403 } 2404 2405 T.consumeClose(); 2406 if (EndLoc) 2407 *EndLoc = T.getCloseLocation(); 2408 2409 ArgsVector ArgExprs; 2410 ArgExprs.push_back(ArgExpr.get()); 2411 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1, 2412 AttributeList::AS_Keyword, EllipsisLoc); 2413} 2414 2415/// Determine whether we're looking at something that might be a declarator 2416/// in a simple-declaration. If it can't possibly be a declarator, maybe 2417/// diagnose a missing semicolon after a prior tag definition in the decl 2418/// specifier. 2419/// 2420/// \return \c true if an error occurred and this can't be any kind of 2421/// declaration. 2422bool 2423Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS, 2424 DeclSpecContext DSContext, 2425 LateParsedAttrList *LateAttrs) { 2426 assert(DS.hasTagDefinition() && "shouldn't call this"); 2427 2428 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level); 2429 2430 if (getLangOpts().CPlusPlus && 2431 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || 2432 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id)) && 2433 TryAnnotateCXXScopeToken(EnteringContext)) { 2434 SkipMalformedDecl(); 2435 return true; 2436 } 2437 2438 bool HasScope = Tok.is(tok::annot_cxxscope); 2439 // Make a copy in case GetLookAheadToken invalidates the result of NextToken. 2440 Token AfterScope = HasScope ? NextToken() : Tok; 2441 2442 // Determine whether the following tokens could possibly be a 2443 // declarator. 2444 bool MightBeDeclarator = true; 2445 if (Tok.is(tok::kw_typename) || Tok.is(tok::annot_typename)) { 2446 // A declarator-id can't start with 'typename'. 2447 MightBeDeclarator = false; 2448 } else if (AfterScope.is(tok::annot_template_id)) { 2449 // If we have a type expressed as a template-id, this cannot be a 2450 // declarator-id (such a type cannot be redeclared in a simple-declaration). 2451 TemplateIdAnnotation *Annot = 2452 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue()); 2453 if (Annot->Kind == TNK_Type_template) 2454 MightBeDeclarator = false; 2455 } else if (AfterScope.is(tok::identifier)) { 2456 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken(); 2457 2458 // These tokens cannot come after the declarator-id in a 2459 // simple-declaration, and are likely to come after a type-specifier. 2460 if (Next.is(tok::star) || Next.is(tok::amp) || Next.is(tok::ampamp) || 2461 Next.is(tok::identifier) || Next.is(tok::annot_cxxscope) || 2462 Next.is(tok::coloncolon)) { 2463 // Missing a semicolon. 2464 MightBeDeclarator = false; 2465 } else if (HasScope) { 2466 // If the declarator-id has a scope specifier, it must redeclare a 2467 // previously-declared entity. If that's a type (and this is not a 2468 // typedef), that's an error. 2469 CXXScopeSpec SS; 2470 Actions.RestoreNestedNameSpecifierAnnotation( 2471 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS); 2472 IdentifierInfo *Name = AfterScope.getIdentifierInfo(); 2473 Sema::NameClassification Classification = Actions.ClassifyName( 2474 getCurScope(), SS, Name, AfterScope.getLocation(), Next, 2475 /*IsAddressOfOperand*/false); 2476 switch (Classification.getKind()) { 2477 case Sema::NC_Error: 2478 SkipMalformedDecl(); 2479 return true; 2480 2481 case Sema::NC_Keyword: 2482 case Sema::NC_NestedNameSpecifier: 2483 llvm_unreachable("typo correction and nested name specifiers not " 2484 "possible here"); 2485 2486 case Sema::NC_Type: 2487 case Sema::NC_TypeTemplate: 2488 // Not a previously-declared non-type entity. 2489 MightBeDeclarator = false; 2490 break; 2491 2492 case Sema::NC_Unknown: 2493 case Sema::NC_Expression: 2494 case Sema::NC_VarTemplate: 2495 case Sema::NC_FunctionTemplate: 2496 // Might be a redeclaration of a prior entity. 2497 break; 2498 } 2499 } 2500 } 2501 2502 if (MightBeDeclarator) 2503 return false; 2504 2505 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy(); 2506 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()), 2507 diag::err_expected_after) 2508 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi; 2509 2510 // Try to recover from the typo, by dropping the tag definition and parsing 2511 // the problematic tokens as a type. 2512 // 2513 // FIXME: Split the DeclSpec into pieces for the standalone 2514 // declaration and pieces for the following declaration, instead 2515 // of assuming that all the other pieces attach to new declaration, 2516 // and call ParsedFreeStandingDeclSpec as appropriate. 2517 DS.ClearTypeSpecType(); 2518 ParsedTemplateInfo NotATemplate; 2519 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs); 2520 return false; 2521} 2522 2523/// ParseDeclarationSpecifiers 2524/// declaration-specifiers: [C99 6.7] 2525/// storage-class-specifier declaration-specifiers[opt] 2526/// type-specifier declaration-specifiers[opt] 2527/// [C99] function-specifier declaration-specifiers[opt] 2528/// [C11] alignment-specifier declaration-specifiers[opt] 2529/// [GNU] attributes declaration-specifiers[opt] 2530/// [Clang] '__module_private__' declaration-specifiers[opt] 2531/// 2532/// storage-class-specifier: [C99 6.7.1] 2533/// 'typedef' 2534/// 'extern' 2535/// 'static' 2536/// 'auto' 2537/// 'register' 2538/// [C++] 'mutable' 2539/// [C++11] 'thread_local' 2540/// [C11] '_Thread_local' 2541/// [GNU] '__thread' 2542/// function-specifier: [C99 6.7.4] 2543/// [C99] 'inline' 2544/// [C++] 'virtual' 2545/// [C++] 'explicit' 2546/// [OpenCL] '__kernel' 2547/// 'friend': [C++ dcl.friend] 2548/// 'constexpr': [C++0x dcl.constexpr] 2549 2550/// 2551void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, 2552 const ParsedTemplateInfo &TemplateInfo, 2553 AccessSpecifier AS, 2554 DeclSpecContext DSContext, 2555 LateParsedAttrList *LateAttrs) { 2556 if (DS.getSourceRange().isInvalid()) { 2557 // Start the range at the current token but make the end of the range 2558 // invalid. This will make the entire range invalid unless we successfully 2559 // consume a token. 2560 DS.SetRangeStart(Tok.getLocation()); 2561 DS.SetRangeEnd(SourceLocation()); 2562 } 2563 2564 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level); 2565 bool AttrsLastTime = false; 2566 ParsedAttributesWithRange attrs(AttrFactory); 2567 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); 2568 while (1) { 2569 bool isInvalid = false; 2570 bool isStorageClass = false; 2571 const char *PrevSpec = nullptr; 2572 unsigned DiagID = 0; 2573 2574 SourceLocation Loc = Tok.getLocation(); 2575 2576 switch (Tok.getKind()) { 2577 default: 2578 DoneWithDeclSpec: 2579 if (!AttrsLastTime) 2580 ProhibitAttributes(attrs); 2581 else { 2582 // Reject C++11 attributes that appertain to decl specifiers as 2583 // we don't support any C++11 attributes that appertain to decl 2584 // specifiers. This also conforms to what g++ 4.8 is doing. 2585 ProhibitCXX11Attributes(attrs); 2586 2587 DS.takeAttributesFrom(attrs); 2588 } 2589 2590 // If this is not a declaration specifier token, we're done reading decl 2591 // specifiers. First verify that DeclSpec's are consistent. 2592 DS.Finish(Diags, PP, Policy); 2593 return; 2594 2595 case tok::l_square: 2596 case tok::kw_alignas: 2597 if (!getLangOpts().CPlusPlus11 || !isCXX11AttributeSpecifier()) 2598 goto DoneWithDeclSpec; 2599 2600 ProhibitAttributes(attrs); 2601 // FIXME: It would be good to recover by accepting the attributes, 2602 // but attempting to do that now would cause serious 2603 // madness in terms of diagnostics. 2604 attrs.clear(); 2605 attrs.Range = SourceRange(); 2606 2607 ParseCXX11Attributes(attrs); 2608 AttrsLastTime = true; 2609 continue; 2610 2611 case tok::code_completion: { 2612 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace; 2613 if (DS.hasTypeSpecifier()) { 2614 bool AllowNonIdentifiers 2615 = (getCurScope()->getFlags() & (Scope::ControlScope | 2616 Scope::BlockScope | 2617 Scope::TemplateParamScope | 2618 Scope::FunctionPrototypeScope | 2619 Scope::AtCatchScope)) == 0; 2620 bool AllowNestedNameSpecifiers 2621 = DSContext == DSC_top_level || 2622 (DSContext == DSC_class && DS.isFriendSpecified()); 2623 2624 Actions.CodeCompleteDeclSpec(getCurScope(), DS, 2625 AllowNonIdentifiers, 2626 AllowNestedNameSpecifiers); 2627 return cutOffParsing(); 2628 } 2629 2630 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent()) 2631 CCC = Sema::PCC_LocalDeclarationSpecifiers; 2632 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) 2633 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate 2634 : Sema::PCC_Template; 2635 else if (DSContext == DSC_class) 2636 CCC = Sema::PCC_Class; 2637 else if (CurParsedObjCImpl) 2638 CCC = Sema::PCC_ObjCImplementation; 2639 2640 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC); 2641 return cutOffParsing(); 2642 } 2643 2644 case tok::coloncolon: // ::foo::bar 2645 // C++ scope specifier. Annotate and loop, or bail out on error. 2646 if (TryAnnotateCXXScopeToken(EnteringContext)) { 2647 if (!DS.hasTypeSpecifier()) 2648 DS.SetTypeSpecError(); 2649 goto DoneWithDeclSpec; 2650 } 2651 if (Tok.is(tok::coloncolon)) // ::new or ::delete 2652 goto DoneWithDeclSpec; 2653 continue; 2654 2655 case tok::annot_cxxscope: { 2656 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector()) 2657 goto DoneWithDeclSpec; 2658 2659 CXXScopeSpec SS; 2660 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), 2661 Tok.getAnnotationRange(), 2662 SS); 2663 2664 // We are looking for a qualified typename. 2665 Token Next = NextToken(); 2666 if (Next.is(tok::annot_template_id) && 2667 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()) 2668 ->Kind == TNK_Type_template) { 2669 // We have a qualified template-id, e.g., N::A<int> 2670 2671 // C++ [class.qual]p2: 2672 // In a lookup in which the constructor is an acceptable lookup 2673 // result and the nested-name-specifier nominates a class C: 2674 // 2675 // - if the name specified after the 2676 // nested-name-specifier, when looked up in C, is the 2677 // injected-class-name of C (Clause 9), or 2678 // 2679 // - if the name specified after the nested-name-specifier 2680 // is the same as the identifier or the 2681 // simple-template-id's template-name in the last 2682 // component of the nested-name-specifier, 2683 // 2684 // the name is instead considered to name the constructor of 2685 // class C. 2686 // 2687 // Thus, if the template-name is actually the constructor 2688 // name, then the code is ill-formed; this interpretation is 2689 // reinforced by the NAD status of core issue 635. 2690 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next); 2691 if ((DSContext == DSC_top_level || DSContext == DSC_class) && 2692 TemplateId->Name && 2693 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { 2694 if (isConstructorDeclarator(/*Unqualified*/false)) { 2695 // The user meant this to be an out-of-line constructor 2696 // definition, but template arguments are not allowed 2697 // there. Just allow this as a constructor; we'll 2698 // complain about it later. 2699 goto DoneWithDeclSpec; 2700 } 2701 2702 // The user meant this to name a type, but it actually names 2703 // a constructor with some extraneous template 2704 // arguments. Complain, then parse it as a type as the user 2705 // intended. 2706 Diag(TemplateId->TemplateNameLoc, 2707 diag::err_out_of_line_template_id_names_constructor) 2708 << TemplateId->Name; 2709 } 2710 2711 DS.getTypeSpecScope() = SS; 2712 ConsumeToken(); // The C++ scope. 2713 assert(Tok.is(tok::annot_template_id) && 2714 "ParseOptionalCXXScopeSpecifier not working"); 2715 AnnotateTemplateIdTokenAsType(); 2716 continue; 2717 } 2718 2719 if (Next.is(tok::annot_typename)) { 2720 DS.getTypeSpecScope() = SS; 2721 ConsumeToken(); // The C++ scope. 2722 if (Tok.getAnnotationValue()) { 2723 ParsedType T = getTypeAnnotation(Tok); 2724 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, 2725 Tok.getAnnotationEndLoc(), 2726 PrevSpec, DiagID, T, Policy); 2727 if (isInvalid) 2728 break; 2729 } 2730 else 2731 DS.SetTypeSpecError(); 2732 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 2733 ConsumeToken(); // The typename 2734 } 2735 2736 if (Next.isNot(tok::identifier)) 2737 goto DoneWithDeclSpec; 2738 2739 // If we're in a context where the identifier could be a class name, 2740 // check whether this is a constructor declaration. 2741 if ((DSContext == DSC_top_level || DSContext == DSC_class) && 2742 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(), 2743 &SS)) { 2744 if (isConstructorDeclarator(/*Unqualified*/false)) 2745 goto DoneWithDeclSpec; 2746 2747 // As noted in C++ [class.qual]p2 (cited above), when the name 2748 // of the class is qualified in a context where it could name 2749 // a constructor, its a constructor name. However, we've 2750 // looked at the declarator, and the user probably meant this 2751 // to be a type. Complain that it isn't supposed to be treated 2752 // as a type, then proceed to parse it as a type. 2753 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor) 2754 << Next.getIdentifierInfo(); 2755 } 2756 2757 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(), 2758 Next.getLocation(), 2759 getCurScope(), &SS, 2760 false, false, ParsedType(), 2761 /*IsCtorOrDtorName=*/false, 2762 /*NonTrivialSourceInfo=*/true); 2763 2764 // If the referenced identifier is not a type, then this declspec is 2765 // erroneous: We already checked about that it has no type specifier, and 2766 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the 2767 // typename. 2768 if (!TypeRep) { 2769 ConsumeToken(); // Eat the scope spec so the identifier is current. 2770 ParsedAttributesWithRange Attrs(AttrFactory); 2771 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) { 2772 if (!Attrs.empty()) { 2773 AttrsLastTime = true; 2774 attrs.takeAllFrom(Attrs); 2775 } 2776 continue; 2777 } 2778 goto DoneWithDeclSpec; 2779 } 2780 2781 DS.getTypeSpecScope() = SS; 2782 ConsumeToken(); // The C++ scope. 2783 2784 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 2785 DiagID, TypeRep, Policy); 2786 if (isInvalid) 2787 break; 2788 2789 DS.SetRangeEnd(Tok.getLocation()); 2790 ConsumeToken(); // The typename. 2791 2792 continue; 2793 } 2794 2795 case tok::annot_typename: { 2796 // If we've previously seen a tag definition, we were almost surely 2797 // missing a semicolon after it. 2798 if (DS.hasTypeSpecifier() && DS.hasTagDefinition()) 2799 goto DoneWithDeclSpec; 2800 2801 if (Tok.getAnnotationValue()) { 2802 ParsedType T = getTypeAnnotation(Tok); 2803 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 2804 DiagID, T, Policy); 2805 } else 2806 DS.SetTypeSpecError(); 2807 2808 if (isInvalid) 2809 break; 2810 2811 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 2812 ConsumeToken(); // The typename 2813 2814 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 2815 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 2816 // Objective-C interface. 2817 if (Tok.is(tok::less) && getLangOpts().ObjC1) 2818 ParseObjCProtocolQualifiers(DS); 2819 2820 continue; 2821 } 2822 2823 case tok::kw___is_signed: 2824 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang 2825 // typically treats it as a trait. If we see __is_signed as it appears 2826 // in libstdc++, e.g., 2827 // 2828 // static const bool __is_signed; 2829 // 2830 // then treat __is_signed as an identifier rather than as a keyword. 2831 if (DS.getTypeSpecType() == TST_bool && 2832 DS.getTypeQualifiers() == DeclSpec::TQ_const && 2833 DS.getStorageClassSpec() == DeclSpec::SCS_static) 2834 TryKeywordIdentFallback(true); 2835 2836 // We're done with the declaration-specifiers. 2837 goto DoneWithDeclSpec; 2838 2839 // typedef-name 2840 case tok::kw___super: 2841 case tok::kw_decltype: 2842 case tok::identifier: { 2843 // This identifier can only be a typedef name if we haven't already seen 2844 // a type-specifier. Without this check we misparse: 2845 // typedef int X; struct Y { short X; }; as 'short int'. 2846 if (DS.hasTypeSpecifier()) 2847 goto DoneWithDeclSpec; 2848 2849 // In C++, check to see if this is a scope specifier like foo::bar::, if 2850 // so handle it as such. This is important for ctor parsing. 2851 if (getLangOpts().CPlusPlus) { 2852 if (TryAnnotateCXXScopeToken(EnteringContext)) { 2853 DS.SetTypeSpecError(); 2854 goto DoneWithDeclSpec; 2855 } 2856 if (!Tok.is(tok::identifier)) 2857 continue; 2858 } 2859 2860 // Check for need to substitute AltiVec keyword tokens. 2861 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid)) 2862 break; 2863 2864 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not 2865 // allow the use of a typedef name as a type specifier. 2866 if (DS.isTypeAltiVecVector()) 2867 goto DoneWithDeclSpec; 2868 2869 ParsedType TypeRep = 2870 Actions.getTypeName(*Tok.getIdentifierInfo(), 2871 Tok.getLocation(), getCurScope()); 2872 2873 // MSVC: If we weren't able to parse a default template argument, and it's 2874 // just a simple identifier, create a DependentNameType. This will allow us 2875 // to defer the name lookup to template instantiation time, as long we forge a 2876 // NestedNameSpecifier for the current context. 2877 if (!TypeRep && DSContext == DSC_template_type_arg && 2878 getLangOpts().MSVCCompat && getCurScope()->isTemplateParamScope()) { 2879 TypeRep = Actions.ActOnDelayedDefaultTemplateArg( 2880 *Tok.getIdentifierInfo(), Tok.getLocation()); 2881 } 2882 2883 // If this is not a typedef name, don't parse it as part of the declspec, 2884 // it must be an implicit int or an error. 2885 if (!TypeRep) { 2886 ParsedAttributesWithRange Attrs(AttrFactory); 2887 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) { 2888 if (!Attrs.empty()) { 2889 AttrsLastTime = true; 2890 attrs.takeAllFrom(Attrs); 2891 } 2892 continue; 2893 } 2894 goto DoneWithDeclSpec; 2895 } 2896 2897 // If we're in a context where the identifier could be a class name, 2898 // check whether this is a constructor declaration. 2899 if (getLangOpts().CPlusPlus && DSContext == DSC_class && 2900 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) && 2901 isConstructorDeclarator(/*Unqualified*/true)) 2902 goto DoneWithDeclSpec; 2903 2904 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 2905 DiagID, TypeRep, Policy); 2906 if (isInvalid) 2907 break; 2908 2909 DS.SetRangeEnd(Tok.getLocation()); 2910 ConsumeToken(); // The identifier 2911 2912 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 2913 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 2914 // Objective-C interface. 2915 if (Tok.is(tok::less) && getLangOpts().ObjC1) 2916 ParseObjCProtocolQualifiers(DS); 2917 2918 // Need to support trailing type qualifiers (e.g. "id<p> const"). 2919 // If a type specifier follows, it will be diagnosed elsewhere. 2920 continue; 2921 } 2922 2923 // type-name 2924 case tok::annot_template_id: { 2925 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 2926 if (TemplateId->Kind != TNK_Type_template) { 2927 // This template-id does not refer to a type name, so we're 2928 // done with the type-specifiers. 2929 goto DoneWithDeclSpec; 2930 } 2931 2932 // If we're in a context where the template-id could be a 2933 // constructor name or specialization, check whether this is a 2934 // constructor declaration. 2935 if (getLangOpts().CPlusPlus && DSContext == DSC_class && 2936 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) && 2937 isConstructorDeclarator(TemplateId->SS.isEmpty())) 2938 goto DoneWithDeclSpec; 2939 2940 // Turn the template-id annotation token into a type annotation 2941 // token, then try again to parse it as a type-specifier. 2942 AnnotateTemplateIdTokenAsType(); 2943 continue; 2944 } 2945 2946 // GNU attributes support. 2947 case tok::kw___attribute: 2948 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs); 2949 continue; 2950 2951 // Microsoft declspec support. 2952 case tok::kw___declspec: 2953 ParseMicrosoftDeclSpec(DS.getAttributes()); 2954 continue; 2955 2956 // Microsoft single token adornments. 2957 case tok::kw___forceinline: { 2958 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID); 2959 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 2960 SourceLocation AttrNameLoc = Tok.getLocation(); 2961 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, 2962 nullptr, 0, AttributeList::AS_Keyword); 2963 break; 2964 } 2965 2966 case tok::kw___sptr: 2967 case tok::kw___uptr: 2968 case tok::kw___ptr64: 2969 case tok::kw___ptr32: 2970 case tok::kw___w64: 2971 case tok::kw___cdecl: 2972 case tok::kw___stdcall: 2973 case tok::kw___fastcall: 2974 case tok::kw___thiscall: 2975 case tok::kw___vectorcall: 2976 case tok::kw___unaligned: 2977 ParseMicrosoftTypeAttributes(DS.getAttributes()); 2978 continue; 2979 2980 // Borland single token adornments. 2981 case tok::kw___pascal: 2982 ParseBorlandTypeAttributes(DS.getAttributes()); 2983 continue; 2984 2985 // OpenCL single token adornments. 2986 case tok::kw___kernel: 2987 ParseOpenCLAttributes(DS.getAttributes()); 2988 continue; 2989 2990 // storage-class-specifier 2991 case tok::kw_typedef: 2992 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc, 2993 PrevSpec, DiagID, Policy); 2994 isStorageClass = true; 2995 break; 2996 case tok::kw_extern: 2997 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread) 2998 Diag(Tok, diag::ext_thread_before) << "extern"; 2999 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc, 3000 PrevSpec, DiagID, Policy); 3001 isStorageClass = true; 3002 break; 3003 case tok::kw___private_extern__: 3004 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern, 3005 Loc, PrevSpec, DiagID, Policy); 3006 isStorageClass = true; 3007 break; 3008 case tok::kw_static: 3009 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread) 3010 Diag(Tok, diag::ext_thread_before) << "static"; 3011 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc, 3012 PrevSpec, DiagID, Policy); 3013 isStorageClass = true; 3014 break; 3015 case tok::kw_auto: 3016 if (getLangOpts().CPlusPlus11) { 3017 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { 3018 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc, 3019 PrevSpec, DiagID, Policy); 3020 if (!isInvalid) 3021 Diag(Tok, diag::ext_auto_storage_class) 3022 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3023 } else 3024 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, 3025 DiagID, Policy); 3026 } else 3027 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc, 3028 PrevSpec, DiagID, Policy); 3029 isStorageClass = true; 3030 break; 3031 case tok::kw_register: 3032 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc, 3033 PrevSpec, DiagID, Policy); 3034 isStorageClass = true; 3035 break; 3036 case tok::kw_mutable: 3037 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc, 3038 PrevSpec, DiagID, Policy); 3039 isStorageClass = true; 3040 break; 3041 case tok::kw___thread: 3042 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc, 3043 PrevSpec, DiagID); 3044 isStorageClass = true; 3045 break; 3046 case tok::kw_thread_local: 3047 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc, 3048 PrevSpec, DiagID); 3049 break; 3050 case tok::kw__Thread_local: 3051 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local, 3052 Loc, PrevSpec, DiagID); 3053 isStorageClass = true; 3054 break; 3055 3056 // function-specifier 3057 case tok::kw_inline: 3058 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID); 3059 break; 3060 case tok::kw_virtual: 3061 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID); 3062 break; 3063 case tok::kw_explicit: 3064 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID); 3065 break; 3066 case tok::kw__Noreturn: 3067 if (!getLangOpts().C11) 3068 Diag(Loc, diag::ext_c11_noreturn); 3069 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID); 3070 break; 3071 3072 // alignment-specifier 3073 case tok::kw__Alignas: 3074 if (!getLangOpts().C11) 3075 Diag(Tok, diag::ext_c11_alignment) << Tok.getName(); 3076 ParseAlignmentSpecifier(DS.getAttributes()); 3077 continue; 3078 3079 // friend 3080 case tok::kw_friend: 3081 if (DSContext == DSC_class) 3082 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID); 3083 else { 3084 PrevSpec = ""; // not actually used by the diagnostic 3085 DiagID = diag::err_friend_invalid_in_context; 3086 isInvalid = true; 3087 } 3088 break; 3089 3090 // Modules 3091 case tok::kw___module_private__: 3092 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID); 3093 break; 3094 3095 // constexpr 3096 case tok::kw_constexpr: 3097 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID); 3098 break; 3099 3100 // type-specifier 3101 case tok::kw_short: 3102 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, 3103 DiagID, Policy); 3104 break; 3105 case tok::kw_long: 3106 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 3107 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 3108 DiagID, Policy); 3109 else 3110 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 3111 DiagID, Policy); 3112 break; 3113 case tok::kw___int64: 3114 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 3115 DiagID, Policy); 3116 break; 3117 case tok::kw_signed: 3118 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, 3119 DiagID); 3120 break; 3121 case tok::kw_unsigned: 3122 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 3123 DiagID); 3124 break; 3125 case tok::kw__Complex: 3126 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 3127 DiagID); 3128 break; 3129 case tok::kw__Imaginary: 3130 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 3131 DiagID); 3132 break; 3133 case tok::kw_void: 3134 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, 3135 DiagID, Policy); 3136 break; 3137 case tok::kw_char: 3138 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, 3139 DiagID, Policy); 3140 break; 3141 case tok::kw_int: 3142 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, 3143 DiagID, Policy); 3144 break; 3145 case tok::kw___int128: 3146 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, 3147 DiagID, Policy); 3148 break; 3149 case tok::kw_half: 3150 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, 3151 DiagID, Policy); 3152 break; 3153 case tok::kw_float: 3154 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, 3155 DiagID, Policy); 3156 break; 3157 case tok::kw_double: 3158 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, 3159 DiagID, Policy); 3160 break; 3161 case tok::kw_wchar_t: 3162 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, 3163 DiagID, Policy); 3164 break; 3165 case tok::kw_char16_t: 3166 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, 3167 DiagID, Policy); 3168 break; 3169 case tok::kw_char32_t: 3170 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, 3171 DiagID, Policy); 3172 break; 3173 case tok::kw_bool: 3174 case tok::kw__Bool: 3175 if (Tok.is(tok::kw_bool) && 3176 DS.getTypeSpecType() != DeclSpec::TST_unspecified && 3177 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 3178 PrevSpec = ""; // Not used by the diagnostic. 3179 DiagID = diag::err_bool_redeclaration; 3180 // For better error recovery. 3181 Tok.setKind(tok::identifier); 3182 isInvalid = true; 3183 } else { 3184 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, 3185 DiagID, Policy); 3186 } 3187 break; 3188 case tok::kw__Decimal32: 3189 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 3190 DiagID, Policy); 3191 break; 3192 case tok::kw__Decimal64: 3193 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 3194 DiagID, Policy); 3195 break; 3196 case tok::kw__Decimal128: 3197 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 3198 DiagID, Policy); 3199 break; 3200 case tok::kw___vector: 3201 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy); 3202 break; 3203 case tok::kw___pixel: 3204 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy); 3205 break; 3206 case tok::kw___bool: 3207 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy); 3208 break; 3209 case tok::kw___unknown_anytype: 3210 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc, 3211 PrevSpec, DiagID, Policy); 3212 break; 3213 3214 // class-specifier: 3215 case tok::kw_class: 3216 case tok::kw_struct: 3217 case tok::kw___interface: 3218 case tok::kw_union: { 3219 tok::TokenKind Kind = Tok.getKind(); 3220 ConsumeToken(); 3221 3222 // These are attributes following class specifiers. 3223 // To produce better diagnostic, we parse them when 3224 // parsing class specifier. 3225 ParsedAttributesWithRange Attributes(AttrFactory); 3226 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS, 3227 EnteringContext, DSContext, Attributes); 3228 3229 // If there are attributes following class specifier, 3230 // take them over and handle them here. 3231 if (!Attributes.empty()) { 3232 AttrsLastTime = true; 3233 attrs.takeAllFrom(Attributes); 3234 } 3235 continue; 3236 } 3237 3238 // enum-specifier: 3239 case tok::kw_enum: 3240 ConsumeToken(); 3241 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext); 3242 continue; 3243 3244 // cv-qualifier: 3245 case tok::kw_const: 3246 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID, 3247 getLangOpts()); 3248 break; 3249 case tok::kw_volatile: 3250 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 3251 getLangOpts()); 3252 break; 3253 case tok::kw_restrict: 3254 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 3255 getLangOpts()); 3256 break; 3257 3258 // C++ typename-specifier: 3259 case tok::kw_typename: 3260 if (TryAnnotateTypeOrScopeToken()) { 3261 DS.SetTypeSpecError(); 3262 goto DoneWithDeclSpec; 3263 } 3264 if (!Tok.is(tok::kw_typename)) 3265 continue; 3266 break; 3267 3268 // GNU typeof support. 3269 case tok::kw_typeof: 3270 ParseTypeofSpecifier(DS); 3271 continue; 3272 3273 case tok::annot_decltype: 3274 ParseDecltypeSpecifier(DS); 3275 continue; 3276 3277 case tok::kw___underlying_type: 3278 ParseUnderlyingTypeSpecifier(DS); 3279 continue; 3280 3281 case tok::kw__Atomic: 3282 // C11 6.7.2.4/4: 3283 // If the _Atomic keyword is immediately followed by a left parenthesis, 3284 // it is interpreted as a type specifier (with a type name), not as a 3285 // type qualifier. 3286 if (NextToken().is(tok::l_paren)) { 3287 ParseAtomicSpecifier(DS); 3288 continue; 3289 } 3290 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID, 3291 getLangOpts()); 3292 break; 3293 3294 // OpenCL qualifiers: 3295 case tok::kw___generic: 3296 // generic address space is introduced only in OpenCL v2.0 3297 // see OpenCL C Spec v2.0 s6.5.5 3298 if (Actions.getLangOpts().OpenCLVersion < 200) { 3299 DiagID = diag::err_opencl_unknown_type_specifier; 3300 PrevSpec = Tok.getIdentifierInfo()->getNameStart(); 3301 isInvalid = true; 3302 break; 3303 }; 3304 case tok::kw___private: 3305 case tok::kw___global: 3306 case tok::kw___local: 3307 case tok::kw___constant: 3308 case tok::kw___read_only: 3309 case tok::kw___write_only: 3310 case tok::kw___read_write: 3311 ParseOpenCLQualifiers(DS.getAttributes()); 3312 break; 3313 3314 case tok::less: 3315 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for 3316 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous, 3317 // but we support it. 3318 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1) 3319 goto DoneWithDeclSpec; 3320 3321 if (!ParseObjCProtocolQualifiers(DS)) 3322 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id) 3323 << FixItHint::CreateInsertion(Loc, "id") 3324 << SourceRange(Loc, DS.getSourceRange().getEnd()); 3325 3326 // Need to support trailing type qualifiers (e.g. "id<p> const"). 3327 // If a type specifier follows, it will be diagnosed elsewhere. 3328 continue; 3329 } 3330 // If the specifier wasn't legal, issue a diagnostic. 3331 if (isInvalid) { 3332 assert(PrevSpec && "Method did not return previous specifier!"); 3333 assert(DiagID); 3334 3335 if (DiagID == diag::ext_duplicate_declspec) 3336 Diag(Tok, DiagID) 3337 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation()); 3338 else if (DiagID == diag::err_opencl_unknown_type_specifier) 3339 Diag(Tok, DiagID) << PrevSpec << isStorageClass; 3340 else 3341 Diag(Tok, DiagID) << PrevSpec; 3342 } 3343 3344 DS.SetRangeEnd(Tok.getLocation()); 3345 if (DiagID != diag::err_bool_redeclaration) 3346 ConsumeToken(); 3347 3348 AttrsLastTime = false; 3349 } 3350} 3351 3352/// ParseStructDeclaration - Parse a struct declaration without the terminating 3353/// semicolon. 3354/// 3355/// struct-declaration: 3356/// specifier-qualifier-list struct-declarator-list 3357/// [GNU] __extension__ struct-declaration 3358/// [GNU] specifier-qualifier-list 3359/// struct-declarator-list: 3360/// struct-declarator 3361/// struct-declarator-list ',' struct-declarator 3362/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator 3363/// struct-declarator: 3364/// declarator 3365/// [GNU] declarator attributes[opt] 3366/// declarator[opt] ':' constant-expression 3367/// [GNU] declarator[opt] ':' constant-expression attributes[opt] 3368/// 3369void Parser::ParseStructDeclaration( 3370 ParsingDeclSpec &DS, 3371 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) { 3372 3373 if (Tok.is(tok::kw___extension__)) { 3374 // __extension__ silences extension warnings in the subexpression. 3375 ExtensionRAIIObject O(Diags); // Use RAII to do this. 3376 ConsumeToken(); 3377 return ParseStructDeclaration(DS, FieldsCallback); 3378 } 3379 3380 // Parse the common specifier-qualifiers-list piece. 3381 ParseSpecifierQualifierList(DS); 3382 3383 // If there are no declarators, this is a free-standing declaration 3384 // specifier. Let the actions module cope with it. 3385 if (Tok.is(tok::semi)) { 3386 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, 3387 DS); 3388 DS.complete(TheDecl); 3389 return; 3390 } 3391 3392 // Read struct-declarators until we find the semicolon. 3393 bool FirstDeclarator = true; 3394 SourceLocation CommaLoc; 3395 while (1) { 3396 ParsingFieldDeclarator DeclaratorInfo(*this, DS); 3397 DeclaratorInfo.D.setCommaLoc(CommaLoc); 3398 3399 // Attributes are only allowed here on successive declarators. 3400 if (!FirstDeclarator) 3401 MaybeParseGNUAttributes(DeclaratorInfo.D); 3402 3403 /// struct-declarator: declarator 3404 /// struct-declarator: declarator[opt] ':' constant-expression 3405 if (Tok.isNot(tok::colon)) { 3406 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 3407 ColonProtectionRAIIObject X(*this); 3408 ParseDeclarator(DeclaratorInfo.D); 3409 } else 3410 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation()); 3411 3412 if (TryConsumeToken(tok::colon)) { 3413 ExprResult Res(ParseConstantExpression()); 3414 if (Res.isInvalid()) 3415 SkipUntil(tok::semi, StopBeforeMatch); 3416 else 3417 DeclaratorInfo.BitfieldSize = Res.get(); 3418 } 3419 3420 // If attributes exist after the declarator, parse them. 3421 MaybeParseGNUAttributes(DeclaratorInfo.D); 3422 3423 // We're done with this declarator; invoke the callback. 3424 FieldsCallback(DeclaratorInfo); 3425 3426 // If we don't have a comma, it is either the end of the list (a ';') 3427 // or an error, bail out. 3428 if (!TryConsumeToken(tok::comma, CommaLoc)) 3429 return; 3430 3431 FirstDeclarator = false; 3432 } 3433} 3434 3435/// ParseStructUnionBody 3436/// struct-contents: 3437/// struct-declaration-list 3438/// [EXT] empty 3439/// [GNU] "struct-declaration-list" without terminatoring ';' 3440/// struct-declaration-list: 3441/// struct-declaration 3442/// struct-declaration-list struct-declaration 3443/// [OBC] '@' 'defs' '(' class-name ')' 3444/// 3445void Parser::ParseStructUnionBody(SourceLocation RecordLoc, 3446 unsigned TagType, Decl *TagDecl) { 3447 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 3448 "parsing struct/union body"); 3449 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported"); 3450 3451 BalancedDelimiterTracker T(*this, tok::l_brace); 3452 if (T.consumeOpen()) 3453 return; 3454 3455 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); 3456 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 3457 3458 SmallVector<Decl *, 32> FieldDecls; 3459 3460 // While we still have something to read, read the declarations in the struct. 3461 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { 3462 // Each iteration of this loop reads one struct-declaration. 3463 3464 // Check for extraneous top-level semicolon. 3465 if (Tok.is(tok::semi)) { 3466 ConsumeExtraSemi(InsideStruct, TagType); 3467 continue; 3468 } 3469 3470 // Parse _Static_assert declaration. 3471 if (Tok.is(tok::kw__Static_assert)) { 3472 SourceLocation DeclEnd; 3473 ParseStaticAssertDeclaration(DeclEnd); 3474 continue; 3475 } 3476 3477 if (Tok.is(tok::annot_pragma_pack)) { 3478 HandlePragmaPack(); 3479 continue; 3480 } 3481 3482 if (Tok.is(tok::annot_pragma_align)) { 3483 HandlePragmaAlign(); 3484 continue; 3485 } 3486 3487 if (!Tok.is(tok::at)) { 3488 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) { 3489 // Install the declarator into the current TagDecl. 3490 Decl *Field = 3491 Actions.ActOnField(getCurScope(), TagDecl, 3492 FD.D.getDeclSpec().getSourceRange().getBegin(), 3493 FD.D, FD.BitfieldSize); 3494 FieldDecls.push_back(Field); 3495 FD.complete(Field); 3496 }; 3497 3498 // Parse all the comma separated declarators. 3499 ParsingDeclSpec DS(*this); 3500 ParseStructDeclaration(DS, CFieldCallback); 3501 } else { // Handle @defs 3502 ConsumeToken(); 3503 if (!Tok.isObjCAtKeyword(tok::objc_defs)) { 3504 Diag(Tok, diag::err_unexpected_at); 3505 SkipUntil(tok::semi); 3506 continue; 3507 } 3508 ConsumeToken(); 3509 ExpectAndConsume(tok::l_paren); 3510 if (!Tok.is(tok::identifier)) { 3511 Diag(Tok, diag::err_expected) << tok::identifier; 3512 SkipUntil(tok::semi); 3513 continue; 3514 } 3515 SmallVector<Decl *, 16> Fields; 3516 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(), 3517 Tok.getIdentifierInfo(), Fields); 3518 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); 3519 ConsumeToken(); 3520 ExpectAndConsume(tok::r_paren); 3521 } 3522 3523 if (TryConsumeToken(tok::semi)) 3524 continue; 3525 3526 if (Tok.is(tok::r_brace)) { 3527 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list); 3528 break; 3529 } 3530 3531 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); 3532 // Skip to end of block or statement to avoid ext-warning on extra ';'. 3533 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 3534 // If we stopped at a ';', eat it. 3535 TryConsumeToken(tok::semi); 3536 } 3537 3538 T.consumeClose(); 3539 3540 ParsedAttributes attrs(AttrFactory); 3541 // If attributes exist after struct contents, parse them. 3542 MaybeParseGNUAttributes(attrs); 3543 3544 Actions.ActOnFields(getCurScope(), 3545 RecordLoc, TagDecl, FieldDecls, 3546 T.getOpenLocation(), T.getCloseLocation(), 3547 attrs.getList()); 3548 StructScope.Exit(); 3549 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, 3550 T.getCloseLocation()); 3551} 3552 3553/// ParseEnumSpecifier 3554/// enum-specifier: [C99 6.7.2.2] 3555/// 'enum' identifier[opt] '{' enumerator-list '}' 3556///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' 3557/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] 3558/// '}' attributes[opt] 3559/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt] 3560/// '}' 3561/// 'enum' identifier 3562/// [GNU] 'enum' attributes[opt] identifier 3563/// 3564/// [C++11] enum-head '{' enumerator-list[opt] '}' 3565/// [C++11] enum-head '{' enumerator-list ',' '}' 3566/// 3567/// enum-head: [C++11] 3568/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt] 3569/// enum-key attribute-specifier-seq[opt] nested-name-specifier 3570/// identifier enum-base[opt] 3571/// 3572/// enum-key: [C++11] 3573/// 'enum' 3574/// 'enum' 'class' 3575/// 'enum' 'struct' 3576/// 3577/// enum-base: [C++11] 3578/// ':' type-specifier-seq 3579/// 3580/// [C++] elaborated-type-specifier: 3581/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier 3582/// 3583void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, 3584 const ParsedTemplateInfo &TemplateInfo, 3585 AccessSpecifier AS, DeclSpecContext DSC) { 3586 // Parse the tag portion of this. 3587 if (Tok.is(tok::code_completion)) { 3588 // Code completion for an enum name. 3589 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum); 3590 return cutOffParsing(); 3591 } 3592 3593 // If attributes exist after tag, parse them. 3594 ParsedAttributesWithRange attrs(AttrFactory); 3595 MaybeParseGNUAttributes(attrs); 3596 MaybeParseCXX11Attributes(attrs); 3597 3598 // If declspecs exist after tag, parse them. 3599 while (Tok.is(tok::kw___declspec)) 3600 ParseMicrosoftDeclSpec(attrs); 3601 3602 SourceLocation ScopedEnumKWLoc; 3603 bool IsScopedUsingClassTag = false; 3604 3605 // In C++11, recognize 'enum class' and 'enum struct'. 3606 if (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct)) { 3607 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum 3608 : diag::ext_scoped_enum); 3609 IsScopedUsingClassTag = Tok.is(tok::kw_class); 3610 ScopedEnumKWLoc = ConsumeToken(); 3611 3612 // Attributes are not allowed between these keywords. Diagnose, 3613 // but then just treat them like they appeared in the right place. 3614 ProhibitAttributes(attrs); 3615 3616 // They are allowed afterwards, though. 3617 MaybeParseGNUAttributes(attrs); 3618 MaybeParseCXX11Attributes(attrs); 3619 while (Tok.is(tok::kw___declspec)) 3620 ParseMicrosoftDeclSpec(attrs); 3621 } 3622 3623 // C++11 [temp.explicit]p12: 3624 // The usual access controls do not apply to names used to specify 3625 // explicit instantiations. 3626 // We extend this to also cover explicit specializations. Note that 3627 // we don't suppress if this turns out to be an elaborated type 3628 // specifier. 3629 bool shouldDelayDiagsInTag = 3630 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation || 3631 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization); 3632 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag); 3633 3634 // Enum definitions should not be parsed in a trailing-return-type. 3635 bool AllowDeclaration = DSC != DSC_trailing; 3636 3637 bool AllowFixedUnderlyingType = AllowDeclaration && 3638 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt || 3639 getLangOpts().ObjC2); 3640 3641 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3642 if (getLangOpts().CPlusPlus) { 3643 // "enum foo : bar;" is not a potential typo for "enum foo::bar;" 3644 // if a fixed underlying type is allowed. 3645 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType); 3646 3647 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 3648 /*EnteringContext=*/true)) 3649 return; 3650 3651 if (SS.isSet() && Tok.isNot(tok::identifier)) { 3652 Diag(Tok, diag::err_expected) << tok::identifier; 3653 if (Tok.isNot(tok::l_brace)) { 3654 // Has no name and is not a definition. 3655 // Skip the rest of this declarator, up until the comma or semicolon. 3656 SkipUntil(tok::comma, StopAtSemi); 3657 return; 3658 } 3659 } 3660 } 3661 3662 // Must have either 'enum name' or 'enum {...}'. 3663 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) && 3664 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) { 3665 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace; 3666 3667 // Skip the rest of this declarator, up until the comma or semicolon. 3668 SkipUntil(tok::comma, StopAtSemi); 3669 return; 3670 } 3671 3672 // If an identifier is present, consume and remember it. 3673 IdentifierInfo *Name = nullptr; 3674 SourceLocation NameLoc; 3675 if (Tok.is(tok::identifier)) { 3676 Name = Tok.getIdentifierInfo(); 3677 NameLoc = ConsumeToken(); 3678 } 3679 3680 if (!Name && ScopedEnumKWLoc.isValid()) { 3681 // C++0x 7.2p2: The optional identifier shall not be omitted in the 3682 // declaration of a scoped enumeration. 3683 Diag(Tok, diag::err_scoped_enum_missing_identifier); 3684 ScopedEnumKWLoc = SourceLocation(); 3685 IsScopedUsingClassTag = false; 3686 } 3687 3688 // Okay, end the suppression area. We'll decide whether to emit the 3689 // diagnostics in a second. 3690 if (shouldDelayDiagsInTag) 3691 diagsFromTag.done(); 3692 3693 TypeResult BaseType; 3694 3695 // Parse the fixed underlying type. 3696 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope; 3697 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) { 3698 bool PossibleBitfield = false; 3699 if (CanBeBitfield) { 3700 // If we're in class scope, this can either be an enum declaration with 3701 // an underlying type, or a declaration of a bitfield member. We try to 3702 // use a simple disambiguation scheme first to catch the common cases 3703 // (integer literal, sizeof); if it's still ambiguous, we then consider 3704 // anything that's a simple-type-specifier followed by '(' as an 3705 // expression. This suffices because function types are not valid 3706 // underlying types anyway. 3707 EnterExpressionEvaluationContext Unevaluated(Actions, 3708 Sema::ConstantEvaluated); 3709 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind()); 3710 // If the next token starts an expression, we know we're parsing a 3711 // bit-field. This is the common case. 3712 if (TPR == TPResult::True) 3713 PossibleBitfield = true; 3714 // If the next token starts a type-specifier-seq, it may be either a 3715 // a fixed underlying type or the start of a function-style cast in C++; 3716 // lookahead one more token to see if it's obvious that we have a 3717 // fixed underlying type. 3718 else if (TPR == TPResult::False && 3719 GetLookAheadToken(2).getKind() == tok::semi) { 3720 // Consume the ':'. 3721 ConsumeToken(); 3722 } else { 3723 // We have the start of a type-specifier-seq, so we have to perform 3724 // tentative parsing to determine whether we have an expression or a 3725 // type. 3726 TentativeParsingAction TPA(*this); 3727 3728 // Consume the ':'. 3729 ConsumeToken(); 3730 3731 // If we see a type specifier followed by an open-brace, we have an 3732 // ambiguity between an underlying type and a C++11 braced 3733 // function-style cast. Resolve this by always treating it as an 3734 // underlying type. 3735 // FIXME: The standard is not entirely clear on how to disambiguate in 3736 // this case. 3737 if ((getLangOpts().CPlusPlus && 3738 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) || 3739 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) { 3740 // We'll parse this as a bitfield later. 3741 PossibleBitfield = true; 3742 TPA.Revert(); 3743 } else { 3744 // We have a type-specifier-seq. 3745 TPA.Commit(); 3746 } 3747 } 3748 } else { 3749 // Consume the ':'. 3750 ConsumeToken(); 3751 } 3752 3753 if (!PossibleBitfield) { 3754 SourceRange Range; 3755 BaseType = ParseTypeName(&Range); 3756 3757 if (getLangOpts().CPlusPlus11) { 3758 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type); 3759 } else if (!getLangOpts().ObjC2) { 3760 if (getLangOpts().CPlusPlus) 3761 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range; 3762 else 3763 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range; 3764 } 3765 } 3766 } 3767 3768 // There are four options here. If we have 'friend enum foo;' then this is a 3769 // friend declaration, and cannot have an accompanying definition. If we have 3770 // 'enum foo;', then this is a forward declaration. If we have 3771 // 'enum foo {...' then this is a definition. Otherwise we have something 3772 // like 'enum foo xyz', a reference. 3773 // 3774 // This is needed to handle stuff like this right (C99 6.7.2.3p11): 3775 // enum foo {..}; void bar() { enum foo; } <- new foo in bar. 3776 // enum foo {..}; void bar() { enum foo x; } <- use of old foo. 3777 // 3778 Sema::TagUseKind TUK; 3779 if (!AllowDeclaration) { 3780 TUK = Sema::TUK_Reference; 3781 } else if (Tok.is(tok::l_brace)) { 3782 if (DS.isFriendSpecified()) { 3783 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type) 3784 << SourceRange(DS.getFriendSpecLoc()); 3785 ConsumeBrace(); 3786 SkipUntil(tok::r_brace, StopAtSemi); 3787 TUK = Sema::TUK_Friend; 3788 } else { 3789 TUK = Sema::TUK_Definition; 3790 } 3791 } else if (!isTypeSpecifier(DSC) && 3792 (Tok.is(tok::semi) || 3793 (Tok.isAtStartOfLine() && 3794 !isValidAfterTypeSpecifier(CanBeBitfield)))) { 3795 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration; 3796 if (Tok.isNot(tok::semi)) { 3797 // A semicolon was missing after this declaration. Diagnose and recover. 3798 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum"); 3799 PP.EnterToken(Tok); 3800 Tok.setKind(tok::semi); 3801 } 3802 } else { 3803 TUK = Sema::TUK_Reference; 3804 } 3805 3806 // If this is an elaborated type specifier, and we delayed 3807 // diagnostics before, just merge them into the current pool. 3808 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) { 3809 diagsFromTag.redelay(); 3810 } 3811 3812 MultiTemplateParamsArg TParams; 3813 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 3814 TUK != Sema::TUK_Reference) { 3815 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) { 3816 // Skip the rest of this declarator, up until the comma or semicolon. 3817 Diag(Tok, diag::err_enum_template); 3818 SkipUntil(tok::comma, StopAtSemi); 3819 return; 3820 } 3821 3822 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { 3823 // Enumerations can't be explicitly instantiated. 3824 DS.SetTypeSpecError(); 3825 Diag(StartLoc, diag::err_explicit_instantiation_enum); 3826 return; 3827 } 3828 3829 assert(TemplateInfo.TemplateParams && "no template parameters"); 3830 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(), 3831 TemplateInfo.TemplateParams->size()); 3832 } 3833 3834 if (TUK == Sema::TUK_Reference) 3835 ProhibitAttributes(attrs); 3836 3837 if (!Name && TUK != Sema::TUK_Definition) { 3838 Diag(Tok, diag::err_enumerator_unnamed_no_def); 3839 3840 // Skip the rest of this declarator, up until the comma or semicolon. 3841 SkipUntil(tok::comma, StopAtSemi); 3842 return; 3843 } 3844 3845 bool Owned = false; 3846 bool IsDependent = false; 3847 const char *PrevSpec = nullptr; 3848 unsigned DiagID; 3849 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, 3850 StartLoc, SS, Name, NameLoc, attrs.getList(), 3851 AS, DS.getModulePrivateSpecLoc(), TParams, 3852 Owned, IsDependent, ScopedEnumKWLoc, 3853 IsScopedUsingClassTag, BaseType, 3854 DSC == DSC_type_specifier); 3855 3856 if (IsDependent) { 3857 // This enum has a dependent nested-name-specifier. Handle it as a 3858 // dependent tag. 3859 if (!Name) { 3860 DS.SetTypeSpecError(); 3861 Diag(Tok, diag::err_expected_type_name_after_typename); 3862 return; 3863 } 3864 3865 TypeResult Type = Actions.ActOnDependentTag( 3866 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc); 3867 if (Type.isInvalid()) { 3868 DS.SetTypeSpecError(); 3869 return; 3870 } 3871 3872 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, 3873 NameLoc.isValid() ? NameLoc : StartLoc, 3874 PrevSpec, DiagID, Type.get(), 3875 Actions.getASTContext().getPrintingPolicy())) 3876 Diag(StartLoc, DiagID) << PrevSpec; 3877 3878 return; 3879 } 3880 3881 if (!TagDecl) { 3882 // The action failed to produce an enumeration tag. If this is a 3883 // definition, consume the entire definition. 3884 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) { 3885 ConsumeBrace(); 3886 SkipUntil(tok::r_brace, StopAtSemi); 3887 } 3888 3889 DS.SetTypeSpecError(); 3890 return; 3891 } 3892 3893 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) 3894 ParseEnumBody(StartLoc, TagDecl); 3895 3896 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, 3897 NameLoc.isValid() ? NameLoc : StartLoc, 3898 PrevSpec, DiagID, TagDecl, Owned, 3899 Actions.getASTContext().getPrintingPolicy())) 3900 Diag(StartLoc, DiagID) << PrevSpec; 3901} 3902 3903/// ParseEnumBody - Parse a {} enclosed enumerator-list. 3904/// enumerator-list: 3905/// enumerator 3906/// enumerator-list ',' enumerator 3907/// enumerator: 3908/// enumeration-constant attributes[opt] 3909/// enumeration-constant attributes[opt] '=' constant-expression 3910/// enumeration-constant: 3911/// identifier 3912/// 3913void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) { 3914 // Enter the scope of the enum body and start the definition. 3915 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope); 3916 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl); 3917 3918 BalancedDelimiterTracker T(*this, tok::l_brace); 3919 T.consumeOpen(); 3920 3921 // C does not allow an empty enumerator-list, C++ does [dcl.enum]. 3922 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) 3923 Diag(Tok, diag::error_empty_enum); 3924 3925 SmallVector<Decl *, 32> EnumConstantDecls; 3926 3927 Decl *LastEnumConstDecl = nullptr; 3928 3929 // Parse the enumerator-list. 3930 while (Tok.isNot(tok::r_brace)) { 3931 // Parse enumerator. If failed, try skipping till the start of the next 3932 // enumerator definition. 3933 if (Tok.isNot(tok::identifier)) { 3934 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; 3935 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) && 3936 TryConsumeToken(tok::comma)) 3937 continue; 3938 break; 3939 } 3940 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 3941 SourceLocation IdentLoc = ConsumeToken(); 3942 3943 // If attributes exist after the enumerator, parse them. 3944 ParsedAttributesWithRange attrs(AttrFactory); 3945 MaybeParseGNUAttributes(attrs); 3946 ProhibitAttributes(attrs); // GNU-style attributes are prohibited. 3947 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) { 3948 if (!getLangOpts().CPlusPlus1z) 3949 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute) 3950 << 1 /*enumerator*/; 3951 ParseCXX11Attributes(attrs); 3952 } 3953 3954 SourceLocation EqualLoc; 3955 ExprResult AssignedVal; 3956 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent); 3957 3958 if (TryConsumeToken(tok::equal, EqualLoc)) { 3959 AssignedVal = ParseConstantExpression(); 3960 if (AssignedVal.isInvalid()) 3961 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch); 3962 } 3963 3964 // Install the enumerator constant into EnumDecl. 3965 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl, 3966 LastEnumConstDecl, 3967 IdentLoc, Ident, 3968 attrs.getList(), EqualLoc, 3969 AssignedVal.get()); 3970 PD.complete(EnumConstDecl); 3971 3972 EnumConstantDecls.push_back(EnumConstDecl); 3973 LastEnumConstDecl = EnumConstDecl; 3974 3975 if (Tok.is(tok::identifier)) { 3976 // We're missing a comma between enumerators. 3977 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); 3978 Diag(Loc, diag::err_enumerator_list_missing_comma) 3979 << FixItHint::CreateInsertion(Loc, ", "); 3980 continue; 3981 } 3982 3983 // Emumerator definition must be finished, only comma or r_brace are 3984 // allowed here. 3985 SourceLocation CommaLoc; 3986 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) { 3987 if (EqualLoc.isValid()) 3988 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace 3989 << tok::comma; 3990 else 3991 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator); 3992 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) { 3993 if (TryConsumeToken(tok::comma, CommaLoc)) 3994 continue; 3995 } else { 3996 break; 3997 } 3998 } 3999 4000 // If comma is followed by r_brace, emit appropriate warning. 4001 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) { 4002 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) 4003 Diag(CommaLoc, getLangOpts().CPlusPlus ? 4004 diag::ext_enumerator_list_comma_cxx : 4005 diag::ext_enumerator_list_comma_c) 4006 << FixItHint::CreateRemoval(CommaLoc); 4007 else if (getLangOpts().CPlusPlus11) 4008 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma) 4009 << FixItHint::CreateRemoval(CommaLoc); 4010 break; 4011 } 4012 } 4013 4014 // Eat the }. 4015 T.consumeClose(); 4016 4017 // If attributes exist after the identifier list, parse them. 4018 ParsedAttributes attrs(AttrFactory); 4019 MaybeParseGNUAttributes(attrs); 4020 4021 Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(), 4022 EnumDecl, EnumConstantDecls, 4023 getCurScope(), 4024 attrs.getList()); 4025 4026 EnumScope.Exit(); 4027 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, 4028 T.getCloseLocation()); 4029 4030 // The next token must be valid after an enum definition. If not, a ';' 4031 // was probably forgotten. 4032 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope; 4033 if (!isValidAfterTypeSpecifier(CanBeBitfield)) { 4034 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum"); 4035 // Push this token back into the preprocessor and change our current token 4036 // to ';' so that the rest of the code recovers as though there were an 4037 // ';' after the definition. 4038 PP.EnterToken(Tok); 4039 Tok.setKind(tok::semi); 4040 } 4041} 4042 4043/// isTypeSpecifierQualifier - Return true if the current token could be the 4044/// start of a type-qualifier-list. 4045bool Parser::isTypeQualifier() const { 4046 switch (Tok.getKind()) { 4047 default: return false; 4048 // type-qualifier 4049 case tok::kw_const: 4050 case tok::kw_volatile: 4051 case tok::kw_restrict: 4052 case tok::kw___private: 4053 case tok::kw___local: 4054 case tok::kw___global: 4055 case tok::kw___constant: 4056 case tok::kw___generic: 4057 case tok::kw___read_only: 4058 case tok::kw___read_write: 4059 case tok::kw___write_only: 4060 return true; 4061 } 4062} 4063 4064/// isKnownToBeTypeSpecifier - Return true if we know that the specified token 4065/// is definitely a type-specifier. Return false if it isn't part of a type 4066/// specifier or if we're not sure. 4067bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const { 4068 switch (Tok.getKind()) { 4069 default: return false; 4070 // type-specifiers 4071 case tok::kw_short: 4072 case tok::kw_long: 4073 case tok::kw___int64: 4074 case tok::kw___int128: 4075 case tok::kw_signed: 4076 case tok::kw_unsigned: 4077 case tok::kw__Complex: 4078 case tok::kw__Imaginary: 4079 case tok::kw_void: 4080 case tok::kw_char: 4081 case tok::kw_wchar_t: 4082 case tok::kw_char16_t: 4083 case tok::kw_char32_t: 4084 case tok::kw_int: 4085 case tok::kw_half: 4086 case tok::kw_float: 4087 case tok::kw_double: 4088 case tok::kw_bool: 4089 case tok::kw__Bool: 4090 case tok::kw__Decimal32: 4091 case tok::kw__Decimal64: 4092 case tok::kw__Decimal128: 4093 case tok::kw___vector: 4094 4095 // struct-or-union-specifier (C99) or class-specifier (C++) 4096 case tok::kw_class: 4097 case tok::kw_struct: 4098 case tok::kw___interface: 4099 case tok::kw_union: 4100 // enum-specifier 4101 case tok::kw_enum: 4102 4103 // typedef-name 4104 case tok::annot_typename: 4105 return true; 4106 } 4107} 4108 4109/// isTypeSpecifierQualifier - Return true if the current token could be the 4110/// start of a specifier-qualifier-list. 4111bool Parser::isTypeSpecifierQualifier() { 4112 switch (Tok.getKind()) { 4113 default: return false; 4114 4115 case tok::identifier: // foo::bar 4116 if (TryAltiVecVectorToken()) 4117 return true; 4118 // Fall through. 4119 case tok::kw_typename: // typename T::type 4120 // Annotate typenames and C++ scope specifiers. If we get one, just 4121 // recurse to handle whatever we get. 4122 if (TryAnnotateTypeOrScopeToken()) 4123 return true; 4124 if (Tok.is(tok::identifier)) 4125 return false; 4126 return isTypeSpecifierQualifier(); 4127 4128 case tok::coloncolon: // ::foo::bar 4129 if (NextToken().is(tok::kw_new) || // ::new 4130 NextToken().is(tok::kw_delete)) // ::delete 4131 return false; 4132 4133 if (TryAnnotateTypeOrScopeToken()) 4134 return true; 4135 return isTypeSpecifierQualifier(); 4136 4137 // GNU attributes support. 4138 case tok::kw___attribute: 4139 // GNU typeof support. 4140 case tok::kw_typeof: 4141 4142 // type-specifiers 4143 case tok::kw_short: 4144 case tok::kw_long: 4145 case tok::kw___int64: 4146 case tok::kw___int128: 4147 case tok::kw_signed: 4148 case tok::kw_unsigned: 4149 case tok::kw__Complex: 4150 case tok::kw__Imaginary: 4151 case tok::kw_void: 4152 case tok::kw_char: 4153 case tok::kw_wchar_t: 4154 case tok::kw_char16_t: 4155 case tok::kw_char32_t: 4156 case tok::kw_int: 4157 case tok::kw_half: 4158 case tok::kw_float: 4159 case tok::kw_double: 4160 case tok::kw_bool: 4161 case tok::kw__Bool: 4162 case tok::kw__Decimal32: 4163 case tok::kw__Decimal64: 4164 case tok::kw__Decimal128: 4165 case tok::kw___vector: 4166 4167 // struct-or-union-specifier (C99) or class-specifier (C++) 4168 case tok::kw_class: 4169 case tok::kw_struct: 4170 case tok::kw___interface: 4171 case tok::kw_union: 4172 // enum-specifier 4173 case tok::kw_enum: 4174 4175 // type-qualifier 4176 case tok::kw_const: 4177 case tok::kw_volatile: 4178 case tok::kw_restrict: 4179 4180 // Debugger support. 4181 case tok::kw___unknown_anytype: 4182 4183 // typedef-name 4184 case tok::annot_typename: 4185 return true; 4186 4187 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 4188 case tok::less: 4189 return getLangOpts().ObjC1; 4190 4191 case tok::kw___cdecl: 4192 case tok::kw___stdcall: 4193 case tok::kw___fastcall: 4194 case tok::kw___thiscall: 4195 case tok::kw___vectorcall: 4196 case tok::kw___w64: 4197 case tok::kw___ptr64: 4198 case tok::kw___ptr32: 4199 case tok::kw___pascal: 4200 case tok::kw___unaligned: 4201 4202 case tok::kw___private: 4203 case tok::kw___local: 4204 case tok::kw___global: 4205 case tok::kw___constant: 4206 case tok::kw___generic: 4207 case tok::kw___read_only: 4208 case tok::kw___read_write: 4209 case tok::kw___write_only: 4210 4211 return true; 4212 4213 // C11 _Atomic 4214 case tok::kw__Atomic: 4215 return true; 4216 } 4217} 4218 4219/// isDeclarationSpecifier() - Return true if the current token is part of a 4220/// declaration specifier. 4221/// 4222/// \param DisambiguatingWithExpression True to indicate that the purpose of 4223/// this check is to disambiguate between an expression and a declaration. 4224bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) { 4225 switch (Tok.getKind()) { 4226 default: return false; 4227 4228 case tok::identifier: // foo::bar 4229 // Unfortunate hack to support "Class.factoryMethod" notation. 4230 if (getLangOpts().ObjC1 && NextToken().is(tok::period)) 4231 return false; 4232 if (TryAltiVecVectorToken()) 4233 return true; 4234 // Fall through. 4235 case tok::kw_decltype: // decltype(T())::type 4236 case tok::kw_typename: // typename T::type 4237 // Annotate typenames and C++ scope specifiers. If we get one, just 4238 // recurse to handle whatever we get. 4239 if (TryAnnotateTypeOrScopeToken()) 4240 return true; 4241 if (Tok.is(tok::identifier)) 4242 return false; 4243 4244 // If we're in Objective-C and we have an Objective-C class type followed 4245 // by an identifier and then either ':' or ']', in a place where an 4246 // expression is permitted, then this is probably a class message send 4247 // missing the initial '['. In this case, we won't consider this to be 4248 // the start of a declaration. 4249 if (DisambiguatingWithExpression && 4250 isStartOfObjCClassMessageMissingOpenBracket()) 4251 return false; 4252 4253 return isDeclarationSpecifier(); 4254 4255 case tok::coloncolon: // ::foo::bar 4256 if (NextToken().is(tok::kw_new) || // ::new 4257 NextToken().is(tok::kw_delete)) // ::delete 4258 return false; 4259 4260 // Annotate typenames and C++ scope specifiers. If we get one, just 4261 // recurse to handle whatever we get. 4262 if (TryAnnotateTypeOrScopeToken()) 4263 return true; 4264 return isDeclarationSpecifier(); 4265 4266 // storage-class-specifier 4267 case tok::kw_typedef: 4268 case tok::kw_extern: 4269 case tok::kw___private_extern__: 4270 case tok::kw_static: 4271 case tok::kw_auto: 4272 case tok::kw_register: 4273 case tok::kw___thread: 4274 case tok::kw_thread_local: 4275 case tok::kw__Thread_local: 4276 4277 // Modules 4278 case tok::kw___module_private__: 4279 4280 // Debugger support 4281 case tok::kw___unknown_anytype: 4282 4283 // type-specifiers 4284 case tok::kw_short: 4285 case tok::kw_long: 4286 case tok::kw___int64: 4287 case tok::kw___int128: 4288 case tok::kw_signed: 4289 case tok::kw_unsigned: 4290 case tok::kw__Complex: 4291 case tok::kw__Imaginary: 4292 case tok::kw_void: 4293 case tok::kw_char: 4294 case tok::kw_wchar_t: 4295 case tok::kw_char16_t: 4296 case tok::kw_char32_t: 4297 4298 case tok::kw_int: 4299 case tok::kw_half: 4300 case tok::kw_float: 4301 case tok::kw_double: 4302 case tok::kw_bool: 4303 case tok::kw__Bool: 4304 case tok::kw__Decimal32: 4305 case tok::kw__Decimal64: 4306 case tok::kw__Decimal128: 4307 case tok::kw___vector: 4308 4309 // struct-or-union-specifier (C99) or class-specifier (C++) 4310 case tok::kw_class: 4311 case tok::kw_struct: 4312 case tok::kw_union: 4313 case tok::kw___interface: 4314 // enum-specifier 4315 case tok::kw_enum: 4316 4317 // type-qualifier 4318 case tok::kw_const: 4319 case tok::kw_volatile: 4320 case tok::kw_restrict: 4321 4322 // function-specifier 4323 case tok::kw_inline: 4324 case tok::kw_virtual: 4325 case tok::kw_explicit: 4326 case tok::kw__Noreturn: 4327 4328 // alignment-specifier 4329 case tok::kw__Alignas: 4330 4331 // friend keyword. 4332 case tok::kw_friend: 4333 4334 // static_assert-declaration 4335 case tok::kw__Static_assert: 4336 4337 // GNU typeof support. 4338 case tok::kw_typeof: 4339 4340 // GNU attributes. 4341 case tok::kw___attribute: 4342 4343 // C++11 decltype and constexpr. 4344 case tok::annot_decltype: 4345 case tok::kw_constexpr: 4346 4347 // C11 _Atomic 4348 case tok::kw__Atomic: 4349 return true; 4350 4351 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 4352 case tok::less: 4353 return getLangOpts().ObjC1; 4354 4355 // typedef-name 4356 case tok::annot_typename: 4357 return !DisambiguatingWithExpression || 4358 !isStartOfObjCClassMessageMissingOpenBracket(); 4359 4360 case tok::kw___declspec: 4361 case tok::kw___cdecl: 4362 case tok::kw___stdcall: 4363 case tok::kw___fastcall: 4364 case tok::kw___thiscall: 4365 case tok::kw___vectorcall: 4366 case tok::kw___w64: 4367 case tok::kw___sptr: 4368 case tok::kw___uptr: 4369 case tok::kw___ptr64: 4370 case tok::kw___ptr32: 4371 case tok::kw___forceinline: 4372 case tok::kw___pascal: 4373 case tok::kw___unaligned: 4374 4375 case tok::kw___private: 4376 case tok::kw___local: 4377 case tok::kw___global: 4378 case tok::kw___constant: 4379 case tok::kw___generic: 4380 case tok::kw___read_only: 4381 case tok::kw___read_write: 4382 case tok::kw___write_only: 4383 4384 return true; 4385 } 4386} 4387 4388bool Parser::isConstructorDeclarator(bool IsUnqualified) { 4389 TentativeParsingAction TPA(*this); 4390 4391 // Parse the C++ scope specifier. 4392 CXXScopeSpec SS; 4393 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 4394 /*EnteringContext=*/true)) { 4395 TPA.Revert(); 4396 return false; 4397 } 4398 4399 // Parse the constructor name. 4400 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) { 4401 // We already know that we have a constructor name; just consume 4402 // the token. 4403 ConsumeToken(); 4404 } else { 4405 TPA.Revert(); 4406 return false; 4407 } 4408 4409 // Current class name must be followed by a left parenthesis. 4410 if (Tok.isNot(tok::l_paren)) { 4411 TPA.Revert(); 4412 return false; 4413 } 4414 ConsumeParen(); 4415 4416 // A right parenthesis, or ellipsis followed by a right parenthesis signals 4417 // that we have a constructor. 4418 if (Tok.is(tok::r_paren) || 4419 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) { 4420 TPA.Revert(); 4421 return true; 4422 } 4423 4424 // A C++11 attribute here signals that we have a constructor, and is an 4425 // attribute on the first constructor parameter. 4426 if (getLangOpts().CPlusPlus11 && 4427 isCXX11AttributeSpecifier(/*Disambiguate*/ false, 4428 /*OuterMightBeMessageSend*/ true)) { 4429 TPA.Revert(); 4430 return true; 4431 } 4432 4433 // If we need to, enter the specified scope. 4434 DeclaratorScopeObj DeclScopeObj(*this, SS); 4435 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS)) 4436 DeclScopeObj.EnterDeclaratorScope(); 4437 4438 // Optionally skip Microsoft attributes. 4439 ParsedAttributes Attrs(AttrFactory); 4440 MaybeParseMicrosoftAttributes(Attrs); 4441 4442 // Check whether the next token(s) are part of a declaration 4443 // specifier, in which case we have the start of a parameter and, 4444 // therefore, we know that this is a constructor. 4445 bool IsConstructor = false; 4446 if (isDeclarationSpecifier()) 4447 IsConstructor = true; 4448 else if (Tok.is(tok::identifier) || 4449 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) { 4450 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type. 4451 // This might be a parenthesized member name, but is more likely to 4452 // be a constructor declaration with an invalid argument type. Keep 4453 // looking. 4454 if (Tok.is(tok::annot_cxxscope)) 4455 ConsumeToken(); 4456 ConsumeToken(); 4457 4458 // If this is not a constructor, we must be parsing a declarator, 4459 // which must have one of the following syntactic forms (see the 4460 // grammar extract at the start of ParseDirectDeclarator): 4461 switch (Tok.getKind()) { 4462 case tok::l_paren: 4463 // C(X ( int)); 4464 case tok::l_square: 4465 // C(X [ 5]); 4466 // C(X [ [attribute]]); 4467 case tok::coloncolon: 4468 // C(X :: Y); 4469 // C(X :: *p); 4470 // Assume this isn't a constructor, rather than assuming it's a 4471 // constructor with an unnamed parameter of an ill-formed type. 4472 break; 4473 4474 case tok::r_paren: 4475 // C(X ) 4476 if (NextToken().is(tok::colon) || NextToken().is(tok::kw_try)) { 4477 // Assume these were meant to be constructors: 4478 // C(X) : (the name of a bit-field cannot be parenthesized). 4479 // C(X) try (this is otherwise ill-formed). 4480 IsConstructor = true; 4481 } 4482 if (NextToken().is(tok::semi) || NextToken().is(tok::l_brace)) { 4483 // If we have a constructor name within the class definition, 4484 // assume these were meant to be constructors: 4485 // C(X) { 4486 // C(X) ; 4487 // ... because otherwise we would be declaring a non-static data 4488 // member that is ill-formed because it's of the same type as its 4489 // surrounding class. 4490 // 4491 // FIXME: We can actually do this whether or not the name is qualified, 4492 // because if it is qualified in this context it must be being used as 4493 // a constructor name. However, we do not implement that rule correctly 4494 // currently, so we're somewhat conservative here. 4495 IsConstructor = IsUnqualified; 4496 } 4497 break; 4498 4499 default: 4500 IsConstructor = true; 4501 break; 4502 } 4503 } 4504 4505 TPA.Revert(); 4506 return IsConstructor; 4507} 4508 4509/// ParseTypeQualifierListOpt 4510/// type-qualifier-list: [C99 6.7.5] 4511/// type-qualifier 4512/// [vendor] attributes 4513/// [ only if AttrReqs & AR_VendorAttributesParsed ] 4514/// type-qualifier-list type-qualifier 4515/// [vendor] type-qualifier-list attributes 4516/// [ only if AttrReqs & AR_VendorAttributesParsed ] 4517/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq 4518/// [ only if AttReqs & AR_CXX11AttributesParsed ] 4519/// Note: vendor can be GNU, MS, etc and can be explicitly controlled via 4520/// AttrRequirements bitmask values. 4521void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, unsigned AttrReqs, 4522 bool AtomicAllowed, 4523 bool IdentifierRequired) { 4524 if (getLangOpts().CPlusPlus11 && (AttrReqs & AR_CXX11AttributesParsed) && 4525 isCXX11AttributeSpecifier()) { 4526 ParsedAttributesWithRange attrs(AttrFactory); 4527 ParseCXX11Attributes(attrs); 4528 DS.takeAttributesFrom(attrs); 4529 } 4530 4531 SourceLocation EndLoc; 4532 4533 while (1) { 4534 bool isInvalid = false; 4535 const char *PrevSpec = nullptr; 4536 unsigned DiagID = 0; 4537 SourceLocation Loc = Tok.getLocation(); 4538 4539 switch (Tok.getKind()) { 4540 case tok::code_completion: 4541 Actions.CodeCompleteTypeQualifiers(DS); 4542 return cutOffParsing(); 4543 4544 case tok::kw_const: 4545 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID, 4546 getLangOpts()); 4547 break; 4548 case tok::kw_volatile: 4549 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 4550 getLangOpts()); 4551 break; 4552 case tok::kw_restrict: 4553 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 4554 getLangOpts()); 4555 break; 4556 case tok::kw__Atomic: 4557 if (!AtomicAllowed) 4558 goto DoneWithTypeQuals; 4559 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID, 4560 getLangOpts()); 4561 break; 4562 4563 // OpenCL qualifiers: 4564 case tok::kw___private: 4565 case tok::kw___global: 4566 case tok::kw___local: 4567 case tok::kw___constant: 4568 case tok::kw___generic: 4569 case tok::kw___read_only: 4570 case tok::kw___write_only: 4571 case tok::kw___read_write: 4572 ParseOpenCLQualifiers(DS.getAttributes()); 4573 break; 4574 4575 case tok::kw___uptr: 4576 // GNU libc headers in C mode use '__uptr' as an identifer which conflicts 4577 // with the MS modifier keyword. 4578 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus && 4579 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) { 4580 if (TryKeywordIdentFallback(false)) 4581 continue; 4582 } 4583 case tok::kw___sptr: 4584 case tok::kw___w64: 4585 case tok::kw___ptr64: 4586 case tok::kw___ptr32: 4587 case tok::kw___cdecl: 4588 case tok::kw___stdcall: 4589 case tok::kw___fastcall: 4590 case tok::kw___thiscall: 4591 case tok::kw___vectorcall: 4592 case tok::kw___unaligned: 4593 if (AttrReqs & AR_DeclspecAttributesParsed) { 4594 ParseMicrosoftTypeAttributes(DS.getAttributes()); 4595 continue; 4596 } 4597 goto DoneWithTypeQuals; 4598 case tok::kw___pascal: 4599 if (AttrReqs & AR_VendorAttributesParsed) { 4600 ParseBorlandTypeAttributes(DS.getAttributes()); 4601 continue; 4602 } 4603 goto DoneWithTypeQuals; 4604 case tok::kw___attribute: 4605 if (AttrReqs & AR_GNUAttributesParsedAndRejected) 4606 // When GNU attributes are expressly forbidden, diagnose their usage. 4607 Diag(Tok, diag::err_attributes_not_allowed); 4608 4609 // Parse the attributes even if they are rejected to ensure that error 4610 // recovery is graceful. 4611 if (AttrReqs & AR_GNUAttributesParsed || 4612 AttrReqs & AR_GNUAttributesParsedAndRejected) { 4613 ParseGNUAttributes(DS.getAttributes()); 4614 continue; // do *not* consume the next token! 4615 } 4616 // otherwise, FALL THROUGH! 4617 default: 4618 DoneWithTypeQuals: 4619 // If this is not a type-qualifier token, we're done reading type 4620 // qualifiers. First verify that DeclSpec's are consistent. 4621 DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy()); 4622 if (EndLoc.isValid()) 4623 DS.SetRangeEnd(EndLoc); 4624 return; 4625 } 4626 4627 // If the specifier combination wasn't legal, issue a diagnostic. 4628 if (isInvalid) { 4629 assert(PrevSpec && "Method did not return previous specifier!"); 4630 Diag(Tok, DiagID) << PrevSpec; 4631 } 4632 EndLoc = ConsumeToken(); 4633 } 4634} 4635 4636 4637/// ParseDeclarator - Parse and verify a newly-initialized declarator. 4638/// 4639void Parser::ParseDeclarator(Declarator &D) { 4640 /// This implements the 'declarator' production in the C grammar, then checks 4641 /// for well-formedness and issues diagnostics. 4642 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 4643} 4644 4645static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang, 4646 unsigned TheContext) { 4647 if (Kind == tok::star || Kind == tok::caret) 4648 return true; 4649 4650 if (!Lang.CPlusPlus) 4651 return false; 4652 4653 if (Kind == tok::amp) 4654 return true; 4655 4656 // We parse rvalue refs in C++03, because otherwise the errors are scary. 4657 // But we must not parse them in conversion-type-ids and new-type-ids, since 4658 // those can be legitimately followed by a && operator. 4659 // (The same thing can in theory happen after a trailing-return-type, but 4660 // since those are a C++11 feature, there is no rejects-valid issue there.) 4661 if (Kind == tok::ampamp) 4662 return Lang.CPlusPlus11 || (TheContext != Declarator::ConversionIdContext && 4663 TheContext != Declarator::CXXNewContext); 4664 4665 return false; 4666} 4667 4668/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator 4669/// is parsed by the function passed to it. Pass null, and the direct-declarator 4670/// isn't parsed at all, making this function effectively parse the C++ 4671/// ptr-operator production. 4672/// 4673/// If the grammar of this construct is extended, matching changes must also be 4674/// made to TryParseDeclarator and MightBeDeclarator, and possibly to 4675/// isConstructorDeclarator. 4676/// 4677/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl] 4678/// [C] pointer[opt] direct-declarator 4679/// [C++] direct-declarator 4680/// [C++] ptr-operator declarator 4681/// 4682/// pointer: [C99 6.7.5] 4683/// '*' type-qualifier-list[opt] 4684/// '*' type-qualifier-list[opt] pointer 4685/// 4686/// ptr-operator: 4687/// '*' cv-qualifier-seq[opt] 4688/// '&' 4689/// [C++0x] '&&' 4690/// [GNU] '&' restrict[opt] attributes[opt] 4691/// [GNU?] '&&' restrict[opt] attributes[opt] 4692/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 4693void Parser::ParseDeclaratorInternal(Declarator &D, 4694 DirectDeclParseFunction DirectDeclParser) { 4695 if (Diags.hasAllExtensionsSilenced()) 4696 D.setExtension(); 4697 4698 // C++ member pointers start with a '::' or a nested-name. 4699 // Member pointers get special handling, since there's no place for the 4700 // scope spec in the generic path below. 4701 if (getLangOpts().CPlusPlus && 4702 (Tok.is(tok::coloncolon) || 4703 (Tok.is(tok::identifier) && 4704 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) || 4705 Tok.is(tok::annot_cxxscope))) { 4706 bool EnteringContext = D.getContext() == Declarator::FileContext || 4707 D.getContext() == Declarator::MemberContext; 4708 CXXScopeSpec SS; 4709 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext); 4710 4711 if (SS.isNotEmpty()) { 4712 if (Tok.isNot(tok::star)) { 4713 // The scope spec really belongs to the direct-declarator. 4714 if (D.mayHaveIdentifier()) 4715 D.getCXXScopeSpec() = SS; 4716 else 4717 AnnotateScopeToken(SS, true); 4718 4719 if (DirectDeclParser) 4720 (this->*DirectDeclParser)(D); 4721 return; 4722 } 4723 4724 SourceLocation Loc = ConsumeToken(); 4725 D.SetRangeEnd(Loc); 4726 DeclSpec DS(AttrFactory); 4727 ParseTypeQualifierListOpt(DS); 4728 D.ExtendWithDeclSpec(DS); 4729 4730 // Recurse to parse whatever is left. 4731 ParseDeclaratorInternal(D, DirectDeclParser); 4732 4733 // Sema will have to catch (syntactically invalid) pointers into global 4734 // scope. It has to catch pointers into namespace scope anyway. 4735 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(), 4736 DS.getLocEnd()), 4737 DS.getAttributes(), 4738 /* Don't replace range end. */SourceLocation()); 4739 return; 4740 } 4741 } 4742 4743 tok::TokenKind Kind = Tok.getKind(); 4744 // Not a pointer, C++ reference, or block. 4745 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) { 4746 if (DirectDeclParser) 4747 (this->*DirectDeclParser)(D); 4748 return; 4749 } 4750 4751 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference, 4752 // '&&' -> rvalue reference 4753 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&. 4754 D.SetRangeEnd(Loc); 4755 4756 if (Kind == tok::star || Kind == tok::caret) { 4757 // Is a pointer. 4758 DeclSpec DS(AttrFactory); 4759 4760 // GNU attributes are not allowed here in a new-type-id, but Declspec and 4761 // C++11 attributes are allowed. 4762 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed | 4763 ((D.getContext() != Declarator::CXXNewContext) 4764 ? AR_GNUAttributesParsed 4765 : AR_GNUAttributesParsedAndRejected); 4766 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier()); 4767 D.ExtendWithDeclSpec(DS); 4768 4769 // Recursively parse the declarator. 4770 ParseDeclaratorInternal(D, DirectDeclParser); 4771 if (Kind == tok::star) 4772 // Remember that we parsed a pointer type, and remember the type-quals. 4773 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc, 4774 DS.getConstSpecLoc(), 4775 DS.getVolatileSpecLoc(), 4776 DS.getRestrictSpecLoc()), 4777 DS.getAttributes(), 4778 SourceLocation()); 4779 else 4780 // Remember that we parsed a Block type, and remember the type-quals. 4781 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), 4782 Loc), 4783 DS.getAttributes(), 4784 SourceLocation()); 4785 } else { 4786 // Is a reference 4787 DeclSpec DS(AttrFactory); 4788 4789 // Complain about rvalue references in C++03, but then go on and build 4790 // the declarator. 4791 if (Kind == tok::ampamp) 4792 Diag(Loc, getLangOpts().CPlusPlus11 ? 4793 diag::warn_cxx98_compat_rvalue_reference : 4794 diag::ext_rvalue_reference); 4795 4796 // GNU-style and C++11 attributes are allowed here, as is restrict. 4797 ParseTypeQualifierListOpt(DS); 4798 D.ExtendWithDeclSpec(DS); 4799 4800 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the 4801 // cv-qualifiers are introduced through the use of a typedef or of a 4802 // template type argument, in which case the cv-qualifiers are ignored. 4803 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { 4804 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4805 Diag(DS.getConstSpecLoc(), 4806 diag::err_invalid_reference_qualifier_application) << "const"; 4807 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4808 Diag(DS.getVolatileSpecLoc(), 4809 diag::err_invalid_reference_qualifier_application) << "volatile"; 4810 // 'restrict' is permitted as an extension. 4811 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4812 Diag(DS.getAtomicSpecLoc(), 4813 diag::err_invalid_reference_qualifier_application) << "_Atomic"; 4814 } 4815 4816 // Recursively parse the declarator. 4817 ParseDeclaratorInternal(D, DirectDeclParser); 4818 4819 if (D.getNumTypeObjects() > 0) { 4820 // C++ [dcl.ref]p4: There shall be no references to references. 4821 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1); 4822 if (InnerChunk.Kind == DeclaratorChunk::Reference) { 4823 if (const IdentifierInfo *II = D.getIdentifier()) 4824 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 4825 << II; 4826 else 4827 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 4828 << "type name"; 4829 4830 // Once we've complained about the reference-to-reference, we 4831 // can go ahead and build the (technically ill-formed) 4832 // declarator: reference collapsing will take care of it. 4833 } 4834 } 4835 4836 // Remember that we parsed a reference type. 4837 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc, 4838 Kind == tok::amp), 4839 DS.getAttributes(), 4840 SourceLocation()); 4841 } 4842} 4843 4844// When correcting from misplaced brackets before the identifier, the location 4845// is saved inside the declarator so that other diagnostic messages can use 4846// them. This extracts and returns that location, or returns the provided 4847// location if a stored location does not exist. 4848static SourceLocation getMissingDeclaratorIdLoc(Declarator &D, 4849 SourceLocation Loc) { 4850 if (D.getName().StartLocation.isInvalid() && 4851 D.getName().EndLocation.isValid()) 4852 return D.getName().EndLocation; 4853 4854 return Loc; 4855} 4856 4857/// ParseDirectDeclarator 4858/// direct-declarator: [C99 6.7.5] 4859/// [C99] identifier 4860/// '(' declarator ')' 4861/// [GNU] '(' attributes declarator ')' 4862/// [C90] direct-declarator '[' constant-expression[opt] ']' 4863/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 4864/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 4865/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 4866/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 4867/// [C++11] direct-declarator '[' constant-expression[opt] ']' 4868/// attribute-specifier-seq[opt] 4869/// direct-declarator '(' parameter-type-list ')' 4870/// direct-declarator '(' identifier-list[opt] ')' 4871/// [GNU] direct-declarator '(' parameter-forward-declarations 4872/// parameter-type-list[opt] ')' 4873/// [C++] direct-declarator '(' parameter-declaration-clause ')' 4874/// cv-qualifier-seq[opt] exception-specification[opt] 4875/// [C++11] direct-declarator '(' parameter-declaration-clause ')' 4876/// attribute-specifier-seq[opt] cv-qualifier-seq[opt] 4877/// ref-qualifier[opt] exception-specification[opt] 4878/// [C++] declarator-id 4879/// [C++11] declarator-id attribute-specifier-seq[opt] 4880/// 4881/// declarator-id: [C++ 8] 4882/// '...'[opt] id-expression 4883/// '::'[opt] nested-name-specifier[opt] type-name 4884/// 4885/// id-expression: [C++ 5.1] 4886/// unqualified-id 4887/// qualified-id 4888/// 4889/// unqualified-id: [C++ 5.1] 4890/// identifier 4891/// operator-function-id 4892/// conversion-function-id 4893/// '~' class-name 4894/// template-id 4895/// 4896/// Note, any additional constructs added here may need corresponding changes 4897/// in isConstructorDeclarator. 4898void Parser::ParseDirectDeclarator(Declarator &D) { 4899 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec()); 4900 4901 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) { 4902 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in 4903 // this context it is a bitfield. Also in range-based for statement colon 4904 // may delimit for-range-declaration. 4905 ColonProtectionRAIIObject X(*this, 4906 D.getContext() == Declarator::MemberContext || 4907 (D.getContext() == Declarator::ForContext && 4908 getLangOpts().CPlusPlus11)); 4909 4910 // ParseDeclaratorInternal might already have parsed the scope. 4911 if (D.getCXXScopeSpec().isEmpty()) { 4912 bool EnteringContext = D.getContext() == Declarator::FileContext || 4913 D.getContext() == Declarator::MemberContext; 4914 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(), 4915 EnteringContext); 4916 } 4917 4918 if (D.getCXXScopeSpec().isValid()) { 4919 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) 4920 // Change the declaration context for name lookup, until this function 4921 // is exited (and the declarator has been parsed). 4922 DeclScopeObj.EnterDeclaratorScope(); 4923 } 4924 4925 // C++0x [dcl.fct]p14: 4926 // There is a syntactic ambiguity when an ellipsis occurs at the end of a 4927 // parameter-declaration-clause without a preceding comma. In this case, 4928 // the ellipsis is parsed as part of the abstract-declarator if the type 4929 // of the parameter either names a template parameter pack that has not 4930 // been expanded or contains auto; otherwise, it is parsed as part of the 4931 // parameter-declaration-clause. 4932 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() && 4933 !((D.getContext() == Declarator::PrototypeContext || 4934 D.getContext() == Declarator::LambdaExprParameterContext || 4935 D.getContext() == Declarator::BlockLiteralContext) && 4936 NextToken().is(tok::r_paren) && 4937 !D.hasGroupingParens() && 4938 !Actions.containsUnexpandedParameterPacks(D) && 4939 D.getDeclSpec().getTypeSpecType() != TST_auto)) { 4940 SourceLocation EllipsisLoc = ConsumeToken(); 4941 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) { 4942 // The ellipsis was put in the wrong place. Recover, and explain to 4943 // the user what they should have done. 4944 ParseDeclarator(D); 4945 if (EllipsisLoc.isValid()) 4946 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D); 4947 return; 4948 } else 4949 D.setEllipsisLoc(EllipsisLoc); 4950 4951 // The ellipsis can't be followed by a parenthesized declarator. We 4952 // check for that in ParseParenDeclarator, after we have disambiguated 4953 // the l_paren token. 4954 } 4955 4956 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) || 4957 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) { 4958 // We found something that indicates the start of an unqualified-id. 4959 // Parse that unqualified-id. 4960 bool AllowConstructorName; 4961 if (D.getDeclSpec().hasTypeSpecifier()) 4962 AllowConstructorName = false; 4963 else if (D.getCXXScopeSpec().isSet()) 4964 AllowConstructorName = 4965 (D.getContext() == Declarator::FileContext || 4966 D.getContext() == Declarator::MemberContext); 4967 else 4968 AllowConstructorName = (D.getContext() == Declarator::MemberContext); 4969 4970 SourceLocation TemplateKWLoc; 4971 if (ParseUnqualifiedId(D.getCXXScopeSpec(), 4972 /*EnteringContext=*/true, 4973 /*AllowDestructorName=*/true, 4974 AllowConstructorName, 4975 ParsedType(), 4976 TemplateKWLoc, 4977 D.getName()) || 4978 // Once we're past the identifier, if the scope was bad, mark the 4979 // whole declarator bad. 4980 D.getCXXScopeSpec().isInvalid()) { 4981 D.SetIdentifier(nullptr, Tok.getLocation()); 4982 D.setInvalidType(true); 4983 } else { 4984 // Parsed the unqualified-id; update range information and move along. 4985 if (D.getSourceRange().getBegin().isInvalid()) 4986 D.SetRangeBegin(D.getName().getSourceRange().getBegin()); 4987 D.SetRangeEnd(D.getName().getSourceRange().getEnd()); 4988 } 4989 goto PastIdentifier; 4990 } 4991 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) { 4992 assert(!getLangOpts().CPlusPlus && 4993 "There's a C++-specific check for tok::identifier above"); 4994 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 4995 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 4996 D.SetRangeEnd(Tok.getLocation()); 4997 ConsumeToken(); 4998 goto PastIdentifier; 4999 } else if (Tok.is(tok::identifier) && D.diagnoseIdentifier()) { 5000 // A virt-specifier isn't treated as an identifier if it appears after a 5001 // trailing-return-type. 5002 if (D.getContext() != Declarator::TrailingReturnContext || 5003 !isCXX11VirtSpecifier(Tok)) { 5004 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id) 5005 << FixItHint::CreateRemoval(Tok.getLocation()); 5006 D.SetIdentifier(nullptr, Tok.getLocation()); 5007 ConsumeToken(); 5008 goto PastIdentifier; 5009 } 5010 } 5011 5012 if (Tok.is(tok::l_paren)) { 5013 // direct-declarator: '(' declarator ')' 5014 // direct-declarator: '(' attributes declarator ')' 5015 // Example: 'char (*X)' or 'int (*XX)(void)' 5016 ParseParenDeclarator(D); 5017 5018 // If the declarator was parenthesized, we entered the declarator 5019 // scope when parsing the parenthesized declarator, then exited 5020 // the scope already. Re-enter the scope, if we need to. 5021 if (D.getCXXScopeSpec().isSet()) { 5022 // If there was an error parsing parenthesized declarator, declarator 5023 // scope may have been entered before. Don't do it again. 5024 if (!D.isInvalidType() && 5025 Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) 5026 // Change the declaration context for name lookup, until this function 5027 // is exited (and the declarator has been parsed). 5028 DeclScopeObj.EnterDeclaratorScope(); 5029 } 5030 } else if (D.mayOmitIdentifier()) { 5031 // This could be something simple like "int" (in which case the declarator 5032 // portion is empty), if an abstract-declarator is allowed. 5033 D.SetIdentifier(nullptr, Tok.getLocation()); 5034 5035 // The grammar for abstract-pack-declarator does not allow grouping parens. 5036 // FIXME: Revisit this once core issue 1488 is resolved. 5037 if (D.hasEllipsis() && D.hasGroupingParens()) 5038 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()), 5039 diag::ext_abstract_pack_declarator_parens); 5040 } else { 5041 if (Tok.getKind() == tok::annot_pragma_parser_crash) 5042 LLVM_BUILTIN_TRAP; 5043 if (Tok.is(tok::l_square)) 5044 return ParseMisplacedBracketDeclarator(D); 5045 if (D.getContext() == Declarator::MemberContext) { 5046 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 5047 diag::err_expected_member_name_or_semi) 5048 << (D.getDeclSpec().isEmpty() ? SourceRange() 5049 : D.getDeclSpec().getSourceRange()); 5050 } else if (getLangOpts().CPlusPlus) { 5051 if (Tok.is(tok::period) || Tok.is(tok::arrow)) 5052 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow); 5053 else { 5054 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc(); 5055 if (Tok.isAtStartOfLine() && Loc.isValid()) 5056 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id) 5057 << getLangOpts().CPlusPlus; 5058 else 5059 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 5060 diag::err_expected_unqualified_id) 5061 << getLangOpts().CPlusPlus; 5062 } 5063 } else { 5064 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 5065 diag::err_expected_either) 5066 << tok::identifier << tok::l_paren; 5067 } 5068 D.SetIdentifier(nullptr, Tok.getLocation()); 5069 D.setInvalidType(true); 5070 } 5071 5072 PastIdentifier: 5073 assert(D.isPastIdentifier() && 5074 "Haven't past the location of the identifier yet?"); 5075 5076 // Don't parse attributes unless we have parsed an unparenthesized name. 5077 if (D.hasName() && !D.getNumTypeObjects()) 5078 MaybeParseCXX11Attributes(D); 5079 5080 while (1) { 5081 if (Tok.is(tok::l_paren)) { 5082 // Enter function-declaration scope, limiting any declarators to the 5083 // function prototype scope, including parameter declarators. 5084 ParseScope PrototypeScope(this, 5085 Scope::FunctionPrototypeScope|Scope::DeclScope| 5086 (D.isFunctionDeclaratorAFunctionDeclaration() 5087 ? Scope::FunctionDeclarationScope : 0)); 5088 5089 // The paren may be part of a C++ direct initializer, eg. "int x(1);". 5090 // In such a case, check if we actually have a function declarator; if it 5091 // is not, the declarator has been fully parsed. 5092 bool IsAmbiguous = false; 5093 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) { 5094 // The name of the declarator, if any, is tentatively declared within 5095 // a possible direct initializer. 5096 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier()); 5097 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous); 5098 TentativelyDeclaredIdentifiers.pop_back(); 5099 if (!IsFunctionDecl) 5100 break; 5101 } 5102 ParsedAttributes attrs(AttrFactory); 5103 BalancedDelimiterTracker T(*this, tok::l_paren); 5104 T.consumeOpen(); 5105 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous); 5106 PrototypeScope.Exit(); 5107 } else if (Tok.is(tok::l_square)) { 5108 ParseBracketDeclarator(D); 5109 } else { 5110 break; 5111 } 5112 } 5113} 5114 5115/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is 5116/// only called before the identifier, so these are most likely just grouping 5117/// parens for precedence. If we find that these are actually function 5118/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. 5119/// 5120/// direct-declarator: 5121/// '(' declarator ')' 5122/// [GNU] '(' attributes declarator ')' 5123/// direct-declarator '(' parameter-type-list ')' 5124/// direct-declarator '(' identifier-list[opt] ')' 5125/// [GNU] direct-declarator '(' parameter-forward-declarations 5126/// parameter-type-list[opt] ')' 5127/// 5128void Parser::ParseParenDeclarator(Declarator &D) { 5129 BalancedDelimiterTracker T(*this, tok::l_paren); 5130 T.consumeOpen(); 5131 5132 assert(!D.isPastIdentifier() && "Should be called before passing identifier"); 5133 5134 // Eat any attributes before we look at whether this is a grouping or function 5135 // declarator paren. If this is a grouping paren, the attribute applies to 5136 // the type being built up, for example: 5137 // int (__attribute__(()) *x)(long y) 5138 // If this ends up not being a grouping paren, the attribute applies to the 5139 // first argument, for example: 5140 // int (__attribute__(()) int x) 5141 // In either case, we need to eat any attributes to be able to determine what 5142 // sort of paren this is. 5143 // 5144 ParsedAttributes attrs(AttrFactory); 5145 bool RequiresArg = false; 5146 if (Tok.is(tok::kw___attribute)) { 5147 ParseGNUAttributes(attrs); 5148 5149 // We require that the argument list (if this is a non-grouping paren) be 5150 // present even if the attribute list was empty. 5151 RequiresArg = true; 5152 } 5153 5154 // Eat any Microsoft extensions. 5155 ParseMicrosoftTypeAttributes(attrs); 5156 5157 // Eat any Borland extensions. 5158 if (Tok.is(tok::kw___pascal)) 5159 ParseBorlandTypeAttributes(attrs); 5160 5161 // If we haven't past the identifier yet (or where the identifier would be 5162 // stored, if this is an abstract declarator), then this is probably just 5163 // grouping parens. However, if this could be an abstract-declarator, then 5164 // this could also be the start of function arguments (consider 'void()'). 5165 bool isGrouping; 5166 5167 if (!D.mayOmitIdentifier()) { 5168 // If this can't be an abstract-declarator, this *must* be a grouping 5169 // paren, because we haven't seen the identifier yet. 5170 isGrouping = true; 5171 } else if (Tok.is(tok::r_paren) || // 'int()' is a function. 5172 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) && 5173 NextToken().is(tok::r_paren)) || // C++ int(...) 5174 isDeclarationSpecifier() || // 'int(int)' is a function. 5175 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function. 5176 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is 5177 // considered to be a type, not a K&R identifier-list. 5178 isGrouping = false; 5179 } else { 5180 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. 5181 isGrouping = true; 5182 } 5183 5184 // If this is a grouping paren, handle: 5185 // direct-declarator: '(' declarator ')' 5186 // direct-declarator: '(' attributes declarator ')' 5187 if (isGrouping) { 5188 SourceLocation EllipsisLoc = D.getEllipsisLoc(); 5189 D.setEllipsisLoc(SourceLocation()); 5190 5191 bool hadGroupingParens = D.hasGroupingParens(); 5192 D.setGroupingParens(true); 5193 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 5194 // Match the ')'. 5195 T.consumeClose(); 5196 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(), 5197 T.getCloseLocation()), 5198 attrs, T.getCloseLocation()); 5199 5200 D.setGroupingParens(hadGroupingParens); 5201 5202 // An ellipsis cannot be placed outside parentheses. 5203 if (EllipsisLoc.isValid()) 5204 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D); 5205 5206 return; 5207 } 5208 5209 // Okay, if this wasn't a grouping paren, it must be the start of a function 5210 // argument list. Recognize that this declarator will never have an 5211 // identifier (and remember where it would have been), then call into 5212 // ParseFunctionDeclarator to handle of argument list. 5213 D.SetIdentifier(nullptr, Tok.getLocation()); 5214 5215 // Enter function-declaration scope, limiting any declarators to the 5216 // function prototype scope, including parameter declarators. 5217 ParseScope PrototypeScope(this, 5218 Scope::FunctionPrototypeScope | Scope::DeclScope | 5219 (D.isFunctionDeclaratorAFunctionDeclaration() 5220 ? Scope::FunctionDeclarationScope : 0)); 5221 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg); 5222 PrototypeScope.Exit(); 5223} 5224 5225/// ParseFunctionDeclarator - We are after the identifier and have parsed the 5226/// declarator D up to a paren, which indicates that we are parsing function 5227/// arguments. 5228/// 5229/// If FirstArgAttrs is non-null, then the caller parsed those arguments 5230/// immediately after the open paren - they should be considered to be the 5231/// first argument of a parameter. 5232/// 5233/// If RequiresArg is true, then the first argument of the function is required 5234/// to be present and required to not be an identifier list. 5235/// 5236/// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt], 5237/// (C++11) ref-qualifier[opt], exception-specification[opt], 5238/// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt]. 5239/// 5240/// [C++11] exception-specification: 5241/// dynamic-exception-specification 5242/// noexcept-specification 5243/// 5244void Parser::ParseFunctionDeclarator(Declarator &D, 5245 ParsedAttributes &FirstArgAttrs, 5246 BalancedDelimiterTracker &Tracker, 5247 bool IsAmbiguous, 5248 bool RequiresArg) { 5249 assert(getCurScope()->isFunctionPrototypeScope() && 5250 "Should call from a Function scope"); 5251 // lparen is already consumed! 5252 assert(D.isPastIdentifier() && "Should not call before identifier!"); 5253 5254 // This should be true when the function has typed arguments. 5255 // Otherwise, it is treated as a K&R-style function. 5256 bool HasProto = false; 5257 // Build up an array of information about the parsed arguments. 5258 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 5259 // Remember where we see an ellipsis, if any. 5260 SourceLocation EllipsisLoc; 5261 5262 DeclSpec DS(AttrFactory); 5263 bool RefQualifierIsLValueRef = true; 5264 SourceLocation RefQualifierLoc; 5265 SourceLocation ConstQualifierLoc; 5266 SourceLocation VolatileQualifierLoc; 5267 SourceLocation RestrictQualifierLoc; 5268 ExceptionSpecificationType ESpecType = EST_None; 5269 SourceRange ESpecRange; 5270 SmallVector<ParsedType, 2> DynamicExceptions; 5271 SmallVector<SourceRange, 2> DynamicExceptionRanges; 5272 ExprResult NoexceptExpr; 5273 CachedTokens *ExceptionSpecTokens = 0; 5274 ParsedAttributes FnAttrs(AttrFactory); 5275 TypeResult TrailingReturnType; 5276 5277 /* LocalEndLoc is the end location for the local FunctionTypeLoc. 5278 EndLoc is the end location for the function declarator. 5279 They differ for trailing return types. */ 5280 SourceLocation StartLoc, LocalEndLoc, EndLoc; 5281 SourceLocation LParenLoc, RParenLoc; 5282 LParenLoc = Tracker.getOpenLocation(); 5283 StartLoc = LParenLoc; 5284 5285 if (isFunctionDeclaratorIdentifierList()) { 5286 if (RequiresArg) 5287 Diag(Tok, diag::err_argument_required_after_attribute); 5288 5289 ParseFunctionDeclaratorIdentifierList(D, ParamInfo); 5290 5291 Tracker.consumeClose(); 5292 RParenLoc = Tracker.getCloseLocation(); 5293 LocalEndLoc = RParenLoc; 5294 EndLoc = RParenLoc; 5295 } else { 5296 if (Tok.isNot(tok::r_paren)) 5297 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, 5298 EllipsisLoc); 5299 else if (RequiresArg) 5300 Diag(Tok, diag::err_argument_required_after_attribute); 5301 5302 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus; 5303 5304 // If we have the closing ')', eat it. 5305 Tracker.consumeClose(); 5306 RParenLoc = Tracker.getCloseLocation(); 5307 LocalEndLoc = RParenLoc; 5308 EndLoc = RParenLoc; 5309 5310 if (getLangOpts().CPlusPlus) { 5311 // FIXME: Accept these components in any order, and produce fixits to 5312 // correct the order if the user gets it wrong. Ideally we should deal 5313 // with the virt-specifier-seq and pure-specifier in the same way. 5314 5315 // Parse cv-qualifier-seq[opt]. 5316 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed, 5317 /*AtomicAllowed*/ false); 5318 if (!DS.getSourceRange().getEnd().isInvalid()) { 5319 EndLoc = DS.getSourceRange().getEnd(); 5320 ConstQualifierLoc = DS.getConstSpecLoc(); 5321 VolatileQualifierLoc = DS.getVolatileSpecLoc(); 5322 RestrictQualifierLoc = DS.getRestrictSpecLoc(); 5323 } 5324 5325 // Parse ref-qualifier[opt]. 5326 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) { 5327 Diag(Tok, getLangOpts().CPlusPlus11 ? 5328 diag::warn_cxx98_compat_ref_qualifier : 5329 diag::ext_ref_qualifier); 5330 5331 RefQualifierIsLValueRef = Tok.is(tok::amp); 5332 RefQualifierLoc = ConsumeToken(); 5333 EndLoc = RefQualifierLoc; 5334 } 5335 5336 // C++11 [expr.prim.general]p3: 5337 // If a declaration declares a member function or member function 5338 // template of a class X, the expression this is a prvalue of type 5339 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 5340 // and the end of the function-definition, member-declarator, or 5341 // declarator. 5342 // FIXME: currently, "static" case isn't handled correctly. 5343 bool IsCXX11MemberFunction = 5344 getLangOpts().CPlusPlus11 && 5345 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5346 (D.getContext() == Declarator::MemberContext 5347 ? !D.getDeclSpec().isFriendSpecified() 5348 : D.getContext() == Declarator::FileContext && 5349 D.getCXXScopeSpec().isValid() && 5350 Actions.CurContext->isRecord()); 5351 Sema::CXXThisScopeRAII ThisScope(Actions, 5352 dyn_cast<CXXRecordDecl>(Actions.CurContext), 5353 DS.getTypeQualifiers() | 5354 (D.getDeclSpec().isConstexprSpecified() && 5355 !getLangOpts().CPlusPlus14 5356 ? Qualifiers::Const : 0), 5357 IsCXX11MemberFunction); 5358 5359 // Parse exception-specification[opt]. 5360 bool Delayed = D.isFirstDeclarationOfMember() && 5361 D.isFunctionDeclaratorAFunctionDeclaration(); 5362 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) && 5363 GetLookAheadToken(0).is(tok::kw_noexcept) && 5364 GetLookAheadToken(1).is(tok::l_paren) && 5365 GetLookAheadToken(2).is(tok::kw_noexcept) && 5366 GetLookAheadToken(3).is(tok::l_paren) && 5367 GetLookAheadToken(4).is(tok::identifier) && 5368 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) { 5369 // HACK: We've got an exception-specification 5370 // noexcept(noexcept(swap(...))) 5371 // or 5372 // noexcept(noexcept(swap(...)) && noexcept(swap(...))) 5373 // on a 'swap' member function. This is a libstdc++ bug; the lookup 5374 // for 'swap' will only find the function we're currently declaring, 5375 // whereas it expects to find a non-member swap through ADL. Turn off 5376 // delayed parsing to give it a chance to find what it expects. 5377 Delayed = false; 5378 } 5379 ESpecType = tryParseExceptionSpecification(Delayed, 5380 ESpecRange, 5381 DynamicExceptions, 5382 DynamicExceptionRanges, 5383 NoexceptExpr, 5384 ExceptionSpecTokens); 5385 if (ESpecType != EST_None) 5386 EndLoc = ESpecRange.getEnd(); 5387 5388 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes 5389 // after the exception-specification. 5390 MaybeParseCXX11Attributes(FnAttrs); 5391 5392 // Parse trailing-return-type[opt]. 5393 LocalEndLoc = EndLoc; 5394 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) { 5395 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type); 5396 if (D.getDeclSpec().getTypeSpecType() == TST_auto) 5397 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 5398 LocalEndLoc = Tok.getLocation(); 5399 SourceRange Range; 5400 TrailingReturnType = ParseTrailingReturnType(Range); 5401 EndLoc = Range.getEnd(); 5402 } 5403 } 5404 } 5405 5406 // Remember that we parsed a function type, and remember the attributes. 5407 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto, 5408 IsAmbiguous, 5409 LParenLoc, 5410 ParamInfo.data(), ParamInfo.size(), 5411 EllipsisLoc, RParenLoc, 5412 DS.getTypeQualifiers(), 5413 RefQualifierIsLValueRef, 5414 RefQualifierLoc, ConstQualifierLoc, 5415 VolatileQualifierLoc, 5416 RestrictQualifierLoc, 5417 /*MutableLoc=*/SourceLocation(), 5418 ESpecType, ESpecRange.getBegin(), 5419 DynamicExceptions.data(), 5420 DynamicExceptionRanges.data(), 5421 DynamicExceptions.size(), 5422 NoexceptExpr.isUsable() ? 5423 NoexceptExpr.get() : nullptr, 5424 ExceptionSpecTokens, 5425 StartLoc, LocalEndLoc, D, 5426 TrailingReturnType), 5427 FnAttrs, EndLoc); 5428} 5429 5430/// isFunctionDeclaratorIdentifierList - This parameter list may have an 5431/// identifier list form for a K&R-style function: void foo(a,b,c) 5432/// 5433/// Note that identifier-lists are only allowed for normal declarators, not for 5434/// abstract-declarators. 5435bool Parser::isFunctionDeclaratorIdentifierList() { 5436 return !getLangOpts().CPlusPlus 5437 && Tok.is(tok::identifier) 5438 && !TryAltiVecVectorToken() 5439 // K&R identifier lists can't have typedefs as identifiers, per C99 5440 // 6.7.5.3p11. 5441 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) 5442 // Identifier lists follow a really simple grammar: the identifiers can 5443 // be followed *only* by a ", identifier" or ")". However, K&R 5444 // identifier lists are really rare in the brave new modern world, and 5445 // it is very common for someone to typo a type in a non-K&R style 5446 // list. If we are presented with something like: "void foo(intptr x, 5447 // float y)", we don't want to start parsing the function declarator as 5448 // though it is a K&R style declarator just because intptr is an 5449 // invalid type. 5450 // 5451 // To handle this, we check to see if the token after the first 5452 // identifier is a "," or ")". Only then do we parse it as an 5453 // identifier list. 5454 && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)); 5455} 5456 5457/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator 5458/// we found a K&R-style identifier list instead of a typed parameter list. 5459/// 5460/// After returning, ParamInfo will hold the parsed parameters. 5461/// 5462/// identifier-list: [C99 6.7.5] 5463/// identifier 5464/// identifier-list ',' identifier 5465/// 5466void Parser::ParseFunctionDeclaratorIdentifierList( 5467 Declarator &D, 5468 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) { 5469 // If there was no identifier specified for the declarator, either we are in 5470 // an abstract-declarator, or we are in a parameter declarator which was found 5471 // to be abstract. In abstract-declarators, identifier lists are not valid: 5472 // diagnose this. 5473 if (!D.getIdentifier()) 5474 Diag(Tok, diag::ext_ident_list_in_param); 5475 5476 // Maintain an efficient lookup of params we have seen so far. 5477 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar; 5478 5479 do { 5480 // If this isn't an identifier, report the error and skip until ')'. 5481 if (Tok.isNot(tok::identifier)) { 5482 Diag(Tok, diag::err_expected) << tok::identifier; 5483 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch); 5484 // Forget we parsed anything. 5485 ParamInfo.clear(); 5486 return; 5487 } 5488 5489 IdentifierInfo *ParmII = Tok.getIdentifierInfo(); 5490 5491 // Reject 'typedef int y; int test(x, y)', but continue parsing. 5492 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope())) 5493 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; 5494 5495 // Verify that the argument identifier has not already been mentioned. 5496 if (!ParamsSoFar.insert(ParmII).second) { 5497 Diag(Tok, diag::err_param_redefinition) << ParmII; 5498 } else { 5499 // Remember this identifier in ParamInfo. 5500 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 5501 Tok.getLocation(), 5502 nullptr)); 5503 } 5504 5505 // Eat the identifier. 5506 ConsumeToken(); 5507 // The list continues if we see a comma. 5508 } while (TryConsumeToken(tok::comma)); 5509} 5510 5511/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list 5512/// after the opening parenthesis. This function will not parse a K&R-style 5513/// identifier list. 5514/// 5515/// D is the declarator being parsed. If FirstArgAttrs is non-null, then the 5516/// caller parsed those arguments immediately after the open paren - they should 5517/// be considered to be part of the first parameter. 5518/// 5519/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will 5520/// be the location of the ellipsis, if any was parsed. 5521/// 5522/// parameter-type-list: [C99 6.7.5] 5523/// parameter-list 5524/// parameter-list ',' '...' 5525/// [C++] parameter-list '...' 5526/// 5527/// parameter-list: [C99 6.7.5] 5528/// parameter-declaration 5529/// parameter-list ',' parameter-declaration 5530/// 5531/// parameter-declaration: [C99 6.7.5] 5532/// declaration-specifiers declarator 5533/// [C++] declaration-specifiers declarator '=' assignment-expression 5534/// [C++11] initializer-clause 5535/// [GNU] declaration-specifiers declarator attributes 5536/// declaration-specifiers abstract-declarator[opt] 5537/// [C++] declaration-specifiers abstract-declarator[opt] 5538/// '=' assignment-expression 5539/// [GNU] declaration-specifiers abstract-declarator[opt] attributes 5540/// [C++11] attribute-specifier-seq parameter-declaration 5541/// 5542void Parser::ParseParameterDeclarationClause( 5543 Declarator &D, 5544 ParsedAttributes &FirstArgAttrs, 5545 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, 5546 SourceLocation &EllipsisLoc) { 5547 do { 5548 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq 5549 // before deciding this was a parameter-declaration-clause. 5550 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) 5551 break; 5552 5553 // Parse the declaration-specifiers. 5554 // Just use the ParsingDeclaration "scope" of the declarator. 5555 DeclSpec DS(AttrFactory); 5556 5557 // Parse any C++11 attributes. 5558 MaybeParseCXX11Attributes(DS.getAttributes()); 5559 5560 // Skip any Microsoft attributes before a param. 5561 MaybeParseMicrosoftAttributes(DS.getAttributes()); 5562 5563 SourceLocation DSStart = Tok.getLocation(); 5564 5565 // If the caller parsed attributes for the first argument, add them now. 5566 // Take them so that we only apply the attributes to the first parameter. 5567 // FIXME: If we can leave the attributes in the token stream somehow, we can 5568 // get rid of a parameter (FirstArgAttrs) and this statement. It might be 5569 // too much hassle. 5570 DS.takeAttributesFrom(FirstArgAttrs); 5571 5572 ParseDeclarationSpecifiers(DS); 5573 5574 5575 // Parse the declarator. This is "PrototypeContext" or 5576 // "LambdaExprParameterContext", because we must accept either 5577 // 'declarator' or 'abstract-declarator' here. 5578 Declarator ParmDeclarator(DS, 5579 D.getContext() == Declarator::LambdaExprContext ? 5580 Declarator::LambdaExprParameterContext : 5581 Declarator::PrototypeContext); 5582 ParseDeclarator(ParmDeclarator); 5583 5584 // Parse GNU attributes, if present. 5585 MaybeParseGNUAttributes(ParmDeclarator); 5586 5587 // Remember this parsed parameter in ParamInfo. 5588 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier(); 5589 5590 // DefArgToks is used when the parsing of default arguments needs 5591 // to be delayed. 5592 CachedTokens *DefArgToks = nullptr; 5593 5594 // If no parameter was specified, verify that *something* was specified, 5595 // otherwise we have a missing type and identifier. 5596 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr && 5597 ParmDeclarator.getNumTypeObjects() == 0) { 5598 // Completely missing, emit error. 5599 Diag(DSStart, diag::err_missing_param); 5600 } else { 5601 // Otherwise, we have something. Add it and let semantic analysis try 5602 // to grok it and add the result to the ParamInfo we are building. 5603 5604 // Last chance to recover from a misplaced ellipsis in an attempted 5605 // parameter pack declaration. 5606 if (Tok.is(tok::ellipsis) && 5607 (NextToken().isNot(tok::r_paren) || 5608 (!ParmDeclarator.getEllipsisLoc().isValid() && 5609 !Actions.isUnexpandedParameterPackPermitted())) && 5610 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) 5611 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator); 5612 5613 // Inform the actions module about the parameter declarator, so it gets 5614 // added to the current scope. 5615 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator); 5616 // Parse the default argument, if any. We parse the default 5617 // arguments in all dialects; the semantic analysis in 5618 // ActOnParamDefaultArgument will reject the default argument in 5619 // C. 5620 if (Tok.is(tok::equal)) { 5621 SourceLocation EqualLoc = Tok.getLocation(); 5622 5623 // Parse the default argument 5624 if (D.getContext() == Declarator::MemberContext) { 5625 // If we're inside a class definition, cache the tokens 5626 // corresponding to the default argument. We'll actually parse 5627 // them when we see the end of the class definition. 5628 // FIXME: Can we use a smart pointer for Toks? 5629 DefArgToks = new CachedTokens; 5630 5631 SourceLocation ArgStartLoc = NextToken().getLocation(); 5632 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) { 5633 delete DefArgToks; 5634 DefArgToks = nullptr; 5635 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc); 5636 } else { 5637 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc, 5638 ArgStartLoc); 5639 } 5640 } else { 5641 // Consume the '='. 5642 ConsumeToken(); 5643 5644 // The argument isn't actually potentially evaluated unless it is 5645 // used. 5646 EnterExpressionEvaluationContext Eval(Actions, 5647 Sema::PotentiallyEvaluatedIfUsed, 5648 Param); 5649 5650 ExprResult DefArgResult; 5651 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 5652 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 5653 DefArgResult = ParseBraceInitializer(); 5654 } else 5655 DefArgResult = ParseAssignmentExpression(); 5656 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult); 5657 if (DefArgResult.isInvalid()) { 5658 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc); 5659 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch); 5660 } else { 5661 // Inform the actions module about the default argument 5662 Actions.ActOnParamDefaultArgument(Param, EqualLoc, 5663 DefArgResult.get()); 5664 } 5665 } 5666 } 5667 5668 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 5669 ParmDeclarator.getIdentifierLoc(), 5670 Param, DefArgToks)); 5671 } 5672 5673 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) { 5674 if (!getLangOpts().CPlusPlus) { 5675 // We have ellipsis without a preceding ',', which is ill-formed 5676 // in C. Complain and provide the fix. 5677 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis) 5678 << FixItHint::CreateInsertion(EllipsisLoc, ", "); 5679 } else if (ParmDeclarator.getEllipsisLoc().isValid() || 5680 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) { 5681 // It looks like this was supposed to be a parameter pack. Warn and 5682 // point out where the ellipsis should have gone. 5683 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc(); 5684 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg) 5685 << ParmEllipsis.isValid() << ParmEllipsis; 5686 if (ParmEllipsis.isValid()) { 5687 Diag(ParmEllipsis, 5688 diag::note_misplaced_ellipsis_vararg_existing_ellipsis); 5689 } else { 5690 Diag(ParmDeclarator.getIdentifierLoc(), 5691 diag::note_misplaced_ellipsis_vararg_add_ellipsis) 5692 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(), 5693 "...") 5694 << !ParmDeclarator.hasName(); 5695 } 5696 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma) 5697 << FixItHint::CreateInsertion(EllipsisLoc, ", "); 5698 } 5699 5700 // We can't have any more parameters after an ellipsis. 5701 break; 5702 } 5703 5704 // If the next token is a comma, consume it and keep reading arguments. 5705 } while (TryConsumeToken(tok::comma)); 5706} 5707 5708/// [C90] direct-declarator '[' constant-expression[opt] ']' 5709/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 5710/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 5711/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 5712/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 5713/// [C++11] direct-declarator '[' constant-expression[opt] ']' 5714/// attribute-specifier-seq[opt] 5715void Parser::ParseBracketDeclarator(Declarator &D) { 5716 if (CheckProhibitedCXX11Attribute()) 5717 return; 5718 5719 BalancedDelimiterTracker T(*this, tok::l_square); 5720 T.consumeOpen(); 5721 5722 // C array syntax has many features, but by-far the most common is [] and [4]. 5723 // This code does a fast path to handle some of the most obvious cases. 5724 if (Tok.getKind() == tok::r_square) { 5725 T.consumeClose(); 5726 ParsedAttributes attrs(AttrFactory); 5727 MaybeParseCXX11Attributes(attrs); 5728 5729 // Remember that we parsed the empty array type. 5730 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr, 5731 T.getOpenLocation(), 5732 T.getCloseLocation()), 5733 attrs, T.getCloseLocation()); 5734 return; 5735 } else if (Tok.getKind() == tok::numeric_constant && 5736 GetLookAheadToken(1).is(tok::r_square)) { 5737 // [4] is very common. Parse the numeric constant expression. 5738 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope())); 5739 ConsumeToken(); 5740 5741 T.consumeClose(); 5742 ParsedAttributes attrs(AttrFactory); 5743 MaybeParseCXX11Attributes(attrs); 5744 5745 // Remember that we parsed a array type, and remember its features. 5746 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 5747 ExprRes.get(), 5748 T.getOpenLocation(), 5749 T.getCloseLocation()), 5750 attrs, T.getCloseLocation()); 5751 return; 5752 } 5753 5754 // If valid, this location is the position where we read the 'static' keyword. 5755 SourceLocation StaticLoc; 5756 TryConsumeToken(tok::kw_static, StaticLoc); 5757 5758 // If there is a type-qualifier-list, read it now. 5759 // Type qualifiers in an array subscript are a C99 feature. 5760 DeclSpec DS(AttrFactory); 5761 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed); 5762 5763 // If we haven't already read 'static', check to see if there is one after the 5764 // type-qualifier-list. 5765 if (!StaticLoc.isValid()) 5766 TryConsumeToken(tok::kw_static, StaticLoc); 5767 5768 // Handle "direct-declarator [ type-qual-list[opt] * ]". 5769 bool isStar = false; 5770 ExprResult NumElements; 5771 5772 // Handle the case where we have '[*]' as the array size. However, a leading 5773 // star could be the start of an expression, for example 'X[*p + 4]'. Verify 5774 // the token after the star is a ']'. Since stars in arrays are 5775 // infrequent, use of lookahead is not costly here. 5776 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) { 5777 ConsumeToken(); // Eat the '*'. 5778 5779 if (StaticLoc.isValid()) { 5780 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static); 5781 StaticLoc = SourceLocation(); // Drop the static. 5782 } 5783 isStar = true; 5784 } else if (Tok.isNot(tok::r_square)) { 5785 // Note, in C89, this production uses the constant-expr production instead 5786 // of assignment-expr. The only difference is that assignment-expr allows 5787 // things like '=' and '*='. Sema rejects these in C89 mode because they 5788 // are not i-c-e's, so we don't need to distinguish between the two here. 5789 5790 // Parse the constant-expression or assignment-expression now (depending 5791 // on dialect). 5792 if (getLangOpts().CPlusPlus) { 5793 NumElements = ParseConstantExpression(); 5794 } else { 5795 EnterExpressionEvaluationContext Unevaluated(Actions, 5796 Sema::ConstantEvaluated); 5797 NumElements = 5798 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()); 5799 } 5800 } else { 5801 if (StaticLoc.isValid()) { 5802 Diag(StaticLoc, diag::err_unspecified_size_with_static); 5803 StaticLoc = SourceLocation(); // Drop the static. 5804 } 5805 } 5806 5807 // If there was an error parsing the assignment-expression, recover. 5808 if (NumElements.isInvalid()) { 5809 D.setInvalidType(true); 5810 // If the expression was invalid, skip it. 5811 SkipUntil(tok::r_square, StopAtSemi); 5812 return; 5813 } 5814 5815 T.consumeClose(); 5816 5817 ParsedAttributes attrs(AttrFactory); 5818 MaybeParseCXX11Attributes(attrs); 5819 5820 // Remember that we parsed a array type, and remember its features. 5821 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(), 5822 StaticLoc.isValid(), isStar, 5823 NumElements.get(), 5824 T.getOpenLocation(), 5825 T.getCloseLocation()), 5826 attrs, T.getCloseLocation()); 5827} 5828 5829/// Diagnose brackets before an identifier. 5830void Parser::ParseMisplacedBracketDeclarator(Declarator &D) { 5831 assert(Tok.is(tok::l_square) && "Missing opening bracket"); 5832 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier"); 5833 5834 SourceLocation StartBracketLoc = Tok.getLocation(); 5835 Declarator TempDeclarator(D.getDeclSpec(), D.getContext()); 5836 5837 while (Tok.is(tok::l_square)) { 5838 ParseBracketDeclarator(TempDeclarator); 5839 } 5840 5841 // Stuff the location of the start of the brackets into the Declarator. 5842 // The diagnostics from ParseDirectDeclarator will make more sense if 5843 // they use this location instead. 5844 if (Tok.is(tok::semi)) 5845 D.getName().EndLocation = StartBracketLoc; 5846 5847 SourceLocation SuggestParenLoc = Tok.getLocation(); 5848 5849 // Now that the brackets are removed, try parsing the declarator again. 5850 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 5851 5852 // Something went wrong parsing the brackets, in which case, 5853 // ParseBracketDeclarator has emitted an error, and we don't need to emit 5854 // one here. 5855 if (TempDeclarator.getNumTypeObjects() == 0) 5856 return; 5857 5858 // Determine if parens will need to be suggested in the diagnostic. 5859 bool NeedParens = false; 5860 if (D.getNumTypeObjects() != 0) { 5861 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) { 5862 case DeclaratorChunk::Pointer: 5863 case DeclaratorChunk::Reference: 5864 case DeclaratorChunk::BlockPointer: 5865 case DeclaratorChunk::MemberPointer: 5866 NeedParens = true; 5867 break; 5868 case DeclaratorChunk::Array: 5869 case DeclaratorChunk::Function: 5870 case DeclaratorChunk::Paren: 5871 break; 5872 } 5873 } 5874 5875 if (NeedParens) { 5876 // Create a DeclaratorChunk for the inserted parens. 5877 ParsedAttributes attrs(AttrFactory); 5878 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd()); 5879 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), attrs, 5880 SourceLocation()); 5881 } 5882 5883 // Adding back the bracket info to the end of the Declarator. 5884 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) { 5885 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i); 5886 ParsedAttributes attrs(AttrFactory); 5887 attrs.set(Chunk.Common.AttrList); 5888 D.AddTypeInfo(Chunk, attrs, SourceLocation()); 5889 } 5890 5891 // The missing identifier would have been diagnosed in ParseDirectDeclarator. 5892 // If parentheses are required, always suggest them. 5893 if (!D.getIdentifier() && !NeedParens) 5894 return; 5895 5896 SourceLocation EndBracketLoc = TempDeclarator.getLocEnd(); 5897 5898 // Generate the move bracket error message. 5899 SourceRange BracketRange(StartBracketLoc, EndBracketLoc); 5900 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd()); 5901 5902 if (NeedParens) { 5903 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id) 5904 << getLangOpts().CPlusPlus 5905 << FixItHint::CreateInsertion(SuggestParenLoc, "(") 5906 << FixItHint::CreateInsertion(EndLoc, ")") 5907 << FixItHint::CreateInsertionFromRange( 5908 EndLoc, CharSourceRange(BracketRange, true)) 5909 << FixItHint::CreateRemoval(BracketRange); 5910 } else { 5911 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id) 5912 << getLangOpts().CPlusPlus 5913 << FixItHint::CreateInsertionFromRange( 5914 EndLoc, CharSourceRange(BracketRange, true)) 5915 << FixItHint::CreateRemoval(BracketRange); 5916 } 5917} 5918 5919/// [GNU] typeof-specifier: 5920/// typeof ( expressions ) 5921/// typeof ( type-name ) 5922/// [GNU/C++] typeof unary-expression 5923/// 5924void Parser::ParseTypeofSpecifier(DeclSpec &DS) { 5925 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier"); 5926 Token OpTok = Tok; 5927 SourceLocation StartLoc = ConsumeToken(); 5928 5929 const bool hasParens = Tok.is(tok::l_paren); 5930 5931 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated, 5932 Sema::ReuseLambdaContextDecl); 5933 5934 bool isCastExpr; 5935 ParsedType CastTy; 5936 SourceRange CastRange; 5937 ExprResult Operand = Actions.CorrectDelayedTyposInExpr( 5938 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange)); 5939 if (hasParens) 5940 DS.setTypeofParensRange(CastRange); 5941 5942 if (CastRange.getEnd().isInvalid()) 5943 // FIXME: Not accurate, the range gets one token more than it should. 5944 DS.SetRangeEnd(Tok.getLocation()); 5945 else 5946 DS.SetRangeEnd(CastRange.getEnd()); 5947 5948 if (isCastExpr) { 5949 if (!CastTy) { 5950 DS.SetTypeSpecError(); 5951 return; 5952 } 5953 5954 const char *PrevSpec = nullptr; 5955 unsigned DiagID; 5956 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 5957 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, 5958 DiagID, CastTy, 5959 Actions.getASTContext().getPrintingPolicy())) 5960 Diag(StartLoc, DiagID) << PrevSpec; 5961 return; 5962 } 5963 5964 // If we get here, the operand to the typeof was an expresion. 5965 if (Operand.isInvalid()) { 5966 DS.SetTypeSpecError(); 5967 return; 5968 } 5969 5970 // We might need to transform the operand if it is potentially evaluated. 5971 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get()); 5972 if (Operand.isInvalid()) { 5973 DS.SetTypeSpecError(); 5974 return; 5975 } 5976 5977 const char *PrevSpec = nullptr; 5978 unsigned DiagID; 5979 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 5980 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 5981 DiagID, Operand.get(), 5982 Actions.getASTContext().getPrintingPolicy())) 5983 Diag(StartLoc, DiagID) << PrevSpec; 5984} 5985 5986/// [C11] atomic-specifier: 5987/// _Atomic ( type-name ) 5988/// 5989void Parser::ParseAtomicSpecifier(DeclSpec &DS) { 5990 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) && 5991 "Not an atomic specifier"); 5992 5993 SourceLocation StartLoc = ConsumeToken(); 5994 BalancedDelimiterTracker T(*this, tok::l_paren); 5995 if (T.consumeOpen()) 5996 return; 5997 5998 TypeResult Result = ParseTypeName(); 5999 if (Result.isInvalid()) { 6000 SkipUntil(tok::r_paren, StopAtSemi); 6001 return; 6002 } 6003 6004 // Match the ')' 6005 T.consumeClose(); 6006 6007 if (T.getCloseLocation().isInvalid()) 6008 return; 6009 6010 DS.setTypeofParensRange(T.getRange()); 6011 DS.SetRangeEnd(T.getCloseLocation()); 6012 6013 const char *PrevSpec = nullptr; 6014 unsigned DiagID; 6015 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec, 6016 DiagID, Result.get(), 6017 Actions.getASTContext().getPrintingPolicy())) 6018 Diag(StartLoc, DiagID) << PrevSpec; 6019} 6020 6021 6022/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called 6023/// from TryAltiVecVectorToken. 6024bool Parser::TryAltiVecVectorTokenOutOfLine() { 6025 Token Next = NextToken(); 6026 switch (Next.getKind()) { 6027 default: return false; 6028 case tok::kw_short: 6029 case tok::kw_long: 6030 case tok::kw_signed: 6031 case tok::kw_unsigned: 6032 case tok::kw_void: 6033 case tok::kw_char: 6034 case tok::kw_int: 6035 case tok::kw_float: 6036 case tok::kw_double: 6037 case tok::kw_bool: 6038 case tok::kw___bool: 6039 case tok::kw___pixel: 6040 Tok.setKind(tok::kw___vector); 6041 return true; 6042 case tok::identifier: 6043 if (Next.getIdentifierInfo() == Ident_pixel) { 6044 Tok.setKind(tok::kw___vector); 6045 return true; 6046 } 6047 if (Next.getIdentifierInfo() == Ident_bool) { 6048 Tok.setKind(tok::kw___vector); 6049 return true; 6050 } 6051 return false; 6052 } 6053} 6054 6055bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, 6056 const char *&PrevSpec, unsigned &DiagID, 6057 bool &isInvalid) { 6058 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); 6059 if (Tok.getIdentifierInfo() == Ident_vector) { 6060 Token Next = NextToken(); 6061 switch (Next.getKind()) { 6062 case tok::kw_short: 6063 case tok::kw_long: 6064 case tok::kw_signed: 6065 case tok::kw_unsigned: 6066 case tok::kw_void: 6067 case tok::kw_char: 6068 case tok::kw_int: 6069 case tok::kw_float: 6070 case tok::kw_double: 6071 case tok::kw_bool: 6072 case tok::kw___bool: 6073 case tok::kw___pixel: 6074 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy); 6075 return true; 6076 case tok::identifier: 6077 if (Next.getIdentifierInfo() == Ident_pixel) { 6078 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy); 6079 return true; 6080 } 6081 if (Next.getIdentifierInfo() == Ident_bool) { 6082 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy); 6083 return true; 6084 } 6085 break; 6086 default: 6087 break; 6088 } 6089 } else if ((Tok.getIdentifierInfo() == Ident_pixel) && 6090 DS.isTypeAltiVecVector()) { 6091 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy); 6092 return true; 6093 } else if ((Tok.getIdentifierInfo() == Ident_bool) && 6094 DS.isTypeAltiVecVector()) { 6095 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy); 6096 return true; 6097 } 6098 return false; 6099} 6100