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