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