ParseDecl.cpp revision 327952
1//===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the Declaration portions of the Parser interfaces. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Parse/Parser.h" 15#include "clang/Parse/RAIIObjectsForParser.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/DeclTemplate.h" 18#include "clang/Basic/AddressSpaces.h" 19#include "clang/Basic/Attributes.h" 20#include "clang/Basic/CharInfo.h" 21#include "clang/Basic/TargetInfo.h" 22#include "clang/Parse/ParseDiagnostic.h" 23#include "clang/Sema/Lookup.h" 24#include "clang/Sema/ParsedTemplate.h" 25#include "clang/Sema/PrettyDeclStackTrace.h" 26#include "clang/Sema/Scope.h" 27#include "clang/Sema/SemaDiagnostic.h" 28#include "llvm/ADT/Optional.h" 29#include "llvm/ADT/SmallSet.h" 30#include "llvm/ADT/SmallString.h" 31#include "llvm/ADT/StringSwitch.h" 32#include "llvm/Support/ScopedPrinter.h" 33 34using namespace clang; 35 36//===----------------------------------------------------------------------===// 37// C99 6.7: Declarations. 38//===----------------------------------------------------------------------===// 39 40/// ParseTypeName 41/// type-name: [C99 6.7.6] 42/// specifier-qualifier-list abstract-declarator[opt] 43/// 44/// Called type-id in C++. 45TypeResult Parser::ParseTypeName(SourceRange *Range, 46 DeclaratorContext Context, 47 AccessSpecifier AS, 48 Decl **OwnedType, 49 ParsedAttributes *Attrs) { 50 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context); 51 if (DSC == DeclSpecContext::DSC_normal) 52 DSC = DeclSpecContext::DSC_type_specifier; 53 54 // Parse the common declaration-specifiers piece. 55 DeclSpec DS(AttrFactory); 56 if (Attrs) 57 DS.addAttributes(Attrs->getList()); 58 ParseSpecifierQualifierList(DS, AS, DSC); 59 if (OwnedType) 60 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr; 61 62 // Parse the abstract-declarator, if present. 63 Declarator DeclaratorInfo(DS, Context); 64 ParseDeclarator(DeclaratorInfo); 65 if (Range) 66 *Range = DeclaratorInfo.getSourceRange(); 67 68 if (DeclaratorInfo.isInvalidType()) 69 return true; 70 71 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 72} 73 74/// \brief Normalizes an attribute name by dropping prefixed and suffixed __. 75static StringRef normalizeAttrName(StringRef Name) { 76 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__")) 77 return Name.drop_front(2).drop_back(2); 78 return Name; 79} 80 81/// isAttributeLateParsed - Return true if the attribute has arguments that 82/// require late parsing. 83static bool isAttributeLateParsed(const IdentifierInfo &II) { 84#define CLANG_ATTR_LATE_PARSED_LIST 85 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName())) 86#include "clang/Parse/AttrParserStringSwitches.inc" 87 .Default(false); 88#undef CLANG_ATTR_LATE_PARSED_LIST 89} 90 91/// ParseGNUAttributes - Parse a non-empty attributes list. 92/// 93/// [GNU] attributes: 94/// attribute 95/// attributes attribute 96/// 97/// [GNU] attribute: 98/// '__attribute__' '(' '(' attribute-list ')' ')' 99/// 100/// [GNU] attribute-list: 101/// attrib 102/// attribute_list ',' attrib 103/// 104/// [GNU] attrib: 105/// empty 106/// attrib-name 107/// attrib-name '(' identifier ')' 108/// attrib-name '(' identifier ',' nonempty-expr-list ')' 109/// attrib-name '(' argument-expression-list [C99 6.5.2] ')' 110/// 111/// [GNU] attrib-name: 112/// identifier 113/// typespec 114/// typequal 115/// storageclass 116/// 117/// Whether an attribute takes an 'identifier' is determined by the 118/// attrib-name. GCC's behavior here is not worth imitating: 119/// 120/// * In C mode, if the attribute argument list starts with an identifier 121/// followed by a ',' or an ')', and the identifier doesn't resolve to 122/// a type, it is parsed as an identifier. If the attribute actually 123/// wanted an expression, it's out of luck (but it turns out that no 124/// attributes work that way, because C constant expressions are very 125/// limited). 126/// * In C++ mode, if the attribute argument list starts with an identifier, 127/// and the attribute *wants* an identifier, it is parsed as an identifier. 128/// At block scope, any additional tokens between the identifier and the 129/// ',' or ')' are ignored, otherwise they produce a parse error. 130/// 131/// We follow the C++ model, but don't allow junk after the identifier. 132void Parser::ParseGNUAttributes(ParsedAttributes &attrs, 133 SourceLocation *endLoc, 134 LateParsedAttrList *LateAttrs, 135 Declarator *D) { 136 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!"); 137 138 while (Tok.is(tok::kw___attribute)) { 139 ConsumeToken(); 140 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 141 "attribute")) { 142 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ; 143 return; 144 } 145 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) { 146 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ; 147 return; 148 } 149 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") )) 150 while (true) { 151 // Allow empty/non-empty attributes. ((__vector_size__(16),,,,)) 152 if (TryConsumeToken(tok::comma)) 153 continue; 154 155 // Expect an identifier or declaration specifier (const, int, etc.) 156 if (Tok.isAnnotation()) 157 break; 158 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 159 if (!AttrName) 160 break; 161 162 SourceLocation AttrNameLoc = ConsumeToken(); 163 164 if (Tok.isNot(tok::l_paren)) { 165 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 166 AttributeList::AS_GNU); 167 continue; 168 } 169 170 // Handle "parameterized" attributes 171 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) { 172 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr, 173 SourceLocation(), AttributeList::AS_GNU, D); 174 continue; 175 } 176 177 // Handle attributes with arguments that require late parsing. 178 LateParsedAttribute *LA = 179 new LateParsedAttribute(this, *AttrName, AttrNameLoc); 180 LateAttrs->push_back(LA); 181 182 // Attributes in a class are parsed at the end of the class, along 183 // with other late-parsed declarations. 184 if (!ClassStack.empty() && !LateAttrs->parseSoon()) 185 getCurrentClass().LateParsedDeclarations.push_back(LA); 186 187 // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it 188 // recursively consumes balanced parens. 189 LA->Toks.push_back(Tok); 190 ConsumeParen(); 191 // Consume everything up to and including the matching right parens. 192 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true); 193 194 Token Eof; 195 Eof.startToken(); 196 Eof.setLocation(Tok.getLocation()); 197 LA->Toks.push_back(Eof); 198 } 199 200 if (ExpectAndConsume(tok::r_paren)) 201 SkipUntil(tok::r_paren, StopAtSemi); 202 SourceLocation Loc = Tok.getLocation(); 203 if (ExpectAndConsume(tok::r_paren)) 204 SkipUntil(tok::r_paren, StopAtSemi); 205 if (endLoc) 206 *endLoc = Loc; 207 } 208} 209 210/// \brief Determine whether the given attribute has an identifier argument. 211static bool attributeHasIdentifierArg(const IdentifierInfo &II) { 212#define CLANG_ATTR_IDENTIFIER_ARG_LIST 213 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName())) 214#include "clang/Parse/AttrParserStringSwitches.inc" 215 .Default(false); 216#undef CLANG_ATTR_IDENTIFIER_ARG_LIST 217} 218 219/// \brief Determine whether the given attribute parses a type argument. 220static bool attributeIsTypeArgAttr(const IdentifierInfo &II) { 221#define CLANG_ATTR_TYPE_ARG_LIST 222 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName())) 223#include "clang/Parse/AttrParserStringSwitches.inc" 224 .Default(false); 225#undef CLANG_ATTR_TYPE_ARG_LIST 226} 227 228/// \brief Determine whether the given attribute requires parsing its arguments 229/// in an unevaluated context or not. 230static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) { 231#define CLANG_ATTR_ARG_CONTEXT_LIST 232 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName())) 233#include "clang/Parse/AttrParserStringSwitches.inc" 234 .Default(false); 235#undef CLANG_ATTR_ARG_CONTEXT_LIST 236} 237 238IdentifierLoc *Parser::ParseIdentifierLoc() { 239 assert(Tok.is(tok::identifier) && "expected an identifier"); 240 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context, 241 Tok.getLocation(), 242 Tok.getIdentifierInfo()); 243 ConsumeToken(); 244 return IL; 245} 246 247void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName, 248 SourceLocation AttrNameLoc, 249 ParsedAttributes &Attrs, 250 SourceLocation *EndLoc, 251 IdentifierInfo *ScopeName, 252 SourceLocation ScopeLoc, 253 AttributeList::Syntax Syntax) { 254 BalancedDelimiterTracker Parens(*this, tok::l_paren); 255 Parens.consumeOpen(); 256 257 TypeResult T; 258 if (Tok.isNot(tok::r_paren)) 259 T = ParseTypeName(); 260 261 if (Parens.consumeClose()) 262 return; 263 264 if (T.isInvalid()) 265 return; 266 267 if (T.isUsable()) 268 Attrs.addNewTypeAttr(&AttrName, 269 SourceRange(AttrNameLoc, Parens.getCloseLocation()), 270 ScopeName, ScopeLoc, T.get(), Syntax); 271 else 272 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()), 273 ScopeName, ScopeLoc, nullptr, 0, Syntax); 274} 275 276unsigned Parser::ParseAttributeArgsCommon( 277 IdentifierInfo *AttrName, SourceLocation AttrNameLoc, 278 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, 279 SourceLocation ScopeLoc, AttributeList::Syntax Syntax) { 280 // Ignore the left paren location for now. 281 ConsumeParen(); 282 283 ArgsVector ArgExprs; 284 if (Tok.is(tok::identifier)) { 285 // If this attribute wants an 'identifier' argument, make it so. 286 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName); 287 AttributeList::Kind AttrKind = 288 AttributeList::getKind(AttrName, ScopeName, Syntax); 289 290 // If we don't know how to parse this attribute, but this is the only 291 // token in this argument, assume it's meant to be an identifier. 292 if (AttrKind == AttributeList::UnknownAttribute || 293 AttrKind == AttributeList::IgnoredAttribute) { 294 const Token &Next = NextToken(); 295 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma); 296 } 297 298 if (IsIdentifierArg) 299 ArgExprs.push_back(ParseIdentifierLoc()); 300 } 301 302 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) { 303 // Eat the comma. 304 if (!ArgExprs.empty()) 305 ConsumeToken(); 306 307 // Parse the non-empty comma-separated list of expressions. 308 do { 309 bool Uneval = attributeParsedArgsUnevaluated(*AttrName); 310 EnterExpressionEvaluationContext Unevaluated( 311 Actions, 312 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated 313 : Sema::ExpressionEvaluationContext::ConstantEvaluated, 314 /*LambdaContextDecl=*/nullptr, 315 /*IsDecltype=*/false); 316 317 ExprResult ArgExpr( 318 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression())); 319 if (ArgExpr.isInvalid()) { 320 SkipUntil(tok::r_paren, StopAtSemi); 321 return 0; 322 } 323 ArgExprs.push_back(ArgExpr.get()); 324 // Eat the comma, move to the next argument 325 } while (TryConsumeToken(tok::comma)); 326 } 327 328 SourceLocation RParen = Tok.getLocation(); 329 if (!ExpectAndConsume(tok::r_paren)) { 330 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc; 331 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc, 332 ArgExprs.data(), ArgExprs.size(), Syntax); 333 } 334 335 if (EndLoc) 336 *EndLoc = RParen; 337 338 return static_cast<unsigned>(ArgExprs.size()); 339} 340 341/// Parse the arguments to a parameterized GNU attribute or 342/// a C++11 attribute in "gnu" namespace. 343void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName, 344 SourceLocation AttrNameLoc, 345 ParsedAttributes &Attrs, 346 SourceLocation *EndLoc, 347 IdentifierInfo *ScopeName, 348 SourceLocation ScopeLoc, 349 AttributeList::Syntax Syntax, 350 Declarator *D) { 351 352 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); 353 354 AttributeList::Kind AttrKind = 355 AttributeList::getKind(AttrName, ScopeName, Syntax); 356 357 if (AttrKind == AttributeList::AT_Availability) { 358 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, 359 ScopeLoc, Syntax); 360 return; 361 } else if (AttrKind == AttributeList::AT_ExternalSourceSymbol) { 362 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, 363 ScopeName, ScopeLoc, Syntax); 364 return; 365 } else if (AttrKind == AttributeList::AT_ObjCBridgeRelated) { 366 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, 367 ScopeName, ScopeLoc, Syntax); 368 return; 369 } else if (AttrKind == AttributeList::AT_TypeTagForDatatype) { 370 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, 371 ScopeName, ScopeLoc, Syntax); 372 return; 373 } else if (attributeIsTypeArgAttr(*AttrName)) { 374 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, 375 ScopeLoc, Syntax); 376 return; 377 } 378 379 // These may refer to the function arguments, but need to be parsed early to 380 // participate in determining whether it's a redeclaration. 381 llvm::Optional<ParseScope> PrototypeScope; 382 if (normalizeAttrName(AttrName->getName()) == "enable_if" && 383 D && D->isFunctionDeclarator()) { 384 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo(); 385 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope | 386 Scope::FunctionDeclarationScope | 387 Scope::DeclScope); 388 for (unsigned i = 0; i != FTI.NumParams; ++i) { 389 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 390 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param); 391 } 392 } 393 394 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, 395 ScopeLoc, Syntax); 396} 397 398unsigned Parser::ParseClangAttributeArgs( 399 IdentifierInfo *AttrName, SourceLocation AttrNameLoc, 400 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, 401 SourceLocation ScopeLoc, AttributeList::Syntax Syntax) { 402 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); 403 404 AttributeList::Kind AttrKind = 405 AttributeList::getKind(AttrName, ScopeName, Syntax); 406 407 if (AttrKind == AttributeList::AT_ExternalSourceSymbol) { 408 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, 409 ScopeName, ScopeLoc, Syntax); 410 return Attrs.getList() ? Attrs.getList()->getNumArgs() : 0; 411 } 412 413 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, 414 ScopeName, ScopeLoc, Syntax); 415} 416 417bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, 418 SourceLocation AttrNameLoc, 419 ParsedAttributes &Attrs) { 420 // If the attribute isn't known, we will not attempt to parse any 421 // arguments. 422 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName, 423 getTargetInfo(), getLangOpts())) { 424 // Eat the left paren, then skip to the ending right paren. 425 ConsumeParen(); 426 SkipUntil(tok::r_paren); 427 return false; 428 } 429 430 SourceLocation OpenParenLoc = Tok.getLocation(); 431 432 if (AttrName->getName() == "property") { 433 // The property declspec is more complex in that it can take one or two 434 // assignment expressions as a parameter, but the lhs of the assignment 435 // must be named get or put. 436 437 BalancedDelimiterTracker T(*this, tok::l_paren); 438 T.expectAndConsume(diag::err_expected_lparen_after, 439 AttrName->getNameStart(), tok::r_paren); 440 441 enum AccessorKind { 442 AK_Invalid = -1, 443 AK_Put = 0, 444 AK_Get = 1 // indices into AccessorNames 445 }; 446 IdentifierInfo *AccessorNames[] = {nullptr, nullptr}; 447 bool HasInvalidAccessor = false; 448 449 // Parse the accessor specifications. 450 while (true) { 451 // Stop if this doesn't look like an accessor spec. 452 if (!Tok.is(tok::identifier)) { 453 // If the user wrote a completely empty list, use a special diagnostic. 454 if (Tok.is(tok::r_paren) && !HasInvalidAccessor && 455 AccessorNames[AK_Put] == nullptr && 456 AccessorNames[AK_Get] == nullptr) { 457 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter); 458 break; 459 } 460 461 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor); 462 break; 463 } 464 465 AccessorKind Kind; 466 SourceLocation KindLoc = Tok.getLocation(); 467 StringRef KindStr = Tok.getIdentifierInfo()->getName(); 468 if (KindStr == "get") { 469 Kind = AK_Get; 470 } else if (KindStr == "put") { 471 Kind = AK_Put; 472 473 // Recover from the common mistake of using 'set' instead of 'put'. 474 } else if (KindStr == "set") { 475 Diag(KindLoc, diag::err_ms_property_has_set_accessor) 476 << FixItHint::CreateReplacement(KindLoc, "put"); 477 Kind = AK_Put; 478 479 // Handle the mistake of forgetting the accessor kind by skipping 480 // this accessor. 481 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) { 482 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind); 483 ConsumeToken(); 484 HasInvalidAccessor = true; 485 goto next_property_accessor; 486 487 // Otherwise, complain about the unknown accessor kind. 488 } else { 489 Diag(KindLoc, diag::err_ms_property_unknown_accessor); 490 HasInvalidAccessor = true; 491 Kind = AK_Invalid; 492 493 // Try to keep parsing unless it doesn't look like an accessor spec. 494 if (!NextToken().is(tok::equal)) 495 break; 496 } 497 498 // Consume the identifier. 499 ConsumeToken(); 500 501 // Consume the '='. 502 if (!TryConsumeToken(tok::equal)) { 503 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal) 504 << KindStr; 505 break; 506 } 507 508 // Expect the method name. 509 if (!Tok.is(tok::identifier)) { 510 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name); 511 break; 512 } 513 514 if (Kind == AK_Invalid) { 515 // Just drop invalid accessors. 516 } else if (AccessorNames[Kind] != nullptr) { 517 // Complain about the repeated accessor, ignore it, and keep parsing. 518 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr; 519 } else { 520 AccessorNames[Kind] = Tok.getIdentifierInfo(); 521 } 522 ConsumeToken(); 523 524 next_property_accessor: 525 // Keep processing accessors until we run out. 526 if (TryConsumeToken(tok::comma)) 527 continue; 528 529 // If we run into the ')', stop without consuming it. 530 if (Tok.is(tok::r_paren)) 531 break; 532 533 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen); 534 break; 535 } 536 537 // Only add the property attribute if it was well-formed. 538 if (!HasInvalidAccessor) 539 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(), 540 AccessorNames[AK_Get], AccessorNames[AK_Put], 541 AttributeList::AS_Declspec); 542 T.skipToEnd(); 543 return !HasInvalidAccessor; 544 } 545 546 unsigned NumArgs = 547 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr, 548 SourceLocation(), AttributeList::AS_Declspec); 549 550 // If this attribute's args were parsed, and it was expected to have 551 // arguments but none were provided, emit a diagnostic. 552 const AttributeList *Attr = Attrs.getList(); 553 if (Attr && Attr->getMaxArgs() && !NumArgs) { 554 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName; 555 return false; 556 } 557 return true; 558} 559 560/// [MS] decl-specifier: 561/// __declspec ( extended-decl-modifier-seq ) 562/// 563/// [MS] extended-decl-modifier-seq: 564/// extended-decl-modifier[opt] 565/// extended-decl-modifier extended-decl-modifier-seq 566void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, 567 SourceLocation *End) { 568 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled"); 569 assert(Tok.is(tok::kw___declspec) && "Not a declspec!"); 570 571 while (Tok.is(tok::kw___declspec)) { 572 ConsumeToken(); 573 BalancedDelimiterTracker T(*this, tok::l_paren); 574 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec", 575 tok::r_paren)) 576 return; 577 578 // An empty declspec is perfectly legal and should not warn. Additionally, 579 // you can specify multiple attributes per declspec. 580 while (Tok.isNot(tok::r_paren)) { 581 // Attribute not present. 582 if (TryConsumeToken(tok::comma)) 583 continue; 584 585 // We expect either a well-known identifier or a generic string. Anything 586 // else is a malformed declspec. 587 bool IsString = Tok.getKind() == tok::string_literal; 588 if (!IsString && Tok.getKind() != tok::identifier && 589 Tok.getKind() != tok::kw_restrict) { 590 Diag(Tok, diag::err_ms_declspec_type); 591 T.skipToEnd(); 592 return; 593 } 594 595 IdentifierInfo *AttrName; 596 SourceLocation AttrNameLoc; 597 if (IsString) { 598 SmallString<8> StrBuffer; 599 bool Invalid = false; 600 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid); 601 if (Invalid) { 602 T.skipToEnd(); 603 return; 604 } 605 AttrName = PP.getIdentifierInfo(Str); 606 AttrNameLoc = ConsumeStringToken(); 607 } else { 608 AttrName = Tok.getIdentifierInfo(); 609 AttrNameLoc = ConsumeToken(); 610 } 611 612 bool AttrHandled = false; 613 614 // Parse attribute arguments. 615 if (Tok.is(tok::l_paren)) 616 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs); 617 else if (AttrName->getName() == "property") 618 // The property attribute must have an argument list. 619 Diag(Tok.getLocation(), diag::err_expected_lparen_after) 620 << AttrName->getName(); 621 622 if (!AttrHandled) 623 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 624 AttributeList::AS_Declspec); 625 } 626 T.consumeClose(); 627 if (End) 628 *End = T.getCloseLocation(); 629 } 630} 631 632void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) { 633 // Treat these like attributes 634 while (true) { 635 switch (Tok.getKind()) { 636 case tok::kw___fastcall: 637 case tok::kw___stdcall: 638 case tok::kw___thiscall: 639 case tok::kw___regcall: 640 case tok::kw___cdecl: 641 case tok::kw___vectorcall: 642 case tok::kw___ptr64: 643 case tok::kw___w64: 644 case tok::kw___ptr32: 645 case tok::kw___sptr: 646 case tok::kw___uptr: { 647 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 648 SourceLocation AttrNameLoc = ConsumeToken(); 649 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 650 AttributeList::AS_Keyword); 651 break; 652 } 653 default: 654 return; 655 } 656 } 657} 658 659void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() { 660 SourceLocation StartLoc = Tok.getLocation(); 661 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes(); 662 663 if (EndLoc.isValid()) { 664 SourceRange Range(StartLoc, EndLoc); 665 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range; 666 } 667} 668 669SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() { 670 SourceLocation EndLoc; 671 672 while (true) { 673 switch (Tok.getKind()) { 674 case tok::kw_const: 675 case tok::kw_volatile: 676 case tok::kw___fastcall: 677 case tok::kw___stdcall: 678 case tok::kw___thiscall: 679 case tok::kw___cdecl: 680 case tok::kw___vectorcall: 681 case tok::kw___ptr32: 682 case tok::kw___ptr64: 683 case tok::kw___w64: 684 case tok::kw___unaligned: 685 case tok::kw___sptr: 686 case tok::kw___uptr: 687 EndLoc = ConsumeToken(); 688 break; 689 default: 690 return EndLoc; 691 } 692 } 693} 694 695void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) { 696 // Treat these like attributes 697 while (Tok.is(tok::kw___pascal)) { 698 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 699 SourceLocation AttrNameLoc = ConsumeToken(); 700 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 701 AttributeList::AS_Keyword); 702 } 703} 704 705void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) { 706 // Treat these like attributes 707 while (Tok.is(tok::kw___kernel)) { 708 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 709 SourceLocation AttrNameLoc = ConsumeToken(); 710 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 711 AttributeList::AS_Keyword); 712 } 713} 714 715void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) { 716 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 717 SourceLocation AttrNameLoc = Tok.getLocation(); 718 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 719 AttributeList::AS_Keyword); 720} 721 722void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) { 723 // Treat these like attributes, even though they're type specifiers. 724 while (true) { 725 switch (Tok.getKind()) { 726 case tok::kw__Nonnull: 727 case tok::kw__Nullable: 728 case tok::kw__Null_unspecified: { 729 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 730 SourceLocation AttrNameLoc = ConsumeToken(); 731 if (!getLangOpts().ObjC1) 732 Diag(AttrNameLoc, diag::ext_nullability) 733 << AttrName; 734 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 735 AttributeList::AS_Keyword); 736 break; 737 } 738 default: 739 return; 740 } 741 } 742} 743 744static bool VersionNumberSeparator(const char Separator) { 745 return (Separator == '.' || Separator == '_'); 746} 747 748/// \brief Parse a version number. 749/// 750/// version: 751/// simple-integer 752/// simple-integer ',' simple-integer 753/// simple-integer ',' simple-integer ',' simple-integer 754VersionTuple Parser::ParseVersionTuple(SourceRange &Range) { 755 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc()); 756 757 if (!Tok.is(tok::numeric_constant)) { 758 Diag(Tok, diag::err_expected_version); 759 SkipUntil(tok::comma, tok::r_paren, 760 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); 761 return VersionTuple(); 762 } 763 764 // Parse the major (and possibly minor and subminor) versions, which 765 // are stored in the numeric constant. We utilize a quirk of the 766 // lexer, which is that it handles something like 1.2.3 as a single 767 // numeric constant, rather than two separate tokens. 768 SmallString<512> Buffer; 769 Buffer.resize(Tok.getLength()+1); 770 const char *ThisTokBegin = &Buffer[0]; 771 772 // Get the spelling of the token, which eliminates trigraphs, etc. 773 bool Invalid = false; 774 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid); 775 if (Invalid) 776 return VersionTuple(); 777 778 // Parse the major version. 779 unsigned AfterMajor = 0; 780 unsigned Major = 0; 781 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) { 782 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0'; 783 ++AfterMajor; 784 } 785 786 if (AfterMajor == 0) { 787 Diag(Tok, diag::err_expected_version); 788 SkipUntil(tok::comma, tok::r_paren, 789 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); 790 return VersionTuple(); 791 } 792 793 if (AfterMajor == ActualLength) { 794 ConsumeToken(); 795 796 // We only had a single version component. 797 if (Major == 0) { 798 Diag(Tok, diag::err_zero_version); 799 return VersionTuple(); 800 } 801 802 return VersionTuple(Major); 803 } 804 805 const char AfterMajorSeparator = ThisTokBegin[AfterMajor]; 806 if (!VersionNumberSeparator(AfterMajorSeparator) 807 || (AfterMajor + 1 == ActualLength)) { 808 Diag(Tok, diag::err_expected_version); 809 SkipUntil(tok::comma, tok::r_paren, 810 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); 811 return VersionTuple(); 812 } 813 814 // Parse the minor version. 815 unsigned AfterMinor = AfterMajor + 1; 816 unsigned Minor = 0; 817 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) { 818 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0'; 819 ++AfterMinor; 820 } 821 822 if (AfterMinor == ActualLength) { 823 ConsumeToken(); 824 825 // We had major.minor. 826 if (Major == 0 && Minor == 0) { 827 Diag(Tok, diag::err_zero_version); 828 return VersionTuple(); 829 } 830 831 return VersionTuple(Major, Minor, (AfterMajorSeparator == '_')); 832 } 833 834 const char AfterMinorSeparator = ThisTokBegin[AfterMinor]; 835 // If what follows is not a '.' or '_', we have a problem. 836 if (!VersionNumberSeparator(AfterMinorSeparator)) { 837 Diag(Tok, diag::err_expected_version); 838 SkipUntil(tok::comma, tok::r_paren, 839 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); 840 return VersionTuple(); 841 } 842 843 // Warn if separators, be it '.' or '_', do not match. 844 if (AfterMajorSeparator != AfterMinorSeparator) 845 Diag(Tok, diag::warn_expected_consistent_version_separator); 846 847 // Parse the subminor version. 848 unsigned AfterSubminor = AfterMinor + 1; 849 unsigned Subminor = 0; 850 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) { 851 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0'; 852 ++AfterSubminor; 853 } 854 855 if (AfterSubminor != ActualLength) { 856 Diag(Tok, diag::err_expected_version); 857 SkipUntil(tok::comma, tok::r_paren, 858 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); 859 return VersionTuple(); 860 } 861 ConsumeToken(); 862 return VersionTuple(Major, Minor, Subminor, (AfterMajorSeparator == '_')); 863} 864 865/// \brief Parse the contents of the "availability" attribute. 866/// 867/// availability-attribute: 868/// 'availability' '(' platform ',' opt-strict version-arg-list, 869/// opt-replacement, opt-message')' 870/// 871/// platform: 872/// identifier 873/// 874/// opt-strict: 875/// 'strict' ',' 876/// 877/// version-arg-list: 878/// version-arg 879/// version-arg ',' version-arg-list 880/// 881/// version-arg: 882/// 'introduced' '=' version 883/// 'deprecated' '=' version 884/// 'obsoleted' = version 885/// 'unavailable' 886/// opt-replacement: 887/// 'replacement' '=' <string> 888/// opt-message: 889/// 'message' '=' <string> 890void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability, 891 SourceLocation AvailabilityLoc, 892 ParsedAttributes &attrs, 893 SourceLocation *endLoc, 894 IdentifierInfo *ScopeName, 895 SourceLocation ScopeLoc, 896 AttributeList::Syntax Syntax) { 897 enum { Introduced, Deprecated, Obsoleted, Unknown }; 898 AvailabilityChange Changes[Unknown]; 899 ExprResult MessageExpr, ReplacementExpr; 900 901 // Opening '('. 902 BalancedDelimiterTracker T(*this, tok::l_paren); 903 if (T.consumeOpen()) { 904 Diag(Tok, diag::err_expected) << tok::l_paren; 905 return; 906 } 907 908 // Parse the platform name. 909 if (Tok.isNot(tok::identifier)) { 910 Diag(Tok, diag::err_availability_expected_platform); 911 SkipUntil(tok::r_paren, StopAtSemi); 912 return; 913 } 914 IdentifierLoc *Platform = ParseIdentifierLoc(); 915 if (const IdentifierInfo *const Ident = Platform->Ident) { 916 // Canonicalize platform name from "macosx" to "macos". 917 if (Ident->getName() == "macosx") 918 Platform->Ident = PP.getIdentifierInfo("macos"); 919 // Canonicalize platform name from "macosx_app_extension" to 920 // "macos_app_extension". 921 else if (Ident->getName() == "macosx_app_extension") 922 Platform->Ident = PP.getIdentifierInfo("macos_app_extension"); 923 else 924 Platform->Ident = PP.getIdentifierInfo( 925 AvailabilityAttr::canonicalizePlatformName(Ident->getName())); 926 } 927 928 // Parse the ',' following the platform name. 929 if (ExpectAndConsume(tok::comma)) { 930 SkipUntil(tok::r_paren, StopAtSemi); 931 return; 932 } 933 934 // If we haven't grabbed the pointers for the identifiers 935 // "introduced", "deprecated", and "obsoleted", do so now. 936 if (!Ident_introduced) { 937 Ident_introduced = PP.getIdentifierInfo("introduced"); 938 Ident_deprecated = PP.getIdentifierInfo("deprecated"); 939 Ident_obsoleted = PP.getIdentifierInfo("obsoleted"); 940 Ident_unavailable = PP.getIdentifierInfo("unavailable"); 941 Ident_message = PP.getIdentifierInfo("message"); 942 Ident_strict = PP.getIdentifierInfo("strict"); 943 Ident_replacement = PP.getIdentifierInfo("replacement"); 944 } 945 946 // Parse the optional "strict", the optional "replacement" and the set of 947 // introductions/deprecations/removals. 948 SourceLocation UnavailableLoc, StrictLoc; 949 do { 950 if (Tok.isNot(tok::identifier)) { 951 Diag(Tok, diag::err_availability_expected_change); 952 SkipUntil(tok::r_paren, StopAtSemi); 953 return; 954 } 955 IdentifierInfo *Keyword = Tok.getIdentifierInfo(); 956 SourceLocation KeywordLoc = ConsumeToken(); 957 958 if (Keyword == Ident_strict) { 959 if (StrictLoc.isValid()) { 960 Diag(KeywordLoc, diag::err_availability_redundant) 961 << Keyword << SourceRange(StrictLoc); 962 } 963 StrictLoc = KeywordLoc; 964 continue; 965 } 966 967 if (Keyword == Ident_unavailable) { 968 if (UnavailableLoc.isValid()) { 969 Diag(KeywordLoc, diag::err_availability_redundant) 970 << Keyword << SourceRange(UnavailableLoc); 971 } 972 UnavailableLoc = KeywordLoc; 973 continue; 974 } 975 976 if (Tok.isNot(tok::equal)) { 977 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal; 978 SkipUntil(tok::r_paren, StopAtSemi); 979 return; 980 } 981 ConsumeToken(); 982 if (Keyword == Ident_message || Keyword == Ident_replacement) { 983 if (Tok.isNot(tok::string_literal)) { 984 Diag(Tok, diag::err_expected_string_literal) 985 << /*Source='availability attribute'*/2; 986 SkipUntil(tok::r_paren, StopAtSemi); 987 return; 988 } 989 if (Keyword == Ident_message) 990 MessageExpr = ParseStringLiteralExpression(); 991 else 992 ReplacementExpr = ParseStringLiteralExpression(); 993 // Also reject wide string literals. 994 if (StringLiteral *MessageStringLiteral = 995 cast_or_null<StringLiteral>(MessageExpr.get())) { 996 if (MessageStringLiteral->getCharByteWidth() != 1) { 997 Diag(MessageStringLiteral->getSourceRange().getBegin(), 998 diag::err_expected_string_literal) 999 << /*Source='availability attribute'*/ 2; 1000 SkipUntil(tok::r_paren, StopAtSemi); 1001 return; 1002 } 1003 } 1004 if (Keyword == Ident_message) 1005 break; 1006 else 1007 continue; 1008 } 1009 1010 // Special handling of 'NA' only when applied to introduced or 1011 // deprecated. 1012 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) && 1013 Tok.is(tok::identifier)) { 1014 IdentifierInfo *NA = Tok.getIdentifierInfo(); 1015 if (NA->getName() == "NA") { 1016 ConsumeToken(); 1017 if (Keyword == Ident_introduced) 1018 UnavailableLoc = KeywordLoc; 1019 continue; 1020 } 1021 } 1022 1023 SourceRange VersionRange; 1024 VersionTuple Version = ParseVersionTuple(VersionRange); 1025 1026 if (Version.empty()) { 1027 SkipUntil(tok::r_paren, StopAtSemi); 1028 return; 1029 } 1030 1031 unsigned Index; 1032 if (Keyword == Ident_introduced) 1033 Index = Introduced; 1034 else if (Keyword == Ident_deprecated) 1035 Index = Deprecated; 1036 else if (Keyword == Ident_obsoleted) 1037 Index = Obsoleted; 1038 else 1039 Index = Unknown; 1040 1041 if (Index < Unknown) { 1042 if (!Changes[Index].KeywordLoc.isInvalid()) { 1043 Diag(KeywordLoc, diag::err_availability_redundant) 1044 << Keyword 1045 << SourceRange(Changes[Index].KeywordLoc, 1046 Changes[Index].VersionRange.getEnd()); 1047 } 1048 1049 Changes[Index].KeywordLoc = KeywordLoc; 1050 Changes[Index].Version = Version; 1051 Changes[Index].VersionRange = VersionRange; 1052 } else { 1053 Diag(KeywordLoc, diag::err_availability_unknown_change) 1054 << Keyword << VersionRange; 1055 } 1056 1057 } while (TryConsumeToken(tok::comma)); 1058 1059 // Closing ')'. 1060 if (T.consumeClose()) 1061 return; 1062 1063 if (endLoc) 1064 *endLoc = T.getCloseLocation(); 1065 1066 // The 'unavailable' availability cannot be combined with any other 1067 // availability changes. Make sure that hasn't happened. 1068 if (UnavailableLoc.isValid()) { 1069 bool Complained = false; 1070 for (unsigned Index = Introduced; Index != Unknown; ++Index) { 1071 if (Changes[Index].KeywordLoc.isValid()) { 1072 if (!Complained) { 1073 Diag(UnavailableLoc, diag::warn_availability_and_unavailable) 1074 << SourceRange(Changes[Index].KeywordLoc, 1075 Changes[Index].VersionRange.getEnd()); 1076 Complained = true; 1077 } 1078 1079 // Clear out the availability. 1080 Changes[Index] = AvailabilityChange(); 1081 } 1082 } 1083 } 1084 1085 // Record this attribute 1086 attrs.addNew(&Availability, 1087 SourceRange(AvailabilityLoc, T.getCloseLocation()), 1088 ScopeName, ScopeLoc, 1089 Platform, 1090 Changes[Introduced], 1091 Changes[Deprecated], 1092 Changes[Obsoleted], 1093 UnavailableLoc, MessageExpr.get(), 1094 Syntax, StrictLoc, ReplacementExpr.get()); 1095} 1096 1097/// \brief Parse the contents of the "external_source_symbol" attribute. 1098/// 1099/// external-source-symbol-attribute: 1100/// 'external_source_symbol' '(' keyword-arg-list ')' 1101/// 1102/// keyword-arg-list: 1103/// keyword-arg 1104/// keyword-arg ',' keyword-arg-list 1105/// 1106/// keyword-arg: 1107/// 'language' '=' <string> 1108/// 'defined_in' '=' <string> 1109/// 'generated_declaration' 1110void Parser::ParseExternalSourceSymbolAttribute( 1111 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc, 1112 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, 1113 SourceLocation ScopeLoc, AttributeList::Syntax Syntax) { 1114 // Opening '('. 1115 BalancedDelimiterTracker T(*this, tok::l_paren); 1116 if (T.expectAndConsume()) 1117 return; 1118 1119 // Initialize the pointers for the keyword identifiers when required. 1120 if (!Ident_language) { 1121 Ident_language = PP.getIdentifierInfo("language"); 1122 Ident_defined_in = PP.getIdentifierInfo("defined_in"); 1123 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration"); 1124 } 1125 1126 ExprResult Language; 1127 bool HasLanguage = false; 1128 ExprResult DefinedInExpr; 1129 bool HasDefinedIn = false; 1130 IdentifierLoc *GeneratedDeclaration = nullptr; 1131 1132 // Parse the language/defined_in/generated_declaration keywords 1133 do { 1134 if (Tok.isNot(tok::identifier)) { 1135 Diag(Tok, diag::err_external_source_symbol_expected_keyword); 1136 SkipUntil(tok::r_paren, StopAtSemi); 1137 return; 1138 } 1139 1140 SourceLocation KeywordLoc = Tok.getLocation(); 1141 IdentifierInfo *Keyword = Tok.getIdentifierInfo(); 1142 if (Keyword == Ident_generated_declaration) { 1143 if (GeneratedDeclaration) { 1144 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword; 1145 SkipUntil(tok::r_paren, StopAtSemi); 1146 return; 1147 } 1148 GeneratedDeclaration = ParseIdentifierLoc(); 1149 continue; 1150 } 1151 1152 if (Keyword != Ident_language && Keyword != Ident_defined_in) { 1153 Diag(Tok, diag::err_external_source_symbol_expected_keyword); 1154 SkipUntil(tok::r_paren, StopAtSemi); 1155 return; 1156 } 1157 1158 ConsumeToken(); 1159 if (ExpectAndConsume(tok::equal, diag::err_expected_after, 1160 Keyword->getName())) { 1161 SkipUntil(tok::r_paren, StopAtSemi); 1162 return; 1163 } 1164 1165 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn; 1166 if (Keyword == Ident_language) 1167 HasLanguage = true; 1168 else 1169 HasDefinedIn = true; 1170 1171 if (Tok.isNot(tok::string_literal)) { 1172 Diag(Tok, diag::err_expected_string_literal) 1173 << /*Source='external_source_symbol attribute'*/ 3 1174 << /*language | source container*/ (Keyword != Ident_language); 1175 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch); 1176 continue; 1177 } 1178 if (Keyword == Ident_language) { 1179 if (HadLanguage) { 1180 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause) 1181 << Keyword; 1182 ParseStringLiteralExpression(); 1183 continue; 1184 } 1185 Language = ParseStringLiteralExpression(); 1186 } else { 1187 assert(Keyword == Ident_defined_in && "Invalid clause keyword!"); 1188 if (HadDefinedIn) { 1189 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause) 1190 << Keyword; 1191 ParseStringLiteralExpression(); 1192 continue; 1193 } 1194 DefinedInExpr = ParseStringLiteralExpression(); 1195 } 1196 } while (TryConsumeToken(tok::comma)); 1197 1198 // Closing ')'. 1199 if (T.consumeClose()) 1200 return; 1201 if (EndLoc) 1202 *EndLoc = T.getCloseLocation(); 1203 1204 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(), 1205 GeneratedDeclaration}; 1206 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()), 1207 ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax); 1208} 1209 1210/// \brief Parse the contents of the "objc_bridge_related" attribute. 1211/// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')' 1212/// related_class: 1213/// Identifier 1214/// 1215/// opt-class_method: 1216/// Identifier: | <empty> 1217/// 1218/// opt-instance_method: 1219/// Identifier | <empty> 1220/// 1221void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, 1222 SourceLocation ObjCBridgeRelatedLoc, 1223 ParsedAttributes &attrs, 1224 SourceLocation *endLoc, 1225 IdentifierInfo *ScopeName, 1226 SourceLocation ScopeLoc, 1227 AttributeList::Syntax Syntax) { 1228 // Opening '('. 1229 BalancedDelimiterTracker T(*this, tok::l_paren); 1230 if (T.consumeOpen()) { 1231 Diag(Tok, diag::err_expected) << tok::l_paren; 1232 return; 1233 } 1234 1235 // Parse the related class name. 1236 if (Tok.isNot(tok::identifier)) { 1237 Diag(Tok, diag::err_objcbridge_related_expected_related_class); 1238 SkipUntil(tok::r_paren, StopAtSemi); 1239 return; 1240 } 1241 IdentifierLoc *RelatedClass = ParseIdentifierLoc(); 1242 if (ExpectAndConsume(tok::comma)) { 1243 SkipUntil(tok::r_paren, StopAtSemi); 1244 return; 1245 } 1246 1247 // Parse optional class method name. 1248 IdentifierLoc *ClassMethod = nullptr; 1249 if (Tok.is(tok::identifier)) { 1250 ClassMethod = ParseIdentifierLoc(); 1251 if (!TryConsumeToken(tok::colon)) { 1252 Diag(Tok, diag::err_objcbridge_related_selector_name); 1253 SkipUntil(tok::r_paren, StopAtSemi); 1254 return; 1255 } 1256 } 1257 if (!TryConsumeToken(tok::comma)) { 1258 if (Tok.is(tok::colon)) 1259 Diag(Tok, diag::err_objcbridge_related_selector_name); 1260 else 1261 Diag(Tok, diag::err_expected) << tok::comma; 1262 SkipUntil(tok::r_paren, StopAtSemi); 1263 return; 1264 } 1265 1266 // Parse optional instance method name. 1267 IdentifierLoc *InstanceMethod = nullptr; 1268 if (Tok.is(tok::identifier)) 1269 InstanceMethod = ParseIdentifierLoc(); 1270 else if (Tok.isNot(tok::r_paren)) { 1271 Diag(Tok, diag::err_expected) << tok::r_paren; 1272 SkipUntil(tok::r_paren, StopAtSemi); 1273 return; 1274 } 1275 1276 // Closing ')'. 1277 if (T.consumeClose()) 1278 return; 1279 1280 if (endLoc) 1281 *endLoc = T.getCloseLocation(); 1282 1283 // Record this attribute 1284 attrs.addNew(&ObjCBridgeRelated, 1285 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()), 1286 ScopeName, ScopeLoc, 1287 RelatedClass, 1288 ClassMethod, 1289 InstanceMethod, 1290 Syntax); 1291} 1292 1293// Late Parsed Attributes: 1294// See other examples of late parsing in lib/Parse/ParseCXXInlineMethods 1295 1296void Parser::LateParsedDeclaration::ParseLexedAttributes() {} 1297 1298void Parser::LateParsedClass::ParseLexedAttributes() { 1299 Self->ParseLexedAttributes(*Class); 1300} 1301 1302void Parser::LateParsedAttribute::ParseLexedAttributes() { 1303 Self->ParseLexedAttribute(*this, true, false); 1304} 1305 1306/// Wrapper class which calls ParseLexedAttribute, after setting up the 1307/// scope appropriately. 1308void Parser::ParseLexedAttributes(ParsingClass &Class) { 1309 // Deal with templates 1310 // FIXME: Test cases to make sure this does the right thing for templates. 1311 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope; 1312 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, 1313 HasTemplateScope); 1314 if (HasTemplateScope) 1315 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate); 1316 1317 // Set or update the scope flags. 1318 bool AlreadyHasClassScope = Class.TopLevelClass; 1319 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope; 1320 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope); 1321 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope); 1322 1323 // Enter the scope of nested classes 1324 if (!AlreadyHasClassScope) 1325 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), 1326 Class.TagOrTemplate); 1327 if (!Class.LateParsedDeclarations.empty()) { 1328 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){ 1329 Class.LateParsedDeclarations[i]->ParseLexedAttributes(); 1330 } 1331 } 1332 1333 if (!AlreadyHasClassScope) 1334 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), 1335 Class.TagOrTemplate); 1336} 1337 1338/// \brief Parse all attributes in LAs, and attach them to Decl D. 1339void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, 1340 bool EnterScope, bool OnDefinition) { 1341 assert(LAs.parseSoon() && 1342 "Attribute list should be marked for immediate parsing."); 1343 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) { 1344 if (D) 1345 LAs[i]->addDecl(D); 1346 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition); 1347 delete LAs[i]; 1348 } 1349 LAs.clear(); 1350} 1351 1352/// \brief Finish parsing an attribute for which parsing was delayed. 1353/// This will be called at the end of parsing a class declaration 1354/// for each LateParsedAttribute. We consume the saved tokens and 1355/// create an attribute with the arguments filled in. We add this 1356/// to the Attribute list for the decl. 1357void Parser::ParseLexedAttribute(LateParsedAttribute &LA, 1358 bool EnterScope, bool OnDefinition) { 1359 // Create a fake EOF so that attribute parsing won't go off the end of the 1360 // attribute. 1361 Token AttrEnd; 1362 AttrEnd.startToken(); 1363 AttrEnd.setKind(tok::eof); 1364 AttrEnd.setLocation(Tok.getLocation()); 1365 AttrEnd.setEofData(LA.Toks.data()); 1366 LA.Toks.push_back(AttrEnd); 1367 1368 // Append the current token at the end of the new token stream so that it 1369 // doesn't get lost. 1370 LA.Toks.push_back(Tok); 1371 PP.EnterTokenStream(LA.Toks, true); 1372 // Consume the previously pushed token. 1373 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 1374 1375 ParsedAttributes Attrs(AttrFactory); 1376 SourceLocation endLoc; 1377 1378 if (LA.Decls.size() > 0) { 1379 Decl *D = LA.Decls[0]; 1380 NamedDecl *ND = dyn_cast<NamedDecl>(D); 1381 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext()); 1382 1383 // Allow 'this' within late-parsed attributes. 1384 Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0, 1385 ND && ND->isCXXInstanceMember()); 1386 1387 if (LA.Decls.size() == 1) { 1388 // If the Decl is templatized, add template parameters to scope. 1389 bool HasTemplateScope = EnterScope && D->isTemplateDecl(); 1390 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope); 1391 if (HasTemplateScope) 1392 Actions.ActOnReenterTemplateScope(Actions.CurScope, D); 1393 1394 // If the Decl is on a function, add function parameters to the scope. 1395 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate(); 1396 ParseScope FnScope( 1397 this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope, 1398 HasFunScope); 1399 if (HasFunScope) 1400 Actions.ActOnReenterFunctionContext(Actions.CurScope, D); 1401 1402 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc, 1403 nullptr, SourceLocation(), AttributeList::AS_GNU, 1404 nullptr); 1405 1406 if (HasFunScope) { 1407 Actions.ActOnExitFunctionContext(); 1408 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver 1409 } 1410 if (HasTemplateScope) { 1411 TempScope.Exit(); 1412 } 1413 } else { 1414 // If there are multiple decls, then the decl cannot be within the 1415 // function scope. 1416 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc, 1417 nullptr, SourceLocation(), AttributeList::AS_GNU, 1418 nullptr); 1419 } 1420 } else { 1421 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName(); 1422 } 1423 1424 const AttributeList *AL = Attrs.getList(); 1425 if (OnDefinition && AL && !AL->isCXX11Attribute() && 1426 AL->isKnownToGCC()) 1427 Diag(Tok, diag::warn_attribute_on_function_definition) 1428 << &LA.AttrName; 1429 1430 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i) 1431 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs); 1432 1433 // Due to a parsing error, we either went over the cached tokens or 1434 // there are still cached tokens left, so we skip the leftover tokens. 1435 while (Tok.isNot(tok::eof)) 1436 ConsumeAnyToken(); 1437 1438 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData()) 1439 ConsumeAnyToken(); 1440} 1441 1442void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, 1443 SourceLocation AttrNameLoc, 1444 ParsedAttributes &Attrs, 1445 SourceLocation *EndLoc, 1446 IdentifierInfo *ScopeName, 1447 SourceLocation ScopeLoc, 1448 AttributeList::Syntax Syntax) { 1449 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); 1450 1451 BalancedDelimiterTracker T(*this, tok::l_paren); 1452 T.consumeOpen(); 1453 1454 if (Tok.isNot(tok::identifier)) { 1455 Diag(Tok, diag::err_expected) << tok::identifier; 1456 T.skipToEnd(); 1457 return; 1458 } 1459 IdentifierLoc *ArgumentKind = ParseIdentifierLoc(); 1460 1461 if (ExpectAndConsume(tok::comma)) { 1462 T.skipToEnd(); 1463 return; 1464 } 1465 1466 SourceRange MatchingCTypeRange; 1467 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange); 1468 if (MatchingCType.isInvalid()) { 1469 T.skipToEnd(); 1470 return; 1471 } 1472 1473 bool LayoutCompatible = false; 1474 bool MustBeNull = false; 1475 while (TryConsumeToken(tok::comma)) { 1476 if (Tok.isNot(tok::identifier)) { 1477 Diag(Tok, diag::err_expected) << tok::identifier; 1478 T.skipToEnd(); 1479 return; 1480 } 1481 IdentifierInfo *Flag = Tok.getIdentifierInfo(); 1482 if (Flag->isStr("layout_compatible")) 1483 LayoutCompatible = true; 1484 else if (Flag->isStr("must_be_null")) 1485 MustBeNull = true; 1486 else { 1487 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag; 1488 T.skipToEnd(); 1489 return; 1490 } 1491 ConsumeToken(); // consume flag 1492 } 1493 1494 if (!T.consumeClose()) { 1495 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc, 1496 ArgumentKind, MatchingCType.get(), 1497 LayoutCompatible, MustBeNull, Syntax); 1498 } 1499 1500 if (EndLoc) 1501 *EndLoc = T.getCloseLocation(); 1502} 1503 1504/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets 1505/// of a C++11 attribute-specifier in a location where an attribute is not 1506/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this 1507/// situation. 1508/// 1509/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if 1510/// this doesn't appear to actually be an attribute-specifier, and the caller 1511/// should try to parse it. 1512bool Parser::DiagnoseProhibitedCXX11Attribute() { 1513 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)); 1514 1515 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) { 1516 case CAK_NotAttributeSpecifier: 1517 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute. 1518 return false; 1519 1520 case CAK_InvalidAttributeSpecifier: 1521 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute); 1522 return false; 1523 1524 case CAK_AttributeSpecifier: 1525 // Parse and discard the attributes. 1526 SourceLocation BeginLoc = ConsumeBracket(); 1527 ConsumeBracket(); 1528 SkipUntil(tok::r_square); 1529 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied"); 1530 SourceLocation EndLoc = ConsumeBracket(); 1531 Diag(BeginLoc, diag::err_attributes_not_allowed) 1532 << SourceRange(BeginLoc, EndLoc); 1533 return true; 1534 } 1535 llvm_unreachable("All cases handled above."); 1536} 1537 1538/// \brief We have found the opening square brackets of a C++11 1539/// attribute-specifier in a location where an attribute is not permitted, but 1540/// we know where the attributes ought to be written. Parse them anyway, and 1541/// provide a fixit moving them to the right place. 1542void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, 1543 SourceLocation CorrectLocation) { 1544 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) || 1545 Tok.is(tok::kw_alignas)); 1546 1547 // Consume the attributes. 1548 SourceLocation Loc = Tok.getLocation(); 1549 ParseCXX11Attributes(Attrs); 1550 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true); 1551 // FIXME: use err_attributes_misplaced 1552 Diag(Loc, diag::err_attributes_not_allowed) 1553 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange) 1554 << FixItHint::CreateRemoval(AttrRange); 1555} 1556 1557void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs, 1558 const SourceLocation CorrectLocation) { 1559 if (CorrectLocation.isValid()) { 1560 CharSourceRange AttrRange(attrs.Range, true); 1561 Diag(CorrectLocation, diag::err_attributes_misplaced) 1562 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange) 1563 << FixItHint::CreateRemoval(AttrRange); 1564 } else 1565 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed) << attrs.Range; 1566} 1567 1568void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs, 1569 unsigned DiagID) { 1570 for (AttributeList *Attr = Attrs.getList(); Attr; Attr = Attr->getNext()) { 1571 if (!Attr->isCXX11Attribute() && !Attr->isC2xAttribute()) 1572 continue; 1573 if (Attr->getKind() == AttributeList::UnknownAttribute) 1574 Diag(Attr->getLoc(), diag::warn_unknown_attribute_ignored) 1575 << Attr->getName(); 1576 else { 1577 Diag(Attr->getLoc(), DiagID) 1578 << Attr->getName(); 1579 Attr->setInvalid(); 1580 } 1581 } 1582} 1583 1584// Usually, `__attribute__((attrib)) class Foo {} var` means that attribute 1585// applies to var, not the type Foo. 1586// As an exception to the rule, __declspec(align(...)) before the 1587// class-key affects the type instead of the variable. 1588// Also, Microsoft-style [attributes] seem to affect the type instead of the 1589// variable. 1590// This function moves attributes that should apply to the type off DS to Attrs. 1591void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs, 1592 DeclSpec &DS, 1593 Sema::TagUseKind TUK) { 1594 if (TUK == Sema::TUK_Reference) 1595 return; 1596 1597 ParsedAttributes &PA = DS.getAttributes(); 1598 AttributeList *AL = PA.getList(); 1599 AttributeList *Prev = nullptr; 1600 AttributeList *TypeAttrHead = nullptr; 1601 AttributeList *TypeAttrTail = nullptr; 1602 while (AL) { 1603 AttributeList *Next = AL->getNext(); 1604 1605 if ((AL->getKind() == AttributeList::AT_Aligned && 1606 AL->isDeclspecAttribute()) || 1607 AL->isMicrosoftAttribute()) { 1608 // Stitch the attribute into the tag's attribute list. 1609 if (TypeAttrTail) 1610 TypeAttrTail->setNext(AL); 1611 else 1612 TypeAttrHead = AL; 1613 TypeAttrTail = AL; 1614 TypeAttrTail->setNext(nullptr); 1615 1616 // Remove the attribute from the variable's attribute list. 1617 if (Prev) { 1618 // Set the last variable attribute's next attribute to be the attribute 1619 // after the current one. 1620 Prev->setNext(Next); 1621 } else { 1622 // Removing the head of the list requires us to reset the head to the 1623 // next attribute. 1624 PA.set(Next); 1625 } 1626 } else { 1627 Prev = AL; 1628 } 1629 1630 AL = Next; 1631 } 1632 1633 // Find end of type attributes Attrs and add NewTypeAttributes in the same 1634 // order they were in originally. (Remember, in AttributeList things earlier 1635 // in source order are later in the list, since new attributes are added to 1636 // the front of the list.) 1637 Attrs.addAllAtEnd(TypeAttrHead); 1638} 1639 1640/// ParseDeclaration - Parse a full 'declaration', which consists of 1641/// declaration-specifiers, some number of declarators, and a semicolon. 1642/// 'Context' should be a DeclaratorContext value. This returns the 1643/// location of the semicolon in DeclEnd. 1644/// 1645/// declaration: [C99 6.7] 1646/// block-declaration -> 1647/// simple-declaration 1648/// others [FIXME] 1649/// [C++] template-declaration 1650/// [C++] namespace-definition 1651/// [C++] using-directive 1652/// [C++] using-declaration 1653/// [C++11/C11] static_assert-declaration 1654/// others... [FIXME] 1655/// 1656Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context, 1657 SourceLocation &DeclEnd, 1658 ParsedAttributesWithRange &attrs) { 1659 ParenBraceBracketBalancer BalancerRAIIObj(*this); 1660 // Must temporarily exit the objective-c container scope for 1661 // parsing c none objective-c decls. 1662 ObjCDeclContextSwitch ObjCDC(*this); 1663 1664 Decl *SingleDecl = nullptr; 1665 switch (Tok.getKind()) { 1666 case tok::kw_template: 1667 case tok::kw_export: 1668 ProhibitAttributes(attrs); 1669 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd); 1670 break; 1671 case tok::kw_inline: 1672 // Could be the start of an inline namespace. Allowed as an ext in C++03. 1673 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) { 1674 ProhibitAttributes(attrs); 1675 SourceLocation InlineLoc = ConsumeToken(); 1676 return ParseNamespace(Context, DeclEnd, InlineLoc); 1677 } 1678 return ParseSimpleDeclaration(Context, DeclEnd, attrs, 1679 true); 1680 case tok::kw_namespace: 1681 ProhibitAttributes(attrs); 1682 return ParseNamespace(Context, DeclEnd); 1683 case tok::kw_using: 1684 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(), 1685 DeclEnd, attrs); 1686 case tok::kw_static_assert: 1687 case tok::kw__Static_assert: 1688 ProhibitAttributes(attrs); 1689 SingleDecl = ParseStaticAssertDeclaration(DeclEnd); 1690 break; 1691 default: 1692 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true); 1693 } 1694 1695 // This routine returns a DeclGroup, if the thing we parsed only contains a 1696 // single decl, convert it now. 1697 return Actions.ConvertDeclToDeclGroup(SingleDecl); 1698} 1699 1700/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl] 1701/// declaration-specifiers init-declarator-list[opt] ';' 1702/// [C++11] attribute-specifier-seq decl-specifier-seq[opt] 1703/// init-declarator-list ';' 1704///[C90/C++]init-declarator-list ';' [TODO] 1705/// [OMP] threadprivate-directive [TODO] 1706/// 1707/// for-range-declaration: [C++11 6.5p1: stmt.ranged] 1708/// attribute-specifier-seq[opt] type-specifier-seq declarator 1709/// 1710/// If RequireSemi is false, this does not check for a ';' at the end of the 1711/// declaration. If it is true, it checks for and eats it. 1712/// 1713/// If FRI is non-null, we might be parsing a for-range-declaration instead 1714/// of a simple-declaration. If we find that we are, we also parse the 1715/// for-range-initializer, and place it here. 1716Parser::DeclGroupPtrTy 1717Parser::ParseSimpleDeclaration(DeclaratorContext Context, 1718 SourceLocation &DeclEnd, 1719 ParsedAttributesWithRange &Attrs, 1720 bool RequireSemi, ForRangeInit *FRI) { 1721 // Parse the common declaration-specifiers piece. 1722 ParsingDeclSpec DS(*this); 1723 1724 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context); 1725 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext); 1726 1727 // If we had a free-standing type definition with a missing semicolon, we 1728 // may get this far before the problem becomes obvious. 1729 if (DS.hasTagDefinition() && 1730 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext)) 1731 return nullptr; 1732 1733 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" 1734 // declaration-specifiers init-declarator-list[opt] ';' 1735 if (Tok.is(tok::semi)) { 1736 ProhibitAttributes(Attrs); 1737 DeclEnd = Tok.getLocation(); 1738 if (RequireSemi) ConsumeToken(); 1739 RecordDecl *AnonRecord = nullptr; 1740 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, 1741 DS, AnonRecord); 1742 DS.complete(TheDecl); 1743 if (AnonRecord) { 1744 Decl* decls[] = {AnonRecord, TheDecl}; 1745 return Actions.BuildDeclaratorGroup(decls); 1746 } 1747 return Actions.ConvertDeclToDeclGroup(TheDecl); 1748 } 1749 1750 DS.takeAttributesFrom(Attrs); 1751 return ParseDeclGroup(DS, Context, &DeclEnd, FRI); 1752} 1753 1754/// Returns true if this might be the start of a declarator, or a common typo 1755/// for a declarator. 1756bool Parser::MightBeDeclarator(DeclaratorContext Context) { 1757 switch (Tok.getKind()) { 1758 case tok::annot_cxxscope: 1759 case tok::annot_template_id: 1760 case tok::caret: 1761 case tok::code_completion: 1762 case tok::coloncolon: 1763 case tok::ellipsis: 1764 case tok::kw___attribute: 1765 case tok::kw_operator: 1766 case tok::l_paren: 1767 case tok::star: 1768 return true; 1769 1770 case tok::amp: 1771 case tok::ampamp: 1772 return getLangOpts().CPlusPlus; 1773 1774 case tok::l_square: // Might be an attribute on an unnamed bit-field. 1775 return Context == DeclaratorContext::MemberContext && 1776 getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square); 1777 1778 case tok::colon: // Might be a typo for '::' or an unnamed bit-field. 1779 return Context == DeclaratorContext::MemberContext || 1780 getLangOpts().CPlusPlus; 1781 1782 case tok::identifier: 1783 switch (NextToken().getKind()) { 1784 case tok::code_completion: 1785 case tok::coloncolon: 1786 case tok::comma: 1787 case tok::equal: 1788 case tok::equalequal: // Might be a typo for '='. 1789 case tok::kw_alignas: 1790 case tok::kw_asm: 1791 case tok::kw___attribute: 1792 case tok::l_brace: 1793 case tok::l_paren: 1794 case tok::l_square: 1795 case tok::less: 1796 case tok::r_brace: 1797 case tok::r_paren: 1798 case tok::r_square: 1799 case tok::semi: 1800 return true; 1801 1802 case tok::colon: 1803 // At namespace scope, 'identifier:' is probably a typo for 'identifier::' 1804 // and in block scope it's probably a label. Inside a class definition, 1805 // this is a bit-field. 1806 return Context == DeclaratorContext::MemberContext || 1807 (getLangOpts().CPlusPlus && 1808 Context == DeclaratorContext::FileContext); 1809 1810 case tok::identifier: // Possible virt-specifier. 1811 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken()); 1812 1813 default: 1814 return false; 1815 } 1816 1817 default: 1818 return false; 1819 } 1820} 1821 1822/// Skip until we reach something which seems like a sensible place to pick 1823/// up parsing after a malformed declaration. This will sometimes stop sooner 1824/// than SkipUntil(tok::r_brace) would, but will never stop later. 1825void Parser::SkipMalformedDecl() { 1826 while (true) { 1827 switch (Tok.getKind()) { 1828 case tok::l_brace: 1829 // Skip until matching }, then stop. We've probably skipped over 1830 // a malformed class or function definition or similar. 1831 ConsumeBrace(); 1832 SkipUntil(tok::r_brace); 1833 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) { 1834 // This declaration isn't over yet. Keep skipping. 1835 continue; 1836 } 1837 TryConsumeToken(tok::semi); 1838 return; 1839 1840 case tok::l_square: 1841 ConsumeBracket(); 1842 SkipUntil(tok::r_square); 1843 continue; 1844 1845 case tok::l_paren: 1846 ConsumeParen(); 1847 SkipUntil(tok::r_paren); 1848 continue; 1849 1850 case tok::r_brace: 1851 return; 1852 1853 case tok::semi: 1854 ConsumeToken(); 1855 return; 1856 1857 case tok::kw_inline: 1858 // 'inline namespace' at the start of a line is almost certainly 1859 // a good place to pick back up parsing, except in an Objective-C 1860 // @interface context. 1861 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) && 1862 (!ParsingInObjCContainer || CurParsedObjCImpl)) 1863 return; 1864 break; 1865 1866 case tok::kw_namespace: 1867 // 'namespace' at the start of a line is almost certainly a good 1868 // place to pick back up parsing, except in an Objective-C 1869 // @interface context. 1870 if (Tok.isAtStartOfLine() && 1871 (!ParsingInObjCContainer || CurParsedObjCImpl)) 1872 return; 1873 break; 1874 1875 case tok::at: 1876 // @end is very much like } in Objective-C contexts. 1877 if (NextToken().isObjCAtKeyword(tok::objc_end) && 1878 ParsingInObjCContainer) 1879 return; 1880 break; 1881 1882 case tok::minus: 1883 case tok::plus: 1884 // - and + probably start new method declarations in Objective-C contexts. 1885 if (Tok.isAtStartOfLine() && ParsingInObjCContainer) 1886 return; 1887 break; 1888 1889 case tok::eof: 1890 case tok::annot_module_begin: 1891 case tok::annot_module_end: 1892 case tok::annot_module_include: 1893 return; 1894 1895 default: 1896 break; 1897 } 1898 1899 ConsumeAnyToken(); 1900 } 1901} 1902 1903/// ParseDeclGroup - Having concluded that this is either a function 1904/// definition or a group of object declarations, actually parse the 1905/// result. 1906Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS, 1907 DeclaratorContext Context, 1908 SourceLocation *DeclEnd, 1909 ForRangeInit *FRI) { 1910 // Parse the first declarator. 1911 ParsingDeclarator D(*this, DS, Context); 1912 ParseDeclarator(D); 1913 1914 // Bail out if the first declarator didn't seem well-formed. 1915 if (!D.hasName() && !D.mayOmitIdentifier()) { 1916 SkipMalformedDecl(); 1917 return nullptr; 1918 } 1919 1920 // Save late-parsed attributes for now; they need to be parsed in the 1921 // appropriate function scope after the function Decl has been constructed. 1922 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList. 1923 LateParsedAttrList LateParsedAttrs(true); 1924 if (D.isFunctionDeclarator()) { 1925 MaybeParseGNUAttributes(D, &LateParsedAttrs); 1926 1927 // The _Noreturn keyword can't appear here, unlike the GNU noreturn 1928 // attribute. If we find the keyword here, tell the user to put it 1929 // at the start instead. 1930 if (Tok.is(tok::kw__Noreturn)) { 1931 SourceLocation Loc = ConsumeToken(); 1932 const char *PrevSpec; 1933 unsigned DiagID; 1934 1935 // We can offer a fixit if it's valid to mark this function as _Noreturn 1936 // and we don't have any other declarators in this declaration. 1937 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID); 1938 MaybeParseGNUAttributes(D, &LateParsedAttrs); 1939 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try); 1940 1941 Diag(Loc, diag::err_c11_noreturn_misplaced) 1942 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint()) 1943 << (Fixit ? FixItHint::CreateInsertion(D.getLocStart(), "_Noreturn ") 1944 : FixItHint()); 1945 } 1946 } 1947 1948 // Check to see if we have a function *definition* which must have a body. 1949 if (D.isFunctionDeclarator() && 1950 // Look at the next token to make sure that this isn't a function 1951 // declaration. We have to check this because __attribute__ might be the 1952 // start of a function definition in GCC-extended K&R C. 1953 !isDeclarationAfterDeclarator()) { 1954 1955 // Function definitions are only allowed at file scope and in C++ classes. 1956 // The C++ inline method definition case is handled elsewhere, so we only 1957 // need to handle the file scope definition case. 1958 if (Context == DeclaratorContext::FileContext) { 1959 if (isStartOfFunctionDefinition(D)) { 1960 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 1961 Diag(Tok, diag::err_function_declared_typedef); 1962 1963 // Recover by treating the 'typedef' as spurious. 1964 DS.ClearStorageClassSpecs(); 1965 } 1966 1967 Decl *TheDecl = 1968 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs); 1969 return Actions.ConvertDeclToDeclGroup(TheDecl); 1970 } 1971 1972 if (isDeclarationSpecifier()) { 1973 // If there is an invalid declaration specifier right after the 1974 // function prototype, then we must be in a missing semicolon case 1975 // where this isn't actually a body. Just fall through into the code 1976 // that handles it as a prototype, and let the top-level code handle 1977 // the erroneous declspec where it would otherwise expect a comma or 1978 // semicolon. 1979 } else { 1980 Diag(Tok, diag::err_expected_fn_body); 1981 SkipUntil(tok::semi); 1982 return nullptr; 1983 } 1984 } else { 1985 if (Tok.is(tok::l_brace)) { 1986 Diag(Tok, diag::err_function_definition_not_allowed); 1987 SkipMalformedDecl(); 1988 return nullptr; 1989 } 1990 } 1991 } 1992 1993 if (ParseAsmAttributesAfterDeclarator(D)) 1994 return nullptr; 1995 1996 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we 1997 // must parse and analyze the for-range-initializer before the declaration is 1998 // analyzed. 1999 // 2000 // Handle the Objective-C for-in loop variable similarly, although we 2001 // don't need to parse the container in advance. 2002 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) { 2003 bool IsForRangeLoop = false; 2004 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) { 2005 IsForRangeLoop = true; 2006 if (Tok.is(tok::l_brace)) 2007 FRI->RangeExpr = ParseBraceInitializer(); 2008 else 2009 FRI->RangeExpr = ParseExpression(); 2010 } 2011 2012 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 2013 if (IsForRangeLoop) 2014 Actions.ActOnCXXForRangeDecl(ThisDecl); 2015 Actions.FinalizeDeclaration(ThisDecl); 2016 D.complete(ThisDecl); 2017 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl); 2018 } 2019 2020 SmallVector<Decl *, 8> DeclsInGroup; 2021 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes( 2022 D, ParsedTemplateInfo(), FRI); 2023 if (LateParsedAttrs.size() > 0) 2024 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false); 2025 D.complete(FirstDecl); 2026 if (FirstDecl) 2027 DeclsInGroup.push_back(FirstDecl); 2028 2029 bool ExpectSemi = Context != DeclaratorContext::ForContext; 2030 2031 // If we don't have a comma, it is either the end of the list (a ';') or an 2032 // error, bail out. 2033 SourceLocation CommaLoc; 2034 while (TryConsumeToken(tok::comma, CommaLoc)) { 2035 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) { 2036 // This comma was followed by a line-break and something which can't be 2037 // the start of a declarator. The comma was probably a typo for a 2038 // semicolon. 2039 Diag(CommaLoc, diag::err_expected_semi_declaration) 2040 << FixItHint::CreateReplacement(CommaLoc, ";"); 2041 ExpectSemi = false; 2042 break; 2043 } 2044 2045 // Parse the next declarator. 2046 D.clear(); 2047 D.setCommaLoc(CommaLoc); 2048 2049 // Accept attributes in an init-declarator. In the first declarator in a 2050 // declaration, these would be part of the declspec. In subsequent 2051 // declarators, they become part of the declarator itself, so that they 2052 // don't apply to declarators after *this* one. Examples: 2053 // short __attribute__((common)) var; -> declspec 2054 // short var __attribute__((common)); -> declarator 2055 // short x, __attribute__((common)) var; -> declarator 2056 MaybeParseGNUAttributes(D); 2057 2058 // MSVC parses but ignores qualifiers after the comma as an extension. 2059 if (getLangOpts().MicrosoftExt) 2060 DiagnoseAndSkipExtendedMicrosoftTypeAttributes(); 2061 2062 ParseDeclarator(D); 2063 if (!D.isInvalidType()) { 2064 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D); 2065 D.complete(ThisDecl); 2066 if (ThisDecl) 2067 DeclsInGroup.push_back(ThisDecl); 2068 } 2069 } 2070 2071 if (DeclEnd) 2072 *DeclEnd = Tok.getLocation(); 2073 2074 if (ExpectSemi && 2075 ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext 2076 ? diag::err_invalid_token_after_toplevel_declarator 2077 : diag::err_expected_semi_declaration)) { 2078 // Okay, there was no semicolon and one was expected. If we see a 2079 // declaration specifier, just assume it was missing and continue parsing. 2080 // Otherwise things are very confused and we skip to recover. 2081 if (!isDeclarationSpecifier()) { 2082 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 2083 TryConsumeToken(tok::semi); 2084 } 2085 } 2086 2087 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup); 2088} 2089 2090/// Parse an optional simple-asm-expr and attributes, and attach them to a 2091/// declarator. Returns true on an error. 2092bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) { 2093 // If a simple-asm-expr is present, parse it. 2094 if (Tok.is(tok::kw_asm)) { 2095 SourceLocation Loc; 2096 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 2097 if (AsmLabel.isInvalid()) { 2098 SkipUntil(tok::semi, StopBeforeMatch); 2099 return true; 2100 } 2101 2102 D.setAsmLabel(AsmLabel.get()); 2103 D.SetRangeEnd(Loc); 2104 } 2105 2106 MaybeParseGNUAttributes(D); 2107 return false; 2108} 2109 2110/// \brief Parse 'declaration' after parsing 'declaration-specifiers 2111/// declarator'. This method parses the remainder of the declaration 2112/// (including any attributes or initializer, among other things) and 2113/// finalizes the declaration. 2114/// 2115/// init-declarator: [C99 6.7] 2116/// declarator 2117/// declarator '=' initializer 2118/// [GNU] declarator simple-asm-expr[opt] attributes[opt] 2119/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer 2120/// [C++] declarator initializer[opt] 2121/// 2122/// [C++] initializer: 2123/// [C++] '=' initializer-clause 2124/// [C++] '(' expression-list ')' 2125/// [C++0x] '=' 'default' [TODO] 2126/// [C++0x] '=' 'delete' 2127/// [C++0x] braced-init-list 2128/// 2129/// According to the standard grammar, =default and =delete are function 2130/// definitions, but that definitely doesn't fit with the parser here. 2131/// 2132Decl *Parser::ParseDeclarationAfterDeclarator( 2133 Declarator &D, const ParsedTemplateInfo &TemplateInfo) { 2134 if (ParseAsmAttributesAfterDeclarator(D)) 2135 return nullptr; 2136 2137 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo); 2138} 2139 2140Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes( 2141 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) { 2142 // RAII type used to track whether we're inside an initializer. 2143 struct InitializerScopeRAII { 2144 Parser &P; 2145 Declarator &D; 2146 Decl *ThisDecl; 2147 2148 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl) 2149 : P(P), D(D), ThisDecl(ThisDecl) { 2150 if (ThisDecl && P.getLangOpts().CPlusPlus) { 2151 Scope *S = nullptr; 2152 if (D.getCXXScopeSpec().isSet()) { 2153 P.EnterScope(0); 2154 S = P.getCurScope(); 2155 } 2156 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl); 2157 } 2158 } 2159 ~InitializerScopeRAII() { pop(); } 2160 void pop() { 2161 if (ThisDecl && P.getLangOpts().CPlusPlus) { 2162 Scope *S = nullptr; 2163 if (D.getCXXScopeSpec().isSet()) 2164 S = P.getCurScope(); 2165 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl); 2166 if (S) 2167 P.ExitScope(); 2168 } 2169 ThisDecl = nullptr; 2170 } 2171 }; 2172 2173 // Inform the current actions module that we just parsed this declarator. 2174 Decl *ThisDecl = nullptr; 2175 switch (TemplateInfo.Kind) { 2176 case ParsedTemplateInfo::NonTemplate: 2177 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 2178 break; 2179 2180 case ParsedTemplateInfo::Template: 2181 case ParsedTemplateInfo::ExplicitSpecialization: { 2182 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(), 2183 *TemplateInfo.TemplateParams, 2184 D); 2185 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl)) 2186 // Re-direct this decl to refer to the templated decl so that we can 2187 // initialize it. 2188 ThisDecl = VT->getTemplatedDecl(); 2189 break; 2190 } 2191 case ParsedTemplateInfo::ExplicitInstantiation: { 2192 if (Tok.is(tok::semi)) { 2193 DeclResult ThisRes = Actions.ActOnExplicitInstantiation( 2194 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D); 2195 if (ThisRes.isInvalid()) { 2196 SkipUntil(tok::semi, StopBeforeMatch); 2197 return nullptr; 2198 } 2199 ThisDecl = ThisRes.get(); 2200 } else { 2201 // FIXME: This check should be for a variable template instantiation only. 2202 2203 // Check that this is a valid instantiation 2204 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 2205 // If the declarator-id is not a template-id, issue a diagnostic and 2206 // recover by ignoring the 'template' keyword. 2207 Diag(Tok, diag::err_template_defn_explicit_instantiation) 2208 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc); 2209 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 2210 } else { 2211 SourceLocation LAngleLoc = 2212 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); 2213 Diag(D.getIdentifierLoc(), 2214 diag::err_explicit_instantiation_with_definition) 2215 << SourceRange(TemplateInfo.TemplateLoc) 2216 << FixItHint::CreateInsertion(LAngleLoc, "<>"); 2217 2218 // Recover as if it were an explicit specialization. 2219 TemplateParameterLists FakedParamLists; 2220 FakedParamLists.push_back(Actions.ActOnTemplateParameterList( 2221 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None, 2222 LAngleLoc, nullptr)); 2223 2224 ThisDecl = 2225 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D); 2226 } 2227 } 2228 break; 2229 } 2230 } 2231 2232 // Parse declarator '=' initializer. 2233 // If a '==' or '+=' is found, suggest a fixit to '='. 2234 if (isTokenEqualOrEqualTypo()) { 2235 SourceLocation EqualLoc = ConsumeToken(); 2236 2237 if (Tok.is(tok::kw_delete)) { 2238 if (D.isFunctionDeclarator()) 2239 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) 2240 << 1 /* delete */; 2241 else 2242 Diag(ConsumeToken(), diag::err_deleted_non_function); 2243 } else if (Tok.is(tok::kw_default)) { 2244 if (D.isFunctionDeclarator()) 2245 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) 2246 << 0 /* default */; 2247 else 2248 Diag(ConsumeToken(), diag::err_default_special_members); 2249 } else { 2250 InitializerScopeRAII InitScope(*this, D, ThisDecl); 2251 2252 if (Tok.is(tok::code_completion)) { 2253 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl); 2254 Actions.FinalizeDeclaration(ThisDecl); 2255 cutOffParsing(); 2256 return nullptr; 2257 } 2258 2259 ExprResult Init(ParseInitializer()); 2260 2261 // If this is the only decl in (possibly) range based for statement, 2262 // our best guess is that the user meant ':' instead of '='. 2263 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) { 2264 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range) 2265 << FixItHint::CreateReplacement(EqualLoc, ":"); 2266 // We are trying to stop parser from looking for ';' in this for 2267 // statement, therefore preventing spurious errors to be issued. 2268 FRI->ColonLoc = EqualLoc; 2269 Init = ExprError(); 2270 FRI->RangeExpr = Init; 2271 } 2272 2273 InitScope.pop(); 2274 2275 if (Init.isInvalid()) { 2276 SmallVector<tok::TokenKind, 2> StopTokens; 2277 StopTokens.push_back(tok::comma); 2278 if (D.getContext() == DeclaratorContext::ForContext || 2279 D.getContext() == DeclaratorContext::InitStmtContext) 2280 StopTokens.push_back(tok::r_paren); 2281 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch); 2282 Actions.ActOnInitializerError(ThisDecl); 2283 } else 2284 Actions.AddInitializerToDecl(ThisDecl, Init.get(), 2285 /*DirectInit=*/false); 2286 } 2287 } else if (Tok.is(tok::l_paren)) { 2288 // Parse C++ direct initializer: '(' expression-list ')' 2289 BalancedDelimiterTracker T(*this, tok::l_paren); 2290 T.consumeOpen(); 2291 2292 ExprVector Exprs; 2293 CommaLocsTy CommaLocs; 2294 2295 InitializerScopeRAII InitScope(*this, D, ThisDecl); 2296 2297 llvm::function_ref<void()> ExprListCompleter; 2298 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl); 2299 auto ConstructorCompleter = [&, ThisVarDecl] { 2300 Actions.CodeCompleteConstructor( 2301 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(), 2302 ThisDecl->getLocation(), Exprs); 2303 }; 2304 if (ThisVarDecl) { 2305 // ParseExpressionList can sometimes succeed even when ThisDecl is not 2306 // VarDecl. This is an error and it is reported in a call to 2307 // Actions.ActOnInitializerError(). However, we call 2308 // CodeCompleteConstructor only on VarDecls, falling back to default 2309 // completer in other cases. 2310 ExprListCompleter = ConstructorCompleter; 2311 } 2312 2313 if (ParseExpressionList(Exprs, CommaLocs, ExprListCompleter)) { 2314 Actions.ActOnInitializerError(ThisDecl); 2315 SkipUntil(tok::r_paren, StopAtSemi); 2316 } else { 2317 // Match the ')'. 2318 T.consumeClose(); 2319 2320 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() && 2321 "Unexpected number of commas!"); 2322 2323 InitScope.pop(); 2324 2325 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(), 2326 T.getCloseLocation(), 2327 Exprs); 2328 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(), 2329 /*DirectInit=*/true); 2330 } 2331 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) && 2332 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) { 2333 // Parse C++0x braced-init-list. 2334 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 2335 2336 InitializerScopeRAII InitScope(*this, D, ThisDecl); 2337 2338 ExprResult Init(ParseBraceInitializer()); 2339 2340 InitScope.pop(); 2341 2342 if (Init.isInvalid()) { 2343 Actions.ActOnInitializerError(ThisDecl); 2344 } else 2345 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true); 2346 2347 } else { 2348 Actions.ActOnUninitializedDecl(ThisDecl); 2349 } 2350 2351 Actions.FinalizeDeclaration(ThisDecl); 2352 2353 return ThisDecl; 2354} 2355 2356/// ParseSpecifierQualifierList 2357/// specifier-qualifier-list: 2358/// type-specifier specifier-qualifier-list[opt] 2359/// type-qualifier specifier-qualifier-list[opt] 2360/// [GNU] attributes specifier-qualifier-list[opt] 2361/// 2362void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS, 2363 DeclSpecContext DSC) { 2364 /// specifier-qualifier-list is a subset of declaration-specifiers. Just 2365 /// parse declaration-specifiers and complain about extra stuff. 2366 /// TODO: diagnose attribute-specifiers and alignment-specifiers. 2367 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC); 2368 2369 // Validate declspec for type-name. 2370 unsigned Specs = DS.getParsedSpecifiers(); 2371 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) { 2372 Diag(Tok, diag::err_expected_type); 2373 DS.SetTypeSpecError(); 2374 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) { 2375 Diag(Tok, diag::err_typename_requires_specqual); 2376 if (!DS.hasTypeSpecifier()) 2377 DS.SetTypeSpecError(); 2378 } 2379 2380 // Issue diagnostic and remove storage class if present. 2381 if (Specs & DeclSpec::PQ_StorageClassSpecifier) { 2382 if (DS.getStorageClassSpecLoc().isValid()) 2383 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass); 2384 else 2385 Diag(DS.getThreadStorageClassSpecLoc(), 2386 diag::err_typename_invalid_storageclass); 2387 DS.ClearStorageClassSpecs(); 2388 } 2389 2390 // Issue diagnostic and remove function specifier if present. 2391 if (Specs & DeclSpec::PQ_FunctionSpecifier) { 2392 if (DS.isInlineSpecified()) 2393 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec); 2394 if (DS.isVirtualSpecified()) 2395 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec); 2396 if (DS.isExplicitSpecified()) 2397 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec); 2398 DS.ClearFunctionSpecs(); 2399 } 2400 2401 // Issue diagnostic and remove constexpr specfier if present. 2402 if (DS.isConstexprSpecified() && DSC != DeclSpecContext::DSC_condition) { 2403 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr); 2404 DS.ClearConstexprSpec(); 2405 } 2406} 2407 2408/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the 2409/// specified token is valid after the identifier in a declarator which 2410/// immediately follows the declspec. For example, these things are valid: 2411/// 2412/// int x [ 4]; // direct-declarator 2413/// int x ( int y); // direct-declarator 2414/// int(int x ) // direct-declarator 2415/// int x ; // simple-declaration 2416/// int x = 17; // init-declarator-list 2417/// int x , y; // init-declarator-list 2418/// int x __asm__ ("foo"); // init-declarator-list 2419/// int x : 4; // struct-declarator 2420/// int x { 5}; // C++'0x unified initializers 2421/// 2422/// This is not, because 'x' does not immediately follow the declspec (though 2423/// ')' happens to be valid anyway). 2424/// int (x) 2425/// 2426static bool isValidAfterIdentifierInDeclarator(const Token &T) { 2427 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi, 2428 tok::comma, tok::equal, tok::kw_asm, tok::l_brace, 2429 tok::colon); 2430} 2431 2432/// ParseImplicitInt - This method is called when we have an non-typename 2433/// identifier in a declspec (which normally terminates the decl spec) when 2434/// the declspec has no type specifier. In this case, the declspec is either 2435/// malformed or is "implicit int" (in K&R and C89). 2436/// 2437/// This method handles diagnosing this prettily and returns false if the 2438/// declspec is done being processed. If it recovers and thinks there may be 2439/// other pieces of declspec after it, it returns true. 2440/// 2441bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, 2442 const ParsedTemplateInfo &TemplateInfo, 2443 AccessSpecifier AS, DeclSpecContext DSC, 2444 ParsedAttributesWithRange &Attrs) { 2445 assert(Tok.is(tok::identifier) && "should have identifier"); 2446 2447 SourceLocation Loc = Tok.getLocation(); 2448 // If we see an identifier that is not a type name, we normally would 2449 // parse it as the identifer being declared. However, when a typename 2450 // is typo'd or the definition is not included, this will incorrectly 2451 // parse the typename as the identifier name and fall over misparsing 2452 // later parts of the diagnostic. 2453 // 2454 // As such, we try to do some look-ahead in cases where this would 2455 // otherwise be an "implicit-int" case to see if this is invalid. For 2456 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as 2457 // an identifier with implicit int, we'd get a parse error because the 2458 // next token is obviously invalid for a type. Parse these as a case 2459 // with an invalid type specifier. 2460 assert(!DS.hasTypeSpecifier() && "Type specifier checked above"); 2461 2462 // Since we know that this either implicit int (which is rare) or an 2463 // error, do lookahead to try to do better recovery. This never applies 2464 // within a type specifier. Outside of C++, we allow this even if the 2465 // language doesn't "officially" support implicit int -- we support 2466 // implicit int as an extension in C99 and C11. 2467 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus && 2468 isValidAfterIdentifierInDeclarator(NextToken())) { 2469 // If this token is valid for implicit int, e.g. "static x = 4", then 2470 // we just avoid eating the identifier, so it will be parsed as the 2471 // identifier in the declarator. 2472 return false; 2473 } 2474 2475 if (getLangOpts().CPlusPlus && 2476 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 2477 // Don't require a type specifier if we have the 'auto' storage class 2478 // specifier in C++98 -- we'll promote it to a type specifier. 2479 if (SS) 2480 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false); 2481 return false; 2482 } 2483 2484 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) && 2485 getLangOpts().MSVCCompat) { 2486 // Lookup of an unqualified type name has failed in MSVC compatibility mode. 2487 // Give Sema a chance to recover if we are in a template with dependent base 2488 // classes. 2489 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName( 2490 *Tok.getIdentifierInfo(), Tok.getLocation(), 2491 DSC == DeclSpecContext::DSC_template_type_arg)) { 2492 const char *PrevSpec; 2493 unsigned DiagID; 2494 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T, 2495 Actions.getASTContext().getPrintingPolicy()); 2496 DS.SetRangeEnd(Tok.getLocation()); 2497 ConsumeToken(); 2498 return false; 2499 } 2500 } 2501 2502 // Otherwise, if we don't consume this token, we are going to emit an 2503 // error anyway. Try to recover from various common problems. Check 2504 // to see if this was a reference to a tag name without a tag specified. 2505 // This is a common problem in C (saying 'foo' instead of 'struct foo'). 2506 // 2507 // C++ doesn't need this, and isTagName doesn't take SS. 2508 if (SS == nullptr) { 2509 const char *TagName = nullptr, *FixitTagName = nullptr; 2510 tok::TokenKind TagKind = tok::unknown; 2511 2512 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) { 2513 default: break; 2514 case DeclSpec::TST_enum: 2515 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break; 2516 case DeclSpec::TST_union: 2517 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break; 2518 case DeclSpec::TST_struct: 2519 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break; 2520 case DeclSpec::TST_interface: 2521 TagName="__interface"; FixitTagName = "__interface "; 2522 TagKind=tok::kw___interface;break; 2523 case DeclSpec::TST_class: 2524 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break; 2525 } 2526 2527 if (TagName) { 2528 IdentifierInfo *TokenName = Tok.getIdentifierInfo(); 2529 LookupResult R(Actions, TokenName, SourceLocation(), 2530 Sema::LookupOrdinaryName); 2531 2532 Diag(Loc, diag::err_use_of_tag_name_without_tag) 2533 << TokenName << TagName << getLangOpts().CPlusPlus 2534 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName); 2535 2536 if (Actions.LookupParsedName(R, getCurScope(), SS)) { 2537 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); 2538 I != IEnd; ++I) 2539 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 2540 << TokenName << TagName; 2541 } 2542 2543 // Parse this as a tag as if the missing tag were present. 2544 if (TagKind == tok::kw_enum) 2545 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, 2546 DeclSpecContext::DSC_normal); 2547 else 2548 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS, 2549 /*EnteringContext*/ false, 2550 DeclSpecContext::DSC_normal, Attrs); 2551 return true; 2552 } 2553 } 2554 2555 // Determine whether this identifier could plausibly be the name of something 2556 // being declared (with a missing type). 2557 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level || 2558 DSC == DeclSpecContext::DSC_class)) { 2559 // Look ahead to the next token to try to figure out what this declaration 2560 // was supposed to be. 2561 switch (NextToken().getKind()) { 2562 case tok::l_paren: { 2563 // static x(4); // 'x' is not a type 2564 // x(int n); // 'x' is not a type 2565 // x (*p)[]; // 'x' is a type 2566 // 2567 // Since we're in an error case, we can afford to perform a tentative 2568 // parse to determine which case we're in. 2569 TentativeParsingAction PA(*this); 2570 ConsumeToken(); 2571 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false); 2572 PA.Revert(); 2573 2574 if (TPR != TPResult::False) { 2575 // The identifier is followed by a parenthesized declarator. 2576 // It's supposed to be a type. 2577 break; 2578 } 2579 2580 // If we're in a context where we could be declaring a constructor, 2581 // check whether this is a constructor declaration with a bogus name. 2582 if (DSC == DeclSpecContext::DSC_class || 2583 (DSC == DeclSpecContext::DSC_top_level && SS)) { 2584 IdentifierInfo *II = Tok.getIdentifierInfo(); 2585 if (Actions.isCurrentClassNameTypo(II, SS)) { 2586 Diag(Loc, diag::err_constructor_bad_name) 2587 << Tok.getIdentifierInfo() << II 2588 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName()); 2589 Tok.setIdentifierInfo(II); 2590 } 2591 } 2592 // Fall through. 2593 LLVM_FALLTHROUGH; 2594 } 2595 case tok::comma: 2596 case tok::equal: 2597 case tok::kw_asm: 2598 case tok::l_brace: 2599 case tok::l_square: 2600 case tok::semi: 2601 // This looks like a variable or function declaration. The type is 2602 // probably missing. We're done parsing decl-specifiers. 2603 if (SS) 2604 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false); 2605 return false; 2606 2607 default: 2608 // This is probably supposed to be a type. This includes cases like: 2609 // int f(itn); 2610 // struct S { unsinged : 4; }; 2611 break; 2612 } 2613 } 2614 2615 // This is almost certainly an invalid type name. Let Sema emit a diagnostic 2616 // and attempt to recover. 2617 ParsedType T; 2618 IdentifierInfo *II = Tok.getIdentifierInfo(); 2619 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less); 2620 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T, 2621 IsTemplateName); 2622 if (T) { 2623 // The action has suggested that the type T could be used. Set that as 2624 // the type in the declaration specifiers, consume the would-be type 2625 // name token, and we're done. 2626 const char *PrevSpec; 2627 unsigned DiagID; 2628 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T, 2629 Actions.getASTContext().getPrintingPolicy()); 2630 DS.SetRangeEnd(Tok.getLocation()); 2631 ConsumeToken(); 2632 // There may be other declaration specifiers after this. 2633 return true; 2634 } else if (II != Tok.getIdentifierInfo()) { 2635 // If no type was suggested, the correction is to a keyword 2636 Tok.setKind(II->getTokenID()); 2637 // There may be other declaration specifiers after this. 2638 return true; 2639 } 2640 2641 // Otherwise, the action had no suggestion for us. Mark this as an error. 2642 DS.SetTypeSpecError(); 2643 DS.SetRangeEnd(Tok.getLocation()); 2644 ConsumeToken(); 2645 2646 // Eat any following template arguments. 2647 if (IsTemplateName) { 2648 SourceLocation LAngle, RAngle; 2649 TemplateArgList Args; 2650 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle); 2651 } 2652 2653 // TODO: Could inject an invalid typedef decl in an enclosing scope to 2654 // avoid rippling error messages on subsequent uses of the same type, 2655 // could be useful if #include was forgotten. 2656 return false; 2657} 2658 2659/// \brief Determine the declaration specifier context from the declarator 2660/// context. 2661/// 2662/// \param Context the declarator context, which is one of the 2663/// DeclaratorContext enumerator values. 2664Parser::DeclSpecContext 2665Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) { 2666 if (Context == DeclaratorContext::MemberContext) 2667 return DeclSpecContext::DSC_class; 2668 if (Context == DeclaratorContext::FileContext) 2669 return DeclSpecContext::DSC_top_level; 2670 if (Context == DeclaratorContext::TemplateParamContext) 2671 return DeclSpecContext::DSC_template_param; 2672 if (Context == DeclaratorContext::TemplateTypeArgContext) 2673 return DeclSpecContext::DSC_template_type_arg; 2674 if (Context == DeclaratorContext::TrailingReturnContext) 2675 return DeclSpecContext::DSC_trailing; 2676 if (Context == DeclaratorContext::AliasDeclContext || 2677 Context == DeclaratorContext::AliasTemplateContext) 2678 return DeclSpecContext::DSC_alias_declaration; 2679 return DeclSpecContext::DSC_normal; 2680} 2681 2682/// ParseAlignArgument - Parse the argument to an alignment-specifier. 2683/// 2684/// FIXME: Simply returns an alignof() expression if the argument is a 2685/// type. Ideally, the type should be propagated directly into Sema. 2686/// 2687/// [C11] type-id 2688/// [C11] constant-expression 2689/// [C++0x] type-id ...[opt] 2690/// [C++0x] assignment-expression ...[opt] 2691ExprResult Parser::ParseAlignArgument(SourceLocation Start, 2692 SourceLocation &EllipsisLoc) { 2693 ExprResult ER; 2694 if (isTypeIdInParens()) { 2695 SourceLocation TypeLoc = Tok.getLocation(); 2696 ParsedType Ty = ParseTypeName().get(); 2697 SourceRange TypeRange(Start, Tok.getLocation()); 2698 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true, 2699 Ty.getAsOpaquePtr(), TypeRange); 2700 } else 2701 ER = ParseConstantExpression(); 2702 2703 if (getLangOpts().CPlusPlus11) 2704 TryConsumeToken(tok::ellipsis, EllipsisLoc); 2705 2706 return ER; 2707} 2708 2709/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the 2710/// attribute to Attrs. 2711/// 2712/// alignment-specifier: 2713/// [C11] '_Alignas' '(' type-id ')' 2714/// [C11] '_Alignas' '(' constant-expression ')' 2715/// [C++11] 'alignas' '(' type-id ...[opt] ')' 2716/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')' 2717void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs, 2718 SourceLocation *EndLoc) { 2719 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) && 2720 "Not an alignment-specifier!"); 2721 2722 IdentifierInfo *KWName = Tok.getIdentifierInfo(); 2723 SourceLocation KWLoc = ConsumeToken(); 2724 2725 BalancedDelimiterTracker T(*this, tok::l_paren); 2726 if (T.expectAndConsume()) 2727 return; 2728 2729 SourceLocation EllipsisLoc; 2730 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc); 2731 if (ArgExpr.isInvalid()) { 2732 T.skipToEnd(); 2733 return; 2734 } 2735 2736 T.consumeClose(); 2737 if (EndLoc) 2738 *EndLoc = T.getCloseLocation(); 2739 2740 ArgsVector ArgExprs; 2741 ArgExprs.push_back(ArgExpr.get()); 2742 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1, 2743 AttributeList::AS_Keyword, EllipsisLoc); 2744} 2745 2746/// Determine whether we're looking at something that might be a declarator 2747/// in a simple-declaration. If it can't possibly be a declarator, maybe 2748/// diagnose a missing semicolon after a prior tag definition in the decl 2749/// specifier. 2750/// 2751/// \return \c true if an error occurred and this can't be any kind of 2752/// declaration. 2753bool 2754Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS, 2755 DeclSpecContext DSContext, 2756 LateParsedAttrList *LateAttrs) { 2757 assert(DS.hasTagDefinition() && "shouldn't call this"); 2758 2759 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class || 2760 DSContext == DeclSpecContext::DSC_top_level); 2761 2762 if (getLangOpts().CPlusPlus && 2763 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype, 2764 tok::annot_template_id) && 2765 TryAnnotateCXXScopeToken(EnteringContext)) { 2766 SkipMalformedDecl(); 2767 return true; 2768 } 2769 2770 bool HasScope = Tok.is(tok::annot_cxxscope); 2771 // Make a copy in case GetLookAheadToken invalidates the result of NextToken. 2772 Token AfterScope = HasScope ? NextToken() : Tok; 2773 2774 // Determine whether the following tokens could possibly be a 2775 // declarator. 2776 bool MightBeDeclarator = true; 2777 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) { 2778 // A declarator-id can't start with 'typename'. 2779 MightBeDeclarator = false; 2780 } else if (AfterScope.is(tok::annot_template_id)) { 2781 // If we have a type expressed as a template-id, this cannot be a 2782 // declarator-id (such a type cannot be redeclared in a simple-declaration). 2783 TemplateIdAnnotation *Annot = 2784 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue()); 2785 if (Annot->Kind == TNK_Type_template) 2786 MightBeDeclarator = false; 2787 } else if (AfterScope.is(tok::identifier)) { 2788 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken(); 2789 2790 // These tokens cannot come after the declarator-id in a 2791 // simple-declaration, and are likely to come after a type-specifier. 2792 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier, 2793 tok::annot_cxxscope, tok::coloncolon)) { 2794 // Missing a semicolon. 2795 MightBeDeclarator = false; 2796 } else if (HasScope) { 2797 // If the declarator-id has a scope specifier, it must redeclare a 2798 // previously-declared entity. If that's a type (and this is not a 2799 // typedef), that's an error. 2800 CXXScopeSpec SS; 2801 Actions.RestoreNestedNameSpecifierAnnotation( 2802 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS); 2803 IdentifierInfo *Name = AfterScope.getIdentifierInfo(); 2804 Sema::NameClassification Classification = Actions.ClassifyName( 2805 getCurScope(), SS, Name, AfterScope.getLocation(), Next, 2806 /*IsAddressOfOperand*/false); 2807 switch (Classification.getKind()) { 2808 case Sema::NC_Error: 2809 SkipMalformedDecl(); 2810 return true; 2811 2812 case Sema::NC_Keyword: 2813 case Sema::NC_NestedNameSpecifier: 2814 llvm_unreachable("typo correction and nested name specifiers not " 2815 "possible here"); 2816 2817 case Sema::NC_Type: 2818 case Sema::NC_TypeTemplate: 2819 // Not a previously-declared non-type entity. 2820 MightBeDeclarator = false; 2821 break; 2822 2823 case Sema::NC_Unknown: 2824 case Sema::NC_Expression: 2825 case Sema::NC_VarTemplate: 2826 case Sema::NC_FunctionTemplate: 2827 // Might be a redeclaration of a prior entity. 2828 break; 2829 } 2830 } 2831 } 2832 2833 if (MightBeDeclarator) 2834 return false; 2835 2836 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy(); 2837 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()), 2838 diag::err_expected_after) 2839 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi; 2840 2841 // Try to recover from the typo, by dropping the tag definition and parsing 2842 // the problematic tokens as a type. 2843 // 2844 // FIXME: Split the DeclSpec into pieces for the standalone 2845 // declaration and pieces for the following declaration, instead 2846 // of assuming that all the other pieces attach to new declaration, 2847 // and call ParsedFreeStandingDeclSpec as appropriate. 2848 DS.ClearTypeSpecType(); 2849 ParsedTemplateInfo NotATemplate; 2850 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs); 2851 return false; 2852} 2853 2854/// ParseDeclarationSpecifiers 2855/// declaration-specifiers: [C99 6.7] 2856/// storage-class-specifier declaration-specifiers[opt] 2857/// type-specifier declaration-specifiers[opt] 2858/// [C99] function-specifier declaration-specifiers[opt] 2859/// [C11] alignment-specifier declaration-specifiers[opt] 2860/// [GNU] attributes declaration-specifiers[opt] 2861/// [Clang] '__module_private__' declaration-specifiers[opt] 2862/// [ObjC1] '__kindof' declaration-specifiers[opt] 2863/// 2864/// storage-class-specifier: [C99 6.7.1] 2865/// 'typedef' 2866/// 'extern' 2867/// 'static' 2868/// 'auto' 2869/// 'register' 2870/// [C++] 'mutable' 2871/// [C++11] 'thread_local' 2872/// [C11] '_Thread_local' 2873/// [GNU] '__thread' 2874/// function-specifier: [C99 6.7.4] 2875/// [C99] 'inline' 2876/// [C++] 'virtual' 2877/// [C++] 'explicit' 2878/// [OpenCL] '__kernel' 2879/// 'friend': [C++ dcl.friend] 2880/// 'constexpr': [C++0x dcl.constexpr] 2881void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, 2882 const ParsedTemplateInfo &TemplateInfo, 2883 AccessSpecifier AS, 2884 DeclSpecContext DSContext, 2885 LateParsedAttrList *LateAttrs) { 2886 if (DS.getSourceRange().isInvalid()) { 2887 // Start the range at the current token but make the end of the range 2888 // invalid. This will make the entire range invalid unless we successfully 2889 // consume a token. 2890 DS.SetRangeStart(Tok.getLocation()); 2891 DS.SetRangeEnd(SourceLocation()); 2892 } 2893 2894 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class || 2895 DSContext == DeclSpecContext::DSC_top_level); 2896 bool AttrsLastTime = false; 2897 ParsedAttributesWithRange attrs(AttrFactory); 2898 // We use Sema's policy to get bool macros right. 2899 PrintingPolicy Policy = Actions.getPrintingPolicy(); 2900 while (1) { 2901 bool isInvalid = false; 2902 bool isStorageClass = false; 2903 const char *PrevSpec = nullptr; 2904 unsigned DiagID = 0; 2905 2906 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL 2907 // implementation for VS2013 uses _Atomic as an identifier for one of the 2908 // classes in <atomic>. 2909 // 2910 // A typedef declaration containing _Atomic<...> is among the places where 2911 // the class is used. If we are currently parsing such a declaration, treat 2912 // the token as an identifier. 2913 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) && 2914 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef && 2915 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less)) 2916 Tok.setKind(tok::identifier); 2917 2918 SourceLocation Loc = Tok.getLocation(); 2919 2920 switch (Tok.getKind()) { 2921 default: 2922 DoneWithDeclSpec: 2923 if (!AttrsLastTime) 2924 ProhibitAttributes(attrs); 2925 else { 2926 // Reject C++11 attributes that appertain to decl specifiers as 2927 // we don't support any C++11 attributes that appertain to decl 2928 // specifiers. This also conforms to what g++ 4.8 is doing. 2929 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr); 2930 2931 DS.takeAttributesFrom(attrs); 2932 } 2933 2934 // If this is not a declaration specifier token, we're done reading decl 2935 // specifiers. First verify that DeclSpec's are consistent. 2936 DS.Finish(Actions, Policy); 2937 return; 2938 2939 case tok::l_square: 2940 case tok::kw_alignas: 2941 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier()) 2942 goto DoneWithDeclSpec; 2943 2944 ProhibitAttributes(attrs); 2945 // FIXME: It would be good to recover by accepting the attributes, 2946 // but attempting to do that now would cause serious 2947 // madness in terms of diagnostics. 2948 attrs.clear(); 2949 attrs.Range = SourceRange(); 2950 2951 ParseCXX11Attributes(attrs); 2952 AttrsLastTime = true; 2953 continue; 2954 2955 case tok::code_completion: { 2956 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace; 2957 if (DS.hasTypeSpecifier()) { 2958 bool AllowNonIdentifiers 2959 = (getCurScope()->getFlags() & (Scope::ControlScope | 2960 Scope::BlockScope | 2961 Scope::TemplateParamScope | 2962 Scope::FunctionPrototypeScope | 2963 Scope::AtCatchScope)) == 0; 2964 bool AllowNestedNameSpecifiers 2965 = DSContext == DeclSpecContext::DSC_top_level || 2966 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified()); 2967 2968 Actions.CodeCompleteDeclSpec(getCurScope(), DS, 2969 AllowNonIdentifiers, 2970 AllowNestedNameSpecifiers); 2971 return cutOffParsing(); 2972 } 2973 2974 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent()) 2975 CCC = Sema::PCC_LocalDeclarationSpecifiers; 2976 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) 2977 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate 2978 : Sema::PCC_Template; 2979 else if (DSContext == DeclSpecContext::DSC_class) 2980 CCC = Sema::PCC_Class; 2981 else if (CurParsedObjCImpl) 2982 CCC = Sema::PCC_ObjCImplementation; 2983 2984 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC); 2985 return cutOffParsing(); 2986 } 2987 2988 case tok::coloncolon: // ::foo::bar 2989 // C++ scope specifier. Annotate and loop, or bail out on error. 2990 if (TryAnnotateCXXScopeToken(EnteringContext)) { 2991 if (!DS.hasTypeSpecifier()) 2992 DS.SetTypeSpecError(); 2993 goto DoneWithDeclSpec; 2994 } 2995 if (Tok.is(tok::coloncolon)) // ::new or ::delete 2996 goto DoneWithDeclSpec; 2997 continue; 2998 2999 case tok::annot_cxxscope: { 3000 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector()) 3001 goto DoneWithDeclSpec; 3002 3003 CXXScopeSpec SS; 3004 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), 3005 Tok.getAnnotationRange(), 3006 SS); 3007 3008 // We are looking for a qualified typename. 3009 Token Next = NextToken(); 3010 if (Next.is(tok::annot_template_id) && 3011 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()) 3012 ->Kind == TNK_Type_template) { 3013 // We have a qualified template-id, e.g., N::A<int> 3014 3015 // If this would be a valid constructor declaration with template 3016 // arguments, we will reject the attempt to form an invalid type-id 3017 // referring to the injected-class-name when we annotate the token, 3018 // per C++ [class.qual]p2. 3019 // 3020 // To improve diagnostics for this case, parse the declaration as a 3021 // constructor (and reject the extra template arguments later). 3022 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next); 3023 if ((DSContext == DeclSpecContext::DSC_top_level || 3024 DSContext == DeclSpecContext::DSC_class) && 3025 TemplateId->Name && 3026 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) && 3027 isConstructorDeclarator(/*Unqualified*/ false)) { 3028 // The user meant this to be an out-of-line constructor 3029 // definition, but template arguments are not allowed 3030 // there. Just allow this as a constructor; we'll 3031 // complain about it later. 3032 goto DoneWithDeclSpec; 3033 } 3034 3035 DS.getTypeSpecScope() = SS; 3036 ConsumeAnnotationToken(); // The C++ scope. 3037 assert(Tok.is(tok::annot_template_id) && 3038 "ParseOptionalCXXScopeSpecifier not working"); 3039 AnnotateTemplateIdTokenAsType(); 3040 continue; 3041 } 3042 3043 if (Next.is(tok::annot_typename)) { 3044 DS.getTypeSpecScope() = SS; 3045 ConsumeAnnotationToken(); // The C++ scope. 3046 if (Tok.getAnnotationValue()) { 3047 ParsedType T = getTypeAnnotation(Tok); 3048 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, 3049 Tok.getAnnotationEndLoc(), 3050 PrevSpec, DiagID, T, Policy); 3051 if (isInvalid) 3052 break; 3053 } 3054 else 3055 DS.SetTypeSpecError(); 3056 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 3057 ConsumeAnnotationToken(); // The typename 3058 } 3059 3060 if (Next.isNot(tok::identifier)) 3061 goto DoneWithDeclSpec; 3062 3063 // Check whether this is a constructor declaration. If we're in a 3064 // context where the identifier could be a class name, and it has the 3065 // shape of a constructor declaration, process it as one. 3066 if ((DSContext == DeclSpecContext::DSC_top_level || 3067 DSContext == DeclSpecContext::DSC_class) && 3068 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(), 3069 &SS) && 3070 isConstructorDeclarator(/*Unqualified*/ false)) 3071 goto DoneWithDeclSpec; 3072 3073 ParsedType TypeRep = 3074 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(), 3075 getCurScope(), &SS, false, false, nullptr, 3076 /*IsCtorOrDtorName=*/false, 3077 /*WantNonTrivialSourceInfo=*/true, 3078 isClassTemplateDeductionContext(DSContext)); 3079 3080 // If the referenced identifier is not a type, then this declspec is 3081 // erroneous: We already checked about that it has no type specifier, and 3082 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the 3083 // typename. 3084 if (!TypeRep) { 3085 // Eat the scope spec so the identifier is current. 3086 ConsumeAnnotationToken(); 3087 ParsedAttributesWithRange Attrs(AttrFactory); 3088 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) { 3089 if (!Attrs.empty()) { 3090 AttrsLastTime = true; 3091 attrs.takeAllFrom(Attrs); 3092 } 3093 continue; 3094 } 3095 goto DoneWithDeclSpec; 3096 } 3097 3098 DS.getTypeSpecScope() = SS; 3099 ConsumeAnnotationToken(); // The C++ scope. 3100 3101 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 3102 DiagID, TypeRep, Policy); 3103 if (isInvalid) 3104 break; 3105 3106 DS.SetRangeEnd(Tok.getLocation()); 3107 ConsumeToken(); // The typename. 3108 3109 continue; 3110 } 3111 3112 case tok::annot_typename: { 3113 // If we've previously seen a tag definition, we were almost surely 3114 // missing a semicolon after it. 3115 if (DS.hasTypeSpecifier() && DS.hasTagDefinition()) 3116 goto DoneWithDeclSpec; 3117 3118 if (Tok.getAnnotationValue()) { 3119 ParsedType T = getTypeAnnotation(Tok); 3120 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 3121 DiagID, T, Policy); 3122 } else 3123 DS.SetTypeSpecError(); 3124 3125 if (isInvalid) 3126 break; 3127 3128 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 3129 ConsumeAnnotationToken(); // The typename 3130 3131 continue; 3132 } 3133 3134 case tok::kw___is_signed: 3135 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang 3136 // typically treats it as a trait. If we see __is_signed as it appears 3137 // in libstdc++, e.g., 3138 // 3139 // static const bool __is_signed; 3140 // 3141 // then treat __is_signed as an identifier rather than as a keyword. 3142 if (DS.getTypeSpecType() == TST_bool && 3143 DS.getTypeQualifiers() == DeclSpec::TQ_const && 3144 DS.getStorageClassSpec() == DeclSpec::SCS_static) 3145 TryKeywordIdentFallback(true); 3146 3147 // We're done with the declaration-specifiers. 3148 goto DoneWithDeclSpec; 3149 3150 // typedef-name 3151 case tok::kw___super: 3152 case tok::kw_decltype: 3153 case tok::identifier: { 3154 // This identifier can only be a typedef name if we haven't already seen 3155 // a type-specifier. Without this check we misparse: 3156 // typedef int X; struct Y { short X; }; as 'short int'. 3157 if (DS.hasTypeSpecifier()) 3158 goto DoneWithDeclSpec; 3159 3160 // If the token is an identifier named "__declspec" and Microsoft 3161 // extensions are not enabled, it is likely that there will be cascading 3162 // parse errors if this really is a __declspec attribute. Attempt to 3163 // recognize that scenario and recover gracefully. 3164 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) && 3165 Tok.getIdentifierInfo()->getName().equals("__declspec")) { 3166 Diag(Loc, diag::err_ms_attributes_not_enabled); 3167 3168 // The next token should be an open paren. If it is, eat the entire 3169 // attribute declaration and continue. 3170 if (NextToken().is(tok::l_paren)) { 3171 // Consume the __declspec identifier. 3172 ConsumeToken(); 3173 3174 // Eat the parens and everything between them. 3175 BalancedDelimiterTracker T(*this, tok::l_paren); 3176 if (T.consumeOpen()) { 3177 assert(false && "Not a left paren?"); 3178 return; 3179 } 3180 T.skipToEnd(); 3181 continue; 3182 } 3183 } 3184 3185 // In C++, check to see if this is a scope specifier like foo::bar::, if 3186 // so handle it as such. This is important for ctor parsing. 3187 if (getLangOpts().CPlusPlus) { 3188 if (TryAnnotateCXXScopeToken(EnteringContext)) { 3189 DS.SetTypeSpecError(); 3190 goto DoneWithDeclSpec; 3191 } 3192 if (!Tok.is(tok::identifier)) 3193 continue; 3194 } 3195 3196 // Check for need to substitute AltiVec keyword tokens. 3197 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid)) 3198 break; 3199 3200 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not 3201 // allow the use of a typedef name as a type specifier. 3202 if (DS.isTypeAltiVecVector()) 3203 goto DoneWithDeclSpec; 3204 3205 if (DSContext == DeclSpecContext::DSC_objc_method_result && 3206 isObjCInstancetype()) { 3207 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc); 3208 assert(TypeRep); 3209 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 3210 DiagID, TypeRep, Policy); 3211 if (isInvalid) 3212 break; 3213 3214 DS.SetRangeEnd(Loc); 3215 ConsumeToken(); 3216 continue; 3217 } 3218 3219 ParsedType TypeRep = Actions.getTypeName( 3220 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr, 3221 false, false, nullptr, false, false, 3222 isClassTemplateDeductionContext(DSContext)); 3223 3224 // If this is not a typedef name, don't parse it as part of the declspec, 3225 // it must be an implicit int or an error. 3226 if (!TypeRep) { 3227 ParsedAttributesWithRange Attrs(AttrFactory); 3228 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) { 3229 if (!Attrs.empty()) { 3230 AttrsLastTime = true; 3231 attrs.takeAllFrom(Attrs); 3232 } 3233 continue; 3234 } 3235 goto DoneWithDeclSpec; 3236 } 3237 3238 // If we're in a context where the identifier could be a class name, 3239 // check whether this is a constructor declaration. 3240 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class && 3241 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) && 3242 isConstructorDeclarator(/*Unqualified*/true)) 3243 goto DoneWithDeclSpec; 3244 3245 // Likewise, if this is a context where the identifier could be a template 3246 // name, check whether this is a deduction guide declaration. 3247 if (getLangOpts().CPlusPlus17 && 3248 (DSContext == DeclSpecContext::DSC_class || 3249 DSContext == DeclSpecContext::DSC_top_level) && 3250 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(), 3251 Tok.getLocation()) && 3252 isConstructorDeclarator(/*Unqualified*/ true, 3253 /*DeductionGuide*/ true)) 3254 goto DoneWithDeclSpec; 3255 3256 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 3257 DiagID, TypeRep, Policy); 3258 if (isInvalid) 3259 break; 3260 3261 DS.SetRangeEnd(Tok.getLocation()); 3262 ConsumeToken(); // The identifier 3263 3264 // Objective-C supports type arguments and protocol references 3265 // following an Objective-C object or object pointer 3266 // type. Handle either one of them. 3267 if (Tok.is(tok::less) && getLangOpts().ObjC1) { 3268 SourceLocation NewEndLoc; 3269 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers( 3270 Loc, TypeRep, /*consumeLastToken=*/true, 3271 NewEndLoc); 3272 if (NewTypeRep.isUsable()) { 3273 DS.UpdateTypeRep(NewTypeRep.get()); 3274 DS.SetRangeEnd(NewEndLoc); 3275 } 3276 } 3277 3278 // Need to support trailing type qualifiers (e.g. "id<p> const"). 3279 // If a type specifier follows, it will be diagnosed elsewhere. 3280 continue; 3281 } 3282 3283 // type-name 3284 case tok::annot_template_id: { 3285 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 3286 if (TemplateId->Kind != TNK_Type_template) { 3287 // This template-id does not refer to a type name, so we're 3288 // done with the type-specifiers. 3289 goto DoneWithDeclSpec; 3290 } 3291 3292 // If we're in a context where the template-id could be a 3293 // constructor name or specialization, check whether this is a 3294 // constructor declaration. 3295 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class && 3296 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) && 3297 isConstructorDeclarator(TemplateId->SS.isEmpty())) 3298 goto DoneWithDeclSpec; 3299 3300 // Turn the template-id annotation token into a type annotation 3301 // token, then try again to parse it as a type-specifier. 3302 AnnotateTemplateIdTokenAsType(); 3303 continue; 3304 } 3305 3306 // GNU attributes support. 3307 case tok::kw___attribute: 3308 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs); 3309 continue; 3310 3311 // Microsoft declspec support. 3312 case tok::kw___declspec: 3313 ParseMicrosoftDeclSpecs(DS.getAttributes()); 3314 continue; 3315 3316 // Microsoft single token adornments. 3317 case tok::kw___forceinline: { 3318 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID); 3319 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 3320 SourceLocation AttrNameLoc = Tok.getLocation(); 3321 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, 3322 nullptr, 0, AttributeList::AS_Keyword); 3323 break; 3324 } 3325 3326 case tok::kw___unaligned: 3327 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID, 3328 getLangOpts()); 3329 break; 3330 3331 case tok::kw___sptr: 3332 case tok::kw___uptr: 3333 case tok::kw___ptr64: 3334 case tok::kw___ptr32: 3335 case tok::kw___w64: 3336 case tok::kw___cdecl: 3337 case tok::kw___stdcall: 3338 case tok::kw___fastcall: 3339 case tok::kw___thiscall: 3340 case tok::kw___regcall: 3341 case tok::kw___vectorcall: 3342 ParseMicrosoftTypeAttributes(DS.getAttributes()); 3343 continue; 3344 3345 // Borland single token adornments. 3346 case tok::kw___pascal: 3347 ParseBorlandTypeAttributes(DS.getAttributes()); 3348 continue; 3349 3350 // OpenCL single token adornments. 3351 case tok::kw___kernel: 3352 ParseOpenCLKernelAttributes(DS.getAttributes()); 3353 continue; 3354 3355 // Nullability type specifiers. 3356 case tok::kw__Nonnull: 3357 case tok::kw__Nullable: 3358 case tok::kw__Null_unspecified: 3359 ParseNullabilityTypeSpecifiers(DS.getAttributes()); 3360 continue; 3361 3362 // Objective-C 'kindof' types. 3363 case tok::kw___kindof: 3364 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc, 3365 nullptr, 0, AttributeList::AS_Keyword); 3366 (void)ConsumeToken(); 3367 continue; 3368 3369 // storage-class-specifier 3370 case tok::kw_typedef: 3371 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc, 3372 PrevSpec, DiagID, Policy); 3373 isStorageClass = true; 3374 break; 3375 case tok::kw_extern: 3376 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread) 3377 Diag(Tok, diag::ext_thread_before) << "extern"; 3378 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc, 3379 PrevSpec, DiagID, Policy); 3380 isStorageClass = true; 3381 break; 3382 case tok::kw___private_extern__: 3383 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern, 3384 Loc, PrevSpec, DiagID, Policy); 3385 isStorageClass = true; 3386 break; 3387 case tok::kw_static: 3388 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread) 3389 Diag(Tok, diag::ext_thread_before) << "static"; 3390 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc, 3391 PrevSpec, DiagID, Policy); 3392 isStorageClass = true; 3393 break; 3394 case tok::kw_auto: 3395 if (getLangOpts().CPlusPlus11) { 3396 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { 3397 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc, 3398 PrevSpec, DiagID, Policy); 3399 if (!isInvalid) 3400 Diag(Tok, diag::ext_auto_storage_class) 3401 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3402 } else 3403 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, 3404 DiagID, Policy); 3405 } else 3406 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc, 3407 PrevSpec, DiagID, Policy); 3408 isStorageClass = true; 3409 break; 3410 case tok::kw___auto_type: 3411 Diag(Tok, diag::ext_auto_type); 3412 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec, 3413 DiagID, Policy); 3414 break; 3415 case tok::kw_register: 3416 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc, 3417 PrevSpec, DiagID, Policy); 3418 isStorageClass = true; 3419 break; 3420 case tok::kw_mutable: 3421 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc, 3422 PrevSpec, DiagID, Policy); 3423 isStorageClass = true; 3424 break; 3425 case tok::kw___thread: 3426 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc, 3427 PrevSpec, DiagID); 3428 isStorageClass = true; 3429 break; 3430 case tok::kw_thread_local: 3431 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc, 3432 PrevSpec, DiagID); 3433 break; 3434 case tok::kw__Thread_local: 3435 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local, 3436 Loc, PrevSpec, DiagID); 3437 isStorageClass = true; 3438 break; 3439 3440 // function-specifier 3441 case tok::kw_inline: 3442 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID); 3443 break; 3444 case tok::kw_virtual: 3445 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID); 3446 break; 3447 case tok::kw_explicit: 3448 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID); 3449 break; 3450 case tok::kw__Noreturn: 3451 if (!getLangOpts().C11) 3452 Diag(Loc, diag::ext_c11_noreturn); 3453 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID); 3454 break; 3455 3456 // alignment-specifier 3457 case tok::kw__Alignas: 3458 if (!getLangOpts().C11) 3459 Diag(Tok, diag::ext_c11_alignment) << Tok.getName(); 3460 ParseAlignmentSpecifier(DS.getAttributes()); 3461 continue; 3462 3463 // friend 3464 case tok::kw_friend: 3465 if (DSContext == DeclSpecContext::DSC_class) 3466 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID); 3467 else { 3468 PrevSpec = ""; // not actually used by the diagnostic 3469 DiagID = diag::err_friend_invalid_in_context; 3470 isInvalid = true; 3471 } 3472 break; 3473 3474 // Modules 3475 case tok::kw___module_private__: 3476 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID); 3477 break; 3478 3479 // constexpr 3480 case tok::kw_constexpr: 3481 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID); 3482 break; 3483 3484 // type-specifier 3485 case tok::kw_short: 3486 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, 3487 DiagID, Policy); 3488 break; 3489 case tok::kw_long: 3490 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 3491 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 3492 DiagID, Policy); 3493 else 3494 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 3495 DiagID, Policy); 3496 break; 3497 case tok::kw___int64: 3498 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 3499 DiagID, Policy); 3500 break; 3501 case tok::kw_signed: 3502 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, 3503 DiagID); 3504 break; 3505 case tok::kw_unsigned: 3506 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 3507 DiagID); 3508 break; 3509 case tok::kw__Complex: 3510 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 3511 DiagID); 3512 break; 3513 case tok::kw__Imaginary: 3514 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 3515 DiagID); 3516 break; 3517 case tok::kw_void: 3518 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, 3519 DiagID, Policy); 3520 break; 3521 case tok::kw_char: 3522 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, 3523 DiagID, Policy); 3524 break; 3525 case tok::kw_int: 3526 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, 3527 DiagID, Policy); 3528 break; 3529 case tok::kw___int128: 3530 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, 3531 DiagID, Policy); 3532 break; 3533 case tok::kw_half: 3534 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, 3535 DiagID, Policy); 3536 break; 3537 case tok::kw_float: 3538 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, 3539 DiagID, Policy); 3540 break; 3541 case tok::kw_double: 3542 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, 3543 DiagID, Policy); 3544 break; 3545 case tok::kw__Float16: 3546 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, 3547 DiagID, Policy); 3548 break; 3549 case tok::kw___float128: 3550 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, 3551 DiagID, Policy); 3552 break; 3553 case tok::kw_wchar_t: 3554 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, 3555 DiagID, Policy); 3556 break; 3557 case tok::kw_char16_t: 3558 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, 3559 DiagID, Policy); 3560 break; 3561 case tok::kw_char32_t: 3562 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, 3563 DiagID, Policy); 3564 break; 3565 case tok::kw_bool: 3566 case tok::kw__Bool: 3567 if (Tok.is(tok::kw_bool) && 3568 DS.getTypeSpecType() != DeclSpec::TST_unspecified && 3569 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 3570 PrevSpec = ""; // Not used by the diagnostic. 3571 DiagID = diag::err_bool_redeclaration; 3572 // For better error recovery. 3573 Tok.setKind(tok::identifier); 3574 isInvalid = true; 3575 } else { 3576 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, 3577 DiagID, Policy); 3578 } 3579 break; 3580 case tok::kw__Decimal32: 3581 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 3582 DiagID, Policy); 3583 break; 3584 case tok::kw__Decimal64: 3585 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 3586 DiagID, Policy); 3587 break; 3588 case tok::kw__Decimal128: 3589 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 3590 DiagID, Policy); 3591 break; 3592 case tok::kw___vector: 3593 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy); 3594 break; 3595 case tok::kw___pixel: 3596 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy); 3597 break; 3598 case tok::kw___bool: 3599 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy); 3600 break; 3601 case tok::kw_pipe: 3602 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) { 3603 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should 3604 // support the "pipe" word as identifier. 3605 Tok.getIdentifierInfo()->revertTokenIDToIdentifier(); 3606 goto DoneWithDeclSpec; 3607 } 3608 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy); 3609 break; 3610#define GENERIC_IMAGE_TYPE(ImgType, Id) \ 3611 case tok::kw_##ImgType##_t: \ 3612 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \ 3613 DiagID, Policy); \ 3614 break; 3615#include "clang/Basic/OpenCLImageTypes.def" 3616 case tok::kw___unknown_anytype: 3617 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc, 3618 PrevSpec, DiagID, Policy); 3619 break; 3620 3621 // class-specifier: 3622 case tok::kw_class: 3623 case tok::kw_struct: 3624 case tok::kw___interface: 3625 case tok::kw_union: { 3626 tok::TokenKind Kind = Tok.getKind(); 3627 ConsumeToken(); 3628 3629 // These are attributes following class specifiers. 3630 // To produce better diagnostic, we parse them when 3631 // parsing class specifier. 3632 ParsedAttributesWithRange Attributes(AttrFactory); 3633 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS, 3634 EnteringContext, DSContext, Attributes); 3635 3636 // If there are attributes following class specifier, 3637 // take them over and handle them here. 3638 if (!Attributes.empty()) { 3639 AttrsLastTime = true; 3640 attrs.takeAllFrom(Attributes); 3641 } 3642 continue; 3643 } 3644 3645 // enum-specifier: 3646 case tok::kw_enum: 3647 ConsumeToken(); 3648 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext); 3649 continue; 3650 3651 // cv-qualifier: 3652 case tok::kw_const: 3653 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID, 3654 getLangOpts()); 3655 break; 3656 case tok::kw_volatile: 3657 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 3658 getLangOpts()); 3659 break; 3660 case tok::kw_restrict: 3661 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 3662 getLangOpts()); 3663 break; 3664 3665 // C++ typename-specifier: 3666 case tok::kw_typename: 3667 if (TryAnnotateTypeOrScopeToken()) { 3668 DS.SetTypeSpecError(); 3669 goto DoneWithDeclSpec; 3670 } 3671 if (!Tok.is(tok::kw_typename)) 3672 continue; 3673 break; 3674 3675 // GNU typeof support. 3676 case tok::kw_typeof: 3677 ParseTypeofSpecifier(DS); 3678 continue; 3679 3680 case tok::annot_decltype: 3681 ParseDecltypeSpecifier(DS); 3682 continue; 3683 3684 case tok::annot_pragma_pack: 3685 HandlePragmaPack(); 3686 continue; 3687 3688 case tok::annot_pragma_ms_pragma: 3689 HandlePragmaMSPragma(); 3690 continue; 3691 3692 case tok::annot_pragma_ms_vtordisp: 3693 HandlePragmaMSVtorDisp(); 3694 continue; 3695 3696 case tok::annot_pragma_ms_pointers_to_members: 3697 HandlePragmaMSPointersToMembers(); 3698 continue; 3699 3700 case tok::kw___underlying_type: 3701 ParseUnderlyingTypeSpecifier(DS); 3702 continue; 3703 3704 case tok::kw__Atomic: 3705 // C11 6.7.2.4/4: 3706 // If the _Atomic keyword is immediately followed by a left parenthesis, 3707 // it is interpreted as a type specifier (with a type name), not as a 3708 // type qualifier. 3709 if (NextToken().is(tok::l_paren)) { 3710 ParseAtomicSpecifier(DS); 3711 continue; 3712 } 3713 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID, 3714 getLangOpts()); 3715 break; 3716 3717 // OpenCL qualifiers: 3718 case tok::kw___generic: 3719 // generic address space is introduced only in OpenCL v2.0 3720 // see OpenCL C Spec v2.0 s6.5.5 3721 if (Actions.getLangOpts().OpenCLVersion < 200) { 3722 DiagID = diag::err_opencl_unknown_type_specifier; 3723 PrevSpec = Tok.getIdentifierInfo()->getNameStart(); 3724 isInvalid = true; 3725 break; 3726 }; 3727 LLVM_FALLTHROUGH; 3728 case tok::kw___private: 3729 case tok::kw___global: 3730 case tok::kw___local: 3731 case tok::kw___constant: 3732 case tok::kw___read_only: 3733 case tok::kw___write_only: 3734 case tok::kw___read_write: 3735 ParseOpenCLQualifiers(DS.getAttributes()); 3736 break; 3737 3738 case tok::less: 3739 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for 3740 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous, 3741 // but we support it. 3742 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1) 3743 goto DoneWithDeclSpec; 3744 3745 SourceLocation StartLoc = Tok.getLocation(); 3746 SourceLocation EndLoc; 3747 TypeResult Type = parseObjCProtocolQualifierType(EndLoc); 3748 if (Type.isUsable()) { 3749 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc, 3750 PrevSpec, DiagID, Type.get(), 3751 Actions.getASTContext().getPrintingPolicy())) 3752 Diag(StartLoc, DiagID) << PrevSpec; 3753 3754 DS.SetRangeEnd(EndLoc); 3755 } else { 3756 DS.SetTypeSpecError(); 3757 } 3758 3759 // Need to support trailing type qualifiers (e.g. "id<p> const"). 3760 // If a type specifier follows, it will be diagnosed elsewhere. 3761 continue; 3762 } 3763 // If the specifier wasn't legal, issue a diagnostic. 3764 if (isInvalid) { 3765 assert(PrevSpec && "Method did not return previous specifier!"); 3766 assert(DiagID); 3767 3768 if (DiagID == diag::ext_duplicate_declspec) 3769 Diag(Tok, DiagID) 3770 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation()); 3771 else if (DiagID == diag::err_opencl_unknown_type_specifier) { 3772 const int OpenCLVer = getLangOpts().OpenCLVersion; 3773 std::string VerSpec = llvm::to_string(OpenCLVer / 100) + 3774 std::string (".") + 3775 llvm::to_string((OpenCLVer % 100) / 10); 3776 Diag(Tok, DiagID) << VerSpec << PrevSpec << isStorageClass; 3777 } else 3778 Diag(Tok, DiagID) << PrevSpec; 3779 } 3780 3781 DS.SetRangeEnd(Tok.getLocation()); 3782 if (DiagID != diag::err_bool_redeclaration) 3783 ConsumeToken(); 3784 3785 AttrsLastTime = false; 3786 } 3787} 3788 3789/// ParseStructDeclaration - Parse a struct declaration without the terminating 3790/// semicolon. 3791/// 3792/// struct-declaration: 3793/// [C2x] attributes-specifier-seq[opt] 3794/// specifier-qualifier-list struct-declarator-list 3795/// [GNU] __extension__ struct-declaration 3796/// [GNU] specifier-qualifier-list 3797/// struct-declarator-list: 3798/// struct-declarator 3799/// struct-declarator-list ',' struct-declarator 3800/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator 3801/// struct-declarator: 3802/// declarator 3803/// [GNU] declarator attributes[opt] 3804/// declarator[opt] ':' constant-expression 3805/// [GNU] declarator[opt] ':' constant-expression attributes[opt] 3806/// 3807void Parser::ParseStructDeclaration( 3808 ParsingDeclSpec &DS, 3809 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) { 3810 3811 if (Tok.is(tok::kw___extension__)) { 3812 // __extension__ silences extension warnings in the subexpression. 3813 ExtensionRAIIObject O(Diags); // Use RAII to do this. 3814 ConsumeToken(); 3815 return ParseStructDeclaration(DS, FieldsCallback); 3816 } 3817 3818 // Parse leading attributes. 3819 ParsedAttributesWithRange Attrs(AttrFactory); 3820 MaybeParseCXX11Attributes(Attrs); 3821 DS.takeAttributesFrom(Attrs); 3822 3823 // Parse the common specifier-qualifiers-list piece. 3824 ParseSpecifierQualifierList(DS); 3825 3826 // If there are no declarators, this is a free-standing declaration 3827 // specifier. Let the actions module cope with it. 3828 if (Tok.is(tok::semi)) { 3829 RecordDecl *AnonRecord = nullptr; 3830 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, 3831 DS, AnonRecord); 3832 assert(!AnonRecord && "Did not expect anonymous struct or union here"); 3833 DS.complete(TheDecl); 3834 return; 3835 } 3836 3837 // Read struct-declarators until we find the semicolon. 3838 bool FirstDeclarator = true; 3839 SourceLocation CommaLoc; 3840 while (1) { 3841 ParsingFieldDeclarator DeclaratorInfo(*this, DS); 3842 DeclaratorInfo.D.setCommaLoc(CommaLoc); 3843 3844 // Attributes are only allowed here on successive declarators. 3845 if (!FirstDeclarator) 3846 MaybeParseGNUAttributes(DeclaratorInfo.D); 3847 3848 /// struct-declarator: declarator 3849 /// struct-declarator: declarator[opt] ':' constant-expression 3850 if (Tok.isNot(tok::colon)) { 3851 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 3852 ColonProtectionRAIIObject X(*this); 3853 ParseDeclarator(DeclaratorInfo.D); 3854 } else 3855 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation()); 3856 3857 if (TryConsumeToken(tok::colon)) { 3858 ExprResult Res(ParseConstantExpression()); 3859 if (Res.isInvalid()) 3860 SkipUntil(tok::semi, StopBeforeMatch); 3861 else 3862 DeclaratorInfo.BitfieldSize = Res.get(); 3863 } 3864 3865 // If attributes exist after the declarator, parse them. 3866 MaybeParseGNUAttributes(DeclaratorInfo.D); 3867 3868 // We're done with this declarator; invoke the callback. 3869 FieldsCallback(DeclaratorInfo); 3870 3871 // If we don't have a comma, it is either the end of the list (a ';') 3872 // or an error, bail out. 3873 if (!TryConsumeToken(tok::comma, CommaLoc)) 3874 return; 3875 3876 FirstDeclarator = false; 3877 } 3878} 3879 3880/// ParseStructUnionBody 3881/// struct-contents: 3882/// struct-declaration-list 3883/// [EXT] empty 3884/// [GNU] "struct-declaration-list" without terminatoring ';' 3885/// struct-declaration-list: 3886/// struct-declaration 3887/// struct-declaration-list struct-declaration 3888/// [OBC] '@' 'defs' '(' class-name ')' 3889/// 3890void Parser::ParseStructUnionBody(SourceLocation RecordLoc, 3891 unsigned TagType, Decl *TagDecl) { 3892 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 3893 "parsing struct/union body"); 3894 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported"); 3895 3896 BalancedDelimiterTracker T(*this, tok::l_brace); 3897 if (T.consumeOpen()) 3898 return; 3899 3900 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); 3901 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 3902 3903 SmallVector<Decl *, 32> FieldDecls; 3904 3905 // While we still have something to read, read the declarations in the struct. 3906 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) && 3907 Tok.isNot(tok::eof)) { 3908 // Each iteration of this loop reads one struct-declaration. 3909 3910 // Check for extraneous top-level semicolon. 3911 if (Tok.is(tok::semi)) { 3912 ConsumeExtraSemi(InsideStruct, TagType); 3913 continue; 3914 } 3915 3916 // Parse _Static_assert declaration. 3917 if (Tok.is(tok::kw__Static_assert)) { 3918 SourceLocation DeclEnd; 3919 ParseStaticAssertDeclaration(DeclEnd); 3920 continue; 3921 } 3922 3923 if (Tok.is(tok::annot_pragma_pack)) { 3924 HandlePragmaPack(); 3925 continue; 3926 } 3927 3928 if (Tok.is(tok::annot_pragma_align)) { 3929 HandlePragmaAlign(); 3930 continue; 3931 } 3932 3933 if (Tok.is(tok::annot_pragma_openmp)) { 3934 // Result can be ignored, because it must be always empty. 3935 AccessSpecifier AS = AS_none; 3936 ParsedAttributesWithRange Attrs(AttrFactory); 3937 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs); 3938 continue; 3939 } 3940 3941 if (!Tok.is(tok::at)) { 3942 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) { 3943 // Install the declarator into the current TagDecl. 3944 Decl *Field = 3945 Actions.ActOnField(getCurScope(), TagDecl, 3946 FD.D.getDeclSpec().getSourceRange().getBegin(), 3947 FD.D, FD.BitfieldSize); 3948 FieldDecls.push_back(Field); 3949 FD.complete(Field); 3950 }; 3951 3952 // Parse all the comma separated declarators. 3953 ParsingDeclSpec DS(*this); 3954 ParseStructDeclaration(DS, CFieldCallback); 3955 } else { // Handle @defs 3956 ConsumeToken(); 3957 if (!Tok.isObjCAtKeyword(tok::objc_defs)) { 3958 Diag(Tok, diag::err_unexpected_at); 3959 SkipUntil(tok::semi); 3960 continue; 3961 } 3962 ConsumeToken(); 3963 ExpectAndConsume(tok::l_paren); 3964 if (!Tok.is(tok::identifier)) { 3965 Diag(Tok, diag::err_expected) << tok::identifier; 3966 SkipUntil(tok::semi); 3967 continue; 3968 } 3969 SmallVector<Decl *, 16> Fields; 3970 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(), 3971 Tok.getIdentifierInfo(), Fields); 3972 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); 3973 ConsumeToken(); 3974 ExpectAndConsume(tok::r_paren); 3975 } 3976 3977 if (TryConsumeToken(tok::semi)) 3978 continue; 3979 3980 if (Tok.is(tok::r_brace)) { 3981 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list); 3982 break; 3983 } 3984 3985 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); 3986 // Skip to end of block or statement to avoid ext-warning on extra ';'. 3987 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 3988 // If we stopped at a ';', eat it. 3989 TryConsumeToken(tok::semi); 3990 } 3991 3992 T.consumeClose(); 3993 3994 ParsedAttributes attrs(AttrFactory); 3995 // If attributes exist after struct contents, parse them. 3996 MaybeParseGNUAttributes(attrs); 3997 3998 Actions.ActOnFields(getCurScope(), 3999 RecordLoc, TagDecl, FieldDecls, 4000 T.getOpenLocation(), T.getCloseLocation(), 4001 attrs.getList()); 4002 StructScope.Exit(); 4003 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange()); 4004} 4005 4006/// ParseEnumSpecifier 4007/// enum-specifier: [C99 6.7.2.2] 4008/// 'enum' identifier[opt] '{' enumerator-list '}' 4009///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' 4010/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] 4011/// '}' attributes[opt] 4012/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt] 4013/// '}' 4014/// 'enum' identifier 4015/// [GNU] 'enum' attributes[opt] identifier 4016/// 4017/// [C++11] enum-head '{' enumerator-list[opt] '}' 4018/// [C++11] enum-head '{' enumerator-list ',' '}' 4019/// 4020/// enum-head: [C++11] 4021/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt] 4022/// enum-key attribute-specifier-seq[opt] nested-name-specifier 4023/// identifier enum-base[opt] 4024/// 4025/// enum-key: [C++11] 4026/// 'enum' 4027/// 'enum' 'class' 4028/// 'enum' 'struct' 4029/// 4030/// enum-base: [C++11] 4031/// ':' type-specifier-seq 4032/// 4033/// [C++] elaborated-type-specifier: 4034/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier 4035/// 4036void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, 4037 const ParsedTemplateInfo &TemplateInfo, 4038 AccessSpecifier AS, DeclSpecContext DSC) { 4039 // Parse the tag portion of this. 4040 if (Tok.is(tok::code_completion)) { 4041 // Code completion for an enum name. 4042 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum); 4043 return cutOffParsing(); 4044 } 4045 4046 // If attributes exist after tag, parse them. 4047 ParsedAttributesWithRange attrs(AttrFactory); 4048 MaybeParseGNUAttributes(attrs); 4049 MaybeParseCXX11Attributes(attrs); 4050 MaybeParseMicrosoftDeclSpecs(attrs); 4051 4052 SourceLocation ScopedEnumKWLoc; 4053 bool IsScopedUsingClassTag = false; 4054 4055 // In C++11, recognize 'enum class' and 'enum struct'. 4056 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) { 4057 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum 4058 : diag::ext_scoped_enum); 4059 IsScopedUsingClassTag = Tok.is(tok::kw_class); 4060 ScopedEnumKWLoc = ConsumeToken(); 4061 4062 // Attributes are not allowed between these keywords. Diagnose, 4063 // but then just treat them like they appeared in the right place. 4064 ProhibitAttributes(attrs); 4065 4066 // They are allowed afterwards, though. 4067 MaybeParseGNUAttributes(attrs); 4068 MaybeParseCXX11Attributes(attrs); 4069 MaybeParseMicrosoftDeclSpecs(attrs); 4070 } 4071 4072 // C++11 [temp.explicit]p12: 4073 // The usual access controls do not apply to names used to specify 4074 // explicit instantiations. 4075 // We extend this to also cover explicit specializations. Note that 4076 // we don't suppress if this turns out to be an elaborated type 4077 // specifier. 4078 bool shouldDelayDiagsInTag = 4079 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation || 4080 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization); 4081 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag); 4082 4083 // Enum definitions should not be parsed in a trailing-return-type. 4084 bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing; 4085 4086 bool AllowFixedUnderlyingType = AllowDeclaration && 4087 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt || 4088 getLangOpts().ObjC2); 4089 4090 CXXScopeSpec &SS = DS.getTypeSpecScope(); 4091 if (getLangOpts().CPlusPlus) { 4092 // "enum foo : bar;" is not a potential typo for "enum foo::bar;" 4093 // if a fixed underlying type is allowed. 4094 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType); 4095 4096 CXXScopeSpec Spec; 4097 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, 4098 /*EnteringContext=*/true)) 4099 return; 4100 4101 if (Spec.isSet() && Tok.isNot(tok::identifier)) { 4102 Diag(Tok, diag::err_expected) << tok::identifier; 4103 if (Tok.isNot(tok::l_brace)) { 4104 // Has no name and is not a definition. 4105 // Skip the rest of this declarator, up until the comma or semicolon. 4106 SkipUntil(tok::comma, StopAtSemi); 4107 return; 4108 } 4109 } 4110 4111 SS = Spec; 4112 } 4113 4114 // Must have either 'enum name' or 'enum {...}'. 4115 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) && 4116 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) { 4117 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace; 4118 4119 // Skip the rest of this declarator, up until the comma or semicolon. 4120 SkipUntil(tok::comma, StopAtSemi); 4121 return; 4122 } 4123 4124 // If an identifier is present, consume and remember it. 4125 IdentifierInfo *Name = nullptr; 4126 SourceLocation NameLoc; 4127 if (Tok.is(tok::identifier)) { 4128 Name = Tok.getIdentifierInfo(); 4129 NameLoc = ConsumeToken(); 4130 } 4131 4132 if (!Name && ScopedEnumKWLoc.isValid()) { 4133 // C++0x 7.2p2: The optional identifier shall not be omitted in the 4134 // declaration of a scoped enumeration. 4135 Diag(Tok, diag::err_scoped_enum_missing_identifier); 4136 ScopedEnumKWLoc = SourceLocation(); 4137 IsScopedUsingClassTag = false; 4138 } 4139 4140 // Okay, end the suppression area. We'll decide whether to emit the 4141 // diagnostics in a second. 4142 if (shouldDelayDiagsInTag) 4143 diagsFromTag.done(); 4144 4145 TypeResult BaseType; 4146 4147 // Parse the fixed underlying type. 4148 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope; 4149 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) { 4150 bool PossibleBitfield = false; 4151 if (CanBeBitfield) { 4152 // If we're in class scope, this can either be an enum declaration with 4153 // an underlying type, or a declaration of a bitfield member. We try to 4154 // use a simple disambiguation scheme first to catch the common cases 4155 // (integer literal, sizeof); if it's still ambiguous, we then consider 4156 // anything that's a simple-type-specifier followed by '(' as an 4157 // expression. This suffices because function types are not valid 4158 // underlying types anyway. 4159 EnterExpressionEvaluationContext Unevaluated( 4160 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated); 4161 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind()); 4162 // If the next token starts an expression, we know we're parsing a 4163 // bit-field. This is the common case. 4164 if (TPR == TPResult::True) 4165 PossibleBitfield = true; 4166 // If the next token starts a type-specifier-seq, it may be either a 4167 // a fixed underlying type or the start of a function-style cast in C++; 4168 // lookahead one more token to see if it's obvious that we have a 4169 // fixed underlying type. 4170 else if (TPR == TPResult::False && 4171 GetLookAheadToken(2).getKind() == tok::semi) { 4172 // Consume the ':'. 4173 ConsumeToken(); 4174 } else { 4175 // We have the start of a type-specifier-seq, so we have to perform 4176 // tentative parsing to determine whether we have an expression or a 4177 // type. 4178 TentativeParsingAction TPA(*this); 4179 4180 // Consume the ':'. 4181 ConsumeToken(); 4182 4183 // If we see a type specifier followed by an open-brace, we have an 4184 // ambiguity between an underlying type and a C++11 braced 4185 // function-style cast. Resolve this by always treating it as an 4186 // underlying type. 4187 // FIXME: The standard is not entirely clear on how to disambiguate in 4188 // this case. 4189 if ((getLangOpts().CPlusPlus && 4190 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) || 4191 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) { 4192 // We'll parse this as a bitfield later. 4193 PossibleBitfield = true; 4194 TPA.Revert(); 4195 } else { 4196 // We have a type-specifier-seq. 4197 TPA.Commit(); 4198 } 4199 } 4200 } else { 4201 // Consume the ':'. 4202 ConsumeToken(); 4203 } 4204 4205 if (!PossibleBitfield) { 4206 SourceRange Range; 4207 BaseType = ParseTypeName(&Range); 4208 4209 if (getLangOpts().CPlusPlus11) { 4210 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type); 4211 } else if (!getLangOpts().ObjC2) { 4212 if (getLangOpts().CPlusPlus) 4213 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range; 4214 else 4215 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range; 4216 } 4217 } 4218 } 4219 4220 // There are four options here. If we have 'friend enum foo;' then this is a 4221 // friend declaration, and cannot have an accompanying definition. If we have 4222 // 'enum foo;', then this is a forward declaration. If we have 4223 // 'enum foo {...' then this is a definition. Otherwise we have something 4224 // like 'enum foo xyz', a reference. 4225 // 4226 // This is needed to handle stuff like this right (C99 6.7.2.3p11): 4227 // enum foo {..}; void bar() { enum foo; } <- new foo in bar. 4228 // enum foo {..}; void bar() { enum foo x; } <- use of old foo. 4229 // 4230 Sema::TagUseKind TUK; 4231 if (!AllowDeclaration) { 4232 TUK = Sema::TUK_Reference; 4233 } else if (Tok.is(tok::l_brace)) { 4234 if (DS.isFriendSpecified()) { 4235 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type) 4236 << SourceRange(DS.getFriendSpecLoc()); 4237 ConsumeBrace(); 4238 SkipUntil(tok::r_brace, StopAtSemi); 4239 TUK = Sema::TUK_Friend; 4240 } else { 4241 TUK = Sema::TUK_Definition; 4242 } 4243 } else if (!isTypeSpecifier(DSC) && 4244 (Tok.is(tok::semi) || 4245 (Tok.isAtStartOfLine() && 4246 !isValidAfterTypeSpecifier(CanBeBitfield)))) { 4247 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration; 4248 if (Tok.isNot(tok::semi)) { 4249 // A semicolon was missing after this declaration. Diagnose and recover. 4250 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum"); 4251 PP.EnterToken(Tok); 4252 Tok.setKind(tok::semi); 4253 } 4254 } else { 4255 TUK = Sema::TUK_Reference; 4256 } 4257 4258 // If this is an elaborated type specifier, and we delayed 4259 // diagnostics before, just merge them into the current pool. 4260 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) { 4261 diagsFromTag.redelay(); 4262 } 4263 4264 MultiTemplateParamsArg TParams; 4265 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 4266 TUK != Sema::TUK_Reference) { 4267 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) { 4268 // Skip the rest of this declarator, up until the comma or semicolon. 4269 Diag(Tok, diag::err_enum_template); 4270 SkipUntil(tok::comma, StopAtSemi); 4271 return; 4272 } 4273 4274 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { 4275 // Enumerations can't be explicitly instantiated. 4276 DS.SetTypeSpecError(); 4277 Diag(StartLoc, diag::err_explicit_instantiation_enum); 4278 return; 4279 } 4280 4281 assert(TemplateInfo.TemplateParams && "no template parameters"); 4282 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(), 4283 TemplateInfo.TemplateParams->size()); 4284 } 4285 4286 if (TUK == Sema::TUK_Reference) 4287 ProhibitAttributes(attrs); 4288 4289 if (!Name && TUK != Sema::TUK_Definition) { 4290 Diag(Tok, diag::err_enumerator_unnamed_no_def); 4291 4292 // Skip the rest of this declarator, up until the comma or semicolon. 4293 SkipUntil(tok::comma, StopAtSemi); 4294 return; 4295 } 4296 4297 stripTypeAttributesOffDeclSpec(attrs, DS, TUK); 4298 4299 Sema::SkipBodyInfo SkipBody; 4300 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) && 4301 NextToken().is(tok::identifier)) 4302 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(), 4303 NextToken().getIdentifierInfo(), 4304 NextToken().getLocation()); 4305 4306 bool Owned = false; 4307 bool IsDependent = false; 4308 const char *PrevSpec = nullptr; 4309 unsigned DiagID; 4310 Decl *TagDecl = Actions.ActOnTag( 4311 getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc, 4312 attrs.getList(), AS, DS.getModulePrivateSpecLoc(), TParams, Owned, 4313 IsDependent, ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType, 4314 DSC == DeclSpecContext::DSC_type_specifier, 4315 DSC == DeclSpecContext::DSC_template_param || 4316 DSC == DeclSpecContext::DSC_template_type_arg, 4317 &SkipBody); 4318 4319 if (SkipBody.ShouldSkip) { 4320 assert(TUK == Sema::TUK_Definition && "can only skip a definition"); 4321 4322 BalancedDelimiterTracker T(*this, tok::l_brace); 4323 T.consumeOpen(); 4324 T.skipToEnd(); 4325 4326 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, 4327 NameLoc.isValid() ? NameLoc : StartLoc, 4328 PrevSpec, DiagID, TagDecl, Owned, 4329 Actions.getASTContext().getPrintingPolicy())) 4330 Diag(StartLoc, DiagID) << PrevSpec; 4331 return; 4332 } 4333 4334 if (IsDependent) { 4335 // This enum has a dependent nested-name-specifier. Handle it as a 4336 // dependent tag. 4337 if (!Name) { 4338 DS.SetTypeSpecError(); 4339 Diag(Tok, diag::err_expected_type_name_after_typename); 4340 return; 4341 } 4342 4343 TypeResult Type = Actions.ActOnDependentTag( 4344 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc); 4345 if (Type.isInvalid()) { 4346 DS.SetTypeSpecError(); 4347 return; 4348 } 4349 4350 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, 4351 NameLoc.isValid() ? NameLoc : StartLoc, 4352 PrevSpec, DiagID, Type.get(), 4353 Actions.getASTContext().getPrintingPolicy())) 4354 Diag(StartLoc, DiagID) << PrevSpec; 4355 4356 return; 4357 } 4358 4359 if (!TagDecl) { 4360 // The action failed to produce an enumeration tag. If this is a 4361 // definition, consume the entire definition. 4362 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) { 4363 ConsumeBrace(); 4364 SkipUntil(tok::r_brace, StopAtSemi); 4365 } 4366 4367 DS.SetTypeSpecError(); 4368 return; 4369 } 4370 4371 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) { 4372 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl; 4373 ParseEnumBody(StartLoc, D); 4374 if (SkipBody.CheckSameAsPrevious && 4375 !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) { 4376 DS.SetTypeSpecError(); 4377 return; 4378 } 4379 } 4380 4381 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, 4382 NameLoc.isValid() ? NameLoc : StartLoc, 4383 PrevSpec, DiagID, TagDecl, Owned, 4384 Actions.getASTContext().getPrintingPolicy())) 4385 Diag(StartLoc, DiagID) << PrevSpec; 4386} 4387 4388/// ParseEnumBody - Parse a {} enclosed enumerator-list. 4389/// enumerator-list: 4390/// enumerator 4391/// enumerator-list ',' enumerator 4392/// enumerator: 4393/// enumeration-constant attributes[opt] 4394/// enumeration-constant attributes[opt] '=' constant-expression 4395/// enumeration-constant: 4396/// identifier 4397/// 4398void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) { 4399 // Enter the scope of the enum body and start the definition. 4400 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope); 4401 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl); 4402 4403 BalancedDelimiterTracker T(*this, tok::l_brace); 4404 T.consumeOpen(); 4405 4406 // C does not allow an empty enumerator-list, C++ does [dcl.enum]. 4407 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) 4408 Diag(Tok, diag::err_empty_enum); 4409 4410 SmallVector<Decl *, 32> EnumConstantDecls; 4411 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags; 4412 4413 Decl *LastEnumConstDecl = nullptr; 4414 4415 // Parse the enumerator-list. 4416 while (Tok.isNot(tok::r_brace)) { 4417 // Parse enumerator. If failed, try skipping till the start of the next 4418 // enumerator definition. 4419 if (Tok.isNot(tok::identifier)) { 4420 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; 4421 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) && 4422 TryConsumeToken(tok::comma)) 4423 continue; 4424 break; 4425 } 4426 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 4427 SourceLocation IdentLoc = ConsumeToken(); 4428 4429 // If attributes exist after the enumerator, parse them. 4430 ParsedAttributesWithRange attrs(AttrFactory); 4431 MaybeParseGNUAttributes(attrs); 4432 ProhibitAttributes(attrs); // GNU-style attributes are prohibited. 4433 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { 4434 if (getLangOpts().CPlusPlus) 4435 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 4436 ? diag::warn_cxx14_compat_ns_enum_attribute 4437 : diag::ext_ns_enum_attribute) 4438 << 1 /*enumerator*/; 4439 ParseCXX11Attributes(attrs); 4440 } 4441 4442 SourceLocation EqualLoc; 4443 ExprResult AssignedVal; 4444 EnumAvailabilityDiags.emplace_back(*this); 4445 4446 if (TryConsumeToken(tok::equal, EqualLoc)) { 4447 AssignedVal = ParseConstantExpression(); 4448 if (AssignedVal.isInvalid()) 4449 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch); 4450 } 4451 4452 // Install the enumerator constant into EnumDecl. 4453 Decl *EnumConstDecl = Actions.ActOnEnumConstant( 4454 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, 4455 attrs.getList(), EqualLoc, AssignedVal.get()); 4456 EnumAvailabilityDiags.back().done(); 4457 4458 EnumConstantDecls.push_back(EnumConstDecl); 4459 LastEnumConstDecl = EnumConstDecl; 4460 4461 if (Tok.is(tok::identifier)) { 4462 // We're missing a comma between enumerators. 4463 SourceLocation Loc = getEndOfPreviousToken(); 4464 Diag(Loc, diag::err_enumerator_list_missing_comma) 4465 << FixItHint::CreateInsertion(Loc, ", "); 4466 continue; 4467 } 4468 4469 // Emumerator definition must be finished, only comma or r_brace are 4470 // allowed here. 4471 SourceLocation CommaLoc; 4472 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) { 4473 if (EqualLoc.isValid()) 4474 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace 4475 << tok::comma; 4476 else 4477 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator); 4478 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) { 4479 if (TryConsumeToken(tok::comma, CommaLoc)) 4480 continue; 4481 } else { 4482 break; 4483 } 4484 } 4485 4486 // If comma is followed by r_brace, emit appropriate warning. 4487 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) { 4488 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) 4489 Diag(CommaLoc, getLangOpts().CPlusPlus ? 4490 diag::ext_enumerator_list_comma_cxx : 4491 diag::ext_enumerator_list_comma_c) 4492 << FixItHint::CreateRemoval(CommaLoc); 4493 else if (getLangOpts().CPlusPlus11) 4494 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma) 4495 << FixItHint::CreateRemoval(CommaLoc); 4496 break; 4497 } 4498 } 4499 4500 // Eat the }. 4501 T.consumeClose(); 4502 4503 // If attributes exist after the identifier list, parse them. 4504 ParsedAttributes attrs(AttrFactory); 4505 MaybeParseGNUAttributes(attrs); 4506 4507 Actions.ActOnEnumBody(StartLoc, T.getRange(), 4508 EnumDecl, EnumConstantDecls, 4509 getCurScope(), 4510 attrs.getList()); 4511 4512 // Now handle enum constant availability diagnostics. 4513 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size()); 4514 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) { 4515 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent); 4516 EnumAvailabilityDiags[i].redelay(); 4517 PD.complete(EnumConstantDecls[i]); 4518 } 4519 4520 EnumScope.Exit(); 4521 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange()); 4522 4523 // The next token must be valid after an enum definition. If not, a ';' 4524 // was probably forgotten. 4525 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope; 4526 if (!isValidAfterTypeSpecifier(CanBeBitfield)) { 4527 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum"); 4528 // Push this token back into the preprocessor and change our current token 4529 // to ';' so that the rest of the code recovers as though there were an 4530 // ';' after the definition. 4531 PP.EnterToken(Tok); 4532 Tok.setKind(tok::semi); 4533 } 4534} 4535 4536/// isKnownToBeTypeSpecifier - Return true if we know that the specified token 4537/// is definitely a type-specifier. Return false if it isn't part of a type 4538/// specifier or if we're not sure. 4539bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const { 4540 switch (Tok.getKind()) { 4541 default: return false; 4542 // type-specifiers 4543 case tok::kw_short: 4544 case tok::kw_long: 4545 case tok::kw___int64: 4546 case tok::kw___int128: 4547 case tok::kw_signed: 4548 case tok::kw_unsigned: 4549 case tok::kw__Complex: 4550 case tok::kw__Imaginary: 4551 case tok::kw_void: 4552 case tok::kw_char: 4553 case tok::kw_wchar_t: 4554 case tok::kw_char16_t: 4555 case tok::kw_char32_t: 4556 case tok::kw_int: 4557 case tok::kw_half: 4558 case tok::kw_float: 4559 case tok::kw_double: 4560 case tok::kw__Float16: 4561 case tok::kw___float128: 4562 case tok::kw_bool: 4563 case tok::kw__Bool: 4564 case tok::kw__Decimal32: 4565 case tok::kw__Decimal64: 4566 case tok::kw__Decimal128: 4567 case tok::kw___vector: 4568#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t: 4569#include "clang/Basic/OpenCLImageTypes.def" 4570 4571 // struct-or-union-specifier (C99) or class-specifier (C++) 4572 case tok::kw_class: 4573 case tok::kw_struct: 4574 case tok::kw___interface: 4575 case tok::kw_union: 4576 // enum-specifier 4577 case tok::kw_enum: 4578 4579 // typedef-name 4580 case tok::annot_typename: 4581 return true; 4582 } 4583} 4584 4585/// isTypeSpecifierQualifier - Return true if the current token could be the 4586/// start of a specifier-qualifier-list. 4587bool Parser::isTypeSpecifierQualifier() { 4588 switch (Tok.getKind()) { 4589 default: return false; 4590 4591 case tok::identifier: // foo::bar 4592 if (TryAltiVecVectorToken()) 4593 return true; 4594 // Fall through. 4595 case tok::kw_typename: // typename T::type 4596 // Annotate typenames and C++ scope specifiers. If we get one, just 4597 // recurse to handle whatever we get. 4598 if (TryAnnotateTypeOrScopeToken()) 4599 return true; 4600 if (Tok.is(tok::identifier)) 4601 return false; 4602 return isTypeSpecifierQualifier(); 4603 4604 case tok::coloncolon: // ::foo::bar 4605 if (NextToken().is(tok::kw_new) || // ::new 4606 NextToken().is(tok::kw_delete)) // ::delete 4607 return false; 4608 4609 if (TryAnnotateTypeOrScopeToken()) 4610 return true; 4611 return isTypeSpecifierQualifier(); 4612 4613 // GNU attributes support. 4614 case tok::kw___attribute: 4615 // GNU typeof support. 4616 case tok::kw_typeof: 4617 4618 // type-specifiers 4619 case tok::kw_short: 4620 case tok::kw_long: 4621 case tok::kw___int64: 4622 case tok::kw___int128: 4623 case tok::kw_signed: 4624 case tok::kw_unsigned: 4625 case tok::kw__Complex: 4626 case tok::kw__Imaginary: 4627 case tok::kw_void: 4628 case tok::kw_char: 4629 case tok::kw_wchar_t: 4630 case tok::kw_char16_t: 4631 case tok::kw_char32_t: 4632 case tok::kw_int: 4633 case tok::kw_half: 4634 case tok::kw_float: 4635 case tok::kw_double: 4636 case tok::kw__Float16: 4637 case tok::kw___float128: 4638 case tok::kw_bool: 4639 case tok::kw__Bool: 4640 case tok::kw__Decimal32: 4641 case tok::kw__Decimal64: 4642 case tok::kw__Decimal128: 4643 case tok::kw___vector: 4644#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t: 4645#include "clang/Basic/OpenCLImageTypes.def" 4646 4647 // struct-or-union-specifier (C99) or class-specifier (C++) 4648 case tok::kw_class: 4649 case tok::kw_struct: 4650 case tok::kw___interface: 4651 case tok::kw_union: 4652 // enum-specifier 4653 case tok::kw_enum: 4654 4655 // type-qualifier 4656 case tok::kw_const: 4657 case tok::kw_volatile: 4658 case tok::kw_restrict: 4659 4660 // Debugger support. 4661 case tok::kw___unknown_anytype: 4662 4663 // typedef-name 4664 case tok::annot_typename: 4665 return true; 4666 4667 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 4668 case tok::less: 4669 return getLangOpts().ObjC1; 4670 4671 case tok::kw___cdecl: 4672 case tok::kw___stdcall: 4673 case tok::kw___fastcall: 4674 case tok::kw___thiscall: 4675 case tok::kw___regcall: 4676 case tok::kw___vectorcall: 4677 case tok::kw___w64: 4678 case tok::kw___ptr64: 4679 case tok::kw___ptr32: 4680 case tok::kw___pascal: 4681 case tok::kw___unaligned: 4682 4683 case tok::kw__Nonnull: 4684 case tok::kw__Nullable: 4685 case tok::kw__Null_unspecified: 4686 4687 case tok::kw___kindof: 4688 4689 case tok::kw___private: 4690 case tok::kw___local: 4691 case tok::kw___global: 4692 case tok::kw___constant: 4693 case tok::kw___generic: 4694 case tok::kw___read_only: 4695 case tok::kw___read_write: 4696 case tok::kw___write_only: 4697 4698 return true; 4699 4700 // C11 _Atomic 4701 case tok::kw__Atomic: 4702 return true; 4703 } 4704} 4705 4706/// isDeclarationSpecifier() - Return true if the current token is part of a 4707/// declaration specifier. 4708/// 4709/// \param DisambiguatingWithExpression True to indicate that the purpose of 4710/// this check is to disambiguate between an expression and a declaration. 4711bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) { 4712 switch (Tok.getKind()) { 4713 default: return false; 4714 4715 case tok::kw_pipe: 4716 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200); 4717 4718 case tok::identifier: // foo::bar 4719 // Unfortunate hack to support "Class.factoryMethod" notation. 4720 if (getLangOpts().ObjC1 && NextToken().is(tok::period)) 4721 return false; 4722 if (TryAltiVecVectorToken()) 4723 return true; 4724 // Fall through. 4725 case tok::kw_decltype: // decltype(T())::type 4726 case tok::kw_typename: // typename T::type 4727 // Annotate typenames and C++ scope specifiers. If we get one, just 4728 // recurse to handle whatever we get. 4729 if (TryAnnotateTypeOrScopeToken()) 4730 return true; 4731 if (Tok.is(tok::identifier)) 4732 return false; 4733 4734 // If we're in Objective-C and we have an Objective-C class type followed 4735 // by an identifier and then either ':' or ']', in a place where an 4736 // expression is permitted, then this is probably a class message send 4737 // missing the initial '['. In this case, we won't consider this to be 4738 // the start of a declaration. 4739 if (DisambiguatingWithExpression && 4740 isStartOfObjCClassMessageMissingOpenBracket()) 4741 return false; 4742 4743 return isDeclarationSpecifier(); 4744 4745 case tok::coloncolon: // ::foo::bar 4746 if (NextToken().is(tok::kw_new) || // ::new 4747 NextToken().is(tok::kw_delete)) // ::delete 4748 return false; 4749 4750 // Annotate typenames and C++ scope specifiers. If we get one, just 4751 // recurse to handle whatever we get. 4752 if (TryAnnotateTypeOrScopeToken()) 4753 return true; 4754 return isDeclarationSpecifier(); 4755 4756 // storage-class-specifier 4757 case tok::kw_typedef: 4758 case tok::kw_extern: 4759 case tok::kw___private_extern__: 4760 case tok::kw_static: 4761 case tok::kw_auto: 4762 case tok::kw___auto_type: 4763 case tok::kw_register: 4764 case tok::kw___thread: 4765 case tok::kw_thread_local: 4766 case tok::kw__Thread_local: 4767 4768 // Modules 4769 case tok::kw___module_private__: 4770 4771 // Debugger support 4772 case tok::kw___unknown_anytype: 4773 4774 // type-specifiers 4775 case tok::kw_short: 4776 case tok::kw_long: 4777 case tok::kw___int64: 4778 case tok::kw___int128: 4779 case tok::kw_signed: 4780 case tok::kw_unsigned: 4781 case tok::kw__Complex: 4782 case tok::kw__Imaginary: 4783 case tok::kw_void: 4784 case tok::kw_char: 4785 case tok::kw_wchar_t: 4786 case tok::kw_char16_t: 4787 case tok::kw_char32_t: 4788 4789 case tok::kw_int: 4790 case tok::kw_half: 4791 case tok::kw_float: 4792 case tok::kw_double: 4793 case tok::kw__Float16: 4794 case tok::kw___float128: 4795 case tok::kw_bool: 4796 case tok::kw__Bool: 4797 case tok::kw__Decimal32: 4798 case tok::kw__Decimal64: 4799 case tok::kw__Decimal128: 4800 case tok::kw___vector: 4801 4802 // struct-or-union-specifier (C99) or class-specifier (C++) 4803 case tok::kw_class: 4804 case tok::kw_struct: 4805 case tok::kw_union: 4806 case tok::kw___interface: 4807 // enum-specifier 4808 case tok::kw_enum: 4809 4810 // type-qualifier 4811 case tok::kw_const: 4812 case tok::kw_volatile: 4813 case tok::kw_restrict: 4814 4815 // function-specifier 4816 case tok::kw_inline: 4817 case tok::kw_virtual: 4818 case tok::kw_explicit: 4819 case tok::kw__Noreturn: 4820 4821 // alignment-specifier 4822 case tok::kw__Alignas: 4823 4824 // friend keyword. 4825 case tok::kw_friend: 4826 4827 // static_assert-declaration 4828 case tok::kw__Static_assert: 4829 4830 // GNU typeof support. 4831 case tok::kw_typeof: 4832 4833 // GNU attributes. 4834 case tok::kw___attribute: 4835 4836 // C++11 decltype and constexpr. 4837 case tok::annot_decltype: 4838 case tok::kw_constexpr: 4839 4840 // C11 _Atomic 4841 case tok::kw__Atomic: 4842 return true; 4843 4844 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 4845 case tok::less: 4846 return getLangOpts().ObjC1; 4847 4848 // typedef-name 4849 case tok::annot_typename: 4850 return !DisambiguatingWithExpression || 4851 !isStartOfObjCClassMessageMissingOpenBracket(); 4852 4853 case tok::kw___declspec: 4854 case tok::kw___cdecl: 4855 case tok::kw___stdcall: 4856 case tok::kw___fastcall: 4857 case tok::kw___thiscall: 4858 case tok::kw___regcall: 4859 case tok::kw___vectorcall: 4860 case tok::kw___w64: 4861 case tok::kw___sptr: 4862 case tok::kw___uptr: 4863 case tok::kw___ptr64: 4864 case tok::kw___ptr32: 4865 case tok::kw___forceinline: 4866 case tok::kw___pascal: 4867 case tok::kw___unaligned: 4868 4869 case tok::kw__Nonnull: 4870 case tok::kw__Nullable: 4871 case tok::kw__Null_unspecified: 4872 4873 case tok::kw___kindof: 4874 4875 case tok::kw___private: 4876 case tok::kw___local: 4877 case tok::kw___global: 4878 case tok::kw___constant: 4879 case tok::kw___generic: 4880 case tok::kw___read_only: 4881 case tok::kw___read_write: 4882 case tok::kw___write_only: 4883#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t: 4884#include "clang/Basic/OpenCLImageTypes.def" 4885 4886 return true; 4887 } 4888} 4889 4890bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) { 4891 TentativeParsingAction TPA(*this); 4892 4893 // Parse the C++ scope specifier. 4894 CXXScopeSpec SS; 4895 if (ParseOptionalCXXScopeSpecifier(SS, nullptr, 4896 /*EnteringContext=*/true)) { 4897 TPA.Revert(); 4898 return false; 4899 } 4900 4901 // Parse the constructor name. 4902 if (Tok.is(tok::identifier)) { 4903 // We already know that we have a constructor name; just consume 4904 // the token. 4905 ConsumeToken(); 4906 } else if (Tok.is(tok::annot_template_id)) { 4907 ConsumeAnnotationToken(); 4908 } else { 4909 TPA.Revert(); 4910 return false; 4911 } 4912 4913 // There may be attributes here, appertaining to the constructor name or type 4914 // we just stepped past. 4915 SkipCXX11Attributes(); 4916 4917 // Current class name must be followed by a left parenthesis. 4918 if (Tok.isNot(tok::l_paren)) { 4919 TPA.Revert(); 4920 return false; 4921 } 4922 ConsumeParen(); 4923 4924 // A right parenthesis, or ellipsis followed by a right parenthesis signals 4925 // that we have a constructor. 4926 if (Tok.is(tok::r_paren) || 4927 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) { 4928 TPA.Revert(); 4929 return true; 4930 } 4931 4932 // A C++11 attribute here signals that we have a constructor, and is an 4933 // attribute on the first constructor parameter. 4934 if (getLangOpts().CPlusPlus11 && 4935 isCXX11AttributeSpecifier(/*Disambiguate*/ false, 4936 /*OuterMightBeMessageSend*/ true)) { 4937 TPA.Revert(); 4938 return true; 4939 } 4940 4941 // If we need to, enter the specified scope. 4942 DeclaratorScopeObj DeclScopeObj(*this, SS); 4943 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS)) 4944 DeclScopeObj.EnterDeclaratorScope(); 4945 4946 // Optionally skip Microsoft attributes. 4947 ParsedAttributes Attrs(AttrFactory); 4948 MaybeParseMicrosoftAttributes(Attrs); 4949 4950 // Check whether the next token(s) are part of a declaration 4951 // specifier, in which case we have the start of a parameter and, 4952 // therefore, we know that this is a constructor. 4953 bool IsConstructor = false; 4954 if (isDeclarationSpecifier()) 4955 IsConstructor = true; 4956 else if (Tok.is(tok::identifier) || 4957 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) { 4958 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type. 4959 // This might be a parenthesized member name, but is more likely to 4960 // be a constructor declaration with an invalid argument type. Keep 4961 // looking. 4962 if (Tok.is(tok::annot_cxxscope)) 4963 ConsumeAnnotationToken(); 4964 ConsumeToken(); 4965 4966 // If this is not a constructor, we must be parsing a declarator, 4967 // which must have one of the following syntactic forms (see the 4968 // grammar extract at the start of ParseDirectDeclarator): 4969 switch (Tok.getKind()) { 4970 case tok::l_paren: 4971 // C(X ( int)); 4972 case tok::l_square: 4973 // C(X [ 5]); 4974 // C(X [ [attribute]]); 4975 case tok::coloncolon: 4976 // C(X :: Y); 4977 // C(X :: *p); 4978 // Assume this isn't a constructor, rather than assuming it's a 4979 // constructor with an unnamed parameter of an ill-formed type. 4980 break; 4981 4982 case tok::r_paren: 4983 // C(X ) 4984 4985 // Skip past the right-paren and any following attributes to get to 4986 // the function body or trailing-return-type. 4987 ConsumeParen(); 4988 SkipCXX11Attributes(); 4989 4990 if (DeductionGuide) { 4991 // C(X) -> ... is a deduction guide. 4992 IsConstructor = Tok.is(tok::arrow); 4993 break; 4994 } 4995 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) { 4996 // Assume these were meant to be constructors: 4997 // C(X) : (the name of a bit-field cannot be parenthesized). 4998 // C(X) try (this is otherwise ill-formed). 4999 IsConstructor = true; 5000 } 5001 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) { 5002 // If we have a constructor name within the class definition, 5003 // assume these were meant to be constructors: 5004 // C(X) { 5005 // C(X) ; 5006 // ... because otherwise we would be declaring a non-static data 5007 // member that is ill-formed because it's of the same type as its 5008 // surrounding class. 5009 // 5010 // FIXME: We can actually do this whether or not the name is qualified, 5011 // because if it is qualified in this context it must be being used as 5012 // a constructor name. 5013 // currently, so we're somewhat conservative here. 5014 IsConstructor = IsUnqualified; 5015 } 5016 break; 5017 5018 default: 5019 IsConstructor = true; 5020 break; 5021 } 5022 } 5023 5024 TPA.Revert(); 5025 return IsConstructor; 5026} 5027 5028/// ParseTypeQualifierListOpt 5029/// type-qualifier-list: [C99 6.7.5] 5030/// type-qualifier 5031/// [vendor] attributes 5032/// [ only if AttrReqs & AR_VendorAttributesParsed ] 5033/// type-qualifier-list type-qualifier 5034/// [vendor] type-qualifier-list attributes 5035/// [ only if AttrReqs & AR_VendorAttributesParsed ] 5036/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq 5037/// [ only if AttReqs & AR_CXX11AttributesParsed ] 5038/// Note: vendor can be GNU, MS, etc and can be explicitly controlled via 5039/// AttrRequirements bitmask values. 5040void Parser::ParseTypeQualifierListOpt( 5041 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed, 5042 bool IdentifierRequired, 5043 Optional<llvm::function_ref<void()>> CodeCompletionHandler) { 5044 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) && 5045 isCXX11AttributeSpecifier()) { 5046 ParsedAttributesWithRange attrs(AttrFactory); 5047 ParseCXX11Attributes(attrs); 5048 DS.takeAttributesFrom(attrs); 5049 } 5050 5051 SourceLocation EndLoc; 5052 5053 while (1) { 5054 bool isInvalid = false; 5055 const char *PrevSpec = nullptr; 5056 unsigned DiagID = 0; 5057 SourceLocation Loc = Tok.getLocation(); 5058 5059 switch (Tok.getKind()) { 5060 case tok::code_completion: 5061 if (CodeCompletionHandler) 5062 (*CodeCompletionHandler)(); 5063 else 5064 Actions.CodeCompleteTypeQualifiers(DS); 5065 return cutOffParsing(); 5066 5067 case tok::kw_const: 5068 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID, 5069 getLangOpts()); 5070 break; 5071 case tok::kw_volatile: 5072 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 5073 getLangOpts()); 5074 break; 5075 case tok::kw_restrict: 5076 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 5077 getLangOpts()); 5078 break; 5079 case tok::kw__Atomic: 5080 if (!AtomicAllowed) 5081 goto DoneWithTypeQuals; 5082 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID, 5083 getLangOpts()); 5084 break; 5085 5086 // OpenCL qualifiers: 5087 case tok::kw___private: 5088 case tok::kw___global: 5089 case tok::kw___local: 5090 case tok::kw___constant: 5091 case tok::kw___generic: 5092 case tok::kw___read_only: 5093 case tok::kw___write_only: 5094 case tok::kw___read_write: 5095 ParseOpenCLQualifiers(DS.getAttributes()); 5096 break; 5097 5098 case tok::kw___unaligned: 5099 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID, 5100 getLangOpts()); 5101 break; 5102 case tok::kw___uptr: 5103 // GNU libc headers in C mode use '__uptr' as an identifer which conflicts 5104 // with the MS modifier keyword. 5105 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus && 5106 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) { 5107 if (TryKeywordIdentFallback(false)) 5108 continue; 5109 } 5110 LLVM_FALLTHROUGH; 5111 case tok::kw___sptr: 5112 case tok::kw___w64: 5113 case tok::kw___ptr64: 5114 case tok::kw___ptr32: 5115 case tok::kw___cdecl: 5116 case tok::kw___stdcall: 5117 case tok::kw___fastcall: 5118 case tok::kw___thiscall: 5119 case tok::kw___regcall: 5120 case tok::kw___vectorcall: 5121 if (AttrReqs & AR_DeclspecAttributesParsed) { 5122 ParseMicrosoftTypeAttributes(DS.getAttributes()); 5123 continue; 5124 } 5125 goto DoneWithTypeQuals; 5126 case tok::kw___pascal: 5127 if (AttrReqs & AR_VendorAttributesParsed) { 5128 ParseBorlandTypeAttributes(DS.getAttributes()); 5129 continue; 5130 } 5131 goto DoneWithTypeQuals; 5132 5133 // Nullability type specifiers. 5134 case tok::kw__Nonnull: 5135 case tok::kw__Nullable: 5136 case tok::kw__Null_unspecified: 5137 ParseNullabilityTypeSpecifiers(DS.getAttributes()); 5138 continue; 5139 5140 // Objective-C 'kindof' types. 5141 case tok::kw___kindof: 5142 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc, 5143 nullptr, 0, AttributeList::AS_Keyword); 5144 (void)ConsumeToken(); 5145 continue; 5146 5147 case tok::kw___attribute: 5148 if (AttrReqs & AR_GNUAttributesParsedAndRejected) 5149 // When GNU attributes are expressly forbidden, diagnose their usage. 5150 Diag(Tok, diag::err_attributes_not_allowed); 5151 5152 // Parse the attributes even if they are rejected to ensure that error 5153 // recovery is graceful. 5154 if (AttrReqs & AR_GNUAttributesParsed || 5155 AttrReqs & AR_GNUAttributesParsedAndRejected) { 5156 ParseGNUAttributes(DS.getAttributes()); 5157 continue; // do *not* consume the next token! 5158 } 5159 // otherwise, FALL THROUGH! 5160 LLVM_FALLTHROUGH; 5161 default: 5162 DoneWithTypeQuals: 5163 // If this is not a type-qualifier token, we're done reading type 5164 // qualifiers. First verify that DeclSpec's are consistent. 5165 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy()); 5166 if (EndLoc.isValid()) 5167 DS.SetRangeEnd(EndLoc); 5168 return; 5169 } 5170 5171 // If the specifier combination wasn't legal, issue a diagnostic. 5172 if (isInvalid) { 5173 assert(PrevSpec && "Method did not return previous specifier!"); 5174 Diag(Tok, DiagID) << PrevSpec; 5175 } 5176 EndLoc = ConsumeToken(); 5177 } 5178} 5179 5180/// ParseDeclarator - Parse and verify a newly-initialized declarator. 5181/// 5182void Parser::ParseDeclarator(Declarator &D) { 5183 /// This implements the 'declarator' production in the C grammar, then checks 5184 /// for well-formedness and issues diagnostics. 5185 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 5186} 5187 5188static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang, 5189 DeclaratorContext TheContext) { 5190 if (Kind == tok::star || Kind == tok::caret) 5191 return true; 5192 5193 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200)) 5194 return true; 5195 5196 if (!Lang.CPlusPlus) 5197 return false; 5198 5199 if (Kind == tok::amp) 5200 return true; 5201 5202 // We parse rvalue refs in C++03, because otherwise the errors are scary. 5203 // But we must not parse them in conversion-type-ids and new-type-ids, since 5204 // those can be legitimately followed by a && operator. 5205 // (The same thing can in theory happen after a trailing-return-type, but 5206 // since those are a C++11 feature, there is no rejects-valid issue there.) 5207 if (Kind == tok::ampamp) 5208 return Lang.CPlusPlus11 || 5209 (TheContext != DeclaratorContext::ConversionIdContext && 5210 TheContext != DeclaratorContext::CXXNewContext); 5211 5212 return false; 5213} 5214 5215// Indicates whether the given declarator is a pipe declarator. 5216static bool isPipeDeclerator(const Declarator &D) { 5217 const unsigned NumTypes = D.getNumTypeObjects(); 5218 5219 for (unsigned Idx = 0; Idx != NumTypes; ++Idx) 5220 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind) 5221 return true; 5222 5223 return false; 5224} 5225 5226/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator 5227/// is parsed by the function passed to it. Pass null, and the direct-declarator 5228/// isn't parsed at all, making this function effectively parse the C++ 5229/// ptr-operator production. 5230/// 5231/// If the grammar of this construct is extended, matching changes must also be 5232/// made to TryParseDeclarator and MightBeDeclarator, and possibly to 5233/// isConstructorDeclarator. 5234/// 5235/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl] 5236/// [C] pointer[opt] direct-declarator 5237/// [C++] direct-declarator 5238/// [C++] ptr-operator declarator 5239/// 5240/// pointer: [C99 6.7.5] 5241/// '*' type-qualifier-list[opt] 5242/// '*' type-qualifier-list[opt] pointer 5243/// 5244/// ptr-operator: 5245/// '*' cv-qualifier-seq[opt] 5246/// '&' 5247/// [C++0x] '&&' 5248/// [GNU] '&' restrict[opt] attributes[opt] 5249/// [GNU?] '&&' restrict[opt] attributes[opt] 5250/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 5251void Parser::ParseDeclaratorInternal(Declarator &D, 5252 DirectDeclParseFunction DirectDeclParser) { 5253 if (Diags.hasAllExtensionsSilenced()) 5254 D.setExtension(); 5255 5256 // C++ member pointers start with a '::' or a nested-name. 5257 // Member pointers get special handling, since there's no place for the 5258 // scope spec in the generic path below. 5259 if (getLangOpts().CPlusPlus && 5260 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) || 5261 (Tok.is(tok::identifier) && 5262 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) || 5263 Tok.is(tok::annot_cxxscope))) { 5264 bool EnteringContext = 5265 D.getContext() == DeclaratorContext::FileContext || 5266 D.getContext() == DeclaratorContext::MemberContext; 5267 CXXScopeSpec SS; 5268 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext); 5269 5270 if (SS.isNotEmpty()) { 5271 if (Tok.isNot(tok::star)) { 5272 // The scope spec really belongs to the direct-declarator. 5273 if (D.mayHaveIdentifier()) 5274 D.getCXXScopeSpec() = SS; 5275 else 5276 AnnotateScopeToken(SS, true); 5277 5278 if (DirectDeclParser) 5279 (this->*DirectDeclParser)(D); 5280 return; 5281 } 5282 5283 SourceLocation Loc = ConsumeToken(); 5284 D.SetRangeEnd(Loc); 5285 DeclSpec DS(AttrFactory); 5286 ParseTypeQualifierListOpt(DS); 5287 D.ExtendWithDeclSpec(DS); 5288 5289 // Recurse to parse whatever is left. 5290 ParseDeclaratorInternal(D, DirectDeclParser); 5291 5292 // Sema will have to catch (syntactically invalid) pointers into global 5293 // scope. It has to catch pointers into namespace scope anyway. 5294 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(), 5295 DS.getLocEnd()), 5296 DS.getAttributes(), 5297 /* Don't replace range end. */SourceLocation()); 5298 return; 5299 } 5300 } 5301 5302 tok::TokenKind Kind = Tok.getKind(); 5303 5304 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) { 5305 DeclSpec DS(AttrFactory); 5306 ParseTypeQualifierListOpt(DS); 5307 5308 D.AddTypeInfo( 5309 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()), 5310 DS.getAttributes(), SourceLocation()); 5311 } 5312 5313 // Not a pointer, C++ reference, or block. 5314 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) { 5315 if (DirectDeclParser) 5316 (this->*DirectDeclParser)(D); 5317 return; 5318 } 5319 5320 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference, 5321 // '&&' -> rvalue reference 5322 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&. 5323 D.SetRangeEnd(Loc); 5324 5325 if (Kind == tok::star || Kind == tok::caret) { 5326 // Is a pointer. 5327 DeclSpec DS(AttrFactory); 5328 5329 // GNU attributes are not allowed here in a new-type-id, but Declspec and 5330 // C++11 attributes are allowed. 5331 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed | 5332 ((D.getContext() != DeclaratorContext::CXXNewContext) 5333 ? AR_GNUAttributesParsed 5334 : AR_GNUAttributesParsedAndRejected); 5335 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier()); 5336 D.ExtendWithDeclSpec(DS); 5337 5338 // Recursively parse the declarator. 5339 ParseDeclaratorInternal(D, DirectDeclParser); 5340 if (Kind == tok::star) 5341 // Remember that we parsed a pointer type, and remember the type-quals. 5342 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc, 5343 DS.getConstSpecLoc(), 5344 DS.getVolatileSpecLoc(), 5345 DS.getRestrictSpecLoc(), 5346 DS.getAtomicSpecLoc(), 5347 DS.getUnalignedSpecLoc()), 5348 DS.getAttributes(), 5349 SourceLocation()); 5350 else 5351 // Remember that we parsed a Block type, and remember the type-quals. 5352 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), 5353 Loc), 5354 DS.getAttributes(), 5355 SourceLocation()); 5356 } else { 5357 // Is a reference 5358 DeclSpec DS(AttrFactory); 5359 5360 // Complain about rvalue references in C++03, but then go on and build 5361 // the declarator. 5362 if (Kind == tok::ampamp) 5363 Diag(Loc, getLangOpts().CPlusPlus11 ? 5364 diag::warn_cxx98_compat_rvalue_reference : 5365 diag::ext_rvalue_reference); 5366 5367 // GNU-style and C++11 attributes are allowed here, as is restrict. 5368 ParseTypeQualifierListOpt(DS); 5369 D.ExtendWithDeclSpec(DS); 5370 5371 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the 5372 // cv-qualifiers are introduced through the use of a typedef or of a 5373 // template type argument, in which case the cv-qualifiers are ignored. 5374 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { 5375 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5376 Diag(DS.getConstSpecLoc(), 5377 diag::err_invalid_reference_qualifier_application) << "const"; 5378 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5379 Diag(DS.getVolatileSpecLoc(), 5380 diag::err_invalid_reference_qualifier_application) << "volatile"; 5381 // 'restrict' is permitted as an extension. 5382 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5383 Diag(DS.getAtomicSpecLoc(), 5384 diag::err_invalid_reference_qualifier_application) << "_Atomic"; 5385 } 5386 5387 // Recursively parse the declarator. 5388 ParseDeclaratorInternal(D, DirectDeclParser); 5389 5390 if (D.getNumTypeObjects() > 0) { 5391 // C++ [dcl.ref]p4: There shall be no references to references. 5392 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1); 5393 if (InnerChunk.Kind == DeclaratorChunk::Reference) { 5394 if (const IdentifierInfo *II = D.getIdentifier()) 5395 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 5396 << II; 5397 else 5398 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 5399 << "type name"; 5400 5401 // Once we've complained about the reference-to-reference, we 5402 // can go ahead and build the (technically ill-formed) 5403 // declarator: reference collapsing will take care of it. 5404 } 5405 } 5406 5407 // Remember that we parsed a reference type. 5408 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc, 5409 Kind == tok::amp), 5410 DS.getAttributes(), 5411 SourceLocation()); 5412 } 5413} 5414 5415// When correcting from misplaced brackets before the identifier, the location 5416// is saved inside the declarator so that other diagnostic messages can use 5417// them. This extracts and returns that location, or returns the provided 5418// location if a stored location does not exist. 5419static SourceLocation getMissingDeclaratorIdLoc(Declarator &D, 5420 SourceLocation Loc) { 5421 if (D.getName().StartLocation.isInvalid() && 5422 D.getName().EndLocation.isValid()) 5423 return D.getName().EndLocation; 5424 5425 return Loc; 5426} 5427 5428/// ParseDirectDeclarator 5429/// direct-declarator: [C99 6.7.5] 5430/// [C99] identifier 5431/// '(' declarator ')' 5432/// [GNU] '(' attributes declarator ')' 5433/// [C90] direct-declarator '[' constant-expression[opt] ']' 5434/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 5435/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 5436/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 5437/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 5438/// [C++11] direct-declarator '[' constant-expression[opt] ']' 5439/// attribute-specifier-seq[opt] 5440/// direct-declarator '(' parameter-type-list ')' 5441/// direct-declarator '(' identifier-list[opt] ')' 5442/// [GNU] direct-declarator '(' parameter-forward-declarations 5443/// parameter-type-list[opt] ')' 5444/// [C++] direct-declarator '(' parameter-declaration-clause ')' 5445/// cv-qualifier-seq[opt] exception-specification[opt] 5446/// [C++11] direct-declarator '(' parameter-declaration-clause ')' 5447/// attribute-specifier-seq[opt] cv-qualifier-seq[opt] 5448/// ref-qualifier[opt] exception-specification[opt] 5449/// [C++] declarator-id 5450/// [C++11] declarator-id attribute-specifier-seq[opt] 5451/// 5452/// declarator-id: [C++ 8] 5453/// '...'[opt] id-expression 5454/// '::'[opt] nested-name-specifier[opt] type-name 5455/// 5456/// id-expression: [C++ 5.1] 5457/// unqualified-id 5458/// qualified-id 5459/// 5460/// unqualified-id: [C++ 5.1] 5461/// identifier 5462/// operator-function-id 5463/// conversion-function-id 5464/// '~' class-name 5465/// template-id 5466/// 5467/// C++17 adds the following, which we also handle here: 5468/// 5469/// simple-declaration: 5470/// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';' 5471/// 5472/// Note, any additional constructs added here may need corresponding changes 5473/// in isConstructorDeclarator. 5474void Parser::ParseDirectDeclarator(Declarator &D) { 5475 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec()); 5476 5477 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) { 5478 // This might be a C++17 structured binding. 5479 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() && 5480 D.getCXXScopeSpec().isEmpty()) 5481 return ParseDecompositionDeclarator(D); 5482 5483 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in 5484 // this context it is a bitfield. Also in range-based for statement colon 5485 // may delimit for-range-declaration. 5486 ColonProtectionRAIIObject X( 5487 *this, D.getContext() == DeclaratorContext::MemberContext || 5488 (D.getContext() == DeclaratorContext::ForContext && 5489 getLangOpts().CPlusPlus11)); 5490 5491 // ParseDeclaratorInternal might already have parsed the scope. 5492 if (D.getCXXScopeSpec().isEmpty()) { 5493 bool EnteringContext = 5494 D.getContext() == DeclaratorContext::FileContext || 5495 D.getContext() == DeclaratorContext::MemberContext; 5496 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr, 5497 EnteringContext); 5498 } 5499 5500 if (D.getCXXScopeSpec().isValid()) { 5501 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), 5502 D.getCXXScopeSpec())) 5503 // Change the declaration context for name lookup, until this function 5504 // is exited (and the declarator has been parsed). 5505 DeclScopeObj.EnterDeclaratorScope(); 5506 else if (getObjCDeclContext()) { 5507 // Ensure that we don't interpret the next token as an identifier when 5508 // dealing with declarations in an Objective-C container. 5509 D.SetIdentifier(nullptr, Tok.getLocation()); 5510 D.setInvalidType(true); 5511 ConsumeToken(); 5512 goto PastIdentifier; 5513 } 5514 } 5515 5516 // C++0x [dcl.fct]p14: 5517 // There is a syntactic ambiguity when an ellipsis occurs at the end of a 5518 // parameter-declaration-clause without a preceding comma. In this case, 5519 // the ellipsis is parsed as part of the abstract-declarator if the type 5520 // of the parameter either names a template parameter pack that has not 5521 // been expanded or contains auto; otherwise, it is parsed as part of the 5522 // parameter-declaration-clause. 5523 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() && 5524 !((D.getContext() == DeclaratorContext::PrototypeContext || 5525 D.getContext() == DeclaratorContext::LambdaExprParameterContext || 5526 D.getContext() == DeclaratorContext::BlockLiteralContext) && 5527 NextToken().is(tok::r_paren) && 5528 !D.hasGroupingParens() && 5529 !Actions.containsUnexpandedParameterPacks(D) && 5530 D.getDeclSpec().getTypeSpecType() != TST_auto)) { 5531 SourceLocation EllipsisLoc = ConsumeToken(); 5532 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) { 5533 // The ellipsis was put in the wrong place. Recover, and explain to 5534 // the user what they should have done. 5535 ParseDeclarator(D); 5536 if (EllipsisLoc.isValid()) 5537 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D); 5538 return; 5539 } else 5540 D.setEllipsisLoc(EllipsisLoc); 5541 5542 // The ellipsis can't be followed by a parenthesized declarator. We 5543 // check for that in ParseParenDeclarator, after we have disambiguated 5544 // the l_paren token. 5545 } 5546 5547 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id, 5548 tok::tilde)) { 5549 // We found something that indicates the start of an unqualified-id. 5550 // Parse that unqualified-id. 5551 bool AllowConstructorName; 5552 bool AllowDeductionGuide; 5553 if (D.getDeclSpec().hasTypeSpecifier()) { 5554 AllowConstructorName = false; 5555 AllowDeductionGuide = false; 5556 } else if (D.getCXXScopeSpec().isSet()) { 5557 AllowConstructorName = 5558 (D.getContext() == DeclaratorContext::FileContext || 5559 D.getContext() == DeclaratorContext::MemberContext); 5560 AllowDeductionGuide = false; 5561 } else { 5562 AllowConstructorName = 5563 (D.getContext() == DeclaratorContext::MemberContext); 5564 AllowDeductionGuide = 5565 (D.getContext() == DeclaratorContext::FileContext || 5566 D.getContext() == DeclaratorContext::MemberContext); 5567 } 5568 5569 SourceLocation TemplateKWLoc; 5570 bool HadScope = D.getCXXScopeSpec().isValid(); 5571 if (ParseUnqualifiedId(D.getCXXScopeSpec(), 5572 /*EnteringContext=*/true, 5573 /*AllowDestructorName=*/true, AllowConstructorName, 5574 AllowDeductionGuide, nullptr, TemplateKWLoc, 5575 D.getName()) || 5576 // Once we're past the identifier, if the scope was bad, mark the 5577 // whole declarator bad. 5578 D.getCXXScopeSpec().isInvalid()) { 5579 D.SetIdentifier(nullptr, Tok.getLocation()); 5580 D.setInvalidType(true); 5581 } else { 5582 // ParseUnqualifiedId might have parsed a scope specifier during error 5583 // recovery. If it did so, enter that scope. 5584 if (!HadScope && D.getCXXScopeSpec().isValid() && 5585 Actions.ShouldEnterDeclaratorScope(getCurScope(), 5586 D.getCXXScopeSpec())) 5587 DeclScopeObj.EnterDeclaratorScope(); 5588 5589 // Parsed the unqualified-id; update range information and move along. 5590 if (D.getSourceRange().getBegin().isInvalid()) 5591 D.SetRangeBegin(D.getName().getSourceRange().getBegin()); 5592 D.SetRangeEnd(D.getName().getSourceRange().getEnd()); 5593 } 5594 goto PastIdentifier; 5595 } 5596 5597 if (D.getCXXScopeSpec().isNotEmpty()) { 5598 // We have a scope specifier but no following unqualified-id. 5599 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()), 5600 diag::err_expected_unqualified_id) 5601 << /*C++*/1; 5602 D.SetIdentifier(nullptr, Tok.getLocation()); 5603 goto PastIdentifier; 5604 } 5605 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) { 5606 assert(!getLangOpts().CPlusPlus && 5607 "There's a C++-specific check for tok::identifier above"); 5608 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 5609 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 5610 D.SetRangeEnd(Tok.getLocation()); 5611 ConsumeToken(); 5612 goto PastIdentifier; 5613 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) { 5614 // We're not allowed an identifier here, but we got one. Try to figure out 5615 // if the user was trying to attach a name to the type, or whether the name 5616 // is some unrelated trailing syntax. 5617 bool DiagnoseIdentifier = false; 5618 if (D.hasGroupingParens()) 5619 // An identifier within parens is unlikely to be intended to be anything 5620 // other than a name being "declared". 5621 DiagnoseIdentifier = true; 5622 else if (D.getContext() == DeclaratorContext::TemplateTypeArgContext) 5623 // T<int N> is an accidental identifier; T<int N indicates a missing '>'. 5624 DiagnoseIdentifier = 5625 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater); 5626 else if (D.getContext() == DeclaratorContext::AliasDeclContext || 5627 D.getContext() == DeclaratorContext::AliasTemplateContext) 5628 // The most likely error is that the ';' was forgotten. 5629 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi); 5630 else if (D.getContext() == DeclaratorContext::TrailingReturnContext && 5631 !isCXX11VirtSpecifier(Tok)) 5632 DiagnoseIdentifier = NextToken().isOneOf( 5633 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try); 5634 if (DiagnoseIdentifier) { 5635 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id) 5636 << FixItHint::CreateRemoval(Tok.getLocation()); 5637 D.SetIdentifier(nullptr, Tok.getLocation()); 5638 ConsumeToken(); 5639 goto PastIdentifier; 5640 } 5641 } 5642 5643 if (Tok.is(tok::l_paren)) { 5644 // direct-declarator: '(' declarator ')' 5645 // direct-declarator: '(' attributes declarator ')' 5646 // Example: 'char (*X)' or 'int (*XX)(void)' 5647 ParseParenDeclarator(D); 5648 5649 // If the declarator was parenthesized, we entered the declarator 5650 // scope when parsing the parenthesized declarator, then exited 5651 // the scope already. Re-enter the scope, if we need to. 5652 if (D.getCXXScopeSpec().isSet()) { 5653 // If there was an error parsing parenthesized declarator, declarator 5654 // scope may have been entered before. Don't do it again. 5655 if (!D.isInvalidType() && 5656 Actions.ShouldEnterDeclaratorScope(getCurScope(), 5657 D.getCXXScopeSpec())) 5658 // Change the declaration context for name lookup, until this function 5659 // is exited (and the declarator has been parsed). 5660 DeclScopeObj.EnterDeclaratorScope(); 5661 } 5662 } else if (D.mayOmitIdentifier()) { 5663 // This could be something simple like "int" (in which case the declarator 5664 // portion is empty), if an abstract-declarator is allowed. 5665 D.SetIdentifier(nullptr, Tok.getLocation()); 5666 5667 // The grammar for abstract-pack-declarator does not allow grouping parens. 5668 // FIXME: Revisit this once core issue 1488 is resolved. 5669 if (D.hasEllipsis() && D.hasGroupingParens()) 5670 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()), 5671 diag::ext_abstract_pack_declarator_parens); 5672 } else { 5673 if (Tok.getKind() == tok::annot_pragma_parser_crash) 5674 LLVM_BUILTIN_TRAP; 5675 if (Tok.is(tok::l_square)) 5676 return ParseMisplacedBracketDeclarator(D); 5677 if (D.getContext() == DeclaratorContext::MemberContext) { 5678 // Objective-C++: Detect C++ keywords and try to prevent further errors by 5679 // treating these keyword as valid member names. 5680 if (getLangOpts().ObjC1 && getLangOpts().CPlusPlus && 5681 Tok.getIdentifierInfo() && 5682 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) { 5683 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 5684 diag::err_expected_member_name_or_semi_objcxx_keyword) 5685 << Tok.getIdentifierInfo() 5686 << (D.getDeclSpec().isEmpty() ? SourceRange() 5687 : D.getDeclSpec().getSourceRange()); 5688 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 5689 D.SetRangeEnd(Tok.getLocation()); 5690 ConsumeToken(); 5691 goto PastIdentifier; 5692 } 5693 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 5694 diag::err_expected_member_name_or_semi) 5695 << (D.getDeclSpec().isEmpty() ? SourceRange() 5696 : D.getDeclSpec().getSourceRange()); 5697 } else if (getLangOpts().CPlusPlus) { 5698 if (Tok.isOneOf(tok::period, tok::arrow)) 5699 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow); 5700 else { 5701 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc(); 5702 if (Tok.isAtStartOfLine() && Loc.isValid()) 5703 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id) 5704 << getLangOpts().CPlusPlus; 5705 else 5706 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 5707 diag::err_expected_unqualified_id) 5708 << getLangOpts().CPlusPlus; 5709 } 5710 } else { 5711 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 5712 diag::err_expected_either) 5713 << tok::identifier << tok::l_paren; 5714 } 5715 D.SetIdentifier(nullptr, Tok.getLocation()); 5716 D.setInvalidType(true); 5717 } 5718 5719 PastIdentifier: 5720 assert(D.isPastIdentifier() && 5721 "Haven't past the location of the identifier yet?"); 5722 5723 // Don't parse attributes unless we have parsed an unparenthesized name. 5724 if (D.hasName() && !D.getNumTypeObjects()) 5725 MaybeParseCXX11Attributes(D); 5726 5727 while (1) { 5728 if (Tok.is(tok::l_paren)) { 5729 // Enter function-declaration scope, limiting any declarators to the 5730 // function prototype scope, including parameter declarators. 5731 ParseScope PrototypeScope(this, 5732 Scope::FunctionPrototypeScope|Scope::DeclScope| 5733 (D.isFunctionDeclaratorAFunctionDeclaration() 5734 ? Scope::FunctionDeclarationScope : 0)); 5735 5736 // The paren may be part of a C++ direct initializer, eg. "int x(1);". 5737 // In such a case, check if we actually have a function declarator; if it 5738 // is not, the declarator has been fully parsed. 5739 bool IsAmbiguous = false; 5740 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) { 5741 // The name of the declarator, if any, is tentatively declared within 5742 // a possible direct initializer. 5743 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier()); 5744 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous); 5745 TentativelyDeclaredIdentifiers.pop_back(); 5746 if (!IsFunctionDecl) 5747 break; 5748 } 5749 ParsedAttributes attrs(AttrFactory); 5750 BalancedDelimiterTracker T(*this, tok::l_paren); 5751 T.consumeOpen(); 5752 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous); 5753 PrototypeScope.Exit(); 5754 } else if (Tok.is(tok::l_square)) { 5755 ParseBracketDeclarator(D); 5756 } else { 5757 break; 5758 } 5759 } 5760} 5761 5762void Parser::ParseDecompositionDeclarator(Declarator &D) { 5763 assert(Tok.is(tok::l_square)); 5764 5765 // If this doesn't look like a structured binding, maybe it's a misplaced 5766 // array declarator. 5767 // FIXME: Consume the l_square first so we don't need extra lookahead for 5768 // this. 5769 if (!(NextToken().is(tok::identifier) && 5770 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) && 5771 !(NextToken().is(tok::r_square) && 5772 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace))) 5773 return ParseMisplacedBracketDeclarator(D); 5774 5775 BalancedDelimiterTracker T(*this, tok::l_square); 5776 T.consumeOpen(); 5777 5778 SmallVector<DecompositionDeclarator::Binding, 32> Bindings; 5779 while (Tok.isNot(tok::r_square)) { 5780 if (!Bindings.empty()) { 5781 if (Tok.is(tok::comma)) 5782 ConsumeToken(); 5783 else { 5784 if (Tok.is(tok::identifier)) { 5785 SourceLocation EndLoc = getEndOfPreviousToken(); 5786 Diag(EndLoc, diag::err_expected) 5787 << tok::comma << FixItHint::CreateInsertion(EndLoc, ","); 5788 } else { 5789 Diag(Tok, diag::err_expected_comma_or_rsquare); 5790 } 5791 5792 SkipUntil(tok::r_square, tok::comma, tok::identifier, 5793 StopAtSemi | StopBeforeMatch); 5794 if (Tok.is(tok::comma)) 5795 ConsumeToken(); 5796 else if (Tok.isNot(tok::identifier)) 5797 break; 5798 } 5799 } 5800 5801 if (Tok.isNot(tok::identifier)) { 5802 Diag(Tok, diag::err_expected) << tok::identifier; 5803 break; 5804 } 5805 5806 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()}); 5807 ConsumeToken(); 5808 } 5809 5810 if (Tok.isNot(tok::r_square)) 5811 // We've already diagnosed a problem here. 5812 T.skipToEnd(); 5813 else { 5814 // C++17 does not allow the identifier-list in a structured binding 5815 // to be empty. 5816 if (Bindings.empty()) 5817 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty); 5818 5819 T.consumeClose(); 5820 } 5821 5822 return D.setDecompositionBindings(T.getOpenLocation(), Bindings, 5823 T.getCloseLocation()); 5824} 5825 5826/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is 5827/// only called before the identifier, so these are most likely just grouping 5828/// parens for precedence. If we find that these are actually function 5829/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. 5830/// 5831/// direct-declarator: 5832/// '(' declarator ')' 5833/// [GNU] '(' attributes declarator ')' 5834/// direct-declarator '(' parameter-type-list ')' 5835/// direct-declarator '(' identifier-list[opt] ')' 5836/// [GNU] direct-declarator '(' parameter-forward-declarations 5837/// parameter-type-list[opt] ')' 5838/// 5839void Parser::ParseParenDeclarator(Declarator &D) { 5840 BalancedDelimiterTracker T(*this, tok::l_paren); 5841 T.consumeOpen(); 5842 5843 assert(!D.isPastIdentifier() && "Should be called before passing identifier"); 5844 5845 // Eat any attributes before we look at whether this is a grouping or function 5846 // declarator paren. If this is a grouping paren, the attribute applies to 5847 // the type being built up, for example: 5848 // int (__attribute__(()) *x)(long y) 5849 // If this ends up not being a grouping paren, the attribute applies to the 5850 // first argument, for example: 5851 // int (__attribute__(()) int x) 5852 // In either case, we need to eat any attributes to be able to determine what 5853 // sort of paren this is. 5854 // 5855 ParsedAttributes attrs(AttrFactory); 5856 bool RequiresArg = false; 5857 if (Tok.is(tok::kw___attribute)) { 5858 ParseGNUAttributes(attrs); 5859 5860 // We require that the argument list (if this is a non-grouping paren) be 5861 // present even if the attribute list was empty. 5862 RequiresArg = true; 5863 } 5864 5865 // Eat any Microsoft extensions. 5866 ParseMicrosoftTypeAttributes(attrs); 5867 5868 // Eat any Borland extensions. 5869 if (Tok.is(tok::kw___pascal)) 5870 ParseBorlandTypeAttributes(attrs); 5871 5872 // If we haven't past the identifier yet (or where the identifier would be 5873 // stored, if this is an abstract declarator), then this is probably just 5874 // grouping parens. However, if this could be an abstract-declarator, then 5875 // this could also be the start of function arguments (consider 'void()'). 5876 bool isGrouping; 5877 5878 if (!D.mayOmitIdentifier()) { 5879 // If this can't be an abstract-declarator, this *must* be a grouping 5880 // paren, because we haven't seen the identifier yet. 5881 isGrouping = true; 5882 } else if (Tok.is(tok::r_paren) || // 'int()' is a function. 5883 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) && 5884 NextToken().is(tok::r_paren)) || // C++ int(...) 5885 isDeclarationSpecifier() || // 'int(int)' is a function. 5886 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function. 5887 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is 5888 // considered to be a type, not a K&R identifier-list. 5889 isGrouping = false; 5890 } else { 5891 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. 5892 isGrouping = true; 5893 } 5894 5895 // If this is a grouping paren, handle: 5896 // direct-declarator: '(' declarator ')' 5897 // direct-declarator: '(' attributes declarator ')' 5898 if (isGrouping) { 5899 SourceLocation EllipsisLoc = D.getEllipsisLoc(); 5900 D.setEllipsisLoc(SourceLocation()); 5901 5902 bool hadGroupingParens = D.hasGroupingParens(); 5903 D.setGroupingParens(true); 5904 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 5905 // Match the ')'. 5906 T.consumeClose(); 5907 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(), 5908 T.getCloseLocation()), 5909 attrs, T.getCloseLocation()); 5910 5911 D.setGroupingParens(hadGroupingParens); 5912 5913 // An ellipsis cannot be placed outside parentheses. 5914 if (EllipsisLoc.isValid()) 5915 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D); 5916 5917 return; 5918 } 5919 5920 // Okay, if this wasn't a grouping paren, it must be the start of a function 5921 // argument list. Recognize that this declarator will never have an 5922 // identifier (and remember where it would have been), then call into 5923 // ParseFunctionDeclarator to handle of argument list. 5924 D.SetIdentifier(nullptr, Tok.getLocation()); 5925 5926 // Enter function-declaration scope, limiting any declarators to the 5927 // function prototype scope, including parameter declarators. 5928 ParseScope PrototypeScope(this, 5929 Scope::FunctionPrototypeScope | Scope::DeclScope | 5930 (D.isFunctionDeclaratorAFunctionDeclaration() 5931 ? Scope::FunctionDeclarationScope : 0)); 5932 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg); 5933 PrototypeScope.Exit(); 5934} 5935 5936/// ParseFunctionDeclarator - We are after the identifier and have parsed the 5937/// declarator D up to a paren, which indicates that we are parsing function 5938/// arguments. 5939/// 5940/// If FirstArgAttrs is non-null, then the caller parsed those arguments 5941/// immediately after the open paren - they should be considered to be the 5942/// first argument of a parameter. 5943/// 5944/// If RequiresArg is true, then the first argument of the function is required 5945/// to be present and required to not be an identifier list. 5946/// 5947/// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt], 5948/// (C++11) ref-qualifier[opt], exception-specification[opt], 5949/// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt]. 5950/// 5951/// [C++11] exception-specification: 5952/// dynamic-exception-specification 5953/// noexcept-specification 5954/// 5955void Parser::ParseFunctionDeclarator(Declarator &D, 5956 ParsedAttributes &FirstArgAttrs, 5957 BalancedDelimiterTracker &Tracker, 5958 bool IsAmbiguous, 5959 bool RequiresArg) { 5960 assert(getCurScope()->isFunctionPrototypeScope() && 5961 "Should call from a Function scope"); 5962 // lparen is already consumed! 5963 assert(D.isPastIdentifier() && "Should not call before identifier!"); 5964 5965 // This should be true when the function has typed arguments. 5966 // Otherwise, it is treated as a K&R-style function. 5967 bool HasProto = false; 5968 // Build up an array of information about the parsed arguments. 5969 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 5970 // Remember where we see an ellipsis, if any. 5971 SourceLocation EllipsisLoc; 5972 5973 DeclSpec DS(AttrFactory); 5974 bool RefQualifierIsLValueRef = true; 5975 SourceLocation RefQualifierLoc; 5976 SourceLocation ConstQualifierLoc; 5977 SourceLocation VolatileQualifierLoc; 5978 SourceLocation RestrictQualifierLoc; 5979 ExceptionSpecificationType ESpecType = EST_None; 5980 SourceRange ESpecRange; 5981 SmallVector<ParsedType, 2> DynamicExceptions; 5982 SmallVector<SourceRange, 2> DynamicExceptionRanges; 5983 ExprResult NoexceptExpr; 5984 CachedTokens *ExceptionSpecTokens = nullptr; 5985 ParsedAttributesWithRange FnAttrs(AttrFactory); 5986 TypeResult TrailingReturnType; 5987 5988 /* LocalEndLoc is the end location for the local FunctionTypeLoc. 5989 EndLoc is the end location for the function declarator. 5990 They differ for trailing return types. */ 5991 SourceLocation StartLoc, LocalEndLoc, EndLoc; 5992 SourceLocation LParenLoc, RParenLoc; 5993 LParenLoc = Tracker.getOpenLocation(); 5994 StartLoc = LParenLoc; 5995 5996 if (isFunctionDeclaratorIdentifierList()) { 5997 if (RequiresArg) 5998 Diag(Tok, diag::err_argument_required_after_attribute); 5999 6000 ParseFunctionDeclaratorIdentifierList(D, ParamInfo); 6001 6002 Tracker.consumeClose(); 6003 RParenLoc = Tracker.getCloseLocation(); 6004 LocalEndLoc = RParenLoc; 6005 EndLoc = RParenLoc; 6006 6007 // If there are attributes following the identifier list, parse them and 6008 // prohibit them. 6009 MaybeParseCXX11Attributes(FnAttrs); 6010 ProhibitAttributes(FnAttrs); 6011 } else { 6012 if (Tok.isNot(tok::r_paren)) 6013 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, 6014 EllipsisLoc); 6015 else if (RequiresArg) 6016 Diag(Tok, diag::err_argument_required_after_attribute); 6017 6018 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus 6019 || getLangOpts().OpenCL; 6020 6021 // If we have the closing ')', eat it. 6022 Tracker.consumeClose(); 6023 RParenLoc = Tracker.getCloseLocation(); 6024 LocalEndLoc = RParenLoc; 6025 EndLoc = RParenLoc; 6026 6027 if (getLangOpts().CPlusPlus) { 6028 // FIXME: Accept these components in any order, and produce fixits to 6029 // correct the order if the user gets it wrong. Ideally we should deal 6030 // with the pure-specifier in the same way. 6031 6032 // Parse cv-qualifier-seq[opt]. 6033 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed, 6034 /*AtomicAllowed*/ false, 6035 /*IdentifierRequired=*/false, 6036 llvm::function_ref<void()>([&]() { 6037 Actions.CodeCompleteFunctionQualifiers(DS, D); 6038 })); 6039 if (!DS.getSourceRange().getEnd().isInvalid()) { 6040 EndLoc = DS.getSourceRange().getEnd(); 6041 ConstQualifierLoc = DS.getConstSpecLoc(); 6042 VolatileQualifierLoc = DS.getVolatileSpecLoc(); 6043 RestrictQualifierLoc = DS.getRestrictSpecLoc(); 6044 } 6045 6046 // Parse ref-qualifier[opt]. 6047 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) 6048 EndLoc = RefQualifierLoc; 6049 6050 // C++11 [expr.prim.general]p3: 6051 // If a declaration declares a member function or member function 6052 // template of a class X, the expression this is a prvalue of type 6053 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 6054 // and the end of the function-definition, member-declarator, or 6055 // declarator. 6056 // FIXME: currently, "static" case isn't handled correctly. 6057 bool IsCXX11MemberFunction = 6058 getLangOpts().CPlusPlus11 && 6059 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6060 (D.getContext() == DeclaratorContext::MemberContext 6061 ? !D.getDeclSpec().isFriendSpecified() 6062 : D.getContext() == DeclaratorContext::FileContext && 6063 D.getCXXScopeSpec().isValid() && 6064 Actions.CurContext->isRecord()); 6065 Sema::CXXThisScopeRAII ThisScope(Actions, 6066 dyn_cast<CXXRecordDecl>(Actions.CurContext), 6067 DS.getTypeQualifiers() | 6068 (D.getDeclSpec().isConstexprSpecified() && 6069 !getLangOpts().CPlusPlus14 6070 ? Qualifiers::Const : 0), 6071 IsCXX11MemberFunction); 6072 6073 // Parse exception-specification[opt]. 6074 bool Delayed = D.isFirstDeclarationOfMember() && 6075 D.isFunctionDeclaratorAFunctionDeclaration(); 6076 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) && 6077 GetLookAheadToken(0).is(tok::kw_noexcept) && 6078 GetLookAheadToken(1).is(tok::l_paren) && 6079 GetLookAheadToken(2).is(tok::kw_noexcept) && 6080 GetLookAheadToken(3).is(tok::l_paren) && 6081 GetLookAheadToken(4).is(tok::identifier) && 6082 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) { 6083 // HACK: We've got an exception-specification 6084 // noexcept(noexcept(swap(...))) 6085 // or 6086 // noexcept(noexcept(swap(...)) && noexcept(swap(...))) 6087 // on a 'swap' member function. This is a libstdc++ bug; the lookup 6088 // for 'swap' will only find the function we're currently declaring, 6089 // whereas it expects to find a non-member swap through ADL. Turn off 6090 // delayed parsing to give it a chance to find what it expects. 6091 Delayed = false; 6092 } 6093 ESpecType = tryParseExceptionSpecification(Delayed, 6094 ESpecRange, 6095 DynamicExceptions, 6096 DynamicExceptionRanges, 6097 NoexceptExpr, 6098 ExceptionSpecTokens); 6099 if (ESpecType != EST_None) 6100 EndLoc = ESpecRange.getEnd(); 6101 6102 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes 6103 // after the exception-specification. 6104 MaybeParseCXX11Attributes(FnAttrs); 6105 6106 // Parse trailing-return-type[opt]. 6107 LocalEndLoc = EndLoc; 6108 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) { 6109 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type); 6110 if (D.getDeclSpec().getTypeSpecType() == TST_auto) 6111 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 6112 LocalEndLoc = Tok.getLocation(); 6113 SourceRange Range; 6114 TrailingReturnType = ParseTrailingReturnType(Range); 6115 EndLoc = Range.getEnd(); 6116 } 6117 } else if (standardAttributesAllowed()) { 6118 MaybeParseCXX11Attributes(FnAttrs); 6119 } 6120 } 6121 6122 // Collect non-parameter declarations from the prototype if this is a function 6123 // declaration. They will be moved into the scope of the function. Only do 6124 // this in C and not C++, where the decls will continue to live in the 6125 // surrounding context. 6126 SmallVector<NamedDecl *, 0> DeclsInPrototype; 6127 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope && 6128 !getLangOpts().CPlusPlus) { 6129 for (Decl *D : getCurScope()->decls()) { 6130 NamedDecl *ND = dyn_cast<NamedDecl>(D); 6131 if (!ND || isa<ParmVarDecl>(ND)) 6132 continue; 6133 DeclsInPrototype.push_back(ND); 6134 } 6135 } 6136 6137 // Remember that we parsed a function type, and remember the attributes. 6138 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto, 6139 IsAmbiguous, 6140 LParenLoc, 6141 ParamInfo.data(), ParamInfo.size(), 6142 EllipsisLoc, RParenLoc, 6143 DS.getTypeQualifiers(), 6144 RefQualifierIsLValueRef, 6145 RefQualifierLoc, ConstQualifierLoc, 6146 VolatileQualifierLoc, 6147 RestrictQualifierLoc, 6148 /*MutableLoc=*/SourceLocation(), 6149 ESpecType, ESpecRange, 6150 DynamicExceptions.data(), 6151 DynamicExceptionRanges.data(), 6152 DynamicExceptions.size(), 6153 NoexceptExpr.isUsable() ? 6154 NoexceptExpr.get() : nullptr, 6155 ExceptionSpecTokens, 6156 DeclsInPrototype, 6157 StartLoc, LocalEndLoc, D, 6158 TrailingReturnType), 6159 FnAttrs, EndLoc); 6160} 6161 6162/// ParseRefQualifier - Parses a member function ref-qualifier. Returns 6163/// true if a ref-qualifier is found. 6164bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef, 6165 SourceLocation &RefQualifierLoc) { 6166 if (Tok.isOneOf(tok::amp, tok::ampamp)) { 6167 Diag(Tok, getLangOpts().CPlusPlus11 ? 6168 diag::warn_cxx98_compat_ref_qualifier : 6169 diag::ext_ref_qualifier); 6170 6171 RefQualifierIsLValueRef = Tok.is(tok::amp); 6172 RefQualifierLoc = ConsumeToken(); 6173 return true; 6174 } 6175 return false; 6176} 6177 6178/// isFunctionDeclaratorIdentifierList - This parameter list may have an 6179/// identifier list form for a K&R-style function: void foo(a,b,c) 6180/// 6181/// Note that identifier-lists are only allowed for normal declarators, not for 6182/// abstract-declarators. 6183bool Parser::isFunctionDeclaratorIdentifierList() { 6184 return !getLangOpts().CPlusPlus 6185 && Tok.is(tok::identifier) 6186 && !TryAltiVecVectorToken() 6187 // K&R identifier lists can't have typedefs as identifiers, per C99 6188 // 6.7.5.3p11. 6189 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) 6190 // Identifier lists follow a really simple grammar: the identifiers can 6191 // be followed *only* by a ", identifier" or ")". However, K&R 6192 // identifier lists are really rare in the brave new modern world, and 6193 // it is very common for someone to typo a type in a non-K&R style 6194 // list. If we are presented with something like: "void foo(intptr x, 6195 // float y)", we don't want to start parsing the function declarator as 6196 // though it is a K&R style declarator just because intptr is an 6197 // invalid type. 6198 // 6199 // To handle this, we check to see if the token after the first 6200 // identifier is a "," or ")". Only then do we parse it as an 6201 // identifier list. 6202 && (!Tok.is(tok::eof) && 6203 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren))); 6204} 6205 6206/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator 6207/// we found a K&R-style identifier list instead of a typed parameter list. 6208/// 6209/// After returning, ParamInfo will hold the parsed parameters. 6210/// 6211/// identifier-list: [C99 6.7.5] 6212/// identifier 6213/// identifier-list ',' identifier 6214/// 6215void Parser::ParseFunctionDeclaratorIdentifierList( 6216 Declarator &D, 6217 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) { 6218 // If there was no identifier specified for the declarator, either we are in 6219 // an abstract-declarator, or we are in a parameter declarator which was found 6220 // to be abstract. In abstract-declarators, identifier lists are not valid: 6221 // diagnose this. 6222 if (!D.getIdentifier()) 6223 Diag(Tok, diag::ext_ident_list_in_param); 6224 6225 // Maintain an efficient lookup of params we have seen so far. 6226 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar; 6227 6228 do { 6229 // If this isn't an identifier, report the error and skip until ')'. 6230 if (Tok.isNot(tok::identifier)) { 6231 Diag(Tok, diag::err_expected) << tok::identifier; 6232 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch); 6233 // Forget we parsed anything. 6234 ParamInfo.clear(); 6235 return; 6236 } 6237 6238 IdentifierInfo *ParmII = Tok.getIdentifierInfo(); 6239 6240 // Reject 'typedef int y; int test(x, y)', but continue parsing. 6241 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope())) 6242 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; 6243 6244 // Verify that the argument identifier has not already been mentioned. 6245 if (!ParamsSoFar.insert(ParmII).second) { 6246 Diag(Tok, diag::err_param_redefinition) << ParmII; 6247 } else { 6248 // Remember this identifier in ParamInfo. 6249 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 6250 Tok.getLocation(), 6251 nullptr)); 6252 } 6253 6254 // Eat the identifier. 6255 ConsumeToken(); 6256 // The list continues if we see a comma. 6257 } while (TryConsumeToken(tok::comma)); 6258} 6259 6260/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list 6261/// after the opening parenthesis. This function will not parse a K&R-style 6262/// identifier list. 6263/// 6264/// D is the declarator being parsed. If FirstArgAttrs is non-null, then the 6265/// caller parsed those arguments immediately after the open paren - they should 6266/// be considered to be part of the first parameter. 6267/// 6268/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will 6269/// be the location of the ellipsis, if any was parsed. 6270/// 6271/// parameter-type-list: [C99 6.7.5] 6272/// parameter-list 6273/// parameter-list ',' '...' 6274/// [C++] parameter-list '...' 6275/// 6276/// parameter-list: [C99 6.7.5] 6277/// parameter-declaration 6278/// parameter-list ',' parameter-declaration 6279/// 6280/// parameter-declaration: [C99 6.7.5] 6281/// declaration-specifiers declarator 6282/// [C++] declaration-specifiers declarator '=' assignment-expression 6283/// [C++11] initializer-clause 6284/// [GNU] declaration-specifiers declarator attributes 6285/// declaration-specifiers abstract-declarator[opt] 6286/// [C++] declaration-specifiers abstract-declarator[opt] 6287/// '=' assignment-expression 6288/// [GNU] declaration-specifiers abstract-declarator[opt] attributes 6289/// [C++11] attribute-specifier-seq parameter-declaration 6290/// 6291void Parser::ParseParameterDeclarationClause( 6292 Declarator &D, 6293 ParsedAttributes &FirstArgAttrs, 6294 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, 6295 SourceLocation &EllipsisLoc) { 6296 do { 6297 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq 6298 // before deciding this was a parameter-declaration-clause. 6299 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) 6300 break; 6301 6302 // Parse the declaration-specifiers. 6303 // Just use the ParsingDeclaration "scope" of the declarator. 6304 DeclSpec DS(AttrFactory); 6305 6306 // Parse any C++11 attributes. 6307 MaybeParseCXX11Attributes(DS.getAttributes()); 6308 6309 // Skip any Microsoft attributes before a param. 6310 MaybeParseMicrosoftAttributes(DS.getAttributes()); 6311 6312 SourceLocation DSStart = Tok.getLocation(); 6313 6314 // If the caller parsed attributes for the first argument, add them now. 6315 // Take them so that we only apply the attributes to the first parameter. 6316 // FIXME: If we can leave the attributes in the token stream somehow, we can 6317 // get rid of a parameter (FirstArgAttrs) and this statement. It might be 6318 // too much hassle. 6319 DS.takeAttributesFrom(FirstArgAttrs); 6320 6321 ParseDeclarationSpecifiers(DS); 6322 6323 6324 // Parse the declarator. This is "PrototypeContext" or 6325 // "LambdaExprParameterContext", because we must accept either 6326 // 'declarator' or 'abstract-declarator' here. 6327 Declarator ParmDeclarator( 6328 DS, D.getContext() == DeclaratorContext::LambdaExprContext 6329 ? DeclaratorContext::LambdaExprParameterContext 6330 : DeclaratorContext::PrototypeContext); 6331 ParseDeclarator(ParmDeclarator); 6332 6333 // Parse GNU attributes, if present. 6334 MaybeParseGNUAttributes(ParmDeclarator); 6335 6336 // Remember this parsed parameter in ParamInfo. 6337 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier(); 6338 6339 // DefArgToks is used when the parsing of default arguments needs 6340 // to be delayed. 6341 std::unique_ptr<CachedTokens> DefArgToks; 6342 6343 // If no parameter was specified, verify that *something* was specified, 6344 // otherwise we have a missing type and identifier. 6345 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr && 6346 ParmDeclarator.getNumTypeObjects() == 0) { 6347 // Completely missing, emit error. 6348 Diag(DSStart, diag::err_missing_param); 6349 } else { 6350 // Otherwise, we have something. Add it and let semantic analysis try 6351 // to grok it and add the result to the ParamInfo we are building. 6352 6353 // Last chance to recover from a misplaced ellipsis in an attempted 6354 // parameter pack declaration. 6355 if (Tok.is(tok::ellipsis) && 6356 (NextToken().isNot(tok::r_paren) || 6357 (!ParmDeclarator.getEllipsisLoc().isValid() && 6358 !Actions.isUnexpandedParameterPackPermitted())) && 6359 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) 6360 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator); 6361 6362 // Inform the actions module about the parameter declarator, so it gets 6363 // added to the current scope. 6364 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator); 6365 // Parse the default argument, if any. We parse the default 6366 // arguments in all dialects; the semantic analysis in 6367 // ActOnParamDefaultArgument will reject the default argument in 6368 // C. 6369 if (Tok.is(tok::equal)) { 6370 SourceLocation EqualLoc = Tok.getLocation(); 6371 6372 // Parse the default argument 6373 if (D.getContext() == DeclaratorContext::MemberContext) { 6374 // If we're inside a class definition, cache the tokens 6375 // corresponding to the default argument. We'll actually parse 6376 // them when we see the end of the class definition. 6377 DefArgToks.reset(new CachedTokens); 6378 6379 SourceLocation ArgStartLoc = NextToken().getLocation(); 6380 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) { 6381 DefArgToks.reset(); 6382 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc); 6383 } else { 6384 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc, 6385 ArgStartLoc); 6386 } 6387 } else { 6388 // Consume the '='. 6389 ConsumeToken(); 6390 6391 // The argument isn't actually potentially evaluated unless it is 6392 // used. 6393 EnterExpressionEvaluationContext Eval( 6394 Actions, 6395 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, 6396 Param); 6397 6398 ExprResult DefArgResult; 6399 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 6400 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 6401 DefArgResult = ParseBraceInitializer(); 6402 } else 6403 DefArgResult = ParseAssignmentExpression(); 6404 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult); 6405 if (DefArgResult.isInvalid()) { 6406 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc); 6407 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch); 6408 } else { 6409 // Inform the actions module about the default argument 6410 Actions.ActOnParamDefaultArgument(Param, EqualLoc, 6411 DefArgResult.get()); 6412 } 6413 } 6414 } 6415 6416 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 6417 ParmDeclarator.getIdentifierLoc(), 6418 Param, std::move(DefArgToks))); 6419 } 6420 6421 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) { 6422 if (!getLangOpts().CPlusPlus) { 6423 // We have ellipsis without a preceding ',', which is ill-formed 6424 // in C. Complain and provide the fix. 6425 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis) 6426 << FixItHint::CreateInsertion(EllipsisLoc, ", "); 6427 } else if (ParmDeclarator.getEllipsisLoc().isValid() || 6428 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) { 6429 // It looks like this was supposed to be a parameter pack. Warn and 6430 // point out where the ellipsis should have gone. 6431 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc(); 6432 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg) 6433 << ParmEllipsis.isValid() << ParmEllipsis; 6434 if (ParmEllipsis.isValid()) { 6435 Diag(ParmEllipsis, 6436 diag::note_misplaced_ellipsis_vararg_existing_ellipsis); 6437 } else { 6438 Diag(ParmDeclarator.getIdentifierLoc(), 6439 diag::note_misplaced_ellipsis_vararg_add_ellipsis) 6440 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(), 6441 "...") 6442 << !ParmDeclarator.hasName(); 6443 } 6444 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma) 6445 << FixItHint::CreateInsertion(EllipsisLoc, ", "); 6446 } 6447 6448 // We can't have any more parameters after an ellipsis. 6449 break; 6450 } 6451 6452 // If the next token is a comma, consume it and keep reading arguments. 6453 } while (TryConsumeToken(tok::comma)); 6454} 6455 6456/// [C90] direct-declarator '[' constant-expression[opt] ']' 6457/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 6458/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 6459/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 6460/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 6461/// [C++11] direct-declarator '[' constant-expression[opt] ']' 6462/// attribute-specifier-seq[opt] 6463void Parser::ParseBracketDeclarator(Declarator &D) { 6464 if (CheckProhibitedCXX11Attribute()) 6465 return; 6466 6467 BalancedDelimiterTracker T(*this, tok::l_square); 6468 T.consumeOpen(); 6469 6470 // C array syntax has many features, but by-far the most common is [] and [4]. 6471 // This code does a fast path to handle some of the most obvious cases. 6472 if (Tok.getKind() == tok::r_square) { 6473 T.consumeClose(); 6474 ParsedAttributes attrs(AttrFactory); 6475 MaybeParseCXX11Attributes(attrs); 6476 6477 // Remember that we parsed the empty array type. 6478 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr, 6479 T.getOpenLocation(), 6480 T.getCloseLocation()), 6481 attrs, T.getCloseLocation()); 6482 return; 6483 } else if (Tok.getKind() == tok::numeric_constant && 6484 GetLookAheadToken(1).is(tok::r_square)) { 6485 // [4] is very common. Parse the numeric constant expression. 6486 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope())); 6487 ConsumeToken(); 6488 6489 T.consumeClose(); 6490 ParsedAttributes attrs(AttrFactory); 6491 MaybeParseCXX11Attributes(attrs); 6492 6493 // Remember that we parsed a array type, and remember its features. 6494 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 6495 ExprRes.get(), 6496 T.getOpenLocation(), 6497 T.getCloseLocation()), 6498 attrs, T.getCloseLocation()); 6499 return; 6500 } else if (Tok.getKind() == tok::code_completion) { 6501 Actions.CodeCompleteBracketDeclarator(getCurScope()); 6502 return cutOffParsing(); 6503 } 6504 6505 // If valid, this location is the position where we read the 'static' keyword. 6506 SourceLocation StaticLoc; 6507 TryConsumeToken(tok::kw_static, StaticLoc); 6508 6509 // If there is a type-qualifier-list, read it now. 6510 // Type qualifiers in an array subscript are a C99 feature. 6511 DeclSpec DS(AttrFactory); 6512 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed); 6513 6514 // If we haven't already read 'static', check to see if there is one after the 6515 // type-qualifier-list. 6516 if (!StaticLoc.isValid()) 6517 TryConsumeToken(tok::kw_static, StaticLoc); 6518 6519 // Handle "direct-declarator [ type-qual-list[opt] * ]". 6520 bool isStar = false; 6521 ExprResult NumElements; 6522 6523 // Handle the case where we have '[*]' as the array size. However, a leading 6524 // star could be the start of an expression, for example 'X[*p + 4]'. Verify 6525 // the token after the star is a ']'. Since stars in arrays are 6526 // infrequent, use of lookahead is not costly here. 6527 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) { 6528 ConsumeToken(); // Eat the '*'. 6529 6530 if (StaticLoc.isValid()) { 6531 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static); 6532 StaticLoc = SourceLocation(); // Drop the static. 6533 } 6534 isStar = true; 6535 } else if (Tok.isNot(tok::r_square)) { 6536 // Note, in C89, this production uses the constant-expr production instead 6537 // of assignment-expr. The only difference is that assignment-expr allows 6538 // things like '=' and '*='. Sema rejects these in C89 mode because they 6539 // are not i-c-e's, so we don't need to distinguish between the two here. 6540 6541 // Parse the constant-expression or assignment-expression now (depending 6542 // on dialect). 6543 if (getLangOpts().CPlusPlus) { 6544 NumElements = ParseConstantExpression(); 6545 } else { 6546 EnterExpressionEvaluationContext Unevaluated( 6547 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated); 6548 NumElements = 6549 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()); 6550 } 6551 } else { 6552 if (StaticLoc.isValid()) { 6553 Diag(StaticLoc, diag::err_unspecified_size_with_static); 6554 StaticLoc = SourceLocation(); // Drop the static. 6555 } 6556 } 6557 6558 // If there was an error parsing the assignment-expression, recover. 6559 if (NumElements.isInvalid()) { 6560 D.setInvalidType(true); 6561 // If the expression was invalid, skip it. 6562 SkipUntil(tok::r_square, StopAtSemi); 6563 return; 6564 } 6565 6566 T.consumeClose(); 6567 6568 MaybeParseCXX11Attributes(DS.getAttributes()); 6569 6570 // Remember that we parsed a array type, and remember its features. 6571 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(), 6572 StaticLoc.isValid(), isStar, 6573 NumElements.get(), 6574 T.getOpenLocation(), 6575 T.getCloseLocation()), 6576 DS.getAttributes(), T.getCloseLocation()); 6577} 6578 6579/// Diagnose brackets before an identifier. 6580void Parser::ParseMisplacedBracketDeclarator(Declarator &D) { 6581 assert(Tok.is(tok::l_square) && "Missing opening bracket"); 6582 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier"); 6583 6584 SourceLocation StartBracketLoc = Tok.getLocation(); 6585 Declarator TempDeclarator(D.getDeclSpec(), D.getContext()); 6586 6587 while (Tok.is(tok::l_square)) { 6588 ParseBracketDeclarator(TempDeclarator); 6589 } 6590 6591 // Stuff the location of the start of the brackets into the Declarator. 6592 // The diagnostics from ParseDirectDeclarator will make more sense if 6593 // they use this location instead. 6594 if (Tok.is(tok::semi)) 6595 D.getName().EndLocation = StartBracketLoc; 6596 6597 SourceLocation SuggestParenLoc = Tok.getLocation(); 6598 6599 // Now that the brackets are removed, try parsing the declarator again. 6600 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 6601 6602 // Something went wrong parsing the brackets, in which case, 6603 // ParseBracketDeclarator has emitted an error, and we don't need to emit 6604 // one here. 6605 if (TempDeclarator.getNumTypeObjects() == 0) 6606 return; 6607 6608 // Determine if parens will need to be suggested in the diagnostic. 6609 bool NeedParens = false; 6610 if (D.getNumTypeObjects() != 0) { 6611 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) { 6612 case DeclaratorChunk::Pointer: 6613 case DeclaratorChunk::Reference: 6614 case DeclaratorChunk::BlockPointer: 6615 case DeclaratorChunk::MemberPointer: 6616 case DeclaratorChunk::Pipe: 6617 NeedParens = true; 6618 break; 6619 case DeclaratorChunk::Array: 6620 case DeclaratorChunk::Function: 6621 case DeclaratorChunk::Paren: 6622 break; 6623 } 6624 } 6625 6626 if (NeedParens) { 6627 // Create a DeclaratorChunk for the inserted parens. 6628 ParsedAttributes attrs(AttrFactory); 6629 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd()); 6630 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), attrs, 6631 SourceLocation()); 6632 } 6633 6634 // Adding back the bracket info to the end of the Declarator. 6635 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) { 6636 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i); 6637 ParsedAttributes attrs(AttrFactory); 6638 attrs.set(Chunk.Common.AttrList); 6639 D.AddTypeInfo(Chunk, attrs, SourceLocation()); 6640 } 6641 6642 // The missing identifier would have been diagnosed in ParseDirectDeclarator. 6643 // If parentheses are required, always suggest them. 6644 if (!D.getIdentifier() && !NeedParens) 6645 return; 6646 6647 SourceLocation EndBracketLoc = TempDeclarator.getLocEnd(); 6648 6649 // Generate the move bracket error message. 6650 SourceRange BracketRange(StartBracketLoc, EndBracketLoc); 6651 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd()); 6652 6653 if (NeedParens) { 6654 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id) 6655 << getLangOpts().CPlusPlus 6656 << FixItHint::CreateInsertion(SuggestParenLoc, "(") 6657 << FixItHint::CreateInsertion(EndLoc, ")") 6658 << FixItHint::CreateInsertionFromRange( 6659 EndLoc, CharSourceRange(BracketRange, true)) 6660 << FixItHint::CreateRemoval(BracketRange); 6661 } else { 6662 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id) 6663 << getLangOpts().CPlusPlus 6664 << FixItHint::CreateInsertionFromRange( 6665 EndLoc, CharSourceRange(BracketRange, true)) 6666 << FixItHint::CreateRemoval(BracketRange); 6667 } 6668} 6669 6670/// [GNU] typeof-specifier: 6671/// typeof ( expressions ) 6672/// typeof ( type-name ) 6673/// [GNU/C++] typeof unary-expression 6674/// 6675void Parser::ParseTypeofSpecifier(DeclSpec &DS) { 6676 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier"); 6677 Token OpTok = Tok; 6678 SourceLocation StartLoc = ConsumeToken(); 6679 6680 const bool hasParens = Tok.is(tok::l_paren); 6681 6682 EnterExpressionEvaluationContext Unevaluated( 6683 Actions, Sema::ExpressionEvaluationContext::Unevaluated, 6684 Sema::ReuseLambdaContextDecl); 6685 6686 bool isCastExpr; 6687 ParsedType CastTy; 6688 SourceRange CastRange; 6689 ExprResult Operand = Actions.CorrectDelayedTyposInExpr( 6690 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange)); 6691 if (hasParens) 6692 DS.setTypeofParensRange(CastRange); 6693 6694 if (CastRange.getEnd().isInvalid()) 6695 // FIXME: Not accurate, the range gets one token more than it should. 6696 DS.SetRangeEnd(Tok.getLocation()); 6697 else 6698 DS.SetRangeEnd(CastRange.getEnd()); 6699 6700 if (isCastExpr) { 6701 if (!CastTy) { 6702 DS.SetTypeSpecError(); 6703 return; 6704 } 6705 6706 const char *PrevSpec = nullptr; 6707 unsigned DiagID; 6708 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 6709 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, 6710 DiagID, CastTy, 6711 Actions.getASTContext().getPrintingPolicy())) 6712 Diag(StartLoc, DiagID) << PrevSpec; 6713 return; 6714 } 6715 6716 // If we get here, the operand to the typeof was an expression. 6717 if (Operand.isInvalid()) { 6718 DS.SetTypeSpecError(); 6719 return; 6720 } 6721 6722 // We might need to transform the operand if it is potentially evaluated. 6723 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get()); 6724 if (Operand.isInvalid()) { 6725 DS.SetTypeSpecError(); 6726 return; 6727 } 6728 6729 const char *PrevSpec = nullptr; 6730 unsigned DiagID; 6731 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 6732 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 6733 DiagID, Operand.get(), 6734 Actions.getASTContext().getPrintingPolicy())) 6735 Diag(StartLoc, DiagID) << PrevSpec; 6736} 6737 6738/// [C11] atomic-specifier: 6739/// _Atomic ( type-name ) 6740/// 6741void Parser::ParseAtomicSpecifier(DeclSpec &DS) { 6742 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) && 6743 "Not an atomic specifier"); 6744 6745 SourceLocation StartLoc = ConsumeToken(); 6746 BalancedDelimiterTracker T(*this, tok::l_paren); 6747 if (T.consumeOpen()) 6748 return; 6749 6750 TypeResult Result = ParseTypeName(); 6751 if (Result.isInvalid()) { 6752 SkipUntil(tok::r_paren, StopAtSemi); 6753 return; 6754 } 6755 6756 // Match the ')' 6757 T.consumeClose(); 6758 6759 if (T.getCloseLocation().isInvalid()) 6760 return; 6761 6762 DS.setTypeofParensRange(T.getRange()); 6763 DS.SetRangeEnd(T.getCloseLocation()); 6764 6765 const char *PrevSpec = nullptr; 6766 unsigned DiagID; 6767 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec, 6768 DiagID, Result.get(), 6769 Actions.getASTContext().getPrintingPolicy())) 6770 Diag(StartLoc, DiagID) << PrevSpec; 6771} 6772 6773/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called 6774/// from TryAltiVecVectorToken. 6775bool Parser::TryAltiVecVectorTokenOutOfLine() { 6776 Token Next = NextToken(); 6777 switch (Next.getKind()) { 6778 default: return false; 6779 case tok::kw_short: 6780 case tok::kw_long: 6781 case tok::kw_signed: 6782 case tok::kw_unsigned: 6783 case tok::kw_void: 6784 case tok::kw_char: 6785 case tok::kw_int: 6786 case tok::kw_float: 6787 case tok::kw_double: 6788 case tok::kw_bool: 6789 case tok::kw___bool: 6790 case tok::kw___pixel: 6791 Tok.setKind(tok::kw___vector); 6792 return true; 6793 case tok::identifier: 6794 if (Next.getIdentifierInfo() == Ident_pixel) { 6795 Tok.setKind(tok::kw___vector); 6796 return true; 6797 } 6798 if (Next.getIdentifierInfo() == Ident_bool) { 6799 Tok.setKind(tok::kw___vector); 6800 return true; 6801 } 6802 return false; 6803 } 6804} 6805 6806bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, 6807 const char *&PrevSpec, unsigned &DiagID, 6808 bool &isInvalid) { 6809 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); 6810 if (Tok.getIdentifierInfo() == Ident_vector) { 6811 Token Next = NextToken(); 6812 switch (Next.getKind()) { 6813 case tok::kw_short: 6814 case tok::kw_long: 6815 case tok::kw_signed: 6816 case tok::kw_unsigned: 6817 case tok::kw_void: 6818 case tok::kw_char: 6819 case tok::kw_int: 6820 case tok::kw_float: 6821 case tok::kw_double: 6822 case tok::kw_bool: 6823 case tok::kw___bool: 6824 case tok::kw___pixel: 6825 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy); 6826 return true; 6827 case tok::identifier: 6828 if (Next.getIdentifierInfo() == Ident_pixel) { 6829 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy); 6830 return true; 6831 } 6832 if (Next.getIdentifierInfo() == Ident_bool) { 6833 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy); 6834 return true; 6835 } 6836 break; 6837 default: 6838 break; 6839 } 6840 } else if ((Tok.getIdentifierInfo() == Ident_pixel) && 6841 DS.isTypeAltiVecVector()) { 6842 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy); 6843 return true; 6844 } else if ((Tok.getIdentifierInfo() == Ident_bool) && 6845 DS.isTypeAltiVecVector()) { 6846 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy); 6847 return true; 6848 } 6849 return false; 6850} 6851