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