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