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