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