1 //===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===// 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 Expression parsing implementation for C++. 10 // 11 //===----------------------------------------------------------------------===// 12 #include "clang/AST/ASTContext.h" 13 #include "clang/AST/Decl.h" 14 #include "clang/AST/DeclTemplate.h" 15 #include "clang/AST/ExprCXX.h" 16 #include "clang/Basic/DiagnosticParse.h" 17 #include "clang/Basic/PrettyStackTrace.h" 18 #include "clang/Basic/TemplateKinds.h" 19 #include "clang/Basic/TokenKinds.h" 20 #include "clang/Lex/LiteralSupport.h" 21 #include "clang/Parse/Parser.h" 22 #include "clang/Parse/RAIIObjectsForParser.h" 23 #include "clang/Sema/DeclSpec.h" 24 #include "clang/Sema/EnterExpressionEvaluationContext.h" 25 #include "clang/Sema/ParsedTemplate.h" 26 #include "clang/Sema/Scope.h" 27 #include "clang/Sema/SemaCodeCompletion.h" 28 #include "llvm/Support/Compiler.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include <numeric> 31 32 using namespace clang; 33 34 static int SelectDigraphErrorMessage(tok::TokenKind Kind) { 35 switch (Kind) { 36 // template name 37 case tok::unknown: return 0; 38 // casts 39 case tok::kw_addrspace_cast: return 1; 40 case tok::kw_const_cast: return 2; 41 case tok::kw_dynamic_cast: return 3; 42 case tok::kw_reinterpret_cast: return 4; 43 case tok::kw_static_cast: return 5; 44 default: 45 llvm_unreachable("Unknown type for digraph error message."); 46 } 47 } 48 49 // Are the two tokens adjacent in the same source file? 50 bool Parser::areTokensAdjacent(const Token &First, const Token &Second) { 51 SourceManager &SM = PP.getSourceManager(); 52 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation()); 53 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength()); 54 return FirstEnd == SM.getSpellingLoc(Second.getLocation()); 55 } 56 57 // Suggest fixit for "<::" after a cast. 58 static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken, 59 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) { 60 // Pull '<:' and ':' off token stream. 61 if (!AtDigraph) 62 PP.Lex(DigraphToken); 63 PP.Lex(ColonToken); 64 65 SourceRange Range; 66 Range.setBegin(DigraphToken.getLocation()); 67 Range.setEnd(ColonToken.getLocation()); 68 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph) 69 << SelectDigraphErrorMessage(Kind) 70 << FixItHint::CreateReplacement(Range, "< ::"); 71 72 // Update token information to reflect their change in token type. 73 ColonToken.setKind(tok::coloncolon); 74 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1)); 75 ColonToken.setLength(2); 76 DigraphToken.setKind(tok::less); 77 DigraphToken.setLength(1); 78 79 // Push new tokens back to token stream. 80 PP.EnterToken(ColonToken, /*IsReinject*/ true); 81 if (!AtDigraph) 82 PP.EnterToken(DigraphToken, /*IsReinject*/ true); 83 } 84 85 // Check for '<::' which should be '< ::' instead of '[:' when following 86 // a template name. 87 void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType, 88 bool EnteringContext, 89 IdentifierInfo &II, CXXScopeSpec &SS) { 90 if (!Next.is(tok::l_square) || Next.getLength() != 2) 91 return; 92 93 Token SecondToken = GetLookAheadToken(2); 94 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken)) 95 return; 96 97 TemplateTy Template; 98 UnqualifiedId TemplateName; 99 TemplateName.setIdentifier(&II, Tok.getLocation()); 100 bool MemberOfUnknownSpecialization; 101 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false, 102 TemplateName, ObjectType, EnteringContext, 103 Template, MemberOfUnknownSpecialization)) 104 return; 105 106 FixDigraph(*this, PP, Next, SecondToken, tok::unknown, 107 /*AtDigraph*/false); 108 } 109 110 /// Parse global scope or nested-name-specifier if present. 111 /// 112 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which 113 /// may be preceded by '::'). Note that this routine will not parse ::new or 114 /// ::delete; it will just leave them in the token stream. 115 /// 116 /// '::'[opt] nested-name-specifier 117 /// '::' 118 /// 119 /// nested-name-specifier: 120 /// type-name '::' 121 /// namespace-name '::' 122 /// nested-name-specifier identifier '::' 123 /// nested-name-specifier 'template'[opt] simple-template-id '::' 124 /// 125 /// 126 /// \param SS the scope specifier that will be set to the parsed 127 /// nested-name-specifier (or empty) 128 /// 129 /// \param ObjectType if this nested-name-specifier is being parsed following 130 /// the "." or "->" of a member access expression, this parameter provides the 131 /// type of the object whose members are being accessed. 132 /// 133 /// \param ObjectHadErrors if this unqualified-id occurs within a member access 134 /// expression, indicates whether the original subexpressions had any errors. 135 /// When true, diagnostics for missing 'template' keyword will be supressed. 136 /// 137 /// \param EnteringContext whether we will be entering into the context of 138 /// the nested-name-specifier after parsing it. 139 /// 140 /// \param MayBePseudoDestructor When non-NULL, points to a flag that 141 /// indicates whether this nested-name-specifier may be part of a 142 /// pseudo-destructor name. In this case, the flag will be set false 143 /// if we don't actually end up parsing a destructor name. Moreover, 144 /// if we do end up determining that we are parsing a destructor name, 145 /// the last component of the nested-name-specifier is not parsed as 146 /// part of the scope specifier. 147 /// 148 /// \param IsTypename If \c true, this nested-name-specifier is known to be 149 /// part of a type name. This is used to improve error recovery. 150 /// 151 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be 152 /// filled in with the leading identifier in the last component of the 153 /// nested-name-specifier, if any. 154 /// 155 /// \param OnlyNamespace If true, only considers namespaces in lookup. 156 /// 157 /// 158 /// \returns true if there was an error parsing a scope specifier 159 bool Parser::ParseOptionalCXXScopeSpecifier( 160 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, 161 bool EnteringContext, bool *MayBePseudoDestructor, bool IsTypename, 162 const IdentifierInfo **LastII, bool OnlyNamespace, bool InUsingDeclaration, 163 bool Disambiguation) { 164 assert(getLangOpts().CPlusPlus && 165 "Call sites of this function should be guarded by checking for C++"); 166 167 if (Tok.is(tok::annot_cxxscope)) { 168 assert(!LastII && "want last identifier but have already annotated scope"); 169 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope"); 170 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), 171 Tok.getAnnotationRange(), 172 SS); 173 ConsumeAnnotationToken(); 174 return false; 175 } 176 177 // Has to happen before any "return false"s in this function. 178 bool CheckForDestructor = false; 179 if (MayBePseudoDestructor && *MayBePseudoDestructor) { 180 CheckForDestructor = true; 181 *MayBePseudoDestructor = false; 182 } 183 184 if (LastII) 185 *LastII = nullptr; 186 187 bool HasScopeSpecifier = false; 188 189 if (Tok.is(tok::coloncolon)) { 190 // ::new and ::delete aren't nested-name-specifiers. 191 tok::TokenKind NextKind = NextToken().getKind(); 192 if (NextKind == tok::kw_new || NextKind == tok::kw_delete) 193 return false; 194 195 if (NextKind == tok::l_brace) { 196 // It is invalid to have :: {, consume the scope qualifier and pretend 197 // like we never saw it. 198 Diag(ConsumeToken(), diag::err_expected) << tok::identifier; 199 } else { 200 // '::' - Global scope qualifier. 201 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS)) 202 return true; 203 204 HasScopeSpecifier = true; 205 } 206 } 207 208 if (Tok.is(tok::kw___super)) { 209 SourceLocation SuperLoc = ConsumeToken(); 210 if (!Tok.is(tok::coloncolon)) { 211 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super); 212 return true; 213 } 214 215 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS); 216 } 217 218 if (!HasScopeSpecifier && 219 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) { 220 DeclSpec DS(AttrFactory); 221 SourceLocation DeclLoc = Tok.getLocation(); 222 SourceLocation EndLoc = ParseDecltypeSpecifier(DS); 223 224 SourceLocation CCLoc; 225 // Work around a standard defect: 'decltype(auto)::' is not a 226 // nested-name-specifier. 227 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto || 228 !TryConsumeToken(tok::coloncolon, CCLoc)) { 229 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc); 230 return false; 231 } 232 233 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc)) 234 SS.SetInvalid(SourceRange(DeclLoc, CCLoc)); 235 236 HasScopeSpecifier = true; 237 } 238 239 else if (!HasScopeSpecifier && Tok.is(tok::identifier) && 240 GetLookAheadToken(1).is(tok::ellipsis) && 241 GetLookAheadToken(2).is(tok::l_square) && 242 !GetLookAheadToken(3).is(tok::r_square)) { 243 SourceLocation Start = Tok.getLocation(); 244 DeclSpec DS(AttrFactory); 245 SourceLocation CCLoc; 246 SourceLocation EndLoc = ParsePackIndexingType(DS); 247 if (DS.getTypeSpecType() == DeclSpec::TST_error) 248 return false; 249 250 QualType Type = Actions.ActOnPackIndexingType( 251 DS.getRepAsType().get(), DS.getPackIndexingExpr(), DS.getBeginLoc(), 252 DS.getEllipsisLoc()); 253 254 if (Type.isNull()) 255 return false; 256 257 // C++ [cpp23.dcl.dcl-2]: 258 // Previously, T...[n] would declare a pack of function parameters. 259 // T...[n] is now a pack-index-specifier. [...] Valid C++ 2023 code that 260 // declares a pack of parameters without specifying a declarator-id 261 // becomes ill-formed. 262 // 263 // However, we still treat it as a pack indexing type because the use case 264 // is fairly rare, to ensure semantic consistency given that we have 265 // backported this feature to pre-C++26 modes. 266 if (!Tok.is(tok::coloncolon) && !getLangOpts().CPlusPlus26 && 267 getCurScope()->isFunctionDeclarationScope()) 268 Diag(Start, diag::warn_pre_cxx26_ambiguous_pack_indexing_type) << Type; 269 270 if (!TryConsumeToken(tok::coloncolon, CCLoc)) { 271 AnnotateExistingIndexedTypeNamePack(ParsedType::make(Type), Start, 272 EndLoc); 273 return false; 274 } 275 if (Actions.ActOnCXXNestedNameSpecifierIndexedPack(SS, DS, CCLoc, 276 std::move(Type))) 277 SS.SetInvalid(SourceRange(Start, CCLoc)); 278 HasScopeSpecifier = true; 279 } 280 281 // Preferred type might change when parsing qualifiers, we need the original. 282 auto SavedType = PreferredType; 283 while (true) { 284 if (HasScopeSpecifier) { 285 if (Tok.is(tok::code_completion)) { 286 cutOffParsing(); 287 // Code completion for a nested-name-specifier, where the code 288 // completion token follows the '::'. 289 Actions.CodeCompletion().CodeCompleteQualifiedId( 290 getCurScope(), SS, EnteringContext, InUsingDeclaration, 291 ObjectType.get(), SavedType.get(SS.getBeginLoc())); 292 // Include code completion token into the range of the scope otherwise 293 // when we try to annotate the scope tokens the dangling code completion 294 // token will cause assertion in 295 // Preprocessor::AnnotatePreviousCachedTokens. 296 SS.setEndLoc(Tok.getLocation()); 297 return true; 298 } 299 300 // C++ [basic.lookup.classref]p5: 301 // If the qualified-id has the form 302 // 303 // ::class-name-or-namespace-name::... 304 // 305 // the class-name-or-namespace-name is looked up in global scope as a 306 // class-name or namespace-name. 307 // 308 // To implement this, we clear out the object type as soon as we've 309 // seen a leading '::' or part of a nested-name-specifier. 310 ObjectType = nullptr; 311 } 312 313 // nested-name-specifier: 314 // nested-name-specifier 'template'[opt] simple-template-id '::' 315 316 // Parse the optional 'template' keyword, then make sure we have 317 // 'identifier <' after it. 318 if (Tok.is(tok::kw_template)) { 319 // If we don't have a scope specifier or an object type, this isn't a 320 // nested-name-specifier, since they aren't allowed to start with 321 // 'template'. 322 if (!HasScopeSpecifier && !ObjectType) 323 break; 324 325 TentativeParsingAction TPA(*this); 326 SourceLocation TemplateKWLoc = ConsumeToken(); 327 328 UnqualifiedId TemplateName; 329 if (Tok.is(tok::identifier)) { 330 // Consume the identifier. 331 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 332 ConsumeToken(); 333 } else if (Tok.is(tok::kw_operator)) { 334 // We don't need to actually parse the unqualified-id in this case, 335 // because a simple-template-id cannot start with 'operator', but 336 // go ahead and parse it anyway for consistency with the case where 337 // we already annotated the template-id. 338 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, 339 TemplateName)) { 340 TPA.Commit(); 341 break; 342 } 343 344 if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId && 345 TemplateName.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId) { 346 Diag(TemplateName.getSourceRange().getBegin(), 347 diag::err_id_after_template_in_nested_name_spec) 348 << TemplateName.getSourceRange(); 349 TPA.Commit(); 350 break; 351 } 352 } else { 353 TPA.Revert(); 354 break; 355 } 356 357 // If the next token is not '<', we have a qualified-id that refers 358 // to a template name, such as T::template apply, but is not a 359 // template-id. 360 if (Tok.isNot(tok::less)) { 361 TPA.Revert(); 362 break; 363 } 364 365 // Commit to parsing the template-id. 366 TPA.Commit(); 367 TemplateTy Template; 368 TemplateNameKind TNK = Actions.ActOnTemplateName( 369 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType, 370 EnteringContext, Template, /*AllowInjectedClassName*/ true); 371 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc, 372 TemplateName, false)) 373 return true; 374 375 continue; 376 } 377 378 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) { 379 // We have 380 // 381 // template-id '::' 382 // 383 // So we need to check whether the template-id is a simple-template-id of 384 // the right kind (it should name a type or be dependent), and then 385 // convert it into a type within the nested-name-specifier. 386 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 387 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) { 388 *MayBePseudoDestructor = true; 389 return false; 390 } 391 392 if (LastII) 393 *LastII = TemplateId->Name; 394 395 // Consume the template-id token. 396 ConsumeAnnotationToken(); 397 398 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!"); 399 SourceLocation CCLoc = ConsumeToken(); 400 401 HasScopeSpecifier = true; 402 403 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 404 TemplateId->NumArgs); 405 406 if (TemplateId->isInvalid() || 407 Actions.ActOnCXXNestedNameSpecifier(getCurScope(), 408 SS, 409 TemplateId->TemplateKWLoc, 410 TemplateId->Template, 411 TemplateId->TemplateNameLoc, 412 TemplateId->LAngleLoc, 413 TemplateArgsPtr, 414 TemplateId->RAngleLoc, 415 CCLoc, 416 EnteringContext)) { 417 SourceLocation StartLoc 418 = SS.getBeginLoc().isValid()? SS.getBeginLoc() 419 : TemplateId->TemplateNameLoc; 420 SS.SetInvalid(SourceRange(StartLoc, CCLoc)); 421 } 422 423 continue; 424 } 425 426 switch (Tok.getKind()) { 427 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait: 428 #include "clang/Basic/TransformTypeTraits.def" 429 if (!NextToken().is(tok::l_paren)) { 430 Tok.setKind(tok::identifier); 431 Diag(Tok, diag::ext_keyword_as_ident) 432 << Tok.getIdentifierInfo()->getName() << 0; 433 continue; 434 } 435 [[fallthrough]]; 436 default: 437 break; 438 } 439 440 // The rest of the nested-name-specifier possibilities start with 441 // tok::identifier. 442 if (Tok.isNot(tok::identifier)) 443 break; 444 445 IdentifierInfo &II = *Tok.getIdentifierInfo(); 446 447 // nested-name-specifier: 448 // type-name '::' 449 // namespace-name '::' 450 // nested-name-specifier identifier '::' 451 Token Next = NextToken(); 452 Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(), 453 ObjectType); 454 455 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover 456 // and emit a fixit hint for it. 457 if (Next.is(tok::colon) && !ColonIsSacred) { 458 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo, 459 EnteringContext) && 460 // If the token after the colon isn't an identifier, it's still an 461 // error, but they probably meant something else strange so don't 462 // recover like this. 463 PP.LookAhead(1).is(tok::identifier)) { 464 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec) 465 << FixItHint::CreateReplacement(Next.getLocation(), "::"); 466 // Recover as if the user wrote '::'. 467 Next.setKind(tok::coloncolon); 468 } 469 } 470 471 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) { 472 // It is invalid to have :: {, consume the scope qualifier and pretend 473 // like we never saw it. 474 Token Identifier = Tok; // Stash away the identifier. 475 ConsumeToken(); // Eat the identifier, current token is now '::'. 476 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected) 477 << tok::identifier; 478 UnconsumeToken(Identifier); // Stick the identifier back. 479 Next = NextToken(); // Point Next at the '{' token. 480 } 481 482 if (Next.is(tok::coloncolon)) { 483 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) { 484 *MayBePseudoDestructor = true; 485 return false; 486 } 487 488 if (ColonIsSacred) { 489 const Token &Next2 = GetLookAheadToken(2); 490 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) || 491 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) { 492 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec) 493 << Next2.getName() 494 << FixItHint::CreateReplacement(Next.getLocation(), ":"); 495 Token ColonColon; 496 PP.Lex(ColonColon); 497 ColonColon.setKind(tok::colon); 498 PP.EnterToken(ColonColon, /*IsReinject*/ true); 499 break; 500 } 501 } 502 503 if (LastII) 504 *LastII = &II; 505 506 // We have an identifier followed by a '::'. Lookup this name 507 // as the name in a nested-name-specifier. 508 Token Identifier = Tok; 509 SourceLocation IdLoc = ConsumeToken(); 510 assert(Tok.isOneOf(tok::coloncolon, tok::colon) && 511 "NextToken() not working properly!"); 512 Token ColonColon = Tok; 513 SourceLocation CCLoc = ConsumeToken(); 514 515 bool IsCorrectedToColon = false; 516 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr; 517 if (Actions.ActOnCXXNestedNameSpecifier( 518 getCurScope(), IdInfo, EnteringContext, SS, CorrectionFlagPtr, 519 OnlyNamespace)) { 520 // Identifier is not recognized as a nested name, but we can have 521 // mistyped '::' instead of ':'. 522 if (CorrectionFlagPtr && IsCorrectedToColon) { 523 ColonColon.setKind(tok::colon); 524 PP.EnterToken(Tok, /*IsReinject*/ true); 525 PP.EnterToken(ColonColon, /*IsReinject*/ true); 526 Tok = Identifier; 527 break; 528 } 529 SS.SetInvalid(SourceRange(IdLoc, CCLoc)); 530 } 531 HasScopeSpecifier = true; 532 continue; 533 } 534 535 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS); 536 537 // nested-name-specifier: 538 // type-name '<' 539 if (Next.is(tok::less)) { 540 541 TemplateTy Template; 542 UnqualifiedId TemplateName; 543 TemplateName.setIdentifier(&II, Tok.getLocation()); 544 bool MemberOfUnknownSpecialization; 545 if (TemplateNameKind TNK = Actions.isTemplateName( 546 getCurScope(), SS, 547 /*hasTemplateKeyword=*/false, TemplateName, ObjectType, 548 EnteringContext, Template, MemberOfUnknownSpecialization, 549 Disambiguation)) { 550 // If lookup didn't find anything, we treat the name as a template-name 551 // anyway. C++20 requires this, and in prior language modes it improves 552 // error recovery. But before we commit to this, check that we actually 553 // have something that looks like a template-argument-list next. 554 if (!IsTypename && TNK == TNK_Undeclared_template && 555 isTemplateArgumentList(1) == TPResult::False) 556 break; 557 558 // We have found a template name, so annotate this token 559 // with a template-id annotation. We do not permit the 560 // template-id to be translated into a type annotation, 561 // because some clients (e.g., the parsing of class template 562 // specializations) still want to see the original template-id 563 // token, and it might not be a type at all (e.g. a concept name in a 564 // type-constraint). 565 ConsumeToken(); 566 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), 567 TemplateName, false)) 568 return true; 569 continue; 570 } 571 572 if (MemberOfUnknownSpecialization && !Disambiguation && 573 (ObjectType || SS.isSet()) && 574 (IsTypename || isTemplateArgumentList(1) == TPResult::True)) { 575 // If we had errors before, ObjectType can be dependent even without any 576 // templates. Do not report missing template keyword in that case. 577 if (!ObjectHadErrors) { 578 // We have something like t::getAs<T>, where getAs is a 579 // member of an unknown specialization. However, this will only 580 // parse correctly as a template, so suggest the keyword 'template' 581 // before 'getAs' and treat this as a dependent template name. 582 unsigned DiagID = diag::err_missing_dependent_template_keyword; 583 if (getLangOpts().MicrosoftExt) 584 DiagID = diag::warn_missing_dependent_template_keyword; 585 586 Diag(Tok.getLocation(), DiagID) 587 << II.getName() 588 << FixItHint::CreateInsertion(Tok.getLocation(), "template "); 589 } 590 591 SourceLocation TemplateNameLoc = ConsumeToken(); 592 593 TemplateNameKind TNK = Actions.ActOnTemplateName( 594 getCurScope(), SS, TemplateNameLoc, TemplateName, ObjectType, 595 EnteringContext, Template, /*AllowInjectedClassName*/ true); 596 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), 597 TemplateName, false)) 598 return true; 599 600 continue; 601 } 602 } 603 604 // We don't have any tokens that form the beginning of a 605 // nested-name-specifier, so we're done. 606 break; 607 } 608 609 // Even if we didn't see any pieces of a nested-name-specifier, we 610 // still check whether there is a tilde in this position, which 611 // indicates a potential pseudo-destructor. 612 if (CheckForDestructor && !HasScopeSpecifier && Tok.is(tok::tilde)) 613 *MayBePseudoDestructor = true; 614 615 return false; 616 } 617 618 ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, 619 bool isAddressOfOperand, 620 Token &Replacement) { 621 ExprResult E; 622 623 // We may have already annotated this id-expression. 624 switch (Tok.getKind()) { 625 case tok::annot_non_type: { 626 NamedDecl *ND = getNonTypeAnnotation(Tok); 627 SourceLocation Loc = ConsumeAnnotationToken(); 628 E = Actions.ActOnNameClassifiedAsNonType(getCurScope(), SS, ND, Loc, Tok); 629 break; 630 } 631 632 case tok::annot_non_type_dependent: { 633 IdentifierInfo *II = getIdentifierAnnotation(Tok); 634 SourceLocation Loc = ConsumeAnnotationToken(); 635 636 // This is only the direct operand of an & operator if it is not 637 // followed by a postfix-expression suffix. 638 if (isAddressOfOperand && isPostfixExpressionSuffixStart()) 639 isAddressOfOperand = false; 640 641 E = Actions.ActOnNameClassifiedAsDependentNonType(SS, II, Loc, 642 isAddressOfOperand); 643 break; 644 } 645 646 case tok::annot_non_type_undeclared: { 647 assert(SS.isEmpty() && 648 "undeclared non-type annotation should be unqualified"); 649 IdentifierInfo *II = getIdentifierAnnotation(Tok); 650 SourceLocation Loc = ConsumeAnnotationToken(); 651 E = Actions.ActOnNameClassifiedAsUndeclaredNonType(II, Loc); 652 break; 653 } 654 655 default: 656 SourceLocation TemplateKWLoc; 657 UnqualifiedId Name; 658 if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr, 659 /*ObjectHadErrors=*/false, 660 /*EnteringContext=*/false, 661 /*AllowDestructorName=*/false, 662 /*AllowConstructorName=*/false, 663 /*AllowDeductionGuide=*/false, &TemplateKWLoc, Name)) 664 return ExprError(); 665 666 // This is only the direct operand of an & operator if it is not 667 // followed by a postfix-expression suffix. 668 if (isAddressOfOperand && isPostfixExpressionSuffixStart()) 669 isAddressOfOperand = false; 670 671 E = Actions.ActOnIdExpression( 672 getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren), 673 isAddressOfOperand, /*CCC=*/nullptr, /*IsInlineAsmIdentifier=*/false, 674 &Replacement); 675 break; 676 } 677 678 // Might be a pack index expression! 679 E = tryParseCXXPackIndexingExpression(E); 680 681 if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less)) 682 checkPotentialAngleBracket(E); 683 return E; 684 } 685 686 ExprResult Parser::ParseCXXPackIndexingExpression(ExprResult PackIdExpression) { 687 assert(Tok.is(tok::ellipsis) && NextToken().is(tok::l_square) && 688 "expected ...["); 689 SourceLocation EllipsisLoc = ConsumeToken(); 690 BalancedDelimiterTracker T(*this, tok::l_square); 691 T.consumeOpen(); 692 ExprResult IndexExpr = ParseConstantExpression(); 693 if (T.consumeClose() || IndexExpr.isInvalid()) 694 return ExprError(); 695 return Actions.ActOnPackIndexingExpr(getCurScope(), PackIdExpression.get(), 696 EllipsisLoc, T.getOpenLocation(), 697 IndexExpr.get(), T.getCloseLocation()); 698 } 699 700 ExprResult 701 Parser::tryParseCXXPackIndexingExpression(ExprResult PackIdExpression) { 702 ExprResult E = PackIdExpression; 703 if (!PackIdExpression.isInvalid() && !PackIdExpression.isUnset() && 704 Tok.is(tok::ellipsis) && NextToken().is(tok::l_square)) { 705 E = ParseCXXPackIndexingExpression(E); 706 } 707 return E; 708 } 709 710 /// ParseCXXIdExpression - Handle id-expression. 711 /// 712 /// id-expression: 713 /// unqualified-id 714 /// qualified-id 715 /// 716 /// qualified-id: 717 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id 718 /// '::' identifier 719 /// '::' operator-function-id 720 /// '::' template-id 721 /// 722 /// NOTE: The standard specifies that, for qualified-id, the parser does not 723 /// expect: 724 /// 725 /// '::' conversion-function-id 726 /// '::' '~' class-name 727 /// 728 /// This may cause a slight inconsistency on diagnostics: 729 /// 730 /// class C {}; 731 /// namespace A {} 732 /// void f() { 733 /// :: A :: ~ C(); // Some Sema error about using destructor with a 734 /// // namespace. 735 /// :: ~ C(); // Some Parser error like 'unexpected ~'. 736 /// } 737 /// 738 /// We simplify the parser a bit and make it work like: 739 /// 740 /// qualified-id: 741 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id 742 /// '::' unqualified-id 743 /// 744 /// That way Sema can handle and report similar errors for namespaces and the 745 /// global scope. 746 /// 747 /// The isAddressOfOperand parameter indicates that this id-expression is a 748 /// direct operand of the address-of operator. This is, besides member contexts, 749 /// the only place where a qualified-id naming a non-static class member may 750 /// appear. 751 /// 752 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) { 753 // qualified-id: 754 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id 755 // '::' unqualified-id 756 // 757 CXXScopeSpec SS; 758 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 759 /*ObjectHasErrors=*/false, 760 /*EnteringContext=*/false); 761 762 Token Replacement; 763 ExprResult Result = 764 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement); 765 if (Result.isUnset()) { 766 // If the ExprResult is valid but null, then typo correction suggested a 767 // keyword replacement that needs to be reparsed. 768 UnconsumeToken(Replacement); 769 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement); 770 } 771 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement " 772 "for a previous keyword suggestion"); 773 return Result; 774 } 775 776 /// ParseLambdaExpression - Parse a C++11 lambda expression. 777 /// 778 /// lambda-expression: 779 /// lambda-introducer lambda-declarator compound-statement 780 /// lambda-introducer '<' template-parameter-list '>' 781 /// requires-clause[opt] lambda-declarator compound-statement 782 /// 783 /// lambda-introducer: 784 /// '[' lambda-capture[opt] ']' 785 /// 786 /// lambda-capture: 787 /// capture-default 788 /// capture-list 789 /// capture-default ',' capture-list 790 /// 791 /// capture-default: 792 /// '&' 793 /// '=' 794 /// 795 /// capture-list: 796 /// capture 797 /// capture-list ',' capture 798 /// 799 /// capture: 800 /// simple-capture 801 /// init-capture [C++1y] 802 /// 803 /// simple-capture: 804 /// identifier 805 /// '&' identifier 806 /// 'this' 807 /// 808 /// init-capture: [C++1y] 809 /// identifier initializer 810 /// '&' identifier initializer 811 /// 812 /// lambda-declarator: 813 /// lambda-specifiers [C++23] 814 /// '(' parameter-declaration-clause ')' lambda-specifiers 815 /// requires-clause[opt] 816 /// 817 /// lambda-specifiers: 818 /// decl-specifier-seq[opt] noexcept-specifier[opt] 819 /// attribute-specifier-seq[opt] trailing-return-type[opt] 820 /// 821 ExprResult Parser::ParseLambdaExpression() { 822 // Parse lambda-introducer. 823 LambdaIntroducer Intro; 824 if (ParseLambdaIntroducer(Intro)) { 825 SkipUntil(tok::r_square, StopAtSemi); 826 SkipUntil(tok::l_brace, StopAtSemi); 827 SkipUntil(tok::r_brace, StopAtSemi); 828 return ExprError(); 829 } 830 831 return ParseLambdaExpressionAfterIntroducer(Intro); 832 } 833 834 /// Use lookahead and potentially tentative parsing to determine if we are 835 /// looking at a C++11 lambda expression, and parse it if we are. 836 /// 837 /// If we are not looking at a lambda expression, returns ExprError(). 838 ExprResult Parser::TryParseLambdaExpression() { 839 assert(getLangOpts().CPlusPlus && Tok.is(tok::l_square) && 840 "Not at the start of a possible lambda expression."); 841 842 const Token Next = NextToken(); 843 if (Next.is(tok::eof)) // Nothing else to lookup here... 844 return ExprEmpty(); 845 846 const Token After = GetLookAheadToken(2); 847 // If lookahead indicates this is a lambda... 848 if (Next.is(tok::r_square) || // [] 849 Next.is(tok::equal) || // [= 850 (Next.is(tok::amp) && // [&] or [&, 851 After.isOneOf(tok::r_square, tok::comma)) || 852 (Next.is(tok::identifier) && // [identifier] 853 After.is(tok::r_square)) || 854 Next.is(tok::ellipsis)) { // [... 855 return ParseLambdaExpression(); 856 } 857 858 // If lookahead indicates an ObjC message send... 859 // [identifier identifier 860 if (Next.is(tok::identifier) && After.is(tok::identifier)) 861 return ExprEmpty(); 862 863 // Here, we're stuck: lambda introducers and Objective-C message sends are 864 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a 865 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of 866 // writing two routines to parse a lambda introducer, just try to parse 867 // a lambda introducer first, and fall back if that fails. 868 LambdaIntroducer Intro; 869 { 870 TentativeParsingAction TPA(*this); 871 LambdaIntroducerTentativeParse Tentative; 872 if (ParseLambdaIntroducer(Intro, &Tentative)) { 873 TPA.Commit(); 874 return ExprError(); 875 } 876 877 switch (Tentative) { 878 case LambdaIntroducerTentativeParse::Success: 879 TPA.Commit(); 880 break; 881 882 case LambdaIntroducerTentativeParse::Incomplete: 883 // Didn't fully parse the lambda-introducer, try again with a 884 // non-tentative parse. 885 TPA.Revert(); 886 Intro = LambdaIntroducer(); 887 if (ParseLambdaIntroducer(Intro)) 888 return ExprError(); 889 break; 890 891 case LambdaIntroducerTentativeParse::MessageSend: 892 case LambdaIntroducerTentativeParse::Invalid: 893 // Not a lambda-introducer, might be a message send. 894 TPA.Revert(); 895 return ExprEmpty(); 896 } 897 } 898 899 return ParseLambdaExpressionAfterIntroducer(Intro); 900 } 901 902 /// Parse a lambda introducer. 903 /// \param Intro A LambdaIntroducer filled in with information about the 904 /// contents of the lambda-introducer. 905 /// \param Tentative If non-null, we are disambiguating between a 906 /// lambda-introducer and some other construct. In this mode, we do not 907 /// produce any diagnostics or take any other irreversible action unless 908 /// we're sure that this is a lambda-expression. 909 /// \return \c true if parsing (or disambiguation) failed with a diagnostic and 910 /// the caller should bail out / recover. 911 bool Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro, 912 LambdaIntroducerTentativeParse *Tentative) { 913 if (Tentative) 914 *Tentative = LambdaIntroducerTentativeParse::Success; 915 916 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['."); 917 BalancedDelimiterTracker T(*this, tok::l_square); 918 T.consumeOpen(); 919 920 Intro.Range.setBegin(T.getOpenLocation()); 921 922 bool First = true; 923 924 // Produce a diagnostic if we're not tentatively parsing; otherwise track 925 // that our parse has failed. 926 auto Invalid = [&](llvm::function_ref<void()> Action) { 927 if (Tentative) { 928 *Tentative = LambdaIntroducerTentativeParse::Invalid; 929 return false; 930 } 931 Action(); 932 return true; 933 }; 934 935 // Perform some irreversible action if this is a non-tentative parse; 936 // otherwise note that our actions were incomplete. 937 auto NonTentativeAction = [&](llvm::function_ref<void()> Action) { 938 if (Tentative) 939 *Tentative = LambdaIntroducerTentativeParse::Incomplete; 940 else 941 Action(); 942 }; 943 944 // Parse capture-default. 945 if (Tok.is(tok::amp) && 946 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) { 947 Intro.Default = LCD_ByRef; 948 Intro.DefaultLoc = ConsumeToken(); 949 First = false; 950 if (!Tok.getIdentifierInfo()) { 951 // This can only be a lambda; no need for tentative parsing any more. 952 // '[[and]]' can still be an attribute, though. 953 Tentative = nullptr; 954 } 955 } else if (Tok.is(tok::equal)) { 956 Intro.Default = LCD_ByCopy; 957 Intro.DefaultLoc = ConsumeToken(); 958 First = false; 959 Tentative = nullptr; 960 } 961 962 while (Tok.isNot(tok::r_square)) { 963 if (!First) { 964 if (Tok.isNot(tok::comma)) { 965 // Provide a completion for a lambda introducer here. Except 966 // in Objective-C, where this is Almost Surely meant to be a message 967 // send. In that case, fail here and let the ObjC message 968 // expression parser perform the completion. 969 if (Tok.is(tok::code_completion) && 970 !(getLangOpts().ObjC && Tentative)) { 971 cutOffParsing(); 972 Actions.CodeCompletion().CodeCompleteLambdaIntroducer( 973 getCurScope(), Intro, 974 /*AfterAmpersand=*/false); 975 break; 976 } 977 978 return Invalid([&] { 979 Diag(Tok.getLocation(), diag::err_expected_comma_or_rsquare); 980 }); 981 } 982 ConsumeToken(); 983 } 984 985 if (Tok.is(tok::code_completion)) { 986 cutOffParsing(); 987 // If we're in Objective-C++ and we have a bare '[', then this is more 988 // likely to be a message receiver. 989 if (getLangOpts().ObjC && Tentative && First) 990 Actions.CodeCompletion().CodeCompleteObjCMessageReceiver(getCurScope()); 991 else 992 Actions.CodeCompletion().CodeCompleteLambdaIntroducer( 993 getCurScope(), Intro, 994 /*AfterAmpersand=*/false); 995 break; 996 } 997 998 First = false; 999 1000 // Parse capture. 1001 LambdaCaptureKind Kind = LCK_ByCopy; 1002 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit; 1003 SourceLocation Loc; 1004 IdentifierInfo *Id = nullptr; 1005 SourceLocation EllipsisLocs[4]; 1006 ExprResult Init; 1007 SourceLocation LocStart = Tok.getLocation(); 1008 1009 if (Tok.is(tok::star)) { 1010 Loc = ConsumeToken(); 1011 if (Tok.is(tok::kw_this)) { 1012 ConsumeToken(); 1013 Kind = LCK_StarThis; 1014 } else { 1015 return Invalid([&] { 1016 Diag(Tok.getLocation(), diag::err_expected_star_this_capture); 1017 }); 1018 } 1019 } else if (Tok.is(tok::kw_this)) { 1020 Kind = LCK_This; 1021 Loc = ConsumeToken(); 1022 } else if (Tok.isOneOf(tok::amp, tok::equal) && 1023 NextToken().isOneOf(tok::comma, tok::r_square) && 1024 Intro.Default == LCD_None) { 1025 // We have a lone "&" or "=" which is either a misplaced capture-default 1026 // or the start of a capture (in the "&" case) with the rest of the 1027 // capture missing. Both are an error but a misplaced capture-default 1028 // is more likely if we don't already have a capture default. 1029 return Invalid( 1030 [&] { Diag(Tok.getLocation(), diag::err_capture_default_first); }); 1031 } else { 1032 TryConsumeToken(tok::ellipsis, EllipsisLocs[0]); 1033 1034 if (Tok.is(tok::amp)) { 1035 Kind = LCK_ByRef; 1036 ConsumeToken(); 1037 1038 if (Tok.is(tok::code_completion)) { 1039 cutOffParsing(); 1040 Actions.CodeCompletion().CodeCompleteLambdaIntroducer( 1041 getCurScope(), Intro, 1042 /*AfterAmpersand=*/true); 1043 break; 1044 } 1045 } 1046 1047 TryConsumeToken(tok::ellipsis, EllipsisLocs[1]); 1048 1049 if (Tok.is(tok::identifier)) { 1050 Id = Tok.getIdentifierInfo(); 1051 Loc = ConsumeToken(); 1052 } else if (Tok.is(tok::kw_this)) { 1053 return Invalid([&] { 1054 // FIXME: Suggest a fixit here. 1055 Diag(Tok.getLocation(), diag::err_this_captured_by_reference); 1056 }); 1057 } else { 1058 return Invalid([&] { 1059 Diag(Tok.getLocation(), diag::err_expected_capture); 1060 }); 1061 } 1062 1063 TryConsumeToken(tok::ellipsis, EllipsisLocs[2]); 1064 1065 if (Tok.is(tok::l_paren)) { 1066 BalancedDelimiterTracker Parens(*this, tok::l_paren); 1067 Parens.consumeOpen(); 1068 1069 InitKind = LambdaCaptureInitKind::DirectInit; 1070 1071 ExprVector Exprs; 1072 if (Tentative) { 1073 Parens.skipToEnd(); 1074 *Tentative = LambdaIntroducerTentativeParse::Incomplete; 1075 } else if (ParseExpressionList(Exprs)) { 1076 Parens.skipToEnd(); 1077 Init = ExprError(); 1078 } else { 1079 Parens.consumeClose(); 1080 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(), 1081 Parens.getCloseLocation(), 1082 Exprs); 1083 } 1084 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) { 1085 // Each lambda init-capture forms its own full expression, which clears 1086 // Actions.MaybeODRUseExprs. So create an expression evaluation context 1087 // to save the necessary state, and restore it later. 1088 EnterExpressionEvaluationContext EC( 1089 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 1090 1091 if (TryConsumeToken(tok::equal)) 1092 InitKind = LambdaCaptureInitKind::CopyInit; 1093 else 1094 InitKind = LambdaCaptureInitKind::ListInit; 1095 1096 if (!Tentative) { 1097 Init = ParseInitializer(); 1098 } else if (Tok.is(tok::l_brace)) { 1099 BalancedDelimiterTracker Braces(*this, tok::l_brace); 1100 Braces.consumeOpen(); 1101 Braces.skipToEnd(); 1102 *Tentative = LambdaIntroducerTentativeParse::Incomplete; 1103 } else { 1104 // We're disambiguating this: 1105 // 1106 // [..., x = expr 1107 // 1108 // We need to find the end of the following expression in order to 1109 // determine whether this is an Obj-C message send's receiver, a 1110 // C99 designator, or a lambda init-capture. 1111 // 1112 // Parse the expression to find where it ends, and annotate it back 1113 // onto the tokens. We would have parsed this expression the same way 1114 // in either case: both the RHS of an init-capture and the RHS of an 1115 // assignment expression are parsed as an initializer-clause, and in 1116 // neither case can anything be added to the scope between the '[' and 1117 // here. 1118 // 1119 // FIXME: This is horrible. Adding a mechanism to skip an expression 1120 // would be much cleaner. 1121 // FIXME: If there is a ',' before the next ']' or ':', we can skip to 1122 // that instead. (And if we see a ':' with no matching '?', we can 1123 // classify this as an Obj-C message send.) 1124 SourceLocation StartLoc = Tok.getLocation(); 1125 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true); 1126 Init = ParseInitializer(); 1127 if (!Init.isInvalid()) 1128 Init = Actions.CorrectDelayedTyposInExpr(Init.get()); 1129 1130 if (Tok.getLocation() != StartLoc) { 1131 // Back out the lexing of the token after the initializer. 1132 PP.RevertCachedTokens(1); 1133 1134 // Replace the consumed tokens with an appropriate annotation. 1135 Tok.setLocation(StartLoc); 1136 Tok.setKind(tok::annot_primary_expr); 1137 setExprAnnotation(Tok, Init); 1138 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation()); 1139 PP.AnnotateCachedTokens(Tok); 1140 1141 // Consume the annotated initializer. 1142 ConsumeAnnotationToken(); 1143 } 1144 } 1145 } 1146 1147 TryConsumeToken(tok::ellipsis, EllipsisLocs[3]); 1148 } 1149 1150 // Check if this is a message send before we act on a possible init-capture. 1151 if (Tentative && Tok.is(tok::identifier) && 1152 NextToken().isOneOf(tok::colon, tok::r_square)) { 1153 // This can only be a message send. We're done with disambiguation. 1154 *Tentative = LambdaIntroducerTentativeParse::MessageSend; 1155 return false; 1156 } 1157 1158 // Ensure that any ellipsis was in the right place. 1159 SourceLocation EllipsisLoc; 1160 if (llvm::any_of(EllipsisLocs, 1161 [](SourceLocation Loc) { return Loc.isValid(); })) { 1162 // The '...' should appear before the identifier in an init-capture, and 1163 // after the identifier otherwise. 1164 bool InitCapture = InitKind != LambdaCaptureInitKind::NoInit; 1165 SourceLocation *ExpectedEllipsisLoc = 1166 !InitCapture ? &EllipsisLocs[2] : 1167 Kind == LCK_ByRef ? &EllipsisLocs[1] : 1168 &EllipsisLocs[0]; 1169 EllipsisLoc = *ExpectedEllipsisLoc; 1170 1171 unsigned DiagID = 0; 1172 if (EllipsisLoc.isInvalid()) { 1173 DiagID = diag::err_lambda_capture_misplaced_ellipsis; 1174 for (SourceLocation Loc : EllipsisLocs) { 1175 if (Loc.isValid()) 1176 EllipsisLoc = Loc; 1177 } 1178 } else { 1179 unsigned NumEllipses = std::accumulate( 1180 std::begin(EllipsisLocs), std::end(EllipsisLocs), 0, 1181 [](int N, SourceLocation Loc) { return N + Loc.isValid(); }); 1182 if (NumEllipses > 1) 1183 DiagID = diag::err_lambda_capture_multiple_ellipses; 1184 } 1185 if (DiagID) { 1186 NonTentativeAction([&] { 1187 // Point the diagnostic at the first misplaced ellipsis. 1188 SourceLocation DiagLoc; 1189 for (SourceLocation &Loc : EllipsisLocs) { 1190 if (&Loc != ExpectedEllipsisLoc && Loc.isValid()) { 1191 DiagLoc = Loc; 1192 break; 1193 } 1194 } 1195 assert(DiagLoc.isValid() && "no location for diagnostic"); 1196 1197 // Issue the diagnostic and produce fixits showing where the ellipsis 1198 // should have been written. 1199 auto &&D = Diag(DiagLoc, DiagID); 1200 if (DiagID == diag::err_lambda_capture_misplaced_ellipsis) { 1201 SourceLocation ExpectedLoc = 1202 InitCapture ? Loc 1203 : Lexer::getLocForEndOfToken( 1204 Loc, 0, PP.getSourceManager(), getLangOpts()); 1205 D << InitCapture << FixItHint::CreateInsertion(ExpectedLoc, "..."); 1206 } 1207 for (SourceLocation &Loc : EllipsisLocs) { 1208 if (&Loc != ExpectedEllipsisLoc && Loc.isValid()) 1209 D << FixItHint::CreateRemoval(Loc); 1210 } 1211 }); 1212 } 1213 } 1214 1215 // Process the init-capture initializers now rather than delaying until we 1216 // form the lambda-expression so that they can be handled in the context 1217 // enclosing the lambda-expression, rather than in the context of the 1218 // lambda-expression itself. 1219 ParsedType InitCaptureType; 1220 if (Init.isUsable()) 1221 Init = Actions.CorrectDelayedTyposInExpr(Init.get()); 1222 if (Init.isUsable()) { 1223 NonTentativeAction([&] { 1224 // Get the pointer and store it in an lvalue, so we can use it as an 1225 // out argument. 1226 Expr *InitExpr = Init.get(); 1227 // This performs any lvalue-to-rvalue conversions if necessary, which 1228 // can affect what gets captured in the containing decl-context. 1229 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization( 1230 Loc, Kind == LCK_ByRef, EllipsisLoc, Id, InitKind, InitExpr); 1231 Init = InitExpr; 1232 }); 1233 } 1234 1235 SourceLocation LocEnd = PrevTokLocation; 1236 1237 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init, 1238 InitCaptureType, SourceRange(LocStart, LocEnd)); 1239 } 1240 1241 T.consumeClose(); 1242 Intro.Range.setEnd(T.getCloseLocation()); 1243 return false; 1244 } 1245 1246 static void tryConsumeLambdaSpecifierToken(Parser &P, 1247 SourceLocation &MutableLoc, 1248 SourceLocation &StaticLoc, 1249 SourceLocation &ConstexprLoc, 1250 SourceLocation &ConstevalLoc, 1251 SourceLocation &DeclEndLoc) { 1252 assert(MutableLoc.isInvalid()); 1253 assert(StaticLoc.isInvalid()); 1254 assert(ConstexprLoc.isInvalid()); 1255 assert(ConstevalLoc.isInvalid()); 1256 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc 1257 // to the final of those locations. Emit an error if we have multiple 1258 // copies of those keywords and recover. 1259 1260 auto ConsumeLocation = [&P, &DeclEndLoc](SourceLocation &SpecifierLoc, 1261 int DiagIndex) { 1262 if (SpecifierLoc.isValid()) { 1263 P.Diag(P.getCurToken().getLocation(), 1264 diag::err_lambda_decl_specifier_repeated) 1265 << DiagIndex 1266 << FixItHint::CreateRemoval(P.getCurToken().getLocation()); 1267 } 1268 SpecifierLoc = P.ConsumeToken(); 1269 DeclEndLoc = SpecifierLoc; 1270 }; 1271 1272 while (true) { 1273 switch (P.getCurToken().getKind()) { 1274 case tok::kw_mutable: 1275 ConsumeLocation(MutableLoc, 0); 1276 break; 1277 case tok::kw_static: 1278 ConsumeLocation(StaticLoc, 1); 1279 break; 1280 case tok::kw_constexpr: 1281 ConsumeLocation(ConstexprLoc, 2); 1282 break; 1283 case tok::kw_consteval: 1284 ConsumeLocation(ConstevalLoc, 3); 1285 break; 1286 default: 1287 return; 1288 } 1289 } 1290 } 1291 1292 static void addStaticToLambdaDeclSpecifier(Parser &P, SourceLocation StaticLoc, 1293 DeclSpec &DS) { 1294 if (StaticLoc.isValid()) { 1295 P.Diag(StaticLoc, !P.getLangOpts().CPlusPlus23 1296 ? diag::err_static_lambda 1297 : diag::warn_cxx20_compat_static_lambda); 1298 const char *PrevSpec = nullptr; 1299 unsigned DiagID = 0; 1300 DS.SetStorageClassSpec(P.getActions(), DeclSpec::SCS_static, StaticLoc, 1301 PrevSpec, DiagID, 1302 P.getActions().getASTContext().getPrintingPolicy()); 1303 assert(PrevSpec == nullptr && DiagID == 0 && 1304 "Static cannot have been set previously!"); 1305 } 1306 } 1307 1308 static void 1309 addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc, 1310 DeclSpec &DS) { 1311 if (ConstexprLoc.isValid()) { 1312 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17 1313 ? diag::ext_constexpr_on_lambda_cxx17 1314 : diag::warn_cxx14_compat_constexpr_on_lambda); 1315 const char *PrevSpec = nullptr; 1316 unsigned DiagID = 0; 1317 DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, ConstexprLoc, PrevSpec, 1318 DiagID); 1319 assert(PrevSpec == nullptr && DiagID == 0 && 1320 "Constexpr cannot have been set previously!"); 1321 } 1322 } 1323 1324 static void addConstevalToLambdaDeclSpecifier(Parser &P, 1325 SourceLocation ConstevalLoc, 1326 DeclSpec &DS) { 1327 if (ConstevalLoc.isValid()) { 1328 P.Diag(ConstevalLoc, diag::warn_cxx20_compat_consteval); 1329 const char *PrevSpec = nullptr; 1330 unsigned DiagID = 0; 1331 DS.SetConstexprSpec(ConstexprSpecKind::Consteval, ConstevalLoc, PrevSpec, 1332 DiagID); 1333 if (DiagID != 0) 1334 P.Diag(ConstevalLoc, DiagID) << PrevSpec; 1335 } 1336 } 1337 1338 static void DiagnoseStaticSpecifierRestrictions(Parser &P, 1339 SourceLocation StaticLoc, 1340 SourceLocation MutableLoc, 1341 const LambdaIntroducer &Intro) { 1342 if (StaticLoc.isInvalid()) 1343 return; 1344 1345 // [expr.prim.lambda.general] p4 1346 // The lambda-specifier-seq shall not contain both mutable and static. 1347 // If the lambda-specifier-seq contains static, there shall be no 1348 // lambda-capture. 1349 if (MutableLoc.isValid()) 1350 P.Diag(StaticLoc, diag::err_static_mutable_lambda); 1351 if (Intro.hasLambdaCapture()) { 1352 P.Diag(StaticLoc, diag::err_static_lambda_captures); 1353 } 1354 } 1355 1356 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda 1357 /// expression. 1358 ExprResult Parser::ParseLambdaExpressionAfterIntroducer( 1359 LambdaIntroducer &Intro) { 1360 SourceLocation LambdaBeginLoc = Intro.Range.getBegin(); 1361 if (getLangOpts().HLSL) 1362 Diag(LambdaBeginLoc, diag::ext_hlsl_lambda) << /*HLSL*/ 1; 1363 else 1364 Diag(LambdaBeginLoc, getLangOpts().CPlusPlus11 1365 ? diag::warn_cxx98_compat_lambda 1366 : diag::ext_lambda) 1367 << /*C++*/ 0; 1368 1369 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc, 1370 "lambda expression parsing"); 1371 1372 // Parse lambda-declarator[opt]. 1373 DeclSpec DS(AttrFactory); 1374 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::LambdaExpr); 1375 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); 1376 1377 ParseScope LambdaScope(this, Scope::LambdaScope | Scope::DeclScope | 1378 Scope::FunctionDeclarationScope | 1379 Scope::FunctionPrototypeScope); 1380 1381 Actions.PushLambdaScope(); 1382 Actions.ActOnLambdaExpressionAfterIntroducer(Intro, getCurScope()); 1383 1384 ParsedAttributes Attributes(AttrFactory); 1385 if (getLangOpts().CUDA) { 1386 // In CUDA code, GNU attributes are allowed to appear immediately after the 1387 // "[...]", even if there is no "(...)" before the lambda body. 1388 // 1389 // Note that we support __noinline__ as a keyword in this mode and thus 1390 // it has to be separately handled. 1391 while (true) { 1392 if (Tok.is(tok::kw___noinline__)) { 1393 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 1394 SourceLocation AttrNameLoc = ConsumeToken(); 1395 Attributes.addNew(AttrName, AttrNameLoc, /*ScopeName=*/nullptr, 1396 AttrNameLoc, /*ArgsUnion=*/nullptr, 1397 /*numArgs=*/0, tok::kw___noinline__); 1398 } else if (Tok.is(tok::kw___attribute)) 1399 ParseGNUAttributes(Attributes, /*LatePArsedAttrList=*/nullptr, &D); 1400 else 1401 break; 1402 } 1403 1404 D.takeAttributes(Attributes); 1405 } 1406 1407 MultiParseScope TemplateParamScope(*this); 1408 if (Tok.is(tok::less)) { 1409 Diag(Tok, getLangOpts().CPlusPlus20 1410 ? diag::warn_cxx17_compat_lambda_template_parameter_list 1411 : diag::ext_lambda_template_parameter_list); 1412 1413 SmallVector<NamedDecl*, 4> TemplateParams; 1414 SourceLocation LAngleLoc, RAngleLoc; 1415 if (ParseTemplateParameters(TemplateParamScope, 1416 CurTemplateDepthTracker.getDepth(), 1417 TemplateParams, LAngleLoc, RAngleLoc)) { 1418 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope()); 1419 return ExprError(); 1420 } 1421 1422 if (TemplateParams.empty()) { 1423 Diag(RAngleLoc, 1424 diag::err_lambda_template_parameter_list_empty); 1425 } else { 1426 // We increase the template depth before recursing into a requires-clause. 1427 // 1428 // This depth is used for setting up a LambdaScopeInfo (in 1429 // Sema::RecordParsingTemplateParameterDepth), which is used later when 1430 // inventing template parameters in InventTemplateParameter. 1431 // 1432 // This way, abbreviated generic lambdas could have different template 1433 // depths, avoiding substitution into the wrong template parameters during 1434 // constraint satisfaction check. 1435 ++CurTemplateDepthTracker; 1436 ExprResult RequiresClause; 1437 if (TryConsumeToken(tok::kw_requires)) { 1438 RequiresClause = 1439 Actions.ActOnRequiresClause(ParseConstraintLogicalOrExpression( 1440 /*IsTrailingRequiresClause=*/false)); 1441 if (RequiresClause.isInvalid()) 1442 SkipUntil({tok::l_brace, tok::l_paren}, StopAtSemi | StopBeforeMatch); 1443 } 1444 1445 Actions.ActOnLambdaExplicitTemplateParameterList( 1446 Intro, LAngleLoc, TemplateParams, RAngleLoc, RequiresClause); 1447 } 1448 } 1449 1450 // Implement WG21 P2173, which allows attributes immediately before the 1451 // lambda declarator and applies them to the corresponding function operator 1452 // or operator template declaration. We accept this as a conforming extension 1453 // in all language modes that support lambdas. 1454 if (isCXX11AttributeSpecifier()) { 1455 Diag(Tok, getLangOpts().CPlusPlus23 1456 ? diag::warn_cxx20_compat_decl_attrs_on_lambda 1457 : diag::ext_decl_attrs_on_lambda) 1458 << Tok.getIdentifierInfo() << Tok.isRegularKeywordAttribute(); 1459 MaybeParseCXX11Attributes(D); 1460 } 1461 1462 TypeResult TrailingReturnType; 1463 SourceLocation TrailingReturnTypeLoc; 1464 SourceLocation LParenLoc, RParenLoc; 1465 SourceLocation DeclEndLoc; 1466 bool HasParentheses = false; 1467 bool HasSpecifiers = false; 1468 SourceLocation MutableLoc; 1469 1470 ParseScope Prototype(this, Scope::FunctionPrototypeScope | 1471 Scope::FunctionDeclarationScope | 1472 Scope::DeclScope); 1473 1474 // Parse parameter-declaration-clause. 1475 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 1476 SourceLocation EllipsisLoc; 1477 1478 if (Tok.is(tok::l_paren)) { 1479 BalancedDelimiterTracker T(*this, tok::l_paren); 1480 T.consumeOpen(); 1481 LParenLoc = T.getOpenLocation(); 1482 1483 if (Tok.isNot(tok::r_paren)) { 1484 Actions.RecordParsingTemplateParameterDepth( 1485 CurTemplateDepthTracker.getOriginalDepth()); 1486 1487 ParseParameterDeclarationClause(D, Attributes, ParamInfo, EllipsisLoc); 1488 // For a generic lambda, each 'auto' within the parameter declaration 1489 // clause creates a template type parameter, so increment the depth. 1490 // If we've parsed any explicit template parameters, then the depth will 1491 // have already been incremented. So we make sure that at most a single 1492 // depth level is added. 1493 if (Actions.getCurGenericLambda()) 1494 CurTemplateDepthTracker.setAddedDepth(1); 1495 } 1496 1497 T.consumeClose(); 1498 DeclEndLoc = RParenLoc = T.getCloseLocation(); 1499 HasParentheses = true; 1500 } 1501 1502 HasSpecifiers = 1503 Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute, 1504 tok::kw_constexpr, tok::kw_consteval, tok::kw_static, 1505 tok::kw___private, tok::kw___global, tok::kw___local, 1506 tok::kw___constant, tok::kw___generic, tok::kw_groupshared, 1507 tok::kw_requires, tok::kw_noexcept) || 1508 Tok.isRegularKeywordAttribute() || 1509 (Tok.is(tok::l_square) && NextToken().is(tok::l_square)); 1510 1511 if (HasSpecifiers && !HasParentheses && !getLangOpts().CPlusPlus23) { 1512 // It's common to forget that one needs '()' before 'mutable', an 1513 // attribute specifier, the result type, or the requires clause. Deal with 1514 // this. 1515 Diag(Tok, diag::ext_lambda_missing_parens) 1516 << FixItHint::CreateInsertion(Tok.getLocation(), "() "); 1517 } 1518 1519 if (HasParentheses || HasSpecifiers) { 1520 // GNU-style attributes must be parsed before the mutable specifier to 1521 // be compatible with GCC. MSVC-style attributes must be parsed before 1522 // the mutable specifier to be compatible with MSVC. 1523 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec, Attributes); 1524 // Parse mutable-opt and/or constexpr-opt or consteval-opt, and update 1525 // the DeclEndLoc. 1526 SourceLocation ConstexprLoc; 1527 SourceLocation ConstevalLoc; 1528 SourceLocation StaticLoc; 1529 1530 tryConsumeLambdaSpecifierToken(*this, MutableLoc, StaticLoc, ConstexprLoc, 1531 ConstevalLoc, DeclEndLoc); 1532 1533 DiagnoseStaticSpecifierRestrictions(*this, StaticLoc, MutableLoc, Intro); 1534 1535 addStaticToLambdaDeclSpecifier(*this, StaticLoc, DS); 1536 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS); 1537 addConstevalToLambdaDeclSpecifier(*this, ConstevalLoc, DS); 1538 } 1539 1540 Actions.ActOnLambdaClosureParameters(getCurScope(), ParamInfo); 1541 1542 if (!HasParentheses) 1543 Actions.ActOnLambdaClosureQualifiers(Intro, MutableLoc); 1544 1545 if (HasSpecifiers || HasParentheses) { 1546 // Parse exception-specification[opt]. 1547 ExceptionSpecificationType ESpecType = EST_None; 1548 SourceRange ESpecRange; 1549 SmallVector<ParsedType, 2> DynamicExceptions; 1550 SmallVector<SourceRange, 2> DynamicExceptionRanges; 1551 ExprResult NoexceptExpr; 1552 CachedTokens *ExceptionSpecTokens; 1553 1554 ESpecType = tryParseExceptionSpecification( 1555 /*Delayed=*/false, ESpecRange, DynamicExceptions, 1556 DynamicExceptionRanges, NoexceptExpr, ExceptionSpecTokens); 1557 1558 if (ESpecType != EST_None) 1559 DeclEndLoc = ESpecRange.getEnd(); 1560 1561 // Parse attribute-specifier[opt]. 1562 if (MaybeParseCXX11Attributes(Attributes)) 1563 DeclEndLoc = Attributes.Range.getEnd(); 1564 1565 // Parse OpenCL addr space attribute. 1566 if (Tok.isOneOf(tok::kw___private, tok::kw___global, tok::kw___local, 1567 tok::kw___constant, tok::kw___generic)) { 1568 ParseOpenCLQualifiers(DS.getAttributes()); 1569 ConsumeToken(); 1570 } 1571 1572 SourceLocation FunLocalRangeEnd = DeclEndLoc; 1573 1574 // Parse trailing-return-type[opt]. 1575 if (Tok.is(tok::arrow)) { 1576 FunLocalRangeEnd = Tok.getLocation(); 1577 SourceRange Range; 1578 TrailingReturnType = 1579 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit=*/false); 1580 TrailingReturnTypeLoc = Range.getBegin(); 1581 if (Range.getEnd().isValid()) 1582 DeclEndLoc = Range.getEnd(); 1583 } 1584 1585 SourceLocation NoLoc; 1586 D.AddTypeInfo(DeclaratorChunk::getFunction( 1587 /*HasProto=*/true, 1588 /*IsAmbiguous=*/false, LParenLoc, ParamInfo.data(), 1589 ParamInfo.size(), EllipsisLoc, RParenLoc, 1590 /*RefQualifierIsLvalueRef=*/true, 1591 /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType, 1592 ESpecRange, DynamicExceptions.data(), 1593 DynamicExceptionRanges.data(), DynamicExceptions.size(), 1594 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr, 1595 /*ExceptionSpecTokens*/ nullptr, 1596 /*DeclsInPrototype=*/{}, LParenLoc, FunLocalRangeEnd, D, 1597 TrailingReturnType, TrailingReturnTypeLoc, &DS), 1598 std::move(Attributes), DeclEndLoc); 1599 1600 // We have called ActOnLambdaClosureQualifiers for parentheses-less cases 1601 // above. 1602 if (HasParentheses) 1603 Actions.ActOnLambdaClosureQualifiers(Intro, MutableLoc); 1604 1605 if (HasParentheses && Tok.is(tok::kw_requires)) 1606 ParseTrailingRequiresClause(D); 1607 } 1608 1609 // Emit a warning if we see a CUDA host/device/global attribute 1610 // after '(...)'. nvcc doesn't accept this. 1611 if (getLangOpts().CUDA) { 1612 for (const ParsedAttr &A : Attributes) 1613 if (A.getKind() == ParsedAttr::AT_CUDADevice || 1614 A.getKind() == ParsedAttr::AT_CUDAHost || 1615 A.getKind() == ParsedAttr::AT_CUDAGlobal) 1616 Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position) 1617 << A.getAttrName()->getName(); 1618 } 1619 1620 Prototype.Exit(); 1621 1622 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using 1623 // it. 1624 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope | 1625 Scope::CompoundStmtScope; 1626 ParseScope BodyScope(this, ScopeFlags); 1627 1628 Actions.ActOnStartOfLambdaDefinition(Intro, D, DS); 1629 1630 // Parse compound-statement. 1631 if (!Tok.is(tok::l_brace)) { 1632 Diag(Tok, diag::err_expected_lambda_body); 1633 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope()); 1634 return ExprError(); 1635 } 1636 1637 StmtResult Stmt(ParseCompoundStatementBody()); 1638 BodyScope.Exit(); 1639 TemplateParamScope.Exit(); 1640 LambdaScope.Exit(); 1641 1642 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid() && 1643 !D.isInvalidType()) 1644 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get()); 1645 1646 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope()); 1647 return ExprError(); 1648 } 1649 1650 /// ParseCXXCasts - This handles the various ways to cast expressions to another 1651 /// type. 1652 /// 1653 /// postfix-expression: [C++ 5.2p1] 1654 /// 'dynamic_cast' '<' type-name '>' '(' expression ')' 1655 /// 'static_cast' '<' type-name '>' '(' expression ')' 1656 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')' 1657 /// 'const_cast' '<' type-name '>' '(' expression ')' 1658 /// 1659 /// C++ for OpenCL s2.3.1 adds: 1660 /// 'addrspace_cast' '<' type-name '>' '(' expression ')' 1661 ExprResult Parser::ParseCXXCasts() { 1662 tok::TokenKind Kind = Tok.getKind(); 1663 const char *CastName = nullptr; // For error messages 1664 1665 switch (Kind) { 1666 default: llvm_unreachable("Unknown C++ cast!"); 1667 case tok::kw_addrspace_cast: CastName = "addrspace_cast"; break; 1668 case tok::kw_const_cast: CastName = "const_cast"; break; 1669 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break; 1670 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break; 1671 case tok::kw_static_cast: CastName = "static_cast"; break; 1672 } 1673 1674 SourceLocation OpLoc = ConsumeToken(); 1675 SourceLocation LAngleBracketLoc = Tok.getLocation(); 1676 1677 // Check for "<::" which is parsed as "[:". If found, fix token stream, 1678 // diagnose error, suggest fix, and recover parsing. 1679 if (Tok.is(tok::l_square) && Tok.getLength() == 2) { 1680 Token Next = NextToken(); 1681 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next)) 1682 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true); 1683 } 1684 1685 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName)) 1686 return ExprError(); 1687 1688 // Parse the common declaration-specifiers piece. 1689 DeclSpec DS(AttrFactory); 1690 ParseSpecifierQualifierList(DS, /*AccessSpecifier=*/AS_none, 1691 DeclSpecContext::DSC_type_specifier); 1692 1693 // Parse the abstract-declarator, if present. 1694 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), 1695 DeclaratorContext::TypeName); 1696 ParseDeclarator(DeclaratorInfo); 1697 1698 SourceLocation RAngleBracketLoc = Tok.getLocation(); 1699 1700 if (ExpectAndConsume(tok::greater)) 1701 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less); 1702 1703 BalancedDelimiterTracker T(*this, tok::l_paren); 1704 1705 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName)) 1706 return ExprError(); 1707 1708 ExprResult Result = ParseExpression(); 1709 1710 // Match the ')'. 1711 T.consumeClose(); 1712 1713 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType()) 1714 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind, 1715 LAngleBracketLoc, DeclaratorInfo, 1716 RAngleBracketLoc, 1717 T.getOpenLocation(), Result.get(), 1718 T.getCloseLocation()); 1719 1720 return Result; 1721 } 1722 1723 /// ParseCXXTypeid - This handles the C++ typeid expression. 1724 /// 1725 /// postfix-expression: [C++ 5.2p1] 1726 /// 'typeid' '(' expression ')' 1727 /// 'typeid' '(' type-id ')' 1728 /// 1729 ExprResult Parser::ParseCXXTypeid() { 1730 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!"); 1731 1732 SourceLocation OpLoc = ConsumeToken(); 1733 SourceLocation LParenLoc, RParenLoc; 1734 BalancedDelimiterTracker T(*this, tok::l_paren); 1735 1736 // typeid expressions are always parenthesized. 1737 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid")) 1738 return ExprError(); 1739 LParenLoc = T.getOpenLocation(); 1740 1741 ExprResult Result; 1742 1743 // C++0x [expr.typeid]p3: 1744 // When typeid is applied to an expression other than an lvalue of a 1745 // polymorphic class type [...] The expression is an unevaluated 1746 // operand (Clause 5). 1747 // 1748 // Note that we can't tell whether the expression is an lvalue of a 1749 // polymorphic class type until after we've parsed the expression; we 1750 // speculatively assume the subexpression is unevaluated, and fix it up 1751 // later. 1752 // 1753 // We enter the unevaluated context before trying to determine whether we 1754 // have a type-id, because the tentative parse logic will try to resolve 1755 // names, and must treat them as unevaluated. 1756 EnterExpressionEvaluationContext Unevaluated( 1757 Actions, Sema::ExpressionEvaluationContext::Unevaluated, 1758 Sema::ReuseLambdaContextDecl); 1759 1760 if (isTypeIdInParens()) { 1761 TypeResult Ty = ParseTypeName(); 1762 1763 // Match the ')'. 1764 T.consumeClose(); 1765 RParenLoc = T.getCloseLocation(); 1766 if (Ty.isInvalid() || RParenLoc.isInvalid()) 1767 return ExprError(); 1768 1769 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true, 1770 Ty.get().getAsOpaquePtr(), RParenLoc); 1771 } else { 1772 Result = ParseExpression(); 1773 1774 // Match the ')'. 1775 if (Result.isInvalid()) 1776 SkipUntil(tok::r_paren, StopAtSemi); 1777 else { 1778 T.consumeClose(); 1779 RParenLoc = T.getCloseLocation(); 1780 if (RParenLoc.isInvalid()) 1781 return ExprError(); 1782 1783 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false, 1784 Result.get(), RParenLoc); 1785 } 1786 } 1787 1788 return Result; 1789 } 1790 1791 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression. 1792 /// 1793 /// '__uuidof' '(' expression ')' 1794 /// '__uuidof' '(' type-id ')' 1795 /// 1796 ExprResult Parser::ParseCXXUuidof() { 1797 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!"); 1798 1799 SourceLocation OpLoc = ConsumeToken(); 1800 BalancedDelimiterTracker T(*this, tok::l_paren); 1801 1802 // __uuidof expressions are always parenthesized. 1803 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof")) 1804 return ExprError(); 1805 1806 ExprResult Result; 1807 1808 if (isTypeIdInParens()) { 1809 TypeResult Ty = ParseTypeName(); 1810 1811 // Match the ')'. 1812 T.consumeClose(); 1813 1814 if (Ty.isInvalid()) 1815 return ExprError(); 1816 1817 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true, 1818 Ty.get().getAsOpaquePtr(), 1819 T.getCloseLocation()); 1820 } else { 1821 EnterExpressionEvaluationContext Unevaluated( 1822 Actions, Sema::ExpressionEvaluationContext::Unevaluated); 1823 Result = ParseExpression(); 1824 1825 // Match the ')'. 1826 if (Result.isInvalid()) 1827 SkipUntil(tok::r_paren, StopAtSemi); 1828 else { 1829 T.consumeClose(); 1830 1831 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), 1832 /*isType=*/false, 1833 Result.get(), T.getCloseLocation()); 1834 } 1835 } 1836 1837 return Result; 1838 } 1839 1840 /// Parse a C++ pseudo-destructor expression after the base, 1841 /// . or -> operator, and nested-name-specifier have already been 1842 /// parsed. We're handling this fragment of the grammar: 1843 /// 1844 /// postfix-expression: [C++2a expr.post] 1845 /// postfix-expression . template[opt] id-expression 1846 /// postfix-expression -> template[opt] id-expression 1847 /// 1848 /// id-expression: 1849 /// qualified-id 1850 /// unqualified-id 1851 /// 1852 /// qualified-id: 1853 /// nested-name-specifier template[opt] unqualified-id 1854 /// 1855 /// nested-name-specifier: 1856 /// type-name :: 1857 /// decltype-specifier :: FIXME: not implemented, but probably only 1858 /// allowed in C++ grammar by accident 1859 /// nested-name-specifier identifier :: 1860 /// nested-name-specifier template[opt] simple-template-id :: 1861 /// [...] 1862 /// 1863 /// unqualified-id: 1864 /// ~ type-name 1865 /// ~ decltype-specifier 1866 /// [...] 1867 /// 1868 /// ... where the all but the last component of the nested-name-specifier 1869 /// has already been parsed, and the base expression is not of a non-dependent 1870 /// class type. 1871 ExprResult 1872 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, 1873 tok::TokenKind OpKind, 1874 CXXScopeSpec &SS, 1875 ParsedType ObjectType) { 1876 // If the last component of the (optional) nested-name-specifier is 1877 // template[opt] simple-template-id, it has already been annotated. 1878 UnqualifiedId FirstTypeName; 1879 SourceLocation CCLoc; 1880 if (Tok.is(tok::identifier)) { 1881 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 1882 ConsumeToken(); 1883 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"); 1884 CCLoc = ConsumeToken(); 1885 } else if (Tok.is(tok::annot_template_id)) { 1886 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1887 // FIXME: Carry on and build an AST representation for tooling. 1888 if (TemplateId->isInvalid()) 1889 return ExprError(); 1890 FirstTypeName.setTemplateId(TemplateId); 1891 ConsumeAnnotationToken(); 1892 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"); 1893 CCLoc = ConsumeToken(); 1894 } else { 1895 assert(SS.isEmpty() && "missing last component of nested name specifier"); 1896 FirstTypeName.setIdentifier(nullptr, SourceLocation()); 1897 } 1898 1899 // Parse the tilde. 1900 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail"); 1901 SourceLocation TildeLoc = ConsumeToken(); 1902 1903 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid()) { 1904 DeclSpec DS(AttrFactory); 1905 ParseDecltypeSpecifier(DS); 1906 if (DS.getTypeSpecType() == TST_error) 1907 return ExprError(); 1908 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind, 1909 TildeLoc, DS); 1910 } 1911 1912 if (!Tok.is(tok::identifier)) { 1913 Diag(Tok, diag::err_destructor_tilde_identifier); 1914 return ExprError(); 1915 } 1916 1917 // pack-index-specifier 1918 if (GetLookAheadToken(1).is(tok::ellipsis) && 1919 GetLookAheadToken(2).is(tok::l_square)) { 1920 DeclSpec DS(AttrFactory); 1921 ParsePackIndexingType(DS); 1922 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind, 1923 TildeLoc, DS); 1924 } 1925 1926 // Parse the second type. 1927 UnqualifiedId SecondTypeName; 1928 IdentifierInfo *Name = Tok.getIdentifierInfo(); 1929 SourceLocation NameLoc = ConsumeToken(); 1930 SecondTypeName.setIdentifier(Name, NameLoc); 1931 1932 // If there is a '<', the second type name is a template-id. Parse 1933 // it as such. 1934 // 1935 // FIXME: This is not a context in which a '<' is assumed to start a template 1936 // argument list. This affects examples such as 1937 // void f(auto *p) { p->~X<int>(); } 1938 // ... but there's no ambiguity, and nowhere to write 'template' in such an 1939 // example, so we accept it anyway. 1940 if (Tok.is(tok::less) && 1941 ParseUnqualifiedIdTemplateId( 1942 SS, ObjectType, Base && Base->containsErrors(), SourceLocation(), 1943 Name, NameLoc, false, SecondTypeName, 1944 /*AssumeTemplateId=*/true)) 1945 return ExprError(); 1946 1947 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind, 1948 SS, FirstTypeName, CCLoc, TildeLoc, 1949 SecondTypeName); 1950 } 1951 1952 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals. 1953 /// 1954 /// boolean-literal: [C++ 2.13.5] 1955 /// 'true' 1956 /// 'false' 1957 ExprResult Parser::ParseCXXBoolLiteral() { 1958 tok::TokenKind Kind = Tok.getKind(); 1959 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind); 1960 } 1961 1962 /// ParseThrowExpression - This handles the C++ throw expression. 1963 /// 1964 /// throw-expression: [C++ 15] 1965 /// 'throw' assignment-expression[opt] 1966 ExprResult Parser::ParseThrowExpression() { 1967 assert(Tok.is(tok::kw_throw) && "Not throw!"); 1968 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token. 1969 1970 // If the current token isn't the start of an assignment-expression, 1971 // then the expression is not present. This handles things like: 1972 // "C ? throw : (void)42", which is crazy but legal. 1973 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common. 1974 case tok::semi: 1975 case tok::r_paren: 1976 case tok::r_square: 1977 case tok::r_brace: 1978 case tok::colon: 1979 case tok::comma: 1980 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr); 1981 1982 default: 1983 ExprResult Expr(ParseAssignmentExpression()); 1984 if (Expr.isInvalid()) return Expr; 1985 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get()); 1986 } 1987 } 1988 1989 /// Parse the C++ Coroutines co_yield expression. 1990 /// 1991 /// co_yield-expression: 1992 /// 'co_yield' assignment-expression[opt] 1993 ExprResult Parser::ParseCoyieldExpression() { 1994 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!"); 1995 1996 SourceLocation Loc = ConsumeToken(); 1997 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer() 1998 : ParseAssignmentExpression(); 1999 if (!Expr.isInvalid()) 2000 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get()); 2001 return Expr; 2002 } 2003 2004 /// ParseCXXThis - This handles the C++ 'this' pointer. 2005 /// 2006 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is 2007 /// a non-lvalue expression whose value is the address of the object for which 2008 /// the function is called. 2009 ExprResult Parser::ParseCXXThis() { 2010 assert(Tok.is(tok::kw_this) && "Not 'this'!"); 2011 SourceLocation ThisLoc = ConsumeToken(); 2012 return Actions.ActOnCXXThis(ThisLoc); 2013 } 2014 2015 /// ParseCXXTypeConstructExpression - Parse construction of a specified type. 2016 /// Can be interpreted either as function-style casting ("int(x)") 2017 /// or class type construction ("ClassType(x,y,z)") 2018 /// or creation of a value-initialized type ("int()"). 2019 /// See [C++ 5.2.3]. 2020 /// 2021 /// postfix-expression: [C++ 5.2p1] 2022 /// simple-type-specifier '(' expression-list[opt] ')' 2023 /// [C++0x] simple-type-specifier braced-init-list 2024 /// typename-specifier '(' expression-list[opt] ')' 2025 /// [C++0x] typename-specifier braced-init-list 2026 /// 2027 /// In C++1z onwards, the type specifier can also be a template-name. 2028 ExprResult 2029 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) { 2030 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), 2031 DeclaratorContext::FunctionalCast); 2032 ParsedType TypeRep = Actions.ActOnTypeName(DeclaratorInfo).get(); 2033 2034 assert((Tok.is(tok::l_paren) || 2035 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) 2036 && "Expected '(' or '{'!"); 2037 2038 if (Tok.is(tok::l_brace)) { 2039 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get()); 2040 ExprResult Init = ParseBraceInitializer(); 2041 if (Init.isInvalid()) 2042 return Init; 2043 Expr *InitList = Init.get(); 2044 return Actions.ActOnCXXTypeConstructExpr( 2045 TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1), 2046 InitList->getEndLoc(), /*ListInitialization=*/true); 2047 } else { 2048 BalancedDelimiterTracker T(*this, tok::l_paren); 2049 T.consumeOpen(); 2050 2051 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get()); 2052 2053 ExprVector Exprs; 2054 2055 auto RunSignatureHelp = [&]() { 2056 QualType PreferredType; 2057 if (TypeRep) 2058 PreferredType = 2059 Actions.CodeCompletion().ProduceConstructorSignatureHelp( 2060 TypeRep.get()->getCanonicalTypeInternal(), DS.getEndLoc(), 2061 Exprs, T.getOpenLocation(), /*Braced=*/false); 2062 CalledSignatureHelp = true; 2063 return PreferredType; 2064 }; 2065 2066 if (Tok.isNot(tok::r_paren)) { 2067 if (ParseExpressionList(Exprs, [&] { 2068 PreferredType.enterFunctionArgument(Tok.getLocation(), 2069 RunSignatureHelp); 2070 })) { 2071 if (PP.isCodeCompletionReached() && !CalledSignatureHelp) 2072 RunSignatureHelp(); 2073 SkipUntil(tok::r_paren, StopAtSemi); 2074 return ExprError(); 2075 } 2076 } 2077 2078 // Match the ')'. 2079 T.consumeClose(); 2080 2081 // TypeRep could be null, if it references an invalid typedef. 2082 if (!TypeRep) 2083 return ExprError(); 2084 2085 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(), 2086 Exprs, T.getCloseLocation(), 2087 /*ListInitialization=*/false); 2088 } 2089 } 2090 2091 Parser::DeclGroupPtrTy 2092 Parser::ParseAliasDeclarationInInitStatement(DeclaratorContext Context, 2093 ParsedAttributes &Attrs) { 2094 assert(Tok.is(tok::kw_using) && "Expected using"); 2095 assert((Context == DeclaratorContext::ForInit || 2096 Context == DeclaratorContext::SelectionInit) && 2097 "Unexpected Declarator Context"); 2098 DeclGroupPtrTy DG; 2099 SourceLocation DeclStart = ConsumeToken(), DeclEnd; 2100 2101 DG = ParseUsingDeclaration(Context, {}, DeclStart, DeclEnd, Attrs, AS_none); 2102 if (!DG) 2103 return DG; 2104 2105 Diag(DeclStart, !getLangOpts().CPlusPlus23 2106 ? diag::ext_alias_in_init_statement 2107 : diag::warn_cxx20_alias_in_init_statement) 2108 << SourceRange(DeclStart, DeclEnd); 2109 2110 return DG; 2111 } 2112 2113 /// ParseCXXCondition - if/switch/while condition expression. 2114 /// 2115 /// condition: 2116 /// expression 2117 /// type-specifier-seq declarator '=' assignment-expression 2118 /// [C++11] type-specifier-seq declarator '=' initializer-clause 2119 /// [C++11] type-specifier-seq declarator braced-init-list 2120 /// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']' 2121 /// brace-or-equal-initializer 2122 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt] 2123 /// '=' assignment-expression 2124 /// 2125 /// In C++1z, a condition may in some contexts be preceded by an 2126 /// optional init-statement. This function will parse that too. 2127 /// 2128 /// \param InitStmt If non-null, an init-statement is permitted, and if present 2129 /// will be parsed and stored here. 2130 /// 2131 /// \param Loc The location of the start of the statement that requires this 2132 /// condition, e.g., the "for" in a for loop. 2133 /// 2134 /// \param MissingOK Whether an empty condition is acceptable here. Otherwise 2135 /// it is considered an error to be recovered from. 2136 /// 2137 /// \param FRI If non-null, a for range declaration is permitted, and if 2138 /// present will be parsed and stored here, and a null result will be returned. 2139 /// 2140 /// \param EnterForConditionScope If true, enter a continue/break scope at the 2141 /// appropriate moment for a 'for' loop. 2142 /// 2143 /// \returns The parsed condition. 2144 Sema::ConditionResult 2145 Parser::ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc, 2146 Sema::ConditionKind CK, bool MissingOK, 2147 ForRangeInfo *FRI, bool EnterForConditionScope) { 2148 // Helper to ensure we always enter a continue/break scope if requested. 2149 struct ForConditionScopeRAII { 2150 Scope *S; 2151 void enter(bool IsConditionVariable) { 2152 if (S) { 2153 S->AddFlags(Scope::BreakScope | Scope::ContinueScope); 2154 S->setIsConditionVarScope(IsConditionVariable); 2155 } 2156 } 2157 ~ForConditionScopeRAII() { 2158 if (S) 2159 S->setIsConditionVarScope(false); 2160 } 2161 } ForConditionScope{EnterForConditionScope ? getCurScope() : nullptr}; 2162 2163 ParenBraceBracketBalancer BalancerRAIIObj(*this); 2164 PreferredType.enterCondition(Actions, Tok.getLocation()); 2165 2166 if (Tok.is(tok::code_completion)) { 2167 cutOffParsing(); 2168 Actions.CodeCompletion().CodeCompleteOrdinaryName( 2169 getCurScope(), SemaCodeCompletion::PCC_Condition); 2170 return Sema::ConditionError(); 2171 } 2172 2173 ParsedAttributes attrs(AttrFactory); 2174 MaybeParseCXX11Attributes(attrs); 2175 2176 const auto WarnOnInit = [this, &CK] { 2177 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 2178 ? diag::warn_cxx14_compat_init_statement 2179 : diag::ext_init_statement) 2180 << (CK == Sema::ConditionKind::Switch); 2181 }; 2182 2183 // Determine what kind of thing we have. 2184 switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) { 2185 case ConditionOrInitStatement::Expression: { 2186 // If this is a for loop, we're entering its condition. 2187 ForConditionScope.enter(/*IsConditionVariable=*/false); 2188 2189 ProhibitAttributes(attrs); 2190 2191 // We can have an empty expression here. 2192 // if (; true); 2193 if (InitStmt && Tok.is(tok::semi)) { 2194 WarnOnInit(); 2195 SourceLocation SemiLoc = Tok.getLocation(); 2196 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) { 2197 Diag(SemiLoc, diag::warn_empty_init_statement) 2198 << (CK == Sema::ConditionKind::Switch) 2199 << FixItHint::CreateRemoval(SemiLoc); 2200 } 2201 ConsumeToken(); 2202 *InitStmt = Actions.ActOnNullStmt(SemiLoc); 2203 return ParseCXXCondition(nullptr, Loc, CK, MissingOK); 2204 } 2205 2206 // Parse the expression. 2207 ExprResult Expr = ParseExpression(); // expression 2208 if (Expr.isInvalid()) 2209 return Sema::ConditionError(); 2210 2211 if (InitStmt && Tok.is(tok::semi)) { 2212 WarnOnInit(); 2213 *InitStmt = Actions.ActOnExprStmt(Expr.get()); 2214 ConsumeToken(); 2215 return ParseCXXCondition(nullptr, Loc, CK, MissingOK); 2216 } 2217 2218 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK, 2219 MissingOK); 2220 } 2221 2222 case ConditionOrInitStatement::InitStmtDecl: { 2223 WarnOnInit(); 2224 DeclGroupPtrTy DG; 2225 SourceLocation DeclStart = Tok.getLocation(), DeclEnd; 2226 if (Tok.is(tok::kw_using)) 2227 DG = ParseAliasDeclarationInInitStatement( 2228 DeclaratorContext::SelectionInit, attrs); 2229 else { 2230 ParsedAttributes DeclSpecAttrs(AttrFactory); 2231 DG = ParseSimpleDeclaration(DeclaratorContext::SelectionInit, DeclEnd, 2232 attrs, DeclSpecAttrs, /*RequireSemi=*/true); 2233 } 2234 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd); 2235 return ParseCXXCondition(nullptr, Loc, CK, MissingOK); 2236 } 2237 2238 case ConditionOrInitStatement::ForRangeDecl: { 2239 // This is 'for (init-stmt; for-range-decl : range-expr)'. 2240 // We're not actually in a for loop yet, so 'break' and 'continue' aren't 2241 // permitted here. 2242 assert(FRI && "should not parse a for range declaration here"); 2243 SourceLocation DeclStart = Tok.getLocation(), DeclEnd; 2244 ParsedAttributes DeclSpecAttrs(AttrFactory); 2245 DeclGroupPtrTy DG = ParseSimpleDeclaration( 2246 DeclaratorContext::ForInit, DeclEnd, attrs, DeclSpecAttrs, false, FRI); 2247 FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation()); 2248 return Sema::ConditionResult(); 2249 } 2250 2251 case ConditionOrInitStatement::ConditionDecl: 2252 case ConditionOrInitStatement::Error: 2253 break; 2254 } 2255 2256 // If this is a for loop, we're entering its condition. 2257 ForConditionScope.enter(/*IsConditionVariable=*/true); 2258 2259 // type-specifier-seq 2260 DeclSpec DS(AttrFactory); 2261 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition); 2262 2263 // declarator 2264 Declarator DeclaratorInfo(DS, attrs, DeclaratorContext::Condition); 2265 ParseDeclarator(DeclaratorInfo); 2266 2267 // simple-asm-expr[opt] 2268 if (Tok.is(tok::kw_asm)) { 2269 SourceLocation Loc; 2270 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc)); 2271 if (AsmLabel.isInvalid()) { 2272 SkipUntil(tok::semi, StopAtSemi); 2273 return Sema::ConditionError(); 2274 } 2275 DeclaratorInfo.setAsmLabel(AsmLabel.get()); 2276 DeclaratorInfo.SetRangeEnd(Loc); 2277 } 2278 2279 // If attributes are present, parse them. 2280 MaybeParseGNUAttributes(DeclaratorInfo); 2281 2282 // Type-check the declaration itself. 2283 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(), 2284 DeclaratorInfo); 2285 if (Dcl.isInvalid()) 2286 return Sema::ConditionError(); 2287 Decl *DeclOut = Dcl.get(); 2288 2289 // '=' assignment-expression 2290 // If a '==' or '+=' is found, suggest a fixit to '='. 2291 bool CopyInitialization = isTokenEqualOrEqualTypo(); 2292 if (CopyInitialization) 2293 ConsumeToken(); 2294 2295 ExprResult InitExpr = ExprError(); 2296 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 2297 Diag(Tok.getLocation(), 2298 diag::warn_cxx98_compat_generalized_initializer_lists); 2299 InitExpr = ParseBraceInitializer(); 2300 } else if (CopyInitialization) { 2301 PreferredType.enterVariableInit(Tok.getLocation(), DeclOut); 2302 InitExpr = ParseAssignmentExpression(); 2303 } else if (Tok.is(tok::l_paren)) { 2304 // This was probably an attempt to initialize the variable. 2305 SourceLocation LParen = ConsumeParen(), RParen = LParen; 2306 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) 2307 RParen = ConsumeParen(); 2308 Diag(DeclOut->getLocation(), 2309 diag::err_expected_init_in_condition_lparen) 2310 << SourceRange(LParen, RParen); 2311 } else { 2312 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition); 2313 } 2314 2315 if (!InitExpr.isInvalid()) 2316 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization); 2317 else 2318 Actions.ActOnInitializerError(DeclOut); 2319 2320 Actions.FinalizeDeclaration(DeclOut); 2321 return Actions.ActOnConditionVariable(DeclOut, Loc, CK); 2322 } 2323 2324 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. 2325 /// This should only be called when the current token is known to be part of 2326 /// simple-type-specifier. 2327 /// 2328 /// simple-type-specifier: 2329 /// '::'[opt] nested-name-specifier[opt] type-name 2330 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO] 2331 /// char 2332 /// wchar_t 2333 /// bool 2334 /// short 2335 /// int 2336 /// long 2337 /// signed 2338 /// unsigned 2339 /// float 2340 /// double 2341 /// void 2342 /// [GNU] typeof-specifier 2343 /// [C++0x] auto [TODO] 2344 /// 2345 /// type-name: 2346 /// class-name 2347 /// enum-name 2348 /// typedef-name 2349 /// 2350 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { 2351 DS.SetRangeStart(Tok.getLocation()); 2352 const char *PrevSpec; 2353 unsigned DiagID; 2354 SourceLocation Loc = Tok.getLocation(); 2355 const clang::PrintingPolicy &Policy = 2356 Actions.getASTContext().getPrintingPolicy(); 2357 2358 switch (Tok.getKind()) { 2359 case tok::identifier: // foo::bar 2360 case tok::coloncolon: // ::foo::bar 2361 llvm_unreachable("Annotation token should already be formed!"); 2362 default: 2363 llvm_unreachable("Not a simple-type-specifier token!"); 2364 2365 // type-name 2366 case tok::annot_typename: { 2367 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, 2368 getTypeAnnotation(Tok), Policy); 2369 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 2370 ConsumeAnnotationToken(); 2371 DS.Finish(Actions, Policy); 2372 return; 2373 } 2374 2375 case tok::kw__ExtInt: 2376 case tok::kw__BitInt: { 2377 DiagnoseBitIntUse(Tok); 2378 ExprResult ER = ParseExtIntegerArgument(); 2379 if (ER.isInvalid()) 2380 DS.SetTypeSpecError(); 2381 else 2382 DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy); 2383 2384 // Do this here because we have already consumed the close paren. 2385 DS.SetRangeEnd(PrevTokLocation); 2386 DS.Finish(Actions, Policy); 2387 return; 2388 } 2389 2390 // builtin types 2391 case tok::kw_short: 2392 DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec, DiagID, 2393 Policy); 2394 break; 2395 case tok::kw_long: 2396 DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec, DiagID, 2397 Policy); 2398 break; 2399 case tok::kw___int64: 2400 DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc, PrevSpec, DiagID, 2401 Policy); 2402 break; 2403 case tok::kw_signed: 2404 DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID); 2405 break; 2406 case tok::kw_unsigned: 2407 DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec, DiagID); 2408 break; 2409 case tok::kw_void: 2410 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy); 2411 break; 2412 case tok::kw_auto: 2413 DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID, Policy); 2414 break; 2415 case tok::kw_char: 2416 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy); 2417 break; 2418 case tok::kw_int: 2419 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy); 2420 break; 2421 case tok::kw___int128: 2422 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy); 2423 break; 2424 case tok::kw___bf16: 2425 DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec, DiagID, Policy); 2426 break; 2427 case tok::kw_half: 2428 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy); 2429 break; 2430 case tok::kw_float: 2431 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy); 2432 break; 2433 case tok::kw_double: 2434 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy); 2435 break; 2436 case tok::kw__Float16: 2437 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy); 2438 break; 2439 case tok::kw___float128: 2440 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy); 2441 break; 2442 case tok::kw___ibm128: 2443 DS.SetTypeSpecType(DeclSpec::TST_ibm128, Loc, PrevSpec, DiagID, Policy); 2444 break; 2445 case tok::kw_wchar_t: 2446 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy); 2447 break; 2448 case tok::kw_char8_t: 2449 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy); 2450 break; 2451 case tok::kw_char16_t: 2452 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy); 2453 break; 2454 case tok::kw_char32_t: 2455 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy); 2456 break; 2457 case tok::kw_bool: 2458 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy); 2459 break; 2460 case tok::kw__Accum: 2461 DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec, DiagID, Policy); 2462 break; 2463 case tok::kw__Fract: 2464 DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec, DiagID, Policy); 2465 break; 2466 case tok::kw__Sat: 2467 DS.SetTypeSpecSat(Loc, PrevSpec, DiagID); 2468 break; 2469 #define GENERIC_IMAGE_TYPE(ImgType, Id) \ 2470 case tok::kw_##ImgType##_t: \ 2471 DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \ 2472 Policy); \ 2473 break; 2474 #include "clang/Basic/OpenCLImageTypes.def" 2475 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \ 2476 case tok::kw_##Name: \ 2477 DS.SetTypeSpecType(DeclSpec::TST_##Name, Loc, PrevSpec, DiagID, Policy); \ 2478 break; 2479 #include "clang/Basic/HLSLIntangibleTypes.def" 2480 2481 case tok::annot_decltype: 2482 case tok::kw_decltype: 2483 DS.SetRangeEnd(ParseDecltypeSpecifier(DS)); 2484 return DS.Finish(Actions, Policy); 2485 2486 case tok::annot_pack_indexing_type: 2487 DS.SetRangeEnd(ParsePackIndexingType(DS)); 2488 return DS.Finish(Actions, Policy); 2489 2490 // GNU typeof support. 2491 case tok::kw_typeof: 2492 ParseTypeofSpecifier(DS); 2493 DS.Finish(Actions, Policy); 2494 return; 2495 } 2496 ConsumeAnyToken(); 2497 DS.SetRangeEnd(PrevTokLocation); 2498 DS.Finish(Actions, Policy); 2499 } 2500 2501 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++ 2502 /// [dcl.name]), which is a non-empty sequence of type-specifiers, 2503 /// e.g., "const short int". Note that the DeclSpec is *not* finished 2504 /// by parsing the type-specifier-seq, because these sequences are 2505 /// typically followed by some form of declarator. Returns true and 2506 /// emits diagnostics if this is not a type-specifier-seq, false 2507 /// otherwise. 2508 /// 2509 /// type-specifier-seq: [C++ 8.1] 2510 /// type-specifier type-specifier-seq[opt] 2511 /// 2512 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS, DeclaratorContext Context) { 2513 ParseSpecifierQualifierList(DS, AS_none, 2514 getDeclSpecContextFromDeclaratorContext(Context)); 2515 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy()); 2516 return false; 2517 } 2518 2519 /// Finish parsing a C++ unqualified-id that is a template-id of 2520 /// some form. 2521 /// 2522 /// This routine is invoked when a '<' is encountered after an identifier or 2523 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine 2524 /// whether the unqualified-id is actually a template-id. This routine will 2525 /// then parse the template arguments and form the appropriate template-id to 2526 /// return to the caller. 2527 /// 2528 /// \param SS the nested-name-specifier that precedes this template-id, if 2529 /// we're actually parsing a qualified-id. 2530 /// 2531 /// \param ObjectType if this unqualified-id occurs within a member access 2532 /// expression, the type of the base object whose member is being accessed. 2533 /// 2534 /// \param ObjectHadErrors this unqualified-id occurs within a member access 2535 /// expression, indicates whether the original subexpressions had any errors. 2536 /// 2537 /// \param Name for constructor and destructor names, this is the actual 2538 /// identifier that may be a template-name. 2539 /// 2540 /// \param NameLoc the location of the class-name in a constructor or 2541 /// destructor. 2542 /// 2543 /// \param EnteringContext whether we're entering the scope of the 2544 /// nested-name-specifier. 2545 /// 2546 /// \param Id as input, describes the template-name or operator-function-id 2547 /// that precedes the '<'. If template arguments were parsed successfully, 2548 /// will be updated with the template-id. 2549 /// 2550 /// \param AssumeTemplateId When true, this routine will assume that the name 2551 /// refers to a template without performing name lookup to verify. 2552 /// 2553 /// \returns true if a parse error occurred, false otherwise. 2554 bool Parser::ParseUnqualifiedIdTemplateId( 2555 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, 2556 SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, 2557 bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId) { 2558 assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id"); 2559 2560 TemplateTy Template; 2561 TemplateNameKind TNK = TNK_Non_template; 2562 switch (Id.getKind()) { 2563 case UnqualifiedIdKind::IK_Identifier: 2564 case UnqualifiedIdKind::IK_OperatorFunctionId: 2565 case UnqualifiedIdKind::IK_LiteralOperatorId: 2566 if (AssumeTemplateId) { 2567 // We defer the injected-class-name checks until we've found whether 2568 // this template-id is used to form a nested-name-specifier or not. 2569 TNK = Actions.ActOnTemplateName(getCurScope(), SS, TemplateKWLoc, Id, 2570 ObjectType, EnteringContext, Template, 2571 /*AllowInjectedClassName*/ true); 2572 } else { 2573 bool MemberOfUnknownSpecialization; 2574 TNK = Actions.isTemplateName(getCurScope(), SS, 2575 TemplateKWLoc.isValid(), Id, 2576 ObjectType, EnteringContext, Template, 2577 MemberOfUnknownSpecialization); 2578 // If lookup found nothing but we're assuming that this is a template 2579 // name, double-check that makes sense syntactically before committing 2580 // to it. 2581 if (TNK == TNK_Undeclared_template && 2582 isTemplateArgumentList(0) == TPResult::False) 2583 return false; 2584 2585 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization && 2586 ObjectType && isTemplateArgumentList(0) == TPResult::True) { 2587 // If we had errors before, ObjectType can be dependent even without any 2588 // templates, do not report missing template keyword in that case. 2589 if (!ObjectHadErrors) { 2590 // We have something like t->getAs<T>(), where getAs is a 2591 // member of an unknown specialization. However, this will only 2592 // parse correctly as a template, so suggest the keyword 'template' 2593 // before 'getAs' and treat this as a dependent template name. 2594 std::string Name; 2595 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier) 2596 Name = std::string(Id.Identifier->getName()); 2597 else { 2598 Name = "operator "; 2599 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId) 2600 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator); 2601 else 2602 Name += Id.Identifier->getName(); 2603 } 2604 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword) 2605 << Name 2606 << FixItHint::CreateInsertion(Id.StartLocation, "template "); 2607 } 2608 TNK = Actions.ActOnTemplateName( 2609 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext, 2610 Template, /*AllowInjectedClassName*/ true); 2611 } else if (TNK == TNK_Non_template) { 2612 return false; 2613 } 2614 } 2615 break; 2616 2617 case UnqualifiedIdKind::IK_ConstructorName: { 2618 UnqualifiedId TemplateName; 2619 bool MemberOfUnknownSpecialization; 2620 TemplateName.setIdentifier(Name, NameLoc); 2621 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), 2622 TemplateName, ObjectType, 2623 EnteringContext, Template, 2624 MemberOfUnknownSpecialization); 2625 if (TNK == TNK_Non_template) 2626 return false; 2627 break; 2628 } 2629 2630 case UnqualifiedIdKind::IK_DestructorName: { 2631 UnqualifiedId TemplateName; 2632 bool MemberOfUnknownSpecialization; 2633 TemplateName.setIdentifier(Name, NameLoc); 2634 if (ObjectType) { 2635 TNK = Actions.ActOnTemplateName( 2636 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType, 2637 EnteringContext, Template, /*AllowInjectedClassName*/ true); 2638 } else { 2639 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), 2640 TemplateName, ObjectType, 2641 EnteringContext, Template, 2642 MemberOfUnknownSpecialization); 2643 2644 if (TNK == TNK_Non_template && !Id.DestructorName.get()) { 2645 Diag(NameLoc, diag::err_destructor_template_id) 2646 << Name << SS.getRange(); 2647 // Carry on to parse the template arguments before bailing out. 2648 } 2649 } 2650 break; 2651 } 2652 2653 default: 2654 return false; 2655 } 2656 2657 // Parse the enclosed template argument list. 2658 SourceLocation LAngleLoc, RAngleLoc; 2659 TemplateArgList TemplateArgs; 2660 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs, RAngleLoc, 2661 Template)) 2662 return true; 2663 2664 // If this is a non-template, we already issued a diagnostic. 2665 if (TNK == TNK_Non_template) 2666 return true; 2667 2668 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier || 2669 Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId || 2670 Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) { 2671 // Form a parsed representation of the template-id to be stored in the 2672 // UnqualifiedId. 2673 2674 // FIXME: Store name for literal operator too. 2675 const IdentifierInfo *TemplateII = 2676 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier 2677 : nullptr; 2678 OverloadedOperatorKind OpKind = 2679 Id.getKind() == UnqualifiedIdKind::IK_Identifier 2680 ? OO_None 2681 : Id.OperatorFunctionId.Operator; 2682 2683 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create( 2684 TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK, 2685 LAngleLoc, RAngleLoc, TemplateArgs, /*ArgsInvalid*/false, TemplateIds); 2686 2687 Id.setTemplateId(TemplateId); 2688 return false; 2689 } 2690 2691 // Bundle the template arguments together. 2692 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs); 2693 2694 // Constructor and destructor names. 2695 TypeResult Type = Actions.ActOnTemplateIdType( 2696 getCurScope(), SS, TemplateKWLoc, Template, Name, NameLoc, LAngleLoc, 2697 TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true); 2698 if (Type.isInvalid()) 2699 return true; 2700 2701 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName) 2702 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc); 2703 else 2704 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc); 2705 2706 return false; 2707 } 2708 2709 /// Parse an operator-function-id or conversion-function-id as part 2710 /// of a C++ unqualified-id. 2711 /// 2712 /// This routine is responsible only for parsing the operator-function-id or 2713 /// conversion-function-id; it does not handle template arguments in any way. 2714 /// 2715 /// \code 2716 /// operator-function-id: [C++ 13.5] 2717 /// 'operator' operator 2718 /// 2719 /// operator: one of 2720 /// new delete new[] delete[] 2721 /// + - * / % ^ & | ~ 2722 /// ! = < > += -= *= /= %= 2723 /// ^= &= |= << >> >>= <<= == != 2724 /// <= >= && || ++ -- , ->* -> 2725 /// () [] <=> 2726 /// 2727 /// conversion-function-id: [C++ 12.3.2] 2728 /// operator conversion-type-id 2729 /// 2730 /// conversion-type-id: 2731 /// type-specifier-seq conversion-declarator[opt] 2732 /// 2733 /// conversion-declarator: 2734 /// ptr-operator conversion-declarator[opt] 2735 /// \endcode 2736 /// 2737 /// \param SS The nested-name-specifier that preceded this unqualified-id. If 2738 /// non-empty, then we are parsing the unqualified-id of a qualified-id. 2739 /// 2740 /// \param EnteringContext whether we are entering the scope of the 2741 /// nested-name-specifier. 2742 /// 2743 /// \param ObjectType if this unqualified-id occurs within a member access 2744 /// expression, the type of the base object whose member is being accessed. 2745 /// 2746 /// \param Result on a successful parse, contains the parsed unqualified-id. 2747 /// 2748 /// \returns true if parsing fails, false otherwise. 2749 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, 2750 ParsedType ObjectType, 2751 UnqualifiedId &Result) { 2752 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword"); 2753 2754 // Consume the 'operator' keyword. 2755 SourceLocation KeywordLoc = ConsumeToken(); 2756 2757 // Determine what kind of operator name we have. 2758 unsigned SymbolIdx = 0; 2759 SourceLocation SymbolLocations[3]; 2760 OverloadedOperatorKind Op = OO_None; 2761 switch (Tok.getKind()) { 2762 case tok::kw_new: 2763 case tok::kw_delete: { 2764 bool isNew = Tok.getKind() == tok::kw_new; 2765 // Consume the 'new' or 'delete'. 2766 SymbolLocations[SymbolIdx++] = ConsumeToken(); 2767 // Check for array new/delete. 2768 if (Tok.is(tok::l_square) && 2769 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) { 2770 // Consume the '[' and ']'. 2771 BalancedDelimiterTracker T(*this, tok::l_square); 2772 T.consumeOpen(); 2773 T.consumeClose(); 2774 if (T.getCloseLocation().isInvalid()) 2775 return true; 2776 2777 SymbolLocations[SymbolIdx++] = T.getOpenLocation(); 2778 SymbolLocations[SymbolIdx++] = T.getCloseLocation(); 2779 Op = isNew? OO_Array_New : OO_Array_Delete; 2780 } else { 2781 Op = isNew? OO_New : OO_Delete; 2782 } 2783 break; 2784 } 2785 2786 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 2787 case tok::Token: \ 2788 SymbolLocations[SymbolIdx++] = ConsumeToken(); \ 2789 Op = OO_##Name; \ 2790 break; 2791 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly) 2792 #include "clang/Basic/OperatorKinds.def" 2793 2794 case tok::l_paren: { 2795 // Consume the '(' and ')'. 2796 BalancedDelimiterTracker T(*this, tok::l_paren); 2797 T.consumeOpen(); 2798 T.consumeClose(); 2799 if (T.getCloseLocation().isInvalid()) 2800 return true; 2801 2802 SymbolLocations[SymbolIdx++] = T.getOpenLocation(); 2803 SymbolLocations[SymbolIdx++] = T.getCloseLocation(); 2804 Op = OO_Call; 2805 break; 2806 } 2807 2808 case tok::l_square: { 2809 // Consume the '[' and ']'. 2810 BalancedDelimiterTracker T(*this, tok::l_square); 2811 T.consumeOpen(); 2812 T.consumeClose(); 2813 if (T.getCloseLocation().isInvalid()) 2814 return true; 2815 2816 SymbolLocations[SymbolIdx++] = T.getOpenLocation(); 2817 SymbolLocations[SymbolIdx++] = T.getCloseLocation(); 2818 Op = OO_Subscript; 2819 break; 2820 } 2821 2822 case tok::code_completion: { 2823 // Don't try to parse any further. 2824 cutOffParsing(); 2825 // Code completion for the operator name. 2826 Actions.CodeCompletion().CodeCompleteOperatorName(getCurScope()); 2827 return true; 2828 } 2829 2830 default: 2831 break; 2832 } 2833 2834 if (Op != OO_None) { 2835 // We have parsed an operator-function-id. 2836 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations); 2837 return false; 2838 } 2839 2840 // Parse a literal-operator-id. 2841 // 2842 // literal-operator-id: C++11 [over.literal] 2843 // operator string-literal identifier 2844 // operator user-defined-string-literal 2845 2846 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) { 2847 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator); 2848 2849 SourceLocation DiagLoc; 2850 unsigned DiagId = 0; 2851 2852 // We're past translation phase 6, so perform string literal concatenation 2853 // before checking for "". 2854 SmallVector<Token, 4> Toks; 2855 SmallVector<SourceLocation, 4> TokLocs; 2856 while (isTokenStringLiteral()) { 2857 if (!Tok.is(tok::string_literal) && !DiagId) { 2858 // C++11 [over.literal]p1: 2859 // The string-literal or user-defined-string-literal in a 2860 // literal-operator-id shall have no encoding-prefix [...]. 2861 DiagLoc = Tok.getLocation(); 2862 DiagId = diag::err_literal_operator_string_prefix; 2863 } 2864 Toks.push_back(Tok); 2865 TokLocs.push_back(ConsumeStringToken()); 2866 } 2867 2868 StringLiteralParser Literal(Toks, PP); 2869 if (Literal.hadError) 2870 return true; 2871 2872 // Grab the literal operator's suffix, which will be either the next token 2873 // or a ud-suffix from the string literal. 2874 bool IsUDSuffix = !Literal.getUDSuffix().empty(); 2875 IdentifierInfo *II = nullptr; 2876 SourceLocation SuffixLoc; 2877 if (IsUDSuffix) { 2878 II = &PP.getIdentifierTable().get(Literal.getUDSuffix()); 2879 SuffixLoc = 2880 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()], 2881 Literal.getUDSuffixOffset(), 2882 PP.getSourceManager(), getLangOpts()); 2883 } else if (Tok.is(tok::identifier)) { 2884 II = Tok.getIdentifierInfo(); 2885 SuffixLoc = ConsumeToken(); 2886 TokLocs.push_back(SuffixLoc); 2887 } else { 2888 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; 2889 return true; 2890 } 2891 2892 // The string literal must be empty. 2893 if (!Literal.GetString().empty() || Literal.Pascal) { 2894 // C++11 [over.literal]p1: 2895 // The string-literal or user-defined-string-literal in a 2896 // literal-operator-id shall [...] contain no characters 2897 // other than the implicit terminating '\0'. 2898 DiagLoc = TokLocs.front(); 2899 DiagId = diag::err_literal_operator_string_not_empty; 2900 } 2901 2902 if (DiagId) { 2903 // This isn't a valid literal-operator-id, but we think we know 2904 // what the user meant. Tell them what they should have written. 2905 SmallString<32> Str; 2906 Str += "\"\""; 2907 Str += II->getName(); 2908 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement( 2909 SourceRange(TokLocs.front(), TokLocs.back()), Str); 2910 } 2911 2912 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc); 2913 2914 return Actions.checkLiteralOperatorId(SS, Result, IsUDSuffix); 2915 } 2916 2917 // Parse a conversion-function-id. 2918 // 2919 // conversion-function-id: [C++ 12.3.2] 2920 // operator conversion-type-id 2921 // 2922 // conversion-type-id: 2923 // type-specifier-seq conversion-declarator[opt] 2924 // 2925 // conversion-declarator: 2926 // ptr-operator conversion-declarator[opt] 2927 2928 // Parse the type-specifier-seq. 2929 DeclSpec DS(AttrFactory); 2930 if (ParseCXXTypeSpecifierSeq( 2931 DS, DeclaratorContext::ConversionId)) // FIXME: ObjectType? 2932 return true; 2933 2934 // Parse the conversion-declarator, which is merely a sequence of 2935 // ptr-operators. 2936 Declarator D(DS, ParsedAttributesView::none(), 2937 DeclaratorContext::ConversionId); 2938 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr); 2939 2940 // Finish up the type. 2941 TypeResult Ty = Actions.ActOnTypeName(D); 2942 if (Ty.isInvalid()) 2943 return true; 2944 2945 // Note that this is a conversion-function-id. 2946 Result.setConversionFunctionId(KeywordLoc, Ty.get(), 2947 D.getSourceRange().getEnd()); 2948 return false; 2949 } 2950 2951 /// Parse a C++ unqualified-id (or a C identifier), which describes the 2952 /// name of an entity. 2953 /// 2954 /// \code 2955 /// unqualified-id: [C++ expr.prim.general] 2956 /// identifier 2957 /// operator-function-id 2958 /// conversion-function-id 2959 /// [C++0x] literal-operator-id [TODO] 2960 /// ~ class-name 2961 /// template-id 2962 /// 2963 /// \endcode 2964 /// 2965 /// \param SS The nested-name-specifier that preceded this unqualified-id. If 2966 /// non-empty, then we are parsing the unqualified-id of a qualified-id. 2967 /// 2968 /// \param ObjectType if this unqualified-id occurs within a member access 2969 /// expression, the type of the base object whose member is being accessed. 2970 /// 2971 /// \param ObjectHadErrors if this unqualified-id occurs within a member access 2972 /// expression, indicates whether the original subexpressions had any errors. 2973 /// When true, diagnostics for missing 'template' keyword will be supressed. 2974 /// 2975 /// \param EnteringContext whether we are entering the scope of the 2976 /// nested-name-specifier. 2977 /// 2978 /// \param AllowDestructorName whether we allow parsing of a destructor name. 2979 /// 2980 /// \param AllowConstructorName whether we allow parsing a constructor name. 2981 /// 2982 /// \param AllowDeductionGuide whether we allow parsing a deduction guide name. 2983 /// 2984 /// \param Result on a successful parse, contains the parsed unqualified-id. 2985 /// 2986 /// \returns true if parsing fails, false otherwise. 2987 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, 2988 bool ObjectHadErrors, bool EnteringContext, 2989 bool AllowDestructorName, 2990 bool AllowConstructorName, 2991 bool AllowDeductionGuide, 2992 SourceLocation *TemplateKWLoc, 2993 UnqualifiedId &Result) { 2994 if (TemplateKWLoc) 2995 *TemplateKWLoc = SourceLocation(); 2996 2997 // Handle 'A::template B'. This is for template-ids which have not 2998 // already been annotated by ParseOptionalCXXScopeSpecifier(). 2999 bool TemplateSpecified = false; 3000 if (Tok.is(tok::kw_template)) { 3001 if (TemplateKWLoc && (ObjectType || SS.isSet())) { 3002 TemplateSpecified = true; 3003 *TemplateKWLoc = ConsumeToken(); 3004 } else { 3005 SourceLocation TemplateLoc = ConsumeToken(); 3006 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id) 3007 << FixItHint::CreateRemoval(TemplateLoc); 3008 } 3009 } 3010 3011 // unqualified-id: 3012 // identifier 3013 // template-id (when it hasn't already been annotated) 3014 if (Tok.is(tok::identifier)) { 3015 ParseIdentifier: 3016 // Consume the identifier. 3017 IdentifierInfo *Id = Tok.getIdentifierInfo(); 3018 SourceLocation IdLoc = ConsumeToken(); 3019 3020 if (!getLangOpts().CPlusPlus) { 3021 // If we're not in C++, only identifiers matter. Record the 3022 // identifier and return. 3023 Result.setIdentifier(Id, IdLoc); 3024 return false; 3025 } 3026 3027 ParsedTemplateTy TemplateName; 3028 if (AllowConstructorName && 3029 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) { 3030 // We have parsed a constructor name. 3031 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS, 3032 EnteringContext); 3033 if (!Ty) 3034 return true; 3035 Result.setConstructorName(Ty, IdLoc, IdLoc); 3036 } else if (getLangOpts().CPlusPlus17 && AllowDeductionGuide && 3037 SS.isEmpty() && 3038 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc, SS, 3039 &TemplateName)) { 3040 // We have parsed a template-name naming a deduction guide. 3041 Result.setDeductionGuideName(TemplateName, IdLoc); 3042 } else { 3043 // We have parsed an identifier. 3044 Result.setIdentifier(Id, IdLoc); 3045 } 3046 3047 // If the next token is a '<', we may have a template. 3048 TemplateTy Template; 3049 if (Tok.is(tok::less)) 3050 return ParseUnqualifiedIdTemplateId( 3051 SS, ObjectType, ObjectHadErrors, 3052 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc, 3053 EnteringContext, Result, TemplateSpecified); 3054 3055 if (TemplateSpecified) { 3056 TemplateNameKind TNK = 3057 Actions.ActOnTemplateName(getCurScope(), SS, *TemplateKWLoc, Result, 3058 ObjectType, EnteringContext, Template, 3059 /*AllowInjectedClassName=*/true); 3060 if (TNK == TNK_Non_template) 3061 return true; 3062 3063 // C++2c [tem.names]p6 3064 // A name prefixed by the keyword template shall be followed by a template 3065 // argument list or refer to a class template or an alias template. 3066 if ((TNK == TNK_Function_template || TNK == TNK_Dependent_template_name || 3067 TNK == TNK_Var_template) && 3068 !Tok.is(tok::less)) 3069 Diag(IdLoc, diag::missing_template_arg_list_after_template_kw); 3070 } 3071 return false; 3072 } 3073 3074 // unqualified-id: 3075 // template-id (already parsed and annotated) 3076 if (Tok.is(tok::annot_template_id)) { 3077 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 3078 3079 // FIXME: Consider passing invalid template-ids on to callers; they may 3080 // be able to recover better than we can. 3081 if (TemplateId->isInvalid()) { 3082 ConsumeAnnotationToken(); 3083 return true; 3084 } 3085 3086 // If the template-name names the current class, then this is a constructor 3087 if (AllowConstructorName && TemplateId->Name && 3088 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { 3089 if (SS.isSet()) { 3090 // C++ [class.qual]p2 specifies that a qualified template-name 3091 // is taken as the constructor name where a constructor can be 3092 // declared. Thus, the template arguments are extraneous, so 3093 // complain about them and remove them entirely. 3094 Diag(TemplateId->TemplateNameLoc, 3095 diag::err_out_of_line_constructor_template_id) 3096 << TemplateId->Name 3097 << FixItHint::CreateRemoval( 3098 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)); 3099 ParsedType Ty = Actions.getConstructorName( 3100 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS, 3101 EnteringContext); 3102 if (!Ty) 3103 return true; 3104 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc, 3105 TemplateId->RAngleLoc); 3106 ConsumeAnnotationToken(); 3107 return false; 3108 } 3109 3110 Result.setConstructorTemplateId(TemplateId); 3111 ConsumeAnnotationToken(); 3112 return false; 3113 } 3114 3115 // We have already parsed a template-id; consume the annotation token as 3116 // our unqualified-id. 3117 Result.setTemplateId(TemplateId); 3118 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc; 3119 if (TemplateLoc.isValid()) { 3120 if (TemplateKWLoc && (ObjectType || SS.isSet())) 3121 *TemplateKWLoc = TemplateLoc; 3122 else 3123 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id) 3124 << FixItHint::CreateRemoval(TemplateLoc); 3125 } 3126 ConsumeAnnotationToken(); 3127 return false; 3128 } 3129 3130 // unqualified-id: 3131 // operator-function-id 3132 // conversion-function-id 3133 if (Tok.is(tok::kw_operator)) { 3134 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result)) 3135 return true; 3136 3137 // If we have an operator-function-id or a literal-operator-id and the next 3138 // token is a '<', we may have a 3139 // 3140 // template-id: 3141 // operator-function-id < template-argument-list[opt] > 3142 TemplateTy Template; 3143 if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId || 3144 Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) && 3145 Tok.is(tok::less)) 3146 return ParseUnqualifiedIdTemplateId( 3147 SS, ObjectType, ObjectHadErrors, 3148 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr, 3149 SourceLocation(), EnteringContext, Result, TemplateSpecified); 3150 else if (TemplateSpecified && 3151 Actions.ActOnTemplateName( 3152 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType, 3153 EnteringContext, Template, 3154 /*AllowInjectedClassName*/ true) == TNK_Non_template) 3155 return true; 3156 3157 return false; 3158 } 3159 3160 if (getLangOpts().CPlusPlus && 3161 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) { 3162 // C++ [expr.unary.op]p10: 3163 // There is an ambiguity in the unary-expression ~X(), where X is a 3164 // class-name. The ambiguity is resolved in favor of treating ~ as a 3165 // unary complement rather than treating ~X as referring to a destructor. 3166 3167 // Parse the '~'. 3168 SourceLocation TildeLoc = ConsumeToken(); 3169 3170 if (TemplateSpecified) { 3171 // C++ [temp.names]p3: 3172 // A name prefixed by the keyword template shall be a template-id [...] 3173 // 3174 // A template-id cannot begin with a '~' token. This would never work 3175 // anyway: x.~A<int>() would specify that the destructor is a template, 3176 // not that 'A' is a template. 3177 // 3178 // FIXME: Suggest replacing the attempted destructor name with a correct 3179 // destructor name and recover. (This is not trivial if this would become 3180 // a pseudo-destructor name). 3181 Diag(*TemplateKWLoc, diag::err_unexpected_template_in_destructor_name) 3182 << Tok.getLocation(); 3183 return true; 3184 } 3185 3186 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) { 3187 DeclSpec DS(AttrFactory); 3188 SourceLocation EndLoc = ParseDecltypeSpecifier(DS); 3189 if (ParsedType Type = 3190 Actions.getDestructorTypeForDecltype(DS, ObjectType)) { 3191 Result.setDestructorName(TildeLoc, Type, EndLoc); 3192 return false; 3193 } 3194 return true; 3195 } 3196 3197 // Parse the class-name. 3198 if (Tok.isNot(tok::identifier)) { 3199 Diag(Tok, diag::err_destructor_tilde_identifier); 3200 return true; 3201 } 3202 3203 // If the user wrote ~T::T, correct it to T::~T. 3204 DeclaratorScopeObj DeclScopeObj(*this, SS); 3205 if (NextToken().is(tok::coloncolon)) { 3206 // Don't let ParseOptionalCXXScopeSpecifier() "correct" 3207 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`, 3208 // it will confuse this recovery logic. 3209 ColonProtectionRAIIObject ColonRAII(*this, false); 3210 3211 if (SS.isSet()) { 3212 AnnotateScopeToken(SS, /*NewAnnotation*/true); 3213 SS.clear(); 3214 } 3215 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, ObjectHadErrors, 3216 EnteringContext)) 3217 return true; 3218 if (SS.isNotEmpty()) 3219 ObjectType = nullptr; 3220 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) || 3221 !SS.isSet()) { 3222 Diag(TildeLoc, diag::err_destructor_tilde_scope); 3223 return true; 3224 } 3225 3226 // Recover as if the tilde had been written before the identifier. 3227 Diag(TildeLoc, diag::err_destructor_tilde_scope) 3228 << FixItHint::CreateRemoval(TildeLoc) 3229 << FixItHint::CreateInsertion(Tok.getLocation(), "~"); 3230 3231 // Temporarily enter the scope for the rest of this function. 3232 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS)) 3233 DeclScopeObj.EnterDeclaratorScope(); 3234 } 3235 3236 // Parse the class-name (or template-name in a simple-template-id). 3237 IdentifierInfo *ClassName = Tok.getIdentifierInfo(); 3238 SourceLocation ClassNameLoc = ConsumeToken(); 3239 3240 if (Tok.is(tok::less)) { 3241 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc); 3242 return ParseUnqualifiedIdTemplateId( 3243 SS, ObjectType, ObjectHadErrors, 3244 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName, 3245 ClassNameLoc, EnteringContext, Result, TemplateSpecified); 3246 } 3247 3248 // Note that this is a destructor name. 3249 ParsedType Ty = 3250 Actions.getDestructorName(*ClassName, ClassNameLoc, getCurScope(), SS, 3251 ObjectType, EnteringContext); 3252 if (!Ty) 3253 return true; 3254 3255 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc); 3256 return false; 3257 } 3258 3259 switch (Tok.getKind()) { 3260 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait: 3261 #include "clang/Basic/TransformTypeTraits.def" 3262 if (!NextToken().is(tok::l_paren)) { 3263 Tok.setKind(tok::identifier); 3264 Diag(Tok, diag::ext_keyword_as_ident) 3265 << Tok.getIdentifierInfo()->getName() << 0; 3266 goto ParseIdentifier; 3267 } 3268 [[fallthrough]]; 3269 default: 3270 Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus; 3271 return true; 3272 } 3273 } 3274 3275 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate 3276 /// memory in a typesafe manner and call constructors. 3277 /// 3278 /// This method is called to parse the new expression after the optional :: has 3279 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start" 3280 /// is its location. Otherwise, "Start" is the location of the 'new' token. 3281 /// 3282 /// new-expression: 3283 /// '::'[opt] 'new' new-placement[opt] new-type-id 3284 /// new-initializer[opt] 3285 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')' 3286 /// new-initializer[opt] 3287 /// 3288 /// new-placement: 3289 /// '(' expression-list ')' 3290 /// 3291 /// new-type-id: 3292 /// type-specifier-seq new-declarator[opt] 3293 /// [GNU] attributes type-specifier-seq new-declarator[opt] 3294 /// 3295 /// new-declarator: 3296 /// ptr-operator new-declarator[opt] 3297 /// direct-new-declarator 3298 /// 3299 /// new-initializer: 3300 /// '(' expression-list[opt] ')' 3301 /// [C++0x] braced-init-list 3302 /// 3303 ExprResult 3304 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) { 3305 assert(Tok.is(tok::kw_new) && "expected 'new' token"); 3306 ConsumeToken(); // Consume 'new' 3307 3308 // A '(' now can be a new-placement or the '(' wrapping the type-id in the 3309 // second form of new-expression. It can't be a new-type-id. 3310 3311 ExprVector PlacementArgs; 3312 SourceLocation PlacementLParen, PlacementRParen; 3313 3314 SourceRange TypeIdParens; 3315 DeclSpec DS(AttrFactory); 3316 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), 3317 DeclaratorContext::CXXNew); 3318 if (Tok.is(tok::l_paren)) { 3319 // If it turns out to be a placement, we change the type location. 3320 BalancedDelimiterTracker T(*this, tok::l_paren); 3321 T.consumeOpen(); 3322 PlacementLParen = T.getOpenLocation(); 3323 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) { 3324 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); 3325 return ExprError(); 3326 } 3327 3328 T.consumeClose(); 3329 PlacementRParen = T.getCloseLocation(); 3330 if (PlacementRParen.isInvalid()) { 3331 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); 3332 return ExprError(); 3333 } 3334 3335 if (PlacementArgs.empty()) { 3336 // Reset the placement locations. There was no placement. 3337 TypeIdParens = T.getRange(); 3338 PlacementLParen = PlacementRParen = SourceLocation(); 3339 } else { 3340 // We still need the type. 3341 if (Tok.is(tok::l_paren)) { 3342 BalancedDelimiterTracker T(*this, tok::l_paren); 3343 T.consumeOpen(); 3344 MaybeParseGNUAttributes(DeclaratorInfo); 3345 ParseSpecifierQualifierList(DS); 3346 DeclaratorInfo.SetSourceRange(DS.getSourceRange()); 3347 ParseDeclarator(DeclaratorInfo); 3348 T.consumeClose(); 3349 TypeIdParens = T.getRange(); 3350 } else { 3351 MaybeParseGNUAttributes(DeclaratorInfo); 3352 if (ParseCXXTypeSpecifierSeq(DS)) 3353 DeclaratorInfo.setInvalidType(true); 3354 else { 3355 DeclaratorInfo.SetSourceRange(DS.getSourceRange()); 3356 ParseDeclaratorInternal(DeclaratorInfo, 3357 &Parser::ParseDirectNewDeclarator); 3358 } 3359 } 3360 } 3361 } else { 3362 // A new-type-id is a simplified type-id, where essentially the 3363 // direct-declarator is replaced by a direct-new-declarator. 3364 MaybeParseGNUAttributes(DeclaratorInfo); 3365 if (ParseCXXTypeSpecifierSeq(DS, DeclaratorContext::CXXNew)) 3366 DeclaratorInfo.setInvalidType(true); 3367 else { 3368 DeclaratorInfo.SetSourceRange(DS.getSourceRange()); 3369 ParseDeclaratorInternal(DeclaratorInfo, 3370 &Parser::ParseDirectNewDeclarator); 3371 } 3372 } 3373 if (DeclaratorInfo.isInvalidType()) { 3374 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); 3375 return ExprError(); 3376 } 3377 3378 ExprResult Initializer; 3379 3380 if (Tok.is(tok::l_paren)) { 3381 SourceLocation ConstructorLParen, ConstructorRParen; 3382 ExprVector ConstructorArgs; 3383 BalancedDelimiterTracker T(*this, tok::l_paren); 3384 T.consumeOpen(); 3385 ConstructorLParen = T.getOpenLocation(); 3386 if (Tok.isNot(tok::r_paren)) { 3387 auto RunSignatureHelp = [&]() { 3388 ParsedType TypeRep = Actions.ActOnTypeName(DeclaratorInfo).get(); 3389 QualType PreferredType; 3390 // ActOnTypeName might adjust DeclaratorInfo and return a null type even 3391 // the passing DeclaratorInfo is valid, e.g. running SignatureHelp on 3392 // `new decltype(invalid) (^)`. 3393 if (TypeRep) 3394 PreferredType = 3395 Actions.CodeCompletion().ProduceConstructorSignatureHelp( 3396 TypeRep.get()->getCanonicalTypeInternal(), 3397 DeclaratorInfo.getEndLoc(), ConstructorArgs, 3398 ConstructorLParen, 3399 /*Braced=*/false); 3400 CalledSignatureHelp = true; 3401 return PreferredType; 3402 }; 3403 if (ParseExpressionList(ConstructorArgs, [&] { 3404 PreferredType.enterFunctionArgument(Tok.getLocation(), 3405 RunSignatureHelp); 3406 })) { 3407 if (PP.isCodeCompletionReached() && !CalledSignatureHelp) 3408 RunSignatureHelp(); 3409 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); 3410 return ExprError(); 3411 } 3412 } 3413 T.consumeClose(); 3414 ConstructorRParen = T.getCloseLocation(); 3415 if (ConstructorRParen.isInvalid()) { 3416 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); 3417 return ExprError(); 3418 } 3419 Initializer = Actions.ActOnParenListExpr(ConstructorLParen, 3420 ConstructorRParen, 3421 ConstructorArgs); 3422 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) { 3423 Diag(Tok.getLocation(), 3424 diag::warn_cxx98_compat_generalized_initializer_lists); 3425 Initializer = ParseBraceInitializer(); 3426 } 3427 if (Initializer.isInvalid()) 3428 return Initializer; 3429 3430 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen, 3431 PlacementArgs, PlacementRParen, 3432 TypeIdParens, DeclaratorInfo, Initializer.get()); 3433 } 3434 3435 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be 3436 /// passed to ParseDeclaratorInternal. 3437 /// 3438 /// direct-new-declarator: 3439 /// '[' expression[opt] ']' 3440 /// direct-new-declarator '[' constant-expression ']' 3441 /// 3442 void Parser::ParseDirectNewDeclarator(Declarator &D) { 3443 // Parse the array dimensions. 3444 bool First = true; 3445 while (Tok.is(tok::l_square)) { 3446 // An array-size expression can't start with a lambda. 3447 if (CheckProhibitedCXX11Attribute()) 3448 continue; 3449 3450 BalancedDelimiterTracker T(*this, tok::l_square); 3451 T.consumeOpen(); 3452 3453 ExprResult Size = 3454 First ? (Tok.is(tok::r_square) ? ExprResult() : ParseExpression()) 3455 : ParseConstantExpression(); 3456 if (Size.isInvalid()) { 3457 // Recover 3458 SkipUntil(tok::r_square, StopAtSemi); 3459 return; 3460 } 3461 First = false; 3462 3463 T.consumeClose(); 3464 3465 // Attributes here appertain to the array type. C++11 [expr.new]p5. 3466 ParsedAttributes Attrs(AttrFactory); 3467 MaybeParseCXX11Attributes(Attrs); 3468 3469 D.AddTypeInfo(DeclaratorChunk::getArray(0, 3470 /*isStatic=*/false, /*isStar=*/false, 3471 Size.get(), T.getOpenLocation(), 3472 T.getCloseLocation()), 3473 std::move(Attrs), T.getCloseLocation()); 3474 3475 if (T.getCloseLocation().isInvalid()) 3476 return; 3477 } 3478 } 3479 3480 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id. 3481 /// This ambiguity appears in the syntax of the C++ new operator. 3482 /// 3483 /// new-expression: 3484 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')' 3485 /// new-initializer[opt] 3486 /// 3487 /// new-placement: 3488 /// '(' expression-list ')' 3489 /// 3490 bool Parser::ParseExpressionListOrTypeId( 3491 SmallVectorImpl<Expr*> &PlacementArgs, 3492 Declarator &D) { 3493 // The '(' was already consumed. 3494 if (isTypeIdInParens()) { 3495 ParseSpecifierQualifierList(D.getMutableDeclSpec()); 3496 D.SetSourceRange(D.getDeclSpec().getSourceRange()); 3497 ParseDeclarator(D); 3498 return D.isInvalidType(); 3499 } 3500 3501 // It's not a type, it has to be an expression list. 3502 return ParseExpressionList(PlacementArgs); 3503 } 3504 3505 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used 3506 /// to free memory allocated by new. 3507 /// 3508 /// This method is called to parse the 'delete' expression after the optional 3509 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true 3510 /// and "Start" is its location. Otherwise, "Start" is the location of the 3511 /// 'delete' token. 3512 /// 3513 /// delete-expression: 3514 /// '::'[opt] 'delete' cast-expression 3515 /// '::'[opt] 'delete' '[' ']' cast-expression 3516 ExprResult 3517 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) { 3518 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword"); 3519 ConsumeToken(); // Consume 'delete' 3520 3521 // Array delete? 3522 bool ArrayDelete = false; 3523 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) { 3524 // C++11 [expr.delete]p1: 3525 // Whenever the delete keyword is followed by empty square brackets, it 3526 // shall be interpreted as [array delete]. 3527 // [Footnote: A lambda expression with a lambda-introducer that consists 3528 // of empty square brackets can follow the delete keyword if 3529 // the lambda expression is enclosed in parentheses.] 3530 3531 const Token Next = GetLookAheadToken(2); 3532 3533 // Basic lookahead to check if we have a lambda expression. 3534 if (Next.isOneOf(tok::l_brace, tok::less) || 3535 (Next.is(tok::l_paren) && 3536 (GetLookAheadToken(3).is(tok::r_paren) || 3537 (GetLookAheadToken(3).is(tok::identifier) && 3538 GetLookAheadToken(4).is(tok::identifier))))) { 3539 TentativeParsingAction TPA(*this); 3540 SourceLocation LSquareLoc = Tok.getLocation(); 3541 SourceLocation RSquareLoc = NextToken().getLocation(); 3542 3543 // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this 3544 // case. 3545 SkipUntil({tok::l_brace, tok::less}, StopBeforeMatch); 3546 SourceLocation RBraceLoc; 3547 bool EmitFixIt = false; 3548 if (Tok.is(tok::l_brace)) { 3549 ConsumeBrace(); 3550 SkipUntil(tok::r_brace, StopBeforeMatch); 3551 RBraceLoc = Tok.getLocation(); 3552 EmitFixIt = true; 3553 } 3554 3555 TPA.Revert(); 3556 3557 if (EmitFixIt) 3558 Diag(Start, diag::err_lambda_after_delete) 3559 << SourceRange(Start, RSquareLoc) 3560 << FixItHint::CreateInsertion(LSquareLoc, "(") 3561 << FixItHint::CreateInsertion( 3562 Lexer::getLocForEndOfToken( 3563 RBraceLoc, 0, Actions.getSourceManager(), getLangOpts()), 3564 ")"); 3565 else 3566 Diag(Start, diag::err_lambda_after_delete) 3567 << SourceRange(Start, RSquareLoc); 3568 3569 // Warn that the non-capturing lambda isn't surrounded by parentheses 3570 // to disambiguate it from 'delete[]'. 3571 ExprResult Lambda = ParseLambdaExpression(); 3572 if (Lambda.isInvalid()) 3573 return ExprError(); 3574 3575 // Evaluate any postfix expressions used on the lambda. 3576 Lambda = ParsePostfixExpressionSuffix(Lambda); 3577 if (Lambda.isInvalid()) 3578 return ExprError(); 3579 return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false, 3580 Lambda.get()); 3581 } 3582 3583 ArrayDelete = true; 3584 BalancedDelimiterTracker T(*this, tok::l_square); 3585 3586 T.consumeOpen(); 3587 T.consumeClose(); 3588 if (T.getCloseLocation().isInvalid()) 3589 return ExprError(); 3590 } 3591 3592 ExprResult Operand(ParseCastExpression(AnyCastExpr)); 3593 if (Operand.isInvalid()) 3594 return Operand; 3595 3596 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get()); 3597 } 3598 3599 /// ParseRequiresExpression - Parse a C++2a requires-expression. 3600 /// C++2a [expr.prim.req]p1 3601 /// A requires-expression provides a concise way to express requirements on 3602 /// template arguments. A requirement is one that can be checked by name 3603 /// lookup (6.4) or by checking properties of types and expressions. 3604 /// 3605 /// requires-expression: 3606 /// 'requires' requirement-parameter-list[opt] requirement-body 3607 /// 3608 /// requirement-parameter-list: 3609 /// '(' parameter-declaration-clause[opt] ')' 3610 /// 3611 /// requirement-body: 3612 /// '{' requirement-seq '}' 3613 /// 3614 /// requirement-seq: 3615 /// requirement 3616 /// requirement-seq requirement 3617 /// 3618 /// requirement: 3619 /// simple-requirement 3620 /// type-requirement 3621 /// compound-requirement 3622 /// nested-requirement 3623 ExprResult Parser::ParseRequiresExpression() { 3624 assert(Tok.is(tok::kw_requires) && "Expected 'requires' keyword"); 3625 SourceLocation RequiresKWLoc = ConsumeToken(); // Consume 'requires' 3626 3627 llvm::SmallVector<ParmVarDecl *, 2> LocalParameterDecls; 3628 BalancedDelimiterTracker Parens(*this, tok::l_paren); 3629 if (Tok.is(tok::l_paren)) { 3630 // requirement parameter list is present. 3631 ParseScope LocalParametersScope(this, Scope::FunctionPrototypeScope | 3632 Scope::DeclScope); 3633 Parens.consumeOpen(); 3634 if (!Tok.is(tok::r_paren)) { 3635 ParsedAttributes FirstArgAttrs(getAttrFactory()); 3636 SourceLocation EllipsisLoc; 3637 llvm::SmallVector<DeclaratorChunk::ParamInfo, 2> LocalParameters; 3638 ParseParameterDeclarationClause(DeclaratorContext::RequiresExpr, 3639 FirstArgAttrs, LocalParameters, 3640 EllipsisLoc); 3641 if (EllipsisLoc.isValid()) 3642 Diag(EllipsisLoc, diag::err_requires_expr_parameter_list_ellipsis); 3643 for (auto &ParamInfo : LocalParameters) 3644 LocalParameterDecls.push_back(cast<ParmVarDecl>(ParamInfo.Param)); 3645 } 3646 Parens.consumeClose(); 3647 } 3648 3649 BalancedDelimiterTracker Braces(*this, tok::l_brace); 3650 if (Braces.expectAndConsume()) 3651 return ExprError(); 3652 3653 // Start of requirement list 3654 llvm::SmallVector<concepts::Requirement *, 2> Requirements; 3655 3656 // C++2a [expr.prim.req]p2 3657 // Expressions appearing within a requirement-body are unevaluated operands. 3658 EnterExpressionEvaluationContext Ctx( 3659 Actions, Sema::ExpressionEvaluationContext::Unevaluated); 3660 3661 ParseScope BodyScope(this, Scope::DeclScope); 3662 // Create a separate diagnostic pool for RequiresExprBodyDecl. 3663 // Dependent diagnostics are attached to this Decl and non-depenedent 3664 // diagnostics are surfaced after this parse. 3665 ParsingDeclRAIIObject ParsingBodyDecl(*this, ParsingDeclRAIIObject::NoParent); 3666 RequiresExprBodyDecl *Body = Actions.ActOnStartRequiresExpr( 3667 RequiresKWLoc, LocalParameterDecls, getCurScope()); 3668 3669 if (Tok.is(tok::r_brace)) { 3670 // Grammar does not allow an empty body. 3671 // requirement-body: 3672 // { requirement-seq } 3673 // requirement-seq: 3674 // requirement 3675 // requirement-seq requirement 3676 Diag(Tok, diag::err_empty_requires_expr); 3677 // Continue anyway and produce a requires expr with no requirements. 3678 } else { 3679 while (!Tok.is(tok::r_brace)) { 3680 switch (Tok.getKind()) { 3681 case tok::l_brace: { 3682 // Compound requirement 3683 // C++ [expr.prim.req.compound] 3684 // compound-requirement: 3685 // '{' expression '}' 'noexcept'[opt] 3686 // return-type-requirement[opt] ';' 3687 // return-type-requirement: 3688 // trailing-return-type 3689 // '->' cv-qualifier-seq[opt] constrained-parameter 3690 // cv-qualifier-seq[opt] abstract-declarator[opt] 3691 BalancedDelimiterTracker ExprBraces(*this, tok::l_brace); 3692 ExprBraces.consumeOpen(); 3693 ExprResult Expression = 3694 Actions.CorrectDelayedTyposInExpr(ParseExpression()); 3695 if (!Expression.isUsable()) { 3696 ExprBraces.skipToEnd(); 3697 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch); 3698 break; 3699 } 3700 if (ExprBraces.consumeClose()) 3701 ExprBraces.skipToEnd(); 3702 3703 concepts::Requirement *Req = nullptr; 3704 SourceLocation NoexceptLoc; 3705 TryConsumeToken(tok::kw_noexcept, NoexceptLoc); 3706 if (Tok.is(tok::semi)) { 3707 Req = Actions.ActOnCompoundRequirement(Expression.get(), NoexceptLoc); 3708 if (Req) 3709 Requirements.push_back(Req); 3710 break; 3711 } 3712 if (!TryConsumeToken(tok::arrow)) 3713 // User probably forgot the arrow, remind them and try to continue. 3714 Diag(Tok, diag::err_requires_expr_missing_arrow) 3715 << FixItHint::CreateInsertion(Tok.getLocation(), "->"); 3716 // Try to parse a 'type-constraint' 3717 if (TryAnnotateTypeConstraint()) { 3718 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch); 3719 break; 3720 } 3721 if (!isTypeConstraintAnnotation()) { 3722 Diag(Tok, diag::err_requires_expr_expected_type_constraint); 3723 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch); 3724 break; 3725 } 3726 CXXScopeSpec SS; 3727 if (Tok.is(tok::annot_cxxscope)) { 3728 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), 3729 Tok.getAnnotationRange(), 3730 SS); 3731 ConsumeAnnotationToken(); 3732 } 3733 3734 Req = Actions.ActOnCompoundRequirement( 3735 Expression.get(), NoexceptLoc, SS, takeTemplateIdAnnotation(Tok), 3736 TemplateParameterDepth); 3737 ConsumeAnnotationToken(); 3738 if (Req) 3739 Requirements.push_back(Req); 3740 break; 3741 } 3742 default: { 3743 bool PossibleRequiresExprInSimpleRequirement = false; 3744 if (Tok.is(tok::kw_requires)) { 3745 auto IsNestedRequirement = [&] { 3746 RevertingTentativeParsingAction TPA(*this); 3747 ConsumeToken(); // 'requires' 3748 if (Tok.is(tok::l_brace)) 3749 // This is a requires expression 3750 // requires (T t) { 3751 // requires { t++; }; 3752 // ... ^ 3753 // } 3754 return false; 3755 if (Tok.is(tok::l_paren)) { 3756 // This might be the parameter list of a requires expression 3757 ConsumeParen(); 3758 auto Res = TryParseParameterDeclarationClause(); 3759 if (Res != TPResult::False) { 3760 // Skip to the closing parenthesis 3761 unsigned Depth = 1; 3762 while (Depth != 0) { 3763 bool FoundParen = SkipUntil(tok::l_paren, tok::r_paren, 3764 SkipUntilFlags::StopBeforeMatch); 3765 if (!FoundParen) 3766 break; 3767 if (Tok.is(tok::l_paren)) 3768 Depth++; 3769 else if (Tok.is(tok::r_paren)) 3770 Depth--; 3771 ConsumeAnyToken(); 3772 } 3773 // requires (T t) { 3774 // requires () ? 3775 // ... ^ 3776 // - OR - 3777 // requires (int x) ? 3778 // ... ^ 3779 // } 3780 if (Tok.is(tok::l_brace)) 3781 // requires (...) { 3782 // ^ - a requires expression as a 3783 // simple-requirement. 3784 return false; 3785 } 3786 } 3787 return true; 3788 }; 3789 if (IsNestedRequirement()) { 3790 ConsumeToken(); 3791 // Nested requirement 3792 // C++ [expr.prim.req.nested] 3793 // nested-requirement: 3794 // 'requires' constraint-expression ';' 3795 ExprResult ConstraintExpr = 3796 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression()); 3797 if (ConstraintExpr.isInvalid() || !ConstraintExpr.isUsable()) { 3798 SkipUntil(tok::semi, tok::r_brace, 3799 SkipUntilFlags::StopBeforeMatch); 3800 break; 3801 } 3802 if (auto *Req = 3803 Actions.ActOnNestedRequirement(ConstraintExpr.get())) 3804 Requirements.push_back(Req); 3805 else { 3806 SkipUntil(tok::semi, tok::r_brace, 3807 SkipUntilFlags::StopBeforeMatch); 3808 break; 3809 } 3810 break; 3811 } else 3812 PossibleRequiresExprInSimpleRequirement = true; 3813 } else if (Tok.is(tok::kw_typename)) { 3814 // This might be 'typename T::value_type;' (a type requirement) or 3815 // 'typename T::value_type{};' (a simple requirement). 3816 TentativeParsingAction TPA(*this); 3817 3818 // We need to consume the typename to allow 'requires { typename a; }' 3819 SourceLocation TypenameKWLoc = ConsumeToken(); 3820 if (TryAnnotateOptionalCXXScopeToken()) { 3821 TPA.Commit(); 3822 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch); 3823 break; 3824 } 3825 CXXScopeSpec SS; 3826 if (Tok.is(tok::annot_cxxscope)) { 3827 Actions.RestoreNestedNameSpecifierAnnotation( 3828 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS); 3829 ConsumeAnnotationToken(); 3830 } 3831 3832 if (Tok.isOneOf(tok::identifier, tok::annot_template_id) && 3833 !NextToken().isOneOf(tok::l_brace, tok::l_paren)) { 3834 TPA.Commit(); 3835 SourceLocation NameLoc = Tok.getLocation(); 3836 IdentifierInfo *II = nullptr; 3837 TemplateIdAnnotation *TemplateId = nullptr; 3838 if (Tok.is(tok::identifier)) { 3839 II = Tok.getIdentifierInfo(); 3840 ConsumeToken(); 3841 } else { 3842 TemplateId = takeTemplateIdAnnotation(Tok); 3843 ConsumeAnnotationToken(); 3844 if (TemplateId->isInvalid()) 3845 break; 3846 } 3847 3848 if (auto *Req = Actions.ActOnTypeRequirement(TypenameKWLoc, SS, 3849 NameLoc, II, 3850 TemplateId)) { 3851 Requirements.push_back(Req); 3852 } 3853 break; 3854 } 3855 TPA.Revert(); 3856 } 3857 // Simple requirement 3858 // C++ [expr.prim.req.simple] 3859 // simple-requirement: 3860 // expression ';' 3861 SourceLocation StartLoc = Tok.getLocation(); 3862 ExprResult Expression = 3863 Actions.CorrectDelayedTyposInExpr(ParseExpression()); 3864 if (!Expression.isUsable()) { 3865 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch); 3866 break; 3867 } 3868 if (!Expression.isInvalid() && PossibleRequiresExprInSimpleRequirement) 3869 Diag(StartLoc, diag::err_requires_expr_in_simple_requirement) 3870 << FixItHint::CreateInsertion(StartLoc, "requires"); 3871 if (auto *Req = Actions.ActOnSimpleRequirement(Expression.get())) 3872 Requirements.push_back(Req); 3873 else { 3874 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch); 3875 break; 3876 } 3877 // User may have tried to put some compound requirement stuff here 3878 if (Tok.is(tok::kw_noexcept)) { 3879 Diag(Tok, diag::err_requires_expr_simple_requirement_noexcept) 3880 << FixItHint::CreateInsertion(StartLoc, "{") 3881 << FixItHint::CreateInsertion(Tok.getLocation(), "}"); 3882 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch); 3883 break; 3884 } 3885 break; 3886 } 3887 } 3888 if (ExpectAndConsumeSemi(diag::err_expected_semi_requirement)) { 3889 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch); 3890 TryConsumeToken(tok::semi); 3891 break; 3892 } 3893 } 3894 if (Requirements.empty()) { 3895 // Don't emit an empty requires expr here to avoid confusing the user with 3896 // other diagnostics quoting an empty requires expression they never 3897 // wrote. 3898 Braces.consumeClose(); 3899 Actions.ActOnFinishRequiresExpr(); 3900 return ExprError(); 3901 } 3902 } 3903 Braces.consumeClose(); 3904 Actions.ActOnFinishRequiresExpr(); 3905 ParsingBodyDecl.complete(Body); 3906 return Actions.ActOnRequiresExpr( 3907 RequiresKWLoc, Body, Parens.getOpenLocation(), LocalParameterDecls, 3908 Parens.getCloseLocation(), Requirements, Braces.getCloseLocation()); 3909 } 3910 3911 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) { 3912 switch (kind) { 3913 default: llvm_unreachable("Not a known type trait"); 3914 #define TYPE_TRAIT_1(Spelling, Name, Key) \ 3915 case tok::kw_ ## Spelling: return UTT_ ## Name; 3916 #define TYPE_TRAIT_2(Spelling, Name, Key) \ 3917 case tok::kw_ ## Spelling: return BTT_ ## Name; 3918 #include "clang/Basic/TokenKinds.def" 3919 #define TYPE_TRAIT_N(Spelling, Name, Key) \ 3920 case tok::kw_ ## Spelling: return TT_ ## Name; 3921 #include "clang/Basic/TokenKinds.def" 3922 } 3923 } 3924 3925 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) { 3926 switch (kind) { 3927 default: 3928 llvm_unreachable("Not a known array type trait"); 3929 #define ARRAY_TYPE_TRAIT(Spelling, Name, Key) \ 3930 case tok::kw_##Spelling: \ 3931 return ATT_##Name; 3932 #include "clang/Basic/TokenKinds.def" 3933 } 3934 } 3935 3936 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) { 3937 switch (kind) { 3938 default: 3939 llvm_unreachable("Not a known unary expression trait."); 3940 #define EXPRESSION_TRAIT(Spelling, Name, Key) \ 3941 case tok::kw_##Spelling: \ 3942 return ET_##Name; 3943 #include "clang/Basic/TokenKinds.def" 3944 } 3945 } 3946 3947 /// Parse the built-in type-trait pseudo-functions that allow 3948 /// implementation of the TR1/C++11 type traits templates. 3949 /// 3950 /// primary-expression: 3951 /// unary-type-trait '(' type-id ')' 3952 /// binary-type-trait '(' type-id ',' type-id ')' 3953 /// type-trait '(' type-id-seq ')' 3954 /// 3955 /// type-id-seq: 3956 /// type-id ...[opt] type-id-seq[opt] 3957 /// 3958 ExprResult Parser::ParseTypeTrait() { 3959 tok::TokenKind Kind = Tok.getKind(); 3960 3961 SourceLocation Loc = ConsumeToken(); 3962 3963 BalancedDelimiterTracker Parens(*this, tok::l_paren); 3964 if (Parens.expectAndConsume()) 3965 return ExprError(); 3966 3967 SmallVector<ParsedType, 2> Args; 3968 do { 3969 // Parse the next type. 3970 TypeResult Ty = ParseTypeName(/*SourceRange=*/nullptr, 3971 getLangOpts().CPlusPlus 3972 ? DeclaratorContext::TemplateTypeArg 3973 : DeclaratorContext::TypeName); 3974 if (Ty.isInvalid()) { 3975 Parens.skipToEnd(); 3976 return ExprError(); 3977 } 3978 3979 // Parse the ellipsis, if present. 3980 if (Tok.is(tok::ellipsis)) { 3981 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken()); 3982 if (Ty.isInvalid()) { 3983 Parens.skipToEnd(); 3984 return ExprError(); 3985 } 3986 } 3987 3988 // Add this type to the list of arguments. 3989 Args.push_back(Ty.get()); 3990 } while (TryConsumeToken(tok::comma)); 3991 3992 if (Parens.consumeClose()) 3993 return ExprError(); 3994 3995 SourceLocation EndLoc = Parens.getCloseLocation(); 3996 3997 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc); 3998 } 3999 4000 /// ParseArrayTypeTrait - Parse the built-in array type-trait 4001 /// pseudo-functions. 4002 /// 4003 /// primary-expression: 4004 /// [Embarcadero] '__array_rank' '(' type-id ')' 4005 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')' 4006 /// 4007 ExprResult Parser::ParseArrayTypeTrait() { 4008 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind()); 4009 SourceLocation Loc = ConsumeToken(); 4010 4011 BalancedDelimiterTracker T(*this, tok::l_paren); 4012 if (T.expectAndConsume()) 4013 return ExprError(); 4014 4015 TypeResult Ty = ParseTypeName(/*SourceRange=*/nullptr, 4016 DeclaratorContext::TemplateTypeArg); 4017 if (Ty.isInvalid()) { 4018 SkipUntil(tok::comma, StopAtSemi); 4019 SkipUntil(tok::r_paren, StopAtSemi); 4020 return ExprError(); 4021 } 4022 4023 switch (ATT) { 4024 case ATT_ArrayRank: { 4025 T.consumeClose(); 4026 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr, 4027 T.getCloseLocation()); 4028 } 4029 case ATT_ArrayExtent: { 4030 if (ExpectAndConsume(tok::comma)) { 4031 SkipUntil(tok::r_paren, StopAtSemi); 4032 return ExprError(); 4033 } 4034 4035 ExprResult DimExpr = ParseExpression(); 4036 T.consumeClose(); 4037 4038 if (DimExpr.isInvalid()) 4039 return ExprError(); 4040 4041 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(), 4042 T.getCloseLocation()); 4043 } 4044 } 4045 llvm_unreachable("Invalid ArrayTypeTrait!"); 4046 } 4047 4048 /// ParseExpressionTrait - Parse built-in expression-trait 4049 /// pseudo-functions like __is_lvalue_expr( xxx ). 4050 /// 4051 /// primary-expression: 4052 /// [Embarcadero] expression-trait '(' expression ')' 4053 /// 4054 ExprResult Parser::ParseExpressionTrait() { 4055 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind()); 4056 SourceLocation Loc = ConsumeToken(); 4057 4058 BalancedDelimiterTracker T(*this, tok::l_paren); 4059 if (T.expectAndConsume()) 4060 return ExprError(); 4061 4062 ExprResult Expr = ParseExpression(); 4063 4064 T.consumeClose(); 4065 4066 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(), 4067 T.getCloseLocation()); 4068 } 4069 4070 4071 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a 4072 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate 4073 /// based on the context past the parens. 4074 ExprResult 4075 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, 4076 ParsedType &CastTy, 4077 BalancedDelimiterTracker &Tracker, 4078 ColonProtectionRAIIObject &ColonProt) { 4079 assert(getLangOpts().CPlusPlus && "Should only be called for C++!"); 4080 assert(ExprType == CastExpr && "Compound literals are not ambiguous!"); 4081 assert(isTypeIdInParens() && "Not a type-id!"); 4082 4083 ExprResult Result(true); 4084 CastTy = nullptr; 4085 4086 // We need to disambiguate a very ugly part of the C++ syntax: 4087 // 4088 // (T())x; - type-id 4089 // (T())*x; - type-id 4090 // (T())/x; - expression 4091 // (T()); - expression 4092 // 4093 // The bad news is that we cannot use the specialized tentative parser, since 4094 // it can only verify that the thing inside the parens can be parsed as 4095 // type-id, it is not useful for determining the context past the parens. 4096 // 4097 // The good news is that the parser can disambiguate this part without 4098 // making any unnecessary Action calls. 4099 // 4100 // It uses a scheme similar to parsing inline methods. The parenthesized 4101 // tokens are cached, the context that follows is determined (possibly by 4102 // parsing a cast-expression), and then we re-introduce the cached tokens 4103 // into the token stream and parse them appropriately. 4104 4105 ParenParseOption ParseAs; 4106 CachedTokens Toks; 4107 4108 // Store the tokens of the parentheses. We will parse them after we determine 4109 // the context that follows them. 4110 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) { 4111 // We didn't find the ')' we expected. 4112 Tracker.consumeClose(); 4113 return ExprError(); 4114 } 4115 4116 if (Tok.is(tok::l_brace)) { 4117 ParseAs = CompoundLiteral; 4118 } else { 4119 bool NotCastExpr; 4120 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) { 4121 NotCastExpr = true; 4122 } else { 4123 // Try parsing the cast-expression that may follow. 4124 // If it is not a cast-expression, NotCastExpr will be true and no token 4125 // will be consumed. 4126 ColonProt.restore(); 4127 Result = ParseCastExpression(AnyCastExpr, 4128 false/*isAddressofOperand*/, 4129 NotCastExpr, 4130 // type-id has priority. 4131 IsTypeCast); 4132 } 4133 4134 // If we parsed a cast-expression, it's really a type-id, otherwise it's 4135 // an expression. 4136 ParseAs = NotCastExpr ? SimpleExpr : CastExpr; 4137 } 4138 4139 // Create a fake EOF to mark end of Toks buffer. 4140 Token AttrEnd; 4141 AttrEnd.startToken(); 4142 AttrEnd.setKind(tok::eof); 4143 AttrEnd.setLocation(Tok.getLocation()); 4144 AttrEnd.setEofData(Toks.data()); 4145 Toks.push_back(AttrEnd); 4146 4147 // The current token should go after the cached tokens. 4148 Toks.push_back(Tok); 4149 // Re-enter the stored parenthesized tokens into the token stream, so we may 4150 // parse them now. 4151 PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true, 4152 /*IsReinject*/ true); 4153 // Drop the current token and bring the first cached one. It's the same token 4154 // as when we entered this function. 4155 ConsumeAnyToken(); 4156 4157 if (ParseAs >= CompoundLiteral) { 4158 // Parse the type declarator. 4159 DeclSpec DS(AttrFactory); 4160 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), 4161 DeclaratorContext::TypeName); 4162 { 4163 ColonProtectionRAIIObject InnerColonProtection(*this); 4164 ParseSpecifierQualifierList(DS); 4165 ParseDeclarator(DeclaratorInfo); 4166 } 4167 4168 // Match the ')'. 4169 Tracker.consumeClose(); 4170 ColonProt.restore(); 4171 4172 // Consume EOF marker for Toks buffer. 4173 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData()); 4174 ConsumeAnyToken(); 4175 4176 if (ParseAs == CompoundLiteral) { 4177 ExprType = CompoundLiteral; 4178 if (DeclaratorInfo.isInvalidType()) 4179 return ExprError(); 4180 4181 TypeResult Ty = Actions.ActOnTypeName(DeclaratorInfo); 4182 return ParseCompoundLiteralExpression(Ty.get(), 4183 Tracker.getOpenLocation(), 4184 Tracker.getCloseLocation()); 4185 } 4186 4187 // We parsed '(' type-id ')' and the thing after it wasn't a '{'. 4188 assert(ParseAs == CastExpr); 4189 4190 if (DeclaratorInfo.isInvalidType()) 4191 return ExprError(); 4192 4193 // Result is what ParseCastExpression returned earlier. 4194 if (!Result.isInvalid()) 4195 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(), 4196 DeclaratorInfo, CastTy, 4197 Tracker.getCloseLocation(), Result.get()); 4198 return Result; 4199 } 4200 4201 // Not a compound literal, and not followed by a cast-expression. 4202 assert(ParseAs == SimpleExpr); 4203 4204 ExprType = SimpleExpr; 4205 Result = ParseExpression(); 4206 if (!Result.isInvalid() && Tok.is(tok::r_paren)) 4207 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(), 4208 Tok.getLocation(), Result.get()); 4209 4210 // Match the ')'. 4211 if (Result.isInvalid()) { 4212 while (Tok.isNot(tok::eof)) 4213 ConsumeAnyToken(); 4214 assert(Tok.getEofData() == AttrEnd.getEofData()); 4215 ConsumeAnyToken(); 4216 return ExprError(); 4217 } 4218 4219 Tracker.consumeClose(); 4220 // Consume EOF marker for Toks buffer. 4221 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData()); 4222 ConsumeAnyToken(); 4223 return Result; 4224 } 4225 4226 /// Parse a __builtin_bit_cast(T, E). 4227 ExprResult Parser::ParseBuiltinBitCast() { 4228 SourceLocation KWLoc = ConsumeToken(); 4229 4230 BalancedDelimiterTracker T(*this, tok::l_paren); 4231 if (T.expectAndConsume(diag::err_expected_lparen_after, "__builtin_bit_cast")) 4232 return ExprError(); 4233 4234 // Parse the common declaration-specifiers piece. 4235 DeclSpec DS(AttrFactory); 4236 ParseSpecifierQualifierList(DS); 4237 4238 // Parse the abstract-declarator, if present. 4239 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), 4240 DeclaratorContext::TypeName); 4241 ParseDeclarator(DeclaratorInfo); 4242 4243 if (ExpectAndConsume(tok::comma)) { 4244 Diag(Tok.getLocation(), diag::err_expected) << tok::comma; 4245 SkipUntil(tok::r_paren, StopAtSemi); 4246 return ExprError(); 4247 } 4248 4249 ExprResult Operand = ParseExpression(); 4250 4251 if (T.consumeClose()) 4252 return ExprError(); 4253 4254 if (Operand.isInvalid() || DeclaratorInfo.isInvalidType()) 4255 return ExprError(); 4256 4257 return Actions.ActOnBuiltinBitCastExpr(KWLoc, DeclaratorInfo, Operand, 4258 T.getCloseLocation()); 4259 } 4260