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