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