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