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