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