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