ParseExprCXX.cpp revision 62ec1f2fd7368542bb926c04797fb07023547694
1//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the Expression parsing implementation for C++. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Parse/ParseDiagnostic.h" 15#include "clang/Parse/Parser.h" 16#include "RAIIObjectsForParser.h" 17#include "clang/Sema/DeclSpec.h" 18#include "clang/Sema/Scope.h" 19#include "clang/Sema/ParsedTemplate.h" 20#include "llvm/Support/ErrorHandling.h" 21 22using namespace clang; 23 24static int SelectDigraphErrorMessage(tok::TokenKind Kind) { 25 switch (Kind) { 26 case tok::kw_template: return 0; 27 case tok::kw_const_cast: return 1; 28 case tok::kw_dynamic_cast: return 2; 29 case tok::kw_reinterpret_cast: return 3; 30 case tok::kw_static_cast: return 4; 31 default: 32 assert(0 && "Unknown type for digraph error message."); 33 return -1; 34 } 35} 36 37// Are the two tokens adjacent in the same source file? 38static bool AreTokensAdjacent(Preprocessor &PP, Token &First, Token &Second) { 39 SourceManager &SM = PP.getSourceManager(); 40 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation()); 41 SourceLocation FirstEnd = FirstLoc.getFileLocWithOffset(First.getLength()); 42 return FirstEnd == SM.getSpellingLoc(Second.getLocation()); 43} 44 45// Suggest fixit for "<::" after a cast. 46static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken, 47 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) { 48 // Pull '<:' and ':' off token stream. 49 if (!AtDigraph) 50 PP.Lex(DigraphToken); 51 PP.Lex(ColonToken); 52 53 SourceRange Range; 54 Range.setBegin(DigraphToken.getLocation()); 55 Range.setEnd(ColonToken.getLocation()); 56 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph) 57 << SelectDigraphErrorMessage(Kind) 58 << FixItHint::CreateReplacement(Range, "< ::"); 59 60 // Update token information to reflect their change in token type. 61 ColonToken.setKind(tok::coloncolon); 62 ColonToken.setLocation(ColonToken.getLocation().getFileLocWithOffset(-1)); 63 ColonToken.setLength(2); 64 DigraphToken.setKind(tok::less); 65 DigraphToken.setLength(1); 66 67 // Push new tokens back to token stream. 68 PP.EnterToken(ColonToken); 69 if (!AtDigraph) 70 PP.EnterToken(DigraphToken); 71} 72 73/// \brief Parse global scope or nested-name-specifier if present. 74/// 75/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which 76/// may be preceded by '::'). Note that this routine will not parse ::new or 77/// ::delete; it will just leave them in the token stream. 78/// 79/// '::'[opt] nested-name-specifier 80/// '::' 81/// 82/// nested-name-specifier: 83/// type-name '::' 84/// namespace-name '::' 85/// nested-name-specifier identifier '::' 86/// nested-name-specifier 'template'[opt] simple-template-id '::' 87/// 88/// 89/// \param SS the scope specifier that will be set to the parsed 90/// nested-name-specifier (or empty) 91/// 92/// \param ObjectType if this nested-name-specifier is being parsed following 93/// the "." or "->" of a member access expression, this parameter provides the 94/// type of the object whose members are being accessed. 95/// 96/// \param EnteringContext whether we will be entering into the context of 97/// the nested-name-specifier after parsing it. 98/// 99/// \param MayBePseudoDestructor When non-NULL, points to a flag that 100/// indicates whether this nested-name-specifier may be part of a 101/// pseudo-destructor name. In this case, the flag will be set false 102/// if we don't actually end up parsing a destructor name. Moreorover, 103/// if we do end up determining that we are parsing a destructor name, 104/// the last component of the nested-name-specifier is not parsed as 105/// part of the scope specifier. 106 107/// member access expression, e.g., the \p T:: in \p p->T::m. 108/// 109/// \returns true if there was an error parsing a scope specifier 110bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, 111 ParsedType ObjectType, 112 bool EnteringContext, 113 bool *MayBePseudoDestructor, 114 bool IsTypename) { 115 assert(getLang().CPlusPlus && 116 "Call sites of this function should be guarded by checking for C++"); 117 118 if (Tok.is(tok::annot_cxxscope)) { 119 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), 120 Tok.getAnnotationRange(), 121 SS); 122 ConsumeToken(); 123 return false; 124 } 125 126 bool HasScopeSpecifier = false; 127 128 if (Tok.is(tok::coloncolon)) { 129 // ::new and ::delete aren't nested-name-specifiers. 130 tok::TokenKind NextKind = NextToken().getKind(); 131 if (NextKind == tok::kw_new || NextKind == tok::kw_delete) 132 return false; 133 134 // '::' - Global scope qualifier. 135 if (Actions.ActOnCXXGlobalScopeSpecifier(getCurScope(), ConsumeToken(), SS)) 136 return true; 137 138 HasScopeSpecifier = true; 139 } 140 141 bool CheckForDestructor = false; 142 if (MayBePseudoDestructor && *MayBePseudoDestructor) { 143 CheckForDestructor = true; 144 *MayBePseudoDestructor = false; 145 } 146 147 while (true) { 148 if (HasScopeSpecifier) { 149 // C++ [basic.lookup.classref]p5: 150 // If the qualified-id has the form 151 // 152 // ::class-name-or-namespace-name::... 153 // 154 // the class-name-or-namespace-name is looked up in global scope as a 155 // class-name or namespace-name. 156 // 157 // To implement this, we clear out the object type as soon as we've 158 // seen a leading '::' or part of a nested-name-specifier. 159 ObjectType = ParsedType(); 160 161 if (Tok.is(tok::code_completion)) { 162 // Code completion for a nested-name-specifier, where the code 163 // code completion token follows the '::'. 164 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext); 165 // Include code completion token into the range of the scope otherwise 166 // when we try to annotate the scope tokens the dangling code completion 167 // token will cause assertion in 168 // Preprocessor::AnnotatePreviousCachedTokens. 169 SS.setEndLoc(Tok.getLocation()); 170 cutOffParsing(); 171 return true; 172 } 173 } 174 175 // nested-name-specifier: 176 // nested-name-specifier 'template'[opt] simple-template-id '::' 177 178 // Parse the optional 'template' keyword, then make sure we have 179 // 'identifier <' after it. 180 if (Tok.is(tok::kw_template)) { 181 // If we don't have a scope specifier or an object type, this isn't a 182 // nested-name-specifier, since they aren't allowed to start with 183 // 'template'. 184 if (!HasScopeSpecifier && !ObjectType) 185 break; 186 187 TentativeParsingAction TPA(*this); 188 SourceLocation TemplateKWLoc = ConsumeToken(); 189 190 UnqualifiedId TemplateName; 191 if (Tok.is(tok::identifier)) { 192 // Consume the identifier. 193 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 194 ConsumeToken(); 195 } else if (Tok.is(tok::kw_operator)) { 196 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, 197 TemplateName)) { 198 TPA.Commit(); 199 break; 200 } 201 202 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId && 203 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) { 204 Diag(TemplateName.getSourceRange().getBegin(), 205 diag::err_id_after_template_in_nested_name_spec) 206 << TemplateName.getSourceRange(); 207 TPA.Commit(); 208 break; 209 } 210 } else { 211 TPA.Revert(); 212 break; 213 } 214 215 // If the next token is not '<', we have a qualified-id that refers 216 // to a template name, such as T::template apply, but is not a 217 // template-id. 218 if (Tok.isNot(tok::less)) { 219 TPA.Revert(); 220 break; 221 } 222 223 // Commit to parsing the template-id. 224 TPA.Commit(); 225 TemplateTy Template; 226 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(getCurScope(), 227 TemplateKWLoc, 228 SS, 229 TemplateName, 230 ObjectType, 231 EnteringContext, 232 Template)) { 233 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName, 234 TemplateKWLoc, false)) 235 return true; 236 } else 237 return true; 238 239 continue; 240 } 241 242 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) { 243 // We have 244 // 245 // simple-template-id '::' 246 // 247 // So we need to check whether the simple-template-id is of the 248 // right kind (it should name a type or be dependent), and then 249 // convert it into a type within the nested-name-specifier. 250 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 251 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) { 252 *MayBePseudoDestructor = true; 253 return false; 254 } 255 256 // Consume the template-id token. 257 ConsumeToken(); 258 259 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!"); 260 SourceLocation CCLoc = ConsumeToken(); 261 262 if (!HasScopeSpecifier) 263 HasScopeSpecifier = true; 264 265 ASTTemplateArgsPtr TemplateArgsPtr(Actions, 266 TemplateId->getTemplateArgs(), 267 TemplateId->NumArgs); 268 269 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), 270 /*FIXME:*/SourceLocation(), 271 SS, 272 TemplateId->Template, 273 TemplateId->TemplateNameLoc, 274 TemplateId->LAngleLoc, 275 TemplateArgsPtr, 276 TemplateId->RAngleLoc, 277 CCLoc, 278 EnteringContext)) { 279 SourceLocation StartLoc 280 = SS.getBeginLoc().isValid()? SS.getBeginLoc() 281 : TemplateId->TemplateNameLoc; 282 SS.SetInvalid(SourceRange(StartLoc, CCLoc)); 283 } 284 285 continue; 286 } 287 288 289 // The rest of the nested-name-specifier possibilities start with 290 // tok::identifier. 291 if (Tok.isNot(tok::identifier)) 292 break; 293 294 IdentifierInfo &II = *Tok.getIdentifierInfo(); 295 296 // nested-name-specifier: 297 // type-name '::' 298 // namespace-name '::' 299 // nested-name-specifier identifier '::' 300 Token Next = NextToken(); 301 302 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover 303 // and emit a fixit hint for it. 304 if (Next.is(tok::colon) && !ColonIsSacred) { 305 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II, 306 Tok.getLocation(), 307 Next.getLocation(), ObjectType, 308 EnteringContext) && 309 // If the token after the colon isn't an identifier, it's still an 310 // error, but they probably meant something else strange so don't 311 // recover like this. 312 PP.LookAhead(1).is(tok::identifier)) { 313 Diag(Next, diag::err_unexected_colon_in_nested_name_spec) 314 << FixItHint::CreateReplacement(Next.getLocation(), "::"); 315 316 // Recover as if the user wrote '::'. 317 Next.setKind(tok::coloncolon); 318 } 319 } 320 321 if (Next.is(tok::coloncolon)) { 322 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) && 323 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(), 324 II, ObjectType)) { 325 *MayBePseudoDestructor = true; 326 return false; 327 } 328 329 // We have an identifier followed by a '::'. Lookup this name 330 // as the name in a nested-name-specifier. 331 SourceLocation IdLoc = ConsumeToken(); 332 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) && 333 "NextToken() not working properly!"); 334 SourceLocation CCLoc = ConsumeToken(); 335 336 HasScopeSpecifier = true; 337 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc, 338 ObjectType, EnteringContext, SS)) 339 SS.SetInvalid(SourceRange(IdLoc, CCLoc)); 340 341 continue; 342 } 343 344 // Check for '<::' which should be '< ::' instead of '[:' when following 345 // a template name. 346 if (Next.is(tok::l_square) && Next.getLength() == 2) { 347 Token SecondToken = GetLookAheadToken(2); 348 if (SecondToken.is(tok::colon) && 349 AreTokensAdjacent(PP, Next, SecondToken)) { 350 TemplateTy Template; 351 UnqualifiedId TemplateName; 352 TemplateName.setIdentifier(&II, Tok.getLocation()); 353 bool MemberOfUnknownSpecialization; 354 if (Actions.isTemplateName(getCurScope(), SS, 355 /*hasTemplateKeyword=*/false, 356 TemplateName, 357 ObjectType, 358 EnteringContext, 359 Template, 360 MemberOfUnknownSpecialization)) { 361 FixDigraph(*this, PP, Next, SecondToken, tok::kw_template, 362 /*AtDigraph*/false); 363 } 364 } 365 } 366 367 // nested-name-specifier: 368 // type-name '<' 369 if (Next.is(tok::less)) { 370 TemplateTy Template; 371 UnqualifiedId TemplateName; 372 TemplateName.setIdentifier(&II, Tok.getLocation()); 373 bool MemberOfUnknownSpecialization; 374 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS, 375 /*hasTemplateKeyword=*/false, 376 TemplateName, 377 ObjectType, 378 EnteringContext, 379 Template, 380 MemberOfUnknownSpecialization)) { 381 // We have found a template name, so annotate this this token 382 // with a template-id annotation. We do not permit the 383 // template-id to be translated into a type annotation, 384 // because some clients (e.g., the parsing of class template 385 // specializations) still want to see the original template-id 386 // token. 387 ConsumeToken(); 388 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName, 389 SourceLocation(), false)) 390 return true; 391 continue; 392 } 393 394 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) && 395 (IsTypename || IsTemplateArgumentList(1))) { 396 // We have something like t::getAs<T>, where getAs is a 397 // member of an unknown specialization. However, this will only 398 // parse correctly as a template, so suggest the keyword 'template' 399 // before 'getAs' and treat this as a dependent template name. 400 unsigned DiagID = diag::err_missing_dependent_template_keyword; 401 if (getLang().MicrosoftExt) 402 DiagID = diag::warn_missing_dependent_template_keyword; 403 404 Diag(Tok.getLocation(), DiagID) 405 << II.getName() 406 << FixItHint::CreateInsertion(Tok.getLocation(), "template "); 407 408 if (TemplateNameKind TNK 409 = Actions.ActOnDependentTemplateName(getCurScope(), 410 Tok.getLocation(), SS, 411 TemplateName, ObjectType, 412 EnteringContext, Template)) { 413 // Consume the identifier. 414 ConsumeToken(); 415 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName, 416 SourceLocation(), false)) 417 return true; 418 } 419 else 420 return true; 421 422 continue; 423 } 424 } 425 426 // We don't have any tokens that form the beginning of a 427 // nested-name-specifier, so we're done. 428 break; 429 } 430 431 // Even if we didn't see any pieces of a nested-name-specifier, we 432 // still check whether there is a tilde in this position, which 433 // indicates a potential pseudo-destructor. 434 if (CheckForDestructor && Tok.is(tok::tilde)) 435 *MayBePseudoDestructor = true; 436 437 return false; 438} 439 440/// ParseCXXIdExpression - Handle id-expression. 441/// 442/// id-expression: 443/// unqualified-id 444/// qualified-id 445/// 446/// qualified-id: 447/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id 448/// '::' identifier 449/// '::' operator-function-id 450/// '::' template-id 451/// 452/// NOTE: The standard specifies that, for qualified-id, the parser does not 453/// expect: 454/// 455/// '::' conversion-function-id 456/// '::' '~' class-name 457/// 458/// This may cause a slight inconsistency on diagnostics: 459/// 460/// class C {}; 461/// namespace A {} 462/// void f() { 463/// :: A :: ~ C(); // Some Sema error about using destructor with a 464/// // namespace. 465/// :: ~ C(); // Some Parser error like 'unexpected ~'. 466/// } 467/// 468/// We simplify the parser a bit and make it work like: 469/// 470/// qualified-id: 471/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id 472/// '::' unqualified-id 473/// 474/// That way Sema can handle and report similar errors for namespaces and the 475/// global scope. 476/// 477/// The isAddressOfOperand parameter indicates that this id-expression is a 478/// direct operand of the address-of operator. This is, besides member contexts, 479/// the only place where a qualified-id naming a non-static class member may 480/// appear. 481/// 482ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) { 483 // qualified-id: 484 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id 485 // '::' unqualified-id 486 // 487 CXXScopeSpec SS; 488 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false); 489 490 UnqualifiedId Name; 491 if (ParseUnqualifiedId(SS, 492 /*EnteringContext=*/false, 493 /*AllowDestructorName=*/false, 494 /*AllowConstructorName=*/false, 495 /*ObjectType=*/ ParsedType(), 496 Name)) 497 return ExprError(); 498 499 // This is only the direct operand of an & operator if it is not 500 // followed by a postfix-expression suffix. 501 if (isAddressOfOperand && isPostfixExpressionSuffixStart()) 502 isAddressOfOperand = false; 503 504 return Actions.ActOnIdExpression(getCurScope(), SS, Name, Tok.is(tok::l_paren), 505 isAddressOfOperand); 506 507} 508 509/// ParseLambdaExpression - Parse a C++0x lambda expression. 510/// 511/// lambda-expression: 512/// lambda-introducer lambda-declarator[opt] compound-statement 513/// 514/// lambda-introducer: 515/// '[' lambda-capture[opt] ']' 516/// 517/// lambda-capture: 518/// capture-default 519/// capture-list 520/// capture-default ',' capture-list 521/// 522/// capture-default: 523/// '&' 524/// '=' 525/// 526/// capture-list: 527/// capture 528/// capture-list ',' capture 529/// 530/// capture: 531/// identifier 532/// '&' identifier 533/// 'this' 534/// 535/// lambda-declarator: 536/// '(' parameter-declaration-clause ')' attribute-specifier[opt] 537/// 'mutable'[opt] exception-specification[opt] 538/// trailing-return-type[opt] 539/// 540ExprResult Parser::ParseLambdaExpression() { 541 // Parse lambda-introducer. 542 LambdaIntroducer Intro; 543 544 llvm::Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro)); 545 if (DiagID) { 546 Diag(Tok, DiagID.getValue()); 547 SkipUntil(tok::r_square); 548 } 549 550 return ParseLambdaExpressionAfterIntroducer(Intro); 551} 552 553/// TryParseLambdaExpression - Use lookahead and potentially tentative 554/// parsing to determine if we are looking at a C++0x lambda expression, and parse 555/// it if we are. 556/// 557/// If we are not looking at a lambda expression, returns ExprError(). 558ExprResult Parser::TryParseLambdaExpression() { 559 assert(getLang().CPlusPlus0x 560 && Tok.is(tok::l_square) 561 && "Not at the start of a possible lambda expression."); 562 563 const Token Next = NextToken(), After = GetLookAheadToken(2); 564 565 // If lookahead indicates this is a lambda... 566 if (Next.is(tok::r_square) || // [] 567 Next.is(tok::equal) || // [= 568 (Next.is(tok::amp) && // [&] or [&, 569 (After.is(tok::r_square) || 570 After.is(tok::comma))) || 571 (Next.is(tok::identifier) && // [identifier] 572 After.is(tok::r_square))) { 573 return ParseLambdaExpression(); 574 } 575 576 // If lookahead indicates this is an Objective-C message... 577 if (Next.is(tok::identifier) && After.is(tok::identifier)) { 578 return ExprError(); 579 } 580 581 LambdaIntroducer Intro; 582 if (TryParseLambdaIntroducer(Intro)) 583 return ExprError(); 584 return ParseLambdaExpressionAfterIntroducer(Intro); 585} 586 587/// ParseLambdaExpression - Parse a lambda introducer. 588/// 589/// Returns a DiagnosticID if it hit something unexpected. 590llvm::Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro) { 591 typedef llvm::Optional<unsigned> DiagResult; 592 593 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['."); 594 Intro.Range.setBegin(ConsumeBracket()); 595 596 bool first = true; 597 598 // Parse capture-default. 599 if (Tok.is(tok::amp) && 600 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) { 601 Intro.Default = LCD_ByRef; 602 ConsumeToken(); 603 first = false; 604 } else if (Tok.is(tok::equal)) { 605 Intro.Default = LCD_ByCopy; 606 ConsumeToken(); 607 first = false; 608 } 609 610 while (Tok.isNot(tok::r_square)) { 611 if (!first) { 612 if (Tok.isNot(tok::comma)) 613 return DiagResult(diag::err_expected_comma_or_rsquare); 614 ConsumeToken(); 615 } 616 617 first = false; 618 619 // Parse capture. 620 LambdaCaptureKind Kind = LCK_ByCopy; 621 SourceLocation Loc; 622 IdentifierInfo* Id = 0; 623 624 if (Tok.is(tok::kw_this)) { 625 Kind = LCK_This; 626 Loc = ConsumeToken(); 627 } else { 628 if (Tok.is(tok::amp)) { 629 Kind = LCK_ByRef; 630 ConsumeToken(); 631 } 632 633 if (Tok.is(tok::identifier)) { 634 Id = Tok.getIdentifierInfo(); 635 Loc = ConsumeToken(); 636 } else if (Tok.is(tok::kw_this)) { 637 // FIXME: If we want to suggest a fixit here, will need to return more 638 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be 639 // Clear()ed to prevent emission in case of tentative parsing? 640 return DiagResult(diag::err_this_captured_by_reference); 641 } else { 642 return DiagResult(diag::err_expected_capture); 643 } 644 } 645 646 Intro.addCapture(Kind, Loc, Id); 647 } 648 649 Intro.Range.setEnd(MatchRHSPunctuation(tok::r_square, 650 Intro.Range.getBegin())); 651 652 return DiagResult(); 653} 654 655/// TryParseLambdaExpression - Tentatively parse a lambda introducer. 656/// 657/// Returns true if it hit something unexpected. 658bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) { 659 TentativeParsingAction PA(*this); 660 661 llvm::Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro)); 662 663 if (DiagID) { 664 PA.Revert(); 665 return true; 666 } 667 668 PA.Commit(); 669 return false; 670} 671 672/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda 673/// expression. 674ExprResult Parser::ParseLambdaExpressionAfterIntroducer( 675 LambdaIntroducer &Intro) { 676 // Parse lambda-declarator[opt]. 677 DeclSpec DS(AttrFactory); 678 Declarator D(DS, Declarator::PrototypeContext); 679 680 if (Tok.is(tok::l_paren)) { 681 ParseScope PrototypeScope(this, 682 Scope::FunctionPrototypeScope | 683 Scope::DeclScope); 684 685 SourceLocation DeclLoc = ConsumeParen(), DeclEndLoc; 686 687 // Parse parameter-declaration-clause. 688 ParsedAttributes Attr(AttrFactory); 689 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 690 SourceLocation EllipsisLoc; 691 692 if (Tok.isNot(tok::r_paren)) 693 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc); 694 695 DeclEndLoc = MatchRHSPunctuation(tok::r_paren, DeclLoc); 696 697 // Parse 'mutable'[opt]. 698 SourceLocation MutableLoc; 699 if (Tok.is(tok::kw_mutable)) { 700 MutableLoc = ConsumeToken(); 701 DeclEndLoc = MutableLoc; 702 } 703 704 // Parse exception-specification[opt]. 705 ExceptionSpecificationType ESpecType = EST_None; 706 SourceRange ESpecRange; 707 llvm::SmallVector<ParsedType, 2> DynamicExceptions; 708 llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges; 709 ExprResult NoexceptExpr; 710 ESpecType = MaybeParseExceptionSpecification(ESpecRange, 711 DynamicExceptions, 712 DynamicExceptionRanges, 713 NoexceptExpr); 714 715 if (ESpecType != EST_None) 716 DeclEndLoc = ESpecRange.getEnd(); 717 718 // Parse attribute-specifier[opt]. 719 MaybeParseCXX0XAttributes(Attr, &DeclEndLoc); 720 721 // Parse trailing-return-type[opt]. 722 ParsedType TrailingReturnType; 723 if (Tok.is(tok::arrow)) { 724 SourceRange Range; 725 TrailingReturnType = ParseTrailingReturnType(Range).get(); 726 if (Range.getEnd().isValid()) 727 DeclEndLoc = Range.getEnd(); 728 } 729 730 PrototypeScope.Exit(); 731 732 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true, 733 /*isVariadic=*/EllipsisLoc.isValid(), 734 EllipsisLoc, 735 ParamInfo.data(), ParamInfo.size(), 736 DS.getTypeQualifiers(), 737 /*RefQualifierIsLValueRef=*/true, 738 /*RefQualifierLoc=*/SourceLocation(), 739 MutableLoc, 740 ESpecType, ESpecRange.getBegin(), 741 DynamicExceptions.data(), 742 DynamicExceptionRanges.data(), 743 DynamicExceptions.size(), 744 NoexceptExpr.isUsable() ? 745 NoexceptExpr.get() : 0, 746 DeclLoc, DeclEndLoc, D, 747 TrailingReturnType), 748 Attr, DeclEndLoc); 749 } 750 751 // Parse compound-statement. 752 if (Tok.is(tok::l_brace)) { 753 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using 754 // it. 755 ParseScope BodyScope(this, Scope::BlockScope | Scope::FnScope | 756 Scope::BreakScope | Scope::ContinueScope | 757 Scope::DeclScope); 758 759 StmtResult Stmt(ParseCompoundStatementBody()); 760 761 BodyScope.Exit(); 762 } else { 763 Diag(Tok, diag::err_expected_lambda_body); 764 } 765 766 return ExprEmpty(); 767} 768 769/// ParseCXXCasts - This handles the various ways to cast expressions to another 770/// type. 771/// 772/// postfix-expression: [C++ 5.2p1] 773/// 'dynamic_cast' '<' type-name '>' '(' expression ')' 774/// 'static_cast' '<' type-name '>' '(' expression ')' 775/// 'reinterpret_cast' '<' type-name '>' '(' expression ')' 776/// 'const_cast' '<' type-name '>' '(' expression ')' 777/// 778ExprResult Parser::ParseCXXCasts() { 779 tok::TokenKind Kind = Tok.getKind(); 780 const char *CastName = 0; // For error messages 781 782 switch (Kind) { 783 default: assert(0 && "Unknown C++ cast!"); abort(); 784 case tok::kw_const_cast: CastName = "const_cast"; break; 785 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break; 786 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break; 787 case tok::kw_static_cast: CastName = "static_cast"; break; 788 } 789 790 SourceLocation OpLoc = ConsumeToken(); 791 SourceLocation LAngleBracketLoc = Tok.getLocation(); 792 793 // Check for "<::" which is parsed as "[:". If found, fix token stream, 794 // diagnose error, suggest fix, and recover parsing. 795 Token Next = NextToken(); 796 if (Tok.is(tok::l_square) && Tok.getLength() == 2 && Next.is(tok::colon) && 797 AreTokensAdjacent(PP, Tok, Next)) 798 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true); 799 800 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName)) 801 return ExprError(); 802 803 // Parse the common declaration-specifiers piece. 804 DeclSpec DS(AttrFactory); 805 ParseSpecifierQualifierList(DS); 806 807 // Parse the abstract-declarator, if present. 808 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 809 ParseDeclarator(DeclaratorInfo); 810 811 SourceLocation RAngleBracketLoc = Tok.getLocation(); 812 813 if (ExpectAndConsume(tok::greater, diag::err_expected_greater)) 814 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<"); 815 816 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; 817 818 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, CastName)) 819 return ExprError(); 820 821 ExprResult Result = ParseExpression(); 822 823 // Match the ')'. 824 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 825 826 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType()) 827 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind, 828 LAngleBracketLoc, DeclaratorInfo, 829 RAngleBracketLoc, 830 LParenLoc, Result.take(), RParenLoc); 831 832 return move(Result); 833} 834 835/// ParseCXXTypeid - This handles the C++ typeid expression. 836/// 837/// postfix-expression: [C++ 5.2p1] 838/// 'typeid' '(' expression ')' 839/// 'typeid' '(' type-id ')' 840/// 841ExprResult Parser::ParseCXXTypeid() { 842 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!"); 843 844 SourceLocation OpLoc = ConsumeToken(); 845 SourceLocation LParenLoc = Tok.getLocation(); 846 SourceLocation RParenLoc; 847 848 // typeid expressions are always parenthesized. 849 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 850 "typeid")) 851 return ExprError(); 852 853 ExprResult Result; 854 855 if (isTypeIdInParens()) { 856 TypeResult Ty = ParseTypeName(); 857 858 // Match the ')'. 859 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 860 861 if (Ty.isInvalid() || RParenLoc.isInvalid()) 862 return ExprError(); 863 864 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true, 865 Ty.get().getAsOpaquePtr(), RParenLoc); 866 } else { 867 // C++0x [expr.typeid]p3: 868 // When typeid is applied to an expression other than an lvalue of a 869 // polymorphic class type [...] The expression is an unevaluated 870 // operand (Clause 5). 871 // 872 // Note that we can't tell whether the expression is an lvalue of a 873 // polymorphic class type until after we've parsed the expression, so 874 // we the expression is potentially potentially evaluated. 875 EnterExpressionEvaluationContext Unevaluated(Actions, 876 Sema::PotentiallyPotentiallyEvaluated); 877 Result = ParseExpression(); 878 879 // Match the ')'. 880 if (Result.isInvalid()) 881 SkipUntil(tok::r_paren); 882 else { 883 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 884 if (RParenLoc.isInvalid()) 885 return ExprError(); 886 887 // If we are a foo<int> that identifies a single function, resolve it now... 888 Expr* e = Result.get(); 889 if (e->getType() == Actions.Context.OverloadTy) { 890 ExprResult er = 891 Actions.ResolveAndFixSingleFunctionTemplateSpecialization(e); 892 if (er.isUsable()) 893 Result = er.release(); 894 } 895 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false, 896 Result.release(), RParenLoc); 897 } 898 } 899 900 return move(Result); 901} 902 903/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression. 904/// 905/// '__uuidof' '(' expression ')' 906/// '__uuidof' '(' type-id ')' 907/// 908ExprResult Parser::ParseCXXUuidof() { 909 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!"); 910 911 SourceLocation OpLoc = ConsumeToken(); 912 SourceLocation LParenLoc = Tok.getLocation(); 913 SourceLocation RParenLoc; 914 915 // __uuidof expressions are always parenthesized. 916 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 917 "__uuidof")) 918 return ExprError(); 919 920 ExprResult Result; 921 922 if (isTypeIdInParens()) { 923 TypeResult Ty = ParseTypeName(); 924 925 // Match the ')'. 926 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 927 928 if (Ty.isInvalid()) 929 return ExprError(); 930 931 Result = Actions.ActOnCXXUuidof(OpLoc, LParenLoc, /*isType=*/true, 932 Ty.get().getAsOpaquePtr(), RParenLoc); 933 } else { 934 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 935 Result = ParseExpression(); 936 937 // Match the ')'. 938 if (Result.isInvalid()) 939 SkipUntil(tok::r_paren); 940 else { 941 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 942 943 Result = Actions.ActOnCXXUuidof(OpLoc, LParenLoc, /*isType=*/false, 944 Result.release(), RParenLoc); 945 } 946 } 947 948 return move(Result); 949} 950 951/// \brief Parse a C++ pseudo-destructor expression after the base, 952/// . or -> operator, and nested-name-specifier have already been 953/// parsed. 954/// 955/// postfix-expression: [C++ 5.2] 956/// postfix-expression . pseudo-destructor-name 957/// postfix-expression -> pseudo-destructor-name 958/// 959/// pseudo-destructor-name: 960/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name 961/// ::[opt] nested-name-specifier template simple-template-id :: 962/// ~type-name 963/// ::[opt] nested-name-specifier[opt] ~type-name 964/// 965ExprResult 966Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc, 967 tok::TokenKind OpKind, 968 CXXScopeSpec &SS, 969 ParsedType ObjectType) { 970 // We're parsing either a pseudo-destructor-name or a dependent 971 // member access that has the same form as a 972 // pseudo-destructor-name. We parse both in the same way and let 973 // the action model sort them out. 974 // 975 // Note that the ::[opt] nested-name-specifier[opt] has already 976 // been parsed, and if there was a simple-template-id, it has 977 // been coalesced into a template-id annotation token. 978 UnqualifiedId FirstTypeName; 979 SourceLocation CCLoc; 980 if (Tok.is(tok::identifier)) { 981 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 982 ConsumeToken(); 983 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"); 984 CCLoc = ConsumeToken(); 985 } else if (Tok.is(tok::annot_template_id)) { 986 FirstTypeName.setTemplateId( 987 (TemplateIdAnnotation *)Tok.getAnnotationValue()); 988 ConsumeToken(); 989 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"); 990 CCLoc = ConsumeToken(); 991 } else { 992 FirstTypeName.setIdentifier(0, SourceLocation()); 993 } 994 995 // Parse the tilde. 996 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail"); 997 SourceLocation TildeLoc = ConsumeToken(); 998 if (!Tok.is(tok::identifier)) { 999 Diag(Tok, diag::err_destructor_tilde_identifier); 1000 return ExprError(); 1001 } 1002 1003 // Parse the second type. 1004 UnqualifiedId SecondTypeName; 1005 IdentifierInfo *Name = Tok.getIdentifierInfo(); 1006 SourceLocation NameLoc = ConsumeToken(); 1007 SecondTypeName.setIdentifier(Name, NameLoc); 1008 1009 // If there is a '<', the second type name is a template-id. Parse 1010 // it as such. 1011 if (Tok.is(tok::less) && 1012 ParseUnqualifiedIdTemplateId(SS, Name, NameLoc, false, ObjectType, 1013 SecondTypeName, /*AssumeTemplateName=*/true, 1014 /*TemplateKWLoc*/SourceLocation())) 1015 return ExprError(); 1016 1017 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, 1018 OpLoc, OpKind, 1019 SS, FirstTypeName, CCLoc, 1020 TildeLoc, SecondTypeName, 1021 Tok.is(tok::l_paren)); 1022} 1023 1024/// ParseCXXBoolLiteral - This handles the C++ Boolean literals. 1025/// 1026/// boolean-literal: [C++ 2.13.5] 1027/// 'true' 1028/// 'false' 1029ExprResult Parser::ParseCXXBoolLiteral() { 1030 tok::TokenKind Kind = Tok.getKind(); 1031 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind); 1032} 1033 1034/// ParseThrowExpression - This handles the C++ throw expression. 1035/// 1036/// throw-expression: [C++ 15] 1037/// 'throw' assignment-expression[opt] 1038ExprResult Parser::ParseThrowExpression() { 1039 assert(Tok.is(tok::kw_throw) && "Not throw!"); 1040 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token. 1041 1042 // If the current token isn't the start of an assignment-expression, 1043 // then the expression is not present. This handles things like: 1044 // "C ? throw : (void)42", which is crazy but legal. 1045 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common. 1046 case tok::semi: 1047 case tok::r_paren: 1048 case tok::r_square: 1049 case tok::r_brace: 1050 case tok::colon: 1051 case tok::comma: 1052 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, 0); 1053 1054 default: 1055 ExprResult Expr(ParseAssignmentExpression()); 1056 if (Expr.isInvalid()) return move(Expr); 1057 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.take()); 1058 } 1059} 1060 1061/// ParseCXXThis - This handles the C++ 'this' pointer. 1062/// 1063/// C++ 9.3.2: In the body of a non-static member function, the keyword this is 1064/// a non-lvalue expression whose value is the address of the object for which 1065/// the function is called. 1066ExprResult Parser::ParseCXXThis() { 1067 assert(Tok.is(tok::kw_this) && "Not 'this'!"); 1068 SourceLocation ThisLoc = ConsumeToken(); 1069 return Actions.ActOnCXXThis(ThisLoc); 1070} 1071 1072/// ParseCXXTypeConstructExpression - Parse construction of a specified type. 1073/// Can be interpreted either as function-style casting ("int(x)") 1074/// or class type construction ("ClassType(x,y,z)") 1075/// or creation of a value-initialized type ("int()"). 1076/// See [C++ 5.2.3]. 1077/// 1078/// postfix-expression: [C++ 5.2p1] 1079/// simple-type-specifier '(' expression-list[opt] ')' 1080/// [C++0x] simple-type-specifier braced-init-list 1081/// typename-specifier '(' expression-list[opt] ')' 1082/// [C++0x] typename-specifier braced-init-list 1083/// 1084ExprResult 1085Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) { 1086 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 1087 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get(); 1088 1089 assert((Tok.is(tok::l_paren) || 1090 (getLang().CPlusPlus0x && Tok.is(tok::l_brace))) 1091 && "Expected '(' or '{'!"); 1092 1093 if (Tok.is(tok::l_brace)) { 1094 1095 // FIXME: Convert to a proper type construct expression. 1096 return ParseBraceInitializer(); 1097 1098 } else { 1099 GreaterThanIsOperatorScope G(GreaterThanIsOperator, true); 1100 1101 SourceLocation LParenLoc = ConsumeParen(); 1102 1103 ExprVector Exprs(Actions); 1104 CommaLocsTy CommaLocs; 1105 1106 if (Tok.isNot(tok::r_paren)) { 1107 if (ParseExpressionList(Exprs, CommaLocs)) { 1108 SkipUntil(tok::r_paren); 1109 return ExprError(); 1110 } 1111 } 1112 1113 // Match the ')'. 1114 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1115 1116 // TypeRep could be null, if it references an invalid typedef. 1117 if (!TypeRep) 1118 return ExprError(); 1119 1120 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&& 1121 "Unexpected number of commas!"); 1122 return Actions.ActOnCXXTypeConstructExpr(TypeRep, LParenLoc, move_arg(Exprs), 1123 RParenLoc); 1124 } 1125} 1126 1127/// ParseCXXCondition - if/switch/while condition expression. 1128/// 1129/// condition: 1130/// expression 1131/// type-specifier-seq declarator '=' assignment-expression 1132/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt] 1133/// '=' assignment-expression 1134/// 1135/// \param ExprResult if the condition was parsed as an expression, the 1136/// parsed expression. 1137/// 1138/// \param DeclResult if the condition was parsed as a declaration, the 1139/// parsed declaration. 1140/// 1141/// \param Loc The location of the start of the statement that requires this 1142/// condition, e.g., the "for" in a for loop. 1143/// 1144/// \param ConvertToBoolean Whether the condition expression should be 1145/// converted to a boolean value. 1146/// 1147/// \returns true if there was a parsing, false otherwise. 1148bool Parser::ParseCXXCondition(ExprResult &ExprOut, 1149 Decl *&DeclOut, 1150 SourceLocation Loc, 1151 bool ConvertToBoolean) { 1152 if (Tok.is(tok::code_completion)) { 1153 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition); 1154 cutOffParsing(); 1155 return true; 1156 } 1157 1158 if (!isCXXConditionDeclaration()) { 1159 // Parse the expression. 1160 ExprOut = ParseExpression(); // expression 1161 DeclOut = 0; 1162 if (ExprOut.isInvalid()) 1163 return true; 1164 1165 // If required, convert to a boolean value. 1166 if (ConvertToBoolean) 1167 ExprOut 1168 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get()); 1169 return ExprOut.isInvalid(); 1170 } 1171 1172 // type-specifier-seq 1173 DeclSpec DS(AttrFactory); 1174 ParseSpecifierQualifierList(DS); 1175 1176 // declarator 1177 Declarator DeclaratorInfo(DS, Declarator::ConditionContext); 1178 ParseDeclarator(DeclaratorInfo); 1179 1180 // simple-asm-expr[opt] 1181 if (Tok.is(tok::kw_asm)) { 1182 SourceLocation Loc; 1183 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 1184 if (AsmLabel.isInvalid()) { 1185 SkipUntil(tok::semi); 1186 return true; 1187 } 1188 DeclaratorInfo.setAsmLabel(AsmLabel.release()); 1189 DeclaratorInfo.SetRangeEnd(Loc); 1190 } 1191 1192 // If attributes are present, parse them. 1193 MaybeParseGNUAttributes(DeclaratorInfo); 1194 1195 // Type-check the declaration itself. 1196 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(), 1197 DeclaratorInfo); 1198 DeclOut = Dcl.get(); 1199 ExprOut = ExprError(); 1200 1201 // '=' assignment-expression 1202 if (isTokenEqualOrMistypedEqualEqual( 1203 diag::err_invalid_equalequal_after_declarator)) { 1204 ConsumeToken(); 1205 ExprResult AssignExpr(ParseAssignmentExpression()); 1206 if (!AssignExpr.isInvalid()) 1207 Actions.AddInitializerToDecl(DeclOut, AssignExpr.take(), false, 1208 DS.getTypeSpecType() == DeclSpec::TST_auto); 1209 } else { 1210 // FIXME: C++0x allows a braced-init-list 1211 Diag(Tok, diag::err_expected_equal_after_declarator); 1212 } 1213 1214 // FIXME: Build a reference to this declaration? Convert it to bool? 1215 // (This is currently handled by Sema). 1216 1217 Actions.FinalizeDeclaration(DeclOut); 1218 1219 return false; 1220} 1221 1222/// \brief Determine whether the current token starts a C++ 1223/// simple-type-specifier. 1224bool Parser::isCXXSimpleTypeSpecifier() const { 1225 switch (Tok.getKind()) { 1226 case tok::annot_typename: 1227 case tok::kw_short: 1228 case tok::kw_long: 1229 case tok::kw___int64: 1230 case tok::kw_signed: 1231 case tok::kw_unsigned: 1232 case tok::kw_void: 1233 case tok::kw_char: 1234 case tok::kw_int: 1235 case tok::kw_float: 1236 case tok::kw_double: 1237 case tok::kw_wchar_t: 1238 case tok::kw_char16_t: 1239 case tok::kw_char32_t: 1240 case tok::kw_bool: 1241 case tok::kw_decltype: 1242 case tok::kw_typeof: 1243 case tok::kw___underlying_type: 1244 return true; 1245 1246 default: 1247 break; 1248 } 1249 1250 return false; 1251} 1252 1253/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. 1254/// This should only be called when the current token is known to be part of 1255/// simple-type-specifier. 1256/// 1257/// simple-type-specifier: 1258/// '::'[opt] nested-name-specifier[opt] type-name 1259/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO] 1260/// char 1261/// wchar_t 1262/// bool 1263/// short 1264/// int 1265/// long 1266/// signed 1267/// unsigned 1268/// float 1269/// double 1270/// void 1271/// [GNU] typeof-specifier 1272/// [C++0x] auto [TODO] 1273/// 1274/// type-name: 1275/// class-name 1276/// enum-name 1277/// typedef-name 1278/// 1279void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { 1280 DS.SetRangeStart(Tok.getLocation()); 1281 const char *PrevSpec; 1282 unsigned DiagID; 1283 SourceLocation Loc = Tok.getLocation(); 1284 1285 switch (Tok.getKind()) { 1286 case tok::identifier: // foo::bar 1287 case tok::coloncolon: // ::foo::bar 1288 assert(0 && "Annotation token should already be formed!"); 1289 default: 1290 assert(0 && "Not a simple-type-specifier token!"); 1291 abort(); 1292 1293 // type-name 1294 case tok::annot_typename: { 1295 if (getTypeAnnotation(Tok)) 1296 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, 1297 getTypeAnnotation(Tok)); 1298 else 1299 DS.SetTypeSpecError(); 1300 1301 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1302 ConsumeToken(); 1303 1304 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 1305 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 1306 // Objective-C interface. If we don't have Objective-C or a '<', this is 1307 // just a normal reference to a typedef name. 1308 if (Tok.is(tok::less) && getLang().ObjC1) 1309 ParseObjCProtocolQualifiers(DS); 1310 1311 DS.Finish(Diags, PP); 1312 return; 1313 } 1314 1315 // builtin types 1316 case tok::kw_short: 1317 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID); 1318 break; 1319 case tok::kw_long: 1320 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID); 1321 break; 1322 case tok::kw___int64: 1323 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID); 1324 break; 1325 case tok::kw_signed: 1326 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID); 1327 break; 1328 case tok::kw_unsigned: 1329 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID); 1330 break; 1331 case tok::kw_void: 1332 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID); 1333 break; 1334 case tok::kw_char: 1335 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID); 1336 break; 1337 case tok::kw_int: 1338 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID); 1339 break; 1340 case tok::kw_float: 1341 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID); 1342 break; 1343 case tok::kw_double: 1344 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID); 1345 break; 1346 case tok::kw_wchar_t: 1347 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID); 1348 break; 1349 case tok::kw_char16_t: 1350 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID); 1351 break; 1352 case tok::kw_char32_t: 1353 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID); 1354 break; 1355 case tok::kw_bool: 1356 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID); 1357 break; 1358 1359 // FIXME: C++0x decltype support. 1360 // GNU typeof support. 1361 case tok::kw_typeof: 1362 ParseTypeofSpecifier(DS); 1363 DS.Finish(Diags, PP); 1364 return; 1365 } 1366 if (Tok.is(tok::annot_typename)) 1367 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1368 else 1369 DS.SetRangeEnd(Tok.getLocation()); 1370 ConsumeToken(); 1371 DS.Finish(Diags, PP); 1372} 1373 1374/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++ 1375/// [dcl.name]), which is a non-empty sequence of type-specifiers, 1376/// e.g., "const short int". Note that the DeclSpec is *not* finished 1377/// by parsing the type-specifier-seq, because these sequences are 1378/// typically followed by some form of declarator. Returns true and 1379/// emits diagnostics if this is not a type-specifier-seq, false 1380/// otherwise. 1381/// 1382/// type-specifier-seq: [C++ 8.1] 1383/// type-specifier type-specifier-seq[opt] 1384/// 1385bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) { 1386 DS.SetRangeStart(Tok.getLocation()); 1387 const char *PrevSpec = 0; 1388 unsigned DiagID; 1389 bool isInvalid = 0; 1390 1391 // Parse one or more of the type specifiers. 1392 if (!ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID, 1393 ParsedTemplateInfo(), /*SuppressDeclarations*/true)) { 1394 Diag(Tok, diag::err_expected_type); 1395 return true; 1396 } 1397 1398 while (ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID, 1399 ParsedTemplateInfo(), /*SuppressDeclarations*/true)) 1400 {} 1401 1402 DS.Finish(Diags, PP); 1403 return false; 1404} 1405 1406/// \brief Finish parsing a C++ unqualified-id that is a template-id of 1407/// some form. 1408/// 1409/// This routine is invoked when a '<' is encountered after an identifier or 1410/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine 1411/// whether the unqualified-id is actually a template-id. This routine will 1412/// then parse the template arguments and form the appropriate template-id to 1413/// return to the caller. 1414/// 1415/// \param SS the nested-name-specifier that precedes this template-id, if 1416/// we're actually parsing a qualified-id. 1417/// 1418/// \param Name for constructor and destructor names, this is the actual 1419/// identifier that may be a template-name. 1420/// 1421/// \param NameLoc the location of the class-name in a constructor or 1422/// destructor. 1423/// 1424/// \param EnteringContext whether we're entering the scope of the 1425/// nested-name-specifier. 1426/// 1427/// \param ObjectType if this unqualified-id occurs within a member access 1428/// expression, the type of the base object whose member is being accessed. 1429/// 1430/// \param Id as input, describes the template-name or operator-function-id 1431/// that precedes the '<'. If template arguments were parsed successfully, 1432/// will be updated with the template-id. 1433/// 1434/// \param AssumeTemplateId When true, this routine will assume that the name 1435/// refers to a template without performing name lookup to verify. 1436/// 1437/// \returns true if a parse error occurred, false otherwise. 1438bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, 1439 IdentifierInfo *Name, 1440 SourceLocation NameLoc, 1441 bool EnteringContext, 1442 ParsedType ObjectType, 1443 UnqualifiedId &Id, 1444 bool AssumeTemplateId, 1445 SourceLocation TemplateKWLoc) { 1446 assert((AssumeTemplateId || Tok.is(tok::less)) && 1447 "Expected '<' to finish parsing a template-id"); 1448 1449 TemplateTy Template; 1450 TemplateNameKind TNK = TNK_Non_template; 1451 switch (Id.getKind()) { 1452 case UnqualifiedId::IK_Identifier: 1453 case UnqualifiedId::IK_OperatorFunctionId: 1454 case UnqualifiedId::IK_LiteralOperatorId: 1455 if (AssumeTemplateId) { 1456 TNK = Actions.ActOnDependentTemplateName(getCurScope(), TemplateKWLoc, SS, 1457 Id, ObjectType, EnteringContext, 1458 Template); 1459 if (TNK == TNK_Non_template) 1460 return true; 1461 } else { 1462 bool MemberOfUnknownSpecialization; 1463 TNK = Actions.isTemplateName(getCurScope(), SS, 1464 TemplateKWLoc.isValid(), Id, 1465 ObjectType, EnteringContext, Template, 1466 MemberOfUnknownSpecialization); 1467 1468 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization && 1469 ObjectType && IsTemplateArgumentList()) { 1470 // We have something like t->getAs<T>(), where getAs is a 1471 // member of an unknown specialization. However, this will only 1472 // parse correctly as a template, so suggest the keyword 'template' 1473 // before 'getAs' and treat this as a dependent template name. 1474 std::string Name; 1475 if (Id.getKind() == UnqualifiedId::IK_Identifier) 1476 Name = Id.Identifier->getName(); 1477 else { 1478 Name = "operator "; 1479 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId) 1480 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator); 1481 else 1482 Name += Id.Identifier->getName(); 1483 } 1484 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword) 1485 << Name 1486 << FixItHint::CreateInsertion(Id.StartLocation, "template "); 1487 TNK = Actions.ActOnDependentTemplateName(getCurScope(), TemplateKWLoc, 1488 SS, Id, ObjectType, 1489 EnteringContext, Template); 1490 if (TNK == TNK_Non_template) 1491 return true; 1492 } 1493 } 1494 break; 1495 1496 case UnqualifiedId::IK_ConstructorName: { 1497 UnqualifiedId TemplateName; 1498 bool MemberOfUnknownSpecialization; 1499 TemplateName.setIdentifier(Name, NameLoc); 1500 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), 1501 TemplateName, ObjectType, 1502 EnteringContext, Template, 1503 MemberOfUnknownSpecialization); 1504 break; 1505 } 1506 1507 case UnqualifiedId::IK_DestructorName: { 1508 UnqualifiedId TemplateName; 1509 bool MemberOfUnknownSpecialization; 1510 TemplateName.setIdentifier(Name, NameLoc); 1511 if (ObjectType) { 1512 TNK = Actions.ActOnDependentTemplateName(getCurScope(), TemplateKWLoc, SS, 1513 TemplateName, ObjectType, 1514 EnteringContext, Template); 1515 if (TNK == TNK_Non_template) 1516 return true; 1517 } else { 1518 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), 1519 TemplateName, ObjectType, 1520 EnteringContext, Template, 1521 MemberOfUnknownSpecialization); 1522 1523 if (TNK == TNK_Non_template && !Id.DestructorName.get()) { 1524 Diag(NameLoc, diag::err_destructor_template_id) 1525 << Name << SS.getRange(); 1526 return true; 1527 } 1528 } 1529 break; 1530 } 1531 1532 default: 1533 return false; 1534 } 1535 1536 if (TNK == TNK_Non_template) 1537 return false; 1538 1539 // Parse the enclosed template argument list. 1540 SourceLocation LAngleLoc, RAngleLoc; 1541 TemplateArgList TemplateArgs; 1542 if (Tok.is(tok::less) && 1543 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation, 1544 SS, true, LAngleLoc, 1545 TemplateArgs, 1546 RAngleLoc)) 1547 return true; 1548 1549 if (Id.getKind() == UnqualifiedId::IK_Identifier || 1550 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId || 1551 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) { 1552 // Form a parsed representation of the template-id to be stored in the 1553 // UnqualifiedId. 1554 TemplateIdAnnotation *TemplateId 1555 = TemplateIdAnnotation::Allocate(TemplateArgs.size()); 1556 1557 if (Id.getKind() == UnqualifiedId::IK_Identifier) { 1558 TemplateId->Name = Id.Identifier; 1559 TemplateId->Operator = OO_None; 1560 TemplateId->TemplateNameLoc = Id.StartLocation; 1561 } else { 1562 TemplateId->Name = 0; 1563 TemplateId->Operator = Id.OperatorFunctionId.Operator; 1564 TemplateId->TemplateNameLoc = Id.StartLocation; 1565 } 1566 1567 TemplateId->SS = SS; 1568 TemplateId->Template = Template; 1569 TemplateId->Kind = TNK; 1570 TemplateId->LAngleLoc = LAngleLoc; 1571 TemplateId->RAngleLoc = RAngleLoc; 1572 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs(); 1573 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); 1574 Arg != ArgEnd; ++Arg) 1575 Args[Arg] = TemplateArgs[Arg]; 1576 1577 Id.setTemplateId(TemplateId); 1578 return false; 1579 } 1580 1581 // Bundle the template arguments together. 1582 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(), 1583 TemplateArgs.size()); 1584 1585 // Constructor and destructor names. 1586 TypeResult Type 1587 = Actions.ActOnTemplateIdType(SS, Template, NameLoc, 1588 LAngleLoc, TemplateArgsPtr, 1589 RAngleLoc); 1590 if (Type.isInvalid()) 1591 return true; 1592 1593 if (Id.getKind() == UnqualifiedId::IK_ConstructorName) 1594 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc); 1595 else 1596 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc); 1597 1598 return false; 1599} 1600 1601/// \brief Parse an operator-function-id or conversion-function-id as part 1602/// of a C++ unqualified-id. 1603/// 1604/// This routine is responsible only for parsing the operator-function-id or 1605/// conversion-function-id; it does not handle template arguments in any way. 1606/// 1607/// \code 1608/// operator-function-id: [C++ 13.5] 1609/// 'operator' operator 1610/// 1611/// operator: one of 1612/// new delete new[] delete[] 1613/// + - * / % ^ & | ~ 1614/// ! = < > += -= *= /= %= 1615/// ^= &= |= << >> >>= <<= == != 1616/// <= >= && || ++ -- , ->* -> 1617/// () [] 1618/// 1619/// conversion-function-id: [C++ 12.3.2] 1620/// operator conversion-type-id 1621/// 1622/// conversion-type-id: 1623/// type-specifier-seq conversion-declarator[opt] 1624/// 1625/// conversion-declarator: 1626/// ptr-operator conversion-declarator[opt] 1627/// \endcode 1628/// 1629/// \param The nested-name-specifier that preceded this unqualified-id. If 1630/// non-empty, then we are parsing the unqualified-id of a qualified-id. 1631/// 1632/// \param EnteringContext whether we are entering the scope of the 1633/// nested-name-specifier. 1634/// 1635/// \param ObjectType if this unqualified-id occurs within a member access 1636/// expression, the type of the base object whose member is being accessed. 1637/// 1638/// \param Result on a successful parse, contains the parsed unqualified-id. 1639/// 1640/// \returns true if parsing fails, false otherwise. 1641bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, 1642 ParsedType ObjectType, 1643 UnqualifiedId &Result) { 1644 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword"); 1645 1646 // Consume the 'operator' keyword. 1647 SourceLocation KeywordLoc = ConsumeToken(); 1648 1649 // Determine what kind of operator name we have. 1650 unsigned SymbolIdx = 0; 1651 SourceLocation SymbolLocations[3]; 1652 OverloadedOperatorKind Op = OO_None; 1653 switch (Tok.getKind()) { 1654 case tok::kw_new: 1655 case tok::kw_delete: { 1656 bool isNew = Tok.getKind() == tok::kw_new; 1657 // Consume the 'new' or 'delete'. 1658 SymbolLocations[SymbolIdx++] = ConsumeToken(); 1659 if (Tok.is(tok::l_square)) { 1660 // Consume the '['. 1661 SourceLocation LBracketLoc = ConsumeBracket(); 1662 // Consume the ']'. 1663 SourceLocation RBracketLoc = MatchRHSPunctuation(tok::r_square, 1664 LBracketLoc); 1665 if (RBracketLoc.isInvalid()) 1666 return true; 1667 1668 SymbolLocations[SymbolIdx++] = LBracketLoc; 1669 SymbolLocations[SymbolIdx++] = RBracketLoc; 1670 Op = isNew? OO_Array_New : OO_Array_Delete; 1671 } else { 1672 Op = isNew? OO_New : OO_Delete; 1673 } 1674 break; 1675 } 1676 1677#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 1678 case tok::Token: \ 1679 SymbolLocations[SymbolIdx++] = ConsumeToken(); \ 1680 Op = OO_##Name; \ 1681 break; 1682#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly) 1683#include "clang/Basic/OperatorKinds.def" 1684 1685 case tok::l_paren: { 1686 // Consume the '('. 1687 SourceLocation LParenLoc = ConsumeParen(); 1688 // Consume the ')'. 1689 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, 1690 LParenLoc); 1691 if (RParenLoc.isInvalid()) 1692 return true; 1693 1694 SymbolLocations[SymbolIdx++] = LParenLoc; 1695 SymbolLocations[SymbolIdx++] = RParenLoc; 1696 Op = OO_Call; 1697 break; 1698 } 1699 1700 case tok::l_square: { 1701 // Consume the '['. 1702 SourceLocation LBracketLoc = ConsumeBracket(); 1703 // Consume the ']'. 1704 SourceLocation RBracketLoc = MatchRHSPunctuation(tok::r_square, 1705 LBracketLoc); 1706 if (RBracketLoc.isInvalid()) 1707 return true; 1708 1709 SymbolLocations[SymbolIdx++] = LBracketLoc; 1710 SymbolLocations[SymbolIdx++] = RBracketLoc; 1711 Op = OO_Subscript; 1712 break; 1713 } 1714 1715 case tok::code_completion: { 1716 // Code completion for the operator name. 1717 Actions.CodeCompleteOperatorName(getCurScope()); 1718 cutOffParsing(); 1719 // Don't try to parse any further. 1720 return true; 1721 } 1722 1723 default: 1724 break; 1725 } 1726 1727 if (Op != OO_None) { 1728 // We have parsed an operator-function-id. 1729 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations); 1730 return false; 1731 } 1732 1733 // Parse a literal-operator-id. 1734 // 1735 // literal-operator-id: [C++0x 13.5.8] 1736 // operator "" identifier 1737 1738 if (getLang().CPlusPlus0x && Tok.is(tok::string_literal)) { 1739 if (Tok.getLength() != 2) 1740 Diag(Tok.getLocation(), diag::err_operator_string_not_empty); 1741 ConsumeStringToken(); 1742 1743 if (Tok.isNot(tok::identifier)) { 1744 Diag(Tok.getLocation(), diag::err_expected_ident); 1745 return true; 1746 } 1747 1748 IdentifierInfo *II = Tok.getIdentifierInfo(); 1749 Result.setLiteralOperatorId(II, KeywordLoc, ConsumeToken()); 1750 return false; 1751 } 1752 1753 // Parse a conversion-function-id. 1754 // 1755 // conversion-function-id: [C++ 12.3.2] 1756 // operator conversion-type-id 1757 // 1758 // conversion-type-id: 1759 // type-specifier-seq conversion-declarator[opt] 1760 // 1761 // conversion-declarator: 1762 // ptr-operator conversion-declarator[opt] 1763 1764 // Parse the type-specifier-seq. 1765 DeclSpec DS(AttrFactory); 1766 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType? 1767 return true; 1768 1769 // Parse the conversion-declarator, which is merely a sequence of 1770 // ptr-operators. 1771 Declarator D(DS, Declarator::TypeNameContext); 1772 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0); 1773 1774 // Finish up the type. 1775 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D); 1776 if (Ty.isInvalid()) 1777 return true; 1778 1779 // Note that this is a conversion-function-id. 1780 Result.setConversionFunctionId(KeywordLoc, Ty.get(), 1781 D.getSourceRange().getEnd()); 1782 return false; 1783} 1784 1785/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the 1786/// name of an entity. 1787/// 1788/// \code 1789/// unqualified-id: [C++ expr.prim.general] 1790/// identifier 1791/// operator-function-id 1792/// conversion-function-id 1793/// [C++0x] literal-operator-id [TODO] 1794/// ~ class-name 1795/// template-id 1796/// 1797/// \endcode 1798/// 1799/// \param The nested-name-specifier that preceded this unqualified-id. If 1800/// non-empty, then we are parsing the unqualified-id of a qualified-id. 1801/// 1802/// \param EnteringContext whether we are entering the scope of the 1803/// nested-name-specifier. 1804/// 1805/// \param AllowDestructorName whether we allow parsing of a destructor name. 1806/// 1807/// \param AllowConstructorName whether we allow parsing a constructor name. 1808/// 1809/// \param ObjectType if this unqualified-id occurs within a member access 1810/// expression, the type of the base object whose member is being accessed. 1811/// 1812/// \param Result on a successful parse, contains the parsed unqualified-id. 1813/// 1814/// \returns true if parsing fails, false otherwise. 1815bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, 1816 bool AllowDestructorName, 1817 bool AllowConstructorName, 1818 ParsedType ObjectType, 1819 UnqualifiedId &Result) { 1820 1821 // Handle 'A::template B'. This is for template-ids which have not 1822 // already been annotated by ParseOptionalCXXScopeSpecifier(). 1823 bool TemplateSpecified = false; 1824 SourceLocation TemplateKWLoc; 1825 if (getLang().CPlusPlus && Tok.is(tok::kw_template) && 1826 (ObjectType || SS.isSet())) { 1827 TemplateSpecified = true; 1828 TemplateKWLoc = ConsumeToken(); 1829 } 1830 1831 // unqualified-id: 1832 // identifier 1833 // template-id (when it hasn't already been annotated) 1834 if (Tok.is(tok::identifier)) { 1835 // Consume the identifier. 1836 IdentifierInfo *Id = Tok.getIdentifierInfo(); 1837 SourceLocation IdLoc = ConsumeToken(); 1838 1839 if (!getLang().CPlusPlus) { 1840 // If we're not in C++, only identifiers matter. Record the 1841 // identifier and return. 1842 Result.setIdentifier(Id, IdLoc); 1843 return false; 1844 } 1845 1846 if (AllowConstructorName && 1847 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) { 1848 // We have parsed a constructor name. 1849 Result.setConstructorName(Actions.getTypeName(*Id, IdLoc, getCurScope(), 1850 &SS, false, false, 1851 ParsedType(), 1852 /*NonTrivialTypeSourceInfo=*/true), 1853 IdLoc, IdLoc); 1854 } else { 1855 // We have parsed an identifier. 1856 Result.setIdentifier(Id, IdLoc); 1857 } 1858 1859 // If the next token is a '<', we may have a template. 1860 if (TemplateSpecified || Tok.is(tok::less)) 1861 return ParseUnqualifiedIdTemplateId(SS, Id, IdLoc, EnteringContext, 1862 ObjectType, Result, 1863 TemplateSpecified, TemplateKWLoc); 1864 1865 return false; 1866 } 1867 1868 // unqualified-id: 1869 // template-id (already parsed and annotated) 1870 if (Tok.is(tok::annot_template_id)) { 1871 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1872 1873 // If the template-name names the current class, then this is a constructor 1874 if (AllowConstructorName && TemplateId->Name && 1875 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { 1876 if (SS.isSet()) { 1877 // C++ [class.qual]p2 specifies that a qualified template-name 1878 // is taken as the constructor name where a constructor can be 1879 // declared. Thus, the template arguments are extraneous, so 1880 // complain about them and remove them entirely. 1881 Diag(TemplateId->TemplateNameLoc, 1882 diag::err_out_of_line_constructor_template_id) 1883 << TemplateId->Name 1884 << FixItHint::CreateRemoval( 1885 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)); 1886 Result.setConstructorName(Actions.getTypeName(*TemplateId->Name, 1887 TemplateId->TemplateNameLoc, 1888 getCurScope(), 1889 &SS, false, false, 1890 ParsedType(), 1891 /*NontrivialTypeSourceInfo=*/true), 1892 TemplateId->TemplateNameLoc, 1893 TemplateId->RAngleLoc); 1894 ConsumeToken(); 1895 return false; 1896 } 1897 1898 Result.setConstructorTemplateId(TemplateId); 1899 ConsumeToken(); 1900 return false; 1901 } 1902 1903 // We have already parsed a template-id; consume the annotation token as 1904 // our unqualified-id. 1905 Result.setTemplateId(TemplateId); 1906 ConsumeToken(); 1907 return false; 1908 } 1909 1910 // unqualified-id: 1911 // operator-function-id 1912 // conversion-function-id 1913 if (Tok.is(tok::kw_operator)) { 1914 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result)) 1915 return true; 1916 1917 // If we have an operator-function-id or a literal-operator-id and the next 1918 // token is a '<', we may have a 1919 // 1920 // template-id: 1921 // operator-function-id < template-argument-list[opt] > 1922 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId || 1923 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) && 1924 (TemplateSpecified || Tok.is(tok::less))) 1925 return ParseUnqualifiedIdTemplateId(SS, 0, SourceLocation(), 1926 EnteringContext, ObjectType, 1927 Result, 1928 TemplateSpecified, TemplateKWLoc); 1929 1930 return false; 1931 } 1932 1933 if (getLang().CPlusPlus && 1934 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) { 1935 // C++ [expr.unary.op]p10: 1936 // There is an ambiguity in the unary-expression ~X(), where X is a 1937 // class-name. The ambiguity is resolved in favor of treating ~ as a 1938 // unary complement rather than treating ~X as referring to a destructor. 1939 1940 // Parse the '~'. 1941 SourceLocation TildeLoc = ConsumeToken(); 1942 1943 // Parse the class-name. 1944 if (Tok.isNot(tok::identifier)) { 1945 Diag(Tok, diag::err_destructor_tilde_identifier); 1946 return true; 1947 } 1948 1949 // Parse the class-name (or template-name in a simple-template-id). 1950 IdentifierInfo *ClassName = Tok.getIdentifierInfo(); 1951 SourceLocation ClassNameLoc = ConsumeToken(); 1952 1953 if (TemplateSpecified || Tok.is(tok::less)) { 1954 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc); 1955 return ParseUnqualifiedIdTemplateId(SS, ClassName, ClassNameLoc, 1956 EnteringContext, ObjectType, Result, 1957 TemplateSpecified, TemplateKWLoc); 1958 } 1959 1960 // Note that this is a destructor name. 1961 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName, 1962 ClassNameLoc, getCurScope(), 1963 SS, ObjectType, 1964 EnteringContext); 1965 if (!Ty) 1966 return true; 1967 1968 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc); 1969 return false; 1970 } 1971 1972 Diag(Tok, diag::err_expected_unqualified_id) 1973 << getLang().CPlusPlus; 1974 return true; 1975} 1976 1977/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate 1978/// memory in a typesafe manner and call constructors. 1979/// 1980/// This method is called to parse the new expression after the optional :: has 1981/// been already parsed. If the :: was present, "UseGlobal" is true and "Start" 1982/// is its location. Otherwise, "Start" is the location of the 'new' token. 1983/// 1984/// new-expression: 1985/// '::'[opt] 'new' new-placement[opt] new-type-id 1986/// new-initializer[opt] 1987/// '::'[opt] 'new' new-placement[opt] '(' type-id ')' 1988/// new-initializer[opt] 1989/// 1990/// new-placement: 1991/// '(' expression-list ')' 1992/// 1993/// new-type-id: 1994/// type-specifier-seq new-declarator[opt] 1995/// [GNU] attributes type-specifier-seq new-declarator[opt] 1996/// 1997/// new-declarator: 1998/// ptr-operator new-declarator[opt] 1999/// direct-new-declarator 2000/// 2001/// new-initializer: 2002/// '(' expression-list[opt] ')' 2003/// [C++0x] braced-init-list 2004/// 2005ExprResult 2006Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) { 2007 assert(Tok.is(tok::kw_new) && "expected 'new' token"); 2008 ConsumeToken(); // Consume 'new' 2009 2010 // A '(' now can be a new-placement or the '(' wrapping the type-id in the 2011 // second form of new-expression. It can't be a new-type-id. 2012 2013 ExprVector PlacementArgs(Actions); 2014 SourceLocation PlacementLParen, PlacementRParen; 2015 2016 SourceRange TypeIdParens; 2017 DeclSpec DS(AttrFactory); 2018 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext); 2019 if (Tok.is(tok::l_paren)) { 2020 // If it turns out to be a placement, we change the type location. 2021 PlacementLParen = ConsumeParen(); 2022 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) { 2023 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 2024 return ExprError(); 2025 } 2026 2027 PlacementRParen = MatchRHSPunctuation(tok::r_paren, PlacementLParen); 2028 if (PlacementRParen.isInvalid()) { 2029 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 2030 return ExprError(); 2031 } 2032 2033 if (PlacementArgs.empty()) { 2034 // Reset the placement locations. There was no placement. 2035 TypeIdParens = SourceRange(PlacementLParen, PlacementRParen); 2036 PlacementLParen = PlacementRParen = SourceLocation(); 2037 } else { 2038 // We still need the type. 2039 if (Tok.is(tok::l_paren)) { 2040 TypeIdParens.setBegin(ConsumeParen()); 2041 MaybeParseGNUAttributes(DeclaratorInfo); 2042 ParseSpecifierQualifierList(DS); 2043 DeclaratorInfo.SetSourceRange(DS.getSourceRange()); 2044 ParseDeclarator(DeclaratorInfo); 2045 TypeIdParens.setEnd(MatchRHSPunctuation(tok::r_paren, 2046 TypeIdParens.getBegin())); 2047 } else { 2048 MaybeParseGNUAttributes(DeclaratorInfo); 2049 if (ParseCXXTypeSpecifierSeq(DS)) 2050 DeclaratorInfo.setInvalidType(true); 2051 else { 2052 DeclaratorInfo.SetSourceRange(DS.getSourceRange()); 2053 ParseDeclaratorInternal(DeclaratorInfo, 2054 &Parser::ParseDirectNewDeclarator); 2055 } 2056 } 2057 } 2058 } else { 2059 // A new-type-id is a simplified type-id, where essentially the 2060 // direct-declarator is replaced by a direct-new-declarator. 2061 MaybeParseGNUAttributes(DeclaratorInfo); 2062 if (ParseCXXTypeSpecifierSeq(DS)) 2063 DeclaratorInfo.setInvalidType(true); 2064 else { 2065 DeclaratorInfo.SetSourceRange(DS.getSourceRange()); 2066 ParseDeclaratorInternal(DeclaratorInfo, 2067 &Parser::ParseDirectNewDeclarator); 2068 } 2069 } 2070 if (DeclaratorInfo.isInvalidType()) { 2071 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 2072 return ExprError(); 2073 } 2074 2075 ExprVector ConstructorArgs(Actions); 2076 SourceLocation ConstructorLParen, ConstructorRParen; 2077 2078 if (Tok.is(tok::l_paren)) { 2079 ConstructorLParen = ConsumeParen(); 2080 if (Tok.isNot(tok::r_paren)) { 2081 CommaLocsTy CommaLocs; 2082 if (ParseExpressionList(ConstructorArgs, CommaLocs)) { 2083 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 2084 return ExprError(); 2085 } 2086 } 2087 ConstructorRParen = MatchRHSPunctuation(tok::r_paren, ConstructorLParen); 2088 if (ConstructorRParen.isInvalid()) { 2089 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 2090 return ExprError(); 2091 } 2092 } else if (Tok.is(tok::l_brace)) { 2093 // FIXME: Have to communicate the init-list to ActOnCXXNew. 2094 ParseBraceInitializer(); 2095 } 2096 2097 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen, 2098 move_arg(PlacementArgs), PlacementRParen, 2099 TypeIdParens, DeclaratorInfo, ConstructorLParen, 2100 move_arg(ConstructorArgs), ConstructorRParen); 2101} 2102 2103/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be 2104/// passed to ParseDeclaratorInternal. 2105/// 2106/// direct-new-declarator: 2107/// '[' expression ']' 2108/// direct-new-declarator '[' constant-expression ']' 2109/// 2110void Parser::ParseDirectNewDeclarator(Declarator &D) { 2111 // Parse the array dimensions. 2112 bool first = true; 2113 while (Tok.is(tok::l_square)) { 2114 SourceLocation LLoc = ConsumeBracket(); 2115 ExprResult Size(first ? ParseExpression() 2116 : ParseConstantExpression()); 2117 if (Size.isInvalid()) { 2118 // Recover 2119 SkipUntil(tok::r_square); 2120 return; 2121 } 2122 first = false; 2123 2124 SourceLocation RLoc = MatchRHSPunctuation(tok::r_square, LLoc); 2125 2126 ParsedAttributes attrs(AttrFactory); 2127 D.AddTypeInfo(DeclaratorChunk::getArray(0, 2128 /*static=*/false, /*star=*/false, 2129 Size.release(), LLoc, RLoc), 2130 attrs, RLoc); 2131 2132 if (RLoc.isInvalid()) 2133 return; 2134 } 2135} 2136 2137/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id. 2138/// This ambiguity appears in the syntax of the C++ new operator. 2139/// 2140/// new-expression: 2141/// '::'[opt] 'new' new-placement[opt] '(' type-id ')' 2142/// new-initializer[opt] 2143/// 2144/// new-placement: 2145/// '(' expression-list ')' 2146/// 2147bool Parser::ParseExpressionListOrTypeId( 2148 SmallVectorImpl<Expr*> &PlacementArgs, 2149 Declarator &D) { 2150 // The '(' was already consumed. 2151 if (isTypeIdInParens()) { 2152 ParseSpecifierQualifierList(D.getMutableDeclSpec()); 2153 D.SetSourceRange(D.getDeclSpec().getSourceRange()); 2154 ParseDeclarator(D); 2155 return D.isInvalidType(); 2156 } 2157 2158 // It's not a type, it has to be an expression list. 2159 // Discard the comma locations - ActOnCXXNew has enough parameters. 2160 CommaLocsTy CommaLocs; 2161 return ParseExpressionList(PlacementArgs, CommaLocs); 2162} 2163 2164/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used 2165/// to free memory allocated by new. 2166/// 2167/// This method is called to parse the 'delete' expression after the optional 2168/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true 2169/// and "Start" is its location. Otherwise, "Start" is the location of the 2170/// 'delete' token. 2171/// 2172/// delete-expression: 2173/// '::'[opt] 'delete' cast-expression 2174/// '::'[opt] 'delete' '[' ']' cast-expression 2175ExprResult 2176Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) { 2177 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword"); 2178 ConsumeToken(); // Consume 'delete' 2179 2180 // Array delete? 2181 bool ArrayDelete = false; 2182 if (Tok.is(tok::l_square)) { 2183 ArrayDelete = true; 2184 SourceLocation LHS = ConsumeBracket(); 2185 SourceLocation RHS = MatchRHSPunctuation(tok::r_square, LHS); 2186 if (RHS.isInvalid()) 2187 return ExprError(); 2188 } 2189 2190 ExprResult Operand(ParseCastExpression(false)); 2191 if (Operand.isInvalid()) 2192 return move(Operand); 2193 2194 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take()); 2195} 2196 2197static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) { 2198 switch(kind) { 2199 default: assert(false && "Not a known unary type trait."); 2200 case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign; 2201 case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor; 2202 case tok::kw___has_nothrow_copy: return UTT_HasNothrowCopy; 2203 case tok::kw___has_trivial_assign: return UTT_HasTrivialAssign; 2204 case tok::kw___has_trivial_constructor: 2205 return UTT_HasTrivialDefaultConstructor; 2206 case tok::kw___has_trivial_copy: return UTT_HasTrivialCopy; 2207 case tok::kw___has_trivial_destructor: return UTT_HasTrivialDestructor; 2208 case tok::kw___has_virtual_destructor: return UTT_HasVirtualDestructor; 2209 case tok::kw___is_abstract: return UTT_IsAbstract; 2210 case tok::kw___is_arithmetic: return UTT_IsArithmetic; 2211 case tok::kw___is_array: return UTT_IsArray; 2212 case tok::kw___is_class: return UTT_IsClass; 2213 case tok::kw___is_complete_type: return UTT_IsCompleteType; 2214 case tok::kw___is_compound: return UTT_IsCompound; 2215 case tok::kw___is_const: return UTT_IsConst; 2216 case tok::kw___is_empty: return UTT_IsEmpty; 2217 case tok::kw___is_enum: return UTT_IsEnum; 2218 case tok::kw___is_floating_point: return UTT_IsFloatingPoint; 2219 case tok::kw___is_function: return UTT_IsFunction; 2220 case tok::kw___is_fundamental: return UTT_IsFundamental; 2221 case tok::kw___is_integral: return UTT_IsIntegral; 2222 case tok::kw___is_lvalue_reference: return UTT_IsLvalueReference; 2223 case tok::kw___is_member_function_pointer: return UTT_IsMemberFunctionPointer; 2224 case tok::kw___is_member_object_pointer: return UTT_IsMemberObjectPointer; 2225 case tok::kw___is_member_pointer: return UTT_IsMemberPointer; 2226 case tok::kw___is_object: return UTT_IsObject; 2227 case tok::kw___is_literal: return UTT_IsLiteral; 2228 case tok::kw___is_literal_type: return UTT_IsLiteral; 2229 case tok::kw___is_pod: return UTT_IsPOD; 2230 case tok::kw___is_pointer: return UTT_IsPointer; 2231 case tok::kw___is_polymorphic: return UTT_IsPolymorphic; 2232 case tok::kw___is_reference: return UTT_IsReference; 2233 case tok::kw___is_rvalue_reference: return UTT_IsRvalueReference; 2234 case tok::kw___is_scalar: return UTT_IsScalar; 2235 case tok::kw___is_signed: return UTT_IsSigned; 2236 case tok::kw___is_standard_layout: return UTT_IsStandardLayout; 2237 case tok::kw___is_trivial: return UTT_IsTrivial; 2238 case tok::kw___is_trivially_copyable: return UTT_IsTriviallyCopyable; 2239 case tok::kw___is_union: return UTT_IsUnion; 2240 case tok::kw___is_unsigned: return UTT_IsUnsigned; 2241 case tok::kw___is_void: return UTT_IsVoid; 2242 case tok::kw___is_volatile: return UTT_IsVolatile; 2243 } 2244} 2245 2246static BinaryTypeTrait BinaryTypeTraitFromTokKind(tok::TokenKind kind) { 2247 switch(kind) { 2248 default: llvm_unreachable("Not a known binary type trait"); 2249 case tok::kw___is_base_of: return BTT_IsBaseOf; 2250 case tok::kw___is_convertible: return BTT_IsConvertible; 2251 case tok::kw___is_same: return BTT_IsSame; 2252 case tok::kw___builtin_types_compatible_p: return BTT_TypeCompatible; 2253 case tok::kw___is_convertible_to: return BTT_IsConvertibleTo; 2254 } 2255} 2256 2257static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) { 2258 switch(kind) { 2259 default: llvm_unreachable("Not a known binary type trait"); 2260 case tok::kw___array_rank: return ATT_ArrayRank; 2261 case tok::kw___array_extent: return ATT_ArrayExtent; 2262 } 2263} 2264 2265static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) { 2266 switch(kind) { 2267 default: assert(false && "Not a known unary expression trait."); 2268 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr; 2269 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr; 2270 } 2271} 2272 2273/// ParseUnaryTypeTrait - Parse the built-in unary type-trait 2274/// pseudo-functions that allow implementation of the TR1/C++0x type traits 2275/// templates. 2276/// 2277/// primary-expression: 2278/// [GNU] unary-type-trait '(' type-id ')' 2279/// 2280ExprResult Parser::ParseUnaryTypeTrait() { 2281 UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind()); 2282 SourceLocation Loc = ConsumeToken(); 2283 2284 SourceLocation LParen = Tok.getLocation(); 2285 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen)) 2286 return ExprError(); 2287 2288 // FIXME: Error reporting absolutely sucks! If the this fails to parse a type 2289 // there will be cryptic errors about mismatched parentheses and missing 2290 // specifiers. 2291 TypeResult Ty = ParseTypeName(); 2292 2293 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen); 2294 2295 if (Ty.isInvalid()) 2296 return ExprError(); 2297 2298 return Actions.ActOnUnaryTypeTrait(UTT, Loc, Ty.get(), RParen); 2299} 2300 2301/// ParseBinaryTypeTrait - Parse the built-in binary type-trait 2302/// pseudo-functions that allow implementation of the TR1/C++0x type traits 2303/// templates. 2304/// 2305/// primary-expression: 2306/// [GNU] binary-type-trait '(' type-id ',' type-id ')' 2307/// 2308ExprResult Parser::ParseBinaryTypeTrait() { 2309 BinaryTypeTrait BTT = BinaryTypeTraitFromTokKind(Tok.getKind()); 2310 SourceLocation Loc = ConsumeToken(); 2311 2312 SourceLocation LParen = Tok.getLocation(); 2313 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen)) 2314 return ExprError(); 2315 2316 TypeResult LhsTy = ParseTypeName(); 2317 if (LhsTy.isInvalid()) { 2318 SkipUntil(tok::r_paren); 2319 return ExprError(); 2320 } 2321 2322 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) { 2323 SkipUntil(tok::r_paren); 2324 return ExprError(); 2325 } 2326 2327 TypeResult RhsTy = ParseTypeName(); 2328 if (RhsTy.isInvalid()) { 2329 SkipUntil(tok::r_paren); 2330 return ExprError(); 2331 } 2332 2333 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen); 2334 2335 return Actions.ActOnBinaryTypeTrait(BTT, Loc, LhsTy.get(), RhsTy.get(), RParen); 2336} 2337 2338/// ParseArrayTypeTrait - Parse the built-in array type-trait 2339/// pseudo-functions. 2340/// 2341/// primary-expression: 2342/// [Embarcadero] '__array_rank' '(' type-id ')' 2343/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')' 2344/// 2345ExprResult Parser::ParseArrayTypeTrait() { 2346 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind()); 2347 SourceLocation Loc = ConsumeToken(); 2348 2349 SourceLocation LParen = Tok.getLocation(); 2350 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen)) 2351 return ExprError(); 2352 2353 TypeResult Ty = ParseTypeName(); 2354 if (Ty.isInvalid()) { 2355 SkipUntil(tok::comma); 2356 SkipUntil(tok::r_paren); 2357 return ExprError(); 2358 } 2359 2360 switch (ATT) { 2361 case ATT_ArrayRank: { 2362 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen); 2363 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), NULL, RParen); 2364 } 2365 case ATT_ArrayExtent: { 2366 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) { 2367 SkipUntil(tok::r_paren); 2368 return ExprError(); 2369 } 2370 2371 ExprResult DimExpr = ParseExpression(); 2372 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen); 2373 2374 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(), RParen); 2375 } 2376 default: 2377 break; 2378 } 2379 return ExprError(); 2380} 2381 2382/// ParseExpressionTrait - Parse built-in expression-trait 2383/// pseudo-functions like __is_lvalue_expr( xxx ). 2384/// 2385/// primary-expression: 2386/// [Embarcadero] expression-trait '(' expression ')' 2387/// 2388ExprResult Parser::ParseExpressionTrait() { 2389 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind()); 2390 SourceLocation Loc = ConsumeToken(); 2391 2392 SourceLocation LParen = Tok.getLocation(); 2393 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen)) 2394 return ExprError(); 2395 2396 ExprResult Expr = ParseExpression(); 2397 2398 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen); 2399 2400 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(), RParen); 2401} 2402 2403 2404/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a 2405/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate 2406/// based on the context past the parens. 2407ExprResult 2408Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, 2409 ParsedType &CastTy, 2410 SourceLocation LParenLoc, 2411 SourceLocation &RParenLoc) { 2412 assert(getLang().CPlusPlus && "Should only be called for C++!"); 2413 assert(ExprType == CastExpr && "Compound literals are not ambiguous!"); 2414 assert(isTypeIdInParens() && "Not a type-id!"); 2415 2416 ExprResult Result(true); 2417 CastTy = ParsedType(); 2418 2419 // We need to disambiguate a very ugly part of the C++ syntax: 2420 // 2421 // (T())x; - type-id 2422 // (T())*x; - type-id 2423 // (T())/x; - expression 2424 // (T()); - expression 2425 // 2426 // The bad news is that we cannot use the specialized tentative parser, since 2427 // it can only verify that the thing inside the parens can be parsed as 2428 // type-id, it is not useful for determining the context past the parens. 2429 // 2430 // The good news is that the parser can disambiguate this part without 2431 // making any unnecessary Action calls. 2432 // 2433 // It uses a scheme similar to parsing inline methods. The parenthesized 2434 // tokens are cached, the context that follows is determined (possibly by 2435 // parsing a cast-expression), and then we re-introduce the cached tokens 2436 // into the token stream and parse them appropriately. 2437 2438 ParenParseOption ParseAs; 2439 CachedTokens Toks; 2440 2441 // Store the tokens of the parentheses. We will parse them after we determine 2442 // the context that follows them. 2443 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) { 2444 // We didn't find the ')' we expected. 2445 MatchRHSPunctuation(tok::r_paren, LParenLoc); 2446 return ExprError(); 2447 } 2448 2449 if (Tok.is(tok::l_brace)) { 2450 ParseAs = CompoundLiteral; 2451 } else { 2452 bool NotCastExpr; 2453 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression 2454 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) { 2455 NotCastExpr = true; 2456 } else { 2457 // Try parsing the cast-expression that may follow. 2458 // If it is not a cast-expression, NotCastExpr will be true and no token 2459 // will be consumed. 2460 Result = ParseCastExpression(false/*isUnaryExpression*/, 2461 false/*isAddressofOperand*/, 2462 NotCastExpr, 2463 // type-id has priority. 2464 true/*isTypeCast*/); 2465 } 2466 2467 // If we parsed a cast-expression, it's really a type-id, otherwise it's 2468 // an expression. 2469 ParseAs = NotCastExpr ? SimpleExpr : CastExpr; 2470 } 2471 2472 // The current token should go after the cached tokens. 2473 Toks.push_back(Tok); 2474 // Re-enter the stored parenthesized tokens into the token stream, so we may 2475 // parse them now. 2476 PP.EnterTokenStream(Toks.data(), Toks.size(), 2477 true/*DisableMacroExpansion*/, false/*OwnsTokens*/); 2478 // Drop the current token and bring the first cached one. It's the same token 2479 // as when we entered this function. 2480 ConsumeAnyToken(); 2481 2482 if (ParseAs >= CompoundLiteral) { 2483 // Parse the type declarator. 2484 DeclSpec DS(AttrFactory); 2485 ParseSpecifierQualifierList(DS); 2486 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 2487 ParseDeclarator(DeclaratorInfo); 2488 2489 // Match the ')'. 2490 if (Tok.is(tok::r_paren)) 2491 RParenLoc = ConsumeParen(); 2492 else 2493 MatchRHSPunctuation(tok::r_paren, LParenLoc); 2494 2495 if (ParseAs == CompoundLiteral) { 2496 ExprType = CompoundLiteral; 2497 TypeResult Ty = ParseTypeName(); 2498 return ParseCompoundLiteralExpression(Ty.get(), LParenLoc, RParenLoc); 2499 } 2500 2501 // We parsed '(' type-id ')' and the thing after it wasn't a '{'. 2502 assert(ParseAs == CastExpr); 2503 2504 if (DeclaratorInfo.isInvalidType()) 2505 return ExprError(); 2506 2507 // Result is what ParseCastExpression returned earlier. 2508 if (!Result.isInvalid()) 2509 Result = Actions.ActOnCastExpr(getCurScope(), LParenLoc, 2510 DeclaratorInfo, CastTy, 2511 RParenLoc, Result.take()); 2512 return move(Result); 2513 } 2514 2515 // Not a compound literal, and not followed by a cast-expression. 2516 assert(ParseAs == SimpleExpr); 2517 2518 ExprType = SimpleExpr; 2519 Result = ParseExpression(); 2520 if (!Result.isInvalid() && Tok.is(tok::r_paren)) 2521 Result = Actions.ActOnParenExpr(LParenLoc, Tok.getLocation(), Result.take()); 2522 2523 // Match the ')'. 2524 if (Result.isInvalid()) { 2525 SkipUntil(tok::r_paren); 2526 return ExprError(); 2527 } 2528 2529 if (Tok.is(tok::r_paren)) 2530 RParenLoc = ConsumeParen(); 2531 else 2532 MatchRHSPunctuation(tok::r_paren, LParenLoc); 2533 2534 return move(Result); 2535} 2536