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