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