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