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