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