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