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