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