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