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