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