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