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 #define GENERIC_IMAGE_TYPE(ImgType, Id) \ 3367 case tok::kw_##ImgType##_t: \ 3368 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \ 3369 DiagID, Policy); \ 3370 break; 3371 #include "clang/Basic/OpenCLImageTypes.def" 3372 case tok::kw___unknown_anytype: 3373 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc, 3374 PrevSpec, DiagID, Policy); 3375 break; 3376 3377 // class-specifier: 3378 case tok::kw_class: 3379 case tok::kw_struct: 3380 case tok::kw___interface: 3381 case tok::kw_union: { 3382 tok::TokenKind Kind = Tok.getKind(); 3383 ConsumeToken(); 3384 3385 // These are attributes following class specifiers. 3386 // To produce better diagnostic, we parse them when 3387 // parsing class specifier. 3388 ParsedAttributesWithRange Attributes(AttrFactory); 3389 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS, 3390 EnteringContext, DSContext, Attributes); 3391 3392 // If there are attributes following class specifier, 3393 // take them over and handle them here. 3394 if (!Attributes.empty()) { 3395 AttrsLastTime = true; 3396 attrs.takeAllFrom(Attributes); 3397 } 3398 continue; 3399 } 3400 3401 // enum-specifier: 3402 case tok::kw_enum: 3403 ConsumeToken(); 3404 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext); 3405 continue; 3406 3407 // cv-qualifier: 3408 case tok::kw_const: 3409 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID, 3410 getLangOpts()); 3411 break; 3412 case tok::kw_volatile: 3413 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 3414 getLangOpts()); 3415 break; 3416 case tok::kw_restrict: 3417 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 3418 getLangOpts()); 3419 break; 3420 3421 // C++ typename-specifier: 3422 case tok::kw_typename: 3423 if (TryAnnotateTypeOrScopeToken()) { 3424 DS.SetTypeSpecError(); 3425 goto DoneWithDeclSpec; 3426 } 3427 if (!Tok.is(tok::kw_typename)) 3428 continue; 3429 break; 3430 3431 // GNU typeof support. 3432 case tok::kw_typeof: 3433 ParseTypeofSpecifier(DS); 3434 continue; 3435 3436 case tok::annot_decltype: 3437 ParseDecltypeSpecifier(DS); 3438 continue; 3439 3440 case tok::kw___underlying_type: 3441 ParseUnderlyingTypeSpecifier(DS); 3442 continue; 3443 3444 case tok::kw__Atomic: 3445 // C11 6.7.2.4/4: 3446 // If the _Atomic keyword is immediately followed by a left parenthesis, 3447 // it is interpreted as a type specifier (with a type name), not as a 3448 // type qualifier. 3449 if (NextToken().is(tok::l_paren)) { 3450 ParseAtomicSpecifier(DS); 3451 continue; 3452 } 3453 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID, 3454 getLangOpts()); 3455 break; 3456 3457 // OpenCL qualifiers: 3458 case tok::kw___generic: 3459 // generic address space is introduced only in OpenCL v2.0 3460 // see OpenCL C Spec v2.0 s6.5.5 3461 if (Actions.getLangOpts().OpenCLVersion < 200) { 3462 DiagID = diag::err_opencl_unknown_type_specifier; 3463 PrevSpec = Tok.getIdentifierInfo()->getNameStart(); 3464 isInvalid = true; 3465 break; 3466 }; 3467 case tok::kw___private: 3468 case tok::kw___global: 3469 case tok::kw___local: 3470 case tok::kw___constant: 3471 case tok::kw___read_only: 3472 case tok::kw___write_only: 3473 case tok::kw___read_write: 3474 ParseOpenCLQualifiers(DS.getAttributes()); 3475 break; 3476 3477 case tok::less: 3478 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for 3479 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous, 3480 // but we support it. 3481 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1) 3482 goto DoneWithDeclSpec; 3483 3484 SourceLocation StartLoc = Tok.getLocation(); 3485 SourceLocation EndLoc; 3486 TypeResult Type = parseObjCProtocolQualifierType(EndLoc); 3487 if (Type.isUsable()) { 3488 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc, 3489 PrevSpec, DiagID, Type.get(), 3490 Actions.getASTContext().getPrintingPolicy())) 3491 Diag(StartLoc, DiagID) << PrevSpec; 3492 3493 DS.SetRangeEnd(EndLoc); 3494 } else { 3495 DS.SetTypeSpecError(); 3496 } 3497 3498 // Need to support trailing type qualifiers (e.g. "id<p> const"). 3499 // If a type specifier follows, it will be diagnosed elsewhere. 3500 continue; 3501 } 3502 // If the specifier wasn't legal, issue a diagnostic. 3503 if (isInvalid) { 3504 assert(PrevSpec && "Method did not return previous specifier!"); 3505 assert(DiagID); 3506 3507 if (DiagID == diag::ext_duplicate_declspec) 3508 Diag(Tok, DiagID) 3509 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation()); 3510 else if (DiagID == diag::err_opencl_unknown_type_specifier) 3511 Diag(Tok, DiagID) << PrevSpec << isStorageClass; 3512 else 3513 Diag(Tok, DiagID) << PrevSpec; 3514 } 3515 3516 DS.SetRangeEnd(Tok.getLocation()); 3517 if (DiagID != diag::err_bool_redeclaration) 3518 ConsumeToken(); 3519 3520 AttrsLastTime = false; 3521 } 3522 } 3523 3524 /// ParseStructDeclaration - Parse a struct declaration without the terminating 3525 /// semicolon. 3526 /// 3527 /// struct-declaration: 3528 /// specifier-qualifier-list struct-declarator-list 3529 /// [GNU] __extension__ struct-declaration 3530 /// [GNU] specifier-qualifier-list 3531 /// struct-declarator-list: 3532 /// struct-declarator 3533 /// struct-declarator-list ',' struct-declarator 3534 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator 3535 /// struct-declarator: 3536 /// declarator 3537 /// [GNU] declarator attributes[opt] 3538 /// declarator[opt] ':' constant-expression 3539 /// [GNU] declarator[opt] ':' constant-expression attributes[opt] 3540 /// 3541 void Parser::ParseStructDeclaration( 3542 ParsingDeclSpec &DS, 3543 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) { 3544 3545 if (Tok.is(tok::kw___extension__)) { 3546 // __extension__ silences extension warnings in the subexpression. 3547 ExtensionRAIIObject O(Diags); // Use RAII to do this. 3548 ConsumeToken(); 3549 return ParseStructDeclaration(DS, FieldsCallback); 3550 } 3551 3552 // Parse the common specifier-qualifiers-list piece. 3553 ParseSpecifierQualifierList(DS); 3554 3555 // If there are no declarators, this is a free-standing declaration 3556 // specifier. Let the actions module cope with it. 3557 if (Tok.is(tok::semi)) { 3558 RecordDecl *AnonRecord = nullptr; 3559 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, 3560 DS, AnonRecord); 3561 assert(!AnonRecord && "Did not expect anonymous struct or union here"); 3562 DS.complete(TheDecl); 3563 return; 3564 } 3565 3566 // Read struct-declarators until we find the semicolon. 3567 bool FirstDeclarator = true; 3568 SourceLocation CommaLoc; 3569 while (1) { 3570 ParsingFieldDeclarator DeclaratorInfo(*this, DS); 3571 DeclaratorInfo.D.setCommaLoc(CommaLoc); 3572 3573 // Attributes are only allowed here on successive declarators. 3574 if (!FirstDeclarator) 3575 MaybeParseGNUAttributes(DeclaratorInfo.D); 3576 3577 /// struct-declarator: declarator 3578 /// struct-declarator: declarator[opt] ':' constant-expression 3579 if (Tok.isNot(tok::colon)) { 3580 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 3581 ColonProtectionRAIIObject X(*this); 3582 ParseDeclarator(DeclaratorInfo.D); 3583 } else 3584 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation()); 3585 3586 if (TryConsumeToken(tok::colon)) { 3587 ExprResult Res(ParseConstantExpression()); 3588 if (Res.isInvalid()) 3589 SkipUntil(tok::semi, StopBeforeMatch); 3590 else 3591 DeclaratorInfo.BitfieldSize = Res.get(); 3592 } 3593 3594 // If attributes exist after the declarator, parse them. 3595 MaybeParseGNUAttributes(DeclaratorInfo.D); 3596 3597 // We're done with this declarator; invoke the callback. 3598 FieldsCallback(DeclaratorInfo); 3599 3600 // If we don't have a comma, it is either the end of the list (a ';') 3601 // or an error, bail out. 3602 if (!TryConsumeToken(tok::comma, CommaLoc)) 3603 return; 3604 3605 FirstDeclarator = false; 3606 } 3607 } 3608 3609 /// ParseStructUnionBody 3610 /// struct-contents: 3611 /// struct-declaration-list 3612 /// [EXT] empty 3613 /// [GNU] "struct-declaration-list" without terminatoring ';' 3614 /// struct-declaration-list: 3615 /// struct-declaration 3616 /// struct-declaration-list struct-declaration 3617 /// [OBC] '@' 'defs' '(' class-name ')' 3618 /// 3619 void Parser::ParseStructUnionBody(SourceLocation RecordLoc, 3620 unsigned TagType, Decl *TagDecl) { 3621 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 3622 "parsing struct/union body"); 3623 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported"); 3624 3625 BalancedDelimiterTracker T(*this, tok::l_brace); 3626 if (T.consumeOpen()) 3627 return; 3628 3629 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); 3630 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 3631 3632 SmallVector<Decl *, 32> FieldDecls; 3633 3634 // While we still have something to read, read the declarations in the struct. 3635 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) && 3636 Tok.isNot(tok::eof)) { 3637 // Each iteration of this loop reads one struct-declaration. 3638 3639 // Check for extraneous top-level semicolon. 3640 if (Tok.is(tok::semi)) { 3641 ConsumeExtraSemi(InsideStruct, TagType); 3642 continue; 3643 } 3644 3645 // Parse _Static_assert declaration. 3646 if (Tok.is(tok::kw__Static_assert)) { 3647 SourceLocation DeclEnd; 3648 ParseStaticAssertDeclaration(DeclEnd); 3649 continue; 3650 } 3651 3652 if (Tok.is(tok::annot_pragma_pack)) { 3653 HandlePragmaPack(); 3654 continue; 3655 } 3656 3657 if (Tok.is(tok::annot_pragma_align)) { 3658 HandlePragmaAlign(); 3659 continue; 3660 } 3661 3662 if (Tok.is(tok::annot_pragma_openmp)) { 3663 // Result can be ignored, because it must be always empty. 3664 AccessSpecifier AS = AS_none; 3665 ParsedAttributesWithRange Attrs(AttrFactory); 3666 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs); 3667 continue; 3668 } 3669 3670 if (!Tok.is(tok::at)) { 3671 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) { 3672 // Install the declarator into the current TagDecl. 3673 Decl *Field = 3674 Actions.ActOnField(getCurScope(), TagDecl, 3675 FD.D.getDeclSpec().getSourceRange().getBegin(), 3676 FD.D, FD.BitfieldSize); 3677 FieldDecls.push_back(Field); 3678 FD.complete(Field); 3679 }; 3680 3681 // Parse all the comma separated declarators. 3682 ParsingDeclSpec DS(*this); 3683 ParseStructDeclaration(DS, CFieldCallback); 3684 } else { // Handle @defs 3685 ConsumeToken(); 3686 if (!Tok.isObjCAtKeyword(tok::objc_defs)) { 3687 Diag(Tok, diag::err_unexpected_at); 3688 SkipUntil(tok::semi); 3689 continue; 3690 } 3691 ConsumeToken(); 3692 ExpectAndConsume(tok::l_paren); 3693 if (!Tok.is(tok::identifier)) { 3694 Diag(Tok, diag::err_expected) << tok::identifier; 3695 SkipUntil(tok::semi); 3696 continue; 3697 } 3698 SmallVector<Decl *, 16> Fields; 3699 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(), 3700 Tok.getIdentifierInfo(), Fields); 3701 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); 3702 ConsumeToken(); 3703 ExpectAndConsume(tok::r_paren); 3704 } 3705 3706 if (TryConsumeToken(tok::semi)) 3707 continue; 3708 3709 if (Tok.is(tok::r_brace)) { 3710 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list); 3711 break; 3712 } 3713 3714 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); 3715 // Skip to end of block or statement to avoid ext-warning on extra ';'. 3716 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 3717 // If we stopped at a ';', eat it. 3718 TryConsumeToken(tok::semi); 3719 } 3720 3721 T.consumeClose(); 3722 3723 ParsedAttributes attrs(AttrFactory); 3724 // If attributes exist after struct contents, parse them. 3725 MaybeParseGNUAttributes(attrs); 3726 3727 Actions.ActOnFields(getCurScope(), 3728 RecordLoc, TagDecl, FieldDecls, 3729 T.getOpenLocation(), T.getCloseLocation(), 3730 attrs.getList()); 3731 StructScope.Exit(); 3732 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, 3733 T.getCloseLocation()); 3734 } 3735 3736 /// ParseEnumSpecifier 3737 /// enum-specifier: [C99 6.7.2.2] 3738 /// 'enum' identifier[opt] '{' enumerator-list '}' 3739 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' 3740 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] 3741 /// '}' attributes[opt] 3742 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt] 3743 /// '}' 3744 /// 'enum' identifier 3745 /// [GNU] 'enum' attributes[opt] identifier 3746 /// 3747 /// [C++11] enum-head '{' enumerator-list[opt] '}' 3748 /// [C++11] enum-head '{' enumerator-list ',' '}' 3749 /// 3750 /// enum-head: [C++11] 3751 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt] 3752 /// enum-key attribute-specifier-seq[opt] nested-name-specifier 3753 /// identifier enum-base[opt] 3754 /// 3755 /// enum-key: [C++11] 3756 /// 'enum' 3757 /// 'enum' 'class' 3758 /// 'enum' 'struct' 3759 /// 3760 /// enum-base: [C++11] 3761 /// ':' type-specifier-seq 3762 /// 3763 /// [C++] elaborated-type-specifier: 3764 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier 3765 /// 3766 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, 3767 const ParsedTemplateInfo &TemplateInfo, 3768 AccessSpecifier AS, DeclSpecContext DSC) { 3769 // Parse the tag portion of this. 3770 if (Tok.is(tok::code_completion)) { 3771 // Code completion for an enum name. 3772 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum); 3773 return cutOffParsing(); 3774 } 3775 3776 // If attributes exist after tag, parse them. 3777 ParsedAttributesWithRange attrs(AttrFactory); 3778 MaybeParseGNUAttributes(attrs); 3779 MaybeParseCXX11Attributes(attrs); 3780 MaybeParseMicrosoftDeclSpecs(attrs); 3781 3782 SourceLocation ScopedEnumKWLoc; 3783 bool IsScopedUsingClassTag = false; 3784 3785 // In C++11, recognize 'enum class' and 'enum struct'. 3786 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) { 3787 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum 3788 : diag::ext_scoped_enum); 3789 IsScopedUsingClassTag = Tok.is(tok::kw_class); 3790 ScopedEnumKWLoc = ConsumeToken(); 3791 3792 // Attributes are not allowed between these keywords. Diagnose, 3793 // but then just treat them like they appeared in the right place. 3794 ProhibitAttributes(attrs); 3795 3796 // They are allowed afterwards, though. 3797 MaybeParseGNUAttributes(attrs); 3798 MaybeParseCXX11Attributes(attrs); 3799 MaybeParseMicrosoftDeclSpecs(attrs); 3800 } 3801 3802 // C++11 [temp.explicit]p12: 3803 // The usual access controls do not apply to names used to specify 3804 // explicit instantiations. 3805 // We extend this to also cover explicit specializations. Note that 3806 // we don't suppress if this turns out to be an elaborated type 3807 // specifier. 3808 bool shouldDelayDiagsInTag = 3809 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation || 3810 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization); 3811 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag); 3812 3813 // Enum definitions should not be parsed in a trailing-return-type. 3814 bool AllowDeclaration = DSC != DSC_trailing; 3815 3816 bool AllowFixedUnderlyingType = AllowDeclaration && 3817 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt || 3818 getLangOpts().ObjC2); 3819 3820 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3821 if (getLangOpts().CPlusPlus) { 3822 // "enum foo : bar;" is not a potential typo for "enum foo::bar;" 3823 // if a fixed underlying type is allowed. 3824 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType); 3825 3826 CXXScopeSpec Spec; 3827 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, 3828 /*EnteringContext=*/true)) 3829 return; 3830 3831 if (Spec.isSet() && Tok.isNot(tok::identifier)) { 3832 Diag(Tok, diag::err_expected) << tok::identifier; 3833 if (Tok.isNot(tok::l_brace)) { 3834 // Has no name and is not a definition. 3835 // Skip the rest of this declarator, up until the comma or semicolon. 3836 SkipUntil(tok::comma, StopAtSemi); 3837 return; 3838 } 3839 } 3840 3841 SS = Spec; 3842 } 3843 3844 // Must have either 'enum name' or 'enum {...}'. 3845 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) && 3846 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) { 3847 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace; 3848 3849 // Skip the rest of this declarator, up until the comma or semicolon. 3850 SkipUntil(tok::comma, StopAtSemi); 3851 return; 3852 } 3853 3854 // If an identifier is present, consume and remember it. 3855 IdentifierInfo *Name = nullptr; 3856 SourceLocation NameLoc; 3857 if (Tok.is(tok::identifier)) { 3858 Name = Tok.getIdentifierInfo(); 3859 NameLoc = ConsumeToken(); 3860 } 3861 3862 if (!Name && ScopedEnumKWLoc.isValid()) { 3863 // C++0x 7.2p2: The optional identifier shall not be omitted in the 3864 // declaration of a scoped enumeration. 3865 Diag(Tok, diag::err_scoped_enum_missing_identifier); 3866 ScopedEnumKWLoc = SourceLocation(); 3867 IsScopedUsingClassTag = false; 3868 } 3869 3870 // Okay, end the suppression area. We'll decide whether to emit the 3871 // diagnostics in a second. 3872 if (shouldDelayDiagsInTag) 3873 diagsFromTag.done(); 3874 3875 TypeResult BaseType; 3876 3877 // Parse the fixed underlying type. 3878 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope; 3879 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) { 3880 bool PossibleBitfield = false; 3881 if (CanBeBitfield) { 3882 // If we're in class scope, this can either be an enum declaration with 3883 // an underlying type, or a declaration of a bitfield member. We try to 3884 // use a simple disambiguation scheme first to catch the common cases 3885 // (integer literal, sizeof); if it's still ambiguous, we then consider 3886 // anything that's a simple-type-specifier followed by '(' as an 3887 // expression. This suffices because function types are not valid 3888 // underlying types anyway. 3889 EnterExpressionEvaluationContext Unevaluated(Actions, 3890 Sema::ConstantEvaluated); 3891 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind()); 3892 // If the next token starts an expression, we know we're parsing a 3893 // bit-field. This is the common case. 3894 if (TPR == TPResult::True) 3895 PossibleBitfield = true; 3896 // If the next token starts a type-specifier-seq, it may be either a 3897 // a fixed underlying type or the start of a function-style cast in C++; 3898 // lookahead one more token to see if it's obvious that we have a 3899 // fixed underlying type. 3900 else if (TPR == TPResult::False && 3901 GetLookAheadToken(2).getKind() == tok::semi) { 3902 // Consume the ':'. 3903 ConsumeToken(); 3904 } else { 3905 // We have the start of a type-specifier-seq, so we have to perform 3906 // tentative parsing to determine whether we have an expression or a 3907 // type. 3908 TentativeParsingAction TPA(*this); 3909 3910 // Consume the ':'. 3911 ConsumeToken(); 3912 3913 // If we see a type specifier followed by an open-brace, we have an 3914 // ambiguity between an underlying type and a C++11 braced 3915 // function-style cast. Resolve this by always treating it as an 3916 // underlying type. 3917 // FIXME: The standard is not entirely clear on how to disambiguate in 3918 // this case. 3919 if ((getLangOpts().CPlusPlus && 3920 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) || 3921 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) { 3922 // We'll parse this as a bitfield later. 3923 PossibleBitfield = true; 3924 TPA.Revert(); 3925 } else { 3926 // We have a type-specifier-seq. 3927 TPA.Commit(); 3928 } 3929 } 3930 } else { 3931 // Consume the ':'. 3932 ConsumeToken(); 3933 } 3934 3935 if (!PossibleBitfield) { 3936 SourceRange Range; 3937 BaseType = ParseTypeName(&Range); 3938 3939 if (getLangOpts().CPlusPlus11) { 3940 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type); 3941 } else if (!getLangOpts().ObjC2) { 3942 if (getLangOpts().CPlusPlus) 3943 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range; 3944 else 3945 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range; 3946 } 3947 } 3948 } 3949 3950 // There are four options here. If we have 'friend enum foo;' then this is a 3951 // friend declaration, and cannot have an accompanying definition. If we have 3952 // 'enum foo;', then this is a forward declaration. If we have 3953 // 'enum foo {...' then this is a definition. Otherwise we have something 3954 // like 'enum foo xyz', a reference. 3955 // 3956 // This is needed to handle stuff like this right (C99 6.7.2.3p11): 3957 // enum foo {..}; void bar() { enum foo; } <- new foo in bar. 3958 // enum foo {..}; void bar() { enum foo x; } <- use of old foo. 3959 // 3960 Sema::TagUseKind TUK; 3961 if (!AllowDeclaration) { 3962 TUK = Sema::TUK_Reference; 3963 } else if (Tok.is(tok::l_brace)) { 3964 if (DS.isFriendSpecified()) { 3965 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type) 3966 << SourceRange(DS.getFriendSpecLoc()); 3967 ConsumeBrace(); 3968 SkipUntil(tok::r_brace, StopAtSemi); 3969 TUK = Sema::TUK_Friend; 3970 } else { 3971 TUK = Sema::TUK_Definition; 3972 } 3973 } else if (!isTypeSpecifier(DSC) && 3974 (Tok.is(tok::semi) || 3975 (Tok.isAtStartOfLine() && 3976 !isValidAfterTypeSpecifier(CanBeBitfield)))) { 3977 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration; 3978 if (Tok.isNot(tok::semi)) { 3979 // A semicolon was missing after this declaration. Diagnose and recover. 3980 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum"); 3981 PP.EnterToken(Tok); 3982 Tok.setKind(tok::semi); 3983 } 3984 } else { 3985 TUK = Sema::TUK_Reference; 3986 } 3987 3988 // If this is an elaborated type specifier, and we delayed 3989 // diagnostics before, just merge them into the current pool. 3990 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) { 3991 diagsFromTag.redelay(); 3992 } 3993 3994 MultiTemplateParamsArg TParams; 3995 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 3996 TUK != Sema::TUK_Reference) { 3997 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) { 3998 // Skip the rest of this declarator, up until the comma or semicolon. 3999 Diag(Tok, diag::err_enum_template); 4000 SkipUntil(tok::comma, StopAtSemi); 4001 return; 4002 } 4003 4004 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { 4005 // Enumerations can't be explicitly instantiated. 4006 DS.SetTypeSpecError(); 4007 Diag(StartLoc, diag::err_explicit_instantiation_enum); 4008 return; 4009 } 4010 4011 assert(TemplateInfo.TemplateParams && "no template parameters"); 4012 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(), 4013 TemplateInfo.TemplateParams->size()); 4014 } 4015 4016 if (TUK == Sema::TUK_Reference) 4017 ProhibitAttributes(attrs); 4018 4019 if (!Name && TUK != Sema::TUK_Definition) { 4020 Diag(Tok, diag::err_enumerator_unnamed_no_def); 4021 4022 // Skip the rest of this declarator, up until the comma or semicolon. 4023 SkipUntil(tok::comma, StopAtSemi); 4024 return; 4025 } 4026 4027 handleDeclspecAlignBeforeClassKey(attrs, DS, TUK); 4028 4029 Sema::SkipBodyInfo SkipBody; 4030 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) && 4031 NextToken().is(tok::identifier)) 4032 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(), 4033 NextToken().getIdentifierInfo(), 4034 NextToken().getLocation()); 4035 4036 bool Owned = false; 4037 bool IsDependent = false; 4038 const char *PrevSpec = nullptr; 4039 unsigned DiagID; 4040 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, 4041 StartLoc, SS, Name, NameLoc, attrs.getList(), 4042 AS, DS.getModulePrivateSpecLoc(), TParams, 4043 Owned, IsDependent, ScopedEnumKWLoc, 4044 IsScopedUsingClassTag, BaseType, 4045 DSC == DSC_type_specifier, &SkipBody); 4046 4047 if (SkipBody.ShouldSkip) { 4048 assert(TUK == Sema::TUK_Definition && "can only skip a definition"); 4049 4050 BalancedDelimiterTracker T(*this, tok::l_brace); 4051 T.consumeOpen(); 4052 T.skipToEnd(); 4053 4054 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, 4055 NameLoc.isValid() ? NameLoc : StartLoc, 4056 PrevSpec, DiagID, TagDecl, Owned, 4057 Actions.getASTContext().getPrintingPolicy())) 4058 Diag(StartLoc, DiagID) << PrevSpec; 4059 return; 4060 } 4061 4062 if (IsDependent) { 4063 // This enum has a dependent nested-name-specifier. Handle it as a 4064 // dependent tag. 4065 if (!Name) { 4066 DS.SetTypeSpecError(); 4067 Diag(Tok, diag::err_expected_type_name_after_typename); 4068 return; 4069 } 4070 4071 TypeResult Type = Actions.ActOnDependentTag( 4072 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc); 4073 if (Type.isInvalid()) { 4074 DS.SetTypeSpecError(); 4075 return; 4076 } 4077 4078 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, 4079 NameLoc.isValid() ? NameLoc : StartLoc, 4080 PrevSpec, DiagID, Type.get(), 4081 Actions.getASTContext().getPrintingPolicy())) 4082 Diag(StartLoc, DiagID) << PrevSpec; 4083 4084 return; 4085 } 4086 4087 if (!TagDecl) { 4088 // The action failed to produce an enumeration tag. If this is a 4089 // definition, consume the entire definition. 4090 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) { 4091 ConsumeBrace(); 4092 SkipUntil(tok::r_brace, StopAtSemi); 4093 } 4094 4095 DS.SetTypeSpecError(); 4096 return; 4097 } 4098 4099 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) 4100 ParseEnumBody(StartLoc, TagDecl); 4101 4102 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, 4103 NameLoc.isValid() ? NameLoc : StartLoc, 4104 PrevSpec, DiagID, TagDecl, Owned, 4105 Actions.getASTContext().getPrintingPolicy())) 4106 Diag(StartLoc, DiagID) << PrevSpec; 4107 } 4108 4109 /// ParseEnumBody - Parse a {} enclosed enumerator-list. 4110 /// enumerator-list: 4111 /// enumerator 4112 /// enumerator-list ',' enumerator 4113 /// enumerator: 4114 /// enumeration-constant attributes[opt] 4115 /// enumeration-constant attributes[opt] '=' constant-expression 4116 /// enumeration-constant: 4117 /// identifier 4118 /// 4119 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) { 4120 // Enter the scope of the enum body and start the definition. 4121 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope); 4122 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl); 4123 4124 BalancedDelimiterTracker T(*this, tok::l_brace); 4125 T.consumeOpen(); 4126 4127 // C does not allow an empty enumerator-list, C++ does [dcl.enum]. 4128 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) 4129 Diag(Tok, diag::error_empty_enum); 4130 4131 SmallVector<Decl *, 32> EnumConstantDecls; 4132 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags; 4133 4134 Decl *LastEnumConstDecl = nullptr; 4135 4136 // Parse the enumerator-list. 4137 while (Tok.isNot(tok::r_brace)) { 4138 // Parse enumerator. If failed, try skipping till the start of the next 4139 // enumerator definition. 4140 if (Tok.isNot(tok::identifier)) { 4141 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; 4142 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) && 4143 TryConsumeToken(tok::comma)) 4144 continue; 4145 break; 4146 } 4147 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 4148 SourceLocation IdentLoc = ConsumeToken(); 4149 4150 // If attributes exist after the enumerator, parse them. 4151 ParsedAttributesWithRange attrs(AttrFactory); 4152 MaybeParseGNUAttributes(attrs); 4153 ProhibitAttributes(attrs); // GNU-style attributes are prohibited. 4154 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) { 4155 if (!getLangOpts().CPlusPlus1z) 4156 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute) 4157 << 1 /*enumerator*/; 4158 ParseCXX11Attributes(attrs); 4159 } 4160 4161 SourceLocation EqualLoc; 4162 ExprResult AssignedVal; 4163 EnumAvailabilityDiags.emplace_back(*this); 4164 4165 if (TryConsumeToken(tok::equal, EqualLoc)) { 4166 AssignedVal = ParseConstantExpression(); 4167 if (AssignedVal.isInvalid()) 4168 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch); 4169 } 4170 4171 // Install the enumerator constant into EnumDecl. 4172 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl, 4173 LastEnumConstDecl, 4174 IdentLoc, Ident, 4175 attrs.getList(), EqualLoc, 4176 AssignedVal.get()); 4177 EnumAvailabilityDiags.back().done(); 4178 4179 EnumConstantDecls.push_back(EnumConstDecl); 4180 LastEnumConstDecl = EnumConstDecl; 4181 4182 if (Tok.is(tok::identifier)) { 4183 // We're missing a comma between enumerators. 4184 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); 4185 Diag(Loc, diag::err_enumerator_list_missing_comma) 4186 << FixItHint::CreateInsertion(Loc, ", "); 4187 continue; 4188 } 4189 4190 // Emumerator definition must be finished, only comma or r_brace are 4191 // allowed here. 4192 SourceLocation CommaLoc; 4193 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) { 4194 if (EqualLoc.isValid()) 4195 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace 4196 << tok::comma; 4197 else 4198 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator); 4199 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) { 4200 if (TryConsumeToken(tok::comma, CommaLoc)) 4201 continue; 4202 } else { 4203 break; 4204 } 4205 } 4206 4207 // If comma is followed by r_brace, emit appropriate warning. 4208 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) { 4209 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) 4210 Diag(CommaLoc, getLangOpts().CPlusPlus ? 4211 diag::ext_enumerator_list_comma_cxx : 4212 diag::ext_enumerator_list_comma_c) 4213 << FixItHint::CreateRemoval(CommaLoc); 4214 else if (getLangOpts().CPlusPlus11) 4215 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma) 4216 << FixItHint::CreateRemoval(CommaLoc); 4217 break; 4218 } 4219 } 4220 4221 // Eat the }. 4222 T.consumeClose(); 4223 4224 // If attributes exist after the identifier list, parse them. 4225 ParsedAttributes attrs(AttrFactory); 4226 MaybeParseGNUAttributes(attrs); 4227 4228 Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(), 4229 EnumDecl, EnumConstantDecls, 4230 getCurScope(), 4231 attrs.getList()); 4232 4233 // Now handle enum constant availability diagnostics. 4234 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size()); 4235 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) { 4236 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent); 4237 EnumAvailabilityDiags[i].redelay(); 4238 PD.complete(EnumConstantDecls[i]); 4239 } 4240 4241 EnumScope.Exit(); 4242 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, 4243 T.getCloseLocation()); 4244 4245 // The next token must be valid after an enum definition. If not, a ';' 4246 // was probably forgotten. 4247 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope; 4248 if (!isValidAfterTypeSpecifier(CanBeBitfield)) { 4249 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum"); 4250 // Push this token back into the preprocessor and change our current token 4251 // to ';' so that the rest of the code recovers as though there were an 4252 // ';' after the definition. 4253 PP.EnterToken(Tok); 4254 Tok.setKind(tok::semi); 4255 } 4256 } 4257 4258 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token 4259 /// is definitely a type-specifier. Return false if it isn't part of a type 4260 /// specifier or if we're not sure. 4261 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const { 4262 switch (Tok.getKind()) { 4263 default: return false; 4264 // type-specifiers 4265 case tok::kw_short: 4266 case tok::kw_long: 4267 case tok::kw___int64: 4268 case tok::kw___int128: 4269 case tok::kw_signed: 4270 case tok::kw_unsigned: 4271 case tok::kw__Complex: 4272 case tok::kw__Imaginary: 4273 case tok::kw_void: 4274 case tok::kw_char: 4275 case tok::kw_wchar_t: 4276 case tok::kw_char16_t: 4277 case tok::kw_char32_t: 4278 case tok::kw_int: 4279 case tok::kw_half: 4280 case tok::kw_float: 4281 case tok::kw_double: 4282 case tok::kw_bool: 4283 case tok::kw__Bool: 4284 case tok::kw__Decimal32: 4285 case tok::kw__Decimal64: 4286 case tok::kw__Decimal128: 4287 case tok::kw___vector: 4288 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t: 4289 #include "clang/Basic/OpenCLImageTypes.def" 4290 4291 // struct-or-union-specifier (C99) or class-specifier (C++) 4292 case tok::kw_class: 4293 case tok::kw_struct: 4294 case tok::kw___interface: 4295 case tok::kw_union: 4296 // enum-specifier 4297 case tok::kw_enum: 4298 4299 // typedef-name 4300 case tok::annot_typename: 4301 return true; 4302 } 4303 } 4304 4305 /// isTypeSpecifierQualifier - Return true if the current token could be the 4306 /// start of a specifier-qualifier-list. 4307 bool Parser::isTypeSpecifierQualifier() { 4308 switch (Tok.getKind()) { 4309 default: return false; 4310 4311 case tok::identifier: // foo::bar 4312 if (TryAltiVecVectorToken()) 4313 return true; 4314 // Fall through. 4315 case tok::kw_typename: // typename T::type 4316 // Annotate typenames and C++ scope specifiers. If we get one, just 4317 // recurse to handle whatever we get. 4318 if (TryAnnotateTypeOrScopeToken()) 4319 return true; 4320 if (Tok.is(tok::identifier)) 4321 return false; 4322 return isTypeSpecifierQualifier(); 4323 4324 case tok::coloncolon: // ::foo::bar 4325 if (NextToken().is(tok::kw_new) || // ::new 4326 NextToken().is(tok::kw_delete)) // ::delete 4327 return false; 4328 4329 if (TryAnnotateTypeOrScopeToken()) 4330 return true; 4331 return isTypeSpecifierQualifier(); 4332 4333 // GNU attributes support. 4334 case tok::kw___attribute: 4335 // GNU typeof support. 4336 case tok::kw_typeof: 4337 4338 // type-specifiers 4339 case tok::kw_short: 4340 case tok::kw_long: 4341 case tok::kw___int64: 4342 case tok::kw___int128: 4343 case tok::kw_signed: 4344 case tok::kw_unsigned: 4345 case tok::kw__Complex: 4346 case tok::kw__Imaginary: 4347 case tok::kw_void: 4348 case tok::kw_char: 4349 case tok::kw_wchar_t: 4350 case tok::kw_char16_t: 4351 case tok::kw_char32_t: 4352 case tok::kw_int: 4353 case tok::kw_half: 4354 case tok::kw_float: 4355 case tok::kw_double: 4356 case tok::kw_bool: 4357 case tok::kw__Bool: 4358 case tok::kw__Decimal32: 4359 case tok::kw__Decimal64: 4360 case tok::kw__Decimal128: 4361 case tok::kw___vector: 4362 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t: 4363 #include "clang/Basic/OpenCLImageTypes.def" 4364 4365 // struct-or-union-specifier (C99) or class-specifier (C++) 4366 case tok::kw_class: 4367 case tok::kw_struct: 4368 case tok::kw___interface: 4369 case tok::kw_union: 4370 // enum-specifier 4371 case tok::kw_enum: 4372 4373 // type-qualifier 4374 case tok::kw_const: 4375 case tok::kw_volatile: 4376 case tok::kw_restrict: 4377 4378 // Debugger support. 4379 case tok::kw___unknown_anytype: 4380 4381 // typedef-name 4382 case tok::annot_typename: 4383 return true; 4384 4385 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 4386 case tok::less: 4387 return getLangOpts().ObjC1; 4388 4389 case tok::kw___cdecl: 4390 case tok::kw___stdcall: 4391 case tok::kw___fastcall: 4392 case tok::kw___thiscall: 4393 case tok::kw___vectorcall: 4394 case tok::kw___w64: 4395 case tok::kw___ptr64: 4396 case tok::kw___ptr32: 4397 case tok::kw___pascal: 4398 case tok::kw___unaligned: 4399 4400 case tok::kw__Nonnull: 4401 case tok::kw__Nullable: 4402 case tok::kw__Null_unspecified: 4403 4404 case tok::kw___kindof: 4405 4406 case tok::kw___private: 4407 case tok::kw___local: 4408 case tok::kw___global: 4409 case tok::kw___constant: 4410 case tok::kw___generic: 4411 case tok::kw___read_only: 4412 case tok::kw___read_write: 4413 case tok::kw___write_only: 4414 4415 return true; 4416 4417 // C11 _Atomic 4418 case tok::kw__Atomic: 4419 return true; 4420 } 4421 } 4422 4423 /// isDeclarationSpecifier() - Return true if the current token is part of a 4424 /// declaration specifier. 4425 /// 4426 /// \param DisambiguatingWithExpression True to indicate that the purpose of 4427 /// this check is to disambiguate between an expression and a declaration. 4428 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) { 4429 switch (Tok.getKind()) { 4430 default: return false; 4431 4432 case tok::kw_pipe: 4433 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200); 4434 4435 case tok::identifier: // foo::bar 4436 // Unfortunate hack to support "Class.factoryMethod" notation. 4437 if (getLangOpts().ObjC1 && NextToken().is(tok::period)) 4438 return false; 4439 if (TryAltiVecVectorToken()) 4440 return true; 4441 // Fall through. 4442 case tok::kw_decltype: // decltype(T())::type 4443 case tok::kw_typename: // typename T::type 4444 // Annotate typenames and C++ scope specifiers. If we get one, just 4445 // recurse to handle whatever we get. 4446 if (TryAnnotateTypeOrScopeToken()) 4447 return true; 4448 if (Tok.is(tok::identifier)) 4449 return false; 4450 4451 // If we're in Objective-C and we have an Objective-C class type followed 4452 // by an identifier and then either ':' or ']', in a place where an 4453 // expression is permitted, then this is probably a class message send 4454 // missing the initial '['. In this case, we won't consider this to be 4455 // the start of a declaration. 4456 if (DisambiguatingWithExpression && 4457 isStartOfObjCClassMessageMissingOpenBracket()) 4458 return false; 4459 4460 return isDeclarationSpecifier(); 4461 4462 case tok::coloncolon: // ::foo::bar 4463 if (NextToken().is(tok::kw_new) || // ::new 4464 NextToken().is(tok::kw_delete)) // ::delete 4465 return false; 4466 4467 // Annotate typenames and C++ scope specifiers. If we get one, just 4468 // recurse to handle whatever we get. 4469 if (TryAnnotateTypeOrScopeToken()) 4470 return true; 4471 return isDeclarationSpecifier(); 4472 4473 // storage-class-specifier 4474 case tok::kw_typedef: 4475 case tok::kw_extern: 4476 case tok::kw___private_extern__: 4477 case tok::kw_static: 4478 case tok::kw_auto: 4479 case tok::kw___auto_type: 4480 case tok::kw_register: 4481 case tok::kw___thread: 4482 case tok::kw_thread_local: 4483 case tok::kw__Thread_local: 4484 4485 // Modules 4486 case tok::kw___module_private__: 4487 4488 // Debugger support 4489 case tok::kw___unknown_anytype: 4490 4491 // type-specifiers 4492 case tok::kw_short: 4493 case tok::kw_long: 4494 case tok::kw___int64: 4495 case tok::kw___int128: 4496 case tok::kw_signed: 4497 case tok::kw_unsigned: 4498 case tok::kw__Complex: 4499 case tok::kw__Imaginary: 4500 case tok::kw_void: 4501 case tok::kw_char: 4502 case tok::kw_wchar_t: 4503 case tok::kw_char16_t: 4504 case tok::kw_char32_t: 4505 4506 case tok::kw_int: 4507 case tok::kw_half: 4508 case tok::kw_float: 4509 case tok::kw_double: 4510 case tok::kw_bool: 4511 case tok::kw__Bool: 4512 case tok::kw__Decimal32: 4513 case tok::kw__Decimal64: 4514 case tok::kw__Decimal128: 4515 case tok::kw___vector: 4516 4517 // struct-or-union-specifier (C99) or class-specifier (C++) 4518 case tok::kw_class: 4519 case tok::kw_struct: 4520 case tok::kw_union: 4521 case tok::kw___interface: 4522 // enum-specifier 4523 case tok::kw_enum: 4524 4525 // type-qualifier 4526 case tok::kw_const: 4527 case tok::kw_volatile: 4528 case tok::kw_restrict: 4529 4530 // function-specifier 4531 case tok::kw_inline: 4532 case tok::kw_virtual: 4533 case tok::kw_explicit: 4534 case tok::kw__Noreturn: 4535 4536 // alignment-specifier 4537 case tok::kw__Alignas: 4538 4539 // friend keyword. 4540 case tok::kw_friend: 4541 4542 // static_assert-declaration 4543 case tok::kw__Static_assert: 4544 4545 // GNU typeof support. 4546 case tok::kw_typeof: 4547 4548 // GNU attributes. 4549 case tok::kw___attribute: 4550 4551 // C++11 decltype and constexpr. 4552 case tok::annot_decltype: 4553 case tok::kw_constexpr: 4554 4555 // C++ Concepts TS - concept 4556 case tok::kw_concept: 4557 4558 // C11 _Atomic 4559 case tok::kw__Atomic: 4560 return true; 4561 4562 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 4563 case tok::less: 4564 return getLangOpts().ObjC1; 4565 4566 // typedef-name 4567 case tok::annot_typename: 4568 return !DisambiguatingWithExpression || 4569 !isStartOfObjCClassMessageMissingOpenBracket(); 4570 4571 case tok::kw___declspec: 4572 case tok::kw___cdecl: 4573 case tok::kw___stdcall: 4574 case tok::kw___fastcall: 4575 case tok::kw___thiscall: 4576 case tok::kw___vectorcall: 4577 case tok::kw___w64: 4578 case tok::kw___sptr: 4579 case tok::kw___uptr: 4580 case tok::kw___ptr64: 4581 case tok::kw___ptr32: 4582 case tok::kw___forceinline: 4583 case tok::kw___pascal: 4584 case tok::kw___unaligned: 4585 4586 case tok::kw__Nonnull: 4587 case tok::kw__Nullable: 4588 case tok::kw__Null_unspecified: 4589 4590 case tok::kw___kindof: 4591 4592 case tok::kw___private: 4593 case tok::kw___local: 4594 case tok::kw___global: 4595 case tok::kw___constant: 4596 case tok::kw___generic: 4597 case tok::kw___read_only: 4598 case tok::kw___read_write: 4599 case tok::kw___write_only: 4600 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t: 4601 #include "clang/Basic/OpenCLImageTypes.def" 4602 4603 return true; 4604 } 4605 } 4606 4607 bool Parser::isConstructorDeclarator(bool IsUnqualified) { 4608 TentativeParsingAction TPA(*this); 4609 4610 // Parse the C++ scope specifier. 4611 CXXScopeSpec SS; 4612 if (ParseOptionalCXXScopeSpecifier(SS, nullptr, 4613 /*EnteringContext=*/true)) { 4614 TPA.Revert(); 4615 return false; 4616 } 4617 4618 // Parse the constructor name. 4619 if (Tok.isOneOf(tok::identifier, tok::annot_template_id)) { 4620 // We already know that we have a constructor name; just consume 4621 // the token. 4622 ConsumeToken(); 4623 } else { 4624 TPA.Revert(); 4625 return false; 4626 } 4627 4628 // Current class name must be followed by a left parenthesis. 4629 if (Tok.isNot(tok::l_paren)) { 4630 TPA.Revert(); 4631 return false; 4632 } 4633 ConsumeParen(); 4634 4635 // A right parenthesis, or ellipsis followed by a right parenthesis signals 4636 // that we have a constructor. 4637 if (Tok.is(tok::r_paren) || 4638 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) { 4639 TPA.Revert(); 4640 return true; 4641 } 4642 4643 // A C++11 attribute here signals that we have a constructor, and is an 4644 // attribute on the first constructor parameter. 4645 if (getLangOpts().CPlusPlus11 && 4646 isCXX11AttributeSpecifier(/*Disambiguate*/ false, 4647 /*OuterMightBeMessageSend*/ true)) { 4648 TPA.Revert(); 4649 return true; 4650 } 4651 4652 // If we need to, enter the specified scope. 4653 DeclaratorScopeObj DeclScopeObj(*this, SS); 4654 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS)) 4655 DeclScopeObj.EnterDeclaratorScope(); 4656 4657 // Optionally skip Microsoft attributes. 4658 ParsedAttributes Attrs(AttrFactory); 4659 MaybeParseMicrosoftAttributes(Attrs); 4660 4661 // Check whether the next token(s) are part of a declaration 4662 // specifier, in which case we have the start of a parameter and, 4663 // therefore, we know that this is a constructor. 4664 bool IsConstructor = false; 4665 if (isDeclarationSpecifier()) 4666 IsConstructor = true; 4667 else if (Tok.is(tok::identifier) || 4668 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) { 4669 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type. 4670 // This might be a parenthesized member name, but is more likely to 4671 // be a constructor declaration with an invalid argument type. Keep 4672 // looking. 4673 if (Tok.is(tok::annot_cxxscope)) 4674 ConsumeToken(); 4675 ConsumeToken(); 4676 4677 // If this is not a constructor, we must be parsing a declarator, 4678 // which must have one of the following syntactic forms (see the 4679 // grammar extract at the start of ParseDirectDeclarator): 4680 switch (Tok.getKind()) { 4681 case tok::l_paren: 4682 // C(X ( int)); 4683 case tok::l_square: 4684 // C(X [ 5]); 4685 // C(X [ [attribute]]); 4686 case tok::coloncolon: 4687 // C(X :: Y); 4688 // C(X :: *p); 4689 // Assume this isn't a constructor, rather than assuming it's a 4690 // constructor with an unnamed parameter of an ill-formed type. 4691 break; 4692 4693 case tok::r_paren: 4694 // C(X ) 4695 if (NextToken().is(tok::colon) || NextToken().is(tok::kw_try)) { 4696 // Assume these were meant to be constructors: 4697 // C(X) : (the name of a bit-field cannot be parenthesized). 4698 // C(X) try (this is otherwise ill-formed). 4699 IsConstructor = true; 4700 } 4701 if (NextToken().is(tok::semi) || NextToken().is(tok::l_brace)) { 4702 // If we have a constructor name within the class definition, 4703 // assume these were meant to be constructors: 4704 // C(X) { 4705 // C(X) ; 4706 // ... because otherwise we would be declaring a non-static data 4707 // member that is ill-formed because it's of the same type as its 4708 // surrounding class. 4709 // 4710 // FIXME: We can actually do this whether or not the name is qualified, 4711 // because if it is qualified in this context it must be being used as 4712 // a constructor name. However, we do not implement that rule correctly 4713 // currently, so we're somewhat conservative here. 4714 IsConstructor = IsUnqualified; 4715 } 4716 break; 4717 4718 default: 4719 IsConstructor = true; 4720 break; 4721 } 4722 } 4723 4724 TPA.Revert(); 4725 return IsConstructor; 4726 } 4727 4728 /// ParseTypeQualifierListOpt 4729 /// type-qualifier-list: [C99 6.7.5] 4730 /// type-qualifier 4731 /// [vendor] attributes 4732 /// [ only if AttrReqs & AR_VendorAttributesParsed ] 4733 /// type-qualifier-list type-qualifier 4734 /// [vendor] type-qualifier-list attributes 4735 /// [ only if AttrReqs & AR_VendorAttributesParsed ] 4736 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq 4737 /// [ only if AttReqs & AR_CXX11AttributesParsed ] 4738 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via 4739 /// AttrRequirements bitmask values. 4740 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, unsigned AttrReqs, 4741 bool AtomicAllowed, 4742 bool IdentifierRequired) { 4743 if (getLangOpts().CPlusPlus11 && (AttrReqs & AR_CXX11AttributesParsed) && 4744 isCXX11AttributeSpecifier()) { 4745 ParsedAttributesWithRange attrs(AttrFactory); 4746 ParseCXX11Attributes(attrs); 4747 DS.takeAttributesFrom(attrs); 4748 } 4749 4750 SourceLocation EndLoc; 4751 4752 while (1) { 4753 bool isInvalid = false; 4754 const char *PrevSpec = nullptr; 4755 unsigned DiagID = 0; 4756 SourceLocation Loc = Tok.getLocation(); 4757 4758 switch (Tok.getKind()) { 4759 case tok::code_completion: 4760 Actions.CodeCompleteTypeQualifiers(DS); 4761 return cutOffParsing(); 4762 4763 case tok::kw_const: 4764 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID, 4765 getLangOpts()); 4766 break; 4767 case tok::kw_volatile: 4768 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 4769 getLangOpts()); 4770 break; 4771 case tok::kw_restrict: 4772 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 4773 getLangOpts()); 4774 break; 4775 case tok::kw__Atomic: 4776 if (!AtomicAllowed) 4777 goto DoneWithTypeQuals; 4778 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID, 4779 getLangOpts()); 4780 break; 4781 4782 // OpenCL qualifiers: 4783 case tok::kw___private: 4784 case tok::kw___global: 4785 case tok::kw___local: 4786 case tok::kw___constant: 4787 case tok::kw___generic: 4788 case tok::kw___read_only: 4789 case tok::kw___write_only: 4790 case tok::kw___read_write: 4791 ParseOpenCLQualifiers(DS.getAttributes()); 4792 break; 4793 4794 case tok::kw___uptr: 4795 // GNU libc headers in C mode use '__uptr' as an identifer which conflicts 4796 // with the MS modifier keyword. 4797 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus && 4798 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) { 4799 if (TryKeywordIdentFallback(false)) 4800 continue; 4801 } 4802 case tok::kw___sptr: 4803 case tok::kw___w64: 4804 case tok::kw___ptr64: 4805 case tok::kw___ptr32: 4806 case tok::kw___cdecl: 4807 case tok::kw___stdcall: 4808 case tok::kw___fastcall: 4809 case tok::kw___thiscall: 4810 case tok::kw___vectorcall: 4811 case tok::kw___unaligned: 4812 if (AttrReqs & AR_DeclspecAttributesParsed) { 4813 ParseMicrosoftTypeAttributes(DS.getAttributes()); 4814 continue; 4815 } 4816 goto DoneWithTypeQuals; 4817 case tok::kw___pascal: 4818 if (AttrReqs & AR_VendorAttributesParsed) { 4819 ParseBorlandTypeAttributes(DS.getAttributes()); 4820 continue; 4821 } 4822 goto DoneWithTypeQuals; 4823 4824 // Nullability type specifiers. 4825 case tok::kw__Nonnull: 4826 case tok::kw__Nullable: 4827 case tok::kw__Null_unspecified: 4828 ParseNullabilityTypeSpecifiers(DS.getAttributes()); 4829 continue; 4830 4831 // Objective-C 'kindof' types. 4832 case tok::kw___kindof: 4833 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc, 4834 nullptr, 0, AttributeList::AS_Keyword); 4835 (void)ConsumeToken(); 4836 continue; 4837 4838 case tok::kw___attribute: 4839 if (AttrReqs & AR_GNUAttributesParsedAndRejected) 4840 // When GNU attributes are expressly forbidden, diagnose their usage. 4841 Diag(Tok, diag::err_attributes_not_allowed); 4842 4843 // Parse the attributes even if they are rejected to ensure that error 4844 // recovery is graceful. 4845 if (AttrReqs & AR_GNUAttributesParsed || 4846 AttrReqs & AR_GNUAttributesParsedAndRejected) { 4847 ParseGNUAttributes(DS.getAttributes()); 4848 continue; // do *not* consume the next token! 4849 } 4850 // otherwise, FALL THROUGH! 4851 default: 4852 DoneWithTypeQuals: 4853 // If this is not a type-qualifier token, we're done reading type 4854 // qualifiers. First verify that DeclSpec's are consistent. 4855 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy()); 4856 if (EndLoc.isValid()) 4857 DS.SetRangeEnd(EndLoc); 4858 return; 4859 } 4860 4861 // If the specifier combination wasn't legal, issue a diagnostic. 4862 if (isInvalid) { 4863 assert(PrevSpec && "Method did not return previous specifier!"); 4864 Diag(Tok, DiagID) << PrevSpec; 4865 } 4866 EndLoc = ConsumeToken(); 4867 } 4868 } 4869 4870 /// ParseDeclarator - Parse and verify a newly-initialized declarator. 4871 /// 4872 void Parser::ParseDeclarator(Declarator &D) { 4873 /// This implements the 'declarator' production in the C grammar, then checks 4874 /// for well-formedness and issues diagnostics. 4875 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 4876 } 4877 4878 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang, 4879 unsigned TheContext) { 4880 if (Kind == tok::star || Kind == tok::caret) 4881 return true; 4882 4883 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200)) 4884 return true; 4885 4886 if (!Lang.CPlusPlus) 4887 return false; 4888 4889 if (Kind == tok::amp) 4890 return true; 4891 4892 // We parse rvalue refs in C++03, because otherwise the errors are scary. 4893 // But we must not parse them in conversion-type-ids and new-type-ids, since 4894 // those can be legitimately followed by a && operator. 4895 // (The same thing can in theory happen after a trailing-return-type, but 4896 // since those are a C++11 feature, there is no rejects-valid issue there.) 4897 if (Kind == tok::ampamp) 4898 return Lang.CPlusPlus11 || (TheContext != Declarator::ConversionIdContext && 4899 TheContext != Declarator::CXXNewContext); 4900 4901 return false; 4902 } 4903 4904 // Indicates whether the given declarator is a pipe declarator. 4905 static bool isPipeDeclerator(const Declarator &D) { 4906 const unsigned NumTypes = D.getNumTypeObjects(); 4907 4908 for (unsigned Idx = 0; Idx != NumTypes; ++Idx) 4909 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind) 4910 return true; 4911 4912 return false; 4913 } 4914 4915 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator 4916 /// is parsed by the function passed to it. Pass null, and the direct-declarator 4917 /// isn't parsed at all, making this function effectively parse the C++ 4918 /// ptr-operator production. 4919 /// 4920 /// If the grammar of this construct is extended, matching changes must also be 4921 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to 4922 /// isConstructorDeclarator. 4923 /// 4924 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl] 4925 /// [C] pointer[opt] direct-declarator 4926 /// [C++] direct-declarator 4927 /// [C++] ptr-operator declarator 4928 /// 4929 /// pointer: [C99 6.7.5] 4930 /// '*' type-qualifier-list[opt] 4931 /// '*' type-qualifier-list[opt] pointer 4932 /// 4933 /// ptr-operator: 4934 /// '*' cv-qualifier-seq[opt] 4935 /// '&' 4936 /// [C++0x] '&&' 4937 /// [GNU] '&' restrict[opt] attributes[opt] 4938 /// [GNU?] '&&' restrict[opt] attributes[opt] 4939 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 4940 void Parser::ParseDeclaratorInternal(Declarator &D, 4941 DirectDeclParseFunction DirectDeclParser) { 4942 if (Diags.hasAllExtensionsSilenced()) 4943 D.setExtension(); 4944 4945 // C++ member pointers start with a '::' or a nested-name. 4946 // Member pointers get special handling, since there's no place for the 4947 // scope spec in the generic path below. 4948 if (getLangOpts().CPlusPlus && 4949 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) || 4950 (Tok.is(tok::identifier) && 4951 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) || 4952 Tok.is(tok::annot_cxxscope))) { 4953 bool EnteringContext = D.getContext() == Declarator::FileContext || 4954 D.getContext() == Declarator::MemberContext; 4955 CXXScopeSpec SS; 4956 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext); 4957 4958 if (SS.isNotEmpty()) { 4959 if (Tok.isNot(tok::star)) { 4960 // The scope spec really belongs to the direct-declarator. 4961 if (D.mayHaveIdentifier()) 4962 D.getCXXScopeSpec() = SS; 4963 else 4964 AnnotateScopeToken(SS, true); 4965 4966 if (DirectDeclParser) 4967 (this->*DirectDeclParser)(D); 4968 return; 4969 } 4970 4971 SourceLocation Loc = ConsumeToken(); 4972 D.SetRangeEnd(Loc); 4973 DeclSpec DS(AttrFactory); 4974 ParseTypeQualifierListOpt(DS); 4975 D.ExtendWithDeclSpec(DS); 4976 4977 // Recurse to parse whatever is left. 4978 ParseDeclaratorInternal(D, DirectDeclParser); 4979 4980 // Sema will have to catch (syntactically invalid) pointers into global 4981 // scope. It has to catch pointers into namespace scope anyway. 4982 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(), 4983 DS.getLocEnd()), 4984 DS.getAttributes(), 4985 /* Don't replace range end. */SourceLocation()); 4986 return; 4987 } 4988 } 4989 4990 tok::TokenKind Kind = Tok.getKind(); 4991 4992 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) { 4993 DeclSpec DS(AttrFactory); 4994 ParseTypeQualifierListOpt(DS); 4995 4996 D.AddTypeInfo( 4997 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()), 4998 DS.getAttributes(), SourceLocation()); 4999 } 5000 5001 // Not a pointer, C++ reference, or block. 5002 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) { 5003 if (DirectDeclParser) 5004 (this->*DirectDeclParser)(D); 5005 return; 5006 } 5007 5008 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference, 5009 // '&&' -> rvalue reference 5010 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&. 5011 D.SetRangeEnd(Loc); 5012 5013 if (Kind == tok::star || Kind == tok::caret) { 5014 // Is a pointer. 5015 DeclSpec DS(AttrFactory); 5016 5017 // GNU attributes are not allowed here in a new-type-id, but Declspec and 5018 // C++11 attributes are allowed. 5019 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed | 5020 ((D.getContext() != Declarator::CXXNewContext) 5021 ? AR_GNUAttributesParsed 5022 : AR_GNUAttributesParsedAndRejected); 5023 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier()); 5024 D.ExtendWithDeclSpec(DS); 5025 5026 // Recursively parse the declarator. 5027 ParseDeclaratorInternal(D, DirectDeclParser); 5028 if (Kind == tok::star) 5029 // Remember that we parsed a pointer type, and remember the type-quals. 5030 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc, 5031 DS.getConstSpecLoc(), 5032 DS.getVolatileSpecLoc(), 5033 DS.getRestrictSpecLoc(), 5034 DS.getAtomicSpecLoc()), 5035 DS.getAttributes(), 5036 SourceLocation()); 5037 else 5038 // Remember that we parsed a Block type, and remember the type-quals. 5039 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), 5040 Loc), 5041 DS.getAttributes(), 5042 SourceLocation()); 5043 } else { 5044 // Is a reference 5045 DeclSpec DS(AttrFactory); 5046 5047 // Complain about rvalue references in C++03, but then go on and build 5048 // the declarator. 5049 if (Kind == tok::ampamp) 5050 Diag(Loc, getLangOpts().CPlusPlus11 ? 5051 diag::warn_cxx98_compat_rvalue_reference : 5052 diag::ext_rvalue_reference); 5053 5054 // GNU-style and C++11 attributes are allowed here, as is restrict. 5055 ParseTypeQualifierListOpt(DS); 5056 D.ExtendWithDeclSpec(DS); 5057 5058 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the 5059 // cv-qualifiers are introduced through the use of a typedef or of a 5060 // template type argument, in which case the cv-qualifiers are ignored. 5061 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { 5062 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5063 Diag(DS.getConstSpecLoc(), 5064 diag::err_invalid_reference_qualifier_application) << "const"; 5065 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5066 Diag(DS.getVolatileSpecLoc(), 5067 diag::err_invalid_reference_qualifier_application) << "volatile"; 5068 // 'restrict' is permitted as an extension. 5069 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5070 Diag(DS.getAtomicSpecLoc(), 5071 diag::err_invalid_reference_qualifier_application) << "_Atomic"; 5072 } 5073 5074 // Recursively parse the declarator. 5075 ParseDeclaratorInternal(D, DirectDeclParser); 5076 5077 if (D.getNumTypeObjects() > 0) { 5078 // C++ [dcl.ref]p4: There shall be no references to references. 5079 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1); 5080 if (InnerChunk.Kind == DeclaratorChunk::Reference) { 5081 if (const IdentifierInfo *II = D.getIdentifier()) 5082 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 5083 << II; 5084 else 5085 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 5086 << "type name"; 5087 5088 // Once we've complained about the reference-to-reference, we 5089 // can go ahead and build the (technically ill-formed) 5090 // declarator: reference collapsing will take care of it. 5091 } 5092 } 5093 5094 // Remember that we parsed a reference type. 5095 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc, 5096 Kind == tok::amp), 5097 DS.getAttributes(), 5098 SourceLocation()); 5099 } 5100 } 5101 5102 // When correcting from misplaced brackets before the identifier, the location 5103 // is saved inside the declarator so that other diagnostic messages can use 5104 // them. This extracts and returns that location, or returns the provided 5105 // location if a stored location does not exist. 5106 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D, 5107 SourceLocation Loc) { 5108 if (D.getName().StartLocation.isInvalid() && 5109 D.getName().EndLocation.isValid()) 5110 return D.getName().EndLocation; 5111 5112 return Loc; 5113 } 5114 5115 /// ParseDirectDeclarator 5116 /// direct-declarator: [C99 6.7.5] 5117 /// [C99] identifier 5118 /// '(' declarator ')' 5119 /// [GNU] '(' attributes declarator ')' 5120 /// [C90] direct-declarator '[' constant-expression[opt] ']' 5121 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 5122 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 5123 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 5124 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 5125 /// [C++11] direct-declarator '[' constant-expression[opt] ']' 5126 /// attribute-specifier-seq[opt] 5127 /// direct-declarator '(' parameter-type-list ')' 5128 /// direct-declarator '(' identifier-list[opt] ')' 5129 /// [GNU] direct-declarator '(' parameter-forward-declarations 5130 /// parameter-type-list[opt] ')' 5131 /// [C++] direct-declarator '(' parameter-declaration-clause ')' 5132 /// cv-qualifier-seq[opt] exception-specification[opt] 5133 /// [C++11] direct-declarator '(' parameter-declaration-clause ')' 5134 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt] 5135 /// ref-qualifier[opt] exception-specification[opt] 5136 /// [C++] declarator-id 5137 /// [C++11] declarator-id attribute-specifier-seq[opt] 5138 /// 5139 /// declarator-id: [C++ 8] 5140 /// '...'[opt] id-expression 5141 /// '::'[opt] nested-name-specifier[opt] type-name 5142 /// 5143 /// id-expression: [C++ 5.1] 5144 /// unqualified-id 5145 /// qualified-id 5146 /// 5147 /// unqualified-id: [C++ 5.1] 5148 /// identifier 5149 /// operator-function-id 5150 /// conversion-function-id 5151 /// '~' class-name 5152 /// template-id 5153 /// 5154 /// Note, any additional constructs added here may need corresponding changes 5155 /// in isConstructorDeclarator. 5156 void Parser::ParseDirectDeclarator(Declarator &D) { 5157 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec()); 5158 5159 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) { 5160 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in 5161 // this context it is a bitfield. Also in range-based for statement colon 5162 // may delimit for-range-declaration. 5163 ColonProtectionRAIIObject X(*this, 5164 D.getContext() == Declarator::MemberContext || 5165 (D.getContext() == Declarator::ForContext && 5166 getLangOpts().CPlusPlus11)); 5167 5168 // ParseDeclaratorInternal might already have parsed the scope. 5169 if (D.getCXXScopeSpec().isEmpty()) { 5170 bool EnteringContext = D.getContext() == Declarator::FileContext || 5171 D.getContext() == Declarator::MemberContext; 5172 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr, 5173 EnteringContext); 5174 } 5175 5176 if (D.getCXXScopeSpec().isValid()) { 5177 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), 5178 D.getCXXScopeSpec())) 5179 // Change the declaration context for name lookup, until this function 5180 // is exited (and the declarator has been parsed). 5181 DeclScopeObj.EnterDeclaratorScope(); 5182 } 5183 5184 // C++0x [dcl.fct]p14: 5185 // There is a syntactic ambiguity when an ellipsis occurs at the end of a 5186 // parameter-declaration-clause without a preceding comma. In this case, 5187 // the ellipsis is parsed as part of the abstract-declarator if the type 5188 // of the parameter either names a template parameter pack that has not 5189 // been expanded or contains auto; otherwise, it is parsed as part of the 5190 // parameter-declaration-clause. 5191 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() && 5192 !((D.getContext() == Declarator::PrototypeContext || 5193 D.getContext() == Declarator::LambdaExprParameterContext || 5194 D.getContext() == Declarator::BlockLiteralContext) && 5195 NextToken().is(tok::r_paren) && 5196 !D.hasGroupingParens() && 5197 !Actions.containsUnexpandedParameterPacks(D) && 5198 D.getDeclSpec().getTypeSpecType() != TST_auto)) { 5199 SourceLocation EllipsisLoc = ConsumeToken(); 5200 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) { 5201 // The ellipsis was put in the wrong place. Recover, and explain to 5202 // the user what they should have done. 5203 ParseDeclarator(D); 5204 if (EllipsisLoc.isValid()) 5205 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D); 5206 return; 5207 } else 5208 D.setEllipsisLoc(EllipsisLoc); 5209 5210 // The ellipsis can't be followed by a parenthesized declarator. We 5211 // check for that in ParseParenDeclarator, after we have disambiguated 5212 // the l_paren token. 5213 } 5214 5215 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id, 5216 tok::tilde)) { 5217 // We found something that indicates the start of an unqualified-id. 5218 // Parse that unqualified-id. 5219 bool AllowConstructorName; 5220 if (D.getDeclSpec().hasTypeSpecifier()) 5221 AllowConstructorName = false; 5222 else if (D.getCXXScopeSpec().isSet()) 5223 AllowConstructorName = 5224 (D.getContext() == Declarator::FileContext || 5225 D.getContext() == Declarator::MemberContext); 5226 else 5227 AllowConstructorName = (D.getContext() == Declarator::MemberContext); 5228 5229 SourceLocation TemplateKWLoc; 5230 bool HadScope = D.getCXXScopeSpec().isValid(); 5231 if (ParseUnqualifiedId(D.getCXXScopeSpec(), 5232 /*EnteringContext=*/true, 5233 /*AllowDestructorName=*/true, AllowConstructorName, 5234 nullptr, TemplateKWLoc, D.getName()) || 5235 // Once we're past the identifier, if the scope was bad, mark the 5236 // whole declarator bad. 5237 D.getCXXScopeSpec().isInvalid()) { 5238 D.SetIdentifier(nullptr, Tok.getLocation()); 5239 D.setInvalidType(true); 5240 } else { 5241 // ParseUnqualifiedId might have parsed a scope specifier during error 5242 // recovery. If it did so, enter that scope. 5243 if (!HadScope && D.getCXXScopeSpec().isValid() && 5244 Actions.ShouldEnterDeclaratorScope(getCurScope(), 5245 D.getCXXScopeSpec())) 5246 DeclScopeObj.EnterDeclaratorScope(); 5247 5248 // Parsed the unqualified-id; update range information and move along. 5249 if (D.getSourceRange().getBegin().isInvalid()) 5250 D.SetRangeBegin(D.getName().getSourceRange().getBegin()); 5251 D.SetRangeEnd(D.getName().getSourceRange().getEnd()); 5252 } 5253 goto PastIdentifier; 5254 } 5255 5256 if (D.getCXXScopeSpec().isNotEmpty()) { 5257 // We have a scope specifier but no following unqualified-id. 5258 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()), 5259 diag::err_expected_unqualified_id) 5260 << /*C++*/1; 5261 D.SetIdentifier(nullptr, Tok.getLocation()); 5262 goto PastIdentifier; 5263 } 5264 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) { 5265 assert(!getLangOpts().CPlusPlus && 5266 "There's a C++-specific check for tok::identifier above"); 5267 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 5268 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 5269 D.SetRangeEnd(Tok.getLocation()); 5270 ConsumeToken(); 5271 goto PastIdentifier; 5272 } else if (Tok.is(tok::identifier) && D.diagnoseIdentifier()) { 5273 // A virt-specifier isn't treated as an identifier if it appears after a 5274 // trailing-return-type. 5275 if (D.getContext() != Declarator::TrailingReturnContext || 5276 !isCXX11VirtSpecifier(Tok)) { 5277 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id) 5278 << FixItHint::CreateRemoval(Tok.getLocation()); 5279 D.SetIdentifier(nullptr, Tok.getLocation()); 5280 ConsumeToken(); 5281 goto PastIdentifier; 5282 } 5283 } 5284 5285 if (Tok.is(tok::l_paren)) { 5286 // direct-declarator: '(' declarator ')' 5287 // direct-declarator: '(' attributes declarator ')' 5288 // Example: 'char (*X)' or 'int (*XX)(void)' 5289 ParseParenDeclarator(D); 5290 5291 // If the declarator was parenthesized, we entered the declarator 5292 // scope when parsing the parenthesized declarator, then exited 5293 // the scope already. Re-enter the scope, if we need to. 5294 if (D.getCXXScopeSpec().isSet()) { 5295 // If there was an error parsing parenthesized declarator, declarator 5296 // scope may have been entered before. Don't do it again. 5297 if (!D.isInvalidType() && 5298 Actions.ShouldEnterDeclaratorScope(getCurScope(), 5299 D.getCXXScopeSpec())) 5300 // Change the declaration context for name lookup, until this function 5301 // is exited (and the declarator has been parsed). 5302 DeclScopeObj.EnterDeclaratorScope(); 5303 } 5304 } else if (D.mayOmitIdentifier()) { 5305 // This could be something simple like "int" (in which case the declarator 5306 // portion is empty), if an abstract-declarator is allowed. 5307 D.SetIdentifier(nullptr, Tok.getLocation()); 5308 5309 // The grammar for abstract-pack-declarator does not allow grouping parens. 5310 // FIXME: Revisit this once core issue 1488 is resolved. 5311 if (D.hasEllipsis() && D.hasGroupingParens()) 5312 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()), 5313 diag::ext_abstract_pack_declarator_parens); 5314 } else { 5315 if (Tok.getKind() == tok::annot_pragma_parser_crash) 5316 LLVM_BUILTIN_TRAP; 5317 if (Tok.is(tok::l_square)) 5318 return ParseMisplacedBracketDeclarator(D); 5319 if (D.getContext() == Declarator::MemberContext) { 5320 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 5321 diag::err_expected_member_name_or_semi) 5322 << (D.getDeclSpec().isEmpty() ? SourceRange() 5323 : D.getDeclSpec().getSourceRange()); 5324 } else if (getLangOpts().CPlusPlus) { 5325 if (Tok.isOneOf(tok::period, tok::arrow)) 5326 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow); 5327 else { 5328 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc(); 5329 if (Tok.isAtStartOfLine() && Loc.isValid()) 5330 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id) 5331 << getLangOpts().CPlusPlus; 5332 else 5333 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 5334 diag::err_expected_unqualified_id) 5335 << getLangOpts().CPlusPlus; 5336 } 5337 } else { 5338 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 5339 diag::err_expected_either) 5340 << tok::identifier << tok::l_paren; 5341 } 5342 D.SetIdentifier(nullptr, Tok.getLocation()); 5343 D.setInvalidType(true); 5344 } 5345 5346 PastIdentifier: 5347 assert(D.isPastIdentifier() && 5348 "Haven't past the location of the identifier yet?"); 5349 5350 // Don't parse attributes unless we have parsed an unparenthesized name. 5351 if (D.hasName() && !D.getNumTypeObjects()) 5352 MaybeParseCXX11Attributes(D); 5353 5354 while (1) { 5355 if (Tok.is(tok::l_paren)) { 5356 // Enter function-declaration scope, limiting any declarators to the 5357 // function prototype scope, including parameter declarators. 5358 ParseScope PrototypeScope(this, 5359 Scope::FunctionPrototypeScope|Scope::DeclScope| 5360 (D.isFunctionDeclaratorAFunctionDeclaration() 5361 ? Scope::FunctionDeclarationScope : 0)); 5362 5363 // The paren may be part of a C++ direct initializer, eg. "int x(1);". 5364 // In such a case, check if we actually have a function declarator; if it 5365 // is not, the declarator has been fully parsed. 5366 bool IsAmbiguous = false; 5367 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) { 5368 // The name of the declarator, if any, is tentatively declared within 5369 // a possible direct initializer. 5370 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier()); 5371 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous); 5372 TentativelyDeclaredIdentifiers.pop_back(); 5373 if (!IsFunctionDecl) 5374 break; 5375 } 5376 ParsedAttributes attrs(AttrFactory); 5377 BalancedDelimiterTracker T(*this, tok::l_paren); 5378 T.consumeOpen(); 5379 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous); 5380 PrototypeScope.Exit(); 5381 } else if (Tok.is(tok::l_square)) { 5382 ParseBracketDeclarator(D); 5383 } else { 5384 break; 5385 } 5386 } 5387 } 5388 5389 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is 5390 /// only called before the identifier, so these are most likely just grouping 5391 /// parens for precedence. If we find that these are actually function 5392 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. 5393 /// 5394 /// direct-declarator: 5395 /// '(' declarator ')' 5396 /// [GNU] '(' attributes declarator ')' 5397 /// direct-declarator '(' parameter-type-list ')' 5398 /// direct-declarator '(' identifier-list[opt] ')' 5399 /// [GNU] direct-declarator '(' parameter-forward-declarations 5400 /// parameter-type-list[opt] ')' 5401 /// 5402 void Parser::ParseParenDeclarator(Declarator &D) { 5403 BalancedDelimiterTracker T(*this, tok::l_paren); 5404 T.consumeOpen(); 5405 5406 assert(!D.isPastIdentifier() && "Should be called before passing identifier"); 5407 5408 // Eat any attributes before we look at whether this is a grouping or function 5409 // declarator paren. If this is a grouping paren, the attribute applies to 5410 // the type being built up, for example: 5411 // int (__attribute__(()) *x)(long y) 5412 // If this ends up not being a grouping paren, the attribute applies to the 5413 // first argument, for example: 5414 // int (__attribute__(()) int x) 5415 // In either case, we need to eat any attributes to be able to determine what 5416 // sort of paren this is. 5417 // 5418 ParsedAttributes attrs(AttrFactory); 5419 bool RequiresArg = false; 5420 if (Tok.is(tok::kw___attribute)) { 5421 ParseGNUAttributes(attrs); 5422 5423 // We require that the argument list (if this is a non-grouping paren) be 5424 // present even if the attribute list was empty. 5425 RequiresArg = true; 5426 } 5427 5428 // Eat any Microsoft extensions. 5429 ParseMicrosoftTypeAttributes(attrs); 5430 5431 // Eat any Borland extensions. 5432 if (Tok.is(tok::kw___pascal)) 5433 ParseBorlandTypeAttributes(attrs); 5434 5435 // If we haven't past the identifier yet (or where the identifier would be 5436 // stored, if this is an abstract declarator), then this is probably just 5437 // grouping parens. However, if this could be an abstract-declarator, then 5438 // this could also be the start of function arguments (consider 'void()'). 5439 bool isGrouping; 5440 5441 if (!D.mayOmitIdentifier()) { 5442 // If this can't be an abstract-declarator, this *must* be a grouping 5443 // paren, because we haven't seen the identifier yet. 5444 isGrouping = true; 5445 } else if (Tok.is(tok::r_paren) || // 'int()' is a function. 5446 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) && 5447 NextToken().is(tok::r_paren)) || // C++ int(...) 5448 isDeclarationSpecifier() || // 'int(int)' is a function. 5449 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function. 5450 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is 5451 // considered to be a type, not a K&R identifier-list. 5452 isGrouping = false; 5453 } else { 5454 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. 5455 isGrouping = true; 5456 } 5457 5458 // If this is a grouping paren, handle: 5459 // direct-declarator: '(' declarator ')' 5460 // direct-declarator: '(' attributes declarator ')' 5461 if (isGrouping) { 5462 SourceLocation EllipsisLoc = D.getEllipsisLoc(); 5463 D.setEllipsisLoc(SourceLocation()); 5464 5465 bool hadGroupingParens = D.hasGroupingParens(); 5466 D.setGroupingParens(true); 5467 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 5468 // Match the ')'. 5469 T.consumeClose(); 5470 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(), 5471 T.getCloseLocation()), 5472 attrs, T.getCloseLocation()); 5473 5474 D.setGroupingParens(hadGroupingParens); 5475 5476 // An ellipsis cannot be placed outside parentheses. 5477 if (EllipsisLoc.isValid()) 5478 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D); 5479 5480 return; 5481 } 5482 5483 // Okay, if this wasn't a grouping paren, it must be the start of a function 5484 // argument list. Recognize that this declarator will never have an 5485 // identifier (and remember where it would have been), then call into 5486 // ParseFunctionDeclarator to handle of argument list. 5487 D.SetIdentifier(nullptr, Tok.getLocation()); 5488 5489 // Enter function-declaration scope, limiting any declarators to the 5490 // function prototype scope, including parameter declarators. 5491 ParseScope PrototypeScope(this, 5492 Scope::FunctionPrototypeScope | Scope::DeclScope | 5493 (D.isFunctionDeclaratorAFunctionDeclaration() 5494 ? Scope::FunctionDeclarationScope : 0)); 5495 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg); 5496 PrototypeScope.Exit(); 5497 } 5498 5499 /// ParseFunctionDeclarator - We are after the identifier and have parsed the 5500 /// declarator D up to a paren, which indicates that we are parsing function 5501 /// arguments. 5502 /// 5503 /// If FirstArgAttrs is non-null, then the caller parsed those arguments 5504 /// immediately after the open paren - they should be considered to be the 5505 /// first argument of a parameter. 5506 /// 5507 /// If RequiresArg is true, then the first argument of the function is required 5508 /// to be present and required to not be an identifier list. 5509 /// 5510 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt], 5511 /// (C++11) ref-qualifier[opt], exception-specification[opt], 5512 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt]. 5513 /// 5514 /// [C++11] exception-specification: 5515 /// dynamic-exception-specification 5516 /// noexcept-specification 5517 /// 5518 void Parser::ParseFunctionDeclarator(Declarator &D, 5519 ParsedAttributes &FirstArgAttrs, 5520 BalancedDelimiterTracker &Tracker, 5521 bool IsAmbiguous, 5522 bool RequiresArg) { 5523 assert(getCurScope()->isFunctionPrototypeScope() && 5524 "Should call from a Function scope"); 5525 // lparen is already consumed! 5526 assert(D.isPastIdentifier() && "Should not call before identifier!"); 5527 5528 // This should be true when the function has typed arguments. 5529 // Otherwise, it is treated as a K&R-style function. 5530 bool HasProto = false; 5531 // Build up an array of information about the parsed arguments. 5532 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 5533 // Remember where we see an ellipsis, if any. 5534 SourceLocation EllipsisLoc; 5535 5536 DeclSpec DS(AttrFactory); 5537 bool RefQualifierIsLValueRef = true; 5538 SourceLocation RefQualifierLoc; 5539 SourceLocation ConstQualifierLoc; 5540 SourceLocation VolatileQualifierLoc; 5541 SourceLocation RestrictQualifierLoc; 5542 ExceptionSpecificationType ESpecType = EST_None; 5543 SourceRange ESpecRange; 5544 SmallVector<ParsedType, 2> DynamicExceptions; 5545 SmallVector<SourceRange, 2> DynamicExceptionRanges; 5546 ExprResult NoexceptExpr; 5547 CachedTokens *ExceptionSpecTokens = nullptr; 5548 ParsedAttributes FnAttrs(AttrFactory); 5549 TypeResult TrailingReturnType; 5550 5551 /* LocalEndLoc is the end location for the local FunctionTypeLoc. 5552 EndLoc is the end location for the function declarator. 5553 They differ for trailing return types. */ 5554 SourceLocation StartLoc, LocalEndLoc, EndLoc; 5555 SourceLocation LParenLoc, RParenLoc; 5556 LParenLoc = Tracker.getOpenLocation(); 5557 StartLoc = LParenLoc; 5558 5559 if (isFunctionDeclaratorIdentifierList()) { 5560 if (RequiresArg) 5561 Diag(Tok, diag::err_argument_required_after_attribute); 5562 5563 ParseFunctionDeclaratorIdentifierList(D, ParamInfo); 5564 5565 Tracker.consumeClose(); 5566 RParenLoc = Tracker.getCloseLocation(); 5567 LocalEndLoc = RParenLoc; 5568 EndLoc = RParenLoc; 5569 } else { 5570 if (Tok.isNot(tok::r_paren)) 5571 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, 5572 EllipsisLoc); 5573 else if (RequiresArg) 5574 Diag(Tok, diag::err_argument_required_after_attribute); 5575 5576 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus; 5577 5578 // If we have the closing ')', eat it. 5579 Tracker.consumeClose(); 5580 RParenLoc = Tracker.getCloseLocation(); 5581 LocalEndLoc = RParenLoc; 5582 EndLoc = RParenLoc; 5583 5584 if (getLangOpts().CPlusPlus) { 5585 // FIXME: Accept these components in any order, and produce fixits to 5586 // correct the order if the user gets it wrong. Ideally we should deal 5587 // with the pure-specifier in the same way. 5588 5589 // Parse cv-qualifier-seq[opt]. 5590 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed, 5591 /*AtomicAllowed*/ false); 5592 if (!DS.getSourceRange().getEnd().isInvalid()) { 5593 EndLoc = DS.getSourceRange().getEnd(); 5594 ConstQualifierLoc = DS.getConstSpecLoc(); 5595 VolatileQualifierLoc = DS.getVolatileSpecLoc(); 5596 RestrictQualifierLoc = DS.getRestrictSpecLoc(); 5597 } 5598 5599 // Parse ref-qualifier[opt]. 5600 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) 5601 EndLoc = RefQualifierLoc; 5602 5603 // C++11 [expr.prim.general]p3: 5604 // If a declaration declares a member function or member function 5605 // template of a class X, the expression this is a prvalue of type 5606 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 5607 // and the end of the function-definition, member-declarator, or 5608 // declarator. 5609 // FIXME: currently, "static" case isn't handled correctly. 5610 bool IsCXX11MemberFunction = 5611 getLangOpts().CPlusPlus11 && 5612 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5613 (D.getContext() == Declarator::MemberContext 5614 ? !D.getDeclSpec().isFriendSpecified() 5615 : D.getContext() == Declarator::FileContext && 5616 D.getCXXScopeSpec().isValid() && 5617 Actions.CurContext->isRecord()); 5618 Sema::CXXThisScopeRAII ThisScope(Actions, 5619 dyn_cast<CXXRecordDecl>(Actions.CurContext), 5620 DS.getTypeQualifiers() | 5621 (D.getDeclSpec().isConstexprSpecified() && 5622 !getLangOpts().CPlusPlus14 5623 ? Qualifiers::Const : 0), 5624 IsCXX11MemberFunction); 5625 5626 // Parse exception-specification[opt]. 5627 bool Delayed = D.isFirstDeclarationOfMember() && 5628 D.isFunctionDeclaratorAFunctionDeclaration(); 5629 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) && 5630 GetLookAheadToken(0).is(tok::kw_noexcept) && 5631 GetLookAheadToken(1).is(tok::l_paren) && 5632 GetLookAheadToken(2).is(tok::kw_noexcept) && 5633 GetLookAheadToken(3).is(tok::l_paren) && 5634 GetLookAheadToken(4).is(tok::identifier) && 5635 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) { 5636 // HACK: We've got an exception-specification 5637 // noexcept(noexcept(swap(...))) 5638 // or 5639 // noexcept(noexcept(swap(...)) && noexcept(swap(...))) 5640 // on a 'swap' member function. This is a libstdc++ bug; the lookup 5641 // for 'swap' will only find the function we're currently declaring, 5642 // whereas it expects to find a non-member swap through ADL. Turn off 5643 // delayed parsing to give it a chance to find what it expects. 5644 Delayed = false; 5645 } 5646 ESpecType = tryParseExceptionSpecification(Delayed, 5647 ESpecRange, 5648 DynamicExceptions, 5649 DynamicExceptionRanges, 5650 NoexceptExpr, 5651 ExceptionSpecTokens); 5652 if (ESpecType != EST_None) 5653 EndLoc = ESpecRange.getEnd(); 5654 5655 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes 5656 // after the exception-specification. 5657 MaybeParseCXX11Attributes(FnAttrs); 5658 5659 // Parse trailing-return-type[opt]. 5660 LocalEndLoc = EndLoc; 5661 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) { 5662 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type); 5663 if (D.getDeclSpec().getTypeSpecType() == TST_auto) 5664 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 5665 LocalEndLoc = Tok.getLocation(); 5666 SourceRange Range; 5667 TrailingReturnType = ParseTrailingReturnType(Range); 5668 EndLoc = Range.getEnd(); 5669 } 5670 } 5671 } 5672 5673 // Remember that we parsed a function type, and remember the attributes. 5674 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto, 5675 IsAmbiguous, 5676 LParenLoc, 5677 ParamInfo.data(), ParamInfo.size(), 5678 EllipsisLoc, RParenLoc, 5679 DS.getTypeQualifiers(), 5680 RefQualifierIsLValueRef, 5681 RefQualifierLoc, ConstQualifierLoc, 5682 VolatileQualifierLoc, 5683 RestrictQualifierLoc, 5684 /*MutableLoc=*/SourceLocation(), 5685 ESpecType, ESpecRange, 5686 DynamicExceptions.data(), 5687 DynamicExceptionRanges.data(), 5688 DynamicExceptions.size(), 5689 NoexceptExpr.isUsable() ? 5690 NoexceptExpr.get() : nullptr, 5691 ExceptionSpecTokens, 5692 StartLoc, LocalEndLoc, D, 5693 TrailingReturnType), 5694 FnAttrs, EndLoc); 5695 } 5696 5697 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns 5698 /// true if a ref-qualifier is found. 5699 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef, 5700 SourceLocation &RefQualifierLoc) { 5701 if (Tok.isOneOf(tok::amp, tok::ampamp)) { 5702 Diag(Tok, getLangOpts().CPlusPlus11 ? 5703 diag::warn_cxx98_compat_ref_qualifier : 5704 diag::ext_ref_qualifier); 5705 5706 RefQualifierIsLValueRef = Tok.is(tok::amp); 5707 RefQualifierLoc = ConsumeToken(); 5708 return true; 5709 } 5710 return false; 5711 } 5712 5713 /// isFunctionDeclaratorIdentifierList - This parameter list may have an 5714 /// identifier list form for a K&R-style function: void foo(a,b,c) 5715 /// 5716 /// Note that identifier-lists are only allowed for normal declarators, not for 5717 /// abstract-declarators. 5718 bool Parser::isFunctionDeclaratorIdentifierList() { 5719 return !getLangOpts().CPlusPlus 5720 && Tok.is(tok::identifier) 5721 && !TryAltiVecVectorToken() 5722 // K&R identifier lists can't have typedefs as identifiers, per C99 5723 // 6.7.5.3p11. 5724 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) 5725 // Identifier lists follow a really simple grammar: the identifiers can 5726 // be followed *only* by a ", identifier" or ")". However, K&R 5727 // identifier lists are really rare in the brave new modern world, and 5728 // it is very common for someone to typo a type in a non-K&R style 5729 // list. If we are presented with something like: "void foo(intptr x, 5730 // float y)", we don't want to start parsing the function declarator as 5731 // though it is a K&R style declarator just because intptr is an 5732 // invalid type. 5733 // 5734 // To handle this, we check to see if the token after the first 5735 // identifier is a "," or ")". Only then do we parse it as an 5736 // identifier list. 5737 && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)); 5738 } 5739 5740 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator 5741 /// we found a K&R-style identifier list instead of a typed parameter list. 5742 /// 5743 /// After returning, ParamInfo will hold the parsed parameters. 5744 /// 5745 /// identifier-list: [C99 6.7.5] 5746 /// identifier 5747 /// identifier-list ',' identifier 5748 /// 5749 void Parser::ParseFunctionDeclaratorIdentifierList( 5750 Declarator &D, 5751 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) { 5752 // If there was no identifier specified for the declarator, either we are in 5753 // an abstract-declarator, or we are in a parameter declarator which was found 5754 // to be abstract. In abstract-declarators, identifier lists are not valid: 5755 // diagnose this. 5756 if (!D.getIdentifier()) 5757 Diag(Tok, diag::ext_ident_list_in_param); 5758 5759 // Maintain an efficient lookup of params we have seen so far. 5760 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar; 5761 5762 do { 5763 // If this isn't an identifier, report the error and skip until ')'. 5764 if (Tok.isNot(tok::identifier)) { 5765 Diag(Tok, diag::err_expected) << tok::identifier; 5766 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch); 5767 // Forget we parsed anything. 5768 ParamInfo.clear(); 5769 return; 5770 } 5771 5772 IdentifierInfo *ParmII = Tok.getIdentifierInfo(); 5773 5774 // Reject 'typedef int y; int test(x, y)', but continue parsing. 5775 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope())) 5776 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; 5777 5778 // Verify that the argument identifier has not already been mentioned. 5779 if (!ParamsSoFar.insert(ParmII).second) { 5780 Diag(Tok, diag::err_param_redefinition) << ParmII; 5781 } else { 5782 // Remember this identifier in ParamInfo. 5783 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 5784 Tok.getLocation(), 5785 nullptr)); 5786 } 5787 5788 // Eat the identifier. 5789 ConsumeToken(); 5790 // The list continues if we see a comma. 5791 } while (TryConsumeToken(tok::comma)); 5792 } 5793 5794 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list 5795 /// after the opening parenthesis. This function will not parse a K&R-style 5796 /// identifier list. 5797 /// 5798 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the 5799 /// caller parsed those arguments immediately after the open paren - they should 5800 /// be considered to be part of the first parameter. 5801 /// 5802 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will 5803 /// be the location of the ellipsis, if any was parsed. 5804 /// 5805 /// parameter-type-list: [C99 6.7.5] 5806 /// parameter-list 5807 /// parameter-list ',' '...' 5808 /// [C++] parameter-list '...' 5809 /// 5810 /// parameter-list: [C99 6.7.5] 5811 /// parameter-declaration 5812 /// parameter-list ',' parameter-declaration 5813 /// 5814 /// parameter-declaration: [C99 6.7.5] 5815 /// declaration-specifiers declarator 5816 /// [C++] declaration-specifiers declarator '=' assignment-expression 5817 /// [C++11] initializer-clause 5818 /// [GNU] declaration-specifiers declarator attributes 5819 /// declaration-specifiers abstract-declarator[opt] 5820 /// [C++] declaration-specifiers abstract-declarator[opt] 5821 /// '=' assignment-expression 5822 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes 5823 /// [C++11] attribute-specifier-seq parameter-declaration 5824 /// 5825 void Parser::ParseParameterDeclarationClause( 5826 Declarator &D, 5827 ParsedAttributes &FirstArgAttrs, 5828 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, 5829 SourceLocation &EllipsisLoc) { 5830 do { 5831 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq 5832 // before deciding this was a parameter-declaration-clause. 5833 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) 5834 break; 5835 5836 // Parse the declaration-specifiers. 5837 // Just use the ParsingDeclaration "scope" of the declarator. 5838 DeclSpec DS(AttrFactory); 5839 5840 // Parse any C++11 attributes. 5841 MaybeParseCXX11Attributes(DS.getAttributes()); 5842 5843 // Skip any Microsoft attributes before a param. 5844 MaybeParseMicrosoftAttributes(DS.getAttributes()); 5845 5846 SourceLocation DSStart = Tok.getLocation(); 5847 5848 // If the caller parsed attributes for the first argument, add them now. 5849 // Take them so that we only apply the attributes to the first parameter. 5850 // FIXME: If we can leave the attributes in the token stream somehow, we can 5851 // get rid of a parameter (FirstArgAttrs) and this statement. It might be 5852 // too much hassle. 5853 DS.takeAttributesFrom(FirstArgAttrs); 5854 5855 ParseDeclarationSpecifiers(DS); 5856 5857 5858 // Parse the declarator. This is "PrototypeContext" or 5859 // "LambdaExprParameterContext", because we must accept either 5860 // 'declarator' or 'abstract-declarator' here. 5861 Declarator ParmDeclarator(DS, 5862 D.getContext() == Declarator::LambdaExprContext ? 5863 Declarator::LambdaExprParameterContext : 5864 Declarator::PrototypeContext); 5865 ParseDeclarator(ParmDeclarator); 5866 5867 // Parse GNU attributes, if present. 5868 MaybeParseGNUAttributes(ParmDeclarator); 5869 5870 // Remember this parsed parameter in ParamInfo. 5871 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier(); 5872 5873 // DefArgToks is used when the parsing of default arguments needs 5874 // to be delayed. 5875 CachedTokens *DefArgToks = nullptr; 5876 5877 // If no parameter was specified, verify that *something* was specified, 5878 // otherwise we have a missing type and identifier. 5879 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr && 5880 ParmDeclarator.getNumTypeObjects() == 0) { 5881 // Completely missing, emit error. 5882 Diag(DSStart, diag::err_missing_param); 5883 } else { 5884 // Otherwise, we have something. Add it and let semantic analysis try 5885 // to grok it and add the result to the ParamInfo we are building. 5886 5887 // Last chance to recover from a misplaced ellipsis in an attempted 5888 // parameter pack declaration. 5889 if (Tok.is(tok::ellipsis) && 5890 (NextToken().isNot(tok::r_paren) || 5891 (!ParmDeclarator.getEllipsisLoc().isValid() && 5892 !Actions.isUnexpandedParameterPackPermitted())) && 5893 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) 5894 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator); 5895 5896 // Inform the actions module about the parameter declarator, so it gets 5897 // added to the current scope. 5898 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator); 5899 // Parse the default argument, if any. We parse the default 5900 // arguments in all dialects; the semantic analysis in 5901 // ActOnParamDefaultArgument will reject the default argument in 5902 // C. 5903 if (Tok.is(tok::equal)) { 5904 SourceLocation EqualLoc = Tok.getLocation(); 5905 5906 // Parse the default argument 5907 if (D.getContext() == Declarator::MemberContext) { 5908 // If we're inside a class definition, cache the tokens 5909 // corresponding to the default argument. We'll actually parse 5910 // them when we see the end of the class definition. 5911 // FIXME: Can we use a smart pointer for Toks? 5912 DefArgToks = new CachedTokens; 5913 5914 SourceLocation ArgStartLoc = NextToken().getLocation(); 5915 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) { 5916 delete DefArgToks; 5917 DefArgToks = nullptr; 5918 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc); 5919 } else { 5920 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc, 5921 ArgStartLoc); 5922 } 5923 } else { 5924 // Consume the '='. 5925 ConsumeToken(); 5926 5927 // The argument isn't actually potentially evaluated unless it is 5928 // used. 5929 EnterExpressionEvaluationContext Eval(Actions, 5930 Sema::PotentiallyEvaluatedIfUsed, 5931 Param); 5932 5933 ExprResult DefArgResult; 5934 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 5935 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 5936 DefArgResult = ParseBraceInitializer(); 5937 } else 5938 DefArgResult = ParseAssignmentExpression(); 5939 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult); 5940 if (DefArgResult.isInvalid()) { 5941 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc); 5942 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch); 5943 } else { 5944 // Inform the actions module about the default argument 5945 Actions.ActOnParamDefaultArgument(Param, EqualLoc, 5946 DefArgResult.get()); 5947 } 5948 } 5949 } 5950 5951 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 5952 ParmDeclarator.getIdentifierLoc(), 5953 Param, DefArgToks)); 5954 } 5955 5956 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) { 5957 if (!getLangOpts().CPlusPlus) { 5958 // We have ellipsis without a preceding ',', which is ill-formed 5959 // in C. Complain and provide the fix. 5960 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis) 5961 << FixItHint::CreateInsertion(EllipsisLoc, ", "); 5962 } else if (ParmDeclarator.getEllipsisLoc().isValid() || 5963 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) { 5964 // It looks like this was supposed to be a parameter pack. Warn and 5965 // point out where the ellipsis should have gone. 5966 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc(); 5967 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg) 5968 << ParmEllipsis.isValid() << ParmEllipsis; 5969 if (ParmEllipsis.isValid()) { 5970 Diag(ParmEllipsis, 5971 diag::note_misplaced_ellipsis_vararg_existing_ellipsis); 5972 } else { 5973 Diag(ParmDeclarator.getIdentifierLoc(), 5974 diag::note_misplaced_ellipsis_vararg_add_ellipsis) 5975 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(), 5976 "...") 5977 << !ParmDeclarator.hasName(); 5978 } 5979 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma) 5980 << FixItHint::CreateInsertion(EllipsisLoc, ", "); 5981 } 5982 5983 // We can't have any more parameters after an ellipsis. 5984 break; 5985 } 5986 5987 // If the next token is a comma, consume it and keep reading arguments. 5988 } while (TryConsumeToken(tok::comma)); 5989 } 5990 5991 /// [C90] direct-declarator '[' constant-expression[opt] ']' 5992 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 5993 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 5994 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 5995 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 5996 /// [C++11] direct-declarator '[' constant-expression[opt] ']' 5997 /// attribute-specifier-seq[opt] 5998 void Parser::ParseBracketDeclarator(Declarator &D) { 5999 if (CheckProhibitedCXX11Attribute()) 6000 return; 6001 6002 BalancedDelimiterTracker T(*this, tok::l_square); 6003 T.consumeOpen(); 6004 6005 // C array syntax has many features, but by-far the most common is [] and [4]. 6006 // This code does a fast path to handle some of the most obvious cases. 6007 if (Tok.getKind() == tok::r_square) { 6008 T.consumeClose(); 6009 ParsedAttributes attrs(AttrFactory); 6010 MaybeParseCXX11Attributes(attrs); 6011 6012 // Remember that we parsed the empty array type. 6013 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr, 6014 T.getOpenLocation(), 6015 T.getCloseLocation()), 6016 attrs, T.getCloseLocation()); 6017 return; 6018 } else if (Tok.getKind() == tok::numeric_constant && 6019 GetLookAheadToken(1).is(tok::r_square)) { 6020 // [4] is very common. Parse the numeric constant expression. 6021 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope())); 6022 ConsumeToken(); 6023 6024 T.consumeClose(); 6025 ParsedAttributes attrs(AttrFactory); 6026 MaybeParseCXX11Attributes(attrs); 6027 6028 // Remember that we parsed a array type, and remember its features. 6029 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 6030 ExprRes.get(), 6031 T.getOpenLocation(), 6032 T.getCloseLocation()), 6033 attrs, T.getCloseLocation()); 6034 return; 6035 } else if (Tok.getKind() == tok::code_completion) { 6036 Actions.CodeCompleteBracketDeclarator(getCurScope()); 6037 return cutOffParsing(); 6038 } 6039 6040 // If valid, this location is the position where we read the 'static' keyword. 6041 SourceLocation StaticLoc; 6042 TryConsumeToken(tok::kw_static, StaticLoc); 6043 6044 // If there is a type-qualifier-list, read it now. 6045 // Type qualifiers in an array subscript are a C99 feature. 6046 DeclSpec DS(AttrFactory); 6047 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed); 6048 6049 // If we haven't already read 'static', check to see if there is one after the 6050 // type-qualifier-list. 6051 if (!StaticLoc.isValid()) 6052 TryConsumeToken(tok::kw_static, StaticLoc); 6053 6054 // Handle "direct-declarator [ type-qual-list[opt] * ]". 6055 bool isStar = false; 6056 ExprResult NumElements; 6057 6058 // Handle the case where we have '[*]' as the array size. However, a leading 6059 // star could be the start of an expression, for example 'X[*p + 4]'. Verify 6060 // the token after the star is a ']'. Since stars in arrays are 6061 // infrequent, use of lookahead is not costly here. 6062 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) { 6063 ConsumeToken(); // Eat the '*'. 6064 6065 if (StaticLoc.isValid()) { 6066 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static); 6067 StaticLoc = SourceLocation(); // Drop the static. 6068 } 6069 isStar = true; 6070 } else if (Tok.isNot(tok::r_square)) { 6071 // Note, in C89, this production uses the constant-expr production instead 6072 // of assignment-expr. The only difference is that assignment-expr allows 6073 // things like '=' and '*='. Sema rejects these in C89 mode because they 6074 // are not i-c-e's, so we don't need to distinguish between the two here. 6075 6076 // Parse the constant-expression or assignment-expression now (depending 6077 // on dialect). 6078 if (getLangOpts().CPlusPlus) { 6079 NumElements = ParseConstantExpression(); 6080 } else { 6081 EnterExpressionEvaluationContext Unevaluated(Actions, 6082 Sema::ConstantEvaluated); 6083 NumElements = 6084 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()); 6085 } 6086 } else { 6087 if (StaticLoc.isValid()) { 6088 Diag(StaticLoc, diag::err_unspecified_size_with_static); 6089 StaticLoc = SourceLocation(); // Drop the static. 6090 } 6091 } 6092 6093 // If there was an error parsing the assignment-expression, recover. 6094 if (NumElements.isInvalid()) { 6095 D.setInvalidType(true); 6096 // If the expression was invalid, skip it. 6097 SkipUntil(tok::r_square, StopAtSemi); 6098 return; 6099 } 6100 6101 T.consumeClose(); 6102 6103 ParsedAttributes attrs(AttrFactory); 6104 MaybeParseCXX11Attributes(attrs); 6105 6106 // Remember that we parsed a array type, and remember its features. 6107 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(), 6108 StaticLoc.isValid(), isStar, 6109 NumElements.get(), 6110 T.getOpenLocation(), 6111 T.getCloseLocation()), 6112 attrs, T.getCloseLocation()); 6113 } 6114 6115 /// Diagnose brackets before an identifier. 6116 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) { 6117 assert(Tok.is(tok::l_square) && "Missing opening bracket"); 6118 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier"); 6119 6120 SourceLocation StartBracketLoc = Tok.getLocation(); 6121 Declarator TempDeclarator(D.getDeclSpec(), D.getContext()); 6122 6123 while (Tok.is(tok::l_square)) { 6124 ParseBracketDeclarator(TempDeclarator); 6125 } 6126 6127 // Stuff the location of the start of the brackets into the Declarator. 6128 // The diagnostics from ParseDirectDeclarator will make more sense if 6129 // they use this location instead. 6130 if (Tok.is(tok::semi)) 6131 D.getName().EndLocation = StartBracketLoc; 6132 6133 SourceLocation SuggestParenLoc = Tok.getLocation(); 6134 6135 // Now that the brackets are removed, try parsing the declarator again. 6136 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 6137 6138 // Something went wrong parsing the brackets, in which case, 6139 // ParseBracketDeclarator has emitted an error, and we don't need to emit 6140 // one here. 6141 if (TempDeclarator.getNumTypeObjects() == 0) 6142 return; 6143 6144 // Determine if parens will need to be suggested in the diagnostic. 6145 bool NeedParens = false; 6146 if (D.getNumTypeObjects() != 0) { 6147 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) { 6148 case DeclaratorChunk::Pointer: 6149 case DeclaratorChunk::Reference: 6150 case DeclaratorChunk::BlockPointer: 6151 case DeclaratorChunk::MemberPointer: 6152 case DeclaratorChunk::Pipe: 6153 NeedParens = true; 6154 break; 6155 case DeclaratorChunk::Array: 6156 case DeclaratorChunk::Function: 6157 case DeclaratorChunk::Paren: 6158 break; 6159 } 6160 } 6161 6162 if (NeedParens) { 6163 // Create a DeclaratorChunk for the inserted parens. 6164 ParsedAttributes attrs(AttrFactory); 6165 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd()); 6166 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), attrs, 6167 SourceLocation()); 6168 } 6169 6170 // Adding back the bracket info to the end of the Declarator. 6171 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) { 6172 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i); 6173 ParsedAttributes attrs(AttrFactory); 6174 attrs.set(Chunk.Common.AttrList); 6175 D.AddTypeInfo(Chunk, attrs, SourceLocation()); 6176 } 6177 6178 // The missing identifier would have been diagnosed in ParseDirectDeclarator. 6179 // If parentheses are required, always suggest them. 6180 if (!D.getIdentifier() && !NeedParens) 6181 return; 6182 6183 SourceLocation EndBracketLoc = TempDeclarator.getLocEnd(); 6184 6185 // Generate the move bracket error message. 6186 SourceRange BracketRange(StartBracketLoc, EndBracketLoc); 6187 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd()); 6188 6189 if (NeedParens) { 6190 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id) 6191 << getLangOpts().CPlusPlus 6192 << FixItHint::CreateInsertion(SuggestParenLoc, "(") 6193 << FixItHint::CreateInsertion(EndLoc, ")") 6194 << FixItHint::CreateInsertionFromRange( 6195 EndLoc, CharSourceRange(BracketRange, true)) 6196 << FixItHint::CreateRemoval(BracketRange); 6197 } else { 6198 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id) 6199 << getLangOpts().CPlusPlus 6200 << FixItHint::CreateInsertionFromRange( 6201 EndLoc, CharSourceRange(BracketRange, true)) 6202 << FixItHint::CreateRemoval(BracketRange); 6203 } 6204 } 6205 6206 /// [GNU] typeof-specifier: 6207 /// typeof ( expressions ) 6208 /// typeof ( type-name ) 6209 /// [GNU/C++] typeof unary-expression 6210 /// 6211 void Parser::ParseTypeofSpecifier(DeclSpec &DS) { 6212 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier"); 6213 Token OpTok = Tok; 6214 SourceLocation StartLoc = ConsumeToken(); 6215 6216 const bool hasParens = Tok.is(tok::l_paren); 6217 6218 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated, 6219 Sema::ReuseLambdaContextDecl); 6220 6221 bool isCastExpr; 6222 ParsedType CastTy; 6223 SourceRange CastRange; 6224 ExprResult Operand = Actions.CorrectDelayedTyposInExpr( 6225 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange)); 6226 if (hasParens) 6227 DS.setTypeofParensRange(CastRange); 6228 6229 if (CastRange.getEnd().isInvalid()) 6230 // FIXME: Not accurate, the range gets one token more than it should. 6231 DS.SetRangeEnd(Tok.getLocation()); 6232 else 6233 DS.SetRangeEnd(CastRange.getEnd()); 6234 6235 if (isCastExpr) { 6236 if (!CastTy) { 6237 DS.SetTypeSpecError(); 6238 return; 6239 } 6240 6241 const char *PrevSpec = nullptr; 6242 unsigned DiagID; 6243 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 6244 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, 6245 DiagID, CastTy, 6246 Actions.getASTContext().getPrintingPolicy())) 6247 Diag(StartLoc, DiagID) << PrevSpec; 6248 return; 6249 } 6250 6251 // If we get here, the operand to the typeof was an expresion. 6252 if (Operand.isInvalid()) { 6253 DS.SetTypeSpecError(); 6254 return; 6255 } 6256 6257 // We might need to transform the operand if it is potentially evaluated. 6258 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get()); 6259 if (Operand.isInvalid()) { 6260 DS.SetTypeSpecError(); 6261 return; 6262 } 6263 6264 const char *PrevSpec = nullptr; 6265 unsigned DiagID; 6266 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 6267 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 6268 DiagID, Operand.get(), 6269 Actions.getASTContext().getPrintingPolicy())) 6270 Diag(StartLoc, DiagID) << PrevSpec; 6271 } 6272 6273 /// [C11] atomic-specifier: 6274 /// _Atomic ( type-name ) 6275 /// 6276 void Parser::ParseAtomicSpecifier(DeclSpec &DS) { 6277 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) && 6278 "Not an atomic specifier"); 6279 6280 SourceLocation StartLoc = ConsumeToken(); 6281 BalancedDelimiterTracker T(*this, tok::l_paren); 6282 if (T.consumeOpen()) 6283 return; 6284 6285 TypeResult Result = ParseTypeName(); 6286 if (Result.isInvalid()) { 6287 SkipUntil(tok::r_paren, StopAtSemi); 6288 return; 6289 } 6290 6291 // Match the ')' 6292 T.consumeClose(); 6293 6294 if (T.getCloseLocation().isInvalid()) 6295 return; 6296 6297 DS.setTypeofParensRange(T.getRange()); 6298 DS.SetRangeEnd(T.getCloseLocation()); 6299 6300 const char *PrevSpec = nullptr; 6301 unsigned DiagID; 6302 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec, 6303 DiagID, Result.get(), 6304 Actions.getASTContext().getPrintingPolicy())) 6305 Diag(StartLoc, DiagID) << PrevSpec; 6306 } 6307 6308 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called 6309 /// from TryAltiVecVectorToken. 6310 bool Parser::TryAltiVecVectorTokenOutOfLine() { 6311 Token Next = NextToken(); 6312 switch (Next.getKind()) { 6313 default: return false; 6314 case tok::kw_short: 6315 case tok::kw_long: 6316 case tok::kw_signed: 6317 case tok::kw_unsigned: 6318 case tok::kw_void: 6319 case tok::kw_char: 6320 case tok::kw_int: 6321 case tok::kw_float: 6322 case tok::kw_double: 6323 case tok::kw_bool: 6324 case tok::kw___bool: 6325 case tok::kw___pixel: 6326 Tok.setKind(tok::kw___vector); 6327 return true; 6328 case tok::identifier: 6329 if (Next.getIdentifierInfo() == Ident_pixel) { 6330 Tok.setKind(tok::kw___vector); 6331 return true; 6332 } 6333 if (Next.getIdentifierInfo() == Ident_bool) { 6334 Tok.setKind(tok::kw___vector); 6335 return true; 6336 } 6337 return false; 6338 } 6339 } 6340 6341 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, 6342 const char *&PrevSpec, unsigned &DiagID, 6343 bool &isInvalid) { 6344 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); 6345 if (Tok.getIdentifierInfo() == Ident_vector) { 6346 Token Next = NextToken(); 6347 switch (Next.getKind()) { 6348 case tok::kw_short: 6349 case tok::kw_long: 6350 case tok::kw_signed: 6351 case tok::kw_unsigned: 6352 case tok::kw_void: 6353 case tok::kw_char: 6354 case tok::kw_int: 6355 case tok::kw_float: 6356 case tok::kw_double: 6357 case tok::kw_bool: 6358 case tok::kw___bool: 6359 case tok::kw___pixel: 6360 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy); 6361 return true; 6362 case tok::identifier: 6363 if (Next.getIdentifierInfo() == Ident_pixel) { 6364 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy); 6365 return true; 6366 } 6367 if (Next.getIdentifierInfo() == Ident_bool) { 6368 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy); 6369 return true; 6370 } 6371 break; 6372 default: 6373 break; 6374 } 6375 } else if ((Tok.getIdentifierInfo() == Ident_pixel) && 6376 DS.isTypeAltiVecVector()) { 6377 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy); 6378 return true; 6379 } else if ((Tok.getIdentifierInfo() == Ident_bool) && 6380 DS.isTypeAltiVecVector()) { 6381 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy); 6382 return true; 6383 } 6384 return false; 6385 } 6386