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