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