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