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