ParseExprCXX.cpp revision 483b9f3bc05c5409e2c6643f1c9d91e21c8ff9d2
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 14#include "clang/Parse/ParseDiagnostic.h" 15#include "clang/Parse/Parser.h" 16#include "RAIIObjectsForParser.h" 17#include "clang/Sema/DeclSpec.h" 18#include "clang/Sema/ParsedTemplate.h" 19#include "llvm/Support/ErrorHandling.h" 20 21using namespace clang; 22 23/// \brief Parse global scope or nested-name-specifier if present. 24/// 25/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which 26/// may be preceded by '::'). Note that this routine will not parse ::new or 27/// ::delete; it will just leave them in the token stream. 28/// 29/// '::'[opt] nested-name-specifier 30/// '::' 31/// 32/// nested-name-specifier: 33/// type-name '::' 34/// namespace-name '::' 35/// nested-name-specifier identifier '::' 36/// nested-name-specifier 'template'[opt] simple-template-id '::' 37/// 38/// 39/// \param SS the scope specifier that will be set to the parsed 40/// nested-name-specifier (or empty) 41/// 42/// \param ObjectType if this nested-name-specifier is being parsed following 43/// the "." or "->" of a member access expression, this parameter provides the 44/// type of the object whose members are being accessed. 45/// 46/// \param EnteringContext whether we will be entering into the context of 47/// the nested-name-specifier after parsing it. 48/// 49/// \param MayBePseudoDestructor When non-NULL, points to a flag that 50/// indicates whether this nested-name-specifier may be part of a 51/// pseudo-destructor name. In this case, the flag will be set false 52/// if we don't actually end up parsing a destructor name. Moreorover, 53/// if we do end up determining that we are parsing a destructor name, 54/// the last component of the nested-name-specifier is not parsed as 55/// part of the scope specifier. 56 57/// member access expression, e.g., the \p T:: in \p p->T::m. 58/// 59/// \returns true if there was an error parsing a scope specifier 60bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, 61 ParsedType ObjectType, 62 bool EnteringContext, 63 bool *MayBePseudoDestructor) { 64 assert(getLang().CPlusPlus && 65 "Call sites of this function should be guarded by checking for C++"); 66 67 if (Tok.is(tok::annot_cxxscope)) { 68 SS.setScopeRep(static_cast<NestedNameSpecifier*>(Tok.getAnnotationValue())); 69 SS.setRange(Tok.getAnnotationRange()); 70 ConsumeToken(); 71 return false; 72 } 73 74 bool HasScopeSpecifier = false; 75 76 if (Tok.is(tok::coloncolon)) { 77 // ::new and ::delete aren't nested-name-specifiers. 78 tok::TokenKind NextKind = NextToken().getKind(); 79 if (NextKind == tok::kw_new || NextKind == tok::kw_delete) 80 return false; 81 82 // '::' - Global scope qualifier. 83 SourceLocation CCLoc = ConsumeToken(); 84 SS.setBeginLoc(CCLoc); 85 SS.setScopeRep(Actions.ActOnCXXGlobalScopeSpecifier(getCurScope(), CCLoc)); 86 SS.setEndLoc(CCLoc); 87 HasScopeSpecifier = true; 88 } 89 90 bool CheckForDestructor = false; 91 if (MayBePseudoDestructor && *MayBePseudoDestructor) { 92 CheckForDestructor = true; 93 *MayBePseudoDestructor = false; 94 } 95 96 while (true) { 97 if (HasScopeSpecifier) { 98 // C++ [basic.lookup.classref]p5: 99 // If the qualified-id has the form 100 // 101 // ::class-name-or-namespace-name::... 102 // 103 // the class-name-or-namespace-name is looked up in global scope as a 104 // class-name or namespace-name. 105 // 106 // To implement this, we clear out the object type as soon as we've 107 // seen a leading '::' or part of a nested-name-specifier. 108 ObjectType = ParsedType(); 109 110 if (Tok.is(tok::code_completion)) { 111 // Code completion for a nested-name-specifier, where the code 112 // code completion token follows the '::'. 113 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext); 114 ConsumeCodeCompletionToken(); 115 } 116 } 117 118 // nested-name-specifier: 119 // nested-name-specifier 'template'[opt] simple-template-id '::' 120 121 // Parse the optional 'template' keyword, then make sure we have 122 // 'identifier <' after it. 123 if (Tok.is(tok::kw_template)) { 124 // If we don't have a scope specifier or an object type, this isn't a 125 // nested-name-specifier, since they aren't allowed to start with 126 // 'template'. 127 if (!HasScopeSpecifier && !ObjectType) 128 break; 129 130 TentativeParsingAction TPA(*this); 131 SourceLocation TemplateKWLoc = ConsumeToken(); 132 133 UnqualifiedId TemplateName; 134 if (Tok.is(tok::identifier)) { 135 // Consume the identifier. 136 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 137 ConsumeToken(); 138 } else if (Tok.is(tok::kw_operator)) { 139 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, 140 TemplateName)) { 141 TPA.Commit(); 142 break; 143 } 144 145 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId && 146 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) { 147 Diag(TemplateName.getSourceRange().getBegin(), 148 diag::err_id_after_template_in_nested_name_spec) 149 << TemplateName.getSourceRange(); 150 TPA.Commit(); 151 break; 152 } 153 } else { 154 TPA.Revert(); 155 break; 156 } 157 158 // If the next token is not '<', we have a qualified-id that refers 159 // to a template name, such as T::template apply, but is not a 160 // template-id. 161 if (Tok.isNot(tok::less)) { 162 TPA.Revert(); 163 break; 164 } 165 166 // Commit to parsing the template-id. 167 TPA.Commit(); 168 TemplateTy Template; 169 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(getCurScope(), 170 TemplateKWLoc, 171 SS, 172 TemplateName, 173 ObjectType, 174 EnteringContext, 175 Template)) { 176 if (AnnotateTemplateIdToken(Template, TNK, &SS, TemplateName, 177 TemplateKWLoc, false)) 178 return true; 179 } else 180 return true; 181 182 continue; 183 } 184 185 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) { 186 // We have 187 // 188 // simple-template-id '::' 189 // 190 // So we need to check whether the simple-template-id is of the 191 // right kind (it should name a type or be dependent), and then 192 // convert it into a type within the nested-name-specifier. 193 TemplateIdAnnotation *TemplateId 194 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 195 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) { 196 *MayBePseudoDestructor = true; 197 return false; 198 } 199 200 if (TemplateId->Kind == TNK_Type_template || 201 TemplateId->Kind == TNK_Dependent_template_name) { 202 AnnotateTemplateIdTokenAsType(&SS); 203 204 assert(Tok.is(tok::annot_typename) && 205 "AnnotateTemplateIdTokenAsType isn't working"); 206 Token TypeToken = Tok; 207 ConsumeToken(); 208 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!"); 209 SourceLocation CCLoc = ConsumeToken(); 210 211 if (!HasScopeSpecifier) { 212 SS.setBeginLoc(TypeToken.getLocation()); 213 HasScopeSpecifier = true; 214 } 215 216 if (ParsedType T = getTypeAnnotation(TypeToken)) { 217 CXXScopeTy *Scope = 218 Actions.ActOnCXXNestedNameSpecifier(getCurScope(), SS, T, 219 TypeToken.getAnnotationRange(), 220 CCLoc); 221 SS.setScopeRep(Scope); 222 } else 223 SS.setScopeRep(0); 224 SS.setEndLoc(CCLoc); 225 continue; 226 } 227 228 assert(false && "FIXME: Only type template names supported here"); 229 } 230 231 232 // The rest of the nested-name-specifier possibilities start with 233 // tok::identifier. 234 if (Tok.isNot(tok::identifier)) 235 break; 236 237 IdentifierInfo &II = *Tok.getIdentifierInfo(); 238 239 // nested-name-specifier: 240 // type-name '::' 241 // namespace-name '::' 242 // nested-name-specifier identifier '::' 243 Token Next = NextToken(); 244 245 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover 246 // and emit a fixit hint for it. 247 if (Next.is(tok::colon) && !ColonIsSacred) { 248 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II, ObjectType, 249 EnteringContext) && 250 // If the token after the colon isn't an identifier, it's still an 251 // error, but they probably meant something else strange so don't 252 // recover like this. 253 PP.LookAhead(1).is(tok::identifier)) { 254 Diag(Next, diag::err_unexected_colon_in_nested_name_spec) 255 << FixItHint::CreateReplacement(Next.getLocation(), "::"); 256 257 // Recover as if the user wrote '::'. 258 Next.setKind(tok::coloncolon); 259 } 260 } 261 262 if (Next.is(tok::coloncolon)) { 263 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) && 264 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(), 265 II, ObjectType)) { 266 *MayBePseudoDestructor = true; 267 return false; 268 } 269 270 // We have an identifier followed by a '::'. Lookup this name 271 // as the name in a nested-name-specifier. 272 SourceLocation IdLoc = ConsumeToken(); 273 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) && 274 "NextToken() not working properly!"); 275 SourceLocation CCLoc = ConsumeToken(); 276 277 if (!HasScopeSpecifier) { 278 SS.setBeginLoc(IdLoc); 279 HasScopeSpecifier = true; 280 } 281 282 if (!SS.isInvalid()) 283 SS.setScopeRep( 284 Actions.ActOnCXXNestedNameSpecifier(getCurScope(), SS, IdLoc, CCLoc, II, 285 ObjectType, EnteringContext)); 286 SS.setEndLoc(CCLoc); 287 continue; 288 } 289 290 // nested-name-specifier: 291 // type-name '<' 292 if (Next.is(tok::less)) { 293 TemplateTy Template; 294 UnqualifiedId TemplateName; 295 TemplateName.setIdentifier(&II, Tok.getLocation()); 296 bool MemberOfUnknownSpecialization; 297 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS, 298 /*hasTemplateKeyword=*/false, 299 TemplateName, 300 ObjectType, 301 EnteringContext, 302 Template, 303 MemberOfUnknownSpecialization)) { 304 // We have found a template name, so annotate this this token 305 // with a template-id annotation. We do not permit the 306 // template-id to be translated into a type annotation, 307 // because some clients (e.g., the parsing of class template 308 // specializations) still want to see the original template-id 309 // token. 310 ConsumeToken(); 311 if (AnnotateTemplateIdToken(Template, TNK, &SS, TemplateName, 312 SourceLocation(), false)) 313 return true; 314 continue; 315 } 316 317 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) && 318 IsTemplateArgumentList(1)) { 319 // We have something like t::getAs<T>, where getAs is a 320 // member of an unknown specialization. However, this will only 321 // parse correctly as a template, so suggest the keyword 'template' 322 // before 'getAs' and treat this as a dependent template name. 323 Diag(Tok.getLocation(), diag::err_missing_dependent_template_keyword) 324 << II.getName() 325 << FixItHint::CreateInsertion(Tok.getLocation(), "template "); 326 327 if (TemplateNameKind TNK 328 = Actions.ActOnDependentTemplateName(getCurScope(), 329 Tok.getLocation(), SS, 330 TemplateName, ObjectType, 331 EnteringContext, Template)) { 332 // Consume the identifier. 333 ConsumeToken(); 334 if (AnnotateTemplateIdToken(Template, TNK, &SS, TemplateName, 335 SourceLocation(), false)) 336 return true; 337 } 338 else 339 return true; 340 341 continue; 342 } 343 } 344 345 // We don't have any tokens that form the beginning of a 346 // nested-name-specifier, so we're done. 347 break; 348 } 349 350 // Even if we didn't see any pieces of a nested-name-specifier, we 351 // still check whether there is a tilde in this position, which 352 // indicates a potential pseudo-destructor. 353 if (CheckForDestructor && Tok.is(tok::tilde)) 354 *MayBePseudoDestructor = true; 355 356 return false; 357} 358 359/// ParseCXXIdExpression - Handle id-expression. 360/// 361/// id-expression: 362/// unqualified-id 363/// qualified-id 364/// 365/// qualified-id: 366/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id 367/// '::' identifier 368/// '::' operator-function-id 369/// '::' template-id 370/// 371/// NOTE: The standard specifies that, for qualified-id, the parser does not 372/// expect: 373/// 374/// '::' conversion-function-id 375/// '::' '~' class-name 376/// 377/// This may cause a slight inconsistency on diagnostics: 378/// 379/// class C {}; 380/// namespace A {} 381/// void f() { 382/// :: A :: ~ C(); // Some Sema error about using destructor with a 383/// // namespace. 384/// :: ~ C(); // Some Parser error like 'unexpected ~'. 385/// } 386/// 387/// We simplify the parser a bit and make it work like: 388/// 389/// qualified-id: 390/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id 391/// '::' unqualified-id 392/// 393/// That way Sema can handle and report similar errors for namespaces and the 394/// global scope. 395/// 396/// The isAddressOfOperand parameter indicates that this id-expression is a 397/// direct operand of the address-of operator. This is, besides member contexts, 398/// the only place where a qualified-id naming a non-static class member may 399/// appear. 400/// 401ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) { 402 // qualified-id: 403 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id 404 // '::' unqualified-id 405 // 406 CXXScopeSpec SS; 407 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false); 408 409 UnqualifiedId Name; 410 if (ParseUnqualifiedId(SS, 411 /*EnteringContext=*/false, 412 /*AllowDestructorName=*/false, 413 /*AllowConstructorName=*/false, 414 /*ObjectType=*/ ParsedType(), 415 Name)) 416 return ExprError(); 417 418 // This is only the direct operand of an & operator if it is not 419 // followed by a postfix-expression suffix. 420 if (isAddressOfOperand && isPostfixExpressionSuffixStart()) 421 isAddressOfOperand = false; 422 423 return Actions.ActOnIdExpression(getCurScope(), SS, Name, Tok.is(tok::l_paren), 424 isAddressOfOperand); 425 426} 427 428/// ParseCXXCasts - This handles the various ways to cast expressions to another 429/// type. 430/// 431/// postfix-expression: [C++ 5.2p1] 432/// 'dynamic_cast' '<' type-name '>' '(' expression ')' 433/// 'static_cast' '<' type-name '>' '(' expression ')' 434/// 'reinterpret_cast' '<' type-name '>' '(' expression ')' 435/// 'const_cast' '<' type-name '>' '(' expression ')' 436/// 437ExprResult Parser::ParseCXXCasts() { 438 tok::TokenKind Kind = Tok.getKind(); 439 const char *CastName = 0; // For error messages 440 441 switch (Kind) { 442 default: assert(0 && "Unknown C++ cast!"); abort(); 443 case tok::kw_const_cast: CastName = "const_cast"; break; 444 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break; 445 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break; 446 case tok::kw_static_cast: CastName = "static_cast"; break; 447 } 448 449 SourceLocation OpLoc = ConsumeToken(); 450 SourceLocation LAngleBracketLoc = Tok.getLocation(); 451 452 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName)) 453 return ExprError(); 454 455 TypeResult CastTy = ParseTypeName(); 456 SourceLocation RAngleBracketLoc = Tok.getLocation(); 457 458 if (ExpectAndConsume(tok::greater, diag::err_expected_greater)) 459 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<"); 460 461 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; 462 463 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, CastName)) 464 return ExprError(); 465 466 ExprResult Result = ParseExpression(); 467 468 // Match the ')'. 469 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 470 471 if (!Result.isInvalid() && !CastTy.isInvalid()) 472 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind, 473 LAngleBracketLoc, CastTy.get(), 474 RAngleBracketLoc, 475 LParenLoc, Result.take(), RParenLoc); 476 477 return move(Result); 478} 479 480/// ParseCXXTypeid - This handles the C++ typeid expression. 481/// 482/// postfix-expression: [C++ 5.2p1] 483/// 'typeid' '(' expression ')' 484/// 'typeid' '(' type-id ')' 485/// 486ExprResult Parser::ParseCXXTypeid() { 487 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!"); 488 489 SourceLocation OpLoc = ConsumeToken(); 490 SourceLocation LParenLoc = Tok.getLocation(); 491 SourceLocation RParenLoc; 492 493 // typeid expressions are always parenthesized. 494 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 495 "typeid")) 496 return ExprError(); 497 498 ExprResult Result; 499 500 if (isTypeIdInParens()) { 501 TypeResult Ty = ParseTypeName(); 502 503 // Match the ')'. 504 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 505 506 if (Ty.isInvalid() || RParenLoc.isInvalid()) 507 return ExprError(); 508 509 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true, 510 Ty.get().getAsOpaquePtr(), RParenLoc); 511 } else { 512 // C++0x [expr.typeid]p3: 513 // When typeid is applied to an expression other than an lvalue of a 514 // polymorphic class type [...] The expression is an unevaluated 515 // operand (Clause 5). 516 // 517 // Note that we can't tell whether the expression is an lvalue of a 518 // polymorphic class type until after we've parsed the expression, so 519 // we the expression is potentially potentially evaluated. 520 EnterExpressionEvaluationContext Unevaluated(Actions, 521 Sema::PotentiallyPotentiallyEvaluated); 522 Result = ParseExpression(); 523 524 // Match the ')'. 525 if (Result.isInvalid()) 526 SkipUntil(tok::r_paren); 527 else { 528 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 529 if (RParenLoc.isInvalid()) 530 return ExprError(); 531 532 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false, 533 Result.release(), RParenLoc); 534 } 535 } 536 537 return move(Result); 538} 539 540/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression. 541/// 542/// '__uuidof' '(' expression ')' 543/// '__uuidof' '(' type-id ')' 544/// 545ExprResult Parser::ParseCXXUuidof() { 546 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!"); 547 548 SourceLocation OpLoc = ConsumeToken(); 549 SourceLocation LParenLoc = Tok.getLocation(); 550 SourceLocation RParenLoc; 551 552 // __uuidof expressions are always parenthesized. 553 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 554 "__uuidof")) 555 return ExprError(); 556 557 ExprResult Result; 558 559 if (isTypeIdInParens()) { 560 TypeResult Ty = ParseTypeName(); 561 562 // Match the ')'. 563 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 564 565 if (Ty.isInvalid()) 566 return ExprError(); 567 568 Result = Actions.ActOnCXXUuidof(OpLoc, LParenLoc, /*isType=*/true, 569 Ty.get().getAsOpaquePtr(), RParenLoc); 570 } else { 571 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 572 Result = ParseExpression(); 573 574 // Match the ')'. 575 if (Result.isInvalid()) 576 SkipUntil(tok::r_paren); 577 else { 578 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 579 580 Result = Actions.ActOnCXXUuidof(OpLoc, LParenLoc, /*isType=*/false, 581 Result.release(), RParenLoc); 582 } 583 } 584 585 return move(Result); 586} 587 588/// \brief Parse a C++ pseudo-destructor expression after the base, 589/// . or -> operator, and nested-name-specifier have already been 590/// parsed. 591/// 592/// postfix-expression: [C++ 5.2] 593/// postfix-expression . pseudo-destructor-name 594/// postfix-expression -> pseudo-destructor-name 595/// 596/// pseudo-destructor-name: 597/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name 598/// ::[opt] nested-name-specifier template simple-template-id :: 599/// ~type-name 600/// ::[opt] nested-name-specifier[opt] ~type-name 601/// 602ExprResult 603Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc, 604 tok::TokenKind OpKind, 605 CXXScopeSpec &SS, 606 ParsedType ObjectType) { 607 // We're parsing either a pseudo-destructor-name or a dependent 608 // member access that has the same form as a 609 // pseudo-destructor-name. We parse both in the same way and let 610 // the action model sort them out. 611 // 612 // Note that the ::[opt] nested-name-specifier[opt] has already 613 // been parsed, and if there was a simple-template-id, it has 614 // been coalesced into a template-id annotation token. 615 UnqualifiedId FirstTypeName; 616 SourceLocation CCLoc; 617 if (Tok.is(tok::identifier)) { 618 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 619 ConsumeToken(); 620 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"); 621 CCLoc = ConsumeToken(); 622 } else if (Tok.is(tok::annot_template_id)) { 623 FirstTypeName.setTemplateId( 624 (TemplateIdAnnotation *)Tok.getAnnotationValue()); 625 ConsumeToken(); 626 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"); 627 CCLoc = ConsumeToken(); 628 } else { 629 FirstTypeName.setIdentifier(0, SourceLocation()); 630 } 631 632 // Parse the tilde. 633 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail"); 634 SourceLocation TildeLoc = ConsumeToken(); 635 if (!Tok.is(tok::identifier)) { 636 Diag(Tok, diag::err_destructor_tilde_identifier); 637 return ExprError(); 638 } 639 640 // Parse the second type. 641 UnqualifiedId SecondTypeName; 642 IdentifierInfo *Name = Tok.getIdentifierInfo(); 643 SourceLocation NameLoc = ConsumeToken(); 644 SecondTypeName.setIdentifier(Name, NameLoc); 645 646 // If there is a '<', the second type name is a template-id. Parse 647 // it as such. 648 if (Tok.is(tok::less) && 649 ParseUnqualifiedIdTemplateId(SS, Name, NameLoc, false, ObjectType, 650 SecondTypeName, /*AssumeTemplateName=*/true, 651 /*TemplateKWLoc*/SourceLocation())) 652 return ExprError(); 653 654 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, 655 OpLoc, OpKind, 656 SS, FirstTypeName, CCLoc, 657 TildeLoc, SecondTypeName, 658 Tok.is(tok::l_paren)); 659} 660 661/// ParseCXXBoolLiteral - This handles the C++ Boolean literals. 662/// 663/// boolean-literal: [C++ 2.13.5] 664/// 'true' 665/// 'false' 666ExprResult Parser::ParseCXXBoolLiteral() { 667 tok::TokenKind Kind = Tok.getKind(); 668 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind); 669} 670 671/// ParseThrowExpression - This handles the C++ throw expression. 672/// 673/// throw-expression: [C++ 15] 674/// 'throw' assignment-expression[opt] 675ExprResult Parser::ParseThrowExpression() { 676 assert(Tok.is(tok::kw_throw) && "Not throw!"); 677 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token. 678 679 // If the current token isn't the start of an assignment-expression, 680 // then the expression is not present. This handles things like: 681 // "C ? throw : (void)42", which is crazy but legal. 682 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common. 683 case tok::semi: 684 case tok::r_paren: 685 case tok::r_square: 686 case tok::r_brace: 687 case tok::colon: 688 case tok::comma: 689 return Actions.ActOnCXXThrow(ThrowLoc, 0); 690 691 default: 692 ExprResult Expr(ParseAssignmentExpression()); 693 if (Expr.isInvalid()) return move(Expr); 694 return Actions.ActOnCXXThrow(ThrowLoc, Expr.take()); 695 } 696} 697 698/// ParseCXXThis - This handles the C++ 'this' pointer. 699/// 700/// C++ 9.3.2: In the body of a non-static member function, the keyword this is 701/// a non-lvalue expression whose value is the address of the object for which 702/// the function is called. 703ExprResult Parser::ParseCXXThis() { 704 assert(Tok.is(tok::kw_this) && "Not 'this'!"); 705 SourceLocation ThisLoc = ConsumeToken(); 706 return Actions.ActOnCXXThis(ThisLoc); 707} 708 709/// ParseCXXTypeConstructExpression - Parse construction of a specified type. 710/// Can be interpreted either as function-style casting ("int(x)") 711/// or class type construction ("ClassType(x,y,z)") 712/// or creation of a value-initialized type ("int()"). 713/// 714/// postfix-expression: [C++ 5.2p1] 715/// simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3] 716/// typename-specifier '(' expression-list[opt] ')' [TODO] 717/// 718ExprResult 719Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) { 720 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 721 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get(); 722 723 assert(Tok.is(tok::l_paren) && "Expected '('!"); 724 GreaterThanIsOperatorScope G(GreaterThanIsOperator, true); 725 726 SourceLocation LParenLoc = ConsumeParen(); 727 728 ExprVector Exprs(Actions); 729 CommaLocsTy CommaLocs; 730 731 if (Tok.isNot(tok::r_paren)) { 732 if (ParseExpressionList(Exprs, CommaLocs)) { 733 SkipUntil(tok::r_paren); 734 return ExprError(); 735 } 736 } 737 738 // Match the ')'. 739 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 740 741 // TypeRep could be null, if it references an invalid typedef. 742 if (!TypeRep) 743 return ExprError(); 744 745 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&& 746 "Unexpected number of commas!"); 747 return Actions.ActOnCXXTypeConstructExpr(TypeRep, LParenLoc, move_arg(Exprs), 748 RParenLoc); 749} 750 751/// ParseCXXCondition - if/switch/while condition expression. 752/// 753/// condition: 754/// expression 755/// type-specifier-seq declarator '=' assignment-expression 756/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt] 757/// '=' assignment-expression 758/// 759/// \param ExprResult if the condition was parsed as an expression, the 760/// parsed expression. 761/// 762/// \param DeclResult if the condition was parsed as a declaration, the 763/// parsed declaration. 764/// 765/// \param Loc The location of the start of the statement that requires this 766/// condition, e.g., the "for" in a for loop. 767/// 768/// \param ConvertToBoolean Whether the condition expression should be 769/// converted to a boolean value. 770/// 771/// \returns true if there was a parsing, false otherwise. 772bool Parser::ParseCXXCondition(ExprResult &ExprOut, 773 Decl *&DeclOut, 774 SourceLocation Loc, 775 bool ConvertToBoolean) { 776 if (Tok.is(tok::code_completion)) { 777 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition); 778 ConsumeCodeCompletionToken(); 779 } 780 781 if (!isCXXConditionDeclaration()) { 782 // Parse the expression. 783 ExprOut = ParseExpression(); // expression 784 DeclOut = 0; 785 if (ExprOut.isInvalid()) 786 return true; 787 788 // If required, convert to a boolean value. 789 if (ConvertToBoolean) 790 ExprOut 791 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get()); 792 return ExprOut.isInvalid(); 793 } 794 795 // type-specifier-seq 796 DeclSpec DS; 797 ParseSpecifierQualifierList(DS); 798 799 // declarator 800 Declarator DeclaratorInfo(DS, Declarator::ConditionContext); 801 ParseDeclarator(DeclaratorInfo); 802 803 // simple-asm-expr[opt] 804 if (Tok.is(tok::kw_asm)) { 805 SourceLocation Loc; 806 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 807 if (AsmLabel.isInvalid()) { 808 SkipUntil(tok::semi); 809 return true; 810 } 811 DeclaratorInfo.setAsmLabel(AsmLabel.release()); 812 DeclaratorInfo.SetRangeEnd(Loc); 813 } 814 815 // If attributes are present, parse them. 816 MaybeParseGNUAttributes(DeclaratorInfo); 817 818 // Type-check the declaration itself. 819 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(), 820 DeclaratorInfo); 821 DeclOut = Dcl.get(); 822 ExprOut = ExprError(); 823 824 // '=' assignment-expression 825 if (isTokenEqualOrMistypedEqualEqual( 826 diag::err_invalid_equalequal_after_declarator)) { 827 ConsumeToken(); 828 ExprResult AssignExpr(ParseAssignmentExpression()); 829 if (!AssignExpr.isInvalid()) 830 Actions.AddInitializerToDecl(DeclOut, AssignExpr.take(), false, 831 DS.getTypeSpecType() == DeclSpec::TST_auto); 832 } else { 833 // FIXME: C++0x allows a braced-init-list 834 Diag(Tok, diag::err_expected_equal_after_declarator); 835 } 836 837 // FIXME: Build a reference to this declaration? Convert it to bool? 838 // (This is currently handled by Sema). 839 840 Actions.FinalizeDeclaration(DeclOut); 841 842 return false; 843} 844 845/// \brief Determine whether the current token starts a C++ 846/// simple-type-specifier. 847bool Parser::isCXXSimpleTypeSpecifier() const { 848 switch (Tok.getKind()) { 849 case tok::annot_typename: 850 case tok::kw_short: 851 case tok::kw_long: 852 case tok::kw_signed: 853 case tok::kw_unsigned: 854 case tok::kw_void: 855 case tok::kw_char: 856 case tok::kw_int: 857 case tok::kw_float: 858 case tok::kw_double: 859 case tok::kw_wchar_t: 860 case tok::kw_char16_t: 861 case tok::kw_char32_t: 862 case tok::kw_bool: 863 // FIXME: C++0x decltype support. 864 // GNU typeof support. 865 case tok::kw_typeof: 866 return true; 867 868 default: 869 break; 870 } 871 872 return false; 873} 874 875/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. 876/// This should only be called when the current token is known to be part of 877/// simple-type-specifier. 878/// 879/// simple-type-specifier: 880/// '::'[opt] nested-name-specifier[opt] type-name 881/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO] 882/// char 883/// wchar_t 884/// bool 885/// short 886/// int 887/// long 888/// signed 889/// unsigned 890/// float 891/// double 892/// void 893/// [GNU] typeof-specifier 894/// [C++0x] auto [TODO] 895/// 896/// type-name: 897/// class-name 898/// enum-name 899/// typedef-name 900/// 901void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { 902 DS.SetRangeStart(Tok.getLocation()); 903 const char *PrevSpec; 904 unsigned DiagID; 905 SourceLocation Loc = Tok.getLocation(); 906 907 switch (Tok.getKind()) { 908 case tok::identifier: // foo::bar 909 case tok::coloncolon: // ::foo::bar 910 assert(0 && "Annotation token should already be formed!"); 911 default: 912 assert(0 && "Not a simple-type-specifier token!"); 913 abort(); 914 915 // type-name 916 case tok::annot_typename: { 917 if (getTypeAnnotation(Tok)) 918 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, 919 getTypeAnnotation(Tok)); 920 else 921 DS.SetTypeSpecError(); 922 923 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 924 ConsumeToken(); 925 926 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 927 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 928 // Objective-C interface. If we don't have Objective-C or a '<', this is 929 // just a normal reference to a typedef name. 930 if (Tok.is(tok::less) && getLang().ObjC1) 931 ParseObjCProtocolQualifiers(DS); 932 933 DS.Finish(Diags, PP); 934 return; 935 } 936 937 // builtin types 938 case tok::kw_short: 939 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID); 940 break; 941 case tok::kw_long: 942 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID); 943 break; 944 case tok::kw_signed: 945 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID); 946 break; 947 case tok::kw_unsigned: 948 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID); 949 break; 950 case tok::kw_void: 951 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID); 952 break; 953 case tok::kw_char: 954 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID); 955 break; 956 case tok::kw_int: 957 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID); 958 break; 959 case tok::kw_float: 960 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID); 961 break; 962 case tok::kw_double: 963 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID); 964 break; 965 case tok::kw_wchar_t: 966 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID); 967 break; 968 case tok::kw_char16_t: 969 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID); 970 break; 971 case tok::kw_char32_t: 972 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID); 973 break; 974 case tok::kw_bool: 975 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID); 976 break; 977 978 // FIXME: C++0x decltype support. 979 // GNU typeof support. 980 case tok::kw_typeof: 981 ParseTypeofSpecifier(DS); 982 DS.Finish(Diags, PP); 983 return; 984 } 985 if (Tok.is(tok::annot_typename)) 986 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 987 else 988 DS.SetRangeEnd(Tok.getLocation()); 989 ConsumeToken(); 990 DS.Finish(Diags, PP); 991} 992 993/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++ 994/// [dcl.name]), which is a non-empty sequence of type-specifiers, 995/// e.g., "const short int". Note that the DeclSpec is *not* finished 996/// by parsing the type-specifier-seq, because these sequences are 997/// typically followed by some form of declarator. Returns true and 998/// emits diagnostics if this is not a type-specifier-seq, false 999/// otherwise. 1000/// 1001/// type-specifier-seq: [C++ 8.1] 1002/// type-specifier type-specifier-seq[opt] 1003/// 1004bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) { 1005 DS.SetRangeStart(Tok.getLocation()); 1006 const char *PrevSpec = 0; 1007 unsigned DiagID; 1008 bool isInvalid = 0; 1009 1010 // Parse one or more of the type specifiers. 1011 if (!ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID, 1012 ParsedTemplateInfo(), /*SuppressDeclarations*/true)) { 1013 Diag(Tok, diag::err_expected_type); 1014 return true; 1015 } 1016 1017 while (ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID, 1018 ParsedTemplateInfo(), /*SuppressDeclarations*/true)) 1019 {} 1020 1021 DS.Finish(Diags, PP); 1022 return false; 1023} 1024 1025/// \brief Finish parsing a C++ unqualified-id that is a template-id of 1026/// some form. 1027/// 1028/// This routine is invoked when a '<' is encountered after an identifier or 1029/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine 1030/// whether the unqualified-id is actually a template-id. This routine will 1031/// then parse the template arguments and form the appropriate template-id to 1032/// return to the caller. 1033/// 1034/// \param SS the nested-name-specifier that precedes this template-id, if 1035/// we're actually parsing a qualified-id. 1036/// 1037/// \param Name for constructor and destructor names, this is the actual 1038/// identifier that may be a template-name. 1039/// 1040/// \param NameLoc the location of the class-name in a constructor or 1041/// destructor. 1042/// 1043/// \param EnteringContext whether we're entering the scope of the 1044/// nested-name-specifier. 1045/// 1046/// \param ObjectType if this unqualified-id occurs within a member access 1047/// expression, the type of the base object whose member is being accessed. 1048/// 1049/// \param Id as input, describes the template-name or operator-function-id 1050/// that precedes the '<'. If template arguments were parsed successfully, 1051/// will be updated with the template-id. 1052/// 1053/// \param AssumeTemplateId When true, this routine will assume that the name 1054/// refers to a template without performing name lookup to verify. 1055/// 1056/// \returns true if a parse error occurred, false otherwise. 1057bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, 1058 IdentifierInfo *Name, 1059 SourceLocation NameLoc, 1060 bool EnteringContext, 1061 ParsedType ObjectType, 1062 UnqualifiedId &Id, 1063 bool AssumeTemplateId, 1064 SourceLocation TemplateKWLoc) { 1065 assert((AssumeTemplateId || Tok.is(tok::less)) && 1066 "Expected '<' to finish parsing a template-id"); 1067 1068 TemplateTy Template; 1069 TemplateNameKind TNK = TNK_Non_template; 1070 switch (Id.getKind()) { 1071 case UnqualifiedId::IK_Identifier: 1072 case UnqualifiedId::IK_OperatorFunctionId: 1073 case UnqualifiedId::IK_LiteralOperatorId: 1074 if (AssumeTemplateId) { 1075 TNK = Actions.ActOnDependentTemplateName(getCurScope(), TemplateKWLoc, SS, 1076 Id, ObjectType, EnteringContext, 1077 Template); 1078 if (TNK == TNK_Non_template) 1079 return true; 1080 } else { 1081 bool MemberOfUnknownSpecialization; 1082 TNK = Actions.isTemplateName(getCurScope(), SS, 1083 TemplateKWLoc.isValid(), Id, 1084 ObjectType, EnteringContext, Template, 1085 MemberOfUnknownSpecialization); 1086 1087 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization && 1088 ObjectType && IsTemplateArgumentList()) { 1089 // We have something like t->getAs<T>(), where getAs is a 1090 // member of an unknown specialization. However, this will only 1091 // parse correctly as a template, so suggest the keyword 'template' 1092 // before 'getAs' and treat this as a dependent template name. 1093 std::string Name; 1094 if (Id.getKind() == UnqualifiedId::IK_Identifier) 1095 Name = Id.Identifier->getName(); 1096 else { 1097 Name = "operator "; 1098 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId) 1099 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator); 1100 else 1101 Name += Id.Identifier->getName(); 1102 } 1103 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword) 1104 << Name 1105 << FixItHint::CreateInsertion(Id.StartLocation, "template "); 1106 TNK = Actions.ActOnDependentTemplateName(getCurScope(), TemplateKWLoc, 1107 SS, Id, ObjectType, 1108 EnteringContext, Template); 1109 if (TNK == TNK_Non_template) 1110 return true; 1111 } 1112 } 1113 break; 1114 1115 case UnqualifiedId::IK_ConstructorName: { 1116 UnqualifiedId TemplateName; 1117 bool MemberOfUnknownSpecialization; 1118 TemplateName.setIdentifier(Name, NameLoc); 1119 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), 1120 TemplateName, ObjectType, 1121 EnteringContext, Template, 1122 MemberOfUnknownSpecialization); 1123 break; 1124 } 1125 1126 case UnqualifiedId::IK_DestructorName: { 1127 UnqualifiedId TemplateName; 1128 bool MemberOfUnknownSpecialization; 1129 TemplateName.setIdentifier(Name, NameLoc); 1130 if (ObjectType) { 1131 TNK = Actions.ActOnDependentTemplateName(getCurScope(), TemplateKWLoc, SS, 1132 TemplateName, ObjectType, 1133 EnteringContext, Template); 1134 if (TNK == TNK_Non_template) 1135 return true; 1136 } else { 1137 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), 1138 TemplateName, ObjectType, 1139 EnteringContext, Template, 1140 MemberOfUnknownSpecialization); 1141 1142 if (TNK == TNK_Non_template && !Id.DestructorName.get()) { 1143 Diag(NameLoc, diag::err_destructor_template_id) 1144 << Name << SS.getRange(); 1145 return true; 1146 } 1147 } 1148 break; 1149 } 1150 1151 default: 1152 return false; 1153 } 1154 1155 if (TNK == TNK_Non_template) 1156 return false; 1157 1158 // Parse the enclosed template argument list. 1159 SourceLocation LAngleLoc, RAngleLoc; 1160 TemplateArgList TemplateArgs; 1161 if (Tok.is(tok::less) && 1162 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation, 1163 &SS, true, LAngleLoc, 1164 TemplateArgs, 1165 RAngleLoc)) 1166 return true; 1167 1168 if (Id.getKind() == UnqualifiedId::IK_Identifier || 1169 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId || 1170 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) { 1171 // Form a parsed representation of the template-id to be stored in the 1172 // UnqualifiedId. 1173 TemplateIdAnnotation *TemplateId 1174 = TemplateIdAnnotation::Allocate(TemplateArgs.size()); 1175 1176 if (Id.getKind() == UnqualifiedId::IK_Identifier) { 1177 TemplateId->Name = Id.Identifier; 1178 TemplateId->Operator = OO_None; 1179 TemplateId->TemplateNameLoc = Id.StartLocation; 1180 } else { 1181 TemplateId->Name = 0; 1182 TemplateId->Operator = Id.OperatorFunctionId.Operator; 1183 TemplateId->TemplateNameLoc = Id.StartLocation; 1184 } 1185 1186 TemplateId->Template = Template; 1187 TemplateId->Kind = TNK; 1188 TemplateId->LAngleLoc = LAngleLoc; 1189 TemplateId->RAngleLoc = RAngleLoc; 1190 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs(); 1191 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); 1192 Arg != ArgEnd; ++Arg) 1193 Args[Arg] = TemplateArgs[Arg]; 1194 1195 Id.setTemplateId(TemplateId); 1196 return false; 1197 } 1198 1199 // Bundle the template arguments together. 1200 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(), 1201 TemplateArgs.size()); 1202 1203 // Constructor and destructor names. 1204 TypeResult Type 1205 = Actions.ActOnTemplateIdType(Template, NameLoc, 1206 LAngleLoc, TemplateArgsPtr, 1207 RAngleLoc); 1208 if (Type.isInvalid()) 1209 return true; 1210 1211 if (Id.getKind() == UnqualifiedId::IK_ConstructorName) 1212 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc); 1213 else 1214 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc); 1215 1216 return false; 1217} 1218 1219/// \brief Parse an operator-function-id or conversion-function-id as part 1220/// of a C++ unqualified-id. 1221/// 1222/// This routine is responsible only for parsing the operator-function-id or 1223/// conversion-function-id; it does not handle template arguments in any way. 1224/// 1225/// \code 1226/// operator-function-id: [C++ 13.5] 1227/// 'operator' operator 1228/// 1229/// operator: one of 1230/// new delete new[] delete[] 1231/// + - * / % ^ & | ~ 1232/// ! = < > += -= *= /= %= 1233/// ^= &= |= << >> >>= <<= == != 1234/// <= >= && || ++ -- , ->* -> 1235/// () [] 1236/// 1237/// conversion-function-id: [C++ 12.3.2] 1238/// operator conversion-type-id 1239/// 1240/// conversion-type-id: 1241/// type-specifier-seq conversion-declarator[opt] 1242/// 1243/// conversion-declarator: 1244/// ptr-operator conversion-declarator[opt] 1245/// \endcode 1246/// 1247/// \param The nested-name-specifier that preceded this unqualified-id. If 1248/// non-empty, then we are parsing the unqualified-id of a qualified-id. 1249/// 1250/// \param EnteringContext whether we are entering the scope of the 1251/// nested-name-specifier. 1252/// 1253/// \param ObjectType if this unqualified-id occurs within a member access 1254/// expression, the type of the base object whose member is being accessed. 1255/// 1256/// \param Result on a successful parse, contains the parsed unqualified-id. 1257/// 1258/// \returns true if parsing fails, false otherwise. 1259bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, 1260 ParsedType ObjectType, 1261 UnqualifiedId &Result) { 1262 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword"); 1263 1264 // Consume the 'operator' keyword. 1265 SourceLocation KeywordLoc = ConsumeToken(); 1266 1267 // Determine what kind of operator name we have. 1268 unsigned SymbolIdx = 0; 1269 SourceLocation SymbolLocations[3]; 1270 OverloadedOperatorKind Op = OO_None; 1271 switch (Tok.getKind()) { 1272 case tok::kw_new: 1273 case tok::kw_delete: { 1274 bool isNew = Tok.getKind() == tok::kw_new; 1275 // Consume the 'new' or 'delete'. 1276 SymbolLocations[SymbolIdx++] = ConsumeToken(); 1277 if (Tok.is(tok::l_square)) { 1278 // Consume the '['. 1279 SourceLocation LBracketLoc = ConsumeBracket(); 1280 // Consume the ']'. 1281 SourceLocation RBracketLoc = MatchRHSPunctuation(tok::r_square, 1282 LBracketLoc); 1283 if (RBracketLoc.isInvalid()) 1284 return true; 1285 1286 SymbolLocations[SymbolIdx++] = LBracketLoc; 1287 SymbolLocations[SymbolIdx++] = RBracketLoc; 1288 Op = isNew? OO_Array_New : OO_Array_Delete; 1289 } else { 1290 Op = isNew? OO_New : OO_Delete; 1291 } 1292 break; 1293 } 1294 1295#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 1296 case tok::Token: \ 1297 SymbolLocations[SymbolIdx++] = ConsumeToken(); \ 1298 Op = OO_##Name; \ 1299 break; 1300#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly) 1301#include "clang/Basic/OperatorKinds.def" 1302 1303 case tok::l_paren: { 1304 // Consume the '('. 1305 SourceLocation LParenLoc = ConsumeParen(); 1306 // Consume the ')'. 1307 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, 1308 LParenLoc); 1309 if (RParenLoc.isInvalid()) 1310 return true; 1311 1312 SymbolLocations[SymbolIdx++] = LParenLoc; 1313 SymbolLocations[SymbolIdx++] = RParenLoc; 1314 Op = OO_Call; 1315 break; 1316 } 1317 1318 case tok::l_square: { 1319 // Consume the '['. 1320 SourceLocation LBracketLoc = ConsumeBracket(); 1321 // Consume the ']'. 1322 SourceLocation RBracketLoc = MatchRHSPunctuation(tok::r_square, 1323 LBracketLoc); 1324 if (RBracketLoc.isInvalid()) 1325 return true; 1326 1327 SymbolLocations[SymbolIdx++] = LBracketLoc; 1328 SymbolLocations[SymbolIdx++] = RBracketLoc; 1329 Op = OO_Subscript; 1330 break; 1331 } 1332 1333 case tok::code_completion: { 1334 // Code completion for the operator name. 1335 Actions.CodeCompleteOperatorName(getCurScope()); 1336 1337 // Consume the operator token. 1338 ConsumeCodeCompletionToken(); 1339 1340 // Don't try to parse any further. 1341 return true; 1342 } 1343 1344 default: 1345 break; 1346 } 1347 1348 if (Op != OO_None) { 1349 // We have parsed an operator-function-id. 1350 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations); 1351 return false; 1352 } 1353 1354 // Parse a literal-operator-id. 1355 // 1356 // literal-operator-id: [C++0x 13.5.8] 1357 // operator "" identifier 1358 1359 if (getLang().CPlusPlus0x && Tok.is(tok::string_literal)) { 1360 if (Tok.getLength() != 2) 1361 Diag(Tok.getLocation(), diag::err_operator_string_not_empty); 1362 ConsumeStringToken(); 1363 1364 if (Tok.isNot(tok::identifier)) { 1365 Diag(Tok.getLocation(), diag::err_expected_ident); 1366 return true; 1367 } 1368 1369 IdentifierInfo *II = Tok.getIdentifierInfo(); 1370 Result.setLiteralOperatorId(II, KeywordLoc, ConsumeToken()); 1371 return false; 1372 } 1373 1374 // Parse a conversion-function-id. 1375 // 1376 // conversion-function-id: [C++ 12.3.2] 1377 // operator conversion-type-id 1378 // 1379 // conversion-type-id: 1380 // type-specifier-seq conversion-declarator[opt] 1381 // 1382 // conversion-declarator: 1383 // ptr-operator conversion-declarator[opt] 1384 1385 // Parse the type-specifier-seq. 1386 DeclSpec DS; 1387 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType? 1388 return true; 1389 1390 // Parse the conversion-declarator, which is merely a sequence of 1391 // ptr-operators. 1392 Declarator D(DS, Declarator::TypeNameContext); 1393 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0); 1394 1395 // Finish up the type. 1396 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D); 1397 if (Ty.isInvalid()) 1398 return true; 1399 1400 // Note that this is a conversion-function-id. 1401 Result.setConversionFunctionId(KeywordLoc, Ty.get(), 1402 D.getSourceRange().getEnd()); 1403 return false; 1404} 1405 1406/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the 1407/// name of an entity. 1408/// 1409/// \code 1410/// unqualified-id: [C++ expr.prim.general] 1411/// identifier 1412/// operator-function-id 1413/// conversion-function-id 1414/// [C++0x] literal-operator-id [TODO] 1415/// ~ class-name 1416/// template-id 1417/// 1418/// \endcode 1419/// 1420/// \param The nested-name-specifier that preceded this unqualified-id. If 1421/// non-empty, then we are parsing the unqualified-id of a qualified-id. 1422/// 1423/// \param EnteringContext whether we are entering the scope of the 1424/// nested-name-specifier. 1425/// 1426/// \param AllowDestructorName whether we allow parsing of a destructor name. 1427/// 1428/// \param AllowConstructorName whether we allow parsing a constructor name. 1429/// 1430/// \param ObjectType if this unqualified-id occurs within a member access 1431/// expression, the type of the base object whose member is being accessed. 1432/// 1433/// \param Result on a successful parse, contains the parsed unqualified-id. 1434/// 1435/// \returns true if parsing fails, false otherwise. 1436bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, 1437 bool AllowDestructorName, 1438 bool AllowConstructorName, 1439 ParsedType ObjectType, 1440 UnqualifiedId &Result) { 1441 1442 // Handle 'A::template B'. This is for template-ids which have not 1443 // already been annotated by ParseOptionalCXXScopeSpecifier(). 1444 bool TemplateSpecified = false; 1445 SourceLocation TemplateKWLoc; 1446 if (getLang().CPlusPlus && Tok.is(tok::kw_template) && 1447 (ObjectType || SS.isSet())) { 1448 TemplateSpecified = true; 1449 TemplateKWLoc = ConsumeToken(); 1450 } 1451 1452 // unqualified-id: 1453 // identifier 1454 // template-id (when it hasn't already been annotated) 1455 if (Tok.is(tok::identifier)) { 1456 // Consume the identifier. 1457 IdentifierInfo *Id = Tok.getIdentifierInfo(); 1458 SourceLocation IdLoc = ConsumeToken(); 1459 1460 if (!getLang().CPlusPlus) { 1461 // If we're not in C++, only identifiers matter. Record the 1462 // identifier and return. 1463 Result.setIdentifier(Id, IdLoc); 1464 return false; 1465 } 1466 1467 if (AllowConstructorName && 1468 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) { 1469 // We have parsed a constructor name. 1470 Result.setConstructorName(Actions.getTypeName(*Id, IdLoc, getCurScope(), 1471 &SS, false), 1472 IdLoc, IdLoc); 1473 } else { 1474 // We have parsed an identifier. 1475 Result.setIdentifier(Id, IdLoc); 1476 } 1477 1478 // If the next token is a '<', we may have a template. 1479 if (TemplateSpecified || Tok.is(tok::less)) 1480 return ParseUnqualifiedIdTemplateId(SS, Id, IdLoc, EnteringContext, 1481 ObjectType, Result, 1482 TemplateSpecified, TemplateKWLoc); 1483 1484 return false; 1485 } 1486 1487 // unqualified-id: 1488 // template-id (already parsed and annotated) 1489 if (Tok.is(tok::annot_template_id)) { 1490 TemplateIdAnnotation *TemplateId 1491 = static_cast<TemplateIdAnnotation*>(Tok.getAnnotationValue()); 1492 1493 // If the template-name names the current class, then this is a constructor 1494 if (AllowConstructorName && TemplateId->Name && 1495 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { 1496 if (SS.isSet()) { 1497 // C++ [class.qual]p2 specifies that a qualified template-name 1498 // is taken as the constructor name where a constructor can be 1499 // declared. Thus, the template arguments are extraneous, so 1500 // complain about them and remove them entirely. 1501 Diag(TemplateId->TemplateNameLoc, 1502 diag::err_out_of_line_constructor_template_id) 1503 << TemplateId->Name 1504 << FixItHint::CreateRemoval( 1505 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)); 1506 Result.setConstructorName(Actions.getTypeName(*TemplateId->Name, 1507 TemplateId->TemplateNameLoc, 1508 getCurScope(), 1509 &SS, false), 1510 TemplateId->TemplateNameLoc, 1511 TemplateId->RAngleLoc); 1512 TemplateId->Destroy(); 1513 ConsumeToken(); 1514 return false; 1515 } 1516 1517 Result.setConstructorTemplateId(TemplateId); 1518 ConsumeToken(); 1519 return false; 1520 } 1521 1522 // We have already parsed a template-id; consume the annotation token as 1523 // our unqualified-id. 1524 Result.setTemplateId(TemplateId); 1525 ConsumeToken(); 1526 return false; 1527 } 1528 1529 // unqualified-id: 1530 // operator-function-id 1531 // conversion-function-id 1532 if (Tok.is(tok::kw_operator)) { 1533 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result)) 1534 return true; 1535 1536 // If we have an operator-function-id or a literal-operator-id and the next 1537 // token is a '<', we may have a 1538 // 1539 // template-id: 1540 // operator-function-id < template-argument-list[opt] > 1541 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId || 1542 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) && 1543 (TemplateSpecified || Tok.is(tok::less))) 1544 return ParseUnqualifiedIdTemplateId(SS, 0, SourceLocation(), 1545 EnteringContext, ObjectType, 1546 Result, 1547 TemplateSpecified, TemplateKWLoc); 1548 1549 return false; 1550 } 1551 1552 if (getLang().CPlusPlus && 1553 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) { 1554 // C++ [expr.unary.op]p10: 1555 // There is an ambiguity in the unary-expression ~X(), where X is a 1556 // class-name. The ambiguity is resolved in favor of treating ~ as a 1557 // unary complement rather than treating ~X as referring to a destructor. 1558 1559 // Parse the '~'. 1560 SourceLocation TildeLoc = ConsumeToken(); 1561 1562 // Parse the class-name. 1563 if (Tok.isNot(tok::identifier)) { 1564 Diag(Tok, diag::err_destructor_tilde_identifier); 1565 return true; 1566 } 1567 1568 // Parse the class-name (or template-name in a simple-template-id). 1569 IdentifierInfo *ClassName = Tok.getIdentifierInfo(); 1570 SourceLocation ClassNameLoc = ConsumeToken(); 1571 1572 if (TemplateSpecified || Tok.is(tok::less)) { 1573 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc); 1574 return ParseUnqualifiedIdTemplateId(SS, ClassName, ClassNameLoc, 1575 EnteringContext, ObjectType, Result, 1576 TemplateSpecified, TemplateKWLoc); 1577 } 1578 1579 // Note that this is a destructor name. 1580 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName, 1581 ClassNameLoc, getCurScope(), 1582 SS, ObjectType, 1583 EnteringContext); 1584 if (!Ty) 1585 return true; 1586 1587 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc); 1588 return false; 1589 } 1590 1591 Diag(Tok, diag::err_expected_unqualified_id) 1592 << getLang().CPlusPlus; 1593 return true; 1594} 1595 1596/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate 1597/// memory in a typesafe manner and call constructors. 1598/// 1599/// This method is called to parse the new expression after the optional :: has 1600/// been already parsed. If the :: was present, "UseGlobal" is true and "Start" 1601/// is its location. Otherwise, "Start" is the location of the 'new' token. 1602/// 1603/// new-expression: 1604/// '::'[opt] 'new' new-placement[opt] new-type-id 1605/// new-initializer[opt] 1606/// '::'[opt] 'new' new-placement[opt] '(' type-id ')' 1607/// new-initializer[opt] 1608/// 1609/// new-placement: 1610/// '(' expression-list ')' 1611/// 1612/// new-type-id: 1613/// type-specifier-seq new-declarator[opt] 1614/// 1615/// new-declarator: 1616/// ptr-operator new-declarator[opt] 1617/// direct-new-declarator 1618/// 1619/// new-initializer: 1620/// '(' expression-list[opt] ')' 1621/// [C++0x] braced-init-list [TODO] 1622/// 1623ExprResult 1624Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) { 1625 assert(Tok.is(tok::kw_new) && "expected 'new' token"); 1626 ConsumeToken(); // Consume 'new' 1627 1628 // A '(' now can be a new-placement or the '(' wrapping the type-id in the 1629 // second form of new-expression. It can't be a new-type-id. 1630 1631 ExprVector PlacementArgs(Actions); 1632 SourceLocation PlacementLParen, PlacementRParen; 1633 1634 SourceRange TypeIdParens; 1635 DeclSpec DS; 1636 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 1637 if (Tok.is(tok::l_paren)) { 1638 // If it turns out to be a placement, we change the type location. 1639 PlacementLParen = ConsumeParen(); 1640 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) { 1641 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 1642 return ExprError(); 1643 } 1644 1645 PlacementRParen = MatchRHSPunctuation(tok::r_paren, PlacementLParen); 1646 if (PlacementRParen.isInvalid()) { 1647 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 1648 return ExprError(); 1649 } 1650 1651 if (PlacementArgs.empty()) { 1652 // Reset the placement locations. There was no placement. 1653 TypeIdParens = SourceRange(PlacementLParen, PlacementRParen); 1654 PlacementLParen = PlacementRParen = SourceLocation(); 1655 } else { 1656 // We still need the type. 1657 if (Tok.is(tok::l_paren)) { 1658 TypeIdParens.setBegin(ConsumeParen()); 1659 ParseSpecifierQualifierList(DS); 1660 DeclaratorInfo.SetSourceRange(DS.getSourceRange()); 1661 ParseDeclarator(DeclaratorInfo); 1662 TypeIdParens.setEnd(MatchRHSPunctuation(tok::r_paren, 1663 TypeIdParens.getBegin())); 1664 } else { 1665 if (ParseCXXTypeSpecifierSeq(DS)) 1666 DeclaratorInfo.setInvalidType(true); 1667 else { 1668 DeclaratorInfo.SetSourceRange(DS.getSourceRange()); 1669 ParseDeclaratorInternal(DeclaratorInfo, 1670 &Parser::ParseDirectNewDeclarator); 1671 } 1672 } 1673 } 1674 } else { 1675 // A new-type-id is a simplified type-id, where essentially the 1676 // direct-declarator is replaced by a direct-new-declarator. 1677 if (ParseCXXTypeSpecifierSeq(DS)) 1678 DeclaratorInfo.setInvalidType(true); 1679 else { 1680 DeclaratorInfo.SetSourceRange(DS.getSourceRange()); 1681 ParseDeclaratorInternal(DeclaratorInfo, 1682 &Parser::ParseDirectNewDeclarator); 1683 } 1684 } 1685 if (DeclaratorInfo.isInvalidType()) { 1686 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 1687 return ExprError(); 1688 } 1689 1690 ExprVector ConstructorArgs(Actions); 1691 SourceLocation ConstructorLParen, ConstructorRParen; 1692 1693 if (Tok.is(tok::l_paren)) { 1694 ConstructorLParen = ConsumeParen(); 1695 if (Tok.isNot(tok::r_paren)) { 1696 CommaLocsTy CommaLocs; 1697 if (ParseExpressionList(ConstructorArgs, CommaLocs)) { 1698 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 1699 return ExprError(); 1700 } 1701 } 1702 ConstructorRParen = MatchRHSPunctuation(tok::r_paren, ConstructorLParen); 1703 if (ConstructorRParen.isInvalid()) { 1704 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 1705 return ExprError(); 1706 } 1707 } 1708 1709 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen, 1710 move_arg(PlacementArgs), PlacementRParen, 1711 TypeIdParens, DeclaratorInfo, ConstructorLParen, 1712 move_arg(ConstructorArgs), ConstructorRParen); 1713} 1714 1715/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be 1716/// passed to ParseDeclaratorInternal. 1717/// 1718/// direct-new-declarator: 1719/// '[' expression ']' 1720/// direct-new-declarator '[' constant-expression ']' 1721/// 1722void Parser::ParseDirectNewDeclarator(Declarator &D) { 1723 // Parse the array dimensions. 1724 bool first = true; 1725 while (Tok.is(tok::l_square)) { 1726 SourceLocation LLoc = ConsumeBracket(); 1727 ExprResult Size(first ? ParseExpression() 1728 : ParseConstantExpression()); 1729 if (Size.isInvalid()) { 1730 // Recover 1731 SkipUntil(tok::r_square); 1732 return; 1733 } 1734 first = false; 1735 1736 SourceLocation RLoc = MatchRHSPunctuation(tok::r_square, LLoc); 1737 D.AddTypeInfo(DeclaratorChunk::getArray(0, ParsedAttributes(), 1738 /*static=*/false, /*star=*/false, 1739 Size.release(), LLoc, RLoc), 1740 RLoc); 1741 1742 if (RLoc.isInvalid()) 1743 return; 1744 } 1745} 1746 1747/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id. 1748/// This ambiguity appears in the syntax of the C++ new operator. 1749/// 1750/// new-expression: 1751/// '::'[opt] 'new' new-placement[opt] '(' type-id ')' 1752/// new-initializer[opt] 1753/// 1754/// new-placement: 1755/// '(' expression-list ')' 1756/// 1757bool Parser::ParseExpressionListOrTypeId( 1758 llvm::SmallVectorImpl<Expr*> &PlacementArgs, 1759 Declarator &D) { 1760 // The '(' was already consumed. 1761 if (isTypeIdInParens()) { 1762 ParseSpecifierQualifierList(D.getMutableDeclSpec()); 1763 D.SetSourceRange(D.getDeclSpec().getSourceRange()); 1764 ParseDeclarator(D); 1765 return D.isInvalidType(); 1766 } 1767 1768 // It's not a type, it has to be an expression list. 1769 // Discard the comma locations - ActOnCXXNew has enough parameters. 1770 CommaLocsTy CommaLocs; 1771 return ParseExpressionList(PlacementArgs, CommaLocs); 1772} 1773 1774/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used 1775/// to free memory allocated by new. 1776/// 1777/// This method is called to parse the 'delete' expression after the optional 1778/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true 1779/// and "Start" is its location. Otherwise, "Start" is the location of the 1780/// 'delete' token. 1781/// 1782/// delete-expression: 1783/// '::'[opt] 'delete' cast-expression 1784/// '::'[opt] 'delete' '[' ']' cast-expression 1785ExprResult 1786Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) { 1787 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword"); 1788 ConsumeToken(); // Consume 'delete' 1789 1790 // Array delete? 1791 bool ArrayDelete = false; 1792 if (Tok.is(tok::l_square)) { 1793 ArrayDelete = true; 1794 SourceLocation LHS = ConsumeBracket(); 1795 SourceLocation RHS = MatchRHSPunctuation(tok::r_square, LHS); 1796 if (RHS.isInvalid()) 1797 return ExprError(); 1798 } 1799 1800 ExprResult Operand(ParseCastExpression(false)); 1801 if (Operand.isInvalid()) 1802 return move(Operand); 1803 1804 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take()); 1805} 1806 1807static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) { 1808 switch(kind) { 1809 default: llvm_unreachable("Not a known unary type trait"); 1810 case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign; 1811 case tok::kw___has_nothrow_copy: return UTT_HasNothrowCopy; 1812 case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor; 1813 case tok::kw___has_trivial_assign: return UTT_HasTrivialAssign; 1814 case tok::kw___has_trivial_copy: return UTT_HasTrivialCopy; 1815 case tok::kw___has_trivial_constructor: return UTT_HasTrivialConstructor; 1816 case tok::kw___has_trivial_destructor: return UTT_HasTrivialDestructor; 1817 case tok::kw___has_virtual_destructor: return UTT_HasVirtualDestructor; 1818 case tok::kw___is_abstract: return UTT_IsAbstract; 1819 case tok::kw___is_class: return UTT_IsClass; 1820 case tok::kw___is_empty: return UTT_IsEmpty; 1821 case tok::kw___is_enum: return UTT_IsEnum; 1822 case tok::kw___is_pod: return UTT_IsPOD; 1823 case tok::kw___is_polymorphic: return UTT_IsPolymorphic; 1824 case tok::kw___is_union: return UTT_IsUnion; 1825 case tok::kw___is_literal: return UTT_IsLiteral; 1826 } 1827} 1828 1829static BinaryTypeTrait BinaryTypeTraitFromTokKind(tok::TokenKind kind) { 1830 switch(kind) { 1831 default: llvm_unreachable("Not a known binary type trait"); 1832 case tok::kw___is_base_of: return BTT_IsBaseOf; 1833 case tok::kw___builtin_types_compatible_p: return BTT_TypeCompatible; 1834 case tok::kw___is_convertible_to: return BTT_IsConvertibleTo; 1835 } 1836} 1837 1838/// ParseUnaryTypeTrait - Parse the built-in unary type-trait 1839/// pseudo-functions that allow implementation of the TR1/C++0x type traits 1840/// templates. 1841/// 1842/// primary-expression: 1843/// [GNU] unary-type-trait '(' type-id ')' 1844/// 1845ExprResult Parser::ParseUnaryTypeTrait() { 1846 UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind()); 1847 SourceLocation Loc = ConsumeToken(); 1848 1849 SourceLocation LParen = Tok.getLocation(); 1850 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen)) 1851 return ExprError(); 1852 1853 // FIXME: Error reporting absolutely sucks! If the this fails to parse a type 1854 // there will be cryptic errors about mismatched parentheses and missing 1855 // specifiers. 1856 TypeResult Ty = ParseTypeName(); 1857 1858 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen); 1859 1860 if (Ty.isInvalid()) 1861 return ExprError(); 1862 1863 return Actions.ActOnUnaryTypeTrait(UTT, Loc, Ty.get(), RParen); 1864} 1865 1866/// ParseBinaryTypeTrait - Parse the built-in binary type-trait 1867/// pseudo-functions that allow implementation of the TR1/C++0x type traits 1868/// templates. 1869/// 1870/// primary-expression: 1871/// [GNU] binary-type-trait '(' type-id ',' type-id ')' 1872/// 1873ExprResult Parser::ParseBinaryTypeTrait() { 1874 BinaryTypeTrait BTT = BinaryTypeTraitFromTokKind(Tok.getKind()); 1875 SourceLocation Loc = ConsumeToken(); 1876 1877 SourceLocation LParen = Tok.getLocation(); 1878 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen)) 1879 return ExprError(); 1880 1881 TypeResult LhsTy = ParseTypeName(); 1882 if (LhsTy.isInvalid()) { 1883 SkipUntil(tok::r_paren); 1884 return ExprError(); 1885 } 1886 1887 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) { 1888 SkipUntil(tok::r_paren); 1889 return ExprError(); 1890 } 1891 1892 TypeResult RhsTy = ParseTypeName(); 1893 if (RhsTy.isInvalid()) { 1894 SkipUntil(tok::r_paren); 1895 return ExprError(); 1896 } 1897 1898 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen); 1899 1900 return Actions.ActOnBinaryTypeTrait(BTT, Loc, LhsTy.get(), RhsTy.get(), RParen); 1901} 1902 1903/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a 1904/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate 1905/// based on the context past the parens. 1906ExprResult 1907Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, 1908 ParsedType &CastTy, 1909 SourceLocation LParenLoc, 1910 SourceLocation &RParenLoc) { 1911 assert(getLang().CPlusPlus && "Should only be called for C++!"); 1912 assert(ExprType == CastExpr && "Compound literals are not ambiguous!"); 1913 assert(isTypeIdInParens() && "Not a type-id!"); 1914 1915 ExprResult Result(true); 1916 CastTy = ParsedType(); 1917 1918 // We need to disambiguate a very ugly part of the C++ syntax: 1919 // 1920 // (T())x; - type-id 1921 // (T())*x; - type-id 1922 // (T())/x; - expression 1923 // (T()); - expression 1924 // 1925 // The bad news is that we cannot use the specialized tentative parser, since 1926 // it can only verify that the thing inside the parens can be parsed as 1927 // type-id, it is not useful for determining the context past the parens. 1928 // 1929 // The good news is that the parser can disambiguate this part without 1930 // making any unnecessary Action calls. 1931 // 1932 // It uses a scheme similar to parsing inline methods. The parenthesized 1933 // tokens are cached, the context that follows is determined (possibly by 1934 // parsing a cast-expression), and then we re-introduce the cached tokens 1935 // into the token stream and parse them appropriately. 1936 1937 ParenParseOption ParseAs; 1938 CachedTokens Toks; 1939 1940 // Store the tokens of the parentheses. We will parse them after we determine 1941 // the context that follows them. 1942 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) { 1943 // We didn't find the ')' we expected. 1944 MatchRHSPunctuation(tok::r_paren, LParenLoc); 1945 return ExprError(); 1946 } 1947 1948 if (Tok.is(tok::l_brace)) { 1949 ParseAs = CompoundLiteral; 1950 } else { 1951 bool NotCastExpr; 1952 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression 1953 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) { 1954 NotCastExpr = true; 1955 } else { 1956 // Try parsing the cast-expression that may follow. 1957 // If it is not a cast-expression, NotCastExpr will be true and no token 1958 // will be consumed. 1959 Result = ParseCastExpression(false/*isUnaryExpression*/, 1960 false/*isAddressofOperand*/, 1961 NotCastExpr, 1962 ParsedType()/*TypeOfCast*/); 1963 } 1964 1965 // If we parsed a cast-expression, it's really a type-id, otherwise it's 1966 // an expression. 1967 ParseAs = NotCastExpr ? SimpleExpr : CastExpr; 1968 } 1969 1970 // The current token should go after the cached tokens. 1971 Toks.push_back(Tok); 1972 // Re-enter the stored parenthesized tokens into the token stream, so we may 1973 // parse them now. 1974 PP.EnterTokenStream(Toks.data(), Toks.size(), 1975 true/*DisableMacroExpansion*/, false/*OwnsTokens*/); 1976 // Drop the current token and bring the first cached one. It's the same token 1977 // as when we entered this function. 1978 ConsumeAnyToken(); 1979 1980 if (ParseAs >= CompoundLiteral) { 1981 TypeResult Ty = ParseTypeName(); 1982 1983 // Match the ')'. 1984 if (Tok.is(tok::r_paren)) 1985 RParenLoc = ConsumeParen(); 1986 else 1987 MatchRHSPunctuation(tok::r_paren, LParenLoc); 1988 1989 if (ParseAs == CompoundLiteral) { 1990 ExprType = CompoundLiteral; 1991 return ParseCompoundLiteralExpression(Ty.get(), LParenLoc, RParenLoc); 1992 } 1993 1994 // We parsed '(' type-id ')' and the thing after it wasn't a '{'. 1995 assert(ParseAs == CastExpr); 1996 1997 if (Ty.isInvalid()) 1998 return ExprError(); 1999 2000 CastTy = Ty.get(); 2001 2002 // Result is what ParseCastExpression returned earlier. 2003 if (!Result.isInvalid()) 2004 Result = Actions.ActOnCastExpr(getCurScope(), LParenLoc, CastTy, RParenLoc, 2005 Result.take()); 2006 return move(Result); 2007 } 2008 2009 // Not a compound literal, and not followed by a cast-expression. 2010 assert(ParseAs == SimpleExpr); 2011 2012 ExprType = SimpleExpr; 2013 Result = ParseExpression(); 2014 if (!Result.isInvalid() && Tok.is(tok::r_paren)) 2015 Result = Actions.ActOnParenExpr(LParenLoc, Tok.getLocation(), Result.take()); 2016 2017 // Match the ')'. 2018 if (Result.isInvalid()) { 2019 SkipUntil(tok::r_paren); 2020 return ExprError(); 2021 } 2022 2023 if (Tok.is(tok::r_paren)) 2024 RParenLoc = ConsumeParen(); 2025 else 2026 MatchRHSPunctuation(tok::r_paren, LParenLoc); 2027 2028 return move(Result); 2029} 2030