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