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