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