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