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