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