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.isOneOf(tok::kw__Static_assert, 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 case tok::kw__Static_assert: 5185 5186 // GNU typeof support. 5187 case tok::kw_typeof: 5188 5189 // GNU attributes. 5190 case tok::kw___attribute: 5191 5192 // C++11 decltype and constexpr. 5193 case tok::annot_decltype: 5194 case tok::kw_constexpr: 5195 5196 // C++20 consteval and constinit. 5197 case tok::kw_consteval: 5198 case tok::kw_constinit: 5199 5200 // C11 _Atomic 5201 case tok::kw__Atomic: 5202 return true; 5203 5204 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 5205 case tok::less: 5206 return getLangOpts().ObjC; 5207 5208 // typedef-name 5209 case tok::annot_typename: 5210 return !DisambiguatingWithExpression || 5211 !isStartOfObjCClassMessageMissingOpenBracket(); 5212 5213 // placeholder-type-specifier 5214 case tok::annot_template_id: { 5215 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 5216 if (TemplateId->hasInvalidName()) 5217 return true; 5218 // FIXME: What about type templates that have only been annotated as 5219 // annot_template_id, not as annot_typename? 5220 return isTypeConstraintAnnotation() && 5221 (NextToken().is(tok::kw_auto) || NextToken().is(tok::kw_decltype)); 5222 } 5223 5224 case tok::annot_cxxscope: { 5225 TemplateIdAnnotation *TemplateId = 5226 NextToken().is(tok::annot_template_id) 5227 ? takeTemplateIdAnnotation(NextToken()) 5228 : nullptr; 5229 if (TemplateId && TemplateId->hasInvalidName()) 5230 return true; 5231 // FIXME: What about type templates that have only been annotated as 5232 // annot_template_id, not as annot_typename? 5233 if (NextToken().is(tok::identifier) && TryAnnotateTypeConstraint()) 5234 return true; 5235 return isTypeConstraintAnnotation() && 5236 GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype); 5237 } 5238 5239 case tok::kw___declspec: 5240 case tok::kw___cdecl: 5241 case tok::kw___stdcall: 5242 case tok::kw___fastcall: 5243 case tok::kw___thiscall: 5244 case tok::kw___regcall: 5245 case tok::kw___vectorcall: 5246 case tok::kw___w64: 5247 case tok::kw___sptr: 5248 case tok::kw___uptr: 5249 case tok::kw___ptr64: 5250 case tok::kw___ptr32: 5251 case tok::kw___forceinline: 5252 case tok::kw___pascal: 5253 case tok::kw___unaligned: 5254 5255 case tok::kw__Nonnull: 5256 case tok::kw__Nullable: 5257 case tok::kw__Nullable_result: 5258 case tok::kw__Null_unspecified: 5259 5260 case tok::kw___kindof: 5261 5262 case tok::kw___private: 5263 case tok::kw___local: 5264 case tok::kw___global: 5265 case tok::kw___constant: 5266 case tok::kw___generic: 5267 case tok::kw___read_only: 5268 case tok::kw___read_write: 5269 case tok::kw___write_only: 5270 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t: 5271 #include "clang/Basic/OpenCLImageTypes.def" 5272 5273 return true; 5274 5275 case tok::kw_private: 5276 return getLangOpts().OpenCL; 5277 } 5278 } 5279 5280 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) { 5281 TentativeParsingAction TPA(*this); 5282 5283 // Parse the C++ scope specifier. 5284 CXXScopeSpec SS; 5285 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 5286 /*ObjectHadErrors=*/false, 5287 /*EnteringContext=*/true)) { 5288 TPA.Revert(); 5289 return false; 5290 } 5291 5292 // Parse the constructor name. 5293 if (Tok.is(tok::identifier)) { 5294 // We already know that we have a constructor name; just consume 5295 // the token. 5296 ConsumeToken(); 5297 } else if (Tok.is(tok::annot_template_id)) { 5298 ConsumeAnnotationToken(); 5299 } else { 5300 TPA.Revert(); 5301 return false; 5302 } 5303 5304 // There may be attributes here, appertaining to the constructor name or type 5305 // we just stepped past. 5306 SkipCXX11Attributes(); 5307 5308 // Current class name must be followed by a left parenthesis. 5309 if (Tok.isNot(tok::l_paren)) { 5310 TPA.Revert(); 5311 return false; 5312 } 5313 ConsumeParen(); 5314 5315 // A right parenthesis, or ellipsis followed by a right parenthesis signals 5316 // that we have a constructor. 5317 if (Tok.is(tok::r_paren) || 5318 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) { 5319 TPA.Revert(); 5320 return true; 5321 } 5322 5323 // A C++11 attribute here signals that we have a constructor, and is an 5324 // attribute on the first constructor parameter. 5325 if (getLangOpts().CPlusPlus11 && 5326 isCXX11AttributeSpecifier(/*Disambiguate*/ false, 5327 /*OuterMightBeMessageSend*/ true)) { 5328 TPA.Revert(); 5329 return true; 5330 } 5331 5332 // If we need to, enter the specified scope. 5333 DeclaratorScopeObj DeclScopeObj(*this, SS); 5334 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS)) 5335 DeclScopeObj.EnterDeclaratorScope(); 5336 5337 // Optionally skip Microsoft attributes. 5338 ParsedAttributes Attrs(AttrFactory); 5339 MaybeParseMicrosoftAttributes(Attrs); 5340 5341 // Check whether the next token(s) are part of a declaration 5342 // specifier, in which case we have the start of a parameter and, 5343 // therefore, we know that this is a constructor. 5344 bool IsConstructor = false; 5345 if (isDeclarationSpecifier()) 5346 IsConstructor = true; 5347 else if (Tok.is(tok::identifier) || 5348 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) { 5349 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type. 5350 // This might be a parenthesized member name, but is more likely to 5351 // be a constructor declaration with an invalid argument type. Keep 5352 // looking. 5353 if (Tok.is(tok::annot_cxxscope)) 5354 ConsumeAnnotationToken(); 5355 ConsumeToken(); 5356 5357 // If this is not a constructor, we must be parsing a declarator, 5358 // which must have one of the following syntactic forms (see the 5359 // grammar extract at the start of ParseDirectDeclarator): 5360 switch (Tok.getKind()) { 5361 case tok::l_paren: 5362 // C(X ( int)); 5363 case tok::l_square: 5364 // C(X [ 5]); 5365 // C(X [ [attribute]]); 5366 case tok::coloncolon: 5367 // C(X :: Y); 5368 // C(X :: *p); 5369 // Assume this isn't a constructor, rather than assuming it's a 5370 // constructor with an unnamed parameter of an ill-formed type. 5371 break; 5372 5373 case tok::r_paren: 5374 // C(X ) 5375 5376 // Skip past the right-paren and any following attributes to get to 5377 // the function body or trailing-return-type. 5378 ConsumeParen(); 5379 SkipCXX11Attributes(); 5380 5381 if (DeductionGuide) { 5382 // C(X) -> ... is a deduction guide. 5383 IsConstructor = Tok.is(tok::arrow); 5384 break; 5385 } 5386 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) { 5387 // Assume these were meant to be constructors: 5388 // C(X) : (the name of a bit-field cannot be parenthesized). 5389 // C(X) try (this is otherwise ill-formed). 5390 IsConstructor = true; 5391 } 5392 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) { 5393 // If we have a constructor name within the class definition, 5394 // assume these were meant to be constructors: 5395 // C(X) { 5396 // C(X) ; 5397 // ... because otherwise we would be declaring a non-static data 5398 // member that is ill-formed because it's of the same type as its 5399 // surrounding class. 5400 // 5401 // FIXME: We can actually do this whether or not the name is qualified, 5402 // because if it is qualified in this context it must be being used as 5403 // a constructor name. 5404 // currently, so we're somewhat conservative here. 5405 IsConstructor = IsUnqualified; 5406 } 5407 break; 5408 5409 default: 5410 IsConstructor = true; 5411 break; 5412 } 5413 } 5414 5415 TPA.Revert(); 5416 return IsConstructor; 5417 } 5418 5419 /// ParseTypeQualifierListOpt 5420 /// type-qualifier-list: [C99 6.7.5] 5421 /// type-qualifier 5422 /// [vendor] attributes 5423 /// [ only if AttrReqs & AR_VendorAttributesParsed ] 5424 /// type-qualifier-list type-qualifier 5425 /// [vendor] type-qualifier-list attributes 5426 /// [ only if AttrReqs & AR_VendorAttributesParsed ] 5427 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq 5428 /// [ only if AttReqs & AR_CXX11AttributesParsed ] 5429 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via 5430 /// AttrRequirements bitmask values. 5431 void Parser::ParseTypeQualifierListOpt( 5432 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed, 5433 bool IdentifierRequired, 5434 Optional<llvm::function_ref<void()>> CodeCompletionHandler) { 5435 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) && 5436 isCXX11AttributeSpecifier()) { 5437 ParsedAttributesWithRange attrs(AttrFactory); 5438 ParseCXX11Attributes(attrs); 5439 DS.takeAttributesFrom(attrs); 5440 } 5441 5442 SourceLocation EndLoc; 5443 5444 while (1) { 5445 bool isInvalid = false; 5446 const char *PrevSpec = nullptr; 5447 unsigned DiagID = 0; 5448 SourceLocation Loc = Tok.getLocation(); 5449 5450 switch (Tok.getKind()) { 5451 case tok::code_completion: 5452 if (CodeCompletionHandler) 5453 (*CodeCompletionHandler)(); 5454 else 5455 Actions.CodeCompleteTypeQualifiers(DS); 5456 return cutOffParsing(); 5457 5458 case tok::kw_const: 5459 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID, 5460 getLangOpts()); 5461 break; 5462 case tok::kw_volatile: 5463 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 5464 getLangOpts()); 5465 break; 5466 case tok::kw_restrict: 5467 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 5468 getLangOpts()); 5469 break; 5470 case tok::kw__Atomic: 5471 if (!AtomicAllowed) 5472 goto DoneWithTypeQuals; 5473 if (!getLangOpts().C11) 5474 Diag(Tok, diag::ext_c11_feature) << Tok.getName(); 5475 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID, 5476 getLangOpts()); 5477 break; 5478 5479 // OpenCL qualifiers: 5480 case tok::kw_private: 5481 if (!getLangOpts().OpenCL) 5482 goto DoneWithTypeQuals; 5483 LLVM_FALLTHROUGH; 5484 case tok::kw___private: 5485 case tok::kw___global: 5486 case tok::kw___local: 5487 case tok::kw___constant: 5488 case tok::kw___generic: 5489 case tok::kw___read_only: 5490 case tok::kw___write_only: 5491 case tok::kw___read_write: 5492 ParseOpenCLQualifiers(DS.getAttributes()); 5493 break; 5494 5495 case tok::kw___unaligned: 5496 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID, 5497 getLangOpts()); 5498 break; 5499 case tok::kw___uptr: 5500 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts 5501 // with the MS modifier keyword. 5502 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus && 5503 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) { 5504 if (TryKeywordIdentFallback(false)) 5505 continue; 5506 } 5507 LLVM_FALLTHROUGH; 5508 case tok::kw___sptr: 5509 case tok::kw___w64: 5510 case tok::kw___ptr64: 5511 case tok::kw___ptr32: 5512 case tok::kw___cdecl: 5513 case tok::kw___stdcall: 5514 case tok::kw___fastcall: 5515 case tok::kw___thiscall: 5516 case tok::kw___regcall: 5517 case tok::kw___vectorcall: 5518 if (AttrReqs & AR_DeclspecAttributesParsed) { 5519 ParseMicrosoftTypeAttributes(DS.getAttributes()); 5520 continue; 5521 } 5522 goto DoneWithTypeQuals; 5523 case tok::kw___pascal: 5524 if (AttrReqs & AR_VendorAttributesParsed) { 5525 ParseBorlandTypeAttributes(DS.getAttributes()); 5526 continue; 5527 } 5528 goto DoneWithTypeQuals; 5529 5530 // Nullability type specifiers. 5531 case tok::kw__Nonnull: 5532 case tok::kw__Nullable: 5533 case tok::kw__Nullable_result: 5534 case tok::kw__Null_unspecified: 5535 ParseNullabilityTypeSpecifiers(DS.getAttributes()); 5536 continue; 5537 5538 // Objective-C 'kindof' types. 5539 case tok::kw___kindof: 5540 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc, 5541 nullptr, 0, ParsedAttr::AS_Keyword); 5542 (void)ConsumeToken(); 5543 continue; 5544 5545 case tok::kw___attribute: 5546 if (AttrReqs & AR_GNUAttributesParsedAndRejected) 5547 // When GNU attributes are expressly forbidden, diagnose their usage. 5548 Diag(Tok, diag::err_attributes_not_allowed); 5549 5550 // Parse the attributes even if they are rejected to ensure that error 5551 // recovery is graceful. 5552 if (AttrReqs & AR_GNUAttributesParsed || 5553 AttrReqs & AR_GNUAttributesParsedAndRejected) { 5554 ParseGNUAttributes(DS.getAttributes()); 5555 continue; // do *not* consume the next token! 5556 } 5557 // otherwise, FALL THROUGH! 5558 LLVM_FALLTHROUGH; 5559 default: 5560 DoneWithTypeQuals: 5561 // If this is not a type-qualifier token, we're done reading type 5562 // qualifiers. First verify that DeclSpec's are consistent. 5563 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy()); 5564 if (EndLoc.isValid()) 5565 DS.SetRangeEnd(EndLoc); 5566 return; 5567 } 5568 5569 // If the specifier combination wasn't legal, issue a diagnostic. 5570 if (isInvalid) { 5571 assert(PrevSpec && "Method did not return previous specifier!"); 5572 Diag(Tok, DiagID) << PrevSpec; 5573 } 5574 EndLoc = ConsumeToken(); 5575 } 5576 } 5577 5578 /// ParseDeclarator - Parse and verify a newly-initialized declarator. 5579 /// 5580 void Parser::ParseDeclarator(Declarator &D) { 5581 /// This implements the 'declarator' production in the C grammar, then checks 5582 /// for well-formedness and issues diagnostics. 5583 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 5584 } 5585 5586 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang, 5587 DeclaratorContext TheContext) { 5588 if (Kind == tok::star || Kind == tok::caret) 5589 return true; 5590 5591 if (Kind == tok::kw_pipe && 5592 ((Lang.OpenCL && Lang.OpenCLVersion >= 200) || Lang.OpenCLCPlusPlus)) 5593 return true; 5594 5595 if (!Lang.CPlusPlus) 5596 return false; 5597 5598 if (Kind == tok::amp) 5599 return true; 5600 5601 // We parse rvalue refs in C++03, because otherwise the errors are scary. 5602 // But we must not parse them in conversion-type-ids and new-type-ids, since 5603 // those can be legitimately followed by a && operator. 5604 // (The same thing can in theory happen after a trailing-return-type, but 5605 // since those are a C++11 feature, there is no rejects-valid issue there.) 5606 if (Kind == tok::ampamp) 5607 return Lang.CPlusPlus11 || (TheContext != DeclaratorContext::ConversionId && 5608 TheContext != DeclaratorContext::CXXNew); 5609 5610 return false; 5611 } 5612 5613 // Indicates whether the given declarator is a pipe declarator. 5614 static bool isPipeDeclerator(const Declarator &D) { 5615 const unsigned NumTypes = D.getNumTypeObjects(); 5616 5617 for (unsigned Idx = 0; Idx != NumTypes; ++Idx) 5618 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind) 5619 return true; 5620 5621 return false; 5622 } 5623 5624 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator 5625 /// is parsed by the function passed to it. Pass null, and the direct-declarator 5626 /// isn't parsed at all, making this function effectively parse the C++ 5627 /// ptr-operator production. 5628 /// 5629 /// If the grammar of this construct is extended, matching changes must also be 5630 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to 5631 /// isConstructorDeclarator. 5632 /// 5633 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl] 5634 /// [C] pointer[opt] direct-declarator 5635 /// [C++] direct-declarator 5636 /// [C++] ptr-operator declarator 5637 /// 5638 /// pointer: [C99 6.7.5] 5639 /// '*' type-qualifier-list[opt] 5640 /// '*' type-qualifier-list[opt] pointer 5641 /// 5642 /// ptr-operator: 5643 /// '*' cv-qualifier-seq[opt] 5644 /// '&' 5645 /// [C++0x] '&&' 5646 /// [GNU] '&' restrict[opt] attributes[opt] 5647 /// [GNU?] '&&' restrict[opt] attributes[opt] 5648 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 5649 void Parser::ParseDeclaratorInternal(Declarator &D, 5650 DirectDeclParseFunction DirectDeclParser) { 5651 if (Diags.hasAllExtensionsSilenced()) 5652 D.setExtension(); 5653 5654 // C++ member pointers start with a '::' or a nested-name. 5655 // Member pointers get special handling, since there's no place for the 5656 // scope spec in the generic path below. 5657 if (getLangOpts().CPlusPlus && 5658 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) || 5659 (Tok.is(tok::identifier) && 5660 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) || 5661 Tok.is(tok::annot_cxxscope))) { 5662 bool EnteringContext = D.getContext() == DeclaratorContext::File || 5663 D.getContext() == DeclaratorContext::Member; 5664 CXXScopeSpec SS; 5665 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 5666 /*ObjectHadErrors=*/false, EnteringContext); 5667 5668 if (SS.isNotEmpty()) { 5669 if (Tok.isNot(tok::star)) { 5670 // The scope spec really belongs to the direct-declarator. 5671 if (D.mayHaveIdentifier()) 5672 D.getCXXScopeSpec() = SS; 5673 else 5674 AnnotateScopeToken(SS, true); 5675 5676 if (DirectDeclParser) 5677 (this->*DirectDeclParser)(D); 5678 return; 5679 } 5680 5681 if (SS.isValid()) { 5682 checkCompoundToken(SS.getEndLoc(), tok::coloncolon, 5683 CompoundToken::MemberPtr); 5684 } 5685 5686 SourceLocation StarLoc = ConsumeToken(); 5687 D.SetRangeEnd(StarLoc); 5688 DeclSpec DS(AttrFactory); 5689 ParseTypeQualifierListOpt(DS); 5690 D.ExtendWithDeclSpec(DS); 5691 5692 // Recurse to parse whatever is left. 5693 ParseDeclaratorInternal(D, DirectDeclParser); 5694 5695 // Sema will have to catch (syntactically invalid) pointers into global 5696 // scope. It has to catch pointers into namespace scope anyway. 5697 D.AddTypeInfo(DeclaratorChunk::getMemberPointer( 5698 SS, DS.getTypeQualifiers(), StarLoc, DS.getEndLoc()), 5699 std::move(DS.getAttributes()), 5700 /* Don't replace range end. */ SourceLocation()); 5701 return; 5702 } 5703 } 5704 5705 tok::TokenKind Kind = Tok.getKind(); 5706 5707 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) { 5708 DeclSpec DS(AttrFactory); 5709 ParseTypeQualifierListOpt(DS); 5710 5711 D.AddTypeInfo( 5712 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()), 5713 std::move(DS.getAttributes()), SourceLocation()); 5714 } 5715 5716 // Not a pointer, C++ reference, or block. 5717 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) { 5718 if (DirectDeclParser) 5719 (this->*DirectDeclParser)(D); 5720 return; 5721 } 5722 5723 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference, 5724 // '&&' -> rvalue reference 5725 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&. 5726 D.SetRangeEnd(Loc); 5727 5728 if (Kind == tok::star || Kind == tok::caret) { 5729 // Is a pointer. 5730 DeclSpec DS(AttrFactory); 5731 5732 // GNU attributes are not allowed here in a new-type-id, but Declspec and 5733 // C++11 attributes are allowed. 5734 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed | 5735 ((D.getContext() != DeclaratorContext::CXXNew) 5736 ? AR_GNUAttributesParsed 5737 : AR_GNUAttributesParsedAndRejected); 5738 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier()); 5739 D.ExtendWithDeclSpec(DS); 5740 5741 // Recursively parse the declarator. 5742 ParseDeclaratorInternal(D, DirectDeclParser); 5743 if (Kind == tok::star) 5744 // Remember that we parsed a pointer type, and remember the type-quals. 5745 D.AddTypeInfo(DeclaratorChunk::getPointer( 5746 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(), 5747 DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(), 5748 DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()), 5749 std::move(DS.getAttributes()), SourceLocation()); 5750 else 5751 // Remember that we parsed a Block type, and remember the type-quals. 5752 D.AddTypeInfo( 5753 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc), 5754 std::move(DS.getAttributes()), SourceLocation()); 5755 } else { 5756 // Is a reference 5757 DeclSpec DS(AttrFactory); 5758 5759 // Complain about rvalue references in C++03, but then go on and build 5760 // the declarator. 5761 if (Kind == tok::ampamp) 5762 Diag(Loc, getLangOpts().CPlusPlus11 ? 5763 diag::warn_cxx98_compat_rvalue_reference : 5764 diag::ext_rvalue_reference); 5765 5766 // GNU-style and C++11 attributes are allowed here, as is restrict. 5767 ParseTypeQualifierListOpt(DS); 5768 D.ExtendWithDeclSpec(DS); 5769 5770 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the 5771 // cv-qualifiers are introduced through the use of a typedef or of a 5772 // template type argument, in which case the cv-qualifiers are ignored. 5773 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { 5774 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5775 Diag(DS.getConstSpecLoc(), 5776 diag::err_invalid_reference_qualifier_application) << "const"; 5777 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5778 Diag(DS.getVolatileSpecLoc(), 5779 diag::err_invalid_reference_qualifier_application) << "volatile"; 5780 // 'restrict' is permitted as an extension. 5781 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5782 Diag(DS.getAtomicSpecLoc(), 5783 diag::err_invalid_reference_qualifier_application) << "_Atomic"; 5784 } 5785 5786 // Recursively parse the declarator. 5787 ParseDeclaratorInternal(D, DirectDeclParser); 5788 5789 if (D.getNumTypeObjects() > 0) { 5790 // C++ [dcl.ref]p4: There shall be no references to references. 5791 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1); 5792 if (InnerChunk.Kind == DeclaratorChunk::Reference) { 5793 if (const IdentifierInfo *II = D.getIdentifier()) 5794 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 5795 << II; 5796 else 5797 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 5798 << "type name"; 5799 5800 // Once we've complained about the reference-to-reference, we 5801 // can go ahead and build the (technically ill-formed) 5802 // declarator: reference collapsing will take care of it. 5803 } 5804 } 5805 5806 // Remember that we parsed a reference type. 5807 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc, 5808 Kind == tok::amp), 5809 std::move(DS.getAttributes()), SourceLocation()); 5810 } 5811 } 5812 5813 // When correcting from misplaced brackets before the identifier, the location 5814 // is saved inside the declarator so that other diagnostic messages can use 5815 // them. This extracts and returns that location, or returns the provided 5816 // location if a stored location does not exist. 5817 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D, 5818 SourceLocation Loc) { 5819 if (D.getName().StartLocation.isInvalid() && 5820 D.getName().EndLocation.isValid()) 5821 return D.getName().EndLocation; 5822 5823 return Loc; 5824 } 5825 5826 /// ParseDirectDeclarator 5827 /// direct-declarator: [C99 6.7.5] 5828 /// [C99] identifier 5829 /// '(' declarator ')' 5830 /// [GNU] '(' attributes declarator ')' 5831 /// [C90] direct-declarator '[' constant-expression[opt] ']' 5832 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 5833 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 5834 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 5835 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 5836 /// [C++11] direct-declarator '[' constant-expression[opt] ']' 5837 /// attribute-specifier-seq[opt] 5838 /// direct-declarator '(' parameter-type-list ')' 5839 /// direct-declarator '(' identifier-list[opt] ')' 5840 /// [GNU] direct-declarator '(' parameter-forward-declarations 5841 /// parameter-type-list[opt] ')' 5842 /// [C++] direct-declarator '(' parameter-declaration-clause ')' 5843 /// cv-qualifier-seq[opt] exception-specification[opt] 5844 /// [C++11] direct-declarator '(' parameter-declaration-clause ')' 5845 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt] 5846 /// ref-qualifier[opt] exception-specification[opt] 5847 /// [C++] declarator-id 5848 /// [C++11] declarator-id attribute-specifier-seq[opt] 5849 /// 5850 /// declarator-id: [C++ 8] 5851 /// '...'[opt] id-expression 5852 /// '::'[opt] nested-name-specifier[opt] type-name 5853 /// 5854 /// id-expression: [C++ 5.1] 5855 /// unqualified-id 5856 /// qualified-id 5857 /// 5858 /// unqualified-id: [C++ 5.1] 5859 /// identifier 5860 /// operator-function-id 5861 /// conversion-function-id 5862 /// '~' class-name 5863 /// template-id 5864 /// 5865 /// C++17 adds the following, which we also handle here: 5866 /// 5867 /// simple-declaration: 5868 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';' 5869 /// 5870 /// Note, any additional constructs added here may need corresponding changes 5871 /// in isConstructorDeclarator. 5872 void Parser::ParseDirectDeclarator(Declarator &D) { 5873 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec()); 5874 5875 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) { 5876 // This might be a C++17 structured binding. 5877 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() && 5878 D.getCXXScopeSpec().isEmpty()) 5879 return ParseDecompositionDeclarator(D); 5880 5881 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in 5882 // this context it is a bitfield. Also in range-based for statement colon 5883 // may delimit for-range-declaration. 5884 ColonProtectionRAIIObject X( 5885 *this, D.getContext() == DeclaratorContext::Member || 5886 (D.getContext() == DeclaratorContext::ForInit && 5887 getLangOpts().CPlusPlus11)); 5888 5889 // ParseDeclaratorInternal might already have parsed the scope. 5890 if (D.getCXXScopeSpec().isEmpty()) { 5891 bool EnteringContext = D.getContext() == DeclaratorContext::File || 5892 D.getContext() == DeclaratorContext::Member; 5893 ParseOptionalCXXScopeSpecifier( 5894 D.getCXXScopeSpec(), /*ObjectType=*/nullptr, 5895 /*ObjectHadErrors=*/false, EnteringContext); 5896 } 5897 5898 if (D.getCXXScopeSpec().isValid()) { 5899 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), 5900 D.getCXXScopeSpec())) 5901 // Change the declaration context for name lookup, until this function 5902 // is exited (and the declarator has been parsed). 5903 DeclScopeObj.EnterDeclaratorScope(); 5904 else if (getObjCDeclContext()) { 5905 // Ensure that we don't interpret the next token as an identifier when 5906 // dealing with declarations in an Objective-C container. 5907 D.SetIdentifier(nullptr, Tok.getLocation()); 5908 D.setInvalidType(true); 5909 ConsumeToken(); 5910 goto PastIdentifier; 5911 } 5912 } 5913 5914 // C++0x [dcl.fct]p14: 5915 // There is a syntactic ambiguity when an ellipsis occurs at the end of a 5916 // parameter-declaration-clause without a preceding comma. In this case, 5917 // the ellipsis is parsed as part of the abstract-declarator if the type 5918 // of the parameter either names a template parameter pack that has not 5919 // been expanded or contains auto; otherwise, it is parsed as part of the 5920 // parameter-declaration-clause. 5921 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() && 5922 !((D.getContext() == DeclaratorContext::Prototype || 5923 D.getContext() == DeclaratorContext::LambdaExprParameter || 5924 D.getContext() == DeclaratorContext::BlockLiteral) && 5925 NextToken().is(tok::r_paren) && !D.hasGroupingParens() && 5926 !Actions.containsUnexpandedParameterPacks(D) && 5927 D.getDeclSpec().getTypeSpecType() != TST_auto)) { 5928 SourceLocation EllipsisLoc = ConsumeToken(); 5929 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) { 5930 // The ellipsis was put in the wrong place. Recover, and explain to 5931 // the user what they should have done. 5932 ParseDeclarator(D); 5933 if (EllipsisLoc.isValid()) 5934 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D); 5935 return; 5936 } else 5937 D.setEllipsisLoc(EllipsisLoc); 5938 5939 // The ellipsis can't be followed by a parenthesized declarator. We 5940 // check for that in ParseParenDeclarator, after we have disambiguated 5941 // the l_paren token. 5942 } 5943 5944 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id, 5945 tok::tilde)) { 5946 // We found something that indicates the start of an unqualified-id. 5947 // Parse that unqualified-id. 5948 bool AllowConstructorName; 5949 bool AllowDeductionGuide; 5950 if (D.getDeclSpec().hasTypeSpecifier()) { 5951 AllowConstructorName = false; 5952 AllowDeductionGuide = false; 5953 } else if (D.getCXXScopeSpec().isSet()) { 5954 AllowConstructorName = (D.getContext() == DeclaratorContext::File || 5955 D.getContext() == DeclaratorContext::Member); 5956 AllowDeductionGuide = false; 5957 } else { 5958 AllowConstructorName = (D.getContext() == DeclaratorContext::Member); 5959 AllowDeductionGuide = (D.getContext() == DeclaratorContext::File || 5960 D.getContext() == DeclaratorContext::Member); 5961 } 5962 5963 bool HadScope = D.getCXXScopeSpec().isValid(); 5964 if (ParseUnqualifiedId(D.getCXXScopeSpec(), 5965 /*ObjectType=*/nullptr, 5966 /*ObjectHadErrors=*/false, 5967 /*EnteringContext=*/true, 5968 /*AllowDestructorName=*/true, AllowConstructorName, 5969 AllowDeductionGuide, nullptr, D.getName()) || 5970 // Once we're past the identifier, if the scope was bad, mark the 5971 // whole declarator bad. 5972 D.getCXXScopeSpec().isInvalid()) { 5973 D.SetIdentifier(nullptr, Tok.getLocation()); 5974 D.setInvalidType(true); 5975 } else { 5976 // ParseUnqualifiedId might have parsed a scope specifier during error 5977 // recovery. If it did so, enter that scope. 5978 if (!HadScope && D.getCXXScopeSpec().isValid() && 5979 Actions.ShouldEnterDeclaratorScope(getCurScope(), 5980 D.getCXXScopeSpec())) 5981 DeclScopeObj.EnterDeclaratorScope(); 5982 5983 // Parsed the unqualified-id; update range information and move along. 5984 if (D.getSourceRange().getBegin().isInvalid()) 5985 D.SetRangeBegin(D.getName().getSourceRange().getBegin()); 5986 D.SetRangeEnd(D.getName().getSourceRange().getEnd()); 5987 } 5988 goto PastIdentifier; 5989 } 5990 5991 if (D.getCXXScopeSpec().isNotEmpty()) { 5992 // We have a scope specifier but no following unqualified-id. 5993 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()), 5994 diag::err_expected_unqualified_id) 5995 << /*C++*/1; 5996 D.SetIdentifier(nullptr, Tok.getLocation()); 5997 goto PastIdentifier; 5998 } 5999 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) { 6000 assert(!getLangOpts().CPlusPlus && 6001 "There's a C++-specific check for tok::identifier above"); 6002 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 6003 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 6004 D.SetRangeEnd(Tok.getLocation()); 6005 ConsumeToken(); 6006 goto PastIdentifier; 6007 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) { 6008 // We're not allowed an identifier here, but we got one. Try to figure out 6009 // if the user was trying to attach a name to the type, or whether the name 6010 // is some unrelated trailing syntax. 6011 bool DiagnoseIdentifier = false; 6012 if (D.hasGroupingParens()) 6013 // An identifier within parens is unlikely to be intended to be anything 6014 // other than a name being "declared". 6015 DiagnoseIdentifier = true; 6016 else if (D.getContext() == DeclaratorContext::TemplateArg) 6017 // T<int N> is an accidental identifier; T<int N indicates a missing '>'. 6018 DiagnoseIdentifier = 6019 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater); 6020 else if (D.getContext() == DeclaratorContext::AliasDecl || 6021 D.getContext() == DeclaratorContext::AliasTemplate) 6022 // The most likely error is that the ';' was forgotten. 6023 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi); 6024 else if ((D.getContext() == DeclaratorContext::TrailingReturn || 6025 D.getContext() == DeclaratorContext::TrailingReturnVar) && 6026 !isCXX11VirtSpecifier(Tok)) 6027 DiagnoseIdentifier = NextToken().isOneOf( 6028 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try); 6029 if (DiagnoseIdentifier) { 6030 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id) 6031 << FixItHint::CreateRemoval(Tok.getLocation()); 6032 D.SetIdentifier(nullptr, Tok.getLocation()); 6033 ConsumeToken(); 6034 goto PastIdentifier; 6035 } 6036 } 6037 6038 if (Tok.is(tok::l_paren)) { 6039 // If this might be an abstract-declarator followed by a direct-initializer, 6040 // check whether this is a valid declarator chunk. If it can't be, assume 6041 // that it's an initializer instead. 6042 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) { 6043 RevertingTentativeParsingAction PA(*this); 6044 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) == 6045 TPResult::False) { 6046 D.SetIdentifier(nullptr, Tok.getLocation()); 6047 goto PastIdentifier; 6048 } 6049 } 6050 6051 // direct-declarator: '(' declarator ')' 6052 // direct-declarator: '(' attributes declarator ')' 6053 // Example: 'char (*X)' or 'int (*XX)(void)' 6054 ParseParenDeclarator(D); 6055 6056 // If the declarator was parenthesized, we entered the declarator 6057 // scope when parsing the parenthesized declarator, then exited 6058 // the scope already. Re-enter the scope, if we need to. 6059 if (D.getCXXScopeSpec().isSet()) { 6060 // If there was an error parsing parenthesized declarator, declarator 6061 // scope may have been entered before. Don't do it again. 6062 if (!D.isInvalidType() && 6063 Actions.ShouldEnterDeclaratorScope(getCurScope(), 6064 D.getCXXScopeSpec())) 6065 // Change the declaration context for name lookup, until this function 6066 // is exited (and the declarator has been parsed). 6067 DeclScopeObj.EnterDeclaratorScope(); 6068 } 6069 } else if (D.mayOmitIdentifier()) { 6070 // This could be something simple like "int" (in which case the declarator 6071 // portion is empty), if an abstract-declarator is allowed. 6072 D.SetIdentifier(nullptr, Tok.getLocation()); 6073 6074 // The grammar for abstract-pack-declarator does not allow grouping parens. 6075 // FIXME: Revisit this once core issue 1488 is resolved. 6076 if (D.hasEllipsis() && D.hasGroupingParens()) 6077 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()), 6078 diag::ext_abstract_pack_declarator_parens); 6079 } else { 6080 if (Tok.getKind() == tok::annot_pragma_parser_crash) 6081 LLVM_BUILTIN_TRAP; 6082 if (Tok.is(tok::l_square)) 6083 return ParseMisplacedBracketDeclarator(D); 6084 if (D.getContext() == DeclaratorContext::Member) { 6085 // Objective-C++: Detect C++ keywords and try to prevent further errors by 6086 // treating these keyword as valid member names. 6087 if (getLangOpts().ObjC && getLangOpts().CPlusPlus && 6088 Tok.getIdentifierInfo() && 6089 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) { 6090 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 6091 diag::err_expected_member_name_or_semi_objcxx_keyword) 6092 << Tok.getIdentifierInfo() 6093 << (D.getDeclSpec().isEmpty() ? SourceRange() 6094 : D.getDeclSpec().getSourceRange()); 6095 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 6096 D.SetRangeEnd(Tok.getLocation()); 6097 ConsumeToken(); 6098 goto PastIdentifier; 6099 } 6100 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 6101 diag::err_expected_member_name_or_semi) 6102 << (D.getDeclSpec().isEmpty() ? SourceRange() 6103 : D.getDeclSpec().getSourceRange()); 6104 } else if (getLangOpts().CPlusPlus) { 6105 if (Tok.isOneOf(tok::period, tok::arrow)) 6106 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow); 6107 else { 6108 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc(); 6109 if (Tok.isAtStartOfLine() && Loc.isValid()) 6110 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id) 6111 << getLangOpts().CPlusPlus; 6112 else 6113 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 6114 diag::err_expected_unqualified_id) 6115 << getLangOpts().CPlusPlus; 6116 } 6117 } else { 6118 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 6119 diag::err_expected_either) 6120 << tok::identifier << tok::l_paren; 6121 } 6122 D.SetIdentifier(nullptr, Tok.getLocation()); 6123 D.setInvalidType(true); 6124 } 6125 6126 PastIdentifier: 6127 assert(D.isPastIdentifier() && 6128 "Haven't past the location of the identifier yet?"); 6129 6130 // Don't parse attributes unless we have parsed an unparenthesized name. 6131 if (D.hasName() && !D.getNumTypeObjects()) 6132 MaybeParseCXX11Attributes(D); 6133 6134 while (1) { 6135 if (Tok.is(tok::l_paren)) { 6136 bool IsFunctionDeclaration = D.isFunctionDeclaratorAFunctionDeclaration(); 6137 // Enter function-declaration scope, limiting any declarators to the 6138 // function prototype scope, including parameter declarators. 6139 ParseScope PrototypeScope(this, 6140 Scope::FunctionPrototypeScope|Scope::DeclScope| 6141 (IsFunctionDeclaration 6142 ? Scope::FunctionDeclarationScope : 0)); 6143 6144 // The paren may be part of a C++ direct initializer, eg. "int x(1);". 6145 // In such a case, check if we actually have a function declarator; if it 6146 // is not, the declarator has been fully parsed. 6147 bool IsAmbiguous = false; 6148 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) { 6149 // The name of the declarator, if any, is tentatively declared within 6150 // a possible direct initializer. 6151 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier()); 6152 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous); 6153 TentativelyDeclaredIdentifiers.pop_back(); 6154 if (!IsFunctionDecl) 6155 break; 6156 } 6157 ParsedAttributes attrs(AttrFactory); 6158 BalancedDelimiterTracker T(*this, tok::l_paren); 6159 T.consumeOpen(); 6160 if (IsFunctionDeclaration) 6161 Actions.ActOnStartFunctionDeclarationDeclarator(D, 6162 TemplateParameterDepth); 6163 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous); 6164 if (IsFunctionDeclaration) 6165 Actions.ActOnFinishFunctionDeclarationDeclarator(D); 6166 PrototypeScope.Exit(); 6167 } else if (Tok.is(tok::l_square)) { 6168 ParseBracketDeclarator(D); 6169 } else if (Tok.is(tok::kw_requires) && D.hasGroupingParens()) { 6170 // This declarator is declaring a function, but the requires clause is 6171 // in the wrong place: 6172 // void (f() requires true); 6173 // instead of 6174 // void f() requires true; 6175 // or 6176 // void (f()) requires true; 6177 Diag(Tok, diag::err_requires_clause_inside_parens); 6178 ConsumeToken(); 6179 ExprResult TrailingRequiresClause = Actions.CorrectDelayedTyposInExpr( 6180 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true)); 6181 if (TrailingRequiresClause.isUsable() && D.isFunctionDeclarator() && 6182 !D.hasTrailingRequiresClause()) 6183 // We're already ill-formed if we got here but we'll accept it anyway. 6184 D.setTrailingRequiresClause(TrailingRequiresClause.get()); 6185 } else { 6186 break; 6187 } 6188 } 6189 } 6190 6191 void Parser::ParseDecompositionDeclarator(Declarator &D) { 6192 assert(Tok.is(tok::l_square)); 6193 6194 // If this doesn't look like a structured binding, maybe it's a misplaced 6195 // array declarator. 6196 // FIXME: Consume the l_square first so we don't need extra lookahead for 6197 // this. 6198 if (!(NextToken().is(tok::identifier) && 6199 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) && 6200 !(NextToken().is(tok::r_square) && 6201 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace))) 6202 return ParseMisplacedBracketDeclarator(D); 6203 6204 BalancedDelimiterTracker T(*this, tok::l_square); 6205 T.consumeOpen(); 6206 6207 SmallVector<DecompositionDeclarator::Binding, 32> Bindings; 6208 while (Tok.isNot(tok::r_square)) { 6209 if (!Bindings.empty()) { 6210 if (Tok.is(tok::comma)) 6211 ConsumeToken(); 6212 else { 6213 if (Tok.is(tok::identifier)) { 6214 SourceLocation EndLoc = getEndOfPreviousToken(); 6215 Diag(EndLoc, diag::err_expected) 6216 << tok::comma << FixItHint::CreateInsertion(EndLoc, ","); 6217 } else { 6218 Diag(Tok, diag::err_expected_comma_or_rsquare); 6219 } 6220 6221 SkipUntil(tok::r_square, tok::comma, tok::identifier, 6222 StopAtSemi | StopBeforeMatch); 6223 if (Tok.is(tok::comma)) 6224 ConsumeToken(); 6225 else if (Tok.isNot(tok::identifier)) 6226 break; 6227 } 6228 } 6229 6230 if (Tok.isNot(tok::identifier)) { 6231 Diag(Tok, diag::err_expected) << tok::identifier; 6232 break; 6233 } 6234 6235 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()}); 6236 ConsumeToken(); 6237 } 6238 6239 if (Tok.isNot(tok::r_square)) 6240 // We've already diagnosed a problem here. 6241 T.skipToEnd(); 6242 else { 6243 // C++17 does not allow the identifier-list in a structured binding 6244 // to be empty. 6245 if (Bindings.empty()) 6246 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty); 6247 6248 T.consumeClose(); 6249 } 6250 6251 return D.setDecompositionBindings(T.getOpenLocation(), Bindings, 6252 T.getCloseLocation()); 6253 } 6254 6255 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is 6256 /// only called before the identifier, so these are most likely just grouping 6257 /// parens for precedence. If we find that these are actually function 6258 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. 6259 /// 6260 /// direct-declarator: 6261 /// '(' declarator ')' 6262 /// [GNU] '(' attributes declarator ')' 6263 /// direct-declarator '(' parameter-type-list ')' 6264 /// direct-declarator '(' identifier-list[opt] ')' 6265 /// [GNU] direct-declarator '(' parameter-forward-declarations 6266 /// parameter-type-list[opt] ')' 6267 /// 6268 void Parser::ParseParenDeclarator(Declarator &D) { 6269 BalancedDelimiterTracker T(*this, tok::l_paren); 6270 T.consumeOpen(); 6271 6272 assert(!D.isPastIdentifier() && "Should be called before passing identifier"); 6273 6274 // Eat any attributes before we look at whether this is a grouping or function 6275 // declarator paren. If this is a grouping paren, the attribute applies to 6276 // the type being built up, for example: 6277 // int (__attribute__(()) *x)(long y) 6278 // If this ends up not being a grouping paren, the attribute applies to the 6279 // first argument, for example: 6280 // int (__attribute__(()) int x) 6281 // In either case, we need to eat any attributes to be able to determine what 6282 // sort of paren this is. 6283 // 6284 ParsedAttributes attrs(AttrFactory); 6285 bool RequiresArg = false; 6286 if (Tok.is(tok::kw___attribute)) { 6287 ParseGNUAttributes(attrs); 6288 6289 // We require that the argument list (if this is a non-grouping paren) be 6290 // present even if the attribute list was empty. 6291 RequiresArg = true; 6292 } 6293 6294 // Eat any Microsoft extensions. 6295 ParseMicrosoftTypeAttributes(attrs); 6296 6297 // Eat any Borland extensions. 6298 if (Tok.is(tok::kw___pascal)) 6299 ParseBorlandTypeAttributes(attrs); 6300 6301 // If we haven't past the identifier yet (or where the identifier would be 6302 // stored, if this is an abstract declarator), then this is probably just 6303 // grouping parens. However, if this could be an abstract-declarator, then 6304 // this could also be the start of function arguments (consider 'void()'). 6305 bool isGrouping; 6306 6307 if (!D.mayOmitIdentifier()) { 6308 // If this can't be an abstract-declarator, this *must* be a grouping 6309 // paren, because we haven't seen the identifier yet. 6310 isGrouping = true; 6311 } else if (Tok.is(tok::r_paren) || // 'int()' is a function. 6312 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) && 6313 NextToken().is(tok::r_paren)) || // C++ int(...) 6314 isDeclarationSpecifier() || // 'int(int)' is a function. 6315 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function. 6316 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is 6317 // considered to be a type, not a K&R identifier-list. 6318 isGrouping = false; 6319 } else { 6320 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. 6321 isGrouping = true; 6322 } 6323 6324 // If this is a grouping paren, handle: 6325 // direct-declarator: '(' declarator ')' 6326 // direct-declarator: '(' attributes declarator ')' 6327 if (isGrouping) { 6328 SourceLocation EllipsisLoc = D.getEllipsisLoc(); 6329 D.setEllipsisLoc(SourceLocation()); 6330 6331 bool hadGroupingParens = D.hasGroupingParens(); 6332 D.setGroupingParens(true); 6333 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 6334 // Match the ')'. 6335 T.consumeClose(); 6336 D.AddTypeInfo( 6337 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()), 6338 std::move(attrs), T.getCloseLocation()); 6339 6340 D.setGroupingParens(hadGroupingParens); 6341 6342 // An ellipsis cannot be placed outside parentheses. 6343 if (EllipsisLoc.isValid()) 6344 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D); 6345 6346 return; 6347 } 6348 6349 // Okay, if this wasn't a grouping paren, it must be the start of a function 6350 // argument list. Recognize that this declarator will never have an 6351 // identifier (and remember where it would have been), then call into 6352 // ParseFunctionDeclarator to handle of argument list. 6353 D.SetIdentifier(nullptr, Tok.getLocation()); 6354 6355 // Enter function-declaration scope, limiting any declarators to the 6356 // function prototype scope, including parameter declarators. 6357 ParseScope PrototypeScope(this, 6358 Scope::FunctionPrototypeScope | Scope::DeclScope | 6359 (D.isFunctionDeclaratorAFunctionDeclaration() 6360 ? Scope::FunctionDeclarationScope : 0)); 6361 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg); 6362 PrototypeScope.Exit(); 6363 } 6364 6365 void Parser::InitCXXThisScopeForDeclaratorIfRelevant( 6366 const Declarator &D, const DeclSpec &DS, 6367 llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope) { 6368 // C++11 [expr.prim.general]p3: 6369 // If a declaration declares a member function or member function 6370 // template of a class X, the expression this is a prvalue of type 6371 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 6372 // and the end of the function-definition, member-declarator, or 6373 // declarator. 6374 // FIXME: currently, "static" case isn't handled correctly. 6375 bool IsCXX11MemberFunction = 6376 getLangOpts().CPlusPlus11 && 6377 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6378 (D.getContext() == DeclaratorContext::Member 6379 ? !D.getDeclSpec().isFriendSpecified() 6380 : D.getContext() == DeclaratorContext::File && 6381 D.getCXXScopeSpec().isValid() && 6382 Actions.CurContext->isRecord()); 6383 if (!IsCXX11MemberFunction) 6384 return; 6385 6386 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers()); 6387 if (D.getDeclSpec().hasConstexprSpecifier() && !getLangOpts().CPlusPlus14) 6388 Q.addConst(); 6389 // FIXME: Collect C++ address spaces. 6390 // If there are multiple different address spaces, the source is invalid. 6391 // Carry on using the first addr space for the qualifiers of 'this'. 6392 // The diagnostic will be given later while creating the function 6393 // prototype for the method. 6394 if (getLangOpts().OpenCLCPlusPlus) { 6395 for (ParsedAttr &attr : DS.getAttributes()) { 6396 LangAS ASIdx = attr.asOpenCLLangAS(); 6397 if (ASIdx != LangAS::Default) { 6398 Q.addAddressSpace(ASIdx); 6399 break; 6400 } 6401 } 6402 } 6403 ThisScope.emplace(Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q, 6404 IsCXX11MemberFunction); 6405 } 6406 6407 /// ParseFunctionDeclarator - We are after the identifier and have parsed the 6408 /// declarator D up to a paren, which indicates that we are parsing function 6409 /// arguments. 6410 /// 6411 /// If FirstArgAttrs is non-null, then the caller parsed those arguments 6412 /// immediately after the open paren - they should be considered to be the 6413 /// first argument of a parameter. 6414 /// 6415 /// If RequiresArg is true, then the first argument of the function is required 6416 /// to be present and required to not be an identifier list. 6417 /// 6418 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt], 6419 /// (C++11) ref-qualifier[opt], exception-specification[opt], 6420 /// (C++11) attribute-specifier-seq[opt], (C++11) trailing-return-type[opt] and 6421 /// (C++2a) the trailing requires-clause. 6422 /// 6423 /// [C++11] exception-specification: 6424 /// dynamic-exception-specification 6425 /// noexcept-specification 6426 /// 6427 void Parser::ParseFunctionDeclarator(Declarator &D, 6428 ParsedAttributes &FirstArgAttrs, 6429 BalancedDelimiterTracker &Tracker, 6430 bool IsAmbiguous, 6431 bool RequiresArg) { 6432 assert(getCurScope()->isFunctionPrototypeScope() && 6433 "Should call from a Function scope"); 6434 // lparen is already consumed! 6435 assert(D.isPastIdentifier() && "Should not call before identifier!"); 6436 6437 // This should be true when the function has typed arguments. 6438 // Otherwise, it is treated as a K&R-style function. 6439 bool HasProto = false; 6440 // Build up an array of information about the parsed arguments. 6441 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 6442 // Remember where we see an ellipsis, if any. 6443 SourceLocation EllipsisLoc; 6444 6445 DeclSpec DS(AttrFactory); 6446 bool RefQualifierIsLValueRef = true; 6447 SourceLocation RefQualifierLoc; 6448 ExceptionSpecificationType ESpecType = EST_None; 6449 SourceRange ESpecRange; 6450 SmallVector<ParsedType, 2> DynamicExceptions; 6451 SmallVector<SourceRange, 2> DynamicExceptionRanges; 6452 ExprResult NoexceptExpr; 6453 CachedTokens *ExceptionSpecTokens = nullptr; 6454 ParsedAttributesWithRange FnAttrs(AttrFactory); 6455 TypeResult TrailingReturnType; 6456 SourceLocation TrailingReturnTypeLoc; 6457 6458 /* LocalEndLoc is the end location for the local FunctionTypeLoc. 6459 EndLoc is the end location for the function declarator. 6460 They differ for trailing return types. */ 6461 SourceLocation StartLoc, LocalEndLoc, EndLoc; 6462 SourceLocation LParenLoc, RParenLoc; 6463 LParenLoc = Tracker.getOpenLocation(); 6464 StartLoc = LParenLoc; 6465 6466 if (isFunctionDeclaratorIdentifierList()) { 6467 if (RequiresArg) 6468 Diag(Tok, diag::err_argument_required_after_attribute); 6469 6470 ParseFunctionDeclaratorIdentifierList(D, ParamInfo); 6471 6472 Tracker.consumeClose(); 6473 RParenLoc = Tracker.getCloseLocation(); 6474 LocalEndLoc = RParenLoc; 6475 EndLoc = RParenLoc; 6476 6477 // If there are attributes following the identifier list, parse them and 6478 // prohibit them. 6479 MaybeParseCXX11Attributes(FnAttrs); 6480 ProhibitAttributes(FnAttrs); 6481 } else { 6482 if (Tok.isNot(tok::r_paren)) 6483 ParseParameterDeclarationClause(D.getContext(), FirstArgAttrs, ParamInfo, 6484 EllipsisLoc); 6485 else if (RequiresArg) 6486 Diag(Tok, diag::err_argument_required_after_attribute); 6487 6488 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus 6489 || getLangOpts().OpenCL; 6490 6491 // If we have the closing ')', eat it. 6492 Tracker.consumeClose(); 6493 RParenLoc = Tracker.getCloseLocation(); 6494 LocalEndLoc = RParenLoc; 6495 EndLoc = RParenLoc; 6496 6497 if (getLangOpts().CPlusPlus) { 6498 // FIXME: Accept these components in any order, and produce fixits to 6499 // correct the order if the user gets it wrong. Ideally we should deal 6500 // with the pure-specifier in the same way. 6501 6502 // Parse cv-qualifier-seq[opt]. 6503 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed, 6504 /*AtomicAllowed*/ false, 6505 /*IdentifierRequired=*/false, 6506 llvm::function_ref<void()>([&]() { 6507 Actions.CodeCompleteFunctionQualifiers(DS, D); 6508 })); 6509 if (!DS.getSourceRange().getEnd().isInvalid()) { 6510 EndLoc = DS.getSourceRange().getEnd(); 6511 } 6512 6513 // Parse ref-qualifier[opt]. 6514 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) 6515 EndLoc = RefQualifierLoc; 6516 6517 llvm::Optional<Sema::CXXThisScopeRAII> ThisScope; 6518 InitCXXThisScopeForDeclaratorIfRelevant(D, DS, ThisScope); 6519 6520 // Parse exception-specification[opt]. 6521 // FIXME: Per [class.mem]p6, all exception-specifications at class scope 6522 // should be delayed, including those for non-members (eg, friend 6523 // declarations). But only applying this to member declarations is 6524 // consistent with what other implementations do. 6525 bool Delayed = D.isFirstDeclarationOfMember() && 6526 D.isFunctionDeclaratorAFunctionDeclaration(); 6527 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) && 6528 GetLookAheadToken(0).is(tok::kw_noexcept) && 6529 GetLookAheadToken(1).is(tok::l_paren) && 6530 GetLookAheadToken(2).is(tok::kw_noexcept) && 6531 GetLookAheadToken(3).is(tok::l_paren) && 6532 GetLookAheadToken(4).is(tok::identifier) && 6533 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) { 6534 // HACK: We've got an exception-specification 6535 // noexcept(noexcept(swap(...))) 6536 // or 6537 // noexcept(noexcept(swap(...)) && noexcept(swap(...))) 6538 // on a 'swap' member function. This is a libstdc++ bug; the lookup 6539 // for 'swap' will only find the function we're currently declaring, 6540 // whereas it expects to find a non-member swap through ADL. Turn off 6541 // delayed parsing to give it a chance to find what it expects. 6542 Delayed = false; 6543 } 6544 ESpecType = tryParseExceptionSpecification(Delayed, 6545 ESpecRange, 6546 DynamicExceptions, 6547 DynamicExceptionRanges, 6548 NoexceptExpr, 6549 ExceptionSpecTokens); 6550 if (ESpecType != EST_None) 6551 EndLoc = ESpecRange.getEnd(); 6552 6553 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes 6554 // after the exception-specification. 6555 MaybeParseCXX11Attributes(FnAttrs); 6556 6557 // Parse trailing-return-type[opt]. 6558 LocalEndLoc = EndLoc; 6559 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) { 6560 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type); 6561 if (D.getDeclSpec().getTypeSpecType() == TST_auto) 6562 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 6563 LocalEndLoc = Tok.getLocation(); 6564 SourceRange Range; 6565 TrailingReturnType = 6566 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit()); 6567 TrailingReturnTypeLoc = Range.getBegin(); 6568 EndLoc = Range.getEnd(); 6569 } 6570 } else if (standardAttributesAllowed()) { 6571 MaybeParseCXX11Attributes(FnAttrs); 6572 } 6573 } 6574 6575 // Collect non-parameter declarations from the prototype if this is a function 6576 // declaration. They will be moved into the scope of the function. Only do 6577 // this in C and not C++, where the decls will continue to live in the 6578 // surrounding context. 6579 SmallVector<NamedDecl *, 0> DeclsInPrototype; 6580 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope && 6581 !getLangOpts().CPlusPlus) { 6582 for (Decl *D : getCurScope()->decls()) { 6583 NamedDecl *ND = dyn_cast<NamedDecl>(D); 6584 if (!ND || isa<ParmVarDecl>(ND)) 6585 continue; 6586 DeclsInPrototype.push_back(ND); 6587 } 6588 } 6589 6590 // Remember that we parsed a function type, and remember the attributes. 6591 D.AddTypeInfo(DeclaratorChunk::getFunction( 6592 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(), 6593 ParamInfo.size(), EllipsisLoc, RParenLoc, 6594 RefQualifierIsLValueRef, RefQualifierLoc, 6595 /*MutableLoc=*/SourceLocation(), 6596 ESpecType, ESpecRange, DynamicExceptions.data(), 6597 DynamicExceptionRanges.data(), DynamicExceptions.size(), 6598 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr, 6599 ExceptionSpecTokens, DeclsInPrototype, StartLoc, 6600 LocalEndLoc, D, TrailingReturnType, TrailingReturnTypeLoc, 6601 &DS), 6602 std::move(FnAttrs), EndLoc); 6603 } 6604 6605 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns 6606 /// true if a ref-qualifier is found. 6607 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef, 6608 SourceLocation &RefQualifierLoc) { 6609 if (Tok.isOneOf(tok::amp, tok::ampamp)) { 6610 Diag(Tok, getLangOpts().CPlusPlus11 ? 6611 diag::warn_cxx98_compat_ref_qualifier : 6612 diag::ext_ref_qualifier); 6613 6614 RefQualifierIsLValueRef = Tok.is(tok::amp); 6615 RefQualifierLoc = ConsumeToken(); 6616 return true; 6617 } 6618 return false; 6619 } 6620 6621 /// isFunctionDeclaratorIdentifierList - This parameter list may have an 6622 /// identifier list form for a K&R-style function: void foo(a,b,c) 6623 /// 6624 /// Note that identifier-lists are only allowed for normal declarators, not for 6625 /// abstract-declarators. 6626 bool Parser::isFunctionDeclaratorIdentifierList() { 6627 return !getLangOpts().CPlusPlus 6628 && Tok.is(tok::identifier) 6629 && !TryAltiVecVectorToken() 6630 // K&R identifier lists can't have typedefs as identifiers, per C99 6631 // 6.7.5.3p11. 6632 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) 6633 // Identifier lists follow a really simple grammar: the identifiers can 6634 // be followed *only* by a ", identifier" or ")". However, K&R 6635 // identifier lists are really rare in the brave new modern world, and 6636 // it is very common for someone to typo a type in a non-K&R style 6637 // list. If we are presented with something like: "void foo(intptr x, 6638 // float y)", we don't want to start parsing the function declarator as 6639 // though it is a K&R style declarator just because intptr is an 6640 // invalid type. 6641 // 6642 // To handle this, we check to see if the token after the first 6643 // identifier is a "," or ")". Only then do we parse it as an 6644 // identifier list. 6645 && (!Tok.is(tok::eof) && 6646 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren))); 6647 } 6648 6649 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator 6650 /// we found a K&R-style identifier list instead of a typed parameter list. 6651 /// 6652 /// After returning, ParamInfo will hold the parsed parameters. 6653 /// 6654 /// identifier-list: [C99 6.7.5] 6655 /// identifier 6656 /// identifier-list ',' identifier 6657 /// 6658 void Parser::ParseFunctionDeclaratorIdentifierList( 6659 Declarator &D, 6660 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) { 6661 // If there was no identifier specified for the declarator, either we are in 6662 // an abstract-declarator, or we are in a parameter declarator which was found 6663 // to be abstract. In abstract-declarators, identifier lists are not valid: 6664 // diagnose this. 6665 if (!D.getIdentifier()) 6666 Diag(Tok, diag::ext_ident_list_in_param); 6667 6668 // Maintain an efficient lookup of params we have seen so far. 6669 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar; 6670 6671 do { 6672 // If this isn't an identifier, report the error and skip until ')'. 6673 if (Tok.isNot(tok::identifier)) { 6674 Diag(Tok, diag::err_expected) << tok::identifier; 6675 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch); 6676 // Forget we parsed anything. 6677 ParamInfo.clear(); 6678 return; 6679 } 6680 6681 IdentifierInfo *ParmII = Tok.getIdentifierInfo(); 6682 6683 // Reject 'typedef int y; int test(x, y)', but continue parsing. 6684 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope())) 6685 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; 6686 6687 // Verify that the argument identifier has not already been mentioned. 6688 if (!ParamsSoFar.insert(ParmII).second) { 6689 Diag(Tok, diag::err_param_redefinition) << ParmII; 6690 } else { 6691 // Remember this identifier in ParamInfo. 6692 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 6693 Tok.getLocation(), 6694 nullptr)); 6695 } 6696 6697 // Eat the identifier. 6698 ConsumeToken(); 6699 // The list continues if we see a comma. 6700 } while (TryConsumeToken(tok::comma)); 6701 } 6702 6703 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list 6704 /// after the opening parenthesis. This function will not parse a K&R-style 6705 /// identifier list. 6706 /// 6707 /// DeclContext is the context of the declarator being parsed. If FirstArgAttrs 6708 /// is non-null, then the caller parsed those attributes immediately after the 6709 /// open paren - they should be considered to be part of the first parameter. 6710 /// 6711 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will 6712 /// be the location of the ellipsis, if any was parsed. 6713 /// 6714 /// parameter-type-list: [C99 6.7.5] 6715 /// parameter-list 6716 /// parameter-list ',' '...' 6717 /// [C++] parameter-list '...' 6718 /// 6719 /// parameter-list: [C99 6.7.5] 6720 /// parameter-declaration 6721 /// parameter-list ',' parameter-declaration 6722 /// 6723 /// parameter-declaration: [C99 6.7.5] 6724 /// declaration-specifiers declarator 6725 /// [C++] declaration-specifiers declarator '=' assignment-expression 6726 /// [C++11] initializer-clause 6727 /// [GNU] declaration-specifiers declarator attributes 6728 /// declaration-specifiers abstract-declarator[opt] 6729 /// [C++] declaration-specifiers abstract-declarator[opt] 6730 /// '=' assignment-expression 6731 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes 6732 /// [C++11] attribute-specifier-seq parameter-declaration 6733 /// 6734 void Parser::ParseParameterDeclarationClause( 6735 DeclaratorContext DeclaratorCtx, 6736 ParsedAttributes &FirstArgAttrs, 6737 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, 6738 SourceLocation &EllipsisLoc) { 6739 6740 // Avoid exceeding the maximum function scope depth. 6741 // See https://bugs.llvm.org/show_bug.cgi?id=19607 6742 // Note Sema::ActOnParamDeclarator calls ParmVarDecl::setScopeInfo with 6743 // getFunctionPrototypeDepth() - 1. 6744 if (getCurScope()->getFunctionPrototypeDepth() - 1 > 6745 ParmVarDecl::getMaxFunctionScopeDepth()) { 6746 Diag(Tok.getLocation(), diag::err_function_scope_depth_exceeded) 6747 << ParmVarDecl::getMaxFunctionScopeDepth(); 6748 cutOffParsing(); 6749 return; 6750 } 6751 6752 do { 6753 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq 6754 // before deciding this was a parameter-declaration-clause. 6755 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) 6756 break; 6757 6758 // Parse the declaration-specifiers. 6759 // Just use the ParsingDeclaration "scope" of the declarator. 6760 DeclSpec DS(AttrFactory); 6761 6762 // Parse any C++11 attributes. 6763 MaybeParseCXX11Attributes(DS.getAttributes()); 6764 6765 // Skip any Microsoft attributes before a param. 6766 MaybeParseMicrosoftAttributes(DS.getAttributes()); 6767 6768 SourceLocation DSStart = Tok.getLocation(); 6769 6770 // If the caller parsed attributes for the first argument, add them now. 6771 // Take them so that we only apply the attributes to the first parameter. 6772 // FIXME: If we can leave the attributes in the token stream somehow, we can 6773 // get rid of a parameter (FirstArgAttrs) and this statement. It might be 6774 // too much hassle. 6775 DS.takeAttributesFrom(FirstArgAttrs); 6776 6777 ParseDeclarationSpecifiers(DS); 6778 6779 6780 // Parse the declarator. This is "PrototypeContext" or 6781 // "LambdaExprParameterContext", because we must accept either 6782 // 'declarator' or 'abstract-declarator' here. 6783 Declarator ParmDeclarator( 6784 DS, DeclaratorCtx == DeclaratorContext::RequiresExpr 6785 ? DeclaratorContext::RequiresExpr 6786 : DeclaratorCtx == DeclaratorContext::LambdaExpr 6787 ? DeclaratorContext::LambdaExprParameter 6788 : DeclaratorContext::Prototype); 6789 ParseDeclarator(ParmDeclarator); 6790 6791 // Parse GNU attributes, if present. 6792 MaybeParseGNUAttributes(ParmDeclarator); 6793 6794 if (Tok.is(tok::kw_requires)) { 6795 // User tried to define a requires clause in a parameter declaration, 6796 // which is surely not a function declaration. 6797 // void f(int (*g)(int, int) requires true); 6798 Diag(Tok, 6799 diag::err_requires_clause_on_declarator_not_declaring_a_function); 6800 ConsumeToken(); 6801 Actions.CorrectDelayedTyposInExpr( 6802 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true)); 6803 } 6804 6805 // Remember this parsed parameter in ParamInfo. 6806 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier(); 6807 6808 // DefArgToks is used when the parsing of default arguments needs 6809 // to be delayed. 6810 std::unique_ptr<CachedTokens> DefArgToks; 6811 6812 // If no parameter was specified, verify that *something* was specified, 6813 // otherwise we have a missing type and identifier. 6814 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr && 6815 ParmDeclarator.getNumTypeObjects() == 0) { 6816 // Completely missing, emit error. 6817 Diag(DSStart, diag::err_missing_param); 6818 } else { 6819 // Otherwise, we have something. Add it and let semantic analysis try 6820 // to grok it and add the result to the ParamInfo we are building. 6821 6822 // Last chance to recover from a misplaced ellipsis in an attempted 6823 // parameter pack declaration. 6824 if (Tok.is(tok::ellipsis) && 6825 (NextToken().isNot(tok::r_paren) || 6826 (!ParmDeclarator.getEllipsisLoc().isValid() && 6827 !Actions.isUnexpandedParameterPackPermitted())) && 6828 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) 6829 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator); 6830 6831 // Now we are at the point where declarator parsing is finished. 6832 // 6833 // Try to catch keywords in place of the identifier in a declarator, and 6834 // in particular the common case where: 6835 // 1 identifier comes at the end of the declarator 6836 // 2 if the identifier is dropped, the declarator is valid but anonymous 6837 // (no identifier) 6838 // 3 declarator parsing succeeds, and then we have a trailing keyword, 6839 // which is never valid in a param list (e.g. missing a ',') 6840 // And we can't handle this in ParseDeclarator because in general keywords 6841 // may be allowed to follow the declarator. (And in some cases there'd be 6842 // better recovery like inserting punctuation). ParseDeclarator is just 6843 // treating this as an anonymous parameter, and fortunately at this point 6844 // we've already almost done that. 6845 // 6846 // We care about case 1) where the declarator type should be known, and 6847 // the identifier should be null. 6848 if (!ParmDeclarator.isInvalidType() && !ParmDeclarator.hasName()) { 6849 if (Tok.getIdentifierInfo() && 6850 Tok.getIdentifierInfo()->isKeyword(getLangOpts())) { 6851 Diag(Tok, diag::err_keyword_as_parameter) << PP.getSpelling(Tok); 6852 // Consume the keyword. 6853 ConsumeToken(); 6854 } 6855 } 6856 // Inform the actions module about the parameter declarator, so it gets 6857 // added to the current scope. 6858 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator); 6859 // Parse the default argument, if any. We parse the default 6860 // arguments in all dialects; the semantic analysis in 6861 // ActOnParamDefaultArgument will reject the default argument in 6862 // C. 6863 if (Tok.is(tok::equal)) { 6864 SourceLocation EqualLoc = Tok.getLocation(); 6865 6866 // Parse the default argument 6867 if (DeclaratorCtx == DeclaratorContext::Member) { 6868 // If we're inside a class definition, cache the tokens 6869 // corresponding to the default argument. We'll actually parse 6870 // them when we see the end of the class definition. 6871 DefArgToks.reset(new CachedTokens); 6872 6873 SourceLocation ArgStartLoc = NextToken().getLocation(); 6874 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) { 6875 DefArgToks.reset(); 6876 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc); 6877 } else { 6878 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc, 6879 ArgStartLoc); 6880 } 6881 } else { 6882 // Consume the '='. 6883 ConsumeToken(); 6884 6885 // The argument isn't actually potentially evaluated unless it is 6886 // used. 6887 EnterExpressionEvaluationContext Eval( 6888 Actions, 6889 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, 6890 Param); 6891 6892 ExprResult DefArgResult; 6893 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 6894 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 6895 DefArgResult = ParseBraceInitializer(); 6896 } else 6897 DefArgResult = ParseAssignmentExpression(); 6898 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult); 6899 if (DefArgResult.isInvalid()) { 6900 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc); 6901 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch); 6902 } else { 6903 // Inform the actions module about the default argument 6904 Actions.ActOnParamDefaultArgument(Param, EqualLoc, 6905 DefArgResult.get()); 6906 } 6907 } 6908 } 6909 6910 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 6911 ParmDeclarator.getIdentifierLoc(), 6912 Param, std::move(DefArgToks))); 6913 } 6914 6915 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) { 6916 if (!getLangOpts().CPlusPlus) { 6917 // We have ellipsis without a preceding ',', which is ill-formed 6918 // in C. Complain and provide the fix. 6919 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis) 6920 << FixItHint::CreateInsertion(EllipsisLoc, ", "); 6921 } else if (ParmDeclarator.getEllipsisLoc().isValid() || 6922 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) { 6923 // It looks like this was supposed to be a parameter pack. Warn and 6924 // point out where the ellipsis should have gone. 6925 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc(); 6926 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg) 6927 << ParmEllipsis.isValid() << ParmEllipsis; 6928 if (ParmEllipsis.isValid()) { 6929 Diag(ParmEllipsis, 6930 diag::note_misplaced_ellipsis_vararg_existing_ellipsis); 6931 } else { 6932 Diag(ParmDeclarator.getIdentifierLoc(), 6933 diag::note_misplaced_ellipsis_vararg_add_ellipsis) 6934 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(), 6935 "...") 6936 << !ParmDeclarator.hasName(); 6937 } 6938 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma) 6939 << FixItHint::CreateInsertion(EllipsisLoc, ", "); 6940 } 6941 6942 // We can't have any more parameters after an ellipsis. 6943 break; 6944 } 6945 6946 // If the next token is a comma, consume it and keep reading arguments. 6947 } while (TryConsumeToken(tok::comma)); 6948 } 6949 6950 /// [C90] direct-declarator '[' constant-expression[opt] ']' 6951 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 6952 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 6953 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 6954 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 6955 /// [C++11] direct-declarator '[' constant-expression[opt] ']' 6956 /// attribute-specifier-seq[opt] 6957 void Parser::ParseBracketDeclarator(Declarator &D) { 6958 if (CheckProhibitedCXX11Attribute()) 6959 return; 6960 6961 BalancedDelimiterTracker T(*this, tok::l_square); 6962 T.consumeOpen(); 6963 6964 // C array syntax has many features, but by-far the most common is [] and [4]. 6965 // This code does a fast path to handle some of the most obvious cases. 6966 if (Tok.getKind() == tok::r_square) { 6967 T.consumeClose(); 6968 ParsedAttributes attrs(AttrFactory); 6969 MaybeParseCXX11Attributes(attrs); 6970 6971 // Remember that we parsed the empty array type. 6972 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr, 6973 T.getOpenLocation(), 6974 T.getCloseLocation()), 6975 std::move(attrs), T.getCloseLocation()); 6976 return; 6977 } else if (Tok.getKind() == tok::numeric_constant && 6978 GetLookAheadToken(1).is(tok::r_square)) { 6979 // [4] is very common. Parse the numeric constant expression. 6980 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope())); 6981 ConsumeToken(); 6982 6983 T.consumeClose(); 6984 ParsedAttributes attrs(AttrFactory); 6985 MaybeParseCXX11Attributes(attrs); 6986 6987 // Remember that we parsed a array type, and remember its features. 6988 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(), 6989 T.getOpenLocation(), 6990 T.getCloseLocation()), 6991 std::move(attrs), T.getCloseLocation()); 6992 return; 6993 } else if (Tok.getKind() == tok::code_completion) { 6994 Actions.CodeCompleteBracketDeclarator(getCurScope()); 6995 return cutOffParsing(); 6996 } 6997 6998 // If valid, this location is the position where we read the 'static' keyword. 6999 SourceLocation StaticLoc; 7000 TryConsumeToken(tok::kw_static, StaticLoc); 7001 7002 // If there is a type-qualifier-list, read it now. 7003 // Type qualifiers in an array subscript are a C99 feature. 7004 DeclSpec DS(AttrFactory); 7005 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed); 7006 7007 // If we haven't already read 'static', check to see if there is one after the 7008 // type-qualifier-list. 7009 if (!StaticLoc.isValid()) 7010 TryConsumeToken(tok::kw_static, StaticLoc); 7011 7012 // Handle "direct-declarator [ type-qual-list[opt] * ]". 7013 bool isStar = false; 7014 ExprResult NumElements; 7015 7016 // Handle the case where we have '[*]' as the array size. However, a leading 7017 // star could be the start of an expression, for example 'X[*p + 4]'. Verify 7018 // the token after the star is a ']'. Since stars in arrays are 7019 // infrequent, use of lookahead is not costly here. 7020 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) { 7021 ConsumeToken(); // Eat the '*'. 7022 7023 if (StaticLoc.isValid()) { 7024 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static); 7025 StaticLoc = SourceLocation(); // Drop the static. 7026 } 7027 isStar = true; 7028 } else if (Tok.isNot(tok::r_square)) { 7029 // Note, in C89, this production uses the constant-expr production instead 7030 // of assignment-expr. The only difference is that assignment-expr allows 7031 // things like '=' and '*='. Sema rejects these in C89 mode because they 7032 // are not i-c-e's, so we don't need to distinguish between the two here. 7033 7034 // Parse the constant-expression or assignment-expression now (depending 7035 // on dialect). 7036 if (getLangOpts().CPlusPlus) { 7037 NumElements = ParseConstantExpression(); 7038 } else { 7039 EnterExpressionEvaluationContext Unevaluated( 7040 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated); 7041 NumElements = 7042 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()); 7043 } 7044 } else { 7045 if (StaticLoc.isValid()) { 7046 Diag(StaticLoc, diag::err_unspecified_size_with_static); 7047 StaticLoc = SourceLocation(); // Drop the static. 7048 } 7049 } 7050 7051 // If there was an error parsing the assignment-expression, recover. 7052 if (NumElements.isInvalid()) { 7053 D.setInvalidType(true); 7054 // If the expression was invalid, skip it. 7055 SkipUntil(tok::r_square, StopAtSemi); 7056 return; 7057 } 7058 7059 T.consumeClose(); 7060 7061 MaybeParseCXX11Attributes(DS.getAttributes()); 7062 7063 // Remember that we parsed a array type, and remember its features. 7064 D.AddTypeInfo( 7065 DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(), 7066 isStar, NumElements.get(), T.getOpenLocation(), 7067 T.getCloseLocation()), 7068 std::move(DS.getAttributes()), T.getCloseLocation()); 7069 } 7070 7071 /// Diagnose brackets before an identifier. 7072 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) { 7073 assert(Tok.is(tok::l_square) && "Missing opening bracket"); 7074 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier"); 7075 7076 SourceLocation StartBracketLoc = Tok.getLocation(); 7077 Declarator TempDeclarator(D.getDeclSpec(), D.getContext()); 7078 7079 while (Tok.is(tok::l_square)) { 7080 ParseBracketDeclarator(TempDeclarator); 7081 } 7082 7083 // Stuff the location of the start of the brackets into the Declarator. 7084 // The diagnostics from ParseDirectDeclarator will make more sense if 7085 // they use this location instead. 7086 if (Tok.is(tok::semi)) 7087 D.getName().EndLocation = StartBracketLoc; 7088 7089 SourceLocation SuggestParenLoc = Tok.getLocation(); 7090 7091 // Now that the brackets are removed, try parsing the declarator again. 7092 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 7093 7094 // Something went wrong parsing the brackets, in which case, 7095 // ParseBracketDeclarator has emitted an error, and we don't need to emit 7096 // one here. 7097 if (TempDeclarator.getNumTypeObjects() == 0) 7098 return; 7099 7100 // Determine if parens will need to be suggested in the diagnostic. 7101 bool NeedParens = false; 7102 if (D.getNumTypeObjects() != 0) { 7103 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) { 7104 case DeclaratorChunk::Pointer: 7105 case DeclaratorChunk::Reference: 7106 case DeclaratorChunk::BlockPointer: 7107 case DeclaratorChunk::MemberPointer: 7108 case DeclaratorChunk::Pipe: 7109 NeedParens = true; 7110 break; 7111 case DeclaratorChunk::Array: 7112 case DeclaratorChunk::Function: 7113 case DeclaratorChunk::Paren: 7114 break; 7115 } 7116 } 7117 7118 if (NeedParens) { 7119 // Create a DeclaratorChunk for the inserted parens. 7120 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc()); 7121 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), 7122 SourceLocation()); 7123 } 7124 7125 // Adding back the bracket info to the end of the Declarator. 7126 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) { 7127 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i); 7128 D.AddTypeInfo(Chunk, SourceLocation()); 7129 } 7130 7131 // The missing identifier would have been diagnosed in ParseDirectDeclarator. 7132 // If parentheses are required, always suggest them. 7133 if (!D.getIdentifier() && !NeedParens) 7134 return; 7135 7136 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc(); 7137 7138 // Generate the move bracket error message. 7139 SourceRange BracketRange(StartBracketLoc, EndBracketLoc); 7140 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc()); 7141 7142 if (NeedParens) { 7143 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id) 7144 << getLangOpts().CPlusPlus 7145 << FixItHint::CreateInsertion(SuggestParenLoc, "(") 7146 << FixItHint::CreateInsertion(EndLoc, ")") 7147 << FixItHint::CreateInsertionFromRange( 7148 EndLoc, CharSourceRange(BracketRange, true)) 7149 << FixItHint::CreateRemoval(BracketRange); 7150 } else { 7151 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id) 7152 << getLangOpts().CPlusPlus 7153 << FixItHint::CreateInsertionFromRange( 7154 EndLoc, CharSourceRange(BracketRange, true)) 7155 << FixItHint::CreateRemoval(BracketRange); 7156 } 7157 } 7158 7159 /// [GNU] typeof-specifier: 7160 /// typeof ( expressions ) 7161 /// typeof ( type-name ) 7162 /// [GNU/C++] typeof unary-expression 7163 /// 7164 void Parser::ParseTypeofSpecifier(DeclSpec &DS) { 7165 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier"); 7166 Token OpTok = Tok; 7167 SourceLocation StartLoc = ConsumeToken(); 7168 7169 const bool hasParens = Tok.is(tok::l_paren); 7170 7171 EnterExpressionEvaluationContext Unevaluated( 7172 Actions, Sema::ExpressionEvaluationContext::Unevaluated, 7173 Sema::ReuseLambdaContextDecl); 7174 7175 bool isCastExpr; 7176 ParsedType CastTy; 7177 SourceRange CastRange; 7178 ExprResult Operand = Actions.CorrectDelayedTyposInExpr( 7179 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange)); 7180 if (hasParens) 7181 DS.setTypeofParensRange(CastRange); 7182 7183 if (CastRange.getEnd().isInvalid()) 7184 // FIXME: Not accurate, the range gets one token more than it should. 7185 DS.SetRangeEnd(Tok.getLocation()); 7186 else 7187 DS.SetRangeEnd(CastRange.getEnd()); 7188 7189 if (isCastExpr) { 7190 if (!CastTy) { 7191 DS.SetTypeSpecError(); 7192 return; 7193 } 7194 7195 const char *PrevSpec = nullptr; 7196 unsigned DiagID; 7197 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 7198 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, 7199 DiagID, CastTy, 7200 Actions.getASTContext().getPrintingPolicy())) 7201 Diag(StartLoc, DiagID) << PrevSpec; 7202 return; 7203 } 7204 7205 // If we get here, the operand to the typeof was an expression. 7206 if (Operand.isInvalid()) { 7207 DS.SetTypeSpecError(); 7208 return; 7209 } 7210 7211 // We might need to transform the operand if it is potentially evaluated. 7212 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get()); 7213 if (Operand.isInvalid()) { 7214 DS.SetTypeSpecError(); 7215 return; 7216 } 7217 7218 const char *PrevSpec = nullptr; 7219 unsigned DiagID; 7220 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 7221 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 7222 DiagID, Operand.get(), 7223 Actions.getASTContext().getPrintingPolicy())) 7224 Diag(StartLoc, DiagID) << PrevSpec; 7225 } 7226 7227 /// [C11] atomic-specifier: 7228 /// _Atomic ( type-name ) 7229 /// 7230 void Parser::ParseAtomicSpecifier(DeclSpec &DS) { 7231 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) && 7232 "Not an atomic specifier"); 7233 7234 SourceLocation StartLoc = ConsumeToken(); 7235 BalancedDelimiterTracker T(*this, tok::l_paren); 7236 if (T.consumeOpen()) 7237 return; 7238 7239 TypeResult Result = ParseTypeName(); 7240 if (Result.isInvalid()) { 7241 SkipUntil(tok::r_paren, StopAtSemi); 7242 return; 7243 } 7244 7245 // Match the ')' 7246 T.consumeClose(); 7247 7248 if (T.getCloseLocation().isInvalid()) 7249 return; 7250 7251 DS.setTypeofParensRange(T.getRange()); 7252 DS.SetRangeEnd(T.getCloseLocation()); 7253 7254 const char *PrevSpec = nullptr; 7255 unsigned DiagID; 7256 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec, 7257 DiagID, Result.get(), 7258 Actions.getASTContext().getPrintingPolicy())) 7259 Diag(StartLoc, DiagID) << PrevSpec; 7260 } 7261 7262 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called 7263 /// from TryAltiVecVectorToken. 7264 bool Parser::TryAltiVecVectorTokenOutOfLine() { 7265 Token Next = NextToken(); 7266 switch (Next.getKind()) { 7267 default: return false; 7268 case tok::kw_short: 7269 case tok::kw_long: 7270 case tok::kw_signed: 7271 case tok::kw_unsigned: 7272 case tok::kw_void: 7273 case tok::kw_char: 7274 case tok::kw_int: 7275 case tok::kw_float: 7276 case tok::kw_double: 7277 case tok::kw_bool: 7278 case tok::kw___bool: 7279 case tok::kw___pixel: 7280 Tok.setKind(tok::kw___vector); 7281 return true; 7282 case tok::identifier: 7283 if (Next.getIdentifierInfo() == Ident_pixel) { 7284 Tok.setKind(tok::kw___vector); 7285 return true; 7286 } 7287 if (Next.getIdentifierInfo() == Ident_bool) { 7288 Tok.setKind(tok::kw___vector); 7289 return true; 7290 } 7291 return false; 7292 } 7293 } 7294 7295 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, 7296 const char *&PrevSpec, unsigned &DiagID, 7297 bool &isInvalid) { 7298 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); 7299 if (Tok.getIdentifierInfo() == Ident_vector) { 7300 Token Next = NextToken(); 7301 switch (Next.getKind()) { 7302 case tok::kw_short: 7303 case tok::kw_long: 7304 case tok::kw_signed: 7305 case tok::kw_unsigned: 7306 case tok::kw_void: 7307 case tok::kw_char: 7308 case tok::kw_int: 7309 case tok::kw_float: 7310 case tok::kw_double: 7311 case tok::kw_bool: 7312 case tok::kw___bool: 7313 case tok::kw___pixel: 7314 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy); 7315 return true; 7316 case tok::identifier: 7317 if (Next.getIdentifierInfo() == Ident_pixel) { 7318 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy); 7319 return true; 7320 } 7321 if (Next.getIdentifierInfo() == Ident_bool) { 7322 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy); 7323 return true; 7324 } 7325 break; 7326 default: 7327 break; 7328 } 7329 } else if ((Tok.getIdentifierInfo() == Ident_pixel) && 7330 DS.isTypeAltiVecVector()) { 7331 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy); 7332 return true; 7333 } else if ((Tok.getIdentifierInfo() == Ident_bool) && 7334 DS.isTypeAltiVecVector()) { 7335 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy); 7336 return true; 7337 } 7338 return false; 7339 } 7340