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