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